3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
33 use C4::Members::Messaging;
35 use Koha::Account::Lines;
38 use Koha::CirculationRules;
43 use Koha::IssuingRules;
52 use List::MoreUtils qw( firstidx any );
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
58 C4::Reserves - Koha functions for dealing with reservation.
66 This modules provides somes functions to deal with reservations.
68 Reserves are stored in reserves table.
69 The following columns contains important values :
70 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
71 =0 : then the reserve is being dealed
72 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
73 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
74 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
75 F(inished) : the reserve has been completed, and is done
76 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
114 &ModReserveMinusPriority
120 &CanReserveBeCanceledFromOpac
121 &CancelExpiredReserves
123 &AutoUnsuspendReserves
125 &IsAvailableForItemLevelRequest
128 &ToggleLowestPriority
134 &GetReservesControlBranch
138 GetMaxPatronHoldsForRecord
140 @EXPORT_OK = qw( MergeHolds );
145 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
147 Adds reserve and generates HOLDPLACED message.
149 The following tables are available witin the HOLDPLACED message:
162 $branch, $borrowernumber, $biblionumber, $bibitems,
163 $priority, $resdate, $expdate, $notes,
164 $title, $checkitem, $found, $itemtype
167 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
168 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
170 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
172 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
173 # of the document, we force the value $priority and $found .
174 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
175 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
178 # If item is already checked out, it cannot be set waiting
181 # The item can't be waiting if it needs a transfer
182 && $item->holdingbranch eq $branch
184 # Similarly, if in transit it can't be waiting
185 && !$item->get_transfer
187 # If we can't hold damaged items, and it is damaged, it can't be waiting
188 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
190 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
191 && !$item->current_holds->count )
198 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
200 # Make room in reserves for this before those of a later reserve date
201 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
206 # If the reserv had the waiting status, we had the value of the resdate
207 if ( $found eq 'W' ) {
208 $waitingdate = $resdate;
211 # Don't add itemtype limit if specific item is selected
212 $itemtype = undef if $checkitem;
214 # updates take place here
215 my $hold = Koha::Hold->new(
217 borrowernumber => $borrowernumber,
218 biblionumber => $biblionumber,
219 reservedate => $resdate,
220 branchcode => $branch,
221 priority => $priority,
222 reservenotes => $notes,
223 itemnumber => $checkitem,
225 waitingdate => $waitingdate,
226 expirationdate => $expdate,
227 itemtype => $itemtype,
228 item_level_hold => $checkitem ? 1 : 0,
231 $hold->set_waiting() if $found eq 'W';
233 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
234 if C4::Context->preference('HoldsLog');
236 my $reserve_id = $hold->id();
238 # add a reserve fee if needed
239 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
240 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
241 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
244 _FixPriority({ biblionumber => $biblionumber});
246 # Send e-mail to librarian if syspref is active
247 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
248 my $patron = Koha::Patrons->find( $borrowernumber );
249 my $library = $patron->library;
250 if ( my $letter = C4::Letters::GetPreparedLetter (
251 module => 'reserves',
252 letter_code => 'HOLDPLACED',
253 branchcode => $branch,
254 lang => $patron->lang,
256 'branches' => $library->unblessed,
257 'borrowers' => $patron->unblessed,
258 'biblio' => $biblionumber,
259 'biblioitems' => $biblionumber,
260 'items' => $checkitem,
261 'reserves' => $hold->unblessed,
265 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
267 C4::Letters::EnqueueLetter(
269 borrowernumber => $borrowernumber,
270 message_transport_type => 'email',
271 from_address => $admin_email_address,
272 to_address => $admin_email_address,
281 =head2 CanBookBeReserved
283 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
284 if ($canReserve eq 'OK') { #We can reserve this Item! }
286 See CanItemBeReserved() for possible return values.
290 sub CanBookBeReserved{
291 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
293 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
294 #get items linked via host records
295 my @hostitems = get_hostitemnumbers_of($biblionumber);
297 push (@itemnumbers, @hostitems);
300 my $canReserve = { status => '' };
301 foreach my $itemnumber (@itemnumbers) {
302 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
303 return { status => 'OK' } if $canReserve->{status} eq 'OK';
308 =head2 CanItemBeReserved
310 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
311 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
313 @RETURNS { status => OK }, if the Item can be reserved.
314 { status => ageRestricted }, if the Item is age restricted for this borrower.
315 { status => damaged }, if the Item is damaged.
316 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
317 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
318 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
319 { status => notReservable }, if holds on this item are not allowed
320 { status => libraryNotFound }, if given branchcode is not an existing library
321 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
322 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
323 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
327 sub CanItemBeReserved {
328 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
330 my $dbh = C4::Context->dbh;
331 my $ruleitemtype; # itemtype of the matching issuing rule
332 my $allowedreserves = 0; # Total number of holds allowed across all records
333 my $holds_per_record = 1; # Total number of holds allowed for this one given record
334 my $holds_per_day; # Default to unlimited
336 # we retrieve borrowers and items informations #
337 # item->{itype} will come for biblioitems if necessery
338 my $item = Koha::Items->find($itemnumber);
339 my $biblio = $item->biblio;
340 my $patron = Koha::Patrons->find( $borrowernumber );
341 my $borrower = $patron->unblessed;
343 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
344 return { status =>'damaged' }
346 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
348 # Check for the age restriction
349 my ( $ageRestriction, $daysToAgeRestriction ) =
350 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
351 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
353 # Check that the patron doesn't have an item level hold on this item already
354 return { status =>'itemAlreadyOnHold' }
355 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
357 my $controlbranch = C4::Context->preference('ReservesControlBranch');
360 SELECT count(*) AS count
362 LEFT JOIN items USING (itemnumber)
363 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
364 LEFT JOIN borrowers USING (borrowernumber)
365 WHERE borrowernumber = ?
369 my $branchfield = "reserves.branchcode";
371 if ( $controlbranch eq "ItemHomeLibrary" ) {
372 $branchfield = "items.homebranch";
373 $branchcode = $item->homebranch;
375 elsif ( $controlbranch eq "PatronLibrary" ) {
376 $branchfield = "borrowers.branchcode";
377 $branchcode = $borrower->{branchcode};
381 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
382 $ruleitemtype = $rights->{itemtype};
383 $allowedreserves = $rights->{reservesallowed};
384 $holds_per_record = $rights->{holds_per_record};
385 $holds_per_day = $rights->{holds_per_day};
391 my $holds = Koha::Holds->search(
393 borrowernumber => $borrowernumber,
394 biblionumber => $item->biblionumber,
395 found => undef, # Found holds don't count against a patron's holds limit
398 if ( $holds->count() >= $holds_per_record ) {
399 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
402 my $today_holds = Koha::Holds->search({
403 borrowernumber => $borrowernumber,
404 reservedate => dt_from_string->date
407 if ( defined $holds_per_day &&
408 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
409 or ( $holds_per_day == 0 ) )
411 return { status => 'tooManyReservesToday', limit => $holds_per_day };
416 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
418 # If using item-level itypes, fall back to the record
419 # level itemtype if the hold has no associated item
421 C4::Context->preference('item-level_itypes')
422 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
423 : " AND biblioitems.itemtype = ?"
424 if ( $ruleitemtype ne "*" );
426 my $sthcount = $dbh->prepare($querycount);
428 if ( $ruleitemtype eq "*" ) {
429 $sthcount->execute( $borrowernumber, $branchcode );
432 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
435 my $reservecount = "0";
436 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
437 $reservecount = $rowcount->{count};
440 # we check if it's ok or not
441 if ( $reservecount >= $allowedreserves ) {
442 return { status => 'tooManyReserves', limit => $allowedreserves };
445 # Now we need to check hold limits by patron category
446 my $rule = Koha::CirculationRules->get_effective_rule(
448 categorycode => $borrower->{categorycode},
449 branchcode => $branchcode,
450 rule_name => 'max_holds',
453 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
454 my $total_holds_count = Koha::Holds->search(
456 borrowernumber => $borrower->{borrowernumber}
460 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
463 my $reserves_control_branch =
464 GetReservesControlBranch( $item->unblessed(), $borrower );
466 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
468 if ( $branchitemrule->{holdallowed} == 0 ) {
469 return { status => 'notReservable' };
472 if ( $branchitemrule->{holdallowed} == 1
473 && $borrower->{branchcode} ne $item->homebranch )
475 return { status => 'cannotReserveFromOtherBranches' };
478 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
479 if ( $branchitemrule->{holdallowed} == 3) {
480 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
481 return { status => 'branchNotInHoldGroup' };
485 # If reservecount is ok, we check item branch if IndependentBranches is ON
486 # and canreservefromotherbranches is OFF
487 if ( C4::Context->preference('IndependentBranches')
488 and !C4::Context->preference('canreservefromotherbranches') )
490 if ( $item->homebranch ne $borrower->{branchcode} ) {
491 return { status => 'cannotReserveFromOtherBranches' };
495 if ($pickup_branchcode) {
496 my $destination = Koha::Libraries->find({
497 branchcode => $pickup_branchcode,
500 unless ($destination) {
501 return { status => 'libraryNotFound' };
503 unless ($destination->pickup_location) {
504 return { status => 'libraryNotPickupLocation' };
506 unless ($item->can_be_transferred({ to => $destination })) {
507 return { status => 'cannotBeTransferred' };
509 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
510 return { status => 'pickupNotInHoldGroup' };
512 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
513 return { status => 'pickupNotInHoldGroup' };
517 return { status => 'OK' };
520 =head2 CanReserveBeCanceledFromOpac
522 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
524 returns 1 if reserve can be cancelled by user from OPAC.
525 First check if reserve belongs to user, next checks if reserve is not in
526 transfer or waiting status
530 sub CanReserveBeCanceledFromOpac {
531 my ($reserve_id, $borrowernumber) = @_;
533 return unless $reserve_id and $borrowernumber;
534 my $reserve = Koha::Holds->find($reserve_id);
536 return 0 unless $reserve->borrowernumber == $borrowernumber;
537 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
543 =head2 GetOtherReserves
545 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
547 Check queued list of this document and check if this document must be transferred
551 sub GetOtherReserves {
552 my ($itemnumber) = @_;
555 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
556 if ($checkreserves) {
557 my $item = Koha::Items->find($itemnumber);
558 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
559 $messages->{'transfert'} = $checkreserves->{'branchcode'};
560 #minus priorities of others reservs
561 ModReserveMinusPriority(
563 $checkreserves->{'reserve_id'},
566 #launch the subroutine dotransfer
567 C4::Items::ModItemTransfer(
569 $item->holdingbranch,
570 $checkreserves->{'branchcode'}
575 #step 2b : case of a reservation on the same branch, set the waiting status
577 $messages->{'waiting'} = 1;
578 ModReserveMinusPriority(
580 $checkreserves->{'reserve_id'},
582 ModReserveStatus($itemnumber,'W');
585 $nextreservinfo = $checkreserves->{'borrowernumber'};
588 return ( $messages, $nextreservinfo );
591 =head2 ChargeReserveFee
593 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
595 Charge the fee for a reserve (if $fee > 0)
599 sub ChargeReserveFee {
600 my ( $borrowernumber, $fee, $title ) = @_;
601 return if !$fee || $fee == 0; # the last test is needed to include 0.00
602 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
605 description => $title,
607 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
608 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
609 interface => C4::Context->interface,
610 invoice_type => undef,
619 $fee = GetReserveFee( $borrowernumber, $biblionumber );
621 Calculate the fee for a reserve (if applicable).
626 my ( $borrowernumber, $biblionumber ) = @_;
628 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
631 SELECT COUNT(*) FROM items
632 LEFT JOIN issues USING (itemnumber)
633 WHERE items.biblionumber=? AND issues.issue_id IS NULL
636 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
639 my $dbh = C4::Context->dbh;
640 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
641 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
642 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
643 # This is a reconstruction of the old code:
644 # Compare number of items with items issued, and optionally check holds
645 # If not all items are issued and there are no holds: charge no fee
646 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
647 my ( $notissued, $reserved );
648 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
651 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
652 ( $biblionumber, $borrowernumber ) );
653 $fee = 0 if $reserved == 0;
659 =head2 GetReserveStatus
661 $reservestatus = GetReserveStatus($itemnumber);
663 Takes an itemnumber and returns the status of the reserve placed on it.
664 If several reserves exist, the reserve with the lower priority is given.
668 ## FIXME: I don't think this does what it thinks it does.
669 ## It only ever checks the first reserve result, even though
670 ## multiple reserves for that bib can have the itemnumber set
671 ## the sub is only used once in the codebase.
672 sub GetReserveStatus {
673 my ($itemnumber) = @_;
675 my $dbh = C4::Context->dbh;
677 my ($sth, $found, $priority);
679 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
680 $sth->execute($itemnumber);
681 ($found, $priority) = $sth->fetchrow_array;
685 return 'Waiting' if $found eq 'W' and $priority == 0;
686 return 'Finished' if $found eq 'F';
689 return 'Reserved' if $priority > 0;
691 return ''; # empty string here will remove need for checking undef, or less log lines
696 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
697 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
698 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
700 Find a book in the reserves.
702 C<$itemnumber> is the book's item number.
703 C<$lookahead> is the number of days to look in advance for future reserves.
705 As I understand it, C<&CheckReserves> looks for the given item in the
706 reserves. If it is found, that's a match, and C<$status> is set to
709 Otherwise, it finds the most important item in the reserves with the
710 same biblio number as this book (I'm not clear on this) and returns it
711 with C<$status> set to C<Reserved>.
713 C<&CheckReserves> returns a two-element list:
715 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
717 C<$reserve> is the reserve item that matched. It is a
718 reference-to-hash whose keys are mostly the fields of the reserves
719 table in the Koha database.
724 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
725 my $dbh = C4::Context->dbh;
728 if (C4::Context->preference('item-level_itypes')){
730 SELECT items.biblionumber,
731 items.biblioitemnumber,
732 itemtypes.notforloan,
733 items.notforloan AS itemnotforloan,
739 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
740 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
745 SELECT items.biblionumber,
746 items.biblioitemnumber,
747 itemtypes.notforloan,
748 items.notforloan AS itemnotforloan,
754 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
755 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
760 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
761 $sth->execute($item);
764 $sth = $dbh->prepare("$select WHERE barcode = ?");
765 $sth->execute($barcode);
767 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
768 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
769 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
771 return unless $itemnumber; # bail if we got nothing.
772 # if item is not for loan it cannot be reserved either.....
773 # except where items.notforloan < 0 : This indicates the item is holdable.
774 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
776 # Find this item in the reserves
777 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
779 # $priority and $highest are used to find the most important item
780 # in the list returned by &_Findgroupreserve. (The lower $priority,
781 # the more important the item.)
782 # $highest is the most important item we've seen so far.
784 if (scalar @reserves) {
785 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
786 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
787 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
789 my $priority = 10000000;
790 foreach my $res (@reserves) {
791 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
792 if ($res->{'found'} eq 'W') {
793 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
795 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
800 my $local_hold_match;
802 if ($LocalHoldsPriority) {
803 $patron = Koha::Patrons->find( $res->{borrowernumber} );
804 $item = Koha::Items->find($itemnumber);
806 my $local_holds_priority_item_branchcode =
807 $item->$LocalHoldsPriorityItemControl;
808 my $local_holds_priority_patron_branchcode =
809 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
811 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
812 ? $patron->branchcode
815 $local_holds_priority_item_branchcode eq
816 $local_holds_priority_patron_branchcode;
819 # See if this item is more important than what we've got so far
820 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
821 $item ||= Koha::Items->find($itemnumber);
822 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
823 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
824 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
825 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
826 next if ($branchitemrule->{'holdallowed'} == 0);
827 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
828 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
829 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
830 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
831 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
832 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
833 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
834 next unless $item->can_be_transferred( { to => scalar Koha::Libraries->find( $res->{branchcode} ) } );
835 $priority = $res->{'priority'};
837 last if $local_hold_match;
843 # If we get this far, then no exact match was found.
844 # We return the most important (i.e. next) reservation.
846 $highest->{'itemnumber'} = $item;
847 return ( "Reserved", $highest, \@reserves );
853 =head2 CancelExpiredReserves
855 CancelExpiredReserves();
857 Cancels all reserves with an expiration date from before today.
861 sub CancelExpiredReserves {
862 my $today = dt_from_string();
863 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
864 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
866 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
867 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
868 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
870 # FIXME To move to Koha::Holds->search_expired (?)
871 my $holds = Koha::Holds->search( $params );
873 while ( my $hold = $holds->next ) {
874 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
876 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
878 my $cancel_params = {};
879 if ( $hold->found eq 'W' ) {
880 $cancel_params->{charge_cancel_fee} = 1;
882 $hold->cancel( $cancel_params );
886 =head2 AutoUnsuspendReserves
888 AutoUnsuspendReserves();
890 Unsuspends all suspended reserves with a suspend_until date from before today.
894 sub AutoUnsuspendReserves {
895 my $today = dt_from_string();
897 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
899 map { $_->resume() } @holds;
904 ModReserve({ rank => $rank,
905 reserve_id => $reserve_id,
906 branchcode => $branchcode
907 [, itemnumber => $itemnumber ]
908 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
911 Change a hold request's priority or cancel it.
913 C<$rank> specifies the effect of the change. If C<$rank>
914 is 'W' or 'n', nothing happens. This corresponds to leaving a
915 request alone when changing its priority in the holds queue
918 If C<$rank> is 'del', the hold request is cancelled.
920 If C<$rank> is an integer greater than zero, the priority of
921 the request is set to that value. Since priority != 0 means
922 that the item is not waiting on the hold shelf, setting the
923 priority to a non-zero value also sets the request's found
924 status and waiting date to NULL.
926 The optional C<$itemnumber> parameter is used only when
927 C<$rank> is a non-zero integer; if supplied, the itemnumber
928 of the hold request is set accordingly; if omitted, the itemnumber
931 B<FIXME:> Note that the forgoing can have the effect of causing
932 item-level hold requests to turn into title-level requests. This
933 will be fixed once reserves has separate columns for requested
934 itemnumber and supplying itemnumber.
941 my $rank = $params->{'rank'};
942 my $reserve_id = $params->{'reserve_id'};
943 my $branchcode = $params->{'branchcode'};
944 my $itemnumber = $params->{'itemnumber'};
945 my $suspend_until = $params->{'suspend_until'};
946 my $borrowernumber = $params->{'borrowernumber'};
947 my $biblionumber = $params->{'biblionumber'};
949 return if $rank eq "W";
950 return if $rank eq "n";
952 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
955 unless ( $reserve_id ) {
956 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
957 return unless $holds->count; # FIXME Should raise an exception
958 $hold = $holds->next;
959 $reserve_id = $hold->reserve_id;
962 $hold ||= Koha::Holds->find($reserve_id);
964 if ( $rank eq "del" ) {
967 elsif ($rank =~ /^\d+/ and $rank > 0) {
968 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
969 if C4::Context->preference('HoldsLog');
973 branchcode => $branchcode,
974 itemnumber => $itemnumber,
978 if (exists $params->{reservedate}) {
979 $properties->{reservedate} = $params->{reservedate} || undef;
981 if (exists $params->{expirationdate}) {
982 $properties->{expirationdate} = $params->{expirationdate} || undef;
985 $hold->set($properties)->store();
987 if ( defined( $suspend_until ) ) {
988 if ( $suspend_until ) {
989 $suspend_until = eval { dt_from_string( $suspend_until ) };
990 $hold->suspend_hold( $suspend_until );
992 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
993 # If the hold is not suspended, this does nothing.
994 $hold->set( { suspend_until => undef } )->store();
998 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1002 =head2 ModReserveFill
1004 &ModReserveFill($reserve);
1006 Fill a reserve. If I understand this correctly, this means that the
1007 reserved book has been found and given to the patron who reserved it.
1009 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1010 whose keys are fields from the reserves table in the Koha database.
1014 sub ModReserveFill {
1016 my $reserve_id = $res->{'reserve_id'};
1018 my $hold = Koha::Holds->find($reserve_id);
1019 # get the priority on this record....
1020 my $priority = $hold->priority;
1022 # update the hold statuses, no need to store it though, we will be deleting it anyway
1030 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1031 Koha::Old::Hold->new( $hold->unblessed() )->store();
1035 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1036 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1037 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1040 # now fix the priority on the others (if the priority wasn't
1041 # already sorted!)....
1042 unless ( $priority == 0 ) {
1043 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1047 =head2 ModReserveStatus
1049 &ModReserveStatus($itemnumber, $newstatus);
1051 Update the reserve status for the active (priority=0) reserve.
1053 $itemnumber is the itemnumber the reserve is on
1055 $newstatus is the new status.
1059 sub ModReserveStatus {
1061 #first : check if we have a reservation for this item .
1062 my ($itemnumber, $newstatus) = @_;
1063 my $dbh = C4::Context->dbh;
1065 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1066 my $sth_set = $dbh->prepare($query);
1067 $sth_set->execute( $newstatus, $itemnumber );
1069 my $item = Koha::Items->find($itemnumber);
1070 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) && $newstatus ) {
1071 CartToShelf( $itemnumber );
1075 =head2 ModReserveAffect
1077 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1079 This function affect an item and a status for a given reserve, either fetched directly
1080 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1081 is given, only first reserve returned is affected, which is ok for anything but
1084 if $transferToDo is not set, then the status is set to "Waiting" as well.
1085 otherwise, a transfer is on the way, and the end of the transfer will
1086 take care of the waiting status
1090 sub ModReserveAffect {
1091 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1092 my $dbh = C4::Context->dbh;
1094 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1095 # attached to $itemnumber
1096 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1097 $sth->execute($itemnumber);
1098 my ($biblionumber) = $sth->fetchrow;
1100 # get request - need to find out if item is already
1101 # waiting in order to not send duplicate hold filled notifications
1104 # Find hold by id if we have it
1105 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1106 # Find item level hold for this item if there is one
1107 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1108 # Find record level hold if there is no item level hold
1109 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1111 return unless $hold;
1113 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1115 $hold->itemnumber($itemnumber);
1116 $hold->set_waiting($transferToDo);
1118 _koha_notify_reserve( $hold->reserve_id )
1119 if ( !$transferToDo && !$already_on_shelf );
1121 _FixPriority( { biblionumber => $biblionumber } );
1122 my $item = Koha::Items->find($itemnumber);
1123 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) ) {
1124 CartToShelf( $itemnumber );
1130 =head2 ModReserveCancelAll
1132 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1134 function to cancel reserv,check other reserves, and transfer document if it's necessary
1138 sub ModReserveCancelAll {
1141 my ( $itemnumber, $borrowernumber ) = @_;
1143 #step 1 : cancel the reservation
1144 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1145 return unless $holds->count;
1146 $holds->next->cancel;
1148 #step 2 launch the subroutine of the others reserves
1149 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1151 return ( $messages, $nextreservinfo );
1154 =head2 ModReserveMinusPriority
1156 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1158 Reduce the values of queued list
1162 sub ModReserveMinusPriority {
1163 my ( $itemnumber, $reserve_id ) = @_;
1165 #first step update the value of the first person on reserv
1166 my $dbh = C4::Context->dbh;
1169 SET priority = 0 , itemnumber = ?
1170 WHERE reserve_id = ?
1172 my $sth_upd = $dbh->prepare($query);
1173 $sth_upd->execute( $itemnumber, $reserve_id );
1174 # second step update all others reserves
1175 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1178 =head2 IsAvailableForItemLevelRequest
1180 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1182 Checks whether a given item record is available for an
1183 item-level hold request. An item is available if
1185 * it is not lost AND
1186 * it is not damaged AND
1187 * it is not withdrawn AND
1188 * a waiting or in transit reserve is placed on
1189 * does not have a not for loan value > 0
1191 Need to check the issuingrules onshelfholds column,
1192 if this is set items on the shelf can be placed on hold
1194 Note that IsAvailableForItemLevelRequest() does not
1195 check if the staff operator is authorized to place
1196 a request on the item - in particular,
1197 this routine does not check IndependentBranches
1198 and canreservefromotherbranches.
1202 sub IsAvailableForItemLevelRequest {
1203 my ( $item, $patron, $pickup_branchcode ) = @_;
1205 my $dbh = C4::Context->dbh;
1206 # must check the notforloan setting of the itemtype
1207 # FIXME - a lot of places in the code do this
1208 # or something similar - need to be
1210 my $itemtype = $item->effective_itemtype;
1211 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1214 $notforloan_per_itemtype ||
1216 $item->notforloan > 0 ||
1218 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1220 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1222 if ($pickup_branchcode) {
1223 my $destination = Koha::Libraries->find($pickup_branchcode);
1224 return 0 unless $destination;
1225 return 0 unless $destination->pickup_location;
1226 return 0 unless $item->can_be_transferred( { to => $destination } );
1227 my $reserves_control_branch =
1228 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1229 my $branchitemrule =
1230 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1231 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1232 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1235 if ( $on_shelf_holds == 1 ) {
1237 } elsif ( $on_shelf_holds == 2 ) {
1239 Koha::Items->search( { biblionumber => $item->biblionumber } );
1241 my $any_available = 0;
1243 foreach my $i (@items) {
1244 my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1245 my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1246 my $item_library = Koha::Libraries->find( {branchcode => $i->homebranch} );
1251 || $i->notforloan > 0
1254 || IsItemOnHoldAndFound( $i->id )
1256 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1257 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1258 || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch
1259 || $branchitemrule->{holdallowed} == 3 && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} );
1262 return $any_available ? 0 : 1;
1263 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1264 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1272 if (C4::Context->preference('item-level_itypes')) {
1273 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1274 # When GetItem is fixed, we can remove this
1275 $itype = $item->{itype};
1278 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1279 # So if we already have a biblioitems join when calling this function,
1280 # we don't need to access the database again
1281 $itype = $item->{itemtype};
1284 my $dbh = C4::Context->dbh;
1285 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1286 my $sth = $dbh->prepare($query);
1287 $sth->execute($item->{biblioitemnumber});
1288 if (my $data = $sth->fetchrow_hashref()){
1289 $itype = $data->{itemtype};
1295 =head2 AlterPriority
1297 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1299 This function changes a reserve's priority up, down, to the top, or to the bottom.
1300 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1305 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1307 my $hold = Koha::Holds->find( $reserve_id );
1308 return unless $hold;
1310 if ( $hold->cancellationdate ) {
1311 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1315 if ( $where eq 'up' ) {
1316 return unless $prev_priority;
1317 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1318 } elsif ( $where eq 'down' ) {
1319 return unless $next_priority;
1320 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1321 } elsif ( $where eq 'top' ) {
1322 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1323 } elsif ( $where eq 'bottom' ) {
1324 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1327 # FIXME Should return the new priority
1330 =head2 ToggleLowestPriority
1332 ToggleLowestPriority( $borrowernumber, $biblionumber );
1334 This function sets the lowestPriority field to true if is false, and false if it is true.
1338 sub ToggleLowestPriority {
1339 my ( $reserve_id ) = @_;
1341 my $dbh = C4::Context->dbh;
1343 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1344 $sth->execute( $reserve_id );
1346 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1349 =head2 ToggleSuspend
1351 ToggleSuspend( $reserve_id );
1353 This function sets the suspend field to true if is false, and false if it is true.
1354 If the reserve is currently suspended with a suspend_until date, that date will
1355 be cleared when it is unsuspended.
1360 my ( $reserve_id, $suspend_until ) = @_;
1362 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1364 my $hold = Koha::Holds->find( $reserve_id );
1366 if ( $hold->is_suspended ) {
1369 $hold->suspend_hold( $suspend_until );
1376 borrowernumber => $borrowernumber,
1377 [ biblionumber => $biblionumber, ]
1378 [ suspend_until => $suspend_until, ]
1379 [ suspend => $suspend ]
1382 This function accepts a set of hash keys as its parameters.
1383 It requires either borrowernumber or biblionumber, or both.
1385 suspend_until is wholly optional.
1392 my $borrowernumber = $params{'borrowernumber'} || undef;
1393 my $biblionumber = $params{'biblionumber'} || undef;
1394 my $suspend_until = $params{'suspend_until'} || undef;
1395 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1397 $suspend_until = eval { dt_from_string($suspend_until) }
1398 if ( defined($suspend_until) );
1400 return unless ( $borrowernumber || $biblionumber );
1403 $params->{found} = undef;
1404 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1405 $params->{biblionumber} = $biblionumber if $biblionumber;
1407 my @holds = Koha::Holds->search($params);
1410 map { $_->suspend_hold($suspend_until) } @holds;
1413 map { $_->resume() } @holds;
1421 reserve_id => $reserve_id,
1423 [ignoreSetLowestRank => $ignoreSetLowestRank]
1428 _FixPriority({ biblionumber => $biblionumber});
1430 This routine adjusts the priority of a hold request and holds
1433 In the first form, where a reserve_id is passed, the priority of the
1434 hold is set to supplied rank, and other holds for that bib are adjusted
1435 accordingly. If the rank is "del", the hold is cancelled. If no rank
1436 is supplied, all of the holds on that bib have their priority adjusted
1437 as if the second form had been used.
1439 In the second form, where a biblionumber is passed, the holds on that
1440 bib (that are not captured) are sorted in order of increasing priority,
1441 then have reserves.priority set so that the first non-captured hold
1442 has its priority set to 1, the second non-captured hold has its priority
1443 set to 2, and so forth.
1445 In both cases, holds that have the lowestPriority flag on are have their
1446 priority adjusted to ensure that they remain at the end of the line.
1448 Note that the ignoreSetLowestRank parameter is meant to be used only
1449 when _FixPriority calls itself.
1454 my ( $params ) = @_;
1455 my $reserve_id = $params->{reserve_id};
1456 my $rank = $params->{rank} // '';
1457 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1458 my $biblionumber = $params->{biblionumber};
1460 my $dbh = C4::Context->dbh;
1463 if ( $reserve_id ) {
1464 $hold = Koha::Holds->find( $reserve_id );
1465 return unless $hold;
1468 unless ( $biblionumber ) { # FIXME This is a very weird API
1469 $biblionumber = $hold->biblionumber;
1472 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1475 elsif ( $rank eq "W" || $rank eq "0" ) {
1477 # make sure priority for waiting or in-transit items is 0
1481 WHERE reserve_id = ?
1482 AND found IN ('W', 'T')
1484 my $sth = $dbh->prepare($query);
1485 $sth->execute( $reserve_id );
1491 SELECT reserve_id, borrowernumber, reservedate
1493 WHERE biblionumber = ?
1494 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1495 ORDER BY priority ASC
1497 my $sth = $dbh->prepare($query);
1498 $sth->execute( $biblionumber );
1499 while ( my $line = $sth->fetchrow_hashref ) {
1500 push( @priority, $line );
1503 # To find the matching index
1505 my $key = -1; # to allow for 0 to be a valid result
1506 for ( $i = 0 ; $i < @priority ; $i++ ) {
1507 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1508 $key = $i; # save the index
1513 # if index exists in array then move it to new position
1514 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1515 my $new_rank = $rank -
1516 1; # $new_rank is what you want the new index to be in the array
1517 my $moving_item = splice( @priority, $key, 1 );
1518 splice( @priority, $new_rank, 0, $moving_item );
1521 # now fix the priority on those that are left....
1525 WHERE reserve_id = ?
1527 $sth = $dbh->prepare($query);
1528 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1531 $priority[$j]->{'reserve_id'}
1535 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1538 unless ( $ignoreSetLowestRank ) {
1539 while ( my $res = $sth->fetchrow_hashref() ) {
1541 reserve_id => $res->{'reserve_id'},
1543 ignoreSetLowestRank => 1
1549 =head2 _Findgroupreserve
1551 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1553 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1554 first match found. If neither, then we look for non-holds-queue based holds.
1555 Lookahead is the number of days to look in advance.
1557 C<&_Findgroupreserve> returns :
1558 C<@results> is an array of references-to-hash whose keys are mostly
1559 fields from the reserves table of the Koha database, plus
1560 C<biblioitemnumber>.
1562 This routine with either return:
1563 1 - Item specific holds from the holds queue
1564 2 - Title level holds from the holds queue
1565 3 - All holds for this biblionumber
1567 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1571 sub _Findgroupreserve {
1572 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1573 my $dbh = C4::Context->dbh;
1575 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1576 # check for exact targeted match
1577 my $item_level_target_query = qq{
1578 SELECT reserves.biblionumber AS biblionumber,
1579 reserves.borrowernumber AS borrowernumber,
1580 reserves.reservedate AS reservedate,
1581 reserves.branchcode AS branchcode,
1582 reserves.cancellationdate AS cancellationdate,
1583 reserves.found AS found,
1584 reserves.reservenotes AS reservenotes,
1585 reserves.priority AS priority,
1586 reserves.timestamp AS timestamp,
1587 biblioitems.biblioitemnumber AS biblioitemnumber,
1588 reserves.itemnumber AS itemnumber,
1589 reserves.reserve_id AS reserve_id,
1590 reserves.itemtype AS itemtype
1592 JOIN biblioitems USING (biblionumber)
1593 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1596 AND item_level_request = 1
1598 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1602 my $sth = $dbh->prepare($item_level_target_query);
1603 $sth->execute($itemnumber, $lookahead||0);
1605 if ( my $data = $sth->fetchrow_hashref ) {
1606 push( @results, $data )
1607 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1609 return @results if @results;
1611 # check for title-level targeted match
1612 my $title_level_target_query = qq{
1613 SELECT reserves.biblionumber AS biblionumber,
1614 reserves.borrowernumber AS borrowernumber,
1615 reserves.reservedate AS reservedate,
1616 reserves.branchcode AS branchcode,
1617 reserves.cancellationdate AS cancellationdate,
1618 reserves.found AS found,
1619 reserves.reservenotes AS reservenotes,
1620 reserves.priority AS priority,
1621 reserves.timestamp AS timestamp,
1622 biblioitems.biblioitemnumber AS biblioitemnumber,
1623 reserves.itemnumber AS itemnumber,
1624 reserves.reserve_id AS reserve_id,
1625 reserves.itemtype AS itemtype
1627 JOIN biblioitems USING (biblionumber)
1628 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1631 AND item_level_request = 0
1632 AND hold_fill_targets.itemnumber = ?
1633 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1637 $sth = $dbh->prepare($title_level_target_query);
1638 $sth->execute($itemnumber, $lookahead||0);
1640 if ( my $data = $sth->fetchrow_hashref ) {
1641 push( @results, $data )
1642 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1644 return @results if @results;
1647 SELECT reserves.biblionumber AS biblionumber,
1648 reserves.borrowernumber AS borrowernumber,
1649 reserves.reservedate AS reservedate,
1650 reserves.waitingdate AS waitingdate,
1651 reserves.branchcode AS branchcode,
1652 reserves.cancellationdate AS cancellationdate,
1653 reserves.found AS found,
1654 reserves.reservenotes AS reservenotes,
1655 reserves.priority AS priority,
1656 reserves.timestamp AS timestamp,
1657 reserves.itemnumber AS itemnumber,
1658 reserves.reserve_id AS reserve_id,
1659 reserves.itemtype AS itemtype
1661 WHERE reserves.biblionumber = ?
1662 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1663 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1667 $sth = $dbh->prepare($query);
1668 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1670 while ( my $data = $sth->fetchrow_hashref ) {
1671 push( @results, $data )
1672 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1677 =head2 _koha_notify_reserve
1679 _koha_notify_reserve( $hold->reserve_id );
1681 Sends a notification to the patron that their hold has been filled (through
1682 ModReserveAffect, _not_ ModReserveFill)
1684 The letter code for this notice may be found using the following query:
1686 select distinct letter_code
1687 from message_transports
1688 inner join message_attributes using (message_attribute_id)
1689 where message_name = 'Hold_Filled'
1691 This will probably sipmly be 'HOLD', but because it is defined in the database,
1692 it is subject to addition or change.
1694 The following tables are availalbe witin the notice:
1705 sub _koha_notify_reserve {
1706 my $reserve_id = shift;
1707 my $hold = Koha::Holds->find($reserve_id);
1708 my $borrowernumber = $hold->borrowernumber;
1710 my $patron = Koha::Patrons->find( $borrowernumber );
1712 # Try to get the borrower's email address
1713 my $to_address = $patron->notice_email_address;
1715 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1716 borrowernumber => $borrowernumber,
1717 message_name => 'Hold_Filled'
1720 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1722 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1724 my %letter_params = (
1725 module => 'reserves',
1726 branchcode => $hold->branchcode,
1727 lang => $patron->lang,
1729 'branches' => $library,
1730 'borrowers' => $patron->unblessed,
1731 'biblio' => $hold->biblionumber,
1732 'biblioitems' => $hold->biblionumber,
1733 'reserves' => $hold->unblessed,
1734 'items' => $hold->itemnumber,
1738 my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message.
1739 my $send_notification = sub {
1740 my ( $mtt, $letter_code ) = (@_);
1741 return unless defined $letter_code;
1742 $letter_params{letter_code} = $letter_code;
1743 $letter_params{message_transport_type} = $mtt;
1744 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1746 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1750 C4::Letters::EnqueueLetter( {
1752 borrowernumber => $borrowernumber,
1753 from_address => $admin_email_address,
1754 message_transport_type => $mtt,
1758 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1760 ( $mtt eq 'email' and not $to_address ) # No email address
1761 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1762 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1765 &$send_notification($mtt, $letter_code);
1766 $notification_sent++;
1768 #Making sure that a print notification is sent if no other transport types can be utilized.
1769 if (! $notification_sent) {
1770 &$send_notification('print', 'HOLD');
1775 =head2 _ShiftPriorityByDateAndPriority
1777 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1779 This increments the priority of all reserves after the one
1780 with either the lowest date after C<$reservedate>
1781 or the lowest priority after C<$priority>.
1783 It effectively makes room for a new reserve to be inserted with a certain
1784 priority, which is returned.
1786 This is most useful when the reservedate can be set by the user. It allows
1787 the new reserve to be placed before other reserves that have a later
1788 reservedate. Since priority also is set by the form in reserves/request.pl
1789 the sub accounts for that too.
1793 sub _ShiftPriorityByDateAndPriority {
1794 my ( $biblio, $resdate, $new_priority ) = @_;
1796 my $dbh = C4::Context->dbh;
1797 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1798 my $sth = $dbh->prepare( $query );
1799 $sth->execute( $biblio, $resdate, $new_priority );
1800 my $min_priority = $sth->fetchrow;
1801 # if no such matches are found, $new_priority remains as original value
1802 $new_priority = $min_priority if ( $min_priority );
1804 # Shift the priority up by one; works in conjunction with the next SQL statement
1805 $query = "UPDATE reserves
1806 SET priority = priority+1
1807 WHERE biblionumber = ?
1808 AND borrowernumber = ?
1811 my $sth_update = $dbh->prepare( $query );
1813 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1814 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1815 $sth = $dbh->prepare( $query );
1816 $sth->execute( $new_priority, $biblio );
1817 while ( my $row = $sth->fetchrow_hashref ) {
1818 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1821 return $new_priority; # so the caller knows what priority they wind up receiving
1826 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1828 Use when checking out an item to handle reserves
1829 If $cancelreserve boolean is set to true, it will remove existing reserve
1834 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1836 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1837 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1840 my $biblionumber = $res->{biblionumber};
1842 if ($res->{borrowernumber} == $borrowernumber) {
1843 ModReserveFill($res);
1847 # The item is reserved by someone else.
1848 # Find this item in the reserves
1850 my $borr_res = Koha::Holds->search({
1851 borrowernumber => $borrowernumber,
1852 biblionumber => $biblionumber,
1854 order_by => 'priority'
1858 # The item is reserved by the current patron
1859 ModReserveFill($borr_res->unblessed);
1862 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1863 RevertWaitingStatus({ itemnumber => $itemnumber });
1865 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1866 my $hold = Koha::Holds->find( $res->{reserve_id} );
1874 MergeHolds($dbh,$to_biblio, $from_biblio);
1876 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1881 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1882 my $sth = $dbh->prepare(
1883 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1885 $sth->execute($from_biblio);
1886 if ( my $data = $sth->fetchrow_hashref() ) {
1888 # holds exist on old record, if not we don't need to do anything
1889 $sth = $dbh->prepare(
1890 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1891 $sth->execute( $to_biblio, $from_biblio );
1894 # don't reorder those already waiting
1896 $sth = $dbh->prepare(
1897 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1899 my $upd_sth = $dbh->prepare(
1900 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1901 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1903 $sth->execute( $to_biblio, 'W', 'T' );
1905 while ( my $reserve = $sth->fetchrow_hashref() ) {
1907 $priority, $to_biblio,
1908 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1909 $reserve->{'itemnumber'}
1916 =head2 RevertWaitingStatus
1918 RevertWaitingStatus({ itemnumber => $itemnumber });
1920 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1922 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1923 item level hold, even if it was only a bibliolevel hold to
1924 begin with. This is because we can no longer know if a hold
1925 was item-level or bib-level after a hold has been set to
1930 sub RevertWaitingStatus {
1931 my ( $params ) = @_;
1932 my $itemnumber = $params->{'itemnumber'};
1934 return unless ( $itemnumber );
1936 my $dbh = C4::Context->dbh;
1938 ## Get the waiting reserve we want to revert
1940 SELECT * FROM reserves
1941 WHERE itemnumber = ?
1942 AND found IS NOT NULL
1944 my $sth = $dbh->prepare( $query );
1945 $sth->execute( $itemnumber );
1946 my $reserve = $sth->fetchrow_hashref();
1948 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1950 ## Increment the priority of all other non-waiting
1951 ## reserves for this bib record
1955 priority = priority + 1
1961 $sth = $dbh->prepare( $query );
1962 $sth->execute( $reserve->{'biblionumber'} );
1964 ## Fix up the currently waiting reserve
1974 $sth = $dbh->prepare( $query );
1975 $sth->execute( $reserve->{'reserve_id'} );
1977 unless ( $hold->item_level_hold ) {
1978 $hold->itemnumber(undef)->store;
1981 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1988 branchcode => $branchcode,
1989 borrowernumber => $borrowernumber,
1990 biblionumber => $biblionumber,
1991 [ itemnumber => $itemnumber, ]
1992 [ barcode => $barcode, ]
1996 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1998 The letter code will be HOLD_SLIP, and the following tables are
1999 available within the slip:
2012 my $branchcode = $args->{branchcode};
2013 my $borrowernumber = $args->{borrowernumber};
2014 my $biblionumber = $args->{biblionumber};
2015 my $itemnumber = $args->{itemnumber};
2016 my $barcode = $args->{barcode};
2019 my $patron = Koha::Patrons->find($borrowernumber);
2022 if ($itemnumber || $barcode ) {
2023 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2025 $hold = Koha::Holds->search(
2027 biblionumber => $biblionumber,
2028 borrowernumber => $borrowernumber,
2029 itemnumber => $itemnumber
2034 $hold = Koha::Holds->search(
2036 biblionumber => $biblionumber,
2037 borrowernumber => $borrowernumber
2042 return unless $hold;
2043 my $reserve = $hold->unblessed;
2045 return C4::Letters::GetPreparedLetter (
2046 module => 'circulation',
2047 letter_code => 'HOLD_SLIP',
2048 branchcode => $branchcode,
2049 lang => $patron->lang,
2051 'reserves' => $reserve,
2052 'branches' => $reserve->{branchcode},
2053 'borrowers' => $reserve->{borrowernumber},
2054 'biblio' => $reserve->{biblionumber},
2055 'biblioitems' => $reserve->{biblionumber},
2056 'items' => $reserve->{itemnumber},
2061 =head2 GetReservesControlBranch
2063 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2065 Return the branchcode to be used to determine which reserves
2066 policy applies to a transaction.
2068 C<$item> is a hashref for an item. Only 'homebranch' is used.
2070 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2074 sub GetReservesControlBranch {
2075 my ( $item, $borrower ) = @_;
2077 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2080 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2081 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2087 =head2 CalculatePriority
2089 my $p = CalculatePriority($biblionumber, $resdate);
2091 Calculate priority for a new reserve on biblionumber, placing it at
2092 the end of the line of all holds whose start date falls before
2093 the current system time and that are neither on the hold shelf
2096 The reserve date parameter is optional; if it is supplied, the
2097 priority is based on the set of holds whose start date falls before
2098 the parameter value.
2100 After calculation of this priority, it is recommended to call
2101 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2106 sub CalculatePriority {
2107 my ( $biblionumber, $resdate ) = @_;
2110 SELECT COUNT(*) FROM reserves
2111 WHERE biblionumber = ?
2113 AND (found IS NULL OR found = '')
2115 #skip found==W or found==T (waiting or transit holds)
2117 $sql.= ' AND ( reservedate <= ? )';
2120 $sql.= ' AND ( reservedate < NOW() )';
2122 my $dbh = C4::Context->dbh();
2123 my @row = $dbh->selectrow_array(
2126 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2129 return @row ? $row[0]+1 : 1;
2132 =head2 IsItemOnHoldAndFound
2134 my $bool = IsItemFoundHold( $itemnumber );
2136 Returns true if the item is currently on hold
2137 and that hold has a non-null found status ( W, T, etc. )
2141 sub IsItemOnHoldAndFound {
2142 my ($itemnumber) = @_;
2144 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2146 my $found = $rs->count(
2148 itemnumber => $itemnumber,
2149 found => { '!=' => undef }
2156 =head2 GetMaxPatronHoldsForRecord
2158 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2160 For multiple holds on a given record for a given patron, the max
2161 number of record level holds that a patron can be placed is the highest
2162 value of the holds_per_record rule for each item if the record for that
2163 patron. This subroutine finds and returns the highest holds_per_record
2164 rule value for a given patron id and record id.
2168 sub GetMaxPatronHoldsForRecord {
2169 my ( $borrowernumber, $biblionumber ) = @_;
2171 my $patron = Koha::Patrons->find($borrowernumber);
2172 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2174 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2176 my $categorycode = $patron->categorycode;
2178 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2181 foreach my $item (@items) {
2182 my $itemtype = $item->effective_itemtype();
2184 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2186 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2187 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2188 $max = $holds_per_record if $holds_per_record > $max;
2196 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2198 Returns the matching hold related issuingrule fields for a given
2199 patron category, itemtype, and library.
2204 my ( $categorycode, $itemtype, $branchcode ) = @_;
2206 my $dbh = C4::Context->dbh;
2208 my $sth = $dbh->prepare(
2210 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2212 WHERE (categorycode in (?,'*') )
2213 AND (itemtype IN (?,'*'))
2214 AND (branchcode IN (?,'*'))
2215 ORDER BY categorycode DESC,
2221 $sth->execute( $categorycode, $itemtype, $branchcode );
2223 return $sth->fetchrow_hashref();
2228 Koha Development Team <http://koha-community.org/>