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 );
50 use List::MoreUtils qw( any );
54 C4::Reserves - Koha functions for dealing with reservation.
62 This modules provides somes functions to deal with reservations.
64 Reserves are stored in reserves table.
65 The following columns contains important values :
66 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
67 =0 : then the reserve is being dealed
68 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
69 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
70 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
71 F(inished) : the reserve has been completed, and is done
72 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
73 by librarian before notice is send and status changed to waiting.
74 Applicable only if HoldsNeedProcessingSIP system preference is set.
75 - itemnumber : empty : the reserve is still unaffected to an item
76 filled: the reserve is attached to an item
77 The complete workflow is :
78 ==== 1st use case ====
79 patron request a document, 1st available : P >0, F=NULL, I=NULL
80 a library having it run "transfertodo", and clic on the list
81 if there is no transfer to do, the reserve waiting
82 patron can pick it up P =0, F=W, I=filled
83 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it check in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
87 ==== 2nd use case ====
88 patron requests a document, a given item,
89 If pickup is holding branch P =0, F=W, I=filled
90 If transfer needed, write in branchtransfer P =0, F=T, I=filled
91 The pickup library receive the book, it checks it in P =0, F=W, I=filled
92 The patron borrow the book P =0, F=F, I=filled
98 our (@ISA, @EXPORT_OK);
115 ModReserveMinusPriority
121 CanReserveBeCanceledFromOpac
122 CancelExpiredReserves
124 AutoUnsuspendReserves
126 IsAvailableForItemLevelRequest
127 ItemsAnyAvailableAndNotRestricted
136 GetReservesControlBranch
142 GetMaxPatronHoldsForRecord
154 branchcode => $branchcode,
155 borrowernumber => $borrowernumber,
156 biblionumber => $biblionumber,
157 priority => $priority,
158 reservation_date => $reservation_date,
159 expiration_date => $expiration_date,
162 itemnumber => $itemnumber,
164 itemtype => $itemtype,
165 item_group_id => $item_group_id
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};
196 my $item_group_id = $params->{item_group_id};
198 $resdate ||= dt_from_string;
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 )
225 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
226 # Make room in reserves for this if passed a priority
227 $priority = _ShiftPriority( $biblionumber, $priority );
232 # If the reserv had the waiting status, we had the value of the resdate
233 if ( $found && $found eq 'W' ) {
234 $waitingdate = $resdate;
237 # Don't add itemtype limit if specific item is selected
238 $itemtype = undef if $checkitem;
240 # updates take place here
241 my $hold = Koha::Hold->new(
243 borrowernumber => $borrowernumber,
244 biblionumber => $biblionumber,
245 item_group_id => $item_group_id,
246 reservedate => $resdate,
247 branchcode => $branch,
248 priority => $priority,
249 reservenotes => $notes,
250 itemnumber => $checkitem,
252 waitingdate => $waitingdate,
253 patron_expiration_date => $patron_expiration_date,
254 itemtype => $itemtype,
255 item_level_hold => $checkitem ? 1 : 0,
256 non_priority => $non_priority ? 1 : 0,
259 $hold->set_waiting() if $found && $found eq 'W';
261 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
262 if C4::Context->preference('HoldsLog');
264 my $reserve_id = $hold->id();
266 # add a reserve fee if needed
267 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
268 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
269 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
272 _FixPriority({ biblionumber => $biblionumber});
274 # Send e-mail to librarian if syspref is active
275 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
276 my $patron = Koha::Patrons->find( $borrowernumber );
277 my $library = $patron->library;
278 if ( my $letter = C4::Letters::GetPreparedLetter (
279 module => 'reserves',
280 letter_code => 'HOLDPLACED',
281 branchcode => $branch,
282 lang => $patron->lang,
284 'branches' => $library->unblessed,
285 'borrowers' => $patron->unblessed,
286 'biblio' => $biblionumber,
287 'biblioitems' => $biblionumber,
288 'items' => $checkitem,
289 'reserves' => $hold->unblessed,
293 my $branch_email_address = $library->inbound_email_address;
295 C4::Letters::EnqueueLetter(
298 borrowernumber => $borrowernumber,
299 message_transport_type => 'email',
300 to_address => $branch_email_address,
306 Koha::Plugins->call('after_hold_create', $hold);
311 payload => { hold => $hold->get_from_storage }
315 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
317 biblio_ids => [ $biblionumber ]
319 ) if C4::Context->preference('RealTimeHoldsQueue');
324 =head2 CanBookBeReserved
326 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
327 if ($canReserve eq 'OK') { #We can reserve this Item! }
329 $params are passed directly through to CanItemBeReserved
331 See CanItemBeReserved() for possible return values.
335 sub CanBookBeReserved{
336 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
338 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
339 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
340 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
341 return { status =>'alreadypossession' };
344 if ( $params->{itemtype} ) {
346 # biblio-level, item type-contrained
347 my $patron = Koha::Patrons->find($borrowernumber);
348 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
350 itemtype => $params->{itemtype},
351 categorycode => $patron->categorycode,
352 branchcode => $pickup_branchcode,
353 rule_name => 'reservesallowed',
357 $reservesallowed = ( $reservesallowed eq '' ) ? undef : $reservesallowed;
359 my $count = $patron->holds->search(
362 { 'me.itemtype' => $params->{itemtype} },
363 { 'item.itype' => $params->{itemtype} }
371 return { status => '' }
372 if defined $reservesallowed and $reservesallowed < $count + 1;
376 #get items linked via host records
377 my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
378 if (@hostitemnumbers){
379 $items = Koha::Items->search({
381 biblionumber => $biblionumber,
382 itemnumber => { -in => @hostitemnumbers }
386 $items = Koha::Items->search({ biblionumber => $biblionumber});
389 my $canReserve = { status => '' };
390 my $patron = Koha::Patrons->find( $borrowernumber );
391 while ( my $item = $items->next ) {
392 $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
393 return { status => 'OK' } if $canReserve->{status} eq 'OK';
398 =head2 CanItemBeReserved
400 $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
401 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
404 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
405 should not check if there are too many holds as we only care about reservability
407 @RETURNS { status => OK }, if the Item can be reserved.
408 { status => ageRestricted }, if the Item is age restricted for this borrower.
409 { status => damaged }, if the Item is damaged.
410 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
411 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
412 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
413 { status => notReservable }, if holds on this item are not allowed
414 { status => libraryNotFound }, if given branchcode is not an existing library
415 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
416 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
417 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
418 { status => recall }, if the borrower has already placed a recall on this item
422 sub CanItemBeReserved {
423 my ( $patron, $item, $pickup_branchcode, $params ) = @_;
425 my $dbh = C4::Context->dbh;
426 my $ruleitemtype; # itemtype of the matching issuing rule
427 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
429 # We check item branch if IndependentBranches is ON
430 # and canreservefromotherbranches is OFF
431 if ( C4::Context->preference('IndependentBranches')
432 and !C4::Context->preference('canreservefromotherbranches') )
434 if ( $item->homebranch ne $patron->branchcode ) {
435 return { status => 'cannotReserveFromOtherBranches' };
439 # we retrieve borrowers and items informations #
440 # item->{itype} will come for biblioitems if necessery
441 my $borrower = $patron->unblessed;
443 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
444 return { status =>'damaged' }
446 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
448 if( GetMarcFromKohaField('biblioitems.agerestriction') ){
449 my $biblio = $item->biblio;
450 # Check for the age restriction
451 my ( $ageRestriction, $daysToAgeRestriction ) =
452 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
453 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
456 # Check that the patron doesn't have an item level hold on this item already
457 return { status =>'itemAlreadyOnHold' }
458 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
460 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
461 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
462 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
463 return { status =>'alreadypossession' };
466 # check if a recall exists on this item from this borrower
467 return { status => 'recall' }
468 if $patron->recalls->filter_by_current->search({ item_id => $item->itemnumber })->count;
470 my $controlbranch = C4::Context->preference('ReservesControlBranch');
472 my $reserves_control_branch;
473 my $branchfield = "reserves.branchcode";
475 if ( $controlbranch eq "ItemHomeLibrary" ) {
476 $branchfield = "items.homebranch";
477 $reserves_control_branch = $item->homebranch;
479 elsif ( $controlbranch eq "PatronLibrary" ) {
480 $branchfield = "borrowers.branchcode";
481 $reserves_control_branch = $borrower->{branchcode};
486 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
487 itemtype => $item->effective_itemtype,
488 categorycode => $borrower->{categorycode},
489 branchcode => $reserves_control_branch,
490 rule_name => 'reservesallowed',
493 $ruleitemtype = $reservesallowed->itemtype;
494 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
497 $ruleitemtype = undef;
500 my $rights = Koha::CirculationRules->get_effective_rules({
501 categorycode => $borrower->{'categorycode'},
502 itemtype => $item->effective_itemtype,
503 branchcode => $reserves_control_branch,
504 rules => ['holds_per_record','holds_per_day']
506 my $holds_per_record = $rights->{holds_per_record} // 1;
507 my $holds_per_day = $rights->{holds_per_day};
509 if ( defined $holds_per_record && $holds_per_record ne '' ){
510 if ( $holds_per_record == 0 ) {
511 return { status => "noReservesAllowed" };
513 if ( !$params->{ignore_hold_counts} ) {
514 my $search_params = {
515 borrowernumber => $patron->borrowernumber,
516 biblionumber => $item->biblionumber,
518 my $holds = Koha::Holds->search($search_params);
519 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record;
523 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '')
525 my $today_holds = Koha::Holds->search({
526 borrowernumber => $patron->borrowernumber,
527 reservedate => dt_from_string->date
529 return { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day;
532 # we check if it's ok or not
533 if ( defined $allowedreserves && $allowedreserves ne '' ){
534 if( $allowedreserves == 0 ){
535 return { status => 'noReservesAllowed' };
537 if ( !$params->{ignore_hold_counts} ) {
540 SELECT count(*) AS count
542 LEFT JOIN items USING (itemnumber)
543 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
544 LEFT JOIN borrowers USING (borrowernumber)
545 WHERE borrowernumber = ?
547 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
549 # If using item-level itypes, fall back to the record
550 # level itemtype if the hold has no associated item
551 if ( defined $ruleitemtype ) {
552 if ( C4::Context->preference('item-level_itypes') ) {
554 AND ( COALESCE( items.itype, biblioitems.itemtype ) = ?
555 OR reserves.itemtype = ? )
560 AND ( biblioitems.itemtype = ?
561 OR reserves.itemtype = ? )
566 my $sthcount = $dbh->prepare($querycount);
568 if ( defined $ruleitemtype ) {
569 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype, $ruleitemtype );
572 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch );
575 my $reservecount = "0";
576 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
577 $reservecount = $rowcount->{count};
580 return { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves;
584 # Now we need to check hold limits by patron category
585 my $rule = Koha::CirculationRules->get_effective_rule(
587 categorycode => $patron->categorycode,
588 branchcode => $reserves_control_branch,
589 rule_name => 'max_holds',
592 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
593 my $total_holds_count = Koha::Holds->search(
595 borrowernumber => $patron->borrowernumber
599 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
603 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
605 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
606 return { status => 'notReservable' };
609 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
610 && $borrower->{branchcode} ne $item->homebranch )
612 return { status => 'cannotReserveFromOtherBranches' };
615 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
616 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
617 if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
618 return { status => 'branchNotInHoldGroup' };
622 if ($pickup_branchcode) {
623 my $destination = Koha::Libraries->find({
624 branchcode => $pickup_branchcode,
627 unless ($destination) {
628 return { status => 'libraryNotFound' };
630 unless ($destination->pickup_location) {
631 return { status => 'libraryNotPickupLocation' };
633 unless ($item->can_be_transferred({ to => $destination })) {
634 return { status => 'cannotBeTransferred' };
636 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
637 return { status => 'pickupNotInHoldGroup' };
639 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
640 return { status => 'pickupNotInHoldGroup' };
644 return { status => 'OK' };
647 =head2 CanReserveBeCanceledFromOpac
649 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
651 returns 1 if reserve can be cancelled by user from OPAC.
652 First check if reserve belongs to user, next checks if reserve is not in
653 transfer or waiting status
657 sub CanReserveBeCanceledFromOpac {
658 my ($reserve_id, $borrowernumber) = @_;
660 return unless $reserve_id and $borrowernumber;
661 my $reserve = Koha::Holds->find($reserve_id) or return;
663 return 0 unless $reserve->borrowernumber == $borrowernumber;
664 return $reserve->is_cancelable_from_opac;
667 =head2 GetOtherReserves
669 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
671 Check queued list of this document and check if this document must be transferred
675 sub GetOtherReserves {
676 my ($itemnumber) = @_;
679 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
680 if ($checkreserves) {
681 my $item = Koha::Items->find($itemnumber);
682 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
683 $messages->{'transfert'} = $checkreserves->{'branchcode'};
684 #minus priorities of others reservs
685 ModReserveMinusPriority(
687 $checkreserves->{'reserve_id'},
690 #launch the subroutine dotransfer
691 C4::Items::ModItemTransfer(
693 $item->holdingbranch,
694 $checkreserves->{'branchcode'},
700 #step 2b : case of a reservation on the same branch, set the waiting status
702 $messages->{'waiting'} = 1;
703 ModReserveMinusPriority(
705 $checkreserves->{'reserve_id'},
707 ModReserveStatus($itemnumber,'W');
710 $nextreservinfo = $checkreserves;
713 return ( $messages, $nextreservinfo );
716 =head2 ChargeReserveFee
718 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
720 Charge the fee for a reserve (if $fee > 0)
724 sub ChargeReserveFee {
725 my ( $borrowernumber, $fee, $title ) = @_;
726 return if !$fee || $fee == 0; # the last test is needed to include 0.00
727 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
730 description => $title,
732 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
733 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
734 interface => C4::Context->interface,
735 invoice_type => undef,
744 $fee = GetReserveFee( $borrowernumber, $biblionumber );
746 Calculate the fee for a reserve (if applicable).
751 my ( $borrowernumber, $biblionumber ) = @_;
753 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
756 SELECT COUNT(*) FROM items
757 LEFT JOIN issues USING (itemnumber)
758 WHERE items.biblionumber=? AND issues.issue_id IS NULL
761 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
764 my $dbh = C4::Context->dbh;
765 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
767 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
768 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
769 # This is a reconstruction of the old code:
770 # Compare number of items with items issued, and optionally check holds
771 # If not all items are issued and there are no holds: charge no fee
772 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
773 my ( $notissued, $reserved );
774 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
776 if( $notissued == 0 ) {
777 # all items are issued
778 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
779 ( $biblionumber, $borrowernumber ) );
780 $fee = 0 if $reserved == 0;
788 =head2 GetReserveStatus
790 $reservestatus = GetReserveStatus($itemnumber);
792 Takes an itemnumber and returns the status of the reserve placed on it.
793 If several reserves exist, the reserve with the lower priority is given.
797 ## FIXME: I don't think this does what it thinks it does.
798 ## It only ever checks the first reserve result, even though
799 ## multiple reserves for that bib can have the itemnumber set
800 ## the sub is only used once in the codebase.
801 sub GetReserveStatus {
802 my ($itemnumber) = @_;
804 my $dbh = C4::Context->dbh;
806 my ($sth, $found, $priority);
808 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
809 $sth->execute($itemnumber);
810 ($found, $priority) = $sth->fetchrow_array;
814 return 'Waiting' if $found eq 'W' and $priority == 0;
815 return 'Processing' if $found eq 'P';
816 return 'Finished' if $found eq 'F';
819 return 'Reserved' if defined $priority && $priority > 0;
821 return ''; # empty string here will remove need for checking undef, or less log lines
826 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
827 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
828 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
830 Find a book in the reserves.
832 C<$itemnumber> is the book's item number.
833 C<$lookahead> is the number of days to look in advance for future reserves.
835 As I understand it, C<&CheckReserves> looks for the given item in the
836 reserves. If it is found, that's a match, and C<$status> is set to
839 Otherwise, it finds the most important item in the reserves with the
840 same biblio number as this book (I'm not clear on this) and returns it
841 with C<$status> set to C<Reserved>.
843 C<&CheckReserves> returns a two-element list:
845 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
847 C<$reserve> is the reserve item that matched. It is a
848 reference-to-hash whose keys are mostly the fields of the reserves
849 table in the Koha database.
854 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
855 my $dbh = C4::Context->dbh;
858 if (C4::Context->preference('item-level_itypes')){
860 SELECT items.biblionumber,
861 items.biblioitemnumber,
862 itemtypes.notforloan,
863 items.notforloan AS itemnotforloan,
869 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
870 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
875 SELECT items.biblionumber,
876 items.biblioitemnumber,
877 itemtypes.notforloan,
878 items.notforloan AS itemnotforloan,
884 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
885 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
890 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
891 $sth->execute($item);
894 $sth = $dbh->prepare("$select WHERE barcode = ?");
895 $sth->execute($barcode);
897 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
898 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
899 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
901 return unless $itemnumber; # bail if we got nothing.
902 # if item is not for loan it cannot be reserved either.....
903 # except where items.notforloan < 0 : This indicates the item is holdable.
905 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
906 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
908 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
909 return if $dont_trap or $notforloan_per_itemtype;
911 # Find this item in the reserves
912 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
914 # $priority and $highest are used to find the most important item
915 # in the list returned by &_Findgroupreserve. (The lower $priority,
916 # the more important the item.)
917 # $highest is the most important item we've seen so far.
920 if (scalar @reserves) {
921 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
922 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
923 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
925 my $priority = 10000000;
926 foreach my $res (@reserves) {
927 if ($res->{'found'} && $res->{'found'} eq 'W') {
928 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
929 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
930 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
931 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
932 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
936 my $local_hold_match;
938 if ($LocalHoldsPriority) {
939 $patron = Koha::Patrons->find( $res->{borrowernumber} );
940 $item = Koha::Items->find($itemnumber);
942 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
943 my $local_holds_priority_item_branchcode =
944 $item->$LocalHoldsPriorityItemControl;
945 my $local_holds_priority_patron_branchcode =
946 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
948 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
949 ? $patron->branchcode
952 $local_holds_priority_item_branchcode eq
953 $local_holds_priority_patron_branchcode;
957 # See if this item is more important than what we've got so far
958 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
959 $item ||= Koha::Items->find($itemnumber);
960 next if $res->{item_group_id} && ( !$item->item_group || $item->item_group->id != $res->{item_group_id} );
961 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
962 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
963 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
964 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
965 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
966 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
967 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
968 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
969 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
970 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
971 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
972 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
973 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
974 $priority = $res->{'priority'};
976 last if $local_hold_match;
982 # If we get this far, then no exact match was found.
983 # We return the most important (i.e. next) reservation.
985 $highest->{'itemnumber'} = $item;
986 return ( "Reserved", $highest, \@reserves );
992 =head2 CancelExpiredReserves
994 CancelExpiredReserves();
996 Cancels all reserves with an expiration date from before today.
1000 sub CancelExpiredReserves {
1001 my $cancellation_reason = shift;
1002 my $today = dt_from_string();
1003 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
1004 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
1006 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1009 { expirationdate => { '<', $dtf->format_date($today) } },
1010 { patron_expiration_date => { '<' => $dtf->format_date($today) } }
1014 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
1016 # FIXME To move to Koha::Holds->search_expired (?)
1017 my $holds = Koha::Holds->search( $params );
1019 while ( my $hold = $holds->next ) {
1020 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
1022 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
1024 my $cancel_params = {};
1025 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
1026 if ( defined($hold->found) && $hold->found eq 'W' ) {
1027 $cancel_params->{charge_cancel_fee} = 1;
1029 $cancel_params->{autofill} = C4::Context->preference('ExpireReservesAutoFill');
1030 $hold->cancel( $cancel_params );
1034 =head2 AutoUnsuspendReserves
1036 AutoUnsuspendReserves();
1038 Unsuspends all suspended reserves with a suspend_until date from before today.
1042 sub AutoUnsuspendReserves {
1043 my $today = dt_from_string();
1045 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
1047 map { $_->resume() } @holds;
1052 ModReserve({ rank => $rank,
1053 reserve_id => $reserve_id,
1054 branchcode => $branchcode
1055 [, itemnumber => $itemnumber ]
1056 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1059 Change a hold request's priority or cancel it.
1061 C<$rank> specifies the effect of the change. If C<$rank>
1062 is 'n', nothing happens. This corresponds to leaving a
1063 request alone when changing its priority in the holds queue
1066 If C<$rank> is 'del', the hold request is cancelled.
1068 If C<$rank> is an integer greater than zero, the priority of
1069 the request is set to that value. Since priority != 0 means
1070 that the item is not waiting on the hold shelf, setting the
1071 priority to a non-zero value also sets the request's found
1072 status and waiting date to NULL.
1074 If the hold is 'found' (waiting, in-transit, processing) the
1075 only field that can be updated is the expiration date.
1077 The optional C<$itemnumber> parameter is used only when
1078 C<$rank> is a non-zero integer; if supplied, the itemnumber
1079 of the hold request is set accordingly; if omitted, the itemnumber
1082 B<FIXME:> Note that the forgoing can have the effect of causing
1083 item-level hold requests to turn into title-level requests. This
1084 will be fixed once reserves has separate columns for requested
1085 itemnumber and supplying itemnumber.
1090 my ( $params ) = @_;
1092 my $rank = $params->{'rank'};
1093 my $reserve_id = $params->{'reserve_id'};
1094 my $branchcode = $params->{'branchcode'};
1095 my $itemnumber = $params->{'itemnumber'};
1096 my $suspend_until = $params->{'suspend_until'};
1097 my $borrowernumber = $params->{'borrowernumber'};
1098 my $biblionumber = $params->{'biblionumber'};
1099 my $cancellation_reason = $params->{'cancellation_reason'};
1100 my $date = $params->{expirationdate};
1102 return if defined $rank && $rank eq "n";
1104 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1107 unless ( $reserve_id ) {
1108 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1109 return unless $holds->count; # FIXME Should raise an exception
1110 $hold = $holds->next;
1111 $reserve_id = $hold->reserve_id;
1114 $hold ||= Koha::Holds->find($reserve_id);
1116 # FIXME Other calls may fail
1117 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1119 if ( $rank eq "del" ) {
1120 $hold->cancel({ cancellation_reason => $cancellation_reason });
1122 elsif ($hold->found && $hold->priority eq '0' && $date) {
1123 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1124 if C4::Context->preference('HoldsLog');
1126 # The only column that can be updated for a found hold is the expiration date
1127 $hold->expirationdate($date)->store();
1129 elsif ($rank =~ /^\d+/ and $rank > 0) {
1130 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1131 if C4::Context->preference('HoldsLog');
1135 branchcode => $branchcode,
1136 itemnumber => $itemnumber,
1138 waitingdate => undef
1140 if (exists $params->{reservedate}) {
1141 $properties->{reservedate} = $params->{reservedate} || undef;
1143 if (exists $params->{expirationdate}) {
1144 $properties->{expirationdate} = $params->{expirationdate} || undef;
1147 $hold->set($properties)->store();
1149 if ( defined( $suspend_until ) ) {
1150 if ( $suspend_until ) {
1151 $hold->suspend_hold( $suspend_until );
1153 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1154 # If the hold is not suspended, this does nothing.
1155 $hold->set( { suspend_until => undef } )->store();
1159 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1163 =head2 ModReserveStatus
1165 &ModReserveStatus($itemnumber, $newstatus);
1167 Update the reserve status for the active (priority=0) reserve.
1169 $itemnumber is the itemnumber the reserve is on
1171 $newstatus is the new status.
1175 sub ModReserveStatus {
1177 #first : check if we have a reservation for this item .
1178 my ($itemnumber, $newstatus) = @_;
1179 my $dbh = C4::Context->dbh;
1181 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1182 my $sth_set = $dbh->prepare($query);
1183 $sth_set->execute( $newstatus, $itemnumber );
1185 my $item = Koha::Items->find($itemnumber);
1186 if ( $item->location && $item->location eq 'CART'
1187 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1189 CartToShelf( $itemnumber );
1193 =head2 ModReserveAffect
1195 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id, $notify_library);
1197 This function affect an item and a status for a given reserve, either fetched directly
1198 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1199 is given, only first reserve returned is affected, which is ok for anything but
1202 if $transferToDo is not set, then the status is set to "Waiting" as well.
1203 otherwise, a transfer is on the way, and the end of the transfer will
1204 take care of the waiting status
1206 This function also removes any entry of the hold in holds queue table.
1210 sub ModReserveAffect {
1211 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id, $notify_library ) = @_;
1212 my $dbh = C4::Context->dbh;
1214 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1215 # attached to $itemnumber
1216 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1217 $sth->execute($itemnumber);
1218 my ($biblionumber) = $sth->fetchrow;
1220 # get request - need to find out if item is already
1221 # waiting in order to not send duplicate hold filled notifications
1224 # Find hold by id if we have it
1225 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1226 # Find item level hold for this item if there is one
1227 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1228 # Find record level hold if there is no item level hold
1229 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1231 return unless $hold;
1233 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1235 $hold->itemnumber($itemnumber);
1237 if ($transferToDo) {
1238 $hold->set_transfer();
1239 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1240 && C4::Context->interface eq 'sip'
1241 && !$already_on_shelf) {
1242 $hold->set_processing();
1244 $hold->set_waiting($desk_id);
1245 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1246 # Complete transfer if one exists
1247 my $transfer = $hold->item->get_transfer;
1248 $transfer->receive if $transfer;
1251 _koha_notify_hold_changed( $hold ) if $notify_library;
1253 _FixPriority( { biblionumber => $biblionumber } );
1254 my $item = Koha::Items->find($itemnumber);
1255 if ( $item->location && $item->location eq 'CART'
1256 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1257 CartToShelf( $itemnumber );
1260 my $std = $dbh->prepare(q{
1262 FROM tmp_holdsqueue q
1263 INNER JOIN hold_fill_targets t
1264 ON q.borrowernumber = t.borrowernumber
1265 AND q.biblionumber = t.biblionumber
1266 AND q.itemnumber = t.itemnumber
1267 AND q.item_level_request = t.item_level_request
1268 AND q.holdingbranch = t.source_branchcode
1269 WHERE t.reserve_id = ?
1271 $std->execute($hold->reserve_id);
1273 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1274 if C4::Context->preference('HoldsLog');
1279 =head2 ModReserveCancelAll
1281 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1283 function to cancel reserv,check other reserves, and transfer document if it's necessary
1287 sub ModReserveCancelAll {
1290 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1292 #step 1 : cancel the reservation
1293 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1294 return unless $holds->count;
1295 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1297 #step 2 launch the subroutine of the others reserves
1298 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1300 return ( $messages, $nextreservinfo->{borrowernumber} );
1303 =head2 ModReserveMinusPriority
1305 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1307 Reduce the values of queued list
1311 sub ModReserveMinusPriority {
1312 my ( $itemnumber, $reserve_id ) = @_;
1314 #first step update the value of the first person on reserv
1315 my $dbh = C4::Context->dbh;
1318 SET priority = 0 , itemnumber = ?
1319 WHERE reserve_id = ?
1321 my $sth_upd = $dbh->prepare($query);
1322 $sth_upd->execute( $itemnumber, $reserve_id );
1323 # second step update all others reserves
1324 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1327 =head2 IsAvailableForItemLevelRequest
1329 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1331 Checks whether a given item record is available for an
1332 item-level hold request. An item is available if
1334 * it is not lost AND
1335 * it is not damaged AND
1336 * it is not withdrawn AND
1337 * a waiting or in transit reserve is placed on
1338 * does not have a not for loan value > 0
1340 Need to check the issuingrules onshelfholds column,
1341 if this is set items on the shelf can be placed on hold
1343 Note that IsAvailableForItemLevelRequest() does not
1344 check if the staff operator is authorized to place
1345 a request on the item - in particular,
1346 this routine does not check IndependentBranches
1347 and canreservefromotherbranches.
1349 Note also that this subroutine does not checks smart
1350 rules limits for item by reservesallowed/holds_per_record
1351 values, this complemented in calling code with calls and
1352 checks with CanItemBeReserved or CanBookBeReserved.
1356 sub IsAvailableForItemLevelRequest {
1359 my $pickup_branchcode = shift;
1360 # items_any_available is precalculated status passed from request.pl when set of items
1361 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1362 my $items_any_available = shift;
1364 my $dbh = C4::Context->dbh;
1365 # must check the notforloan setting of the itemtype
1366 # FIXME - a lot of places in the code do this
1367 # or something similar - need to be
1369 my $itemtype = $item->effective_itemtype;
1371 unless defined $itemtype;
1372 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1375 $notforloan_per_itemtype ||
1377 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1379 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1381 if ($pickup_branchcode) {
1382 my $destination = Koha::Libraries->find($pickup_branchcode);
1383 return 0 unless $destination;
1384 return 0 unless $destination->pickup_location;
1385 return 0 unless $item->can_be_transferred( { to => $destination } );
1386 my $reserves_control_branch =
1387 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1388 my $branchitemrule =
1389 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1390 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1391 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1394 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1396 if ( $on_shelf_holds == 1 ) {
1398 } elsif ( $on_shelf_holds == 2 ) {
1400 # if we have this param predefined from outer caller sub, we just need
1401 # to return it, so we saving from having loop inside other loop:
1402 return $items_any_available ? 0 : 1
1403 if defined $items_any_available;
1405 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1406 return $any_available ? 0 : 1;
1407 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1408 return $item->notforloan < 0 || $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1412 =head2 ItemsAnyAvailableAndNotRestricted
1414 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1416 This function checks all items for specified biblionumber (numeric) against patron (object)
1417 and returns true (1) if at least one item available for loan/check out/present/not held
1418 and also checks other parameters logic which not restricts item for hold at all (for ex.
1419 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1423 sub ItemsAnyAvailableAndNotRestricted {
1426 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1428 foreach my $i (@items) {
1429 my $reserves_control_branch =
1430 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1431 my $branchitemrule =
1432 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1433 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1435 # we can return (end the loop) when first one found:
1438 || $i->notforloan # items with non-zero notforloan cannot be checked out
1441 || IsItemOnHoldAndFound( $i->id )
1443 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1444 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1445 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1446 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1447 || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1453 =head2 AlterPriority
1455 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1457 This function changes a reserve's priority up, down, to the top, or to the bottom.
1458 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1463 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1465 my $hold = Koha::Holds->find( $reserve_id );
1466 return unless $hold;
1468 if ( $hold->cancellationdate ) {
1469 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1473 if ( $where eq 'up' ) {
1474 return unless $prev_priority;
1475 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1476 } elsif ( $where eq 'down' ) {
1477 return unless $next_priority;
1478 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1479 } elsif ( $where eq 'top' ) {
1480 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1481 } elsif ( $where eq 'bottom' ) {
1482 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1485 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
1487 biblio_ids => [ $hold->biblionumber ]
1489 ) if C4::Context->preference('RealTimeHoldsQueue');
1490 # FIXME Should return the new priority
1493 =head2 ToggleLowestPriority
1495 ToggleLowestPriority( $borrowernumber, $biblionumber );
1497 This function sets the lowestPriority field to true if is false, and false if it is true.
1501 sub ToggleLowestPriority {
1502 my ( $reserve_id ) = @_;
1504 my $dbh = C4::Context->dbh;
1506 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1507 $sth->execute( $reserve_id );
1509 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1512 =head2 ToggleSuspend
1514 ToggleSuspend( $reserve_id );
1516 This function sets the suspend field to true if is false, and false if it is true.
1517 If the reserve is currently suspended with a suspend_until date, that date will
1518 be cleared when it is unsuspended.
1523 my ( $reserve_id, $suspend_until ) = @_;
1525 my $hold = Koha::Holds->find( $reserve_id );
1527 if ( $hold->is_suspended ) {
1530 $hold->suspend_hold( $suspend_until );
1537 borrowernumber => $borrowernumber,
1538 [ biblionumber => $biblionumber, ]
1539 [ suspend_until => $suspend_until, ]
1540 [ suspend => $suspend ]
1543 This function accepts a set of hash keys as its parameters.
1544 It requires either borrowernumber or biblionumber, or both.
1546 suspend_until is wholly optional.
1553 my $borrowernumber = $params{'borrowernumber'} || undef;
1554 my $biblionumber = $params{'biblionumber'} || undef;
1555 my $suspend_until = $params{'suspend_until'} || undef;
1556 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1558 return unless ( $borrowernumber || $biblionumber );
1561 $params->{found} = undef;
1562 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1563 $params->{biblionumber} = $biblionumber if $biblionumber;
1565 my @holds = Koha::Holds->search($params)->as_list;
1568 map { $_->suspend_hold($suspend_until) } @holds;
1571 map { $_->resume() } @holds;
1579 reserve_id => $reserve_id,
1581 [ignoreSetLowestRank => $ignoreSetLowestRank]
1586 _FixPriority({ biblionumber => $biblionumber});
1588 This routine adjusts the priority of a hold request and holds
1591 In the first form, where a reserve_id is passed, the priority of the
1592 hold is set to supplied rank, and other holds for that bib are adjusted
1593 accordingly. If the rank is "del", the hold is cancelled. If no rank
1594 is supplied, all of the holds on that bib have their priority adjusted
1595 as if the second form had been used.
1597 In the second form, where a biblionumber is passed, the holds on that
1598 bib (that are not captured) are sorted in order of increasing priority,
1599 then have reserves.priority set so that the first non-captured hold
1600 has its priority set to 1, the second non-captured hold has its priority
1601 set to 2, and so forth.
1603 In both cases, holds that have the lowestPriority flag on are have their
1604 priority adjusted to ensure that they remain at the end of the line.
1606 Note that the ignoreSetLowestRank parameter is meant to be used only
1607 when _FixPriority calls itself.
1612 my ( $params ) = @_;
1613 my $reserve_id = $params->{reserve_id};
1614 my $rank = $params->{rank} // '';
1615 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1616 my $biblionumber = $params->{biblionumber};
1618 my $dbh = C4::Context->dbh;
1621 if ( $reserve_id ) {
1622 $hold = Koha::Holds->find( $reserve_id );
1623 if (!defined $hold){
1624 # may have already been checked out and hold fulfilled
1625 $hold = Koha::Old::Holds->find( $reserve_id );
1627 return unless $hold;
1630 unless ( $biblionumber ) { # FIXME This is a very weird API
1631 $biblionumber = $hold->biblionumber;
1634 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1637 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1639 # make sure priority for waiting or in-transit items is 0
1643 WHERE reserve_id = ?
1644 AND found IN ('W', 'T', 'P')
1646 my $sth = $dbh->prepare($query);
1647 $sth->execute( $reserve_id );
1653 SELECT reserve_id, borrowernumber, reservedate
1655 WHERE biblionumber = ?
1656 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1657 ORDER BY priority ASC
1659 my $sth = $dbh->prepare($query);
1660 $sth->execute( $biblionumber );
1661 while ( my $line = $sth->fetchrow_hashref ) {
1662 push( @priority, $line );
1665 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1666 # To find the matching index
1668 my $key = -1; # to allow for 0 to be a valid result
1669 for ( $i = 0 ; $i < @priority ; $i++ ) {
1670 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1671 $key = $i; # save the index
1676 # if index exists in array then move it to new position
1677 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1678 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1679 my $moving_item = splice( @priority, $key, 1 );
1680 $new_rank = scalar @priority if $new_rank > scalar @priority;
1681 splice( @priority, $new_rank, 0, $moving_item );
1684 # now fix the priority on those that are left....
1688 WHERE reserve_id = ?
1690 $sth = $dbh->prepare($query);
1691 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1694 $priority[$j]->{'reserve_id'}
1698 unless ( $ignoreSetLowestRank ) {
1699 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1700 $sth->execute($biblionumber);
1701 while ( my $res = $sth->fetchrow_hashref() ) {
1703 reserve_id => $res->{'reserve_id'},
1705 ignoreSetLowestRank => 1
1711 =head2 _Findgroupreserve
1713 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1715 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1716 first match found. If neither, then we look for non-holds-queue based holds.
1717 Lookahead is the number of days to look in advance.
1719 C<&_Findgroupreserve> returns :
1720 C<@results> is an array of references-to-hash whose keys are mostly
1721 fields from the reserves table of the Koha database, plus
1722 C<biblioitemnumber>.
1724 This routine with either return:
1725 1 - Item specific holds from the holds queue
1726 2 - Title level holds from the holds queue
1727 3 - All holds for this biblionumber
1729 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1733 sub _Findgroupreserve {
1734 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1735 my $dbh = C4::Context->dbh;
1737 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1738 # check for exact targeted match
1739 my $item_level_target_query = qq{
1740 SELECT reserves.biblionumber AS biblionumber,
1741 reserves.borrowernumber AS borrowernumber,
1742 reserves.reservedate AS reservedate,
1743 reserves.branchcode AS branchcode,
1744 reserves.cancellationdate AS cancellationdate,
1745 reserves.found AS found,
1746 reserves.reservenotes AS reservenotes,
1747 reserves.priority AS priority,
1748 reserves.timestamp AS timestamp,
1749 biblioitems.biblioitemnumber AS biblioitemnumber,
1750 reserves.itemnumber AS itemnumber,
1751 reserves.reserve_id AS reserve_id,
1752 reserves.itemtype AS itemtype,
1753 reserves.non_priority AS non_priority,
1754 reserves.item_group_id AS item_group_id
1756 JOIN biblioitems USING (biblionumber)
1757 JOIN hold_fill_targets USING (reserve_id)
1760 AND item_level_request = 1
1761 AND hold_fill_targets.itemnumber = ?
1762 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1766 my $sth = $dbh->prepare($item_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;
1775 # check for title-level targeted match
1776 my $title_level_target_query = qq{
1777 SELECT reserves.biblionumber AS biblionumber,
1778 reserves.borrowernumber AS borrowernumber,
1779 reserves.reservedate AS reservedate,
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 biblioitems.biblioitemnumber AS biblioitemnumber,
1787 reserves.itemnumber AS itemnumber,
1788 reserves.reserve_id AS reserve_id,
1789 reserves.itemtype AS itemtype,
1790 reserves.non_priority AS non_priority,
1791 reserves.item_group_id AS item_group_id
1793 JOIN biblioitems USING (biblionumber)
1794 JOIN hold_fill_targets USING (reserve_id)
1795 LEFT JOIN item_group_items ON ( item_group_items.item_id = hold_fill_targets.itemnumber )
1798 AND item_level_request = 0
1799 AND hold_fill_targets.itemnumber = ?
1800 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1802 AND reserves.item_group_id = item_group_items.item_group_id
1805 $sth = $dbh->prepare($title_level_target_query);
1806 $sth->execute($itemnumber, $lookahead||0);
1808 if ( my $data = $sth->fetchrow_hashref ) {
1809 push( @results, $data )
1810 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1812 return @results if @results;
1815 SELECT reserves.biblionumber AS biblionumber,
1816 reserves.borrowernumber AS borrowernumber,
1817 reserves.reservedate AS reservedate,
1818 reserves.waitingdate AS waitingdate,
1819 reserves.branchcode AS branchcode,
1820 reserves.cancellationdate AS cancellationdate,
1821 reserves.found AS found,
1822 reserves.reservenotes AS reservenotes,
1823 reserves.priority AS priority,
1824 reserves.timestamp AS timestamp,
1825 reserves.itemnumber AS itemnumber,
1826 reserves.reserve_id AS reserve_id,
1827 reserves.itemtype AS itemtype,
1828 reserves.non_priority AS non_priority,
1829 reserves.item_group_id AS item_group_id
1831 WHERE reserves.biblionumber = ?
1832 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1833 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1837 $sth = $dbh->prepare($query);
1838 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1840 while ( my $data = $sth->fetchrow_hashref ) {
1841 push( @results, $data )
1842 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1847 =head2 _koha_notify_reserve
1849 _koha_notify_reserve( $hold->reserve_id );
1851 Sends a notification to the patron that their hold has been filled (through
1854 The letter code for this notice may be found using the following query:
1856 select distinct letter_code
1857 from message_transports
1858 inner join message_attributes using (message_attribute_id)
1859 where message_name = 'Hold_Filled'
1861 This will probably sipmly be 'HOLD', but because it is defined in the database,
1862 it is subject to addition or change.
1864 The following tables are availalbe witin the notice:
1875 sub _koha_notify_reserve {
1876 my $reserve_id = shift;
1878 my $hold = Koha::Holds->find($reserve_id);
1879 my $borrowernumber = $hold->borrowernumber;
1881 my $patron = Koha::Patrons->find( $borrowernumber );
1883 # Try to get the borrower's email address
1884 my $to_address = $patron->notice_email_address;
1886 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1887 borrowernumber => $borrowernumber,
1888 message_name => 'Hold_Filled'
1891 my $library = Koha::Libraries->find( $hold->branchcode );
1892 my $from_email_address = $library->from_email_address;
1894 my %letter_params = (
1895 module => 'reserves',
1896 branchcode => $hold->branchcode,
1897 lang => $patron->lang,
1899 'branches' => $library->unblessed,
1900 'borrowers' => $patron->unblessed,
1901 'biblio' => $hold->biblionumber,
1902 'biblioitems' => $hold->biblionumber,
1903 'reserves' => $hold->unblessed,
1904 'items' => $hold->itemnumber,
1908 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.
1909 my $send_notification = sub {
1910 my ( $mtt, $letter_code ) = (@_);
1911 return unless defined $letter_code;
1912 $letter_params{letter_code} = $letter_code;
1913 $letter_params{message_transport_type} = $mtt;
1914 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1916 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1920 C4::Letters::EnqueueLetter( {
1922 borrowernumber => $borrowernumber,
1923 from_address => $from_email_address,
1924 message_transport_type => $mtt,
1928 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1930 ( $mtt eq 'email' and not $to_address ) # No email address
1931 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1932 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1933 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1936 &$send_notification($mtt, $letter_code);
1937 $notification_sent++;
1939 #Making sure that a print notification is sent if no other transport types can be utilized.
1940 if (! $notification_sent) {
1941 &$send_notification('print', 'HOLD');
1946 =head2 _koha_notify_hold_changed
1948 _koha_notify_hold_changed( $hold_object );
1952 sub _koha_notify_hold_changed {
1955 my $patron = $hold->patron;
1956 my $library = $hold->branch;
1958 my $letter = C4::Letters::GetPreparedLetter(
1959 module => 'reserves',
1960 letter_code => 'HOLD_CHANGED',
1961 branchcode => $hold->branchcode,
1962 substitute => { today => output_pref( dt_from_string ) },
1964 'branches' => $library->unblessed,
1965 'borrowers' => $patron->unblessed,
1966 'biblio' => $hold->biblionumber,
1967 'biblioitems' => $hold->biblionumber,
1968 'reserves' => $hold->unblessed,
1969 'items' => $hold->itemnumber,
1973 return unless $letter;
1976 C4::Context->preference('ExpireReservesAutoFillEmail')
1977 || $library->inbound_email_address;
1979 C4::Letters::EnqueueLetter(
1982 borrowernumber => $patron->id,
1983 message_transport_type => 'email',
1984 from_address => $library->from_email_address,
1985 to_address => $email,
1990 =head2 _ShiftPriority
1992 $new_priority = _ShiftPriority( $biblionumber, $priority );
1994 This increments the priority of all reserves after the one
1995 with either the lowest date after C<$reservedate>
1996 or the lowest priority after C<$priority>.
1998 It effectively makes room for a new reserve to be inserted with a certain
1999 priority, which is returned.
2001 This is most useful when the reservedate can be set by the user. It allows
2002 the new reserve to be placed before other reserves that have a later
2003 reservedate. Since priority also is set by the form in reserves/request.pl
2004 the sub accounts for that too.
2008 sub _ShiftPriority {
2009 my ( $biblio, $new_priority ) = @_;
2011 my $dbh = C4::Context->dbh;
2012 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND priority > ? ORDER BY priority ASC LIMIT 1";
2013 my $sth = $dbh->prepare( $query );
2014 $sth->execute( $biblio, $new_priority );
2015 my $min_priority = $sth->fetchrow;
2016 # if no such matches are found, $new_priority remains as original value
2017 $new_priority = $min_priority if ( $min_priority );
2019 # Shift the priority up by one; works in conjunction with the next SQL statement
2020 $query = "UPDATE reserves
2021 SET priority = priority+1
2022 WHERE biblionumber = ?
2023 AND borrowernumber = ?
2026 my $sth_update = $dbh->prepare( $query );
2028 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2029 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2030 $sth = $dbh->prepare( $query );
2031 $sth->execute( $new_priority, $biblio );
2032 while ( my $row = $sth->fetchrow_hashref ) {
2033 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2036 return $new_priority; # so the caller knows what priority they wind up receiving
2041 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2043 Use when checking out an item to handle reserves
2044 If $cancelreserve boolean is set to true, it will remove existing reserve
2049 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2051 $cancelreserve //= 0;
2053 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2054 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
2057 my $biblionumber = $res->{biblionumber};
2059 if ($res->{borrowernumber} == $borrowernumber) {
2060 my $hold = Koha::Holds->find( $res->{reserve_id} );
2061 $hold->fill({ item_id => $itemnumber });
2065 # The item is reserved by someone else.
2066 # Find this item in the reserves
2068 my $borr_res = Koha::Holds->search({
2069 borrowernumber => $borrowernumber,
2070 biblionumber => $biblionumber,
2072 order_by => 'priority'
2076 # The item is reserved by the current patron
2077 $borr_res->fill({ item_id => $itemnumber });
2080 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2081 RevertWaitingStatus({ itemnumber => $itemnumber });
2083 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2084 my $hold = Koha::Holds->find( $res->{reserve_id} );
2092 MergeHolds($dbh,$to_biblio, $from_biblio);
2094 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2099 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2100 my $sth = $dbh->prepare(
2101 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2103 $sth->execute($from_biblio);
2104 if ( my $data = $sth->fetchrow_hashref() ) {
2106 # holds exist on old record, if not we don't need to do anything
2107 $sth = $dbh->prepare(
2108 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2109 $sth->execute( $to_biblio, $from_biblio );
2112 # don't reorder those already waiting
2114 $sth = $dbh->prepare(
2115 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2117 my $upd_sth = $dbh->prepare(
2118 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2119 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2121 $sth->execute( $to_biblio );
2123 while ( my $reserve = $sth->fetchrow_hashref() ) {
2125 $priority, $to_biblio,
2126 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2127 $reserve->{'itemnumber'}
2134 =head2 RevertWaitingStatus
2136 RevertWaitingStatus({ itemnumber => $itemnumber });
2138 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2140 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2141 item level hold, even if it was only a bibliolevel hold to
2142 begin with. This is because we can no longer know if a hold
2143 was item-level or bib-level after a hold has been set to
2148 sub RevertWaitingStatus {
2149 my ( $params ) = @_;
2150 my $itemnumber = $params->{'itemnumber'};
2152 return unless ( $itemnumber );
2154 my $dbh = C4::Context->dbh;
2156 ## Get the waiting reserve we want to revert
2157 my $hold = Koha::Holds->search(
2159 itemnumber => $itemnumber,
2160 found => { not => undef },
2164 ## Increment the priority of all other non-waiting
2165 ## reserves for this bib record
2166 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2167 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2169 ## Fix up the currently waiting reserve
2174 waitingdate => undef,
2175 expirationdate => $hold->patron_expiration_date,
2176 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2180 _FixPriority( { biblionumber => $hold->biblionumber } );
2182 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
2184 biblio_ids => [ $hold->biblionumber ]
2186 ) if C4::Context->preference('RealTimeHoldsQueue');
2196 branchcode => $branchcode,
2197 borrowernumber => $borrowernumber,
2198 biblionumber => $biblionumber,
2199 [ itemnumber => $itemnumber, ]
2200 [ barcode => $barcode, ]
2204 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2206 The letter code will be HOLD_SLIP, and the following tables are
2207 available within the slip:
2220 my $branchcode = $args->{branchcode};
2221 my $reserve_id = $args->{reserve_id};
2223 my $hold = Koha::Holds->find($reserve_id);
2224 return unless $hold;
2226 my $patron = $hold->borrower;
2227 my $reserve = $hold->unblessed;
2229 return C4::Letters::GetPreparedLetter (
2230 module => 'circulation',
2231 letter_code => 'HOLD_SLIP',
2232 branchcode => $branchcode,
2233 lang => $patron->lang,
2235 'reserves' => $reserve,
2236 'branches' => $reserve->{branchcode},
2237 'borrowers' => $reserve->{borrowernumber},
2238 'biblio' => $reserve->{biblionumber},
2239 'biblioitems' => $reserve->{biblionumber},
2240 'items' => $reserve->{itemnumber},
2245 =head2 GetReservesControlBranch
2247 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2249 Return the branchcode to be used to determine which reserves
2250 policy applies to a transaction.
2252 C<$item> is a hashref for an item. Only 'homebranch' is used.
2254 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2258 sub GetReservesControlBranch {
2259 my ( $item, $borrower ) = @_;
2261 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2264 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2265 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2271 =head2 CalculatePriority
2273 my $p = CalculatePriority($biblionumber, $resdate);
2275 Calculate priority for a new reserve on biblionumber, placing it at
2276 the end of the line of all holds whose start date falls before
2277 the current system time and that are neither on the hold shelf
2280 The reserve date parameter is optional; if it is supplied, the
2281 priority is based on the set of holds whose start date falls before
2282 the parameter value.
2284 After calculation of this priority, it is recommended to call
2285 _ShiftPriority. Note that this is currently done in
2290 sub CalculatePriority {
2291 my ( $biblionumber, $resdate ) = @_;
2294 SELECT COUNT(*) FROM reserves
2295 WHERE biblionumber = ?
2297 AND (found IS NULL OR found = '')
2299 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2301 $sql.= ' AND ( reservedate <= ? )';
2304 $sql.= ' AND ( reservedate < NOW() )';
2306 my $dbh = C4::Context->dbh();
2307 my @row = $dbh->selectrow_array(
2310 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2313 return @row ? $row[0]+1 : 1;
2316 =head2 IsItemOnHoldAndFound
2318 my $bool = IsItemFoundHold( $itemnumber );
2320 Returns true if the item is currently on hold
2321 and that hold has a non-null found status ( W, T, etc. )
2325 sub IsItemOnHoldAndFound {
2326 my ($itemnumber) = @_;
2328 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2330 my $found = $rs->count(
2332 itemnumber => $itemnumber,
2333 found => { '!=' => undef }
2340 =head2 GetMaxPatronHoldsForRecord
2342 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2344 For multiple holds on a given record for a given patron, the max
2345 number of record level holds that a patron can be placed is the highest
2346 value of the holds_per_record rule for each item if the record for that
2347 patron. This subroutine finds and returns the highest holds_per_record
2348 rule value for a given patron id and record id.
2352 sub GetMaxPatronHoldsForRecord {
2353 my ( $borrowernumber, $biblionumber ) = @_;
2355 my $patron = Koha::Patrons->find($borrowernumber);
2356 my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2358 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2360 my $categorycode = $patron->categorycode;
2362 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2365 foreach my $item (@items) {
2366 my $itemtype = $item->effective_itemtype();
2368 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2370 my $rule = Koha::CirculationRules->get_effective_rule({
2371 categorycode => $categorycode,
2372 itemtype => $itemtype,
2373 branchcode => $branchcode,
2374 rule_name => 'holds_per_record'
2376 my $holds_per_record = $rule ? $rule->rule_value : 0;
2377 $max = $holds_per_record if $holds_per_record > $max;
2385 Koha Development Team <http://koha-community.org/>