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::Biblio qw( GetMarcFromKohaField );
28 use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
30 use C4::Items qw( CartToShelf get_hostitemnumbers_of );
32 use C4::Log qw( logaction );
33 use C4::Members::Messaging;
35 use Koha::Account::Lines;
36 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
39 use Koha::CirculationRules;
41 use Koha::DateUtils qw( dt_from_string output_pref );
51 use List::MoreUtils qw( any );
55 C4::Reserves - Koha functions for dealing with reservation.
63 This modules provides somes functions to deal with reservations.
65 Reserves are stored in reserves table.
66 The following columns contains important values :
67 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
68 =0 : then the reserve is being dealed
69 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
70 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
71 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
72 F(inished) : the reserve has been completed, and is done
73 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
74 by librarian before notice is send and status changed to waiting.
75 Applicable only if HoldsNeedProcessingSIP system preference is set.
76 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
99 our (@ISA, @EXPORT_OK);
116 ModReserveMinusPriority
122 CanReserveBeCanceledFromOpac
123 CancelExpiredReserves
125 AutoUnsuspendReserves
127 IsAvailableForItemLevelRequest
128 ItemsAnyAvailableAndNotRestricted
137 GetReservesControlBranch
143 GetMaxPatronHoldsForRecord
155 branchcode => $branchcode,
156 borrowernumber => $borrowernumber,
157 biblionumber => $biblionumber,
158 priority => $priority,
159 reservation_date => $reservation_date,
160 expiration_date => $expiration_date,
163 itemnumber => $itemnumber,
165 itemtype => $itemtype,
169 Adds reserve and generates HOLDPLACED message.
171 The following tables are available witin the HOLDPLACED message:
184 my $branch = $params->{branchcode};
185 my $borrowernumber = $params->{borrowernumber};
186 my $biblionumber = $params->{biblionumber};
187 my $priority = $params->{priority};
188 my $resdate = $params->{reservation_date};
189 my $patron_expiration_date = $params->{expiration_date};
190 my $notes = $params->{notes};
191 my $title = $params->{title};
192 my $checkitem = $params->{itemnumber};
193 my $found = $params->{found};
194 my $itemtype = $params->{itemtype};
195 my $non_priority = $params->{non_priority};
197 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
198 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
200 $patron_expiration_date = output_pref({ str => $patron_expiration_date, dateonly => 1, dateformat => 'iso' });
202 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
203 # of the document, we force the value $priority and $found .
204 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
205 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
208 # If item is already checked out, it cannot be set waiting
211 # The item can't be waiting if it needs a transfer
212 && $item->holdingbranch eq $branch
214 # Similarly, if in transit it can't be waiting
215 && !$item->get_transfer
217 # If we can't hold damaged items, and it is damaged, it can't be waiting
218 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
220 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
221 && !$item->current_holds->count )
228 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
230 # Make room in reserves for this before those of a later reserve date
231 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
236 # If the reserv had the waiting status, we had the value of the resdate
237 if ( $found && $found eq 'W' ) {
238 $waitingdate = $resdate;
241 # Don't add itemtype limit if specific item is selected
242 $itemtype = undef if $checkitem;
244 # updates take place here
245 my $hold = Koha::Hold->new(
247 borrowernumber => $borrowernumber,
248 biblionumber => $biblionumber,
249 reservedate => $resdate,
250 branchcode => $branch,
251 priority => $priority,
252 reservenotes => $notes,
253 itemnumber => $checkitem,
255 waitingdate => $waitingdate,
256 patron_expiration_date => $patron_expiration_date,
257 itemtype => $itemtype,
258 item_level_hold => $checkitem ? 1 : 0,
259 non_priority => $non_priority ? 1 : 0,
262 $hold->set_waiting() if $found && $found eq 'W';
264 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
265 if C4::Context->preference('HoldsLog');
267 my $reserve_id = $hold->id();
269 # add a reserve fee if needed
270 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
271 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
272 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
275 _FixPriority({ biblionumber => $biblionumber});
277 # Send e-mail to librarian if syspref is active
278 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
279 my $patron = Koha::Patrons->find( $borrowernumber );
280 my $library = $patron->library;
281 if ( my $letter = C4::Letters::GetPreparedLetter (
282 module => 'reserves',
283 letter_code => 'HOLDPLACED',
284 branchcode => $branch,
285 lang => $patron->lang,
287 'branches' => $library->unblessed,
288 'borrowers' => $patron->unblessed,
289 'biblio' => $biblionumber,
290 'biblioitems' => $biblionumber,
291 'items' => $checkitem,
292 'reserves' => $hold->unblessed,
296 my $branch_email_address = $library->inbound_email_address;
298 C4::Letters::EnqueueLetter(
301 borrowernumber => $borrowernumber,
302 message_transport_type => 'email',
303 to_address => $branch_email_address,
309 Koha::Plugins->call('after_hold_create', $hold);
314 payload => { hold => $hold->get_from_storage }
318 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
320 biblio_ids => [ $biblionumber ]
327 =head2 CanBookBeReserved
329 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
330 if ($canReserve eq 'OK') { #We can reserve this Item! }
332 $params are passed directly through to CanItemBeReserved
334 See CanItemBeReserved() for possible return values.
338 sub CanBookBeReserved{
339 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
341 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
342 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
343 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
344 return { status =>'alreadypossession' };
348 #get items linked via host records
349 my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
350 if (@hostitemnumbers){
351 $items = Koha::Items->search({
353 biblionumber => $biblionumber,
354 itemnumber => { -in => @hostitemnumbers }
358 $items = Koha::Items->search({ biblionumber => $biblionumber});
361 my $canReserve = { status => '' };
362 my $patron = Koha::Patrons->find( $borrowernumber );
363 while ( my $item = $items->next ) {
364 $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
365 return { status => 'OK' } if $canReserve->{status} eq 'OK';
370 =head2 CanItemBeReserved
372 $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
373 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
376 'ignore_found_holds' - if true holds that have been trapped are not counted
377 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
378 current checkout against the high holds threshold
379 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
380 should not check if there are too many holds as we only csre about reservability
382 @RETURNS { status => OK }, if the Item can be reserved.
383 { status => ageRestricted }, if the Item is age restricted for this borrower.
384 { status => damaged }, if the Item is damaged.
385 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
386 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
387 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
388 { status => notReservable }, if holds on this item are not allowed
389 { status => libraryNotFound }, if given branchcode is not an existing library
390 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
391 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
392 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
393 { status => recall }, if the borrower has already placed a recall on this item
397 sub CanItemBeReserved {
398 my ( $patron, $item, $pickup_branchcode, $params ) = @_;
400 my $dbh = C4::Context->dbh;
401 my $ruleitemtype; # itemtype of the matching issuing rule
402 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
404 # We check item branch if IndependentBranches is ON
405 # and canreservefromotherbranches is OFF
406 if ( C4::Context->preference('IndependentBranches')
407 and !C4::Context->preference('canreservefromotherbranches') )
409 if ( $item->homebranch ne $patron->branchcode ) {
410 return { status => 'cannotReserveFromOtherBranches' };
414 # we retrieve borrowers and items informations #
415 # item->{itype} will come for biblioitems if necessery
416 my $borrower = $patron->unblessed;
418 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
419 return { status =>'damaged' }
421 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
423 if( GetMarcFromKohaField('biblioitems.agerestriction') ){
424 my $biblio = $item->biblio;
425 # Check for the age restriction
426 my ( $ageRestriction, $daysToAgeRestriction ) =
427 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
428 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
431 # Check that the patron doesn't have an item level hold on this item already
432 return { status =>'itemAlreadyOnHold' }
433 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
435 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
436 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
437 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
438 return { status =>'alreadypossession' };
441 # check if a recall exists on this item from this borrower
442 return { status => 'recall' }
443 if $patron->recalls->filter_by_current->search({ itemnumber => $item->itemnumber })->count;
445 my $controlbranch = C4::Context->preference('ReservesControlBranch');
447 my $reserves_control_branch;
448 my $branchfield = "reserves.branchcode";
450 if ( $controlbranch eq "ItemHomeLibrary" ) {
451 $branchfield = "items.homebranch";
452 $reserves_control_branch = $item->homebranch;
454 elsif ( $controlbranch eq "PatronLibrary" ) {
455 $branchfield = "borrowers.branchcode";
456 $reserves_control_branch = $borrower->{branchcode};
461 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
462 itemtype => $item->effective_itemtype,
463 categorycode => $borrower->{categorycode},
464 branchcode => $reserves_control_branch,
465 rule_name => 'reservesallowed',
468 $ruleitemtype = $reservesallowed->itemtype;
469 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
472 $ruleitemtype = undef;
475 my $rights = Koha::CirculationRules->get_effective_rules({
476 categorycode => $borrower->{'categorycode'},
477 itemtype => $item->effective_itemtype,
478 branchcode => $reserves_control_branch,
479 rules => ['holds_per_record','holds_per_day']
481 my $holds_per_record = $rights->{holds_per_record} // 1;
482 my $holds_per_day = $rights->{holds_per_day};
484 if ( defined $holds_per_record && $holds_per_record ne '' ){
485 if ( $holds_per_record == 0 ) {
486 return { status => "noReservesAllowed" };
488 if ( !$params->{ignore_hold_counts} ) {
489 my $search_params = {
490 borrowernumber => $patron->borrowernumber,
491 biblionumber => $item->biblionumber,
493 $search_params->{found} = undef if $params->{ignore_found_holds};
494 my $holds = Koha::Holds->search($search_params);
495 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record;
499 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '')
501 my $today_holds = Koha::Holds->search({
502 borrowernumber => $patron->borrowernumber,
503 reservedate => dt_from_string->date
505 return { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day;
508 # we check if it's ok or not
509 if ( defined $allowedreserves && $allowedreserves ne '' ){
510 if( $allowedreserves == 0 ){
511 return { status => 'noReservesAllowed' };
513 if ( !$params->{ignore_hold_counts} ) {
516 SELECT count(*) AS count
518 LEFT JOIN items USING (itemnumber)
519 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
520 LEFT JOIN borrowers USING (borrowernumber)
521 WHERE borrowernumber = ?
523 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
525 # If using item-level itypes, fall back to the record
526 # level itemtype if the hold has no associated item
528 C4::Context->preference('item-level_itypes')
529 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
530 : " AND biblioitems.itemtype = ?"
531 if defined $ruleitemtype;
533 my $sthcount = $dbh->prepare($querycount);
535 if ( defined $ruleitemtype ) {
536 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype );
539 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch );
542 my $reservecount = "0";
543 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
544 $reservecount = $rowcount->{count};
547 return { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves;
551 # Now we need to check hold limits by patron category
552 my $rule = Koha::CirculationRules->get_effective_rule(
554 categorycode => $patron->categorycode,
555 branchcode => $reserves_control_branch,
556 rule_name => 'max_holds',
559 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
560 my $total_holds_count = Koha::Holds->search(
562 borrowernumber => $patron->borrowernumber
566 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
570 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
572 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
573 return { status => 'notReservable' };
576 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
577 && $borrower->{branchcode} ne $item->homebranch )
579 return { status => 'cannotReserveFromOtherBranches' };
582 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
583 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
584 if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
585 return { status => 'branchNotInHoldGroup' };
589 if ($pickup_branchcode) {
590 my $destination = Koha::Libraries->find({
591 branchcode => $pickup_branchcode,
594 unless ($destination) {
595 return { status => 'libraryNotFound' };
597 unless ($destination->pickup_location) {
598 return { status => 'libraryNotPickupLocation' };
600 unless ($item->can_be_transferred({ to => $destination })) {
601 return { status => 'cannotBeTransferred' };
603 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
604 return { status => 'pickupNotInHoldGroup' };
606 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
607 return { status => 'pickupNotInHoldGroup' };
611 return { status => 'OK' };
614 =head2 CanReserveBeCanceledFromOpac
616 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
618 returns 1 if reserve can be cancelled by user from OPAC.
619 First check if reserve belongs to user, next checks if reserve is not in
620 transfer or waiting status
624 sub CanReserveBeCanceledFromOpac {
625 my ($reserve_id, $borrowernumber) = @_;
627 return unless $reserve_id and $borrowernumber;
628 my $reserve = Koha::Holds->find($reserve_id) or return;
630 return 0 unless $reserve->borrowernumber == $borrowernumber;
631 return $reserve->is_cancelable_from_opac;
634 =head2 GetOtherReserves
636 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
638 Check queued list of this document and check if this document must be transferred
642 sub GetOtherReserves {
643 my ($itemnumber) = @_;
646 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
647 if ($checkreserves) {
648 my $item = Koha::Items->find($itemnumber);
649 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
650 $messages->{'transfert'} = $checkreserves->{'branchcode'};
651 #minus priorities of others reservs
652 ModReserveMinusPriority(
654 $checkreserves->{'reserve_id'},
657 #launch the subroutine dotransfer
658 C4::Items::ModItemTransfer(
660 $item->holdingbranch,
661 $checkreserves->{'branchcode'},
667 #step 2b : case of a reservation on the same branch, set the waiting status
669 $messages->{'waiting'} = 1;
670 ModReserveMinusPriority(
672 $checkreserves->{'reserve_id'},
674 ModReserveStatus($itemnumber,'W');
677 $nextreservinfo = $checkreserves;
680 return ( $messages, $nextreservinfo );
683 =head2 ChargeReserveFee
685 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
687 Charge the fee for a reserve (if $fee > 0)
691 sub ChargeReserveFee {
692 my ( $borrowernumber, $fee, $title ) = @_;
693 return if !$fee || $fee == 0; # the last test is needed to include 0.00
694 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
697 description => $title,
699 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
700 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
701 interface => C4::Context->interface,
702 invoice_type => undef,
711 $fee = GetReserveFee( $borrowernumber, $biblionumber );
713 Calculate the fee for a reserve (if applicable).
718 my ( $borrowernumber, $biblionumber ) = @_;
720 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
723 SELECT COUNT(*) FROM items
724 LEFT JOIN issues USING (itemnumber)
725 WHERE items.biblionumber=? AND issues.issue_id IS NULL
728 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
731 my $dbh = C4::Context->dbh;
732 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
733 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
734 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
735 # This is a reconstruction of the old code:
736 # Compare number of items with items issued, and optionally check holds
737 # If not all items are issued and there are no holds: charge no fee
738 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
739 my ( $notissued, $reserved );
740 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
743 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
744 ( $biblionumber, $borrowernumber ) );
745 $fee = 0 if $reserved == 0;
751 =head2 GetReserveStatus
753 $reservestatus = GetReserveStatus($itemnumber);
755 Takes an itemnumber and returns the status of the reserve placed on it.
756 If several reserves exist, the reserve with the lower priority is given.
760 ## FIXME: I don't think this does what it thinks it does.
761 ## It only ever checks the first reserve result, even though
762 ## multiple reserves for that bib can have the itemnumber set
763 ## the sub is only used once in the codebase.
764 sub GetReserveStatus {
765 my ($itemnumber) = @_;
767 my $dbh = C4::Context->dbh;
769 my ($sth, $found, $priority);
771 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
772 $sth->execute($itemnumber);
773 ($found, $priority) = $sth->fetchrow_array;
777 return 'Waiting' if $found eq 'W' and $priority == 0;
778 return 'Processing' if $found eq 'P';
779 return 'Finished' if $found eq 'F';
782 return 'Reserved' if defined $priority && $priority > 0;
784 return ''; # empty string here will remove need for checking undef, or less log lines
789 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
790 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
791 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
793 Find a book in the reserves.
795 C<$itemnumber> is the book's item number.
796 C<$lookahead> is the number of days to look in advance for future reserves.
798 As I understand it, C<&CheckReserves> looks for the given item in the
799 reserves. If it is found, that's a match, and C<$status> is set to
802 Otherwise, it finds the most important item in the reserves with the
803 same biblio number as this book (I'm not clear on this) and returns it
804 with C<$status> set to C<Reserved>.
806 C<&CheckReserves> returns a two-element list:
808 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
810 C<$reserve> is the reserve item that matched. It is a
811 reference-to-hash whose keys are mostly the fields of the reserves
812 table in the Koha database.
817 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
818 my $dbh = C4::Context->dbh;
821 if (C4::Context->preference('item-level_itypes')){
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 items.itype = itemtypes.itemtype
838 SELECT items.biblionumber,
839 items.biblioitemnumber,
840 itemtypes.notforloan,
841 items.notforloan AS itemnotforloan,
847 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
848 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
853 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
854 $sth->execute($item);
857 $sth = $dbh->prepare("$select WHERE barcode = ?");
858 $sth->execute($barcode);
860 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
861 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
862 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
864 return unless $itemnumber; # bail if we got nothing.
865 # if item is not for loan it cannot be reserved either.....
866 # except where items.notforloan < 0 : This indicates the item is holdable.
868 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
869 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
871 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
872 return if $dont_trap or $notforloan_per_itemtype;
874 # Find this item in the reserves
875 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
877 # $priority and $highest are used to find the most important item
878 # in the list returned by &_Findgroupreserve. (The lower $priority,
879 # the more important the item.)
880 # $highest is the most important item we've seen so far.
883 if (scalar @reserves) {
884 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
885 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
886 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
888 my $priority = 10000000;
889 foreach my $res (@reserves) {
890 if ($res->{'found'} && $res->{'found'} eq 'W') {
891 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
892 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
893 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
894 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
895 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
899 my $local_hold_match;
901 if ($LocalHoldsPriority) {
902 $patron = Koha::Patrons->find( $res->{borrowernumber} );
903 $item = Koha::Items->find($itemnumber);
905 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
906 my $local_holds_priority_item_branchcode =
907 $item->$LocalHoldsPriorityItemControl;
908 my $local_holds_priority_patron_branchcode =
909 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
911 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
912 ? $patron->branchcode
915 $local_holds_priority_item_branchcode eq
916 $local_holds_priority_patron_branchcode;
920 # See if this item is more important than what we've got so far
921 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
922 $item ||= Koha::Items->find($itemnumber);
923 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
924 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
925 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
926 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
927 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
928 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
929 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
930 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
931 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
932 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
933 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
934 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
935 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
936 $priority = $res->{'priority'};
938 last if $local_hold_match;
944 # If we get this far, then no exact match was found.
945 # We return the most important (i.e. next) reservation.
947 $highest->{'itemnumber'} = $item;
948 return ( "Reserved", $highest, \@reserves );
954 =head2 CancelExpiredReserves
956 CancelExpiredReserves();
958 Cancels all reserves with an expiration date from before today.
962 sub CancelExpiredReserves {
963 my $cancellation_reason = shift;
964 my $today = dt_from_string();
965 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
966 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
968 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
971 { expirationdate => { '<', $dtf->format_date($today) } },
972 { patron_expiration_date => { '<' => $dtf->format_date($today) } }
976 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
978 # FIXME To move to Koha::Holds->search_expired (?)
979 my $holds = Koha::Holds->search( $params );
981 while ( my $hold = $holds->next ) {
982 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
984 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
986 my $cancel_params = {};
987 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
988 if ( defined($hold->found) && $hold->found eq 'W' ) {
989 $cancel_params->{charge_cancel_fee} = 1;
991 $hold->cancel( $cancel_params );
995 =head2 AutoUnsuspendReserves
997 AutoUnsuspendReserves();
999 Unsuspends all suspended reserves with a suspend_until date from before today.
1003 sub AutoUnsuspendReserves {
1004 my $today = dt_from_string();
1006 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
1008 map { $_->resume() } @holds;
1013 ModReserve({ rank => $rank,
1014 reserve_id => $reserve_id,
1015 branchcode => $branchcode
1016 [, itemnumber => $itemnumber ]
1017 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1020 Change a hold request's priority or cancel it.
1022 C<$rank> specifies the effect of the change. If C<$rank>
1023 is 'n', nothing happens. This corresponds to leaving a
1024 request alone when changing its priority in the holds queue
1027 If C<$rank> is 'del', the hold request is cancelled.
1029 If C<$rank> is an integer greater than zero, the priority of
1030 the request is set to that value. Since priority != 0 means
1031 that the item is not waiting on the hold shelf, setting the
1032 priority to a non-zero value also sets the request's found
1033 status and waiting date to NULL.
1035 If the hold is 'found' (waiting, in-transit, processing) the
1036 only field that can be updated is the expiration date.
1038 The optional C<$itemnumber> parameter is used only when
1039 C<$rank> is a non-zero integer; if supplied, the itemnumber
1040 of the hold request is set accordingly; if omitted, the itemnumber
1043 B<FIXME:> Note that the forgoing can have the effect of causing
1044 item-level hold requests to turn into title-level requests. This
1045 will be fixed once reserves has separate columns for requested
1046 itemnumber and supplying itemnumber.
1051 my ( $params ) = @_;
1053 my $rank = $params->{'rank'};
1054 my $reserve_id = $params->{'reserve_id'};
1055 my $branchcode = $params->{'branchcode'};
1056 my $itemnumber = $params->{'itemnumber'};
1057 my $suspend_until = $params->{'suspend_until'};
1058 my $borrowernumber = $params->{'borrowernumber'};
1059 my $biblionumber = $params->{'biblionumber'};
1060 my $cancellation_reason = $params->{'cancellation_reason'};
1061 my $date = $params->{expirationdate};
1063 return if defined $rank && $rank eq "n";
1065 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1068 unless ( $reserve_id ) {
1069 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1070 return unless $holds->count; # FIXME Should raise an exception
1071 $hold = $holds->next;
1072 $reserve_id = $hold->reserve_id;
1075 $hold ||= Koha::Holds->find($reserve_id);
1077 # FIXME Other calls may fail
1078 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1080 if ( $rank eq "del" ) {
1081 $hold->cancel({ cancellation_reason => $cancellation_reason });
1083 elsif ($hold->found && $hold->priority eq '0' && $date) {
1084 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1085 if C4::Context->preference('HoldsLog');
1087 # The only column that can be updated for a found hold is the expiration date
1088 $hold->expirationdate(dt_from_string($date))->store();
1090 elsif ($rank =~ /^\d+/ and $rank > 0) {
1091 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1092 if C4::Context->preference('HoldsLog');
1096 branchcode => $branchcode,
1097 itemnumber => $itemnumber,
1099 waitingdate => undef
1101 if (exists $params->{reservedate}) {
1102 $properties->{reservedate} = $params->{reservedate} || undef;
1104 if (exists $params->{expirationdate}) {
1105 $properties->{expirationdate} = $params->{expirationdate} || undef;
1108 $hold->set($properties)->store();
1110 if ( defined( $suspend_until ) ) {
1111 if ( $suspend_until ) {
1112 $suspend_until = eval { dt_from_string( $suspend_until ) };
1113 $hold->suspend_hold( $suspend_until );
1115 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1116 # If the hold is not suspended, this does nothing.
1117 $hold->set( { suspend_until => undef } )->store();
1121 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1125 =head2 ModReserveStatus
1127 &ModReserveStatus($itemnumber, $newstatus);
1129 Update the reserve status for the active (priority=0) reserve.
1131 $itemnumber is the itemnumber the reserve is on
1133 $newstatus is the new status.
1137 sub ModReserveStatus {
1139 #first : check if we have a reservation for this item .
1140 my ($itemnumber, $newstatus) = @_;
1141 my $dbh = C4::Context->dbh;
1143 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1144 my $sth_set = $dbh->prepare($query);
1145 $sth_set->execute( $newstatus, $itemnumber );
1147 my $item = Koha::Items->find($itemnumber);
1148 if ( $item->location && $item->location eq 'CART'
1149 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1151 CartToShelf( $itemnumber );
1155 =head2 ModReserveAffect
1157 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1159 This function affect an item and a status for a given reserve, either fetched directly
1160 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1161 is given, only first reserve returned is affected, which is ok for anything but
1164 if $transferToDo is not set, then the status is set to "Waiting" as well.
1165 otherwise, a transfer is on the way, and the end of the transfer will
1166 take care of the waiting status
1168 This function also removes any entry of the hold in holds queue table.
1172 sub ModReserveAffect {
1173 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1174 my $dbh = C4::Context->dbh;
1176 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1177 # attached to $itemnumber
1178 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1179 $sth->execute($itemnumber);
1180 my ($biblionumber) = $sth->fetchrow;
1182 # get request - need to find out if item is already
1183 # waiting in order to not send duplicate hold filled notifications
1186 # Find hold by id if we have it
1187 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1188 # Find item level hold for this item if there is one
1189 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1190 # Find record level hold if there is no item level hold
1191 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1193 return unless $hold;
1195 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1197 $hold->itemnumber($itemnumber);
1199 if ($transferToDo) {
1200 $hold->set_transfer();
1201 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1202 && C4::Context->interface eq 'sip'
1203 && !$already_on_shelf) {
1204 $hold->set_processing();
1206 $hold->set_waiting($desk_id);
1207 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1208 # Complete transfer if one exists
1209 my $transfer = $hold->item->get_transfer;
1210 $transfer->receive if $transfer;
1213 _FixPriority( { biblionumber => $biblionumber } );
1214 my $item = Koha::Items->find($itemnumber);
1215 if ( $item->location && $item->location eq 'CART'
1216 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1217 CartToShelf( $itemnumber );
1220 my $std = $dbh->prepare(q{
1222 FROM tmp_holdsqueue q
1223 INNER JOIN hold_fill_targets t
1224 ON q.borrowernumber = t.borrowernumber
1225 AND q.biblionumber = t.biblionumber
1226 AND q.itemnumber = t.itemnumber
1227 AND q.item_level_request = t.item_level_request
1228 AND q.holdingbranch = t.source_branchcode
1229 WHERE t.reserve_id = ?
1231 $std->execute($hold->reserve_id);
1233 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1234 if C4::Context->preference('HoldsLog');
1239 =head2 ModReserveCancelAll
1241 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1243 function to cancel reserv,check other reserves, and transfer document if it's necessary
1247 sub ModReserveCancelAll {
1250 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1252 #step 1 : cancel the reservation
1253 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1254 return unless $holds->count;
1255 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1257 #step 2 launch the subroutine of the others reserves
1258 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1260 return ( $messages, $nextreservinfo->{borrowernumber} );
1263 =head2 ModReserveMinusPriority
1265 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1267 Reduce the values of queued list
1271 sub ModReserveMinusPriority {
1272 my ( $itemnumber, $reserve_id ) = @_;
1274 #first step update the value of the first person on reserv
1275 my $dbh = C4::Context->dbh;
1278 SET priority = 0 , itemnumber = ?
1279 WHERE reserve_id = ?
1281 my $sth_upd = $dbh->prepare($query);
1282 $sth_upd->execute( $itemnumber, $reserve_id );
1283 # second step update all others reserves
1284 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1287 =head2 IsAvailableForItemLevelRequest
1289 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1291 Checks whether a given item record is available for an
1292 item-level hold request. An item is available if
1294 * it is not lost AND
1295 * it is not damaged AND
1296 * it is not withdrawn AND
1297 * a waiting or in transit reserve is placed on
1298 * does not have a not for loan value > 0
1300 Need to check the issuingrules onshelfholds column,
1301 if this is set items on the shelf can be placed on hold
1303 Note that IsAvailableForItemLevelRequest() does not
1304 check if the staff operator is authorized to place
1305 a request on the item - in particular,
1306 this routine does not check IndependentBranches
1307 and canreservefromotherbranches.
1309 Note also that this subroutine does not checks smart
1310 rules limits for item by reservesallowed/holds_per_record
1311 values, this complemented in calling code with calls and
1312 checks with CanItemBeReserved or CanBookBeReserved.
1316 sub IsAvailableForItemLevelRequest {
1319 my $pickup_branchcode = shift;
1320 # items_any_available is precalculated status passed from request.pl when set of items
1321 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1322 my $items_any_available = shift;
1324 my $dbh = C4::Context->dbh;
1325 # must check the notforloan setting of the itemtype
1326 # FIXME - a lot of places in the code do this
1327 # or something similar - need to be
1329 my $itemtype = $item->effective_itemtype;
1331 unless defined $itemtype;
1332 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1335 $notforloan_per_itemtype ||
1337 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1339 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1341 if ($pickup_branchcode) {
1342 my $destination = Koha::Libraries->find($pickup_branchcode);
1343 return 0 unless $destination;
1344 return 0 unless $destination->pickup_location;
1345 return 0 unless $item->can_be_transferred( { to => $destination } );
1346 my $reserves_control_branch =
1347 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1348 my $branchitemrule =
1349 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1350 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1351 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1354 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1356 if ( $on_shelf_holds == 1 ) {
1358 } elsif ( $on_shelf_holds == 2 ) {
1360 # if we have this param predefined from outer caller sub, we just need
1361 # to return it, so we saving from having loop inside other loop:
1362 return $items_any_available ? 0 : 1
1363 if defined $items_any_available;
1365 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1366 return $any_available ? 0 : 1;
1367 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1368 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1372 =head2 ItemsAnyAvailableAndNotRestricted
1374 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1376 This function checks all items for specified biblionumber (numeric) against patron (object)
1377 and returns true (1) if at least one item available for loan/check out/present/not held
1378 and also checks other parameters logic which not restricts item for hold at all (for ex.
1379 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1383 sub ItemsAnyAvailableAndNotRestricted {
1386 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1388 foreach my $i (@items) {
1389 my $reserves_control_branch =
1390 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1391 my $branchitemrule =
1392 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1393 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1395 # we can return (end the loop) when first one found:
1398 || $i->notforloan # items with non-zero notforloan cannot be checked out
1401 || IsItemOnHoldAndFound( $i->id )
1403 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1404 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1405 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1406 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1407 || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1413 =head2 AlterPriority
1415 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1417 This function changes a reserve's priority up, down, to the top, or to the bottom.
1418 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1423 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1425 my $hold = Koha::Holds->find( $reserve_id );
1426 return unless $hold;
1428 if ( $hold->cancellationdate ) {
1429 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1433 if ( $where eq 'up' ) {
1434 return unless $prev_priority;
1435 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1436 } elsif ( $where eq 'down' ) {
1437 return unless $next_priority;
1438 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1439 } elsif ( $where eq 'top' ) {
1440 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1441 } elsif ( $where eq 'bottom' ) {
1442 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1445 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
1447 biblio_ids => [ $hold->biblionumber ]
1450 # FIXME Should return the new priority
1453 =head2 ToggleLowestPriority
1455 ToggleLowestPriority( $borrowernumber, $biblionumber );
1457 This function sets the lowestPriority field to true if is false, and false if it is true.
1461 sub ToggleLowestPriority {
1462 my ( $reserve_id ) = @_;
1464 my $dbh = C4::Context->dbh;
1466 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1467 $sth->execute( $reserve_id );
1469 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1472 =head2 ToggleSuspend
1474 ToggleSuspend( $reserve_id );
1476 This function sets the suspend field to true if is false, and false if it is true.
1477 If the reserve is currently suspended with a suspend_until date, that date will
1478 be cleared when it is unsuspended.
1483 my ( $reserve_id, $suspend_until ) = @_;
1485 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1487 my $hold = Koha::Holds->find( $reserve_id );
1489 if ( $hold->is_suspended ) {
1492 $hold->suspend_hold( $suspend_until );
1499 borrowernumber => $borrowernumber,
1500 [ biblionumber => $biblionumber, ]
1501 [ suspend_until => $suspend_until, ]
1502 [ suspend => $suspend ]
1505 This function accepts a set of hash keys as its parameters.
1506 It requires either borrowernumber or biblionumber, or both.
1508 suspend_until is wholly optional.
1515 my $borrowernumber = $params{'borrowernumber'} || undef;
1516 my $biblionumber = $params{'biblionumber'} || undef;
1517 my $suspend_until = $params{'suspend_until'} || undef;
1518 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1520 $suspend_until = eval { dt_from_string($suspend_until) }
1521 if ( defined($suspend_until) );
1523 return unless ( $borrowernumber || $biblionumber );
1526 $params->{found} = undef;
1527 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1528 $params->{biblionumber} = $biblionumber if $biblionumber;
1530 my @holds = Koha::Holds->search($params)->as_list;
1533 map { $_->suspend_hold($suspend_until) } @holds;
1536 map { $_->resume() } @holds;
1544 reserve_id => $reserve_id,
1546 [ignoreSetLowestRank => $ignoreSetLowestRank]
1551 _FixPriority({ biblionumber => $biblionumber});
1553 This routine adjusts the priority of a hold request and holds
1556 In the first form, where a reserve_id is passed, the priority of the
1557 hold is set to supplied rank, and other holds for that bib are adjusted
1558 accordingly. If the rank is "del", the hold is cancelled. If no rank
1559 is supplied, all of the holds on that bib have their priority adjusted
1560 as if the second form had been used.
1562 In the second form, where a biblionumber is passed, the holds on that
1563 bib (that are not captured) are sorted in order of increasing priority,
1564 then have reserves.priority set so that the first non-captured hold
1565 has its priority set to 1, the second non-captured hold has its priority
1566 set to 2, and so forth.
1568 In both cases, holds that have the lowestPriority flag on are have their
1569 priority adjusted to ensure that they remain at the end of the line.
1571 Note that the ignoreSetLowestRank parameter is meant to be used only
1572 when _FixPriority calls itself.
1577 my ( $params ) = @_;
1578 my $reserve_id = $params->{reserve_id};
1579 my $rank = $params->{rank} // '';
1580 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1581 my $biblionumber = $params->{biblionumber};
1583 my $dbh = C4::Context->dbh;
1586 if ( $reserve_id ) {
1587 $hold = Koha::Holds->find( $reserve_id );
1588 if (!defined $hold){
1589 # may have already been checked out and hold fulfilled
1590 $hold = Koha::Old::Holds->find( $reserve_id );
1592 return unless $hold;
1595 unless ( $biblionumber ) { # FIXME This is a very weird API
1596 $biblionumber = $hold->biblionumber;
1599 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1602 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1604 # make sure priority for waiting or in-transit items is 0
1608 WHERE reserve_id = ?
1609 AND found IN ('W', 'T', 'P')
1611 my $sth = $dbh->prepare($query);
1612 $sth->execute( $reserve_id );
1618 SELECT reserve_id, borrowernumber, reservedate
1620 WHERE biblionumber = ?
1621 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1622 ORDER BY priority ASC
1624 my $sth = $dbh->prepare($query);
1625 $sth->execute( $biblionumber );
1626 while ( my $line = $sth->fetchrow_hashref ) {
1627 push( @priority, $line );
1630 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1631 # To find the matching index
1633 my $key = -1; # to allow for 0 to be a valid result
1634 for ( $i = 0 ; $i < @priority ; $i++ ) {
1635 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1636 $key = $i; # save the index
1641 # if index exists in array then move it to new position
1642 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1643 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1644 my $moving_item = splice( @priority, $key, 1 );
1645 $new_rank = scalar @priority if $new_rank > scalar @priority;
1646 splice( @priority, $new_rank, 0, $moving_item );
1649 # now fix the priority on those that are left....
1653 WHERE reserve_id = ?
1655 $sth = $dbh->prepare($query);
1656 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1659 $priority[$j]->{'reserve_id'}
1663 unless ( $ignoreSetLowestRank ) {
1664 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1665 $sth->execute($biblionumber);
1666 while ( my $res = $sth->fetchrow_hashref() ) {
1668 reserve_id => $res->{'reserve_id'},
1670 ignoreSetLowestRank => 1
1676 =head2 _Findgroupreserve
1678 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1680 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1681 first match found. If neither, then we look for non-holds-queue based holds.
1682 Lookahead is the number of days to look in advance.
1684 C<&_Findgroupreserve> returns :
1685 C<@results> is an array of references-to-hash whose keys are mostly
1686 fields from the reserves table of the Koha database, plus
1687 C<biblioitemnumber>.
1689 This routine with either return:
1690 1 - Item specific holds from the holds queue
1691 2 - Title level holds from the holds queue
1692 3 - All holds for this biblionumber
1694 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1698 sub _Findgroupreserve {
1699 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1700 my $dbh = C4::Context->dbh;
1702 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1703 # check for exact targeted match
1704 my $item_level_target_query = qq{
1705 SELECT reserves.biblionumber AS biblionumber,
1706 reserves.borrowernumber AS borrowernumber,
1707 reserves.reservedate AS reservedate,
1708 reserves.branchcode AS branchcode,
1709 reserves.cancellationdate AS cancellationdate,
1710 reserves.found AS found,
1711 reserves.reservenotes AS reservenotes,
1712 reserves.priority AS priority,
1713 reserves.timestamp AS timestamp,
1714 biblioitems.biblioitemnumber AS biblioitemnumber,
1715 reserves.itemnumber AS itemnumber,
1716 reserves.reserve_id AS reserve_id,
1717 reserves.itemtype AS itemtype,
1718 reserves.non_priority AS non_priority
1720 JOIN biblioitems USING (biblionumber)
1721 JOIN hold_fill_targets USING (reserve_id)
1724 AND item_level_request = 1
1725 AND hold_fill_targets.itemnumber = ?
1726 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1730 my $sth = $dbh->prepare($item_level_target_query);
1731 $sth->execute($itemnumber, $lookahead||0);
1733 if ( my $data = $sth->fetchrow_hashref ) {
1734 push( @results, $data )
1735 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1737 return @results if @results;
1739 # check for title-level targeted match
1740 my $title_level_target_query = qq{
1741 SELECT reserves.biblionumber AS biblionumber,
1742 reserves.borrowernumber AS borrowernumber,
1743 reserves.reservedate AS reservedate,
1744 reserves.branchcode AS branchcode,
1745 reserves.cancellationdate AS cancellationdate,
1746 reserves.found AS found,
1747 reserves.reservenotes AS reservenotes,
1748 reserves.priority AS priority,
1749 reserves.timestamp AS timestamp,
1750 biblioitems.biblioitemnumber AS biblioitemnumber,
1751 reserves.itemnumber AS itemnumber,
1752 reserves.reserve_id AS reserve_id,
1753 reserves.itemtype AS itemtype,
1754 reserves.non_priority AS non_priority
1756 JOIN biblioitems USING (biblionumber)
1757 JOIN hold_fill_targets USING (reserve_id)
1760 AND item_level_request = 0
1761 AND hold_fill_targets.itemnumber = ?
1762 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1766 $sth = $dbh->prepare($title_level_target_query);
1767 $sth->execute($itemnumber, $lookahead||0);
1769 if ( my $data = $sth->fetchrow_hashref ) {
1770 push( @results, $data )
1771 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1773 return @results if @results;
1776 SELECT reserves.biblionumber AS biblionumber,
1777 reserves.borrowernumber AS borrowernumber,
1778 reserves.reservedate AS reservedate,
1779 reserves.waitingdate AS waitingdate,
1780 reserves.branchcode AS branchcode,
1781 reserves.cancellationdate AS cancellationdate,
1782 reserves.found AS found,
1783 reserves.reservenotes AS reservenotes,
1784 reserves.priority AS priority,
1785 reserves.timestamp AS timestamp,
1786 reserves.itemnumber AS itemnumber,
1787 reserves.reserve_id AS reserve_id,
1788 reserves.itemtype AS itemtype,
1789 reserves.non_priority AS non_priority
1791 WHERE reserves.biblionumber = ?
1792 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1793 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1797 $sth = $dbh->prepare($query);
1798 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1800 while ( my $data = $sth->fetchrow_hashref ) {
1801 push( @results, $data )
1802 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1807 =head2 _koha_notify_reserve
1809 _koha_notify_reserve( $hold->reserve_id );
1811 Sends a notification to the patron that their hold has been filled (through
1814 The letter code for this notice may be found using the following query:
1816 select distinct letter_code
1817 from message_transports
1818 inner join message_attributes using (message_attribute_id)
1819 where message_name = 'Hold_Filled'
1821 This will probably sipmly be 'HOLD', but because it is defined in the database,
1822 it is subject to addition or change.
1824 The following tables are availalbe witin the notice:
1835 sub _koha_notify_reserve {
1836 my $reserve_id = shift;
1837 my $hold = Koha::Holds->find($reserve_id);
1838 my $borrowernumber = $hold->borrowernumber;
1840 my $patron = Koha::Patrons->find( $borrowernumber );
1842 # Try to get the borrower's email address
1843 my $to_address = $patron->notice_email_address;
1845 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1846 borrowernumber => $borrowernumber,
1847 message_name => 'Hold_Filled'
1850 my $library = Koha::Libraries->find( $hold->branchcode );
1851 my $admin_email_address = $library->from_email_address;
1852 $library = $library->unblessed;
1854 my %letter_params = (
1855 module => 'reserves',
1856 branchcode => $hold->branchcode,
1857 lang => $patron->lang,
1859 'branches' => $library,
1860 'borrowers' => $patron->unblessed,
1861 'biblio' => $hold->biblionumber,
1862 'biblioitems' => $hold->biblionumber,
1863 'reserves' => $hold->unblessed,
1864 'items' => $hold->itemnumber,
1868 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.
1869 my $send_notification = sub {
1870 my ( $mtt, $letter_code ) = (@_);
1871 return unless defined $letter_code;
1872 $letter_params{letter_code} = $letter_code;
1873 $letter_params{message_transport_type} = $mtt;
1874 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1876 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1880 C4::Letters::EnqueueLetter( {
1882 borrowernumber => $borrowernumber,
1883 from_address => $admin_email_address,
1884 message_transport_type => $mtt,
1888 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1890 ( $mtt eq 'email' and not $to_address ) # No email address
1891 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1892 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1893 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1896 &$send_notification($mtt, $letter_code);
1897 $notification_sent++;
1899 #Making sure that a print notification is sent if no other transport types can be utilized.
1900 if (! $notification_sent) {
1901 &$send_notification('print', 'HOLD');
1906 =head2 _ShiftPriorityByDateAndPriority
1908 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1910 This increments the priority of all reserves after the one
1911 with either the lowest date after C<$reservedate>
1912 or the lowest priority after C<$priority>.
1914 It effectively makes room for a new reserve to be inserted with a certain
1915 priority, which is returned.
1917 This is most useful when the reservedate can be set by the user. It allows
1918 the new reserve to be placed before other reserves that have a later
1919 reservedate. Since priority also is set by the form in reserves/request.pl
1920 the sub accounts for that too.
1924 sub _ShiftPriorityByDateAndPriority {
1925 my ( $biblio, $resdate, $new_priority ) = @_;
1927 my $dbh = C4::Context->dbh;
1928 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1929 my $sth = $dbh->prepare( $query );
1930 $sth->execute( $biblio, $resdate, $new_priority );
1931 my $min_priority = $sth->fetchrow;
1932 # if no such matches are found, $new_priority remains as original value
1933 $new_priority = $min_priority if ( $min_priority );
1935 # Shift the priority up by one; works in conjunction with the next SQL statement
1936 $query = "UPDATE reserves
1937 SET priority = priority+1
1938 WHERE biblionumber = ?
1939 AND borrowernumber = ?
1942 my $sth_update = $dbh->prepare( $query );
1944 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1945 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1946 $sth = $dbh->prepare( $query );
1947 $sth->execute( $new_priority, $biblio );
1948 while ( my $row = $sth->fetchrow_hashref ) {
1949 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1952 return $new_priority; # so the caller knows what priority they wind up receiving
1957 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1959 Use when checking out an item to handle reserves
1960 If $cancelreserve boolean is set to true, it will remove existing reserve
1965 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1967 $cancelreserve //= 0;
1969 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1970 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1973 my $biblionumber = $res->{biblionumber};
1975 if ($res->{borrowernumber} == $borrowernumber) {
1976 my $hold = Koha::Holds->find( $res->{reserve_id} );
1981 # The item is reserved by someone else.
1982 # Find this item in the reserves
1984 my $borr_res = Koha::Holds->search({
1985 borrowernumber => $borrowernumber,
1986 biblionumber => $biblionumber,
1988 order_by => 'priority'
1992 # The item is reserved by the current patron
1996 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1997 RevertWaitingStatus({ itemnumber => $itemnumber });
1999 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2000 my $hold = Koha::Holds->find( $res->{reserve_id} );
2008 MergeHolds($dbh,$to_biblio, $from_biblio);
2010 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2015 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2016 my $sth = $dbh->prepare(
2017 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2019 $sth->execute($from_biblio);
2020 if ( my $data = $sth->fetchrow_hashref() ) {
2022 # holds exist on old record, if not we don't need to do anything
2023 $sth = $dbh->prepare(
2024 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2025 $sth->execute( $to_biblio, $from_biblio );
2028 # don't reorder those already waiting
2030 $sth = $dbh->prepare(
2031 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2033 my $upd_sth = $dbh->prepare(
2034 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2035 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2037 $sth->execute( $to_biblio );
2039 while ( my $reserve = $sth->fetchrow_hashref() ) {
2041 $priority, $to_biblio,
2042 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2043 $reserve->{'itemnumber'}
2050 =head2 RevertWaitingStatus
2052 RevertWaitingStatus({ itemnumber => $itemnumber });
2054 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2056 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2057 item level hold, even if it was only a bibliolevel hold to
2058 begin with. This is because we can no longer know if a hold
2059 was item-level or bib-level after a hold has been set to
2064 sub RevertWaitingStatus {
2065 my ( $params ) = @_;
2066 my $itemnumber = $params->{'itemnumber'};
2068 return unless ( $itemnumber );
2070 my $dbh = C4::Context->dbh;
2072 ## Get the waiting reserve we want to revert
2073 my $hold = Koha::Holds->search(
2075 itemnumber => $itemnumber,
2076 found => { not => undef },
2080 ## Increment the priority of all other non-waiting
2081 ## reserves for this bib record
2082 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2083 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2085 ## Fix up the currently waiting reserve
2090 waitingdate => undef,
2091 expirationdate => $hold->patron_expiration_date,
2092 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2096 _FixPriority( { biblionumber => $hold->biblionumber } );
2098 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
2100 biblio_ids => [ $hold->biblionumber ]
2112 branchcode => $branchcode,
2113 borrowernumber => $borrowernumber,
2114 biblionumber => $biblionumber,
2115 [ itemnumber => $itemnumber, ]
2116 [ barcode => $barcode, ]
2120 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2122 The letter code will be HOLD_SLIP, and the following tables are
2123 available within the slip:
2136 my $branchcode = $args->{branchcode};
2137 my $reserve_id = $args->{reserve_id};
2139 my $hold = Koha::Holds->find($reserve_id);
2140 return unless $hold;
2142 my $patron = $hold->borrower;
2143 my $reserve = $hold->unblessed;
2145 return C4::Letters::GetPreparedLetter (
2146 module => 'circulation',
2147 letter_code => 'HOLD_SLIP',
2148 branchcode => $branchcode,
2149 lang => $patron->lang,
2151 'reserves' => $reserve,
2152 'branches' => $reserve->{branchcode},
2153 'borrowers' => $reserve->{borrowernumber},
2154 'biblio' => $reserve->{biblionumber},
2155 'biblioitems' => $reserve->{biblionumber},
2156 'items' => $reserve->{itemnumber},
2161 =head2 GetReservesControlBranch
2163 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2165 Return the branchcode to be used to determine which reserves
2166 policy applies to a transaction.
2168 C<$item> is a hashref for an item. Only 'homebranch' is used.
2170 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2174 sub GetReservesControlBranch {
2175 my ( $item, $borrower ) = @_;
2177 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2180 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2181 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2187 =head2 CalculatePriority
2189 my $p = CalculatePriority($biblionumber, $resdate);
2191 Calculate priority for a new reserve on biblionumber, placing it at
2192 the end of the line of all holds whose start date falls before
2193 the current system time and that are neither on the hold shelf
2196 The reserve date parameter is optional; if it is supplied, the
2197 priority is based on the set of holds whose start date falls before
2198 the parameter value.
2200 After calculation of this priority, it is recommended to call
2201 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2206 sub CalculatePriority {
2207 my ( $biblionumber, $resdate ) = @_;
2210 SELECT COUNT(*) FROM reserves
2211 WHERE biblionumber = ?
2213 AND (found IS NULL OR found = '')
2215 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2217 $sql.= ' AND ( reservedate <= ? )';
2220 $sql.= ' AND ( reservedate < NOW() )';
2222 my $dbh = C4::Context->dbh();
2223 my @row = $dbh->selectrow_array(
2226 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2229 return @row ? $row[0]+1 : 1;
2232 =head2 IsItemOnHoldAndFound
2234 my $bool = IsItemFoundHold( $itemnumber );
2236 Returns true if the item is currently on hold
2237 and that hold has a non-null found status ( W, T, etc. )
2241 sub IsItemOnHoldAndFound {
2242 my ($itemnumber) = @_;
2244 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2246 my $found = $rs->count(
2248 itemnumber => $itemnumber,
2249 found => { '!=' => undef }
2256 =head2 GetMaxPatronHoldsForRecord
2258 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2260 For multiple holds on a given record for a given patron, the max
2261 number of record level holds that a patron can be placed is the highest
2262 value of the holds_per_record rule for each item if the record for that
2263 patron. This subroutine finds and returns the highest holds_per_record
2264 rule value for a given patron id and record id.
2268 sub GetMaxPatronHoldsForRecord {
2269 my ( $borrowernumber, $biblionumber ) = @_;
2271 my $patron = Koha::Patrons->find($borrowernumber);
2272 my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2274 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2276 my $categorycode = $patron->categorycode;
2278 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2281 foreach my $item (@items) {
2282 my $itemtype = $item->effective_itemtype();
2284 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2286 my $rule = Koha::CirculationRules->get_effective_rule({
2287 categorycode => $categorycode,
2288 itemtype => $itemtype,
2289 branchcode => $branchcode,
2290 rule_name => 'holds_per_record'
2292 my $holds_per_record = $rule ? $rule->rule_value : 0;
2293 $max = $holds_per_record if $holds_per_record > $max;
2301 Koha Development Team <http://koha-community.org/>