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>.
27 use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
29 use C4::Items qw( CartToShelf get_hostitemnumbers_of );
31 use C4::Log qw( logaction );
32 use C4::Members::Messaging;
34 use Koha::Account::Lines;
37 use Koha::CirculationRules;
39 use Koha::DateUtils qw( dt_from_string output_pref );
49 use List::MoreUtils qw( any );
53 C4::Reserves - Koha functions for dealing with reservation.
61 This modules provides somes functions to deal with reservations.
63 Reserves are stored in reserves table.
64 The following columns contains important values :
65 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
66 =0 : then the reserve is being dealed
67 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
68 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
69 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
70 F(inished) : the reserve has been completed, and is done
71 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
72 by librarian before notice is send and status changed to waiting.
73 Applicable only if HoldsNeedProcessingSIP system preference is set.
74 - itemnumber : empty : the reserve is still unaffected to an item
75 filled: the reserve is attached to an item
76 The complete workflow is :
77 ==== 1st use case ====
78 patron request a document, 1st available : P >0, F=NULL, I=NULL
79 a library having it run "transfertodo", and clic on the list
80 if there is no transfer to do, the reserve waiting
81 patron can pick it up P =0, F=W, I=filled
82 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
83 The pickup library receive the book, it check in P =0, F=W, I=filled
84 The patron borrow the book P =0, F=F, I=filled
86 ==== 2nd use case ====
87 patron requests a document, a given item,
88 If pickup is holding branch P =0, F=W, I=filled
89 If transfer needed, write in branchtransfer P =0, F=T, I=filled
90 The pickup library receive the book, it checks it in P =0, F=W, I=filled
91 The patron borrow the book P =0, F=F, I=filled
97 our (@ISA, @EXPORT_OK);
114 ModReserveMinusPriority
120 CanReserveBeCanceledFromOpac
121 CancelExpiredReserves
123 AutoUnsuspendReserves
125 IsAvailableForItemLevelRequest
126 ItemsAnyAvailableAndNotRestricted
135 GetReservesControlBranch
141 GetMaxPatronHoldsForRecord
153 branchcode => $branchcode,
154 borrowernumber => $borrowernumber,
155 biblionumber => $biblionumber,
156 priority => $priority,
157 reservation_date => $reservation_date,
158 expiration_date => $expiration_date,
161 itemnumber => $itemnumber,
163 itemtype => $itemtype,
167 Adds reserve and generates HOLDPLACED message.
169 The following tables are available witin the HOLDPLACED message:
182 my $branch = $params->{branchcode};
183 my $borrowernumber = $params->{borrowernumber};
184 my $biblionumber = $params->{biblionumber};
185 my $priority = $params->{priority};
186 my $resdate = $params->{reservation_date};
187 my $patron_expiration_date = $params->{expiration_date};
188 my $notes = $params->{notes};
189 my $title = $params->{title};
190 my $checkitem = $params->{itemnumber};
191 my $found = $params->{found};
192 my $itemtype = $params->{itemtype};
193 my $non_priority = $params->{non_priority};
195 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
196 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
198 $patron_expiration_date = output_pref({ str => $patron_expiration_date, dateonly => 1, dateformat => 'iso' });
200 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
201 # of the document, we force the value $priority and $found .
202 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
203 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
206 # If item is already checked out, it cannot be set waiting
209 # The item can't be waiting if it needs a transfer
210 && $item->holdingbranch eq $branch
212 # Similarly, if in transit it can't be waiting
213 && !$item->get_transfer
215 # If we can't hold damaged items, and it is damaged, it can't be waiting
216 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
218 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
219 && !$item->current_holds->count )
226 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
228 # Make room in reserves for this before those of a later reserve date
229 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
234 # If the reserv had the waiting status, we had the value of the resdate
235 if ( $found && $found eq 'W' ) {
236 $waitingdate = $resdate;
239 # Don't add itemtype limit if specific item is selected
240 $itemtype = undef if $checkitem;
242 # updates take place here
243 my $hold = Koha::Hold->new(
245 borrowernumber => $borrowernumber,
246 biblionumber => $biblionumber,
247 reservedate => $resdate,
248 branchcode => $branch,
249 priority => $priority,
250 reservenotes => $notes,
251 itemnumber => $checkitem,
253 waitingdate => $waitingdate,
254 patron_expiration_date => $patron_expiration_date,
255 itemtype => $itemtype,
256 item_level_hold => $checkitem ? 1 : 0,
257 non_priority => $non_priority ? 1 : 0,
260 $hold->set_waiting() if $found && $found eq 'W';
262 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
263 if C4::Context->preference('HoldsLog');
265 my $reserve_id = $hold->id();
267 # add a reserve fee if needed
268 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
269 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
270 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
273 _FixPriority({ biblionumber => $biblionumber});
275 # Send e-mail to librarian if syspref is active
276 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
277 my $patron = Koha::Patrons->find( $borrowernumber );
278 my $library = $patron->library;
279 if ( my $letter = C4::Letters::GetPreparedLetter (
280 module => 'reserves',
281 letter_code => 'HOLDPLACED',
282 branchcode => $branch,
283 lang => $patron->lang,
285 'branches' => $library->unblessed,
286 'borrowers' => $patron->unblessed,
287 'biblio' => $biblionumber,
288 'biblioitems' => $biblionumber,
289 'items' => $checkitem,
290 'reserves' => $hold->unblessed,
294 my $branch_email_address = $library->inbound_email_address;
296 C4::Letters::EnqueueLetter(
299 borrowernumber => $borrowernumber,
300 message_transport_type => 'email',
301 to_address => $branch_email_address,
307 Koha::Plugins->call('after_hold_create', $hold);
312 =head2 CanBookBeReserved
314 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
315 if ($canReserve eq 'OK') { #We can reserve this Item! }
317 $params are passed directly through to CanItemBeReserved
319 See CanItemBeReserved() for possible return values.
323 sub CanBookBeReserved{
324 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
326 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
327 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
328 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
329 return { status =>'alreadypossession' };
333 #get items linked via host records
334 my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
335 if (@hostitemnumbers){
336 $items = Koha::Items->search({
338 biblionumber => $biblionumber,
339 itemnumber => { -in => @hostitemnumbers }
343 $items = Koha::Items->search({ biblionumber => $biblionumber});
346 my $canReserve = { status => '' };
347 my $patron = Koha::Patrons->find( $borrowernumber );
348 while ( my $item = $items->next ) {
349 $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
350 return { status => 'OK' } if $canReserve->{status} eq 'OK';
355 =head2 CanItemBeReserved
357 $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
358 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
361 'ignore_found_holds' - if true holds that have been trapped are not counted
362 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
363 current checkout against the high holds threshold
364 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
365 should not check if there are too many holds as we only csre about reservability
367 @RETURNS { status => OK }, if the Item can be reserved.
368 { status => ageRestricted }, if the Item is age restricted for this borrower.
369 { status => damaged }, if the Item is damaged.
370 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
371 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
372 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
373 { status => notReservable }, if holds on this item are not allowed
374 { status => libraryNotFound }, if given branchcode is not an existing library
375 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
376 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
377 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
381 sub CanItemBeReserved {
382 my ( $patron, $item, $pickup_branchcode, $params ) = @_;
384 my $dbh = C4::Context->dbh;
385 my $ruleitemtype; # itemtype of the matching issuing rule
386 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
388 # we retrieve borrowers and items informations #
389 # item->{itype} will come for biblioitems if necessery
390 my $biblio = $item->biblio;
391 my $borrower = $patron->unblessed;
393 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
394 return { status =>'damaged' }
396 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
398 # Check for the age restriction
399 my ( $ageRestriction, $daysToAgeRestriction ) =
400 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
401 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
403 # Check that the patron doesn't have an item level hold on this item already
404 return { status =>'itemAlreadyOnHold' }
405 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
407 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
408 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
409 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
410 return { status =>'alreadypossession' };
413 my $controlbranch = C4::Context->preference('ReservesControlBranch');
416 SELECT count(*) AS count
418 LEFT JOIN items USING (itemnumber)
419 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
420 LEFT JOIN borrowers USING (borrowernumber)
421 WHERE borrowernumber = ?
425 my $branchfield = "reserves.branchcode";
427 if ( $controlbranch eq "ItemHomeLibrary" ) {
428 $branchfield = "items.homebranch";
429 $branchcode = $item->homebranch;
431 elsif ( $controlbranch eq "PatronLibrary" ) {
432 $branchfield = "borrowers.branchcode";
433 $branchcode = $borrower->{branchcode};
438 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
439 itemtype => $item->effective_itemtype,
440 categorycode => $borrower->{categorycode},
441 branchcode => $branchcode,
442 rule_name => 'reservesallowed',
445 $ruleitemtype = $reservesallowed->itemtype;
446 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
449 $ruleitemtype = undef;
452 my $rights = Koha::CirculationRules->get_effective_rules({
453 categorycode => $borrower->{'categorycode'},
454 itemtype => $item->effective_itemtype,
455 branchcode => $branchcode,
456 rules => ['holds_per_record','holds_per_day']
458 my $holds_per_record = $rights->{holds_per_record} // 1;
459 my $holds_per_day = $rights->{holds_per_day};
461 my $search_params = {
462 borrowernumber => $patron->borrowernumber,
463 biblionumber => $item->biblionumber,
465 $search_params->{found} = undef if $params->{ignore_found_holds};
467 my $holds = Koha::Holds->search($search_params);
468 if ( defined $holds_per_record && $holds_per_record ne '' ){
469 if ( $holds_per_record == 0 ) {
470 return { status => "noReservesAllowed" };
472 if ( !$params->{ignore_hold_counts} && $holds->count() >= $holds_per_record ) {
473 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
477 my $today_holds = Koha::Holds->search({
478 borrowernumber => $patron->borrowernumber,
479 reservedate => dt_from_string->date
482 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne ''
483 && $today_holds->count() >= $holds_per_day )
485 return { status => 'tooManyReservesToday', limit => $holds_per_day };
490 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
492 # If using item-level itypes, fall back to the record
493 # level itemtype if the hold has no associated item
495 C4::Context->preference('item-level_itypes')
496 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
497 : " AND biblioitems.itemtype = ?"
498 if defined $ruleitemtype;
500 my $sthcount = $dbh->prepare($querycount);
502 if ( defined $ruleitemtype ) {
503 $sthcount->execute( $patron->borrowernumber, $branchcode, $ruleitemtype );
506 $sthcount->execute( $patron->borrowernumber, $branchcode );
509 my $reservecount = "0";
510 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
511 $reservecount = $rowcount->{count};
514 # we check if it's ok or not
515 if ( defined $allowedreserves && $allowedreserves ne '' ){
516 if( $allowedreserves == 0 ){
517 return { status => 'noReservesAllowed' };
519 if ( !$params->{ignore_hold_counts} && $reservecount >= $allowedreserves ) {
520 return { status => 'tooManyReserves', limit => $allowedreserves };
524 # Now we need to check hold limits by patron category
525 my $rule = Koha::CirculationRules->get_effective_rule(
527 categorycode => $patron->categorycode,
528 branchcode => $branchcode,
529 rule_name => 'max_holds',
532 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
533 my $total_holds_count = Koha::Holds->search(
535 borrowernumber => $patron->borrowernumber
539 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
542 my $reserves_control_branch =
543 GetReservesControlBranch( $item->unblessed(), $patron->unblessed );
545 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
547 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
548 return { status => 'notReservable' };
551 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
552 && $borrower->{branchcode} ne $item->homebranch )
554 return { status => 'cannotReserveFromOtherBranches' };
557 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
558 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
559 if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
560 return { status => 'branchNotInHoldGroup' };
564 # If reservecount is ok, we check item branch if IndependentBranches is ON
565 # and canreservefromotherbranches is OFF
566 if ( C4::Context->preference('IndependentBranches')
567 and !C4::Context->preference('canreservefromotherbranches') )
569 if ( $item->homebranch ne $patron->branchcode ) {
570 return { status => 'cannotReserveFromOtherBranches' };
574 if ($pickup_branchcode) {
575 my $destination = Koha::Libraries->find({
576 branchcode => $pickup_branchcode,
579 unless ($destination) {
580 return { status => 'libraryNotFound' };
582 unless ($destination->pickup_location) {
583 return { status => 'libraryNotPickupLocation' };
585 unless ($item->can_be_transferred({ to => $destination })) {
586 return { status => 'cannotBeTransferred' };
588 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
589 return { status => 'pickupNotInHoldGroup' };
591 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
592 return { status => 'pickupNotInHoldGroup' };
596 return { status => 'OK' };
599 =head2 CanReserveBeCanceledFromOpac
601 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
603 returns 1 if reserve can be cancelled by user from OPAC.
604 First check if reserve belongs to user, next checks if reserve is not in
605 transfer or waiting status
609 sub CanReserveBeCanceledFromOpac {
610 my ($reserve_id, $borrowernumber) = @_;
612 return unless $reserve_id and $borrowernumber;
613 my $reserve = Koha::Holds->find($reserve_id) or return;
615 return 0 unless $reserve->borrowernumber == $borrowernumber;
616 return $reserve->is_cancelable_from_opac;
619 =head2 GetOtherReserves
621 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
623 Check queued list of this document and check if this document must be transferred
627 sub GetOtherReserves {
628 my ($itemnumber) = @_;
631 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
632 if ($checkreserves) {
633 my $item = Koha::Items->find($itemnumber);
634 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
635 $messages->{'transfert'} = $checkreserves->{'branchcode'};
636 #minus priorities of others reservs
637 ModReserveMinusPriority(
639 $checkreserves->{'reserve_id'},
642 #launch the subroutine dotransfer
643 C4::Items::ModItemTransfer(
645 $item->holdingbranch,
646 $checkreserves->{'branchcode'},
652 #step 2b : case of a reservation on the same branch, set the waiting status
654 $messages->{'waiting'} = 1;
655 ModReserveMinusPriority(
657 $checkreserves->{'reserve_id'},
659 ModReserveStatus($itemnumber,'W');
662 $nextreservinfo = $checkreserves;
665 return ( $messages, $nextreservinfo );
668 =head2 ChargeReserveFee
670 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
672 Charge the fee for a reserve (if $fee > 0)
676 sub ChargeReserveFee {
677 my ( $borrowernumber, $fee, $title ) = @_;
678 return if !$fee || $fee == 0; # the last test is needed to include 0.00
679 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
682 description => $title,
684 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
685 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
686 interface => C4::Context->interface,
687 invoice_type => undef,
696 $fee = GetReserveFee( $borrowernumber, $biblionumber );
698 Calculate the fee for a reserve (if applicable).
703 my ( $borrowernumber, $biblionumber ) = @_;
705 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
708 SELECT COUNT(*) FROM items
709 LEFT JOIN issues USING (itemnumber)
710 WHERE items.biblionumber=? AND issues.issue_id IS NULL
713 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
716 my $dbh = C4::Context->dbh;
717 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
718 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
719 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
720 # This is a reconstruction of the old code:
721 # Compare number of items with items issued, and optionally check holds
722 # If not all items are issued and there are no holds: charge no fee
723 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
724 my ( $notissued, $reserved );
725 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
728 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
729 ( $biblionumber, $borrowernumber ) );
730 $fee = 0 if $reserved == 0;
736 =head2 GetReserveStatus
738 $reservestatus = GetReserveStatus($itemnumber);
740 Takes an itemnumber and returns the status of the reserve placed on it.
741 If several reserves exist, the reserve with the lower priority is given.
745 ## FIXME: I don't think this does what it thinks it does.
746 ## It only ever checks the first reserve result, even though
747 ## multiple reserves for that bib can have the itemnumber set
748 ## the sub is only used once in the codebase.
749 sub GetReserveStatus {
750 my ($itemnumber) = @_;
752 my $dbh = C4::Context->dbh;
754 my ($sth, $found, $priority);
756 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
757 $sth->execute($itemnumber);
758 ($found, $priority) = $sth->fetchrow_array;
762 return 'Waiting' if $found eq 'W' and $priority == 0;
763 return 'Processing' if $found eq 'P';
764 return 'Finished' if $found eq 'F';
767 return 'Reserved' if defined $priority && $priority > 0;
769 return ''; # empty string here will remove need for checking undef, or less log lines
774 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
775 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
776 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
778 Find a book in the reserves.
780 C<$itemnumber> is the book's item number.
781 C<$lookahead> is the number of days to look in advance for future reserves.
783 As I understand it, C<&CheckReserves> looks for the given item in the
784 reserves. If it is found, that's a match, and C<$status> is set to
787 Otherwise, it finds the most important item in the reserves with the
788 same biblio number as this book (I'm not clear on this) and returns it
789 with C<$status> set to C<Reserved>.
791 C<&CheckReserves> returns a two-element list:
793 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
795 C<$reserve> is the reserve item that matched. It is a
796 reference-to-hash whose keys are mostly the fields of the reserves
797 table in the Koha database.
802 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
803 my $dbh = C4::Context->dbh;
806 if (C4::Context->preference('item-level_itypes')){
808 SELECT items.biblionumber,
809 items.biblioitemnumber,
810 itemtypes.notforloan,
811 items.notforloan AS itemnotforloan,
817 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
818 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
823 SELECT items.biblionumber,
824 items.biblioitemnumber,
825 itemtypes.notforloan,
826 items.notforloan AS itemnotforloan,
832 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
833 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
838 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
839 $sth->execute($item);
842 $sth = $dbh->prepare("$select WHERE barcode = ?");
843 $sth->execute($barcode);
845 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
846 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
847 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
849 return unless $itemnumber; # bail if we got nothing.
850 # if item is not for loan it cannot be reserved either.....
851 # except where items.notforloan < 0 : This indicates the item is holdable.
853 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
854 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
856 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
857 return if $dont_trap or $notforloan_per_itemtype;
859 # Find this item in the reserves
860 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
862 # $priority and $highest are used to find the most important item
863 # in the list returned by &_Findgroupreserve. (The lower $priority,
864 # the more important the item.)
865 # $highest is the most important item we've seen so far.
868 if (scalar @reserves) {
869 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
870 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
871 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
873 my $priority = 10000000;
874 foreach my $res (@reserves) {
875 if ($res->{'found'} && $res->{'found'} eq 'W') {
876 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
877 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
878 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
879 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
880 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
884 my $local_hold_match;
886 if ($LocalHoldsPriority) {
887 $patron = Koha::Patrons->find( $res->{borrowernumber} );
888 $item = Koha::Items->find($itemnumber);
890 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
891 my $local_holds_priority_item_branchcode =
892 $item->$LocalHoldsPriorityItemControl;
893 my $local_holds_priority_patron_branchcode =
894 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
896 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
897 ? $patron->branchcode
900 $local_holds_priority_item_branchcode eq
901 $local_holds_priority_patron_branchcode;
905 # See if this item is more important than what we've got so far
906 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
907 $item ||= Koha::Items->find($itemnumber);
908 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
909 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
910 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
911 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
912 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
913 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
914 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
915 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
916 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
917 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
918 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
919 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
920 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
921 $priority = $res->{'priority'};
923 last if $local_hold_match;
929 # If we get this far, then no exact match was found.
930 # We return the most important (i.e. next) reservation.
932 $highest->{'itemnumber'} = $item;
933 return ( "Reserved", $highest, \@reserves );
939 =head2 CancelExpiredReserves
941 CancelExpiredReserves();
943 Cancels all reserves with an expiration date from before today.
947 sub CancelExpiredReserves {
948 my $cancellation_reason = shift;
949 my $today = dt_from_string();
950 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
951 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
953 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
956 { expirationdate => { '<', $dtf->format_date($today) } },
957 { patron_expiration_date => { '<' => $dtf->format_date($today) } }
961 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
963 # FIXME To move to Koha::Holds->search_expired (?)
964 my $holds = Koha::Holds->search( $params );
966 while ( my $hold = $holds->next ) {
967 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
969 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
971 my $cancel_params = {};
972 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
973 if ( defined($hold->found) && $hold->found eq 'W' ) {
974 $cancel_params->{charge_cancel_fee} = 1;
976 $hold->cancel( $cancel_params );
980 =head2 AutoUnsuspendReserves
982 AutoUnsuspendReserves();
984 Unsuspends all suspended reserves with a suspend_until date from before today.
988 sub AutoUnsuspendReserves {
989 my $today = dt_from_string();
991 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
993 map { $_->resume() } @holds;
998 ModReserve({ rank => $rank,
999 reserve_id => $reserve_id,
1000 branchcode => $branchcode
1001 [, itemnumber => $itemnumber ]
1002 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1005 Change a hold request's priority or cancel it.
1007 C<$rank> specifies the effect of the change. If C<$rank>
1008 is 'n', nothing happens. This corresponds to leaving a
1009 request alone when changing its priority in the holds queue
1012 If C<$rank> is 'del', the hold request is cancelled.
1014 If C<$rank> is an integer greater than zero, the priority of
1015 the request is set to that value. Since priority != 0 means
1016 that the item is not waiting on the hold shelf, setting the
1017 priority to a non-zero value also sets the request's found
1018 status and waiting date to NULL.
1020 If the hold is 'found' (waiting, in-transit, processing) the
1021 only field that can be updated is the expiration date.
1023 The optional C<$itemnumber> parameter is used only when
1024 C<$rank> is a non-zero integer; if supplied, the itemnumber
1025 of the hold request is set accordingly; if omitted, the itemnumber
1028 B<FIXME:> Note that the forgoing can have the effect of causing
1029 item-level hold requests to turn into title-level requests. This
1030 will be fixed once reserves has separate columns for requested
1031 itemnumber and supplying itemnumber.
1036 my ( $params ) = @_;
1038 my $rank = $params->{'rank'};
1039 my $reserve_id = $params->{'reserve_id'};
1040 my $branchcode = $params->{'branchcode'};
1041 my $itemnumber = $params->{'itemnumber'};
1042 my $suspend_until = $params->{'suspend_until'};
1043 my $borrowernumber = $params->{'borrowernumber'};
1044 my $biblionumber = $params->{'biblionumber'};
1045 my $cancellation_reason = $params->{'cancellation_reason'};
1046 my $date = $params->{expirationdate};
1048 return if defined $rank && $rank eq "n";
1050 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1053 unless ( $reserve_id ) {
1054 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1055 return unless $holds->count; # FIXME Should raise an exception
1056 $hold = $holds->next;
1057 $reserve_id = $hold->reserve_id;
1060 $hold ||= Koha::Holds->find($reserve_id);
1062 # FIXME Other calls may fail
1063 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1065 if ( $rank eq "del" ) {
1066 $hold->cancel({ cancellation_reason => $cancellation_reason });
1068 elsif ($hold->found && $hold->priority eq '0' && $date) {
1069 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1070 if C4::Context->preference('HoldsLog');
1072 # The only column that can be updated for a found hold is the expiration date
1073 $hold->expirationdate(dt_from_string($date))->store();
1075 elsif ($rank =~ /^\d+/ and $rank > 0) {
1076 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1077 if C4::Context->preference('HoldsLog');
1081 branchcode => $branchcode,
1082 itemnumber => $itemnumber,
1084 waitingdate => undef
1086 if (exists $params->{reservedate}) {
1087 $properties->{reservedate} = $params->{reservedate} || undef;
1089 if (exists $params->{expirationdate}) {
1090 $properties->{expirationdate} = $params->{expirationdate} || undef;
1093 $hold->set($properties)->store();
1095 if ( defined( $suspend_until ) ) {
1096 if ( $suspend_until ) {
1097 $suspend_until = eval { dt_from_string( $suspend_until ) };
1098 $hold->suspend_hold( $suspend_until );
1100 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1101 # If the hold is not suspended, this does nothing.
1102 $hold->set( { suspend_until => undef } )->store();
1106 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1110 =head2 ModReserveStatus
1112 &ModReserveStatus($itemnumber, $newstatus);
1114 Update the reserve status for the active (priority=0) reserve.
1116 $itemnumber is the itemnumber the reserve is on
1118 $newstatus is the new status.
1122 sub ModReserveStatus {
1124 #first : check if we have a reservation for this item .
1125 my ($itemnumber, $newstatus) = @_;
1126 my $dbh = C4::Context->dbh;
1128 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1129 my $sth_set = $dbh->prepare($query);
1130 $sth_set->execute( $newstatus, $itemnumber );
1132 my $item = Koha::Items->find($itemnumber);
1133 if ( $item->location && $item->location eq 'CART'
1134 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1136 CartToShelf( $itemnumber );
1140 =head2 ModReserveAffect
1142 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1144 This function affect an item and a status for a given reserve, either fetched directly
1145 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1146 is given, only first reserve returned is affected, which is ok for anything but
1149 if $transferToDo is not set, then the status is set to "Waiting" as well.
1150 otherwise, a transfer is on the way, and the end of the transfer will
1151 take care of the waiting status
1153 This function also removes any entry of the hold in holds queue table.
1157 sub ModReserveAffect {
1158 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1159 my $dbh = C4::Context->dbh;
1161 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1162 # attached to $itemnumber
1163 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1164 $sth->execute($itemnumber);
1165 my ($biblionumber) = $sth->fetchrow;
1167 # get request - need to find out if item is already
1168 # waiting in order to not send duplicate hold filled notifications
1171 # Find hold by id if we have it
1172 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1173 # Find item level hold for this item if there is one
1174 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1175 # Find record level hold if there is no item level hold
1176 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1178 return unless $hold;
1180 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1182 $hold->itemnumber($itemnumber);
1184 if ($transferToDo) {
1185 $hold->set_transfer();
1186 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1187 && C4::Context->interface eq 'sip'
1188 && !$already_on_shelf) {
1189 $hold->set_processing();
1191 $hold->set_waiting($desk_id);
1192 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1193 # Complete transfer if one exists
1194 my $transfer = $hold->item->get_transfer;
1195 $transfer->receive if $transfer;
1198 _FixPriority( { biblionumber => $biblionumber } );
1199 my $item = Koha::Items->find($itemnumber);
1200 if ( $item->location && $item->location eq 'CART'
1201 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1202 CartToShelf( $itemnumber );
1205 my $std = $dbh->prepare(q{
1207 FROM tmp_holdsqueue q
1208 INNER JOIN hold_fill_targets t
1209 ON q.borrowernumber = t.borrowernumber
1210 AND q.biblionumber = t.biblionumber
1211 AND q.itemnumber = t.itemnumber
1212 AND q.item_level_request = t.item_level_request
1213 AND q.holdingbranch = t.source_branchcode
1214 WHERE t.reserve_id = ?
1216 $std->execute($hold->reserve_id);
1218 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1219 if C4::Context->preference('HoldsLog');
1224 =head2 ModReserveCancelAll
1226 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1228 function to cancel reserv,check other reserves, and transfer document if it's necessary
1232 sub ModReserveCancelAll {
1235 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1237 #step 1 : cancel the reservation
1238 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1239 return unless $holds->count;
1240 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1242 #step 2 launch the subroutine of the others reserves
1243 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1245 return ( $messages, $nextreservinfo->{borrowernumber} );
1248 =head2 ModReserveMinusPriority
1250 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1252 Reduce the values of queued list
1256 sub ModReserveMinusPriority {
1257 my ( $itemnumber, $reserve_id ) = @_;
1259 #first step update the value of the first person on reserv
1260 my $dbh = C4::Context->dbh;
1263 SET priority = 0 , itemnumber = ?
1264 WHERE reserve_id = ?
1266 my $sth_upd = $dbh->prepare($query);
1267 $sth_upd->execute( $itemnumber, $reserve_id );
1268 # second step update all others reserves
1269 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1272 =head2 IsAvailableForItemLevelRequest
1274 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1276 Checks whether a given item record is available for an
1277 item-level hold request. An item is available if
1279 * it is not lost AND
1280 * it is not damaged AND
1281 * it is not withdrawn AND
1282 * a waiting or in transit reserve is placed on
1283 * does not have a not for loan value > 0
1285 Need to check the issuingrules onshelfholds column,
1286 if this is set items on the shelf can be placed on hold
1288 Note that IsAvailableForItemLevelRequest() does not
1289 check if the staff operator is authorized to place
1290 a request on the item - in particular,
1291 this routine does not check IndependentBranches
1292 and canreservefromotherbranches.
1294 Note also that this subroutine does not checks smart
1295 rules limits for item by reservesallowed/holds_per_record
1296 values, this complemented in calling code with calls and
1297 checks with CanItemBeReserved or CanBookBeReserved.
1301 sub IsAvailableForItemLevelRequest {
1304 my $pickup_branchcode = shift;
1305 # items_any_available is precalculated status passed from request.pl when set of items
1306 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1307 my $items_any_available = shift;
1309 my $dbh = C4::Context->dbh;
1310 # must check the notforloan setting of the itemtype
1311 # FIXME - a lot of places in the code do this
1312 # or something similar - need to be
1314 my $itemtype = $item->effective_itemtype;
1316 unless defined $itemtype;
1317 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1320 $notforloan_per_itemtype ||
1322 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1324 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1326 if ($pickup_branchcode) {
1327 my $destination = Koha::Libraries->find($pickup_branchcode);
1328 return 0 unless $destination;
1329 return 0 unless $destination->pickup_location;
1330 return 0 unless $item->can_be_transferred( { to => $destination } );
1331 my $reserves_control_branch =
1332 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1333 my $branchitemrule =
1334 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1335 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1336 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1339 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1341 if ( $on_shelf_holds == 1 ) {
1343 } elsif ( $on_shelf_holds == 2 ) {
1345 # if we have this param predefined from outer caller sub, we just need
1346 # to return it, so we saving from having loop inside other loop:
1347 return $items_any_available ? 0 : 1
1348 if defined $items_any_available;
1350 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1351 return $any_available ? 0 : 1;
1352 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1353 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1357 =head2 ItemsAnyAvailableAndNotRestricted
1359 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1361 This function checks all items for specified biblionumber (numeric) against patron (object)
1362 and returns true (1) if at least one item available for loan/check out/present/not held
1363 and also checks other parameters logic which not restricts item for hold at all (for ex.
1364 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1368 sub ItemsAnyAvailableAndNotRestricted {
1371 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1373 foreach my $i (@items) {
1374 my $reserves_control_branch =
1375 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1376 my $branchitemrule =
1377 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1378 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1380 # we can return (end the loop) when first one found:
1383 || $i->notforloan # items with non-zero notforloan cannot be checked out
1386 || IsItemOnHoldAndFound( $i->id )
1388 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1389 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1390 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1391 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1392 || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1398 =head2 AlterPriority
1400 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1402 This function changes a reserve's priority up, down, to the top, or to the bottom.
1403 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1408 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1410 my $hold = Koha::Holds->find( $reserve_id );
1411 return unless $hold;
1413 if ( $hold->cancellationdate ) {
1414 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1418 if ( $where eq 'up' ) {
1419 return unless $prev_priority;
1420 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1421 } elsif ( $where eq 'down' ) {
1422 return unless $next_priority;
1423 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1424 } elsif ( $where eq 'top' ) {
1425 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1426 } elsif ( $where eq 'bottom' ) {
1427 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1430 # FIXME Should return the new priority
1433 =head2 ToggleLowestPriority
1435 ToggleLowestPriority( $borrowernumber, $biblionumber );
1437 This function sets the lowestPriority field to true if is false, and false if it is true.
1441 sub ToggleLowestPriority {
1442 my ( $reserve_id ) = @_;
1444 my $dbh = C4::Context->dbh;
1446 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1447 $sth->execute( $reserve_id );
1449 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1452 =head2 ToggleSuspend
1454 ToggleSuspend( $reserve_id );
1456 This function sets the suspend field to true if is false, and false if it is true.
1457 If the reserve is currently suspended with a suspend_until date, that date will
1458 be cleared when it is unsuspended.
1463 my ( $reserve_id, $suspend_until ) = @_;
1465 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1467 my $hold = Koha::Holds->find( $reserve_id );
1469 if ( $hold->is_suspended ) {
1472 $hold->suspend_hold( $suspend_until );
1479 borrowernumber => $borrowernumber,
1480 [ biblionumber => $biblionumber, ]
1481 [ suspend_until => $suspend_until, ]
1482 [ suspend => $suspend ]
1485 This function accepts a set of hash keys as its parameters.
1486 It requires either borrowernumber or biblionumber, or both.
1488 suspend_until is wholly optional.
1495 my $borrowernumber = $params{'borrowernumber'} || undef;
1496 my $biblionumber = $params{'biblionumber'} || undef;
1497 my $suspend_until = $params{'suspend_until'} || undef;
1498 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1500 $suspend_until = eval { dt_from_string($suspend_until) }
1501 if ( defined($suspend_until) );
1503 return unless ( $borrowernumber || $biblionumber );
1506 $params->{found} = undef;
1507 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1508 $params->{biblionumber} = $biblionumber if $biblionumber;
1510 my @holds = Koha::Holds->search($params)->as_list;
1513 map { $_->suspend_hold($suspend_until) } @holds;
1516 map { $_->resume() } @holds;
1524 reserve_id => $reserve_id,
1526 [ignoreSetLowestRank => $ignoreSetLowestRank]
1531 _FixPriority({ biblionumber => $biblionumber});
1533 This routine adjusts the priority of a hold request and holds
1536 In the first form, where a reserve_id is passed, the priority of the
1537 hold is set to supplied rank, and other holds for that bib are adjusted
1538 accordingly. If the rank is "del", the hold is cancelled. If no rank
1539 is supplied, all of the holds on that bib have their priority adjusted
1540 as if the second form had been used.
1542 In the second form, where a biblionumber is passed, the holds on that
1543 bib (that are not captured) are sorted in order of increasing priority,
1544 then have reserves.priority set so that the first non-captured hold
1545 has its priority set to 1, the second non-captured hold has its priority
1546 set to 2, and so forth.
1548 In both cases, holds that have the lowestPriority flag on are have their
1549 priority adjusted to ensure that they remain at the end of the line.
1551 Note that the ignoreSetLowestRank parameter is meant to be used only
1552 when _FixPriority calls itself.
1557 my ( $params ) = @_;
1558 my $reserve_id = $params->{reserve_id};
1559 my $rank = $params->{rank} // '';
1560 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1561 my $biblionumber = $params->{biblionumber};
1563 my $dbh = C4::Context->dbh;
1566 if ( $reserve_id ) {
1567 $hold = Koha::Holds->find( $reserve_id );
1568 if (!defined $hold){
1569 # may have already been checked out and hold fulfilled
1570 $hold = Koha::Old::Holds->find( $reserve_id );
1572 return unless $hold;
1575 unless ( $biblionumber ) { # FIXME This is a very weird API
1576 $biblionumber = $hold->biblionumber;
1579 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1582 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1584 # make sure priority for waiting or in-transit items is 0
1588 WHERE reserve_id = ?
1589 AND found IN ('W', 'T', 'P')
1591 my $sth = $dbh->prepare($query);
1592 $sth->execute( $reserve_id );
1598 SELECT reserve_id, borrowernumber, reservedate
1600 WHERE biblionumber = ?
1601 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1602 ORDER BY priority ASC
1604 my $sth = $dbh->prepare($query);
1605 $sth->execute( $biblionumber );
1606 while ( my $line = $sth->fetchrow_hashref ) {
1607 push( @priority, $line );
1610 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1611 # To find the matching index
1613 my $key = -1; # to allow for 0 to be a valid result
1614 for ( $i = 0 ; $i < @priority ; $i++ ) {
1615 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1616 $key = $i; # save the index
1621 # if index exists in array then move it to new position
1622 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1623 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1624 my $moving_item = splice( @priority, $key, 1 );
1625 $new_rank = scalar @priority if $new_rank > scalar @priority;
1626 splice( @priority, $new_rank, 0, $moving_item );
1629 # now fix the priority on those that are left....
1633 WHERE reserve_id = ?
1635 $sth = $dbh->prepare($query);
1636 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1639 $priority[$j]->{'reserve_id'}
1643 unless ( $ignoreSetLowestRank ) {
1644 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1645 $sth->execute($biblionumber);
1646 while ( my $res = $sth->fetchrow_hashref() ) {
1648 reserve_id => $res->{'reserve_id'},
1650 ignoreSetLowestRank => 1
1656 =head2 _Findgroupreserve
1658 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1660 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1661 first match found. If neither, then we look for non-holds-queue based holds.
1662 Lookahead is the number of days to look in advance.
1664 C<&_Findgroupreserve> returns :
1665 C<@results> is an array of references-to-hash whose keys are mostly
1666 fields from the reserves table of the Koha database, plus
1667 C<biblioitemnumber>.
1669 This routine with either return:
1670 1 - Item specific holds from the holds queue
1671 2 - Title level holds from the holds queue
1672 3 - All holds for this biblionumber
1674 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1678 sub _Findgroupreserve {
1679 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1680 my $dbh = C4::Context->dbh;
1682 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1683 # check for exact targeted match
1684 my $item_level_target_query = qq{
1685 SELECT reserves.biblionumber AS biblionumber,
1686 reserves.borrowernumber AS borrowernumber,
1687 reserves.reservedate AS reservedate,
1688 reserves.branchcode AS branchcode,
1689 reserves.cancellationdate AS cancellationdate,
1690 reserves.found AS found,
1691 reserves.reservenotes AS reservenotes,
1692 reserves.priority AS priority,
1693 reserves.timestamp AS timestamp,
1694 biblioitems.biblioitemnumber AS biblioitemnumber,
1695 reserves.itemnumber AS itemnumber,
1696 reserves.reserve_id AS reserve_id,
1697 reserves.itemtype AS itemtype,
1698 reserves.non_priority AS non_priority
1700 JOIN biblioitems USING (biblionumber)
1701 JOIN hold_fill_targets USING (reserve_id)
1704 AND item_level_request = 1
1705 AND hold_fill_targets.itemnumber = ?
1706 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1710 my $sth = $dbh->prepare($item_level_target_query);
1711 $sth->execute($itemnumber, $lookahead||0);
1713 if ( my $data = $sth->fetchrow_hashref ) {
1714 push( @results, $data )
1715 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1717 return @results if @results;
1719 # check for title-level targeted match
1720 my $title_level_target_query = qq{
1721 SELECT reserves.biblionumber AS biblionumber,
1722 reserves.borrowernumber AS borrowernumber,
1723 reserves.reservedate AS reservedate,
1724 reserves.branchcode AS branchcode,
1725 reserves.cancellationdate AS cancellationdate,
1726 reserves.found AS found,
1727 reserves.reservenotes AS reservenotes,
1728 reserves.priority AS priority,
1729 reserves.timestamp AS timestamp,
1730 biblioitems.biblioitemnumber AS biblioitemnumber,
1731 reserves.itemnumber AS itemnumber,
1732 reserves.reserve_id AS reserve_id,
1733 reserves.itemtype AS itemtype,
1734 reserves.non_priority AS non_priority
1736 JOIN biblioitems USING (biblionumber)
1737 JOIN hold_fill_targets USING (reserve_id)
1740 AND item_level_request = 0
1741 AND hold_fill_targets.itemnumber = ?
1742 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1746 $sth = $dbh->prepare($title_level_target_query);
1747 $sth->execute($itemnumber, $lookahead||0);
1749 if ( my $data = $sth->fetchrow_hashref ) {
1750 push( @results, $data )
1751 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1753 return @results if @results;
1756 SELECT reserves.biblionumber AS biblionumber,
1757 reserves.borrowernumber AS borrowernumber,
1758 reserves.reservedate AS reservedate,
1759 reserves.waitingdate AS waitingdate,
1760 reserves.branchcode AS branchcode,
1761 reserves.cancellationdate AS cancellationdate,
1762 reserves.found AS found,
1763 reserves.reservenotes AS reservenotes,
1764 reserves.priority AS priority,
1765 reserves.timestamp AS timestamp,
1766 reserves.itemnumber AS itemnumber,
1767 reserves.reserve_id AS reserve_id,
1768 reserves.itemtype AS itemtype,
1769 reserves.non_priority AS non_priority
1771 WHERE reserves.biblionumber = ?
1772 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1773 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1777 $sth = $dbh->prepare($query);
1778 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1780 while ( my $data = $sth->fetchrow_hashref ) {
1781 push( @results, $data )
1782 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1787 =head2 _koha_notify_reserve
1789 _koha_notify_reserve( $hold->reserve_id );
1791 Sends a notification to the patron that their hold has been filled (through
1794 The letter code for this notice may be found using the following query:
1796 select distinct letter_code
1797 from message_transports
1798 inner join message_attributes using (message_attribute_id)
1799 where message_name = 'Hold_Filled'
1801 This will probably sipmly be 'HOLD', but because it is defined in the database,
1802 it is subject to addition or change.
1804 The following tables are availalbe witin the notice:
1815 sub _koha_notify_reserve {
1816 my $reserve_id = shift;
1817 my $hold = Koha::Holds->find($reserve_id);
1818 my $borrowernumber = $hold->borrowernumber;
1820 my $patron = Koha::Patrons->find( $borrowernumber );
1822 # Try to get the borrower's email address
1823 my $to_address = $patron->notice_email_address;
1825 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1826 borrowernumber => $borrowernumber,
1827 message_name => 'Hold_Filled'
1830 my $library = Koha::Libraries->find( $hold->branchcode );
1831 my $admin_email_address = $library->from_email_address;
1832 $library = $library->unblessed;
1834 my %letter_params = (
1835 module => 'reserves',
1836 branchcode => $hold->branchcode,
1837 lang => $patron->lang,
1839 'branches' => $library,
1840 'borrowers' => $patron->unblessed,
1841 'biblio' => $hold->biblionumber,
1842 'biblioitems' => $hold->biblionumber,
1843 'reserves' => $hold->unblessed,
1844 'items' => $hold->itemnumber,
1848 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.
1849 my $send_notification = sub {
1850 my ( $mtt, $letter_code ) = (@_);
1851 return unless defined $letter_code;
1852 $letter_params{letter_code} = $letter_code;
1853 $letter_params{message_transport_type} = $mtt;
1854 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1856 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1860 C4::Letters::EnqueueLetter( {
1862 borrowernumber => $borrowernumber,
1863 from_address => $admin_email_address,
1864 message_transport_type => $mtt,
1868 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1870 ( $mtt eq 'email' and not $to_address ) # No email address
1871 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1872 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1873 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1876 &$send_notification($mtt, $letter_code);
1877 $notification_sent++;
1879 #Making sure that a print notification is sent if no other transport types can be utilized.
1880 if (! $notification_sent) {
1881 &$send_notification('print', 'HOLD');
1886 =head2 _ShiftPriorityByDateAndPriority
1888 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1890 This increments the priority of all reserves after the one
1891 with either the lowest date after C<$reservedate>
1892 or the lowest priority after C<$priority>.
1894 It effectively makes room for a new reserve to be inserted with a certain
1895 priority, which is returned.
1897 This is most useful when the reservedate can be set by the user. It allows
1898 the new reserve to be placed before other reserves that have a later
1899 reservedate. Since priority also is set by the form in reserves/request.pl
1900 the sub accounts for that too.
1904 sub _ShiftPriorityByDateAndPriority {
1905 my ( $biblio, $resdate, $new_priority ) = @_;
1907 my $dbh = C4::Context->dbh;
1908 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1909 my $sth = $dbh->prepare( $query );
1910 $sth->execute( $biblio, $resdate, $new_priority );
1911 my $min_priority = $sth->fetchrow;
1912 # if no such matches are found, $new_priority remains as original value
1913 $new_priority = $min_priority if ( $min_priority );
1915 # Shift the priority up by one; works in conjunction with the next SQL statement
1916 $query = "UPDATE reserves
1917 SET priority = priority+1
1918 WHERE biblionumber = ?
1919 AND borrowernumber = ?
1922 my $sth_update = $dbh->prepare( $query );
1924 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1925 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1926 $sth = $dbh->prepare( $query );
1927 $sth->execute( $new_priority, $biblio );
1928 while ( my $row = $sth->fetchrow_hashref ) {
1929 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1932 return $new_priority; # so the caller knows what priority they wind up receiving
1937 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1939 Use when checking out an item to handle reserves
1940 If $cancelreserve boolean is set to true, it will remove existing reserve
1945 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1947 $cancelreserve //= 0;
1949 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1950 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1953 my $biblionumber = $res->{biblionumber};
1955 if ($res->{borrowernumber} == $borrowernumber) {
1956 my $hold = Koha::Holds->find( $res->{reserve_id} );
1961 # The item is reserved by someone else.
1962 # Find this item in the reserves
1964 my $borr_res = Koha::Holds->search({
1965 borrowernumber => $borrowernumber,
1966 biblionumber => $biblionumber,
1968 order_by => 'priority'
1972 # The item is reserved by the current patron
1976 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1977 RevertWaitingStatus({ itemnumber => $itemnumber });
1979 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1980 my $hold = Koha::Holds->find( $res->{reserve_id} );
1988 MergeHolds($dbh,$to_biblio, $from_biblio);
1990 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1995 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1996 my $sth = $dbh->prepare(
1997 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1999 $sth->execute($from_biblio);
2000 if ( my $data = $sth->fetchrow_hashref() ) {
2002 # holds exist on old record, if not we don't need to do anything
2003 $sth = $dbh->prepare(
2004 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2005 $sth->execute( $to_biblio, $from_biblio );
2008 # don't reorder those already waiting
2010 $sth = $dbh->prepare(
2011 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2013 my $upd_sth = $dbh->prepare(
2014 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2015 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2017 $sth->execute( $to_biblio );
2019 while ( my $reserve = $sth->fetchrow_hashref() ) {
2021 $priority, $to_biblio,
2022 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2023 $reserve->{'itemnumber'}
2030 =head2 RevertWaitingStatus
2032 RevertWaitingStatus({ itemnumber => $itemnumber });
2034 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2036 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2037 item level hold, even if it was only a bibliolevel hold to
2038 begin with. This is because we can no longer know if a hold
2039 was item-level or bib-level after a hold has been set to
2044 sub RevertWaitingStatus {
2045 my ( $params ) = @_;
2046 my $itemnumber = $params->{'itemnumber'};
2048 return unless ( $itemnumber );
2050 my $dbh = C4::Context->dbh;
2052 ## Get the waiting reserve we want to revert
2053 my $hold = Koha::Holds->search(
2055 itemnumber => $itemnumber,
2056 found => { not => undef },
2060 ## Increment the priority of all other non-waiting
2061 ## reserves for this bib record
2062 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2063 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2065 ## Fix up the currently waiting reserve
2070 waitingdate => undef,
2071 expirationdate => $hold->patron_expiration_date,
2072 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2076 _FixPriority( { biblionumber => $hold->biblionumber } );
2085 branchcode => $branchcode,
2086 borrowernumber => $borrowernumber,
2087 biblionumber => $biblionumber,
2088 [ itemnumber => $itemnumber, ]
2089 [ barcode => $barcode, ]
2093 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2095 The letter code will be HOLD_SLIP, and the following tables are
2096 available within the slip:
2109 my $branchcode = $args->{branchcode};
2110 my $reserve_id = $args->{reserve_id};
2112 my $hold = Koha::Holds->find($reserve_id);
2113 return unless $hold;
2115 my $patron = $hold->borrower;
2116 my $reserve = $hold->unblessed;
2118 return C4::Letters::GetPreparedLetter (
2119 module => 'circulation',
2120 letter_code => 'HOLD_SLIP',
2121 branchcode => $branchcode,
2122 lang => $patron->lang,
2124 'reserves' => $reserve,
2125 'branches' => $reserve->{branchcode},
2126 'borrowers' => $reserve->{borrowernumber},
2127 'biblio' => $reserve->{biblionumber},
2128 'biblioitems' => $reserve->{biblionumber},
2129 'items' => $reserve->{itemnumber},
2134 =head2 GetReservesControlBranch
2136 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2138 Return the branchcode to be used to determine which reserves
2139 policy applies to a transaction.
2141 C<$item> is a hashref for an item. Only 'homebranch' is used.
2143 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2147 sub GetReservesControlBranch {
2148 my ( $item, $borrower ) = @_;
2150 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2153 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2154 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2160 =head2 CalculatePriority
2162 my $p = CalculatePriority($biblionumber, $resdate);
2164 Calculate priority for a new reserve on biblionumber, placing it at
2165 the end of the line of all holds whose start date falls before
2166 the current system time and that are neither on the hold shelf
2169 The reserve date parameter is optional; if it is supplied, the
2170 priority is based on the set of holds whose start date falls before
2171 the parameter value.
2173 After calculation of this priority, it is recommended to call
2174 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2179 sub CalculatePriority {
2180 my ( $biblionumber, $resdate ) = @_;
2183 SELECT COUNT(*) FROM reserves
2184 WHERE biblionumber = ?
2186 AND (found IS NULL OR found = '')
2188 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2190 $sql.= ' AND ( reservedate <= ? )';
2193 $sql.= ' AND ( reservedate < NOW() )';
2195 my $dbh = C4::Context->dbh();
2196 my @row = $dbh->selectrow_array(
2199 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2202 return @row ? $row[0]+1 : 1;
2205 =head2 IsItemOnHoldAndFound
2207 my $bool = IsItemFoundHold( $itemnumber );
2209 Returns true if the item is currently on hold
2210 and that hold has a non-null found status ( W, T, etc. )
2214 sub IsItemOnHoldAndFound {
2215 my ($itemnumber) = @_;
2217 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2219 my $found = $rs->count(
2221 itemnumber => $itemnumber,
2222 found => { '!=' => undef }
2229 =head2 GetMaxPatronHoldsForRecord
2231 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2233 For multiple holds on a given record for a given patron, the max
2234 number of record level holds that a patron can be placed is the highest
2235 value of the holds_per_record rule for each item if the record for that
2236 patron. This subroutine finds and returns the highest holds_per_record
2237 rule value for a given patron id and record id.
2241 sub GetMaxPatronHoldsForRecord {
2242 my ( $borrowernumber, $biblionumber ) = @_;
2244 my $patron = Koha::Patrons->find($borrowernumber);
2245 my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2247 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2249 my $categorycode = $patron->categorycode;
2251 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2254 foreach my $item (@items) {
2255 my $itemtype = $item->effective_itemtype();
2257 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2259 my $rule = Koha::CirculationRules->get_effective_rule({
2260 categorycode => $categorycode,
2261 itemtype => $itemtype,
2262 branchcode => $branchcode,
2263 rule_name => 'holds_per_record'
2265 my $holds_per_record = $rule ? $rule->rule_value : 0;
2266 $max = $holds_per_record if $holds_per_record > $max;
2274 Koha Development Team <http://koha-community.org/>