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;
38 use Koha::CirculationRules;
40 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);
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 $expdate = $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 $expdate = output_pref({ str => $expdate, 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 )
227 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
228 # Make room in reserves for this if passed a priority
229 $priority = _ShiftPriority( $biblionumber, $priority );
234 # If the reserv had the waiting status, we had the value of the resdate
235 if ( $found && $found eq 'W' ) {
236 $waitingdate = $resdate;
239 # Don't add itemtype limit if specific item is selected
240 $itemtype = undef if $checkitem;
242 # updates take place here
243 my $hold = Koha::Hold->new(
245 borrowernumber => $borrowernumber,
246 biblionumber => $biblionumber,
247 reservedate => $resdate,
248 branchcode => $branch,
249 priority => $priority,
250 reservenotes => $notes,
251 itemnumber => $checkitem,
253 waitingdate => $waitingdate,
254 expirationdate => $expdate,
255 itemtype => $itemtype,
256 item_level_hold => $checkitem ? 1 : 0,
257 non_priority => $non_priority ? 1 : 0,
260 $hold->set_waiting() if $found && $found eq 'W';
262 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
263 if C4::Context->preference('HoldsLog');
265 my $reserve_id = $hold->id();
267 # add a reserve fee if needed
268 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
269 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
270 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
273 _FixPriority({ biblionumber => $biblionumber});
275 # Send e-mail to librarian if syspref is active
276 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
277 my $patron = Koha::Patrons->find( $borrowernumber );
278 my $library = $patron->library;
279 if ( my $letter = C4::Letters::GetPreparedLetter (
280 module => 'reserves',
281 letter_code => 'HOLDPLACED',
282 branchcode => $branch,
283 lang => $patron->lang,
285 'branches' => $library->unblessed,
286 'borrowers' => $patron->unblessed,
287 'biblio' => $biblionumber,
288 'biblioitems' => $biblionumber,
289 'items' => $checkitem,
290 'reserves' => $hold->unblessed,
294 my $branch_email_address = $library->inbound_email_address;
296 C4::Letters::EnqueueLetter(
299 borrowernumber => $borrowernumber,
300 message_transport_type => 'email',
301 to_address => $branch_email_address,
307 Koha::Plugins->call('after_hold_create', $hold);
312 =head2 CanBookBeReserved
314 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
315 if ($canReserve eq 'OK') { #We can reserve this Item! }
317 $params are passed directly through to CanItemBeReserved
319 See CanItemBeReserved() for possible return values.
323 sub CanBookBeReserved{
324 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
326 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
327 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
328 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
329 return { status =>'alreadypossession' };
332 if ( $params->{itemtype} ) {
334 # biblio-level, item type-contrained
335 my $patron = Koha::Patrons->find($borrowernumber);
336 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
338 itemtype => $params->{itemtype},
339 categorycode => $patron->categorycode,
340 branchcode => $pickup_branchcode,
341 rule_name => 'reservesallowed',
345 $reservesallowed = ( $reservesallowed eq '' ) ? undef : $reservesallowed;
347 my $count = $patron->holds->search(
350 { 'me.itemtype' => $params->{itemtype} },
351 { 'item.itype' => $params->{itemtype} }
359 return { status => '' }
360 if defined $reservesallowed and $reservesallowed < $count + 1;
363 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
364 #get items linked via host records
365 my @hostitems = get_hostitemnumbers_of($biblionumber);
367 push (@itemnumbers, @hostitems);
370 my $canReserve = { status => '' };
371 foreach my $itemnumber (@itemnumbers) {
372 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
373 return { status => 'OK' } if $canReserve->{status} eq 'OK';
378 =head2 CanItemBeReserved
380 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
381 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
384 'ignore_found_holds' - if true holds that have been trapped are not counted
385 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
386 current checkout against the high holds threshold
387 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
388 should not check if there are too many holds as we only csre about reservability
390 @RETURNS { status => OK }, if the Item can be reserved.
391 { status => ageRestricted }, if the Item is age restricted for this borrower.
392 { status => damaged }, if the Item is damaged.
393 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
394 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
395 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
396 { status => notReservable }, if holds on this item are not allowed
397 { status => libraryNotFound }, if given branchcode is not an existing library
398 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
399 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
400 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
404 sub CanItemBeReserved {
405 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
407 my $dbh = C4::Context->dbh;
408 my $ruleitemtype; # itemtype of the matching issuing rule
409 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
411 # we retrieve borrowers and items informations #
412 # item->{itype} will come for biblioitems if necessery
413 my $item = Koha::Items->find($itemnumber);
414 my $patron = Koha::Patrons->find( $borrowernumber );
415 my $borrower = $patron->unblessed;
417 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
418 return { status =>'damaged' }
420 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
422 if( GetMarcFromKohaField('biblioitems.agerestriction') ){
423 my $biblio = $item->biblio;
424 # Check for the age restriction
425 my ( $ageRestriction, $daysToAgeRestriction ) =
426 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
427 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
430 # Check that the patron doesn't have an item level hold on this item already
431 return { status =>'itemAlreadyOnHold' }
432 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count() );
434 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
435 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
436 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
437 return { status =>'alreadypossession' };
440 my $controlbranch = C4::Context->preference('ReservesControlBranch');
443 SELECT count(*) AS count
445 LEFT JOIN items USING (itemnumber)
446 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
447 LEFT JOIN borrowers USING (borrowernumber)
448 WHERE borrowernumber = ?
452 my $branchfield = "reserves.branchcode";
454 if ( $controlbranch eq "ItemHomeLibrary" ) {
455 $branchfield = "items.homebranch";
456 $branchcode = $item->homebranch;
458 elsif ( $controlbranch eq "PatronLibrary" ) {
459 $branchfield = "borrowers.branchcode";
460 $branchcode = $borrower->{branchcode};
465 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
466 itemtype => $item->effective_itemtype,
467 categorycode => $borrower->{categorycode},
468 branchcode => $branchcode,
469 rule_name => 'reservesallowed',
472 $ruleitemtype = $reservesallowed->itemtype;
473 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
476 $ruleitemtype = undef;
479 my $rights = Koha::CirculationRules->get_effective_rules({
480 categorycode => $borrower->{'categorycode'},
481 itemtype => $item->effective_itemtype,
482 branchcode => $branchcode,
483 rules => ['holds_per_record','holds_per_day']
485 my $holds_per_record = $rights->{holds_per_record} // 1;
486 my $holds_per_day = $rights->{holds_per_day};
488 my $search_params = {
489 borrowernumber => $borrowernumber,
490 biblionumber => $item->biblionumber,
492 $search_params->{found} = undef if $params->{ignore_found_holds};
494 my $holds = Koha::Holds->search($search_params);
495 if ( defined $holds_per_record && $holds_per_record ne '' ){
496 if ( $holds_per_record == 0 ) {
497 return { status => "noReservesAllowed" };
499 if ( !$params->{ignore_hold_counts} && $holds->count() >= $holds_per_record ) {
500 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
504 my $today_holds = Koha::Holds->search({
505 borrowernumber => $borrowernumber,
506 reservedate => dt_from_string->date
509 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne ''
510 && $today_holds->count() >= $holds_per_day )
512 return { status => 'tooManyReservesToday', limit => $holds_per_day };
517 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
519 # If using item-level itypes, fall back to the record
520 # level itemtype if the hold has no associated item
521 if ( defined $ruleitemtype ) {
522 if ( C4::Context->preference('item-level_itypes') ) {
524 AND ( COALESCE( items.itype, biblioitems.itemtype ) = ?
525 OR reserves.itemtype = ? )
530 AND ( biblioitems.itemtype = ?
531 OR reserves.itemtype = ? )
536 my $sthcount = $dbh->prepare($querycount);
538 if ( defined $ruleitemtype ) {
539 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype, $ruleitemtype );
542 $sthcount->execute( $borrowernumber, $branchcode );
545 my $reservecount = "0";
546 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
547 $reservecount = $rowcount->{count};
550 # we check if it's ok or not
551 if ( defined $allowedreserves && $allowedreserves ne '' ){
552 if( $allowedreserves == 0 ){
553 return { status => 'noReservesAllowed' };
555 if ( !$params->{ignore_hold_counts} && $reservecount >= $allowedreserves ) {
556 return { status => 'tooManyReserves', limit => $allowedreserves };
560 # Now we need to check hold limits by patron category
561 my $rule = Koha::CirculationRules->get_effective_rule(
563 categorycode => $borrower->{categorycode},
564 branchcode => $branchcode,
565 rule_name => 'max_holds',
568 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
569 my $total_holds_count = Koha::Holds->search(
571 borrowernumber => $borrower->{borrowernumber}
575 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
578 my $reserves_control_branch =
579 GetReservesControlBranch( $item->unblessed(), $borrower );
581 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
583 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
584 return { status => 'notReservable' };
587 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
588 && $borrower->{branchcode} ne $item->homebranch )
590 return { status => 'cannotReserveFromOtherBranches' };
593 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
594 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
595 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
596 return { status => 'branchNotInHoldGroup' };
600 # If reservecount is ok, we check item branch if IndependentBranches is ON
601 # and canreservefromotherbranches is OFF
602 if ( C4::Context->preference('IndependentBranches')
603 and !C4::Context->preference('canreservefromotherbranches') )
605 if ( $item->homebranch ne $borrower->{branchcode} ) {
606 return { status => 'cannotReserveFromOtherBranches' };
610 if ($pickup_branchcode) {
611 my $destination = Koha::Libraries->find({
612 branchcode => $pickup_branchcode,
615 unless ($destination) {
616 return { status => 'libraryNotFound' };
618 unless ($destination->pickup_location) {
619 return { status => 'libraryNotPickupLocation' };
621 unless ($item->can_be_transferred({ to => $destination })) {
622 return { status => 'cannotBeTransferred' };
624 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
625 return { status => 'pickupNotInHoldGroup' };
627 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
628 return { status => 'pickupNotInHoldGroup' };
632 return { status => 'OK' };
635 =head2 CanReserveBeCanceledFromOpac
637 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
639 returns 1 if reserve can be cancelled by user from OPAC.
640 First check if reserve belongs to user, next checks if reserve is not in
641 transfer or waiting status
645 sub CanReserveBeCanceledFromOpac {
646 my ($reserve_id, $borrowernumber) = @_;
648 return unless $reserve_id and $borrowernumber;
649 my $reserve = Koha::Holds->find($reserve_id) or return;
651 return 0 unless $reserve->borrowernumber == $borrowernumber;
652 return $reserve->is_cancelable_from_opac;
655 =head2 GetOtherReserves
657 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
659 Check queued list of this document and check if this document must be transferred
663 sub GetOtherReserves {
664 my ($itemnumber) = @_;
667 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
668 if ($checkreserves) {
669 my $item = Koha::Items->find($itemnumber);
670 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
671 $messages->{'transfert'} = $checkreserves->{'branchcode'};
672 #minus priorities of others reservs
673 ModReserveMinusPriority(
675 $checkreserves->{'reserve_id'},
678 #launch the subroutine dotransfer
679 C4::Items::ModItemTransfer(
681 $item->holdingbranch,
682 $checkreserves->{'branchcode'},
688 #step 2b : case of a reservation on the same branch, set the waiting status
690 $messages->{'waiting'} = 1;
691 ModReserveMinusPriority(
693 $checkreserves->{'reserve_id'},
695 ModReserveStatus($itemnumber,'W');
698 $nextreservinfo = $checkreserves;
701 return ( $messages, $nextreservinfo );
704 =head2 ChargeReserveFee
706 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
708 Charge the fee for a reserve (if $fee > 0)
712 sub ChargeReserveFee {
713 my ( $borrowernumber, $fee, $title ) = @_;
714 return if !$fee || $fee == 0; # the last test is needed to include 0.00
715 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
718 description => $title,
720 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
721 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
722 interface => C4::Context->interface,
723 invoice_type => undef,
732 $fee = GetReserveFee( $borrowernumber, $biblionumber );
734 Calculate the fee for a reserve (if applicable).
739 my ( $borrowernumber, $biblionumber ) = @_;
741 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
744 SELECT COUNT(*) FROM items
745 LEFT JOIN issues USING (itemnumber)
746 WHERE items.biblionumber=? AND issues.issue_id IS NULL
749 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
752 my $dbh = C4::Context->dbh;
753 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
754 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
755 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
756 # This is a reconstruction of the old code:
757 # Compare number of items with items issued, and optionally check holds
758 # If not all items are issued and there are no holds: charge no fee
759 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
760 my ( $notissued, $reserved );
761 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
764 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
765 ( $biblionumber, $borrowernumber ) );
766 $fee = 0 if $reserved == 0;
772 =head2 GetReserveStatus
774 $reservestatus = GetReserveStatus($itemnumber);
776 Takes an itemnumber and returns the status of the reserve placed on it.
777 If several reserves exist, the reserve with the lower priority is given.
781 ## FIXME: I don't think this does what it thinks it does.
782 ## It only ever checks the first reserve result, even though
783 ## multiple reserves for that bib can have the itemnumber set
784 ## the sub is only used once in the codebase.
785 sub GetReserveStatus {
786 my ($itemnumber) = @_;
788 my $dbh = C4::Context->dbh;
790 my ($sth, $found, $priority);
792 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
793 $sth->execute($itemnumber);
794 ($found, $priority) = $sth->fetchrow_array;
798 return 'Waiting' if $found eq 'W' and $priority == 0;
799 return 'Processing' if $found eq 'P';
800 return 'Finished' if $found eq 'F';
803 return 'Reserved' if defined $priority && $priority > 0;
805 return ''; # empty string here will remove need for checking undef, or less log lines
810 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
811 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
812 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
814 Find a book in the reserves.
816 C<$itemnumber> is the book's item number.
817 C<$lookahead> is the number of days to look in advance for future reserves.
819 As I understand it, C<&CheckReserves> looks for the given item in the
820 reserves. If it is found, that's a match, and C<$status> is set to
823 Otherwise, it finds the most important item in the reserves with the
824 same biblio number as this book (I'm not clear on this) and returns it
825 with C<$status> set to C<Reserved>.
827 C<&CheckReserves> returns a two-element list:
829 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
831 C<$reserve> is the reserve item that matched. It is a
832 reference-to-hash whose keys are mostly the fields of the reserves
833 table in the Koha database.
838 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
839 my $dbh = C4::Context->dbh;
842 if (C4::Context->preference('item-level_itypes')){
844 SELECT items.biblionumber,
845 items.biblioitemnumber,
846 itemtypes.notforloan,
847 items.notforloan AS itemnotforloan,
853 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
854 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
859 SELECT items.biblionumber,
860 items.biblioitemnumber,
861 itemtypes.notforloan,
862 items.notforloan AS itemnotforloan,
868 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
869 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
874 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
875 $sth->execute($item);
878 $sth = $dbh->prepare("$select WHERE barcode = ?");
879 $sth->execute($barcode);
881 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
882 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
883 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
885 return unless $itemnumber; # bail if we got nothing.
886 # if item is not for loan it cannot be reserved either.....
887 # except where items.notforloan < 0 : This indicates the item is holdable.
889 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
890 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
892 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
893 return if $dont_trap or $notforloan_per_itemtype;
895 # Find this item in the reserves
896 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
898 # $priority and $highest are used to find the most important item
899 # in the list returned by &_Findgroupreserve. (The lower $priority,
900 # the more important the item.)
901 # $highest is the most important item we've seen so far.
904 if (scalar @reserves) {
905 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
906 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
907 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
909 my $priority = 10000000;
910 foreach my $res (@reserves) {
911 if ($res->{'found'} && $res->{'found'} eq 'W') {
912 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
913 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
914 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
915 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
916 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
920 my $local_hold_match;
922 if ($LocalHoldsPriority) {
923 $patron = Koha::Patrons->find( $res->{borrowernumber} );
924 $item = Koha::Items->find($itemnumber);
926 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
927 my $local_holds_priority_item_branchcode =
928 $item->$LocalHoldsPriorityItemControl;
929 my $local_holds_priority_patron_branchcode =
930 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
932 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
933 ? $patron->branchcode
936 $local_holds_priority_item_branchcode eq
937 $local_holds_priority_patron_branchcode;
941 # See if this item is more important than what we've got so far
942 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
943 $item ||= Koha::Items->find($itemnumber);
944 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
945 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
946 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
947 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
948 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
949 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
950 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
951 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
952 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
953 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
954 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
955 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
956 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
957 $priority = $res->{'priority'};
959 last if $local_hold_match;
965 # If we get this far, then no exact match was found.
966 # We return the most important (i.e. next) reservation.
968 $highest->{'itemnumber'} = $item;
969 return ( "Reserved", $highest, \@reserves );
975 =head2 CancelExpiredReserves
977 CancelExpiredReserves();
979 Cancels all reserves with an expiration date from before today.
983 sub CancelExpiredReserves {
984 my $cancellation_reason = shift;
985 my $today = dt_from_string();
986 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
987 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
989 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
990 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
991 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
993 # FIXME To move to Koha::Holds->search_expired (?)
994 my $holds = Koha::Holds->search( $params );
996 while ( my $hold = $holds->next ) {
997 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
999 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
1001 my $cancel_params = {};
1002 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
1003 if ( defined($hold->found) && $hold->found eq 'W' ) {
1004 $cancel_params->{charge_cancel_fee} = 1;
1006 $hold->cancel( $cancel_params );
1010 =head2 AutoUnsuspendReserves
1012 AutoUnsuspendReserves();
1014 Unsuspends all suspended reserves with a suspend_until date from before today.
1018 sub AutoUnsuspendReserves {
1019 my $today = dt_from_string();
1021 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
1023 map { $_->resume() } @holds;
1028 ModReserve({ rank => $rank,
1029 reserve_id => $reserve_id,
1030 branchcode => $branchcode
1031 [, itemnumber => $itemnumber ]
1032 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1035 Change a hold request's priority or cancel it.
1037 C<$rank> specifies the effect of the change. If C<$rank>
1038 is 'n', nothing happens. This corresponds to leaving a
1039 request alone when changing its priority in the holds queue
1042 If C<$rank> is 'del', the hold request is cancelled.
1044 If C<$rank> is an integer greater than zero, the priority of
1045 the request is set to that value. Since priority != 0 means
1046 that the item is not waiting on the hold shelf, setting the
1047 priority to a non-zero value also sets the request's found
1048 status and waiting date to NULL.
1050 If the hold is 'found' (waiting, in-transit, processing) the
1051 only field that can be updated is the expiration date.
1053 The optional C<$itemnumber> parameter is used only when
1054 C<$rank> is a non-zero integer; if supplied, the itemnumber
1055 of the hold request is set accordingly; if omitted, the itemnumber
1058 B<FIXME:> Note that the forgoing can have the effect of causing
1059 item-level hold requests to turn into title-level requests. This
1060 will be fixed once reserves has separate columns for requested
1061 itemnumber and supplying itemnumber.
1066 my ( $params ) = @_;
1068 my $rank = $params->{'rank'};
1069 my $reserve_id = $params->{'reserve_id'};
1070 my $branchcode = $params->{'branchcode'};
1071 my $itemnumber = $params->{'itemnumber'};
1072 my $suspend_until = $params->{'suspend_until'};
1073 my $borrowernumber = $params->{'borrowernumber'};
1074 my $biblionumber = $params->{'biblionumber'};
1075 my $cancellation_reason = $params->{'cancellation_reason'};
1076 my $date = $params->{expirationdate};
1078 return if defined $rank && $rank eq "n";
1080 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1083 unless ( $reserve_id ) {
1084 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1085 return unless $holds->count; # FIXME Should raise an exception
1086 $hold = $holds->next;
1087 $reserve_id = $hold->reserve_id;
1090 $hold ||= Koha::Holds->find($reserve_id);
1092 # FIXME Other calls may fail
1093 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1095 if ( $rank eq "del" ) {
1096 $hold->cancel({ cancellation_reason => $cancellation_reason });
1098 elsif ($hold->found && $hold->priority eq '0' && $date) {
1099 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1100 if C4::Context->preference('HoldsLog');
1102 # The only column that can be updated for a found hold is the expiration date
1103 $hold->expirationdate(dt_from_string($date))->store();
1105 elsif ($rank =~ /^\d+/ and $rank > 0) {
1106 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1107 if C4::Context->preference('HoldsLog');
1111 branchcode => $branchcode,
1112 itemnumber => $itemnumber,
1114 waitingdate => undef
1116 if (exists $params->{reservedate}) {
1117 $properties->{reservedate} = $params->{reservedate} || undef;
1119 if (exists $params->{expirationdate}) {
1120 $properties->{expirationdate} = $params->{expirationdate} || undef;
1123 $hold->set($properties)->store();
1125 if ( defined( $suspend_until ) ) {
1126 if ( $suspend_until ) {
1127 $suspend_until = eval { dt_from_string( $suspend_until ) };
1128 $hold->suspend_hold( $suspend_until );
1130 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1131 # If the hold is not suspended, this does nothing.
1132 $hold->set( { suspend_until => undef } )->store();
1136 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1140 =head2 ModReserveFill
1142 &ModReserveFill($reserve);
1144 Fill a reserve. If I understand this correctly, this means that the
1145 reserved book has been found and given to the patron who reserved it.
1147 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1148 whose keys are fields from the reserves table in the Koha database.
1152 sub ModReserveFill {
1154 my $reserve_id = $res->{'reserve_id'};
1156 my $hold = Koha::Holds->find($reserve_id);
1157 # get the priority on this record....
1158 my $priority = $hold->priority;
1160 # update the hold statuses, no need to store it though, we will be deleting it anyway
1168 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1169 if C4::Context->preference('HoldsLog');
1171 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1172 my $old_hold = Koha::Old::Hold->new( $hold->unblessed() )->store();
1174 Koha::Plugins->call(
1175 'after_hold_action',
1178 payload => { hold => $old_hold->get_from_storage }
1184 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1185 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1186 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1189 # now fix the priority on the others (if the priority wasn't
1190 # already sorted!)....
1191 unless ( $priority == 0 ) {
1192 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1196 =head2 ModReserveStatus
1198 &ModReserveStatus($itemnumber, $newstatus);
1200 Update the reserve status for the active (priority=0) reserve.
1202 $itemnumber is the itemnumber the reserve is on
1204 $newstatus is the new status.
1208 sub ModReserveStatus {
1210 #first : check if we have a reservation for this item .
1211 my ($itemnumber, $newstatus) = @_;
1212 my $dbh = C4::Context->dbh;
1214 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1215 my $sth_set = $dbh->prepare($query);
1216 $sth_set->execute( $newstatus, $itemnumber );
1218 my $item = Koha::Items->find($itemnumber);
1219 if ( $item->location && $item->location eq 'CART'
1220 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1222 CartToShelf( $itemnumber );
1226 =head2 ModReserveAffect
1228 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1230 This function affect an item and a status for a given reserve, either fetched directly
1231 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1232 is given, only first reserve returned is affected, which is ok for anything but
1235 if $transferToDo is not set, then the status is set to "Waiting" as well.
1236 otherwise, a transfer is on the way, and the end of the transfer will
1237 take care of the waiting status
1239 This function also removes any entry of the hold in holds queue table.
1243 sub ModReserveAffect {
1244 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1245 my $dbh = C4::Context->dbh;
1247 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1248 # attached to $itemnumber
1249 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1250 $sth->execute($itemnumber);
1251 my ($biblionumber) = $sth->fetchrow;
1253 # get request - need to find out if item is already
1254 # waiting in order to not send duplicate hold filled notifications
1257 # Find hold by id if we have it
1258 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1259 # Find item level hold for this item if there is one
1260 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1261 # Find record level hold if there is no item level hold
1262 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1264 return unless $hold;
1266 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1268 $hold->itemnumber($itemnumber);
1270 if ($transferToDo) {
1271 $hold->set_transfer();
1272 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1273 && C4::Context->interface eq 'sip'
1274 && !$already_on_shelf) {
1275 $hold->set_processing();
1277 $hold->set_waiting($desk_id);
1278 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1279 # Complete transfer if one exists
1280 my $transfer = $hold->item->get_transfer;
1281 $transfer->receive if $transfer;
1284 _FixPriority( { biblionumber => $biblionumber } );
1285 my $item = Koha::Items->find($itemnumber);
1286 if ( $item->location && $item->location eq 'CART'
1287 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1288 CartToShelf( $itemnumber );
1291 my $std = $dbh->prepare(q{
1293 FROM tmp_holdsqueue q
1294 INNER JOIN hold_fill_targets t
1295 ON q.borrowernumber = t.borrowernumber
1296 AND q.biblionumber = t.biblionumber
1297 AND q.itemnumber = t.itemnumber
1298 AND q.item_level_request = t.item_level_request
1299 AND q.holdingbranch = t.source_branchcode
1300 WHERE t.reserve_id = ?
1302 $std->execute($hold->reserve_id);
1304 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1305 if C4::Context->preference('HoldsLog');
1310 =head2 ModReserveCancelAll
1312 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1314 function to cancel reserv,check other reserves, and transfer document if it's necessary
1318 sub ModReserveCancelAll {
1321 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1323 #step 1 : cancel the reservation
1324 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1325 return unless $holds->count;
1326 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1328 #step 2 launch the subroutine of the others reserves
1329 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1331 return ( $messages, $nextreservinfo->{borrowernumber} );
1334 =head2 ModReserveMinusPriority
1336 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1338 Reduce the values of queued list
1342 sub ModReserveMinusPriority {
1343 my ( $itemnumber, $reserve_id ) = @_;
1345 #first step update the value of the first person on reserv
1346 my $dbh = C4::Context->dbh;
1349 SET priority = 0 , itemnumber = ?
1350 WHERE reserve_id = ?
1352 my $sth_upd = $dbh->prepare($query);
1353 $sth_upd->execute( $itemnumber, $reserve_id );
1354 # second step update all others reserves
1355 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1358 =head2 IsAvailableForItemLevelRequest
1360 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1362 Checks whether a given item record is available for an
1363 item-level hold request. An item is available if
1365 * it is not lost AND
1366 * it is not damaged AND
1367 * it is not withdrawn AND
1368 * a waiting or in transit reserve is placed on
1369 * does not have a not for loan value > 0
1371 Need to check the issuingrules onshelfholds column,
1372 if this is set items on the shelf can be placed on hold
1374 Note that IsAvailableForItemLevelRequest() does not
1375 check if the staff operator is authorized to place
1376 a request on the item - in particular,
1377 this routine does not check IndependentBranches
1378 and canreservefromotherbranches.
1380 Note also that this subroutine does not checks smart
1381 rules limits for item by reservesallowed/holds_per_record
1382 values, this complemented in calling code with calls and
1383 checks with CanItemBeReserved or CanBookBeReserved.
1387 sub IsAvailableForItemLevelRequest {
1390 my $pickup_branchcode = shift;
1391 # items_any_available is precalculated status passed from request.pl when set of items
1392 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1393 my $items_any_available = shift;
1395 my $dbh = C4::Context->dbh;
1396 # must check the notforloan setting of the itemtype
1397 # FIXME - a lot of places in the code do this
1398 # or something similar - need to be
1400 my $itemtype = $item->effective_itemtype;
1402 unless defined $itemtype;
1403 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1406 $notforloan_per_itemtype ||
1408 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1410 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1412 if ($pickup_branchcode) {
1413 my $destination = Koha::Libraries->find($pickup_branchcode);
1414 return 0 unless $destination;
1415 return 0 unless $destination->pickup_location;
1416 return 0 unless $item->can_be_transferred( { to => $destination } );
1417 my $reserves_control_branch =
1418 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1419 my $branchitemrule =
1420 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1421 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1422 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1425 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1427 if ( $on_shelf_holds == 1 ) {
1429 } elsif ( $on_shelf_holds == 2 ) {
1431 # if we have this param predefined from outer caller sub, we just need
1432 # to return it, so we saving from having loop inside other loop:
1433 return $items_any_available ? 0 : 1
1434 if defined $items_any_available;
1436 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1437 return $any_available ? 0 : 1;
1438 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1439 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1443 =head2 ItemsAnyAvailableAndNotRestricted
1445 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1447 This function checks all items for specified biblionumber (numeric) against patron (object)
1448 and returns true (1) if at least one item available for loan/check out/present/not held
1449 and also checks other parameters logic which not restricts item for hold at all (for ex.
1450 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1454 sub ItemsAnyAvailableAndNotRestricted {
1457 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1459 foreach my $i (@items) {
1460 my $reserves_control_branch =
1461 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1462 my $branchitemrule =
1463 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1464 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1466 # we can return (end the loop) when first one found:
1469 || $i->notforloan # items with non-zero notforloan cannot be checked out
1472 || IsItemOnHoldAndFound( $i->id )
1474 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1475 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1476 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1477 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1478 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1484 =head2 AlterPriority
1486 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1488 This function changes a reserve's priority up, down, to the top, or to the bottom.
1489 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1494 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1496 my $hold = Koha::Holds->find( $reserve_id );
1497 return unless $hold;
1499 if ( $hold->cancellationdate ) {
1500 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1504 if ( $where eq 'up' ) {
1505 return unless $prev_priority;
1506 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1507 } elsif ( $where eq 'down' ) {
1508 return unless $next_priority;
1509 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1510 } elsif ( $where eq 'top' ) {
1511 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1512 } elsif ( $where eq 'bottom' ) {
1513 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1516 # FIXME Should return the new priority
1519 =head2 ToggleLowestPriority
1521 ToggleLowestPriority( $borrowernumber, $biblionumber );
1523 This function sets the lowestPriority field to true if is false, and false if it is true.
1527 sub ToggleLowestPriority {
1528 my ( $reserve_id ) = @_;
1530 my $dbh = C4::Context->dbh;
1532 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1533 $sth->execute( $reserve_id );
1535 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1538 =head2 ToggleSuspend
1540 ToggleSuspend( $reserve_id );
1542 This function sets the suspend field to true if is false, and false if it is true.
1543 If the reserve is currently suspended with a suspend_until date, that date will
1544 be cleared when it is unsuspended.
1549 my ( $reserve_id, $suspend_until ) = @_;
1551 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1553 my $hold = Koha::Holds->find( $reserve_id );
1555 if ( $hold->is_suspended ) {
1558 $hold->suspend_hold( $suspend_until );
1565 borrowernumber => $borrowernumber,
1566 [ biblionumber => $biblionumber, ]
1567 [ suspend_until => $suspend_until, ]
1568 [ suspend => $suspend ]
1571 This function accepts a set of hash keys as its parameters.
1572 It requires either borrowernumber or biblionumber, or both.
1574 suspend_until is wholly optional.
1581 my $borrowernumber = $params{'borrowernumber'} || undef;
1582 my $biblionumber = $params{'biblionumber'} || undef;
1583 my $suspend_until = $params{'suspend_until'} || undef;
1584 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1586 $suspend_until = eval { dt_from_string($suspend_until) }
1587 if ( defined($suspend_until) );
1589 return unless ( $borrowernumber || $biblionumber );
1592 $params->{found} = undef;
1593 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1594 $params->{biblionumber} = $biblionumber if $biblionumber;
1596 my @holds = Koha::Holds->search($params);
1599 map { $_->suspend_hold($suspend_until) } @holds;
1602 map { $_->resume() } @holds;
1610 reserve_id => $reserve_id,
1612 [ignoreSetLowestRank => $ignoreSetLowestRank]
1617 _FixPriority({ biblionumber => $biblionumber});
1619 This routine adjusts the priority of a hold request and holds
1622 In the first form, where a reserve_id is passed, the priority of the
1623 hold is set to supplied rank, and other holds for that bib are adjusted
1624 accordingly. If the rank is "del", the hold is cancelled. If no rank
1625 is supplied, all of the holds on that bib have their priority adjusted
1626 as if the second form had been used.
1628 In the second form, where a biblionumber is passed, the holds on that
1629 bib (that are not captured) are sorted in order of increasing priority,
1630 then have reserves.priority set so that the first non-captured hold
1631 has its priority set to 1, the second non-captured hold has its priority
1632 set to 2, and so forth.
1634 In both cases, holds that have the lowestPriority flag on are have their
1635 priority adjusted to ensure that they remain at the end of the line.
1637 Note that the ignoreSetLowestRank parameter is meant to be used only
1638 when _FixPriority calls itself.
1643 my ( $params ) = @_;
1644 my $reserve_id = $params->{reserve_id};
1645 my $rank = $params->{rank} // '';
1646 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1647 my $biblionumber = $params->{biblionumber};
1649 my $dbh = C4::Context->dbh;
1652 if ( $reserve_id ) {
1653 $hold = Koha::Holds->find( $reserve_id );
1654 if (!defined $hold){
1655 # may have already been checked out and hold fulfilled
1656 $hold = Koha::Old::Holds->find( $reserve_id );
1658 return unless $hold;
1661 unless ( $biblionumber ) { # FIXME This is a very weird API
1662 $biblionumber = $hold->biblionumber;
1665 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1668 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1670 # make sure priority for waiting or in-transit items is 0
1674 WHERE reserve_id = ?
1675 AND found IN ('W', 'T', 'P')
1677 my $sth = $dbh->prepare($query);
1678 $sth->execute( $reserve_id );
1684 SELECT reserve_id, borrowernumber, reservedate
1686 WHERE biblionumber = ?
1687 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1688 ORDER BY priority ASC
1690 my $sth = $dbh->prepare($query);
1691 $sth->execute( $biblionumber );
1692 while ( my $line = $sth->fetchrow_hashref ) {
1693 push( @priority, $line );
1696 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1697 # To find the matching index
1699 my $key = -1; # to allow for 0 to be a valid result
1700 for ( $i = 0 ; $i < @priority ; $i++ ) {
1701 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1702 $key = $i; # save the index
1707 # if index exists in array then move it to new position
1708 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1709 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1710 my $moving_item = splice( @priority, $key, 1 );
1711 $new_rank = scalar @priority if $new_rank > scalar @priority;
1712 splice( @priority, $new_rank, 0, $moving_item );
1715 # now fix the priority on those that are left....
1719 WHERE reserve_id = ?
1721 $sth = $dbh->prepare($query);
1722 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1725 $priority[$j]->{'reserve_id'}
1729 unless ( $ignoreSetLowestRank ) {
1730 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1731 $sth->execute($biblionumber);
1732 while ( my $res = $sth->fetchrow_hashref() ) {
1734 reserve_id => $res->{'reserve_id'},
1736 ignoreSetLowestRank => 1
1742 =head2 _Findgroupreserve
1744 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1746 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1747 first match found. If neither, then we look for non-holds-queue based holds.
1748 Lookahead is the number of days to look in advance.
1750 C<&_Findgroupreserve> returns :
1751 C<@results> is an array of references-to-hash whose keys are mostly
1752 fields from the reserves table of the Koha database, plus
1753 C<biblioitemnumber>.
1755 This routine with either return:
1756 1 - Item specific holds from the holds queue
1757 2 - Title level holds from the holds queue
1758 3 - All holds for this biblionumber
1760 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1764 sub _Findgroupreserve {
1765 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1766 my $dbh = C4::Context->dbh;
1768 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1769 # check for exact targeted match
1770 my $item_level_target_query = qq{
1771 SELECT reserves.biblionumber AS biblionumber,
1772 reserves.borrowernumber AS borrowernumber,
1773 reserves.reservedate AS reservedate,
1774 reserves.branchcode AS branchcode,
1775 reserves.cancellationdate AS cancellationdate,
1776 reserves.found AS found,
1777 reserves.reservenotes AS reservenotes,
1778 reserves.priority AS priority,
1779 reserves.timestamp AS timestamp,
1780 biblioitems.biblioitemnumber AS biblioitemnumber,
1781 reserves.itemnumber AS itemnumber,
1782 reserves.reserve_id AS reserve_id,
1783 reserves.itemtype AS itemtype,
1784 reserves.non_priority AS non_priority
1786 JOIN biblioitems USING (biblionumber)
1787 JOIN hold_fill_targets USING (reserve_id)
1790 AND item_level_request = 1
1791 AND hold_fill_targets.itemnumber = ?
1792 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1796 my $sth = $dbh->prepare($item_level_target_query);
1797 $sth->execute($itemnumber, $lookahead||0);
1799 if ( my $data = $sth->fetchrow_hashref ) {
1800 push( @results, $data )
1801 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1803 return @results if @results;
1805 # check for title-level targeted match
1806 my $title_level_target_query = qq{
1807 SELECT reserves.biblionumber AS biblionumber,
1808 reserves.borrowernumber AS borrowernumber,
1809 reserves.reservedate AS reservedate,
1810 reserves.branchcode AS branchcode,
1811 reserves.cancellationdate AS cancellationdate,
1812 reserves.found AS found,
1813 reserves.reservenotes AS reservenotes,
1814 reserves.priority AS priority,
1815 reserves.timestamp AS timestamp,
1816 biblioitems.biblioitemnumber AS biblioitemnumber,
1817 reserves.itemnumber AS itemnumber,
1818 reserves.reserve_id AS reserve_id,
1819 reserves.itemtype AS itemtype,
1820 reserves.non_priority AS non_priority
1822 JOIN biblioitems USING (biblionumber)
1823 JOIN hold_fill_targets USING (reserve_id)
1826 AND item_level_request = 0
1827 AND hold_fill_targets.itemnumber = ?
1828 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1832 $sth = $dbh->prepare($title_level_target_query);
1833 $sth->execute($itemnumber, $lookahead||0);
1835 if ( my $data = $sth->fetchrow_hashref ) {
1836 push( @results, $data )
1837 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1839 return @results if @results;
1842 SELECT reserves.biblionumber AS biblionumber,
1843 reserves.borrowernumber AS borrowernumber,
1844 reserves.reservedate AS reservedate,
1845 reserves.waitingdate AS waitingdate,
1846 reserves.branchcode AS branchcode,
1847 reserves.cancellationdate AS cancellationdate,
1848 reserves.found AS found,
1849 reserves.reservenotes AS reservenotes,
1850 reserves.priority AS priority,
1851 reserves.timestamp AS timestamp,
1852 reserves.itemnumber AS itemnumber,
1853 reserves.reserve_id AS reserve_id,
1854 reserves.itemtype AS itemtype,
1855 reserves.non_priority AS non_priority
1857 WHERE reserves.biblionumber = ?
1858 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1859 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1863 $sth = $dbh->prepare($query);
1864 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1866 while ( my $data = $sth->fetchrow_hashref ) {
1867 push( @results, $data )
1868 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1873 =head2 _koha_notify_reserve
1875 _koha_notify_reserve( $hold->reserve_id );
1877 Sends a notification to the patron that their hold has been filled (through
1878 ModReserveAffect, _not_ ModReserveFill)
1880 The letter code for this notice may be found using the following query:
1882 select distinct letter_code
1883 from message_transports
1884 inner join message_attributes using (message_attribute_id)
1885 where message_name = 'Hold_Filled'
1887 This will probably sipmly be 'HOLD', but because it is defined in the database,
1888 it is subject to addition or change.
1890 The following tables are availalbe witin the notice:
1901 sub _koha_notify_reserve {
1902 my $reserve_id = shift;
1903 my $hold = Koha::Holds->find($reserve_id);
1904 my $borrowernumber = $hold->borrowernumber;
1906 my $patron = Koha::Patrons->find( $borrowernumber );
1908 # Try to get the borrower's email address
1909 my $to_address = $patron->notice_email_address;
1911 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1912 borrowernumber => $borrowernumber,
1913 message_name => 'Hold_Filled'
1916 my $library = Koha::Libraries->find( $hold->branchcode );
1917 my $admin_email_address = $library->from_email_address;
1918 $library = $library->unblessed;
1920 my %letter_params = (
1921 module => 'reserves',
1922 branchcode => $hold->branchcode,
1923 lang => $patron->lang,
1925 'branches' => $library,
1926 'borrowers' => $patron->unblessed,
1927 'biblio' => $hold->biblionumber,
1928 'biblioitems' => $hold->biblionumber,
1929 'reserves' => $hold->unblessed,
1930 'items' => $hold->itemnumber,
1934 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.
1935 my $send_notification = sub {
1936 my ( $mtt, $letter_code ) = (@_);
1937 return unless defined $letter_code;
1938 $letter_params{letter_code} = $letter_code;
1939 $letter_params{message_transport_type} = $mtt;
1940 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1942 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1946 C4::Letters::EnqueueLetter( {
1948 borrowernumber => $borrowernumber,
1949 from_address => $admin_email_address,
1950 message_transport_type => $mtt,
1954 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1956 ( $mtt eq 'email' and not $to_address ) # No email address
1957 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1958 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1959 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1962 &$send_notification($mtt, $letter_code);
1963 $notification_sent++;
1965 #Making sure that a print notification is sent if no other transport types can be utilized.
1966 if (! $notification_sent) {
1967 &$send_notification('print', 'HOLD');
1972 =head2 _ShiftPriority
1974 $new_priority = _ShiftPriority( $biblionumber, $priority );
1976 This increments the priority of all reserves after the one
1977 with either the lowest date after C<$reservedate>
1978 or the lowest priority after C<$priority>.
1980 It effectively makes room for a new reserve to be inserted with a certain
1981 priority, which is returned.
1983 This is most useful when the reservedate can be set by the user. It allows
1984 the new reserve to be placed before other reserves that have a later
1985 reservedate. Since priority also is set by the form in reserves/request.pl
1986 the sub accounts for that too.
1990 sub _ShiftPriority {
1991 my ( $biblio, $new_priority ) = @_;
1993 my $dbh = C4::Context->dbh;
1994 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND priority > ? ORDER BY priority ASC LIMIT 1";
1995 my $sth = $dbh->prepare( $query );
1996 $sth->execute( $biblio, $new_priority );
1997 my $min_priority = $sth->fetchrow;
1998 # if no such matches are found, $new_priority remains as original value
1999 $new_priority = $min_priority if ( $min_priority );
2001 # Shift the priority up by one; works in conjunction with the next SQL statement
2002 $query = "UPDATE reserves
2003 SET priority = priority+1
2004 WHERE biblionumber = ?
2005 AND borrowernumber = ?
2008 my $sth_update = $dbh->prepare( $query );
2010 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2011 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2012 $sth = $dbh->prepare( $query );
2013 $sth->execute( $new_priority, $biblio );
2014 while ( my $row = $sth->fetchrow_hashref ) {
2015 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2018 return $new_priority; # so the caller knows what priority they wind up receiving
2023 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2025 Use when checking out an item to handle reserves
2026 If $cancelreserve boolean is set to true, it will remove existing reserve
2031 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2033 $cancelreserve //= 0;
2035 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2036 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
2039 my $biblionumber = $res->{biblionumber};
2041 if ($res->{borrowernumber} == $borrowernumber) {
2042 ModReserveFill($res);
2046 # The item is reserved by someone else.
2047 # Find this item in the reserves
2049 my $borr_res = Koha::Holds->search({
2050 borrowernumber => $borrowernumber,
2051 biblionumber => $biblionumber,
2053 order_by => 'priority'
2057 # The item is reserved by the current patron
2058 ModReserveFill($borr_res->unblessed);
2061 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2062 RevertWaitingStatus({ itemnumber => $itemnumber });
2064 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2065 my $hold = Koha::Holds->find( $res->{reserve_id} );
2073 MergeHolds($dbh,$to_biblio, $from_biblio);
2075 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2080 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2081 my $sth = $dbh->prepare(
2082 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2084 $sth->execute($from_biblio);
2085 if ( my $data = $sth->fetchrow_hashref() ) {
2087 # holds exist on old record, if not we don't need to do anything
2088 $sth = $dbh->prepare(
2089 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2090 $sth->execute( $to_biblio, $from_biblio );
2093 # don't reorder those already waiting
2095 $sth = $dbh->prepare(
2096 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2098 my $upd_sth = $dbh->prepare(
2099 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2100 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2102 $sth->execute( $to_biblio );
2104 while ( my $reserve = $sth->fetchrow_hashref() ) {
2106 $priority, $to_biblio,
2107 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2108 $reserve->{'itemnumber'}
2115 =head2 RevertWaitingStatus
2117 RevertWaitingStatus({ itemnumber => $itemnumber });
2119 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2121 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2122 item level hold, even if it was only a bibliolevel hold to
2123 begin with. This is because we can no longer know if a hold
2124 was item-level or bib-level after a hold has been set to
2129 sub RevertWaitingStatus {
2130 my ( $params ) = @_;
2131 my $itemnumber = $params->{'itemnumber'};
2133 return unless ( $itemnumber );
2135 my $dbh = C4::Context->dbh;
2137 ## Get the waiting reserve we want to revert
2138 my $hold = Koha::Holds->search(
2140 itemnumber => $itemnumber,
2141 found => { not => undef },
2145 ## Increment the priority of all other non-waiting
2146 ## reserves for this bib record
2147 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2148 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2150 ## Fix up the currently waiting reserve
2155 waitingdate => undef,
2156 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2160 _FixPriority( { biblionumber => $hold->biblionumber } );
2169 branchcode => $branchcode,
2170 borrowernumber => $borrowernumber,
2171 biblionumber => $biblionumber,
2172 [ itemnumber => $itemnumber, ]
2173 [ barcode => $barcode, ]
2177 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2179 The letter code will be HOLD_SLIP, and the following tables are
2180 available within the slip:
2193 my $branchcode = $args->{branchcode};
2194 my $reserve_id = $args->{reserve_id};
2196 my $hold = Koha::Holds->find($reserve_id);
2197 return unless $hold;
2199 my $patron = $hold->borrower;
2200 my $reserve = $hold->unblessed;
2202 return C4::Letters::GetPreparedLetter (
2203 module => 'circulation',
2204 letter_code => 'HOLD_SLIP',
2205 branchcode => $branchcode,
2206 lang => $patron->lang,
2208 'reserves' => $reserve,
2209 'branches' => $reserve->{branchcode},
2210 'borrowers' => $reserve->{borrowernumber},
2211 'biblio' => $reserve->{biblionumber},
2212 'biblioitems' => $reserve->{biblionumber},
2213 'items' => $reserve->{itemnumber},
2218 =head2 GetReservesControlBranch
2220 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2222 Return the branchcode to be used to determine which reserves
2223 policy applies to a transaction.
2225 C<$item> is a hashref for an item. Only 'homebranch' is used.
2227 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2231 sub GetReservesControlBranch {
2232 my ( $item, $borrower ) = @_;
2234 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2237 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2238 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2244 =head2 CalculatePriority
2246 my $p = CalculatePriority($biblionumber, $resdate);
2248 Calculate priority for a new reserve on biblionumber, placing it at
2249 the end of the line of all holds whose start date falls before
2250 the current system time and that are neither on the hold shelf
2253 The reserve date parameter is optional; if it is supplied, the
2254 priority is based on the set of holds whose start date falls before
2255 the parameter value.
2257 After calculation of this priority, it is recommended to call
2258 _ShiftPriority. Note that this is currently done in
2263 sub CalculatePriority {
2264 my ( $biblionumber, $resdate ) = @_;
2267 SELECT COUNT(*) FROM reserves
2268 WHERE biblionumber = ?
2270 AND (found IS NULL OR found = '')
2272 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2274 $sql.= ' AND ( reservedate <= ? )';
2277 $sql.= ' AND ( reservedate < NOW() )';
2279 my $dbh = C4::Context->dbh();
2280 my @row = $dbh->selectrow_array(
2283 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2286 return @row ? $row[0]+1 : 1;
2289 =head2 IsItemOnHoldAndFound
2291 my $bool = IsItemFoundHold( $itemnumber );
2293 Returns true if the item is currently on hold
2294 and that hold has a non-null found status ( W, T, etc. )
2298 sub IsItemOnHoldAndFound {
2299 my ($itemnumber) = @_;
2301 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2303 my $found = $rs->count(
2305 itemnumber => $itemnumber,
2306 found => { '!=' => undef }
2313 =head2 GetMaxPatronHoldsForRecord
2315 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2317 For multiple holds on a given record for a given patron, the max
2318 number of record level holds that a patron can be placed is the highest
2319 value of the holds_per_record rule for each item if the record for that
2320 patron. This subroutine finds and returns the highest holds_per_record
2321 rule value for a given patron id and record id.
2325 sub GetMaxPatronHoldsForRecord {
2326 my ( $borrowernumber, $biblionumber ) = @_;
2328 my $patron = Koha::Patrons->find($borrowernumber);
2329 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2331 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2333 my $categorycode = $patron->categorycode;
2335 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2338 foreach my $item (@items) {
2339 my $itemtype = $item->effective_itemtype();
2341 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2343 my $rule = Koha::CirculationRules->get_effective_rule({
2344 categorycode => $categorycode,
2345 itemtype => $itemtype,
2346 branchcode => $branchcode,
2347 rule_name => 'holds_per_record'
2349 my $holds_per_record = $rule ? $rule->rule_value : 0;
2350 $max = $holds_per_record if $holds_per_record > $max;
2358 Koha Development Team <http://koha-community.org/>