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' };
514 return { status => 'OK' };
517 =head2 CanReserveBeCanceledFromOpac
519 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
521 returns 1 if reserve can be cancelled by user from OPAC.
522 First check if reserve belongs to user, next checks if reserve is not in
523 transfer or waiting status
527 sub CanReserveBeCanceledFromOpac {
528 my ($reserve_id, $borrowernumber) = @_;
530 return unless $reserve_id and $borrowernumber;
531 my $reserve = Koha::Holds->find($reserve_id);
533 return 0 unless $reserve->borrowernumber == $borrowernumber;
534 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
540 =head2 GetOtherReserves
542 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
544 Check queued list of this document and check if this document must be transferred
548 sub GetOtherReserves {
549 my ($itemnumber) = @_;
552 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
553 if ($checkreserves) {
554 my $item = Koha::Items->find($itemnumber);
555 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
556 $messages->{'transfert'} = $checkreserves->{'branchcode'};
557 #minus priorities of others reservs
558 ModReserveMinusPriority(
560 $checkreserves->{'reserve_id'},
563 #launch the subroutine dotransfer
564 C4::Items::ModItemTransfer(
566 $item->holdingbranch,
567 $checkreserves->{'branchcode'}
572 #step 2b : case of a reservation on the same branch, set the waiting status
574 $messages->{'waiting'} = 1;
575 ModReserveMinusPriority(
577 $checkreserves->{'reserve_id'},
579 ModReserveStatus($itemnumber,'W');
582 $nextreservinfo = $checkreserves->{'borrowernumber'};
585 return ( $messages, $nextreservinfo );
588 =head2 ChargeReserveFee
590 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
592 Charge the fee for a reserve (if $fee > 0)
596 sub ChargeReserveFee {
597 my ( $borrowernumber, $fee, $title ) = @_;
598 return if !$fee || $fee == 0; # the last test is needed to include 0.00
599 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
602 description => $title,
604 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
605 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
606 interface => C4::Context->interface,
607 invoice_type => undef,
616 $fee = GetReserveFee( $borrowernumber, $biblionumber );
618 Calculate the fee for a reserve (if applicable).
623 my ( $borrowernumber, $biblionumber ) = @_;
625 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
628 SELECT COUNT(*) FROM items
629 LEFT JOIN issues USING (itemnumber)
630 WHERE items.biblionumber=? AND issues.issue_id IS NULL
633 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
636 my $dbh = C4::Context->dbh;
637 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
638 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
639 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
640 # This is a reconstruction of the old code:
641 # Compare number of items with items issued, and optionally check holds
642 # If not all items are issued and there are no holds: charge no fee
643 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
644 my ( $notissued, $reserved );
645 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
648 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
649 ( $biblionumber, $borrowernumber ) );
650 $fee = 0 if $reserved == 0;
656 =head2 GetReserveStatus
658 $reservestatus = GetReserveStatus($itemnumber);
660 Takes an itemnumber and returns the status of the reserve placed on it.
661 If several reserves exist, the reserve with the lower priority is given.
665 ## FIXME: I don't think this does what it thinks it does.
666 ## It only ever checks the first reserve result, even though
667 ## multiple reserves for that bib can have the itemnumber set
668 ## the sub is only used once in the codebase.
669 sub GetReserveStatus {
670 my ($itemnumber) = @_;
672 my $dbh = C4::Context->dbh;
674 my ($sth, $found, $priority);
676 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
677 $sth->execute($itemnumber);
678 ($found, $priority) = $sth->fetchrow_array;
682 return 'Waiting' if $found eq 'W' and $priority == 0;
683 return 'Finished' if $found eq 'F';
686 return 'Reserved' if $priority > 0;
688 return ''; # empty string here will remove need for checking undef, or less log lines
693 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
694 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
695 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
697 Find a book in the reserves.
699 C<$itemnumber> is the book's item number.
700 C<$lookahead> is the number of days to look in advance for future reserves.
702 As I understand it, C<&CheckReserves> looks for the given item in the
703 reserves. If it is found, that's a match, and C<$status> is set to
706 Otherwise, it finds the most important item in the reserves with the
707 same biblio number as this book (I'm not clear on this) and returns it
708 with C<$status> set to C<Reserved>.
710 C<&CheckReserves> returns a two-element list:
712 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
714 C<$reserve> is the reserve item that matched. It is a
715 reference-to-hash whose keys are mostly the fields of the reserves
716 table in the Koha database.
721 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
722 my $dbh = C4::Context->dbh;
725 if (C4::Context->preference('item-level_itypes')){
727 SELECT items.biblionumber,
728 items.biblioitemnumber,
729 itemtypes.notforloan,
730 items.notforloan AS itemnotforloan,
736 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
737 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
742 SELECT items.biblionumber,
743 items.biblioitemnumber,
744 itemtypes.notforloan,
745 items.notforloan AS itemnotforloan,
751 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
752 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
757 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
758 $sth->execute($item);
761 $sth = $dbh->prepare("$select WHERE barcode = ?");
762 $sth->execute($barcode);
764 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
765 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
766 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
768 return unless $itemnumber; # bail if we got nothing.
769 # if item is not for loan it cannot be reserved either.....
770 # except where items.notforloan < 0 : This indicates the item is holdable.
771 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
773 # Find this item in the reserves
774 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
776 # $priority and $highest are used to find the most important item
777 # in the list returned by &_Findgroupreserve. (The lower $priority,
778 # the more important the item.)
779 # $highest is the most important item we've seen so far.
781 if (scalar @reserves) {
782 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
783 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
784 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
786 my $priority = 10000000;
787 foreach my $res (@reserves) {
788 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
789 if ($res->{'found'} eq 'W') {
790 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
792 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
797 my $local_hold_match;
799 if ($LocalHoldsPriority) {
800 $patron = Koha::Patrons->find( $res->{borrowernumber} );
801 $item = Koha::Items->find($itemnumber);
803 my $local_holds_priority_item_branchcode =
804 $item->$LocalHoldsPriorityItemControl;
805 my $local_holds_priority_patron_branchcode =
806 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
808 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
809 ? $patron->branchcode
812 $local_holds_priority_item_branchcode eq
813 $local_holds_priority_patron_branchcode;
816 # See if this item is more important than what we've got so far
817 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
818 $item ||= Koha::Items->find($itemnumber);
819 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
820 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
821 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
822 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
823 next if ($branchitemrule->{'holdallowed'} == 0);
824 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
825 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
826 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
827 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
828 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
829 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
830 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
831 next unless $item->can_be_transferred( { to => scalar Koha::Libraries->find( $res->{branchcode} ) } );
832 $priority = $res->{'priority'};
834 last if $local_hold_match;
840 # If we get this far, then no exact match was found.
841 # We return the most important (i.e. next) reservation.
843 $highest->{'itemnumber'} = $item;
844 return ( "Reserved", $highest, \@reserves );
850 =head2 CancelExpiredReserves
852 CancelExpiredReserves();
854 Cancels all reserves with an expiration date from before today.
858 sub CancelExpiredReserves {
859 my $today = dt_from_string();
860 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
861 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
863 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
864 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
865 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
867 # FIXME To move to Koha::Holds->search_expired (?)
868 my $holds = Koha::Holds->search( $params );
870 while ( my $hold = $holds->next ) {
871 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
873 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
875 my $cancel_params = {};
876 if ( $hold->found eq 'W' ) {
877 $cancel_params->{charge_cancel_fee} = 1;
879 $hold->cancel( $cancel_params );
883 =head2 AutoUnsuspendReserves
885 AutoUnsuspendReserves();
887 Unsuspends all suspended reserves with a suspend_until date from before today.
891 sub AutoUnsuspendReserves {
892 my $today = dt_from_string();
894 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
896 map { $_->resume() } @holds;
901 ModReserve({ rank => $rank,
902 reserve_id => $reserve_id,
903 branchcode => $branchcode
904 [, itemnumber => $itemnumber ]
905 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
908 Change a hold request's priority or cancel it.
910 C<$rank> specifies the effect of the change. If C<$rank>
911 is 'W' or 'n', nothing happens. This corresponds to leaving a
912 request alone when changing its priority in the holds queue
915 If C<$rank> is 'del', the hold request is cancelled.
917 If C<$rank> is an integer greater than zero, the priority of
918 the request is set to that value. Since priority != 0 means
919 that the item is not waiting on the hold shelf, setting the
920 priority to a non-zero value also sets the request's found
921 status and waiting date to NULL.
923 The optional C<$itemnumber> parameter is used only when
924 C<$rank> is a non-zero integer; if supplied, the itemnumber
925 of the hold request is set accordingly; if omitted, the itemnumber
928 B<FIXME:> Note that the forgoing can have the effect of causing
929 item-level hold requests to turn into title-level requests. This
930 will be fixed once reserves has separate columns for requested
931 itemnumber and supplying itemnumber.
938 my $rank = $params->{'rank'};
939 my $reserve_id = $params->{'reserve_id'};
940 my $branchcode = $params->{'branchcode'};
941 my $itemnumber = $params->{'itemnumber'};
942 my $suspend_until = $params->{'suspend_until'};
943 my $borrowernumber = $params->{'borrowernumber'};
944 my $biblionumber = $params->{'biblionumber'};
946 return if $rank eq "W";
947 return if $rank eq "n";
949 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
952 unless ( $reserve_id ) {
953 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
954 return unless $holds->count; # FIXME Should raise an exception
955 $hold = $holds->next;
956 $reserve_id = $hold->reserve_id;
959 $hold ||= Koha::Holds->find($reserve_id);
961 if ( $rank eq "del" ) {
964 elsif ($rank =~ /^\d+/ and $rank > 0) {
965 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
966 if C4::Context->preference('HoldsLog');
970 branchcode => $branchcode,
971 itemnumber => $itemnumber,
975 if (exists $params->{reservedate}) {
976 $properties->{reservedate} = $params->{reservedate} || undef;
978 if (exists $params->{expirationdate}) {
979 $properties->{expirationdate} = $params->{expirationdate} || undef;
982 $hold->set($properties)->store();
984 if ( defined( $suspend_until ) ) {
985 if ( $suspend_until ) {
986 $suspend_until = eval { dt_from_string( $suspend_until ) };
987 $hold->suspend_hold( $suspend_until );
989 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
990 # If the hold is not suspended, this does nothing.
991 $hold->set( { suspend_until => undef } )->store();
995 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
999 =head2 ModReserveFill
1001 &ModReserveFill($reserve);
1003 Fill a reserve. If I understand this correctly, this means that the
1004 reserved book has been found and given to the patron who reserved it.
1006 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1007 whose keys are fields from the reserves table in the Koha database.
1011 sub ModReserveFill {
1013 my $reserve_id = $res->{'reserve_id'};
1015 my $hold = Koha::Holds->find($reserve_id);
1016 # get the priority on this record....
1017 my $priority = $hold->priority;
1019 # update the hold statuses, no need to store it though, we will be deleting it anyway
1027 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1028 Koha::Old::Hold->new( $hold->unblessed() )->store();
1032 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1033 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1034 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1037 # now fix the priority on the others (if the priority wasn't
1038 # already sorted!)....
1039 unless ( $priority == 0 ) {
1040 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1044 =head2 ModReserveStatus
1046 &ModReserveStatus($itemnumber, $newstatus);
1048 Update the reserve status for the active (priority=0) reserve.
1050 $itemnumber is the itemnumber the reserve is on
1052 $newstatus is the new status.
1056 sub ModReserveStatus {
1058 #first : check if we have a reservation for this item .
1059 my ($itemnumber, $newstatus) = @_;
1060 my $dbh = C4::Context->dbh;
1062 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1063 my $sth_set = $dbh->prepare($query);
1064 $sth_set->execute( $newstatus, $itemnumber );
1066 my $item = Koha::Items->find($itemnumber);
1067 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) && $newstatus ) {
1068 CartToShelf( $itemnumber );
1072 =head2 ModReserveAffect
1074 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1076 This function affect an item and a status for a given reserve, either fetched directly
1077 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1078 is given, only first reserve returned is affected, which is ok for anything but
1081 if $transferToDo is not set, then the status is set to "Waiting" as well.
1082 otherwise, a transfer is on the way, and the end of the transfer will
1083 take care of the waiting status
1087 sub ModReserveAffect {
1088 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1089 my $dbh = C4::Context->dbh;
1091 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1092 # attached to $itemnumber
1093 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1094 $sth->execute($itemnumber);
1095 my ($biblionumber) = $sth->fetchrow;
1097 # get request - need to find out if item is already
1098 # waiting in order to not send duplicate hold filled notifications
1101 # Find hold by id if we have it
1102 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1103 # Find item level hold for this item if there is one
1104 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1105 # Find record level hold if there is no item level hold
1106 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1108 return unless $hold;
1110 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1112 $hold->itemnumber($itemnumber);
1113 $hold->set_waiting($transferToDo);
1115 _koha_notify_reserve( $hold->reserve_id )
1116 if ( !$transferToDo && !$already_on_shelf );
1118 _FixPriority( { biblionumber => $biblionumber } );
1119 my $item = Koha::Items->find($itemnumber);
1120 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) ) {
1121 CartToShelf( $itemnumber );
1127 =head2 ModReserveCancelAll
1129 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1131 function to cancel reserv,check other reserves, and transfer document if it's necessary
1135 sub ModReserveCancelAll {
1138 my ( $itemnumber, $borrowernumber ) = @_;
1140 #step 1 : cancel the reservation
1141 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1142 return unless $holds->count;
1143 $holds->next->cancel;
1145 #step 2 launch the subroutine of the others reserves
1146 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1148 return ( $messages, $nextreservinfo );
1151 =head2 ModReserveMinusPriority
1153 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1155 Reduce the values of queued list
1159 sub ModReserveMinusPriority {
1160 my ( $itemnumber, $reserve_id ) = @_;
1162 #first step update the value of the first person on reserv
1163 my $dbh = C4::Context->dbh;
1166 SET priority = 0 , itemnumber = ?
1167 WHERE reserve_id = ?
1169 my $sth_upd = $dbh->prepare($query);
1170 $sth_upd->execute( $itemnumber, $reserve_id );
1171 # second step update all others reserves
1172 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1175 =head2 IsAvailableForItemLevelRequest
1177 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1179 Checks whether a given item record is available for an
1180 item-level hold request. An item is available if
1182 * it is not lost AND
1183 * it is not damaged AND
1184 * it is not withdrawn AND
1185 * a waiting or in transit reserve is placed on
1186 * does not have a not for loan value > 0
1188 Need to check the issuingrules onshelfholds column,
1189 if this is set items on the shelf can be placed on hold
1191 Note that IsAvailableForItemLevelRequest() does not
1192 check if the staff operator is authorized to place
1193 a request on the item - in particular,
1194 this routine does not check IndependentBranches
1195 and canreservefromotherbranches.
1199 sub IsAvailableForItemLevelRequest {
1200 my ( $item, $patron, $pickup_branchcode ) = @_;
1202 my $dbh = C4::Context->dbh;
1203 # must check the notforloan setting of the itemtype
1204 # FIXME - a lot of places in the code do this
1205 # or something similar - need to be
1207 my $itemtype = $item->effective_itemtype;
1208 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1211 $notforloan_per_itemtype ||
1213 $item->notforloan > 0 ||
1215 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1217 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1219 if ($pickup_branchcode) {
1220 my $destination = Koha::Libraries->find($pickup_branchcode);
1221 return 0 unless $destination;
1222 return 0 unless $destination->pickup_location;
1223 return 0 unless $item->can_be_transferred( { to => $destination } );
1224 my $reserves_control_branch =
1225 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1226 my $branchitemrule =
1227 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1228 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1229 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1232 if ( $on_shelf_holds == 1 ) {
1234 } elsif ( $on_shelf_holds == 2 ) {
1236 Koha::Items->search( { biblionumber => $item->biblionumber } );
1238 my $any_available = 0;
1240 foreach my $i (@items) {
1241 my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1242 my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1243 my $item_library = Koha::Libraries->find( {branchcode => $i->homebranch} );
1248 || $i->notforloan > 0
1251 || IsItemOnHoldAndFound( $i->id )
1253 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1254 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1255 || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch
1256 || $branchitemrule->{holdallowed} == 3 && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} );
1259 return $any_available ? 0 : 1;
1260 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1261 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1269 if (C4::Context->preference('item-level_itypes')) {
1270 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1271 # When GetItem is fixed, we can remove this
1272 $itype = $item->{itype};
1275 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1276 # So if we already have a biblioitems join when calling this function,
1277 # we don't need to access the database again
1278 $itype = $item->{itemtype};
1281 my $dbh = C4::Context->dbh;
1282 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1283 my $sth = $dbh->prepare($query);
1284 $sth->execute($item->{biblioitemnumber});
1285 if (my $data = $sth->fetchrow_hashref()){
1286 $itype = $data->{itemtype};
1292 =head2 AlterPriority
1294 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1296 This function changes a reserve's priority up, down, to the top, or to the bottom.
1297 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1302 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1304 my $hold = Koha::Holds->find( $reserve_id );
1305 return unless $hold;
1307 if ( $hold->cancellationdate ) {
1308 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1312 if ( $where eq 'up' ) {
1313 return unless $prev_priority;
1314 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1315 } elsif ( $where eq 'down' ) {
1316 return unless $next_priority;
1317 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1318 } elsif ( $where eq 'top' ) {
1319 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1320 } elsif ( $where eq 'bottom' ) {
1321 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1324 # FIXME Should return the new priority
1327 =head2 ToggleLowestPriority
1329 ToggleLowestPriority( $borrowernumber, $biblionumber );
1331 This function sets the lowestPriority field to true if is false, and false if it is true.
1335 sub ToggleLowestPriority {
1336 my ( $reserve_id ) = @_;
1338 my $dbh = C4::Context->dbh;
1340 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1341 $sth->execute( $reserve_id );
1343 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1346 =head2 ToggleSuspend
1348 ToggleSuspend( $reserve_id );
1350 This function sets the suspend field to true if is false, and false if it is true.
1351 If the reserve is currently suspended with a suspend_until date, that date will
1352 be cleared when it is unsuspended.
1357 my ( $reserve_id, $suspend_until ) = @_;
1359 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1361 my $hold = Koha::Holds->find( $reserve_id );
1363 if ( $hold->is_suspended ) {
1366 $hold->suspend_hold( $suspend_until );
1373 borrowernumber => $borrowernumber,
1374 [ biblionumber => $biblionumber, ]
1375 [ suspend_until => $suspend_until, ]
1376 [ suspend => $suspend ]
1379 This function accepts a set of hash keys as its parameters.
1380 It requires either borrowernumber or biblionumber, or both.
1382 suspend_until is wholly optional.
1389 my $borrowernumber = $params{'borrowernumber'} || undef;
1390 my $biblionumber = $params{'biblionumber'} || undef;
1391 my $suspend_until = $params{'suspend_until'} || undef;
1392 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1394 $suspend_until = eval { dt_from_string($suspend_until) }
1395 if ( defined($suspend_until) );
1397 return unless ( $borrowernumber || $biblionumber );
1400 $params->{found} = undef;
1401 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1402 $params->{biblionumber} = $biblionumber if $biblionumber;
1404 my @holds = Koha::Holds->search($params);
1407 map { $_->suspend_hold($suspend_until) } @holds;
1410 map { $_->resume() } @holds;
1418 reserve_id => $reserve_id,
1420 [ignoreSetLowestRank => $ignoreSetLowestRank]
1425 _FixPriority({ biblionumber => $biblionumber});
1427 This routine adjusts the priority of a hold request and holds
1430 In the first form, where a reserve_id is passed, the priority of the
1431 hold is set to supplied rank, and other holds for that bib are adjusted
1432 accordingly. If the rank is "del", the hold is cancelled. If no rank
1433 is supplied, all of the holds on that bib have their priority adjusted
1434 as if the second form had been used.
1436 In the second form, where a biblionumber is passed, the holds on that
1437 bib (that are not captured) are sorted in order of increasing priority,
1438 then have reserves.priority set so that the first non-captured hold
1439 has its priority set to 1, the second non-captured hold has its priority
1440 set to 2, and so forth.
1442 In both cases, holds that have the lowestPriority flag on are have their
1443 priority adjusted to ensure that they remain at the end of the line.
1445 Note that the ignoreSetLowestRank parameter is meant to be used only
1446 when _FixPriority calls itself.
1451 my ( $params ) = @_;
1452 my $reserve_id = $params->{reserve_id};
1453 my $rank = $params->{rank} // '';
1454 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1455 my $biblionumber = $params->{biblionumber};
1457 my $dbh = C4::Context->dbh;
1460 if ( $reserve_id ) {
1461 $hold = Koha::Holds->find( $reserve_id );
1462 return unless $hold;
1465 unless ( $biblionumber ) { # FIXME This is a very weird API
1466 $biblionumber = $hold->biblionumber;
1469 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1472 elsif ( $rank eq "W" || $rank eq "0" ) {
1474 # make sure priority for waiting or in-transit items is 0
1478 WHERE reserve_id = ?
1479 AND found IN ('W', 'T')
1481 my $sth = $dbh->prepare($query);
1482 $sth->execute( $reserve_id );
1488 SELECT reserve_id, borrowernumber, reservedate
1490 WHERE biblionumber = ?
1491 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1492 ORDER BY priority ASC
1494 my $sth = $dbh->prepare($query);
1495 $sth->execute( $biblionumber );
1496 while ( my $line = $sth->fetchrow_hashref ) {
1497 push( @priority, $line );
1500 # To find the matching index
1502 my $key = -1; # to allow for 0 to be a valid result
1503 for ( $i = 0 ; $i < @priority ; $i++ ) {
1504 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1505 $key = $i; # save the index
1510 # if index exists in array then move it to new position
1511 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1512 my $new_rank = $rank -
1513 1; # $new_rank is what you want the new index to be in the array
1514 my $moving_item = splice( @priority, $key, 1 );
1515 splice( @priority, $new_rank, 0, $moving_item );
1518 # now fix the priority on those that are left....
1522 WHERE reserve_id = ?
1524 $sth = $dbh->prepare($query);
1525 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1528 $priority[$j]->{'reserve_id'}
1532 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1535 unless ( $ignoreSetLowestRank ) {
1536 while ( my $res = $sth->fetchrow_hashref() ) {
1538 reserve_id => $res->{'reserve_id'},
1540 ignoreSetLowestRank => 1
1546 =head2 _Findgroupreserve
1548 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1550 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1551 first match found. If neither, then we look for non-holds-queue based holds.
1552 Lookahead is the number of days to look in advance.
1554 C<&_Findgroupreserve> returns :
1555 C<@results> is an array of references-to-hash whose keys are mostly
1556 fields from the reserves table of the Koha database, plus
1557 C<biblioitemnumber>.
1559 This routine with either return:
1560 1 - Item specific holds from the holds queue
1561 2 - Title level holds from the holds queue
1562 3 - All holds for this biblionumber
1564 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1568 sub _Findgroupreserve {
1569 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1570 my $dbh = C4::Context->dbh;
1572 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1573 # check for exact targeted match
1574 my $item_level_target_query = qq{
1575 SELECT reserves.biblionumber AS biblionumber,
1576 reserves.borrowernumber AS borrowernumber,
1577 reserves.reservedate AS reservedate,
1578 reserves.branchcode AS branchcode,
1579 reserves.cancellationdate AS cancellationdate,
1580 reserves.found AS found,
1581 reserves.reservenotes AS reservenotes,
1582 reserves.priority AS priority,
1583 reserves.timestamp AS timestamp,
1584 biblioitems.biblioitemnumber AS biblioitemnumber,
1585 reserves.itemnumber AS itemnumber,
1586 reserves.reserve_id AS reserve_id,
1587 reserves.itemtype AS itemtype
1589 JOIN biblioitems USING (biblionumber)
1590 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1593 AND item_level_request = 1
1595 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1599 my $sth = $dbh->prepare($item_level_target_query);
1600 $sth->execute($itemnumber, $lookahead||0);
1602 if ( my $data = $sth->fetchrow_hashref ) {
1603 push( @results, $data )
1604 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1606 return @results if @results;
1608 # check for title-level targeted match
1609 my $title_level_target_query = qq{
1610 SELECT reserves.biblionumber AS biblionumber,
1611 reserves.borrowernumber AS borrowernumber,
1612 reserves.reservedate AS reservedate,
1613 reserves.branchcode AS branchcode,
1614 reserves.cancellationdate AS cancellationdate,
1615 reserves.found AS found,
1616 reserves.reservenotes AS reservenotes,
1617 reserves.priority AS priority,
1618 reserves.timestamp AS timestamp,
1619 biblioitems.biblioitemnumber AS biblioitemnumber,
1620 reserves.itemnumber AS itemnumber,
1621 reserves.reserve_id AS reserve_id,
1622 reserves.itemtype AS itemtype
1624 JOIN biblioitems USING (biblionumber)
1625 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1628 AND item_level_request = 0
1629 AND hold_fill_targets.itemnumber = ?
1630 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1634 $sth = $dbh->prepare($title_level_target_query);
1635 $sth->execute($itemnumber, $lookahead||0);
1637 if ( my $data = $sth->fetchrow_hashref ) {
1638 push( @results, $data )
1639 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1641 return @results if @results;
1644 SELECT reserves.biblionumber AS biblionumber,
1645 reserves.borrowernumber AS borrowernumber,
1646 reserves.reservedate AS reservedate,
1647 reserves.waitingdate AS waitingdate,
1648 reserves.branchcode AS branchcode,
1649 reserves.cancellationdate AS cancellationdate,
1650 reserves.found AS found,
1651 reserves.reservenotes AS reservenotes,
1652 reserves.priority AS priority,
1653 reserves.timestamp AS timestamp,
1654 reserves.itemnumber AS itemnumber,
1655 reserves.reserve_id AS reserve_id,
1656 reserves.itemtype AS itemtype
1658 WHERE reserves.biblionumber = ?
1659 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1660 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1664 $sth = $dbh->prepare($query);
1665 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1667 while ( my $data = $sth->fetchrow_hashref ) {
1668 push( @results, $data )
1669 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1674 =head2 _koha_notify_reserve
1676 _koha_notify_reserve( $hold->reserve_id );
1678 Sends a notification to the patron that their hold has been filled (through
1679 ModReserveAffect, _not_ ModReserveFill)
1681 The letter code for this notice may be found using the following query:
1683 select distinct letter_code
1684 from message_transports
1685 inner join message_attributes using (message_attribute_id)
1686 where message_name = 'Hold_Filled'
1688 This will probably sipmly be 'HOLD', but because it is defined in the database,
1689 it is subject to addition or change.
1691 The following tables are availalbe witin the notice:
1702 sub _koha_notify_reserve {
1703 my $reserve_id = shift;
1704 my $hold = Koha::Holds->find($reserve_id);
1705 my $borrowernumber = $hold->borrowernumber;
1707 my $patron = Koha::Patrons->find( $borrowernumber );
1709 # Try to get the borrower's email address
1710 my $to_address = $patron->notice_email_address;
1712 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1713 borrowernumber => $borrowernumber,
1714 message_name => 'Hold_Filled'
1717 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1719 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1721 my %letter_params = (
1722 module => 'reserves',
1723 branchcode => $hold->branchcode,
1724 lang => $patron->lang,
1726 'branches' => $library,
1727 'borrowers' => $patron->unblessed,
1728 'biblio' => $hold->biblionumber,
1729 'biblioitems' => $hold->biblionumber,
1730 'reserves' => $hold->unblessed,
1731 'items' => $hold->itemnumber,
1735 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.
1736 my $send_notification = sub {
1737 my ( $mtt, $letter_code ) = (@_);
1738 return unless defined $letter_code;
1739 $letter_params{letter_code} = $letter_code;
1740 $letter_params{message_transport_type} = $mtt;
1741 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1743 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1747 C4::Letters::EnqueueLetter( {
1749 borrowernumber => $borrowernumber,
1750 from_address => $admin_email_address,
1751 message_transport_type => $mtt,
1755 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1757 ( $mtt eq 'email' and not $to_address ) # No email address
1758 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1759 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1762 &$send_notification($mtt, $letter_code);
1763 $notification_sent++;
1765 #Making sure that a print notification is sent if no other transport types can be utilized.
1766 if (! $notification_sent) {
1767 &$send_notification('print', 'HOLD');
1772 =head2 _ShiftPriorityByDateAndPriority
1774 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1776 This increments the priority of all reserves after the one
1777 with either the lowest date after C<$reservedate>
1778 or the lowest priority after C<$priority>.
1780 It effectively makes room for a new reserve to be inserted with a certain
1781 priority, which is returned.
1783 This is most useful when the reservedate can be set by the user. It allows
1784 the new reserve to be placed before other reserves that have a later
1785 reservedate. Since priority also is set by the form in reserves/request.pl
1786 the sub accounts for that too.
1790 sub _ShiftPriorityByDateAndPriority {
1791 my ( $biblio, $resdate, $new_priority ) = @_;
1793 my $dbh = C4::Context->dbh;
1794 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1795 my $sth = $dbh->prepare( $query );
1796 $sth->execute( $biblio, $resdate, $new_priority );
1797 my $min_priority = $sth->fetchrow;
1798 # if no such matches are found, $new_priority remains as original value
1799 $new_priority = $min_priority if ( $min_priority );
1801 # Shift the priority up by one; works in conjunction with the next SQL statement
1802 $query = "UPDATE reserves
1803 SET priority = priority+1
1804 WHERE biblionumber = ?
1805 AND borrowernumber = ?
1808 my $sth_update = $dbh->prepare( $query );
1810 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1811 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1812 $sth = $dbh->prepare( $query );
1813 $sth->execute( $new_priority, $biblio );
1814 while ( my $row = $sth->fetchrow_hashref ) {
1815 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1818 return $new_priority; # so the caller knows what priority they wind up receiving
1823 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1825 Use when checking out an item to handle reserves
1826 If $cancelreserve boolean is set to true, it will remove existing reserve
1831 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1833 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1834 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1837 my $biblionumber = $res->{biblionumber};
1839 if ($res->{borrowernumber} == $borrowernumber) {
1840 ModReserveFill($res);
1844 # The item is reserved by someone else.
1845 # Find this item in the reserves
1847 my $borr_res = Koha::Holds->search({
1848 borrowernumber => $borrowernumber,
1849 biblionumber => $biblionumber,
1851 order_by => 'priority'
1855 # The item is reserved by the current patron
1856 ModReserveFill($borr_res->unblessed);
1859 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1860 RevertWaitingStatus({ itemnumber => $itemnumber });
1862 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1863 my $hold = Koha::Holds->find( $res->{reserve_id} );
1871 MergeHolds($dbh,$to_biblio, $from_biblio);
1873 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1878 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1879 my $sth = $dbh->prepare(
1880 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1882 $sth->execute($from_biblio);
1883 if ( my $data = $sth->fetchrow_hashref() ) {
1885 # holds exist on old record, if not we don't need to do anything
1886 $sth = $dbh->prepare(
1887 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1888 $sth->execute( $to_biblio, $from_biblio );
1891 # don't reorder those already waiting
1893 $sth = $dbh->prepare(
1894 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1896 my $upd_sth = $dbh->prepare(
1897 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1898 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1900 $sth->execute( $to_biblio, 'W', 'T' );
1902 while ( my $reserve = $sth->fetchrow_hashref() ) {
1904 $priority, $to_biblio,
1905 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1906 $reserve->{'itemnumber'}
1913 =head2 RevertWaitingStatus
1915 RevertWaitingStatus({ itemnumber => $itemnumber });
1917 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1919 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1920 item level hold, even if it was only a bibliolevel hold to
1921 begin with. This is because we can no longer know if a hold
1922 was item-level or bib-level after a hold has been set to
1927 sub RevertWaitingStatus {
1928 my ( $params ) = @_;
1929 my $itemnumber = $params->{'itemnumber'};
1931 return unless ( $itemnumber );
1933 my $dbh = C4::Context->dbh;
1935 ## Get the waiting reserve we want to revert
1937 SELECT * FROM reserves
1938 WHERE itemnumber = ?
1939 AND found IS NOT NULL
1941 my $sth = $dbh->prepare( $query );
1942 $sth->execute( $itemnumber );
1943 my $reserve = $sth->fetchrow_hashref();
1945 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1947 ## Increment the priority of all other non-waiting
1948 ## reserves for this bib record
1952 priority = priority + 1
1958 $sth = $dbh->prepare( $query );
1959 $sth->execute( $reserve->{'biblionumber'} );
1961 ## Fix up the currently waiting reserve
1971 $sth = $dbh->prepare( $query );
1972 $sth->execute( $reserve->{'reserve_id'} );
1974 unless ( $hold->item_level_hold ) {
1975 $hold->itemnumber(undef)->store;
1978 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1985 branchcode => $branchcode,
1986 borrowernumber => $borrowernumber,
1987 biblionumber => $biblionumber,
1988 [ itemnumber => $itemnumber, ]
1989 [ barcode => $barcode, ]
1993 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1995 The letter code will be HOLD_SLIP, and the following tables are
1996 available within the slip:
2009 my $branchcode = $args->{branchcode};
2010 my $borrowernumber = $args->{borrowernumber};
2011 my $biblionumber = $args->{biblionumber};
2012 my $itemnumber = $args->{itemnumber};
2013 my $barcode = $args->{barcode};
2016 my $patron = Koha::Patrons->find($borrowernumber);
2019 if ($itemnumber || $barcode ) {
2020 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2022 $hold = Koha::Holds->search(
2024 biblionumber => $biblionumber,
2025 borrowernumber => $borrowernumber,
2026 itemnumber => $itemnumber
2031 $hold = Koha::Holds->search(
2033 biblionumber => $biblionumber,
2034 borrowernumber => $borrowernumber
2039 return unless $hold;
2040 my $reserve = $hold->unblessed;
2042 return C4::Letters::GetPreparedLetter (
2043 module => 'circulation',
2044 letter_code => 'HOLD_SLIP',
2045 branchcode => $branchcode,
2046 lang => $patron->lang,
2048 'reserves' => $reserve,
2049 'branches' => $reserve->{branchcode},
2050 'borrowers' => $reserve->{borrowernumber},
2051 'biblio' => $reserve->{biblionumber},
2052 'biblioitems' => $reserve->{biblionumber},
2053 'items' => $reserve->{itemnumber},
2058 =head2 GetReservesControlBranch
2060 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2062 Return the branchcode to be used to determine which reserves
2063 policy applies to a transaction.
2065 C<$item> is a hashref for an item. Only 'homebranch' is used.
2067 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2071 sub GetReservesControlBranch {
2072 my ( $item, $borrower ) = @_;
2074 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2077 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2078 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2084 =head2 CalculatePriority
2086 my $p = CalculatePriority($biblionumber, $resdate);
2088 Calculate priority for a new reserve on biblionumber, placing it at
2089 the end of the line of all holds whose start date falls before
2090 the current system time and that are neither on the hold shelf
2093 The reserve date parameter is optional; if it is supplied, the
2094 priority is based on the set of holds whose start date falls before
2095 the parameter value.
2097 After calculation of this priority, it is recommended to call
2098 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2103 sub CalculatePriority {
2104 my ( $biblionumber, $resdate ) = @_;
2107 SELECT COUNT(*) FROM reserves
2108 WHERE biblionumber = ?
2110 AND (found IS NULL OR found = '')
2112 #skip found==W or found==T (waiting or transit holds)
2114 $sql.= ' AND ( reservedate <= ? )';
2117 $sql.= ' AND ( reservedate < NOW() )';
2119 my $dbh = C4::Context->dbh();
2120 my @row = $dbh->selectrow_array(
2123 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2126 return @row ? $row[0]+1 : 1;
2129 =head2 IsItemOnHoldAndFound
2131 my $bool = IsItemFoundHold( $itemnumber );
2133 Returns true if the item is currently on hold
2134 and that hold has a non-null found status ( W, T, etc. )
2138 sub IsItemOnHoldAndFound {
2139 my ($itemnumber) = @_;
2141 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2143 my $found = $rs->count(
2145 itemnumber => $itemnumber,
2146 found => { '!=' => undef }
2153 =head2 GetMaxPatronHoldsForRecord
2155 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2157 For multiple holds on a given record for a given patron, the max
2158 number of record level holds that a patron can be placed is the highest
2159 value of the holds_per_record rule for each item if the record for that
2160 patron. This subroutine finds and returns the highest holds_per_record
2161 rule value for a given patron id and record id.
2165 sub GetMaxPatronHoldsForRecord {
2166 my ( $borrowernumber, $biblionumber ) = @_;
2168 my $patron = Koha::Patrons->find($borrowernumber);
2169 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2171 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2173 my $categorycode = $patron->categorycode;
2175 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2178 foreach my $item (@items) {
2179 my $itemtype = $item->effective_itemtype();
2181 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2183 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2184 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2185 $max = $holds_per_record if $holds_per_record > $max;
2193 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2195 Returns the matching hold related issuingrule fields for a given
2196 patron category, itemtype, and library.
2201 my ( $categorycode, $itemtype, $branchcode ) = @_;
2203 my $dbh = C4::Context->dbh;
2205 my $sth = $dbh->prepare(
2207 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2209 WHERE (categorycode in (?,'*') )
2210 AND (itemtype IN (?,'*'))
2211 AND (branchcode IN (?,'*'))
2212 ORDER BY categorycode DESC,
2218 $sth->execute( $categorycode, $itemtype, $branchcode );
2220 return $sth->fetchrow_hashref();
2225 Koha Development Team <http://koha-community.org/>