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;
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 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
77 by librarian before notice is send and status changed to waiting.
78 Applicable only if HoldsNeedProcessingSIP system preference is set.
79 - itemnumber : empty : the reserve is still unaffected to an item
80 filled: the reserve is attached to an item
81 The complete workflow is :
82 ==== 1st use case ====
83 patron request a document, 1st available : P >0, F=NULL, I=NULL
84 a library having it run "transfertodo", and clic on the list
85 if there is no transfer to do, the reserve waiting
86 patron can pick it up P =0, F=W, I=filled
87 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
88 The pickup library receive the book, it check in P =0, F=W, I=filled
89 The patron borrow the book P =0, F=F, I=filled
91 ==== 2nd use case ====
92 patron requests a document, a given item,
93 If pickup is holding branch P =0, F=W, I=filled
94 If transfer needed, write in branchtransfer P =0, F=T, I=filled
95 The pickup library receive the book, it checks it in P =0, F=W, I=filled
96 The patron borrow the book P =0, F=F, I=filled
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
129 ItemsAnyAvailableAndNotRestricted
132 &ToggleLowestPriority
138 &GetReservesControlBranch
142 GetMaxPatronHoldsForRecord
144 @EXPORT_OK = qw( MergeHolds );
151 branchcode => $branchcode,
152 borrowernumber => $borrowernumber,
153 biblionumber => $biblionumber,
154 priority => $priority,
155 reservation_date => $reservation_date,
156 expiration_date => $expiration_date,
159 itemnumber => $itemnumber,
161 itemtype => $itemtype,
165 Adds reserve and generates HOLDPLACED message.
167 The following tables are available witin the HOLDPLACED message:
180 my $branch = $params->{branchcode};
181 my $borrowernumber = $params->{borrowernumber};
182 my $biblionumber = $params->{biblionumber};
183 my $priority = $params->{priority};
184 my $resdate = $params->{reservation_date};
185 my $expdate = $params->{expiration_date};
186 my $notes = $params->{notes};
187 my $title = $params->{title};
188 my $checkitem = $params->{itemnumber};
189 my $found = $params->{found};
190 my $itemtype = $params->{itemtype};
191 my $non_priority = $params->{non_priority};
193 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
194 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
196 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
198 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
199 # of the document, we force the value $priority and $found .
200 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
201 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
204 # If item is already checked out, it cannot be set waiting
207 # The item can't be waiting if it needs a transfer
208 && $item->holdingbranch eq $branch
210 # Similarly, if in transit it can't be waiting
211 && !$item->get_transfer
213 # If we can't hold damaged items, and it is damaged, it can't be waiting
214 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
216 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
217 && !$item->current_holds->count )
224 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
226 # Make room in reserves for this before those of a later reserve date
227 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
232 # If the reserv had the waiting status, we had the value of the resdate
233 if ( $found && $found eq 'W' ) {
234 $waitingdate = $resdate;
237 # Don't add itemtype limit if specific item is selected
238 $itemtype = undef if $checkitem;
240 # updates take place here
241 my $hold = Koha::Hold->new(
243 borrowernumber => $borrowernumber,
244 biblionumber => $biblionumber,
245 reservedate => $resdate,
246 branchcode => $branch,
247 priority => $priority,
248 reservenotes => $notes,
249 itemnumber => $checkitem,
251 waitingdate => $waitingdate,
252 expirationdate => $expdate,
253 itemtype => $itemtype,
254 item_level_hold => $checkitem ? 1 : 0,
255 non_priority => $non_priority ? 1 : 0,
258 $hold->set_waiting() if $found && $found eq 'W';
260 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
261 if C4::Context->preference('HoldsLog');
263 my $reserve_id = $hold->id();
265 # add a reserve fee if needed
266 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
267 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
268 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
271 _FixPriority({ biblionumber => $biblionumber});
273 # Send e-mail to librarian if syspref is active
274 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
275 my $patron = Koha::Patrons->find( $borrowernumber );
276 my $library = $patron->library;
277 if ( my $letter = C4::Letters::GetPreparedLetter (
278 module => 'reserves',
279 letter_code => 'HOLDPLACED',
280 branchcode => $branch,
281 lang => $patron->lang,
283 'branches' => $library->unblessed,
284 'borrowers' => $patron->unblessed,
285 'biblio' => $biblionumber,
286 'biblioitems' => $biblionumber,
287 'items' => $checkitem,
288 'reserves' => $hold->unblessed,
292 my $branch_email_address = $library->inbound_email_address;
294 C4::Letters::EnqueueLetter(
297 borrowernumber => $borrowernumber,
298 message_transport_type => 'email',
299 to_address => $branch_email_address,
305 Koha::Plugins->call('after_hold_create', $hold);
310 =head2 CanBookBeReserved
312 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
313 if ($canReserve eq 'OK') { #We can reserve this Item! }
315 $params are passed directly through to CanItemBeReserved
317 See CanItemBeReserved() for possible return values.
321 sub CanBookBeReserved{
322 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
324 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
325 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
326 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
327 return { status =>'alreadypossession' };
330 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
331 #get items linked via host records
332 my @hostitems = get_hostitemnumbers_of($biblionumber);
334 push (@itemnumbers, @hostitems);
337 my $canReserve = { status => '' };
338 foreach my $itemnumber (@itemnumbers) {
339 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
340 return { status => 'OK' } if $canReserve->{status} eq 'OK';
345 =head2 CanItemBeReserved
347 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
348 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
351 'ignore_found_holds' - if true holds that have been trapped are not counted
352 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
353 current checkout against the high holds threshold
354 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
355 should not check if there are too many holds as we only csre about reservability
357 @RETURNS { status => OK }, if the Item can be reserved.
358 { status => ageRestricted }, if the Item is age restricted for this borrower.
359 { status => damaged }, if the Item is damaged.
360 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
361 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
362 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
363 { status => notReservable }, if holds on this item are not allowed
364 { status => libraryNotFound }, if given branchcode is not an existing library
365 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
366 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
367 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
371 sub CanItemBeReserved {
372 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
374 my $dbh = C4::Context->dbh;
375 my $ruleitemtype; # itemtype of the matching issuing rule
376 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
378 # we retrieve borrowers and items informations #
379 # item->{itype} will come for biblioitems if necessery
380 my $item = Koha::Items->find($itemnumber);
381 my $biblio = $item->biblio;
382 my $patron = Koha::Patrons->find( $borrowernumber );
383 my $borrower = $patron->unblessed;
385 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
386 return { status =>'damaged' }
388 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
390 # Check for the age restriction
391 my ( $ageRestriction, $daysToAgeRestriction ) =
392 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
393 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
395 # Check that the patron doesn't have an item level hold on this item already
396 return { status =>'itemAlreadyOnHold' }
397 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
399 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
400 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
401 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
402 return { status =>'alreadypossession' };
405 my $controlbranch = C4::Context->preference('ReservesControlBranch');
408 SELECT count(*) AS count
410 LEFT JOIN items USING (itemnumber)
411 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
412 LEFT JOIN borrowers USING (borrowernumber)
413 WHERE borrowernumber = ?
417 my $branchfield = "reserves.branchcode";
419 if ( $controlbranch eq "ItemHomeLibrary" ) {
420 $branchfield = "items.homebranch";
421 $branchcode = $item->homebranch;
423 elsif ( $controlbranch eq "PatronLibrary" ) {
424 $branchfield = "borrowers.branchcode";
425 $branchcode = $borrower->{branchcode};
430 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
431 itemtype => $item->effective_itemtype,
432 categorycode => $borrower->{categorycode},
433 branchcode => $branchcode,
434 rule_name => 'reservesallowed',
437 $ruleitemtype = $reservesallowed->itemtype;
438 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
441 $ruleitemtype = undef;
444 my $rights = Koha::CirculationRules->get_effective_rules({
445 categorycode => $borrower->{'categorycode'},
446 itemtype => $item->effective_itemtype,
447 branchcode => $branchcode,
448 rules => ['holds_per_record','holds_per_day']
450 my $holds_per_record = $rights->{holds_per_record} // 1;
451 my $holds_per_day = $rights->{holds_per_day};
453 my $search_params = {
454 borrowernumber => $borrowernumber,
455 biblionumber => $item->biblionumber,
457 $search_params->{found} = undef if $params->{ignore_found_holds};
459 my $holds = Koha::Holds->search($search_params);
460 if (!$params->{ignore_hold_counts} && defined $holds_per_record && $holds_per_record ne ''
461 && $holds->count() >= $holds_per_record ) {
462 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
465 my $today_holds = Koha::Holds->search({
466 borrowernumber => $borrowernumber,
467 reservedate => dt_from_string->date
470 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne ''
471 && $today_holds->count() >= $holds_per_day )
473 return { status => 'tooManyReservesToday', limit => $holds_per_day };
478 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
480 # If using item-level itypes, fall back to the record
481 # level itemtype if the hold has no associated item
483 C4::Context->preference('item-level_itypes')
484 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
485 : " AND biblioitems.itemtype = ?"
486 if defined $ruleitemtype;
488 my $sthcount = $dbh->prepare($querycount);
490 if ( defined $ruleitemtype ) {
491 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
494 $sthcount->execute( $borrowernumber, $branchcode );
497 my $reservecount = "0";
498 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
499 $reservecount = $rowcount->{count};
502 # we check if it's ok or not
503 if ( defined $allowedreserves && $allowedreserves ne ''
504 && $reservecount >= $allowedreserves && (!$params->{ignore_hold_counts} || $allowedreserves == 0 ) ) {
505 return { status => 'tooManyReserves', limit => $allowedreserves };
508 # Now we need to check hold limits by patron category
509 my $rule = Koha::CirculationRules->get_effective_rule(
511 categorycode => $borrower->{categorycode},
512 branchcode => $branchcode,
513 rule_name => 'max_holds',
516 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
517 my $total_holds_count = Koha::Holds->search(
519 borrowernumber => $borrower->{borrowernumber}
523 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
526 my $reserves_control_branch =
527 GetReservesControlBranch( $item->unblessed(), $borrower );
529 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
531 if ( $branchitemrule->{holdallowed} == 0 ) {
532 return { status => 'notReservable' };
535 if ( $branchitemrule->{holdallowed} == 1
536 && $borrower->{branchcode} ne $item->homebranch )
538 return { status => 'cannotReserveFromOtherBranches' };
541 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
542 if ( $branchitemrule->{holdallowed} == 3) {
543 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
544 return { status => 'branchNotInHoldGroup' };
548 # If reservecount is ok, we check item branch if IndependentBranches is ON
549 # and canreservefromotherbranches is OFF
550 if ( C4::Context->preference('IndependentBranches')
551 and !C4::Context->preference('canreservefromotherbranches') )
553 if ( $item->homebranch ne $borrower->{branchcode} ) {
554 return { status => 'cannotReserveFromOtherBranches' };
558 if ($pickup_branchcode) {
559 my $destination = Koha::Libraries->find({
560 branchcode => $pickup_branchcode,
563 unless ($destination) {
564 return { status => 'libraryNotFound' };
566 unless ($destination->pickup_location) {
567 return { status => 'libraryNotPickupLocation' };
569 unless ($item->can_be_transferred({ to => $destination })) {
570 return { status => 'cannotBeTransferred' };
572 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
573 return { status => 'pickupNotInHoldGroup' };
575 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
576 return { status => 'pickupNotInHoldGroup' };
580 return { status => 'OK' };
583 =head2 CanReserveBeCanceledFromOpac
585 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
587 returns 1 if reserve can be cancelled by user from OPAC.
588 First check if reserve belongs to user, next checks if reserve is not in
589 transfer or waiting status
593 sub CanReserveBeCanceledFromOpac {
594 my ($reserve_id, $borrowernumber) = @_;
596 return unless $reserve_id and $borrowernumber;
597 my $reserve = Koha::Holds->find($reserve_id);
599 return 0 unless $reserve->borrowernumber == $borrowernumber;
600 return $reserve->is_cancelable_from_opac;
603 =head2 GetOtherReserves
605 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
607 Check queued list of this document and check if this document must be transferred
611 sub GetOtherReserves {
612 my ($itemnumber) = @_;
615 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
616 if ($checkreserves) {
617 my $item = Koha::Items->find($itemnumber);
618 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
619 $messages->{'transfert'} = $checkreserves->{'branchcode'};
620 #minus priorities of others reservs
621 ModReserveMinusPriority(
623 $checkreserves->{'reserve_id'},
626 #launch the subroutine dotransfer
627 C4::Items::ModItemTransfer(
629 $item->holdingbranch,
630 $checkreserves->{'branchcode'},
636 #step 2b : case of a reservation on the same branch, set the waiting status
638 $messages->{'waiting'} = 1;
639 ModReserveMinusPriority(
641 $checkreserves->{'reserve_id'},
643 ModReserveStatus($itemnumber,'W');
646 $nextreservinfo = $checkreserves;
649 return ( $messages, $nextreservinfo );
652 =head2 ChargeReserveFee
654 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
656 Charge the fee for a reserve (if $fee > 0)
660 sub ChargeReserveFee {
661 my ( $borrowernumber, $fee, $title ) = @_;
662 return if !$fee || $fee == 0; # the last test is needed to include 0.00
663 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
666 description => $title,
668 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
669 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
670 interface => C4::Context->interface,
671 invoice_type => undef,
680 $fee = GetReserveFee( $borrowernumber, $biblionumber );
682 Calculate the fee for a reserve (if applicable).
687 my ( $borrowernumber, $biblionumber ) = @_;
689 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
692 SELECT COUNT(*) FROM items
693 LEFT JOIN issues USING (itemnumber)
694 WHERE items.biblionumber=? AND issues.issue_id IS NULL
697 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
700 my $dbh = C4::Context->dbh;
701 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
702 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
703 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
704 # This is a reconstruction of the old code:
705 # Compare number of items with items issued, and optionally check holds
706 # If not all items are issued and there are no holds: charge no fee
707 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
708 my ( $notissued, $reserved );
709 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
712 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
713 ( $biblionumber, $borrowernumber ) );
714 $fee = 0 if $reserved == 0;
720 =head2 GetReserveStatus
722 $reservestatus = GetReserveStatus($itemnumber);
724 Takes an itemnumber and returns the status of the reserve placed on it.
725 If several reserves exist, the reserve with the lower priority is given.
729 ## FIXME: I don't think this does what it thinks it does.
730 ## It only ever checks the first reserve result, even though
731 ## multiple reserves for that bib can have the itemnumber set
732 ## the sub is only used once in the codebase.
733 sub GetReserveStatus {
734 my ($itemnumber) = @_;
736 my $dbh = C4::Context->dbh;
738 my ($sth, $found, $priority);
740 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
741 $sth->execute($itemnumber);
742 ($found, $priority) = $sth->fetchrow_array;
746 return 'Waiting' if $found eq 'W' and $priority == 0;
747 return 'Processing' if $found eq 'P';
748 return 'Finished' if $found eq 'F';
751 return 'Reserved' if defined $priority && $priority > 0;
753 return ''; # empty string here will remove need for checking undef, or less log lines
758 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
759 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
760 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
762 Find a book in the reserves.
764 C<$itemnumber> is the book's item number.
765 C<$lookahead> is the number of days to look in advance for future reserves.
767 As I understand it, C<&CheckReserves> looks for the given item in the
768 reserves. If it is found, that's a match, and C<$status> is set to
771 Otherwise, it finds the most important item in the reserves with the
772 same biblio number as this book (I'm not clear on this) and returns it
773 with C<$status> set to C<Reserved>.
775 C<&CheckReserves> returns a two-element list:
777 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
779 C<$reserve> is the reserve item that matched. It is a
780 reference-to-hash whose keys are mostly the fields of the reserves
781 table in the Koha database.
786 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
787 my $dbh = C4::Context->dbh;
790 if (C4::Context->preference('item-level_itypes')){
792 SELECT items.biblionumber,
793 items.biblioitemnumber,
794 itemtypes.notforloan,
795 items.notforloan AS itemnotforloan,
801 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
802 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
807 SELECT items.biblionumber,
808 items.biblioitemnumber,
809 itemtypes.notforloan,
810 items.notforloan AS itemnotforloan,
816 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
817 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
822 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
823 $sth->execute($item);
826 $sth = $dbh->prepare("$select WHERE barcode = ?");
827 $sth->execute($barcode);
829 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
830 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
831 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
833 return unless $itemnumber; # bail if we got nothing.
834 # if item is not for loan it cannot be reserved either.....
835 # except where items.notforloan < 0 : This indicates the item is holdable.
837 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
838 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
840 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
841 return if $dont_trap or $notforloan_per_itemtype;
843 # Find this item in the reserves
844 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
846 # $priority and $highest are used to find the most important item
847 # in the list returned by &_Findgroupreserve. (The lower $priority,
848 # the more important the item.)
849 # $highest is the most important item we've seen so far.
852 if (scalar @reserves) {
853 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
854 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
855 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
857 my $priority = 10000000;
858 foreach my $res (@reserves) {
859 if ($res->{'found'} && $res->{'found'} eq 'W') {
860 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
861 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
862 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
863 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
864 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
868 my $local_hold_match;
870 if ($LocalHoldsPriority) {
871 $patron = Koha::Patrons->find( $res->{borrowernumber} );
872 $item = Koha::Items->find($itemnumber);
874 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
875 my $local_holds_priority_item_branchcode =
876 $item->$LocalHoldsPriorityItemControl;
877 my $local_holds_priority_patron_branchcode =
878 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
880 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
881 ? $patron->branchcode
884 $local_holds_priority_item_branchcode eq
885 $local_holds_priority_patron_branchcode;
889 # See if this item is more important than what we've got so far
890 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
891 $item ||= Koha::Items->find($itemnumber);
892 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
893 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
894 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
895 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
896 next if ($branchitemrule->{'holdallowed'} == 0);
897 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
898 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
899 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
900 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
901 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
902 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
903 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
904 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
905 $priority = $res->{'priority'};
907 last if $local_hold_match;
913 # If we get this far, then no exact match was found.
914 # We return the most important (i.e. next) reservation.
916 $highest->{'itemnumber'} = $item;
917 return ( "Reserved", $highest, \@reserves );
923 =head2 CancelExpiredReserves
925 CancelExpiredReserves();
927 Cancels all reserves with an expiration date from before today.
931 sub CancelExpiredReserves {
932 my $cancellation_reason = shift;
933 my $today = dt_from_string();
934 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
935 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
937 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
938 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
939 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
941 # FIXME To move to Koha::Holds->search_expired (?)
942 my $holds = Koha::Holds->search( $params );
944 while ( my $hold = $holds->next ) {
945 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
947 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
949 my $cancel_params = {};
950 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
951 if ( defined($hold->found) && $hold->found eq 'W' ) {
952 $cancel_params->{charge_cancel_fee} = 1;
954 $hold->cancel( $cancel_params );
958 =head2 AutoUnsuspendReserves
960 AutoUnsuspendReserves();
962 Unsuspends all suspended reserves with a suspend_until date from before today.
966 sub AutoUnsuspendReserves {
967 my $today = dt_from_string();
969 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
971 map { $_->resume() } @holds;
976 ModReserve({ rank => $rank,
977 reserve_id => $reserve_id,
978 branchcode => $branchcode
979 [, itemnumber => $itemnumber ]
980 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
983 Change a hold request's priority or cancel it.
985 C<$rank> specifies the effect of the change. If C<$rank>
986 is 'W' or 'n', nothing happens. This corresponds to leaving a
987 request alone when changing its priority in the holds queue
990 If C<$rank> is 'del', the hold request is cancelled.
992 If C<$rank> is an integer greater than zero, the priority of
993 the request is set to that value. Since priority != 0 means
994 that the item is not waiting on the hold shelf, setting the
995 priority to a non-zero value also sets the request's found
996 status and waiting date to NULL.
998 The optional C<$itemnumber> parameter is used only when
999 C<$rank> is a non-zero integer; if supplied, the itemnumber
1000 of the hold request is set accordingly; if omitted, the itemnumber
1003 B<FIXME:> Note that the forgoing can have the effect of causing
1004 item-level hold requests to turn into title-level requests. This
1005 will be fixed once reserves has separate columns for requested
1006 itemnumber and supplying itemnumber.
1011 my ( $params ) = @_;
1013 my $rank = $params->{'rank'};
1014 my $reserve_id = $params->{'reserve_id'};
1015 my $branchcode = $params->{'branchcode'};
1016 my $itemnumber = $params->{'itemnumber'};
1017 my $suspend_until = $params->{'suspend_until'};
1018 my $borrowernumber = $params->{'borrowernumber'};
1019 my $biblionumber = $params->{'biblionumber'};
1020 my $cancellation_reason = $params->{'cancellation_reason'};
1022 return if $rank eq "W";
1023 return if $rank eq "n";
1025 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1028 unless ( $reserve_id ) {
1029 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1030 return unless $holds->count; # FIXME Should raise an exception
1031 $hold = $holds->next;
1032 $reserve_id = $hold->reserve_id;
1035 $hold ||= Koha::Holds->find($reserve_id);
1037 if ( $rank eq "del" ) {
1038 $hold->cancel({ cancellation_reason => $cancellation_reason });
1040 elsif ($rank =~ /^\d+/ and $rank > 0) {
1041 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1042 if C4::Context->preference('HoldsLog');
1046 branchcode => $branchcode,
1047 itemnumber => $itemnumber,
1049 waitingdate => undef
1051 if (exists $params->{reservedate}) {
1052 $properties->{reservedate} = $params->{reservedate} || undef;
1054 if (exists $params->{expirationdate}) {
1055 $properties->{expirationdate} = $params->{expirationdate} || undef;
1058 $hold->set($properties)->store();
1060 if ( defined( $suspend_until ) ) {
1061 if ( $suspend_until ) {
1062 $suspend_until = eval { dt_from_string( $suspend_until ) };
1063 $hold->suspend_hold( $suspend_until );
1065 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1066 # If the hold is not suspended, this does nothing.
1067 $hold->set( { suspend_until => undef } )->store();
1071 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1075 =head2 ModReserveFill
1077 &ModReserveFill($reserve);
1079 Fill a reserve. If I understand this correctly, this means that the
1080 reserved book has been found and given to the patron who reserved it.
1082 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1083 whose keys are fields from the reserves table in the Koha database.
1087 sub ModReserveFill {
1089 my $reserve_id = $res->{'reserve_id'};
1091 my $hold = Koha::Holds->find($reserve_id);
1092 # get the priority on this record....
1093 my $priority = $hold->priority;
1095 # update the hold statuses, no need to store it though, we will be deleting it anyway
1103 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1104 if C4::Context->preference('HoldsLog');
1106 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1107 Koha::Old::Hold->new( $hold->unblessed() )->store();
1111 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1112 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1113 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1116 # now fix the priority on the others (if the priority wasn't
1117 # already sorted!)....
1118 unless ( $priority == 0 ) {
1119 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1123 =head2 ModReserveStatus
1125 &ModReserveStatus($itemnumber, $newstatus);
1127 Update the reserve status for the active (priority=0) reserve.
1129 $itemnumber is the itemnumber the reserve is on
1131 $newstatus is the new status.
1135 sub ModReserveStatus {
1137 #first : check if we have a reservation for this item .
1138 my ($itemnumber, $newstatus) = @_;
1139 my $dbh = C4::Context->dbh;
1141 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1142 my $sth_set = $dbh->prepare($query);
1143 $sth_set->execute( $newstatus, $itemnumber );
1145 my $item = Koha::Items->find($itemnumber);
1146 if ( $item->location && $item->location eq 'CART'
1147 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1149 CartToShelf( $itemnumber );
1153 =head2 ModReserveAffect
1155 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1157 This function affect an item and a status for a given reserve, either fetched directly
1158 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1159 is given, only first reserve returned is affected, which is ok for anything but
1162 if $transferToDo is not set, then the status is set to "Waiting" as well.
1163 otherwise, a transfer is on the way, and the end of the transfer will
1164 take care of the waiting status
1166 This function also removes any entry of the hold in holds queue table.
1170 sub ModReserveAffect {
1171 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1172 my $dbh = C4::Context->dbh;
1174 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1175 # attached to $itemnumber
1176 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1177 $sth->execute($itemnumber);
1178 my ($biblionumber) = $sth->fetchrow;
1180 # get request - need to find out if item is already
1181 # waiting in order to not send duplicate hold filled notifications
1184 # Find hold by id if we have it
1185 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1186 # Find item level hold for this item if there is one
1187 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1188 # Find record level hold if there is no item level hold
1189 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1191 return unless $hold;
1193 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1195 $hold->itemnumber($itemnumber);
1197 if ($transferToDo) {
1198 $hold->set_transfer();
1199 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1200 && C4::Context->interface eq 'sip'
1201 && !$already_on_shelf) {
1202 $hold->set_processing();
1204 $hold->set_waiting($desk_id);
1205 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1206 my $transfers = Koha::Item::Transfers->search({
1207 itemnumber => $itemnumber,
1208 datearrived => undef
1210 while( my $transfer = $transfers->next ){
1211 $transfer->datearrived( dt_from_string() )->store;
1216 _FixPriority( { biblionumber => $biblionumber } );
1217 my $item = Koha::Items->find($itemnumber);
1218 if ( $item->location && $item->location eq 'CART'
1219 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1220 CartToShelf( $itemnumber );
1223 my $std = $dbh->prepare(q{
1225 FROM tmp_holdsqueue q
1226 INNER JOIN hold_fill_targets t
1227 ON q.borrowernumber = t.borrowernumber
1228 AND q.biblionumber = t.biblionumber
1229 AND q.itemnumber = t.itemnumber
1230 AND q.item_level_request = t.item_level_request
1231 AND q.holdingbranch = t.source_branchcode
1232 WHERE t.reserve_id = ?
1234 $std->execute($hold->reserve_id);
1236 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->get_from_storage->unblessed) )
1237 if C4::Context->preference('HoldsLog');
1242 =head2 ModReserveCancelAll
1244 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1246 function to cancel reserv,check other reserves, and transfer document if it's necessary
1250 sub ModReserveCancelAll {
1253 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1255 #step 1 : cancel the reservation
1256 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1257 return unless $holds->count;
1258 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1260 #step 2 launch the subroutine of the others reserves
1261 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1263 return ( $messages, $nextreservinfo->{borrowernumber} );
1266 =head2 ModReserveMinusPriority
1268 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1270 Reduce the values of queued list
1274 sub ModReserveMinusPriority {
1275 my ( $itemnumber, $reserve_id ) = @_;
1277 #first step update the value of the first person on reserv
1278 my $dbh = C4::Context->dbh;
1281 SET priority = 0 , itemnumber = ?
1282 WHERE reserve_id = ?
1284 my $sth_upd = $dbh->prepare($query);
1285 $sth_upd->execute( $itemnumber, $reserve_id );
1286 # second step update all others reserves
1287 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1290 =head2 IsAvailableForItemLevelRequest
1292 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1294 Checks whether a given item record is available for an
1295 item-level hold request. An item is available if
1297 * it is not lost AND
1298 * it is not damaged AND
1299 * it is not withdrawn AND
1300 * a waiting or in transit reserve is placed on
1301 * does not have a not for loan value > 0
1303 Need to check the issuingrules onshelfholds column,
1304 if this is set items on the shelf can be placed on hold
1306 Note that IsAvailableForItemLevelRequest() does not
1307 check if the staff operator is authorized to place
1308 a request on the item - in particular,
1309 this routine does not check IndependentBranches
1310 and canreservefromotherbranches.
1312 Note also that this subroutine does not checks smart
1313 rules limits for item by reservesallowed/holds_per_record
1314 values, this complemented in calling code with calls and
1315 checks with CanItemBeReserved or CanBookBeReserved.
1319 sub IsAvailableForItemLevelRequest {
1322 my $pickup_branchcode = shift;
1323 # items_any_available is precalculated status passed from request.pl when set of items
1324 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1325 my $items_any_available = shift;
1327 my $dbh = C4::Context->dbh;
1328 # must check the notforloan setting of the itemtype
1329 # FIXME - a lot of places in the code do this
1330 # or something similar - need to be
1332 my $itemtype = $item->effective_itemtype;
1333 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1336 $notforloan_per_itemtype ||
1338 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1340 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1342 if ($pickup_branchcode) {
1343 my $destination = Koha::Libraries->find($pickup_branchcode);
1344 return 0 unless $destination;
1345 return 0 unless $destination->pickup_location;
1346 return 0 unless $item->can_be_transferred( { to => $destination } );
1347 my $reserves_control_branch =
1348 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1349 my $branchitemrule =
1350 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1351 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1352 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1355 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1357 if ( $on_shelf_holds == 1 ) {
1359 } elsif ( $on_shelf_holds == 2 ) {
1361 # if we have this param predefined from outer caller sub, we just need
1362 # to return it, so we saving from having loop inside other loop:
1363 return $items_any_available ? 0 : 1
1364 if defined $items_any_available;
1366 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1367 return $any_available ? 0 : 1;
1368 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1369 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1373 =head2 ItemsAnyAvailableAndNotRestricted
1375 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1377 This function checks all items for specified biblionumber (numeric) against patron (object)
1378 and returns true (1) if at least one item available for loan/check out/present/not held
1379 and also checks other parameters logic which not restricts item for hold at all (for ex.
1380 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1384 sub ItemsAnyAvailableAndNotRestricted {
1387 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1389 foreach my $i (@items) {
1390 my $reserves_control_branch =
1391 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1392 my $branchitemrule =
1393 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1394 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1396 # we can return (end the loop) when first one found:
1399 || $i->notforloan # items with non-zero notforloan cannot be checked out
1402 || IsItemOnHoldAndFound( $i->id )
1404 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1405 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1406 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1407 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1408 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1414 =head2 AlterPriority
1416 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1418 This function changes a reserve's priority up, down, to the top, or to the bottom.
1419 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1424 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1426 my $hold = Koha::Holds->find( $reserve_id );
1427 return unless $hold;
1429 if ( $hold->cancellationdate ) {
1430 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1434 if ( $where eq 'up' ) {
1435 return unless $prev_priority;
1436 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1437 } elsif ( $where eq 'down' ) {
1438 return unless $next_priority;
1439 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1440 } elsif ( $where eq 'top' ) {
1441 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1442 } elsif ( $where eq 'bottom' ) {
1443 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1446 # FIXME Should return the new priority
1449 =head2 ToggleLowestPriority
1451 ToggleLowestPriority( $borrowernumber, $biblionumber );
1453 This function sets the lowestPriority field to true if is false, and false if it is true.
1457 sub ToggleLowestPriority {
1458 my ( $reserve_id ) = @_;
1460 my $dbh = C4::Context->dbh;
1462 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1463 $sth->execute( $reserve_id );
1465 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1468 =head2 ToggleSuspend
1470 ToggleSuspend( $reserve_id );
1472 This function sets the suspend field to true if is false, and false if it is true.
1473 If the reserve is currently suspended with a suspend_until date, that date will
1474 be cleared when it is unsuspended.
1479 my ( $reserve_id, $suspend_until ) = @_;
1481 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1483 my $hold = Koha::Holds->find( $reserve_id );
1485 if ( $hold->is_suspended ) {
1488 $hold->suspend_hold( $suspend_until );
1495 borrowernumber => $borrowernumber,
1496 [ biblionumber => $biblionumber, ]
1497 [ suspend_until => $suspend_until, ]
1498 [ suspend => $suspend ]
1501 This function accepts a set of hash keys as its parameters.
1502 It requires either borrowernumber or biblionumber, or both.
1504 suspend_until is wholly optional.
1511 my $borrowernumber = $params{'borrowernumber'} || undef;
1512 my $biblionumber = $params{'biblionumber'} || undef;
1513 my $suspend_until = $params{'suspend_until'} || undef;
1514 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1516 $suspend_until = eval { dt_from_string($suspend_until) }
1517 if ( defined($suspend_until) );
1519 return unless ( $borrowernumber || $biblionumber );
1522 $params->{found} = undef;
1523 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1524 $params->{biblionumber} = $biblionumber if $biblionumber;
1526 my @holds = Koha::Holds->search($params);
1529 map { $_->suspend_hold($suspend_until) } @holds;
1532 map { $_->resume() } @holds;
1540 reserve_id => $reserve_id,
1542 [ignoreSetLowestRank => $ignoreSetLowestRank]
1547 _FixPriority({ biblionumber => $biblionumber});
1549 This routine adjusts the priority of a hold request and holds
1552 In the first form, where a reserve_id is passed, the priority of the
1553 hold is set to supplied rank, and other holds for that bib are adjusted
1554 accordingly. If the rank is "del", the hold is cancelled. If no rank
1555 is supplied, all of the holds on that bib have their priority adjusted
1556 as if the second form had been used.
1558 In the second form, where a biblionumber is passed, the holds on that
1559 bib (that are not captured) are sorted in order of increasing priority,
1560 then have reserves.priority set so that the first non-captured hold
1561 has its priority set to 1, the second non-captured hold has its priority
1562 set to 2, and so forth.
1564 In both cases, holds that have the lowestPriority flag on are have their
1565 priority adjusted to ensure that they remain at the end of the line.
1567 Note that the ignoreSetLowestRank parameter is meant to be used only
1568 when _FixPriority calls itself.
1573 my ( $params ) = @_;
1574 my $reserve_id = $params->{reserve_id};
1575 my $rank = $params->{rank} // '';
1576 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1577 my $biblionumber = $params->{biblionumber};
1579 my $dbh = C4::Context->dbh;
1582 if ( $reserve_id ) {
1583 $hold = Koha::Holds->find( $reserve_id );
1584 if (!defined $hold){
1585 # may have already been checked out and hold fulfilled
1586 $hold = Koha::Old::Holds->find( $reserve_id );
1588 return unless $hold;
1591 unless ( $biblionumber ) { # FIXME This is a very weird API
1592 $biblionumber = $hold->biblionumber;
1595 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1598 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1600 # make sure priority for waiting or in-transit items is 0
1604 WHERE reserve_id = ?
1605 AND found IN ('W', 'T', 'P')
1607 my $sth = $dbh->prepare($query);
1608 $sth->execute( $reserve_id );
1614 SELECT reserve_id, borrowernumber, reservedate
1616 WHERE biblionumber = ?
1617 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1618 ORDER BY priority ASC
1620 my $sth = $dbh->prepare($query);
1621 $sth->execute( $biblionumber );
1622 while ( my $line = $sth->fetchrow_hashref ) {
1623 push( @priority, $line );
1626 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1627 # To find the matching index
1629 my $key = -1; # to allow for 0 to be a valid result
1630 for ( $i = 0 ; $i < @priority ; $i++ ) {
1631 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1632 $key = $i; # save the index
1637 # if index exists in array then move it to new position
1638 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1639 my $new_rank = $rank -
1640 1; # $new_rank is what you want the new index to be in the array
1641 my $moving_item = splice( @priority, $key, 1 );
1642 splice( @priority, $new_rank, 0, $moving_item );
1645 # now fix the priority on those that are left....
1649 WHERE reserve_id = ?
1651 $sth = $dbh->prepare($query);
1652 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1655 $priority[$j]->{'reserve_id'}
1659 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1662 unless ( $ignoreSetLowestRank ) {
1663 while ( my $res = $sth->fetchrow_hashref() ) {
1665 reserve_id => $res->{'reserve_id'},
1667 ignoreSetLowestRank => 1
1673 =head2 _Findgroupreserve
1675 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1677 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1678 first match found. If neither, then we look for non-holds-queue based holds.
1679 Lookahead is the number of days to look in advance.
1681 C<&_Findgroupreserve> returns :
1682 C<@results> is an array of references-to-hash whose keys are mostly
1683 fields from the reserves table of the Koha database, plus
1684 C<biblioitemnumber>.
1686 This routine with either return:
1687 1 - Item specific holds from the holds queue
1688 2 - Title level holds from the holds queue
1689 3 - All holds for this biblionumber
1691 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1695 sub _Findgroupreserve {
1696 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1697 my $dbh = C4::Context->dbh;
1699 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1700 # check for exact targeted match
1701 my $item_level_target_query = qq{
1702 SELECT reserves.biblionumber AS biblionumber,
1703 reserves.borrowernumber AS borrowernumber,
1704 reserves.reservedate AS reservedate,
1705 reserves.branchcode AS branchcode,
1706 reserves.cancellationdate AS cancellationdate,
1707 reserves.found AS found,
1708 reserves.reservenotes AS reservenotes,
1709 reserves.priority AS priority,
1710 reserves.timestamp AS timestamp,
1711 biblioitems.biblioitemnumber AS biblioitemnumber,
1712 reserves.itemnumber AS itemnumber,
1713 reserves.reserve_id AS reserve_id,
1714 reserves.itemtype AS itemtype,
1715 reserves.non_priority AS non_priority
1717 JOIN biblioitems USING (biblionumber)
1718 JOIN hold_fill_targets USING (reserve_id)
1721 AND item_level_request = 1
1722 AND hold_fill_targets.itemnumber = ?
1723 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1727 my $sth = $dbh->prepare($item_level_target_query);
1728 $sth->execute($itemnumber, $lookahead||0);
1730 if ( my $data = $sth->fetchrow_hashref ) {
1731 push( @results, $data )
1732 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1734 return @results if @results;
1736 # check for title-level targeted match
1737 my $title_level_target_query = qq{
1738 SELECT reserves.biblionumber AS biblionumber,
1739 reserves.borrowernumber AS borrowernumber,
1740 reserves.reservedate AS reservedate,
1741 reserves.branchcode AS branchcode,
1742 reserves.cancellationdate AS cancellationdate,
1743 reserves.found AS found,
1744 reserves.reservenotes AS reservenotes,
1745 reserves.priority AS priority,
1746 reserves.timestamp AS timestamp,
1747 biblioitems.biblioitemnumber AS biblioitemnumber,
1748 reserves.itemnumber AS itemnumber,
1749 reserves.reserve_id AS reserve_id,
1750 reserves.itemtype AS itemtype,
1751 reserves.non_priority AS non_priority
1753 JOIN biblioitems USING (biblionumber)
1754 JOIN hold_fill_targets USING (reserve_id)
1757 AND item_level_request = 0
1758 AND hold_fill_targets.itemnumber = ?
1759 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1763 $sth = $dbh->prepare($title_level_target_query);
1764 $sth->execute($itemnumber, $lookahead||0);
1766 if ( my $data = $sth->fetchrow_hashref ) {
1767 push( @results, $data )
1768 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1770 return @results if @results;
1773 SELECT reserves.biblionumber AS biblionumber,
1774 reserves.borrowernumber AS borrowernumber,
1775 reserves.reservedate AS reservedate,
1776 reserves.waitingdate AS waitingdate,
1777 reserves.branchcode AS branchcode,
1778 reserves.cancellationdate AS cancellationdate,
1779 reserves.found AS found,
1780 reserves.reservenotes AS reservenotes,
1781 reserves.priority AS priority,
1782 reserves.timestamp AS timestamp,
1783 reserves.itemnumber AS itemnumber,
1784 reserves.reserve_id AS reserve_id,
1785 reserves.itemtype AS itemtype,
1786 reserves.non_priority AS non_priority
1788 WHERE reserves.biblionumber = ?
1789 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1790 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1794 $sth = $dbh->prepare($query);
1795 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1797 while ( my $data = $sth->fetchrow_hashref ) {
1798 push( @results, $data )
1799 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1804 =head2 _koha_notify_reserve
1806 _koha_notify_reserve( $hold->reserve_id );
1808 Sends a notification to the patron that their hold has been filled (through
1809 ModReserveAffect, _not_ ModReserveFill)
1811 The letter code for this notice may be found using the following query:
1813 select distinct letter_code
1814 from message_transports
1815 inner join message_attributes using (message_attribute_id)
1816 where message_name = 'Hold_Filled'
1818 This will probably sipmly be 'HOLD', but because it is defined in the database,
1819 it is subject to addition or change.
1821 The following tables are availalbe witin the notice:
1832 sub _koha_notify_reserve {
1833 my $reserve_id = shift;
1834 my $hold = Koha::Holds->find($reserve_id);
1835 my $borrowernumber = $hold->borrowernumber;
1837 my $patron = Koha::Patrons->find( $borrowernumber );
1839 # Try to get the borrower's email address
1840 my $to_address = $patron->notice_email_address;
1842 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1843 borrowernumber => $borrowernumber,
1844 message_name => 'Hold_Filled'
1847 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1849 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1851 my %letter_params = (
1852 module => 'reserves',
1853 branchcode => $hold->branchcode,
1854 lang => $patron->lang,
1856 'branches' => $library,
1857 'borrowers' => $patron->unblessed,
1858 'biblio' => $hold->biblionumber,
1859 'biblioitems' => $hold->biblionumber,
1860 'reserves' => $hold->unblessed,
1861 'items' => $hold->itemnumber,
1865 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.
1866 my $send_notification = sub {
1867 my ( $mtt, $letter_code ) = (@_);
1868 return unless defined $letter_code;
1869 $letter_params{letter_code} = $letter_code;
1870 $letter_params{message_transport_type} = $mtt;
1871 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1873 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1877 C4::Letters::EnqueueLetter( {
1879 borrowernumber => $borrowernumber,
1880 from_address => $admin_email_address,
1881 message_transport_type => $mtt,
1885 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1887 ( $mtt eq 'email' and not $to_address ) # No email address
1888 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1889 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1890 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1893 &$send_notification($mtt, $letter_code);
1894 $notification_sent++;
1896 #Making sure that a print notification is sent if no other transport types can be utilized.
1897 if (! $notification_sent) {
1898 &$send_notification('print', 'HOLD');
1903 =head2 _ShiftPriorityByDateAndPriority
1905 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1907 This increments the priority of all reserves after the one
1908 with either the lowest date after C<$reservedate>
1909 or the lowest priority after C<$priority>.
1911 It effectively makes room for a new reserve to be inserted with a certain
1912 priority, which is returned.
1914 This is most useful when the reservedate can be set by the user. It allows
1915 the new reserve to be placed before other reserves that have a later
1916 reservedate. Since priority also is set by the form in reserves/request.pl
1917 the sub accounts for that too.
1921 sub _ShiftPriorityByDateAndPriority {
1922 my ( $biblio, $resdate, $new_priority ) = @_;
1924 my $dbh = C4::Context->dbh;
1925 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1926 my $sth = $dbh->prepare( $query );
1927 $sth->execute( $biblio, $resdate, $new_priority );
1928 my $min_priority = $sth->fetchrow;
1929 # if no such matches are found, $new_priority remains as original value
1930 $new_priority = $min_priority if ( $min_priority );
1932 # Shift the priority up by one; works in conjunction with the next SQL statement
1933 $query = "UPDATE reserves
1934 SET priority = priority+1
1935 WHERE biblionumber = ?
1936 AND borrowernumber = ?
1939 my $sth_update = $dbh->prepare( $query );
1941 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1942 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1943 $sth = $dbh->prepare( $query );
1944 $sth->execute( $new_priority, $biblio );
1945 while ( my $row = $sth->fetchrow_hashref ) {
1946 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1949 return $new_priority; # so the caller knows what priority they wind up receiving
1954 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1956 Use when checking out an item to handle reserves
1957 If $cancelreserve boolean is set to true, it will remove existing reserve
1962 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1964 $cancelreserve //= 0;
1966 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1967 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1970 my $biblionumber = $res->{biblionumber};
1972 if ($res->{borrowernumber} == $borrowernumber) {
1973 ModReserveFill($res);
1977 # The item is reserved by someone else.
1978 # Find this item in the reserves
1980 my $borr_res = Koha::Holds->search({
1981 borrowernumber => $borrowernumber,
1982 biblionumber => $biblionumber,
1984 order_by => 'priority'
1988 # The item is reserved by the current patron
1989 ModReserveFill($borr_res->unblessed);
1992 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1993 RevertWaitingStatus({ itemnumber => $itemnumber });
1995 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1996 my $hold = Koha::Holds->find( $res->{reserve_id} );
2004 MergeHolds($dbh,$to_biblio, $from_biblio);
2006 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2011 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2012 my $sth = $dbh->prepare(
2013 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2015 $sth->execute($from_biblio);
2016 if ( my $data = $sth->fetchrow_hashref() ) {
2018 # holds exist on old record, if not we don't need to do anything
2019 $sth = $dbh->prepare(
2020 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2021 $sth->execute( $to_biblio, $from_biblio );
2024 # don't reorder those already waiting
2026 $sth = $dbh->prepare(
2027 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2029 my $upd_sth = $dbh->prepare(
2030 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2031 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2033 $sth->execute( $to_biblio );
2035 while ( my $reserve = $sth->fetchrow_hashref() ) {
2037 $priority, $to_biblio,
2038 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2039 $reserve->{'itemnumber'}
2046 =head2 RevertWaitingStatus
2048 RevertWaitingStatus({ itemnumber => $itemnumber });
2050 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2052 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2053 item level hold, even if it was only a bibliolevel hold to
2054 begin with. This is because we can no longer know if a hold
2055 was item-level or bib-level after a hold has been set to
2060 sub RevertWaitingStatus {
2061 my ( $params ) = @_;
2062 my $itemnumber = $params->{'itemnumber'};
2064 return unless ( $itemnumber );
2066 my $dbh = C4::Context->dbh;
2068 ## Get the waiting reserve we want to revert
2069 my $hold = Koha::Holds->search(
2071 itemnumber => $itemnumber,
2072 found => { not => undef },
2076 ## Increment the priority of all other non-waiting
2077 ## reserves for this bib record
2078 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2079 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2081 ## Fix up the currently waiting reserve
2086 waitingdate => undef,
2087 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2091 _FixPriority( { biblionumber => $hold->biblionumber } );
2100 branchcode => $branchcode,
2101 borrowernumber => $borrowernumber,
2102 biblionumber => $biblionumber,
2103 [ itemnumber => $itemnumber, ]
2104 [ barcode => $barcode, ]
2108 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2110 The letter code will be HOLD_SLIP, and the following tables are
2111 available within the slip:
2124 my $branchcode = $args->{branchcode};
2125 my $reserve_id = $args->{reserve_id};
2127 my $hold = Koha::Holds->find($reserve_id);
2128 return unless $hold;
2130 my $patron = $hold->borrower;
2131 my $reserve = $hold->unblessed;
2133 return C4::Letters::GetPreparedLetter (
2134 module => 'circulation',
2135 letter_code => 'HOLD_SLIP',
2136 branchcode => $branchcode,
2137 lang => $patron->lang,
2139 'reserves' => $reserve,
2140 'branches' => $reserve->{branchcode},
2141 'borrowers' => $reserve->{borrowernumber},
2142 'biblio' => $reserve->{biblionumber},
2143 'biblioitems' => $reserve->{biblionumber},
2144 'items' => $reserve->{itemnumber},
2149 =head2 GetReservesControlBranch
2151 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2153 Return the branchcode to be used to determine which reserves
2154 policy applies to a transaction.
2156 C<$item> is a hashref for an item. Only 'homebranch' is used.
2158 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2162 sub GetReservesControlBranch {
2163 my ( $item, $borrower ) = @_;
2165 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2168 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2169 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2175 =head2 CalculatePriority
2177 my $p = CalculatePriority($biblionumber, $resdate);
2179 Calculate priority for a new reserve on biblionumber, placing it at
2180 the end of the line of all holds whose start date falls before
2181 the current system time and that are neither on the hold shelf
2184 The reserve date parameter is optional; if it is supplied, the
2185 priority is based on the set of holds whose start date falls before
2186 the parameter value.
2188 After calculation of this priority, it is recommended to call
2189 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2194 sub CalculatePriority {
2195 my ( $biblionumber, $resdate ) = @_;
2198 SELECT COUNT(*) FROM reserves
2199 WHERE biblionumber = ?
2201 AND (found IS NULL OR found = '')
2203 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2205 $sql.= ' AND ( reservedate <= ? )';
2208 $sql.= ' AND ( reservedate < NOW() )';
2210 my $dbh = C4::Context->dbh();
2211 my @row = $dbh->selectrow_array(
2214 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2217 return @row ? $row[0]+1 : 1;
2220 =head2 IsItemOnHoldAndFound
2222 my $bool = IsItemFoundHold( $itemnumber );
2224 Returns true if the item is currently on hold
2225 and that hold has a non-null found status ( W, T, etc. )
2229 sub IsItemOnHoldAndFound {
2230 my ($itemnumber) = @_;
2232 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2234 my $found = $rs->count(
2236 itemnumber => $itemnumber,
2237 found => { '!=' => undef }
2244 =head2 GetMaxPatronHoldsForRecord
2246 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2248 For multiple holds on a given record for a given patron, the max
2249 number of record level holds that a patron can be placed is the highest
2250 value of the holds_per_record rule for each item if the record for that
2251 patron. This subroutine finds and returns the highest holds_per_record
2252 rule value for a given patron id and record id.
2256 sub GetMaxPatronHoldsForRecord {
2257 my ( $borrowernumber, $biblionumber ) = @_;
2259 my $patron = Koha::Patrons->find($borrowernumber);
2260 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2262 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2264 my $categorycode = $patron->categorycode;
2266 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2269 foreach my $item (@items) {
2270 my $itemtype = $item->effective_itemtype();
2272 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2274 my $rule = Koha::CirculationRules->get_effective_rule({
2275 categorycode => $categorycode,
2276 itemtype => $itemtype,
2277 branchcode => $branchcode,
2278 rule_name => 'holds_per_record'
2280 my $holds_per_record = $rule ? $rule->rule_value : 0;
2281 $max = $holds_per_record if $holds_per_record > $max;
2289 Koha Development Team <http://koha-community.org/>