3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
33 use C4::Members::Messaging;
35 use Koha::Account::Lines;
38 use Koha::CirculationRules;
52 use List::MoreUtils qw( firstidx any );
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
58 C4::Reserves - Koha functions for dealing with reservation.
66 This modules provides somes functions to deal with reservations.
68 Reserves are stored in reserves table.
69 The following columns contains important values :
70 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
71 =0 : then the reserve is being dealed
72 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
73 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
74 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
75 F(inished) : the reserve has been completed, and is done
76 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
77 by librarian before notice is send and status changed to waiting.
78 Applicable only if HoldsNeedProcessingSIP system preference is set.
79 - itemnumber : empty : the reserve is still unaffected to an item
80 filled: the reserve is attached to an item
81 The complete workflow is :
82 ==== 1st use case ====
83 patron request a document, 1st available : P >0, F=NULL, I=NULL
84 a library having it run "transfertodo", and clic on the list
85 if there is no transfer to do, the reserve waiting
86 patron can pick it up P =0, F=W, I=filled
87 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
88 The pickup library receive the book, it check in P =0, F=W, I=filled
89 The patron borrow the book P =0, F=F, I=filled
91 ==== 2nd use case ====
92 patron requests a document, a given item,
93 If pickup is holding branch P =0, F=W, I=filled
94 If transfer needed, write in branchtransfer P =0, F=T, I=filled
95 The pickup library receive the book, it checks it in P =0, F=W, I=filled
96 The patron borrow the book P =0, F=F, I=filled
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
129 ItemsAnyAvailableAndNotRestricted
132 &ToggleLowestPriority
138 &GetReservesControlBranch
142 GetMaxPatronHoldsForRecord
144 @EXPORT_OK = qw( MergeHolds );
151 branchcode => $branchcode,
152 borrowernumber => $borrowernumber,
153 biblionumber => $biblionumber,
154 priority => $priority,
155 reservation_date => $reservation_date,
156 expiration_date => $expiration_date,
159 itemnumber => $itemnumber,
161 itemtype => $itemtype,
165 Adds reserve and generates HOLDPLACED message.
167 The following tables are available witin the HOLDPLACED message:
180 my $branch = $params->{branchcode};
181 my $borrowernumber = $params->{borrowernumber};
182 my $biblionumber = $params->{biblionumber};
183 my $priority = $params->{priority};
184 my $resdate = $params->{reservation_date};
185 my $expdate = $params->{expiration_date};
186 my $notes = $params->{notes};
187 my $title = $params->{title};
188 my $checkitem = $params->{itemnumber};
189 my $found = $params->{found};
190 my $itemtype = $params->{itemtype};
191 my $non_priority = $params->{non_priority};
193 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
194 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
196 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
198 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
199 # of the document, we force the value $priority and $found .
200 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
201 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
204 # If item is already checked out, it cannot be set waiting
207 # The item can't be waiting if it needs a transfer
208 && $item->holdingbranch eq $branch
210 # Similarly, if in transit it can't be waiting
211 && !$item->get_transfer
213 # If we can't hold damaged items, and it is damaged, it can't be waiting
214 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
216 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
217 && !$item->current_holds->count )
224 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
226 # Make room in reserves for this before those of a later reserve date
227 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
232 # If the reserv had the waiting status, we had the value of the resdate
233 if ( $found && $found eq 'W' ) {
234 $waitingdate = $resdate;
237 # Don't add itemtype limit if specific item is selected
238 $itemtype = undef if $checkitem;
240 # updates take place here
241 my $hold = Koha::Hold->new(
243 borrowernumber => $borrowernumber,
244 biblionumber => $biblionumber,
245 reservedate => $resdate,
246 branchcode => $branch,
247 priority => $priority,
248 reservenotes => $notes,
249 itemnumber => $checkitem,
251 waitingdate => $waitingdate,
252 expirationdate => $expdate,
253 itemtype => $itemtype,
254 item_level_hold => $checkitem ? 1 : 0,
255 non_priority => $non_priority ? 1 : 0,
258 $hold->set_waiting() if $found && $found eq 'W';
260 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
261 if C4::Context->preference('HoldsLog');
263 my $reserve_id = $hold->id();
265 # add a reserve fee if needed
266 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
267 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
268 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
271 _FixPriority({ biblionumber => $biblionumber});
273 # Send e-mail to librarian if syspref is active
274 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
275 my $patron = Koha::Patrons->find( $borrowernumber );
276 my $library = $patron->library;
277 if ( my $letter = C4::Letters::GetPreparedLetter (
278 module => 'reserves',
279 letter_code => 'HOLDPLACED',
280 branchcode => $branch,
281 lang => $patron->lang,
283 'branches' => $library->unblessed,
284 'borrowers' => $patron->unblessed,
285 'biblio' => $biblionumber,
286 'biblioitems' => $biblionumber,
287 'items' => $checkitem,
288 'reserves' => $hold->unblessed,
292 my $branch_email_address = $library->inbound_email_address;
294 C4::Letters::EnqueueLetter(
297 borrowernumber => $borrowernumber,
298 message_transport_type => 'email',
299 to_address => $branch_email_address,
305 Koha::Plugins->call('after_hold_create', $hold);
310 =head2 CanBookBeReserved
312 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
313 if ($canReserve eq 'OK') { #We can reserve this Item! }
315 $params are passed directly through to CanItemBeReserved
317 See CanItemBeReserved() for possible return values.
321 sub CanBookBeReserved{
322 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
324 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
325 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
326 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
327 return { status =>'alreadypossession' };
330 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
331 #get items linked via host records
332 my @hostitems = get_hostitemnumbers_of($biblionumber);
334 push (@itemnumbers, @hostitems);
337 my $canReserve = { status => '' };
338 foreach my $itemnumber (@itemnumbers) {
339 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
340 return { status => 'OK' } if $canReserve->{status} eq 'OK';
345 =head2 CanItemBeReserved
347 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
348 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
350 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
351 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
352 current checkout against the high holds threshold
354 @RETURNS { status => OK }, if the Item can be reserved.
355 { status => ageRestricted }, if the Item is age restricted for this borrower.
356 { status => damaged }, if the Item is damaged.
357 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
358 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
359 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
360 { status => notReservable }, if holds on this item are not allowed
361 { status => libraryNotFound }, if given branchcode is not an existing library
362 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
363 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
364 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
368 sub CanItemBeReserved {
369 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
371 my $dbh = C4::Context->dbh;
372 my $ruleitemtype; # itemtype of the matching issuing rule
373 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
375 # we retrieve borrowers and items informations #
376 # item->{itype} will come for biblioitems if necessery
377 my $item = Koha::Items->find($itemnumber);
378 my $biblio = $item->biblio;
379 my $patron = Koha::Patrons->find( $borrowernumber );
380 my $borrower = $patron->unblessed;
382 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
383 return { status =>'damaged' }
385 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
387 # Check for the age restriction
388 my ( $ageRestriction, $daysToAgeRestriction ) =
389 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
390 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
392 # Check that the patron doesn't have an item level hold on this item already
393 return { status =>'itemAlreadyOnHold' }
394 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
396 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
397 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
398 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
399 return { status =>'alreadypossession' };
402 my $controlbranch = C4::Context->preference('ReservesControlBranch');
405 SELECT count(*) AS count
407 LEFT JOIN items USING (itemnumber)
408 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
409 LEFT JOIN borrowers USING (borrowernumber)
410 WHERE borrowernumber = ?
414 my $branchfield = "reserves.branchcode";
416 if ( $controlbranch eq "ItemHomeLibrary" ) {
417 $branchfield = "items.homebranch";
418 $branchcode = $item->homebranch;
420 elsif ( $controlbranch eq "PatronLibrary" ) {
421 $branchfield = "borrowers.branchcode";
422 $branchcode = $borrower->{branchcode};
427 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
428 itemtype => $item->effective_itemtype,
429 categorycode => $borrower->{categorycode},
430 branchcode => $branchcode,
431 rule_name => 'reservesallowed',
434 $ruleitemtype = $reservesallowed->itemtype;
435 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
438 $ruleitemtype = undef;
441 my $rights = Koha::CirculationRules->get_effective_rules({
442 categorycode => $borrower->{'categorycode'},
443 itemtype => $item->effective_itemtype,
444 branchcode => $branchcode,
445 rules => ['holds_per_record','holds_per_day']
447 my $holds_per_record = $rights->{holds_per_record} // 1;
448 my $holds_per_day = $rights->{holds_per_day};
450 my $search_params = {
451 borrowernumber => $borrowernumber,
452 biblionumber => $item->biblionumber,
454 $search_params->{found} = undef if $params->{ignore_found_holds};
456 my $holds = Koha::Holds->search($search_params);
457 if ( defined $holds_per_record && $holds_per_record ne ''
458 && $holds->count() >= $holds_per_record ) {
459 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
462 my $today_holds = Koha::Holds->search({
463 borrowernumber => $borrowernumber,
464 reservedate => dt_from_string->date
467 if ( defined $holds_per_day && $holds_per_day ne ''
468 && $today_holds->count() >= $holds_per_day )
470 return { status => 'tooManyReservesToday', limit => $holds_per_day };
475 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
477 # If using item-level itypes, fall back to the record
478 # level itemtype if the hold has no associated item
480 C4::Context->preference('item-level_itypes')
481 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
482 : " AND biblioitems.itemtype = ?"
483 if defined $ruleitemtype;
485 my $sthcount = $dbh->prepare($querycount);
487 if ( defined $ruleitemtype ) {
488 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
491 $sthcount->execute( $borrowernumber, $branchcode );
494 my $reservecount = "0";
495 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
496 $reservecount = $rowcount->{count};
499 # we check if it's ok or not
500 if ( defined $allowedreserves && $allowedreserves ne ''
501 && $reservecount >= $allowedreserves ) {
502 return { status => 'tooManyReserves', limit => $allowedreserves };
505 # Now we need to check hold limits by patron category
506 my $rule = Koha::CirculationRules->get_effective_rule(
508 categorycode => $borrower->{categorycode},
509 branchcode => $branchcode,
510 rule_name => 'max_holds',
513 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
514 my $total_holds_count = Koha::Holds->search(
516 borrowernumber => $borrower->{borrowernumber}
520 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
523 my $reserves_control_branch =
524 GetReservesControlBranch( $item->unblessed(), $borrower );
526 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
528 if ( $branchitemrule->{holdallowed} == 0 ) {
529 return { status => 'notReservable' };
532 if ( $branchitemrule->{holdallowed} == 1
533 && $borrower->{branchcode} ne $item->homebranch )
535 return { status => 'cannotReserveFromOtherBranches' };
538 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
539 if ( $branchitemrule->{holdallowed} == 3) {
540 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
541 return { status => 'branchNotInHoldGroup' };
545 # If reservecount is ok, we check item branch if IndependentBranches is ON
546 # and canreservefromotherbranches is OFF
547 if ( C4::Context->preference('IndependentBranches')
548 and !C4::Context->preference('canreservefromotherbranches') )
550 if ( $item->homebranch ne $borrower->{branchcode} ) {
551 return { status => 'cannotReserveFromOtherBranches' };
555 if ($pickup_branchcode) {
556 my $destination = Koha::Libraries->find({
557 branchcode => $pickup_branchcode,
560 unless ($destination) {
561 return { status => 'libraryNotFound' };
563 unless ($destination->pickup_location) {
564 return { status => 'libraryNotPickupLocation' };
566 unless ($item->can_be_transferred({ to => $destination })) {
567 return { status => 'cannotBeTransferred' };
569 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
570 return { status => 'pickupNotInHoldGroup' };
572 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
573 return { status => 'pickupNotInHoldGroup' };
577 return { status => 'OK' };
580 =head2 CanReserveBeCanceledFromOpac
582 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
584 returns 1 if reserve can be cancelled by user from OPAC.
585 First check if reserve belongs to user, next checks if reserve is not in
586 transfer or waiting status
590 sub CanReserveBeCanceledFromOpac {
591 my ($reserve_id, $borrowernumber) = @_;
593 return unless $reserve_id and $borrowernumber;
594 my $reserve = Koha::Holds->find($reserve_id);
596 return 0 unless $reserve->borrowernumber == $borrowernumber;
597 return $reserve->is_cancelable_from_opac;
600 =head2 GetOtherReserves
602 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
604 Check queued list of this document and check if this document must be transferred
608 sub GetOtherReserves {
609 my ($itemnumber) = @_;
612 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
613 if ($checkreserves) {
614 my $item = Koha::Items->find($itemnumber);
615 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
616 $messages->{'transfert'} = $checkreserves->{'branchcode'};
617 #minus priorities of others reservs
618 ModReserveMinusPriority(
620 $checkreserves->{'reserve_id'},
623 #launch the subroutine dotransfer
624 C4::Items::ModItemTransfer(
626 $item->holdingbranch,
627 $checkreserves->{'branchcode'},
633 #step 2b : case of a reservation on the same branch, set the waiting status
635 $messages->{'waiting'} = 1;
636 ModReserveMinusPriority(
638 $checkreserves->{'reserve_id'},
640 ModReserveStatus($itemnumber,'W');
643 $nextreservinfo = $checkreserves;
646 return ( $messages, $nextreservinfo );
649 =head2 ChargeReserveFee
651 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
653 Charge the fee for a reserve (if $fee > 0)
657 sub ChargeReserveFee {
658 my ( $borrowernumber, $fee, $title ) = @_;
659 return if !$fee || $fee == 0; # the last test is needed to include 0.00
660 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
663 description => $title,
665 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
666 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
667 interface => C4::Context->interface,
668 invoice_type => undef,
677 $fee = GetReserveFee( $borrowernumber, $biblionumber );
679 Calculate the fee for a reserve (if applicable).
684 my ( $borrowernumber, $biblionumber ) = @_;
686 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
689 SELECT COUNT(*) FROM items
690 LEFT JOIN issues USING (itemnumber)
691 WHERE items.biblionumber=? AND issues.issue_id IS NULL
694 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
697 my $dbh = C4::Context->dbh;
698 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
699 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
700 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
701 # This is a reconstruction of the old code:
702 # Compare number of items with items issued, and optionally check holds
703 # If not all items are issued and there are no holds: charge no fee
704 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
705 my ( $notissued, $reserved );
706 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
709 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
710 ( $biblionumber, $borrowernumber ) );
711 $fee = 0 if $reserved == 0;
717 =head2 GetReserveStatus
719 $reservestatus = GetReserveStatus($itemnumber);
721 Takes an itemnumber and returns the status of the reserve placed on it.
722 If several reserves exist, the reserve with the lower priority is given.
726 ## FIXME: I don't think this does what it thinks it does.
727 ## It only ever checks the first reserve result, even though
728 ## multiple reserves for that bib can have the itemnumber set
729 ## the sub is only used once in the codebase.
730 sub GetReserveStatus {
731 my ($itemnumber) = @_;
733 my $dbh = C4::Context->dbh;
735 my ($sth, $found, $priority);
737 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
738 $sth->execute($itemnumber);
739 ($found, $priority) = $sth->fetchrow_array;
743 return 'Waiting' if $found eq 'W' and $priority == 0;
744 return 'Processing' if $found eq 'P';
745 return 'Finished' if $found eq 'F';
748 return 'Reserved' if defined $priority && $priority > 0;
750 return ''; # empty string here will remove need for checking undef, or less log lines
755 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
756 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
757 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
759 Find a book in the reserves.
761 C<$itemnumber> is the book's item number.
762 C<$lookahead> is the number of days to look in advance for future reserves.
764 As I understand it, C<&CheckReserves> looks for the given item in the
765 reserves. If it is found, that's a match, and C<$status> is set to
768 Otherwise, it finds the most important item in the reserves with the
769 same biblio number as this book (I'm not clear on this) and returns it
770 with C<$status> set to C<Reserved>.
772 C<&CheckReserves> returns a two-element list:
774 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
776 C<$reserve> is the reserve item that matched. It is a
777 reference-to-hash whose keys are mostly the fields of the reserves
778 table in the Koha database.
783 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
784 my $dbh = C4::Context->dbh;
787 if (C4::Context->preference('item-level_itypes')){
789 SELECT items.biblionumber,
790 items.biblioitemnumber,
791 itemtypes.notforloan,
792 items.notforloan AS itemnotforloan,
798 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
799 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
804 SELECT items.biblionumber,
805 items.biblioitemnumber,
806 itemtypes.notforloan,
807 items.notforloan AS itemnotforloan,
813 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
814 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
819 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
820 $sth->execute($item);
823 $sth = $dbh->prepare("$select WHERE barcode = ?");
824 $sth->execute($barcode);
826 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
827 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
828 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
830 return unless $itemnumber; # bail if we got nothing.
831 # if item is not for loan it cannot be reserved either.....
832 # except where items.notforloan < 0 : This indicates the item is holdable.
834 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
835 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
837 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
838 return if $dont_trap or $notforloan_per_itemtype;
840 # Find this item in the reserves
841 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
843 # $priority and $highest are used to find the most important item
844 # in the list returned by &_Findgroupreserve. (The lower $priority,
845 # the more important the item.)
846 # $highest is the most important item we've seen so far.
849 if (scalar @reserves) {
850 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
851 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
852 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
854 my $priority = 10000000;
855 foreach my $res (@reserves) {
856 if ($res->{'found'} eq 'W') {
857 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
858 } elsif ($res->{'found'} eq 'P') {
859 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
860 } elsif ($res->{'found'} eq 'T') {
861 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
865 my $local_hold_match;
867 if ($LocalHoldsPriority) {
868 $patron = Koha::Patrons->find( $res->{borrowernumber} );
869 $item = Koha::Items->find($itemnumber);
871 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
872 my $local_holds_priority_item_branchcode =
873 $item->$LocalHoldsPriorityItemControl;
874 my $local_holds_priority_patron_branchcode =
875 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
877 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
878 ? $patron->branchcode
881 $local_holds_priority_item_branchcode eq
882 $local_holds_priority_patron_branchcode;
886 # See if this item is more important than what we've got so far
887 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
888 $item ||= Koha::Items->find($itemnumber);
889 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
890 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
891 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
892 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
893 next if ($branchitemrule->{'holdallowed'} == 0);
894 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
895 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
896 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
897 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
898 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
899 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
900 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
901 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
902 $priority = $res->{'priority'};
904 last if $local_hold_match;
910 # If we get this far, then no exact match was found.
911 # We return the most important (i.e. next) reservation.
913 $highest->{'itemnumber'} = $item;
914 return ( "Reserved", $highest, \@reserves );
920 =head2 CancelExpiredReserves
922 CancelExpiredReserves();
924 Cancels all reserves with an expiration date from before today.
928 sub CancelExpiredReserves {
929 my $cancellation_reason = shift;
930 my $today = dt_from_string();
931 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
932 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
934 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
935 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
936 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
938 # FIXME To move to Koha::Holds->search_expired (?)
939 my $holds = Koha::Holds->search( $params );
941 while ( my $hold = $holds->next ) {
942 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
944 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
946 my $cancel_params = {};
947 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
948 if ( defined($hold->found) && $hold->found eq 'W' ) {
949 $cancel_params->{charge_cancel_fee} = 1;
951 $hold->cancel( $cancel_params );
955 =head2 AutoUnsuspendReserves
957 AutoUnsuspendReserves();
959 Unsuspends all suspended reserves with a suspend_until date from before today.
963 sub AutoUnsuspendReserves {
964 my $today = dt_from_string();
966 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
968 map { $_->resume() } @holds;
973 ModReserve({ rank => $rank,
974 reserve_id => $reserve_id,
975 branchcode => $branchcode
976 [, itemnumber => $itemnumber ]
977 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
980 Change a hold request's priority or cancel it.
982 C<$rank> specifies the effect of the change. If C<$rank>
983 is 'W' or 'n', nothing happens. This corresponds to leaving a
984 request alone when changing its priority in the holds queue
987 If C<$rank> is 'del', the hold request is cancelled.
989 If C<$rank> is an integer greater than zero, the priority of
990 the request is set to that value. Since priority != 0 means
991 that the item is not waiting on the hold shelf, setting the
992 priority to a non-zero value also sets the request's found
993 status and waiting date to NULL.
995 The optional C<$itemnumber> parameter is used only when
996 C<$rank> is a non-zero integer; if supplied, the itemnumber
997 of the hold request is set accordingly; if omitted, the itemnumber
1000 B<FIXME:> Note that the forgoing can have the effect of causing
1001 item-level hold requests to turn into title-level requests. This
1002 will be fixed once reserves has separate columns for requested
1003 itemnumber and supplying itemnumber.
1008 my ( $params ) = @_;
1010 my $rank = $params->{'rank'};
1011 my $reserve_id = $params->{'reserve_id'};
1012 my $branchcode = $params->{'branchcode'};
1013 my $itemnumber = $params->{'itemnumber'};
1014 my $suspend_until = $params->{'suspend_until'};
1015 my $borrowernumber = $params->{'borrowernumber'};
1016 my $biblionumber = $params->{'biblionumber'};
1017 my $cancellation_reason = $params->{'cancellation_reason'};
1019 return if $rank eq "W";
1020 return if $rank eq "n";
1022 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1025 unless ( $reserve_id ) {
1026 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1027 return unless $holds->count; # FIXME Should raise an exception
1028 $hold = $holds->next;
1029 $reserve_id = $hold->reserve_id;
1032 $hold ||= Koha::Holds->find($reserve_id);
1034 if ( $rank eq "del" ) {
1035 $hold->cancel({ cancellation_reason => $cancellation_reason });
1037 elsif ($rank =~ /^\d+/ and $rank > 0) {
1038 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1039 if C4::Context->preference('HoldsLog');
1043 branchcode => $branchcode,
1044 itemnumber => $itemnumber,
1046 waitingdate => undef
1048 if (exists $params->{reservedate}) {
1049 $properties->{reservedate} = $params->{reservedate} || undef;
1051 if (exists $params->{expirationdate}) {
1052 $properties->{expirationdate} = $params->{expirationdate} || undef;
1055 $hold->set($properties)->store();
1057 if ( defined( $suspend_until ) ) {
1058 if ( $suspend_until ) {
1059 $suspend_until = eval { dt_from_string( $suspend_until ) };
1060 $hold->suspend_hold( $suspend_until );
1062 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1063 # If the hold is not suspended, this does nothing.
1064 $hold->set( { suspend_until => undef } )->store();
1068 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1072 =head2 ModReserveFill
1074 &ModReserveFill($reserve);
1076 Fill a reserve. If I understand this correctly, this means that the
1077 reserved book has been found and given to the patron who reserved it.
1079 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1080 whose keys are fields from the reserves table in the Koha database.
1084 sub ModReserveFill {
1086 my $reserve_id = $res->{'reserve_id'};
1088 my $hold = Koha::Holds->find($reserve_id);
1089 # get the priority on this record....
1090 my $priority = $hold->priority;
1092 # update the hold statuses, no need to store it though, we will be deleting it anyway
1100 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1101 if C4::Context->preference('HoldsLog');
1103 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1104 Koha::Old::Hold->new( $hold->unblessed() )->store();
1108 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1109 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1110 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1113 # now fix the priority on the others (if the priority wasn't
1114 # already sorted!)....
1115 unless ( $priority == 0 ) {
1116 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1120 =head2 ModReserveStatus
1122 &ModReserveStatus($itemnumber, $newstatus);
1124 Update the reserve status for the active (priority=0) reserve.
1126 $itemnumber is the itemnumber the reserve is on
1128 $newstatus is the new status.
1132 sub ModReserveStatus {
1134 #first : check if we have a reservation for this item .
1135 my ($itemnumber, $newstatus) = @_;
1136 my $dbh = C4::Context->dbh;
1138 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1139 my $sth_set = $dbh->prepare($query);
1140 $sth_set->execute( $newstatus, $itemnumber );
1142 my $item = Koha::Items->find($itemnumber);
1143 if ( $item->location && $item->location eq 'CART'
1144 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1146 CartToShelf( $itemnumber );
1150 =head2 ModReserveAffect
1152 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1154 This function affect an item and a status for a given reserve, either fetched directly
1155 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1156 is given, only first reserve returned is affected, which is ok for anything but
1159 if $transferToDo is not set, then the status is set to "Waiting" as well.
1160 otherwise, a transfer is on the way, and the end of the transfer will
1161 take care of the waiting status
1165 sub ModReserveAffect {
1166 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1167 my $dbh = C4::Context->dbh;
1169 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1170 # attached to $itemnumber
1171 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1172 $sth->execute($itemnumber);
1173 my ($biblionumber) = $sth->fetchrow;
1175 # get request - need to find out if item is already
1176 # waiting in order to not send duplicate hold filled notifications
1179 # Find hold by id if we have it
1180 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1181 # Find item level hold for this item if there is one
1182 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1183 # Find record level hold if there is no item level hold
1184 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1186 return unless $hold;
1188 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1190 $hold->itemnumber($itemnumber);
1192 if ($transferToDo) {
1193 $hold->set_transfer();
1194 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1195 && C4::Context->interface eq 'sip'
1196 && !$already_on_shelf) {
1197 $hold->set_processing();
1199 $hold->set_waiting($desk_id);
1200 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1201 # Complete transfer if one exists
1202 my $transfer = $hold->item->get_transfer;
1203 $transfer->receive if $transfer;
1206 _FixPriority( { biblionumber => $biblionumber } );
1207 my $item = Koha::Items->find($itemnumber);
1208 if ( $item->location && $item->location eq 'CART'
1209 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1210 CartToShelf( $itemnumber );
1213 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1214 if C4::Context->preference('HoldsLog');
1219 =head2 ModReserveCancelAll
1221 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1223 function to cancel reserv,check other reserves, and transfer document if it's necessary
1227 sub ModReserveCancelAll {
1230 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1232 #step 1 : cancel the reservation
1233 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1234 return unless $holds->count;
1235 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1237 #step 2 launch the subroutine of the others reserves
1238 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1240 return ( $messages, $nextreservinfo->{borrowernumber} );
1243 =head2 ModReserveMinusPriority
1245 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1247 Reduce the values of queued list
1251 sub ModReserveMinusPriority {
1252 my ( $itemnumber, $reserve_id ) = @_;
1254 #first step update the value of the first person on reserv
1255 my $dbh = C4::Context->dbh;
1258 SET priority = 0 , itemnumber = ?
1259 WHERE reserve_id = ?
1261 my $sth_upd = $dbh->prepare($query);
1262 $sth_upd->execute( $itemnumber, $reserve_id );
1263 # second step update all others reserves
1264 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1267 =head2 IsAvailableForItemLevelRequest
1269 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1271 Checks whether a given item record is available for an
1272 item-level hold request. An item is available if
1274 * it is not lost AND
1275 * it is not damaged AND
1276 * it is not withdrawn AND
1277 * a waiting or in transit reserve is placed on
1278 * does not have a not for loan value > 0
1280 Need to check the issuingrules onshelfholds column,
1281 if this is set items on the shelf can be placed on hold
1283 Note that IsAvailableForItemLevelRequest() does not
1284 check if the staff operator is authorized to place
1285 a request on the item - in particular,
1286 this routine does not check IndependentBranches
1287 and canreservefromotherbranches.
1289 Note also that this subroutine does not checks smart
1290 rules limits for item by reservesallowed/holds_per_record
1291 values, this complemented in calling code with calls and
1292 checks with CanItemBeReserved or CanBookBeReserved.
1296 sub IsAvailableForItemLevelRequest {
1299 my $pickup_branchcode = shift;
1300 # items_any_available is precalculated status passed from request.pl when set of items
1301 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1302 my $items_any_available = shift;
1304 my $dbh = C4::Context->dbh;
1305 # must check the notforloan setting of the itemtype
1306 # FIXME - a lot of places in the code do this
1307 # or something similar - need to be
1309 my $itemtype = $item->effective_itemtype;
1310 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1313 $notforloan_per_itemtype ||
1315 $item->notforloan > 0 ||
1317 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1319 if ($pickup_branchcode) {
1320 my $destination = Koha::Libraries->find($pickup_branchcode);
1321 return 0 unless $destination;
1322 return 0 unless $destination->pickup_location;
1323 return 0 unless $item->can_be_transferred( { to => $destination } );
1324 my $reserves_control_branch =
1325 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1326 my $branchitemrule =
1327 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1328 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1329 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1332 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1334 if ( $on_shelf_holds == 1 ) {
1336 } elsif ( $on_shelf_holds == 2 ) {
1338 # if we have this param predefined from outer caller sub, we just need
1339 # to return it, so we saving from having loop inside other loop:
1340 return $items_any_available ? 0 : 1
1341 if defined $items_any_available;
1343 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1344 return $any_available ? 0 : 1;
1345 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1346 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1350 =head2 ItemsAnyAvailableAndNotRestricted
1352 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1354 This function checks all items for specified biblionumber (numeric) against patron (object)
1355 and returns true (1) if at least one item available for loan/check out/present/not held
1356 and also checks other parameters logic which not restricts item for hold at all (for ex.
1357 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1361 sub ItemsAnyAvailableAndNotRestricted {
1364 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1366 foreach my $i (@items) {
1367 my $reserves_control_branch =
1368 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1369 my $branchitemrule =
1370 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1371 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1373 # we can return (end the loop) when first one found:
1376 || $i->notforloan > 0
1379 || IsItemOnHoldAndFound( $i->id )
1381 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1382 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1383 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1384 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1385 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1391 =head2 AlterPriority
1393 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1395 This function changes a reserve's priority up, down, to the top, or to the bottom.
1396 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1401 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1403 my $hold = Koha::Holds->find( $reserve_id );
1404 return unless $hold;
1406 if ( $hold->cancellationdate ) {
1407 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1411 if ( $where eq 'up' ) {
1412 return unless $prev_priority;
1413 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1414 } elsif ( $where eq 'down' ) {
1415 return unless $next_priority;
1416 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1417 } elsif ( $where eq 'top' ) {
1418 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1419 } elsif ( $where eq 'bottom' ) {
1420 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1423 # FIXME Should return the new priority
1426 =head2 ToggleLowestPriority
1428 ToggleLowestPriority( $borrowernumber, $biblionumber );
1430 This function sets the lowestPriority field to true if is false, and false if it is true.
1434 sub ToggleLowestPriority {
1435 my ( $reserve_id ) = @_;
1437 my $dbh = C4::Context->dbh;
1439 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1440 $sth->execute( $reserve_id );
1442 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1445 =head2 ToggleSuspend
1447 ToggleSuspend( $reserve_id );
1449 This function sets the suspend field to true if is false, and false if it is true.
1450 If the reserve is currently suspended with a suspend_until date, that date will
1451 be cleared when it is unsuspended.
1456 my ( $reserve_id, $suspend_until ) = @_;
1458 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1460 my $hold = Koha::Holds->find( $reserve_id );
1462 if ( $hold->is_suspended ) {
1465 $hold->suspend_hold( $suspend_until );
1472 borrowernumber => $borrowernumber,
1473 [ biblionumber => $biblionumber, ]
1474 [ suspend_until => $suspend_until, ]
1475 [ suspend => $suspend ]
1478 This function accepts a set of hash keys as its parameters.
1479 It requires either borrowernumber or biblionumber, or both.
1481 suspend_until is wholly optional.
1488 my $borrowernumber = $params{'borrowernumber'} || undef;
1489 my $biblionumber = $params{'biblionumber'} || undef;
1490 my $suspend_until = $params{'suspend_until'} || undef;
1491 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1493 $suspend_until = eval { dt_from_string($suspend_until) }
1494 if ( defined($suspend_until) );
1496 return unless ( $borrowernumber || $biblionumber );
1499 $params->{found} = undef;
1500 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1501 $params->{biblionumber} = $biblionumber if $biblionumber;
1503 my @holds = Koha::Holds->search($params);
1506 map { $_->suspend_hold($suspend_until) } @holds;
1509 map { $_->resume() } @holds;
1517 reserve_id => $reserve_id,
1519 [ignoreSetLowestRank => $ignoreSetLowestRank]
1524 _FixPriority({ biblionumber => $biblionumber});
1526 This routine adjusts the priority of a hold request and holds
1529 In the first form, where a reserve_id is passed, the priority of the
1530 hold is set to supplied rank, and other holds for that bib are adjusted
1531 accordingly. If the rank is "del", the hold is cancelled. If no rank
1532 is supplied, all of the holds on that bib have their priority adjusted
1533 as if the second form had been used.
1535 In the second form, where a biblionumber is passed, the holds on that
1536 bib (that are not captured) are sorted in order of increasing priority,
1537 then have reserves.priority set so that the first non-captured hold
1538 has its priority set to 1, the second non-captured hold has its priority
1539 set to 2, and so forth.
1541 In both cases, holds that have the lowestPriority flag on are have their
1542 priority adjusted to ensure that they remain at the end of the line.
1544 Note that the ignoreSetLowestRank parameter is meant to be used only
1545 when _FixPriority calls itself.
1550 my ( $params ) = @_;
1551 my $reserve_id = $params->{reserve_id};
1552 my $rank = $params->{rank} // '';
1553 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1554 my $biblionumber = $params->{biblionumber};
1556 my $dbh = C4::Context->dbh;
1559 if ( $reserve_id ) {
1560 $hold = Koha::Holds->find( $reserve_id );
1561 if (!defined $hold){
1562 # may have already been checked out and hold fulfilled
1563 $hold = Koha::Old::Holds->find( $reserve_id );
1565 return unless $hold;
1568 unless ( $biblionumber ) { # FIXME This is a very weird API
1569 $biblionumber = $hold->biblionumber;
1572 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1575 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1577 # make sure priority for waiting or in-transit items is 0
1581 WHERE reserve_id = ?
1582 AND found IN ('W', 'T', 'P')
1584 my $sth = $dbh->prepare($query);
1585 $sth->execute( $reserve_id );
1591 SELECT reserve_id, borrowernumber, reservedate
1593 WHERE biblionumber = ?
1594 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1595 ORDER BY priority ASC
1597 my $sth = $dbh->prepare($query);
1598 $sth->execute( $biblionumber );
1599 while ( my $line = $sth->fetchrow_hashref ) {
1600 push( @priority, $line );
1603 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1604 # To find the matching index
1606 my $key = -1; # to allow for 0 to be a valid result
1607 for ( $i = 0 ; $i < @priority ; $i++ ) {
1608 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1609 $key = $i; # save the index
1614 # if index exists in array then move it to new position
1615 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1616 my $new_rank = $rank -
1617 1; # $new_rank is what you want the new index to be in the array
1618 my $moving_item = splice( @priority, $key, 1 );
1619 splice( @priority, $new_rank, 0, $moving_item );
1622 # now fix the priority on those that are left....
1626 WHERE reserve_id = ?
1628 $sth = $dbh->prepare($query);
1629 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1632 $priority[$j]->{'reserve_id'}
1636 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1639 unless ( $ignoreSetLowestRank ) {
1640 while ( my $res = $sth->fetchrow_hashref() ) {
1642 reserve_id => $res->{'reserve_id'},
1644 ignoreSetLowestRank => 1
1650 =head2 _Findgroupreserve
1652 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1654 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1655 first match found. If neither, then we look for non-holds-queue based holds.
1656 Lookahead is the number of days to look in advance.
1658 C<&_Findgroupreserve> returns :
1659 C<@results> is an array of references-to-hash whose keys are mostly
1660 fields from the reserves table of the Koha database, plus
1661 C<biblioitemnumber>.
1663 This routine with either return:
1664 1 - Item specific holds from the holds queue
1665 2 - Title level holds from the holds queue
1666 3 - All holds for this biblionumber
1668 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1672 sub _Findgroupreserve {
1673 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1674 my $dbh = C4::Context->dbh;
1676 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1677 # check for exact targeted match
1678 my $item_level_target_query = qq{
1679 SELECT reserves.biblionumber AS biblionumber,
1680 reserves.borrowernumber AS borrowernumber,
1681 reserves.reservedate AS reservedate,
1682 reserves.branchcode AS branchcode,
1683 reserves.cancellationdate AS cancellationdate,
1684 reserves.found AS found,
1685 reserves.reservenotes AS reservenotes,
1686 reserves.priority AS priority,
1687 reserves.timestamp AS timestamp,
1688 biblioitems.biblioitemnumber AS biblioitemnumber,
1689 reserves.itemnumber AS itemnumber,
1690 reserves.reserve_id AS reserve_id,
1691 reserves.itemtype AS itemtype,
1692 reserves.non_priority AS non_priority
1694 JOIN biblioitems USING (biblionumber)
1695 JOIN hold_fill_targets USING (reserve_id)
1698 AND item_level_request = 1
1699 AND hold_fill_targets.itemnumber = ?
1700 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1704 my $sth = $dbh->prepare($item_level_target_query);
1705 $sth->execute($itemnumber, $lookahead||0);
1707 if ( my $data = $sth->fetchrow_hashref ) {
1708 push( @results, $data )
1709 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1711 return @results if @results;
1713 # check for title-level targeted match
1714 my $title_level_target_query = qq{
1715 SELECT reserves.biblionumber AS biblionumber,
1716 reserves.borrowernumber AS borrowernumber,
1717 reserves.reservedate AS reservedate,
1718 reserves.branchcode AS branchcode,
1719 reserves.cancellationdate AS cancellationdate,
1720 reserves.found AS found,
1721 reserves.reservenotes AS reservenotes,
1722 reserves.priority AS priority,
1723 reserves.timestamp AS timestamp,
1724 biblioitems.biblioitemnumber AS biblioitemnumber,
1725 reserves.itemnumber AS itemnumber,
1726 reserves.reserve_id AS reserve_id,
1727 reserves.itemtype AS itemtype,
1728 reserves.non_priority AS non_priority
1730 JOIN biblioitems USING (biblionumber)
1731 JOIN hold_fill_targets USING (reserve_id)
1734 AND item_level_request = 0
1735 AND hold_fill_targets.itemnumber = ?
1736 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1740 $sth = $dbh->prepare($title_level_target_query);
1741 $sth->execute($itemnumber, $lookahead||0);
1743 if ( my $data = $sth->fetchrow_hashref ) {
1744 push( @results, $data )
1745 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1747 return @results if @results;
1750 SELECT reserves.biblionumber AS biblionumber,
1751 reserves.borrowernumber AS borrowernumber,
1752 reserves.reservedate AS reservedate,
1753 reserves.waitingdate AS waitingdate,
1754 reserves.branchcode AS branchcode,
1755 reserves.cancellationdate AS cancellationdate,
1756 reserves.found AS found,
1757 reserves.reservenotes AS reservenotes,
1758 reserves.priority AS priority,
1759 reserves.timestamp AS timestamp,
1760 reserves.itemnumber AS itemnumber,
1761 reserves.reserve_id AS reserve_id,
1762 reserves.itemtype AS itemtype,
1763 reserves.non_priority AS non_priority
1765 WHERE reserves.biblionumber = ?
1766 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1767 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1771 $sth = $dbh->prepare($query);
1772 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1774 while ( my $data = $sth->fetchrow_hashref ) {
1775 push( @results, $data )
1776 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1781 =head2 _koha_notify_reserve
1783 _koha_notify_reserve( $hold->reserve_id );
1785 Sends a notification to the patron that their hold has been filled (through
1786 ModReserveAffect, _not_ ModReserveFill)
1788 The letter code for this notice may be found using the following query:
1790 select distinct letter_code
1791 from message_transports
1792 inner join message_attributes using (message_attribute_id)
1793 where message_name = 'Hold_Filled'
1795 This will probably sipmly be 'HOLD', but because it is defined in the database,
1796 it is subject to addition or change.
1798 The following tables are availalbe witin the notice:
1809 sub _koha_notify_reserve {
1810 my $reserve_id = shift;
1811 my $hold = Koha::Holds->find($reserve_id);
1812 my $borrowernumber = $hold->borrowernumber;
1814 my $patron = Koha::Patrons->find( $borrowernumber );
1816 # Try to get the borrower's email address
1817 my $to_address = $patron->notice_email_address;
1819 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1820 borrowernumber => $borrowernumber,
1821 message_name => 'Hold_Filled'
1824 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1826 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1828 my %letter_params = (
1829 module => 'reserves',
1830 branchcode => $hold->branchcode,
1831 lang => $patron->lang,
1833 'branches' => $library,
1834 'borrowers' => $patron->unblessed,
1835 'biblio' => $hold->biblionumber,
1836 'biblioitems' => $hold->biblionumber,
1837 'reserves' => $hold->unblessed,
1838 'items' => $hold->itemnumber,
1842 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.
1843 my $send_notification = sub {
1844 my ( $mtt, $letter_code ) = (@_);
1845 return unless defined $letter_code;
1846 $letter_params{letter_code} = $letter_code;
1847 $letter_params{message_transport_type} = $mtt;
1848 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1850 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1854 C4::Letters::EnqueueLetter( {
1856 borrowernumber => $borrowernumber,
1857 from_address => $admin_email_address,
1858 message_transport_type => $mtt,
1862 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1864 ( $mtt eq 'email' and not $to_address ) # No email address
1865 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1866 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1867 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1870 &$send_notification($mtt, $letter_code);
1871 $notification_sent++;
1873 #Making sure that a print notification is sent if no other transport types can be utilized.
1874 if (! $notification_sent) {
1875 &$send_notification('print', 'HOLD');
1880 =head2 _ShiftPriorityByDateAndPriority
1882 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1884 This increments the priority of all reserves after the one
1885 with either the lowest date after C<$reservedate>
1886 or the lowest priority after C<$priority>.
1888 It effectively makes room for a new reserve to be inserted with a certain
1889 priority, which is returned.
1891 This is most useful when the reservedate can be set by the user. It allows
1892 the new reserve to be placed before other reserves that have a later
1893 reservedate. Since priority also is set by the form in reserves/request.pl
1894 the sub accounts for that too.
1898 sub _ShiftPriorityByDateAndPriority {
1899 my ( $biblio, $resdate, $new_priority ) = @_;
1901 my $dbh = C4::Context->dbh;
1902 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1903 my $sth = $dbh->prepare( $query );
1904 $sth->execute( $biblio, $resdate, $new_priority );
1905 my $min_priority = $sth->fetchrow;
1906 # if no such matches are found, $new_priority remains as original value
1907 $new_priority = $min_priority if ( $min_priority );
1909 # Shift the priority up by one; works in conjunction with the next SQL statement
1910 $query = "UPDATE reserves
1911 SET priority = priority+1
1912 WHERE biblionumber = ?
1913 AND borrowernumber = ?
1916 my $sth_update = $dbh->prepare( $query );
1918 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1919 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1920 $sth = $dbh->prepare( $query );
1921 $sth->execute( $new_priority, $biblio );
1922 while ( my $row = $sth->fetchrow_hashref ) {
1923 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1926 return $new_priority; # so the caller knows what priority they wind up receiving
1931 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1933 Use when checking out an item to handle reserves
1934 If $cancelreserve boolean is set to true, it will remove existing reserve
1939 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1941 $cancelreserve //= 0;
1943 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1944 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1947 my $biblionumber = $res->{biblionumber};
1949 if ($res->{borrowernumber} == $borrowernumber) {
1950 ModReserveFill($res);
1954 # The item is reserved by someone else.
1955 # Find this item in the reserves
1957 my $borr_res = Koha::Holds->search({
1958 borrowernumber => $borrowernumber,
1959 biblionumber => $biblionumber,
1961 order_by => 'priority'
1965 # The item is reserved by the current patron
1966 ModReserveFill($borr_res->unblessed);
1969 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1970 RevertWaitingStatus({ itemnumber => $itemnumber });
1972 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1973 my $hold = Koha::Holds->find( $res->{reserve_id} );
1981 MergeHolds($dbh,$to_biblio, $from_biblio);
1983 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1988 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1989 my $sth = $dbh->prepare(
1990 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1992 $sth->execute($from_biblio);
1993 if ( my $data = $sth->fetchrow_hashref() ) {
1995 # holds exist on old record, if not we don't need to do anything
1996 $sth = $dbh->prepare(
1997 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1998 $sth->execute( $to_biblio, $from_biblio );
2001 # don't reorder those already waiting
2003 $sth = $dbh->prepare(
2004 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2006 my $upd_sth = $dbh->prepare(
2007 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2008 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2010 $sth->execute( $to_biblio );
2012 while ( my $reserve = $sth->fetchrow_hashref() ) {
2014 $priority, $to_biblio,
2015 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2016 $reserve->{'itemnumber'}
2023 =head2 RevertWaitingStatus
2025 RevertWaitingStatus({ itemnumber => $itemnumber });
2027 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2029 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2030 item level hold, even if it was only a bibliolevel hold to
2031 begin with. This is because we can no longer know if a hold
2032 was item-level or bib-level after a hold has been set to
2037 sub RevertWaitingStatus {
2038 my ( $params ) = @_;
2039 my $itemnumber = $params->{'itemnumber'};
2041 return unless ( $itemnumber );
2043 my $dbh = C4::Context->dbh;
2045 ## Get the waiting reserve we want to revert
2046 my $hold = Koha::Holds->search(
2048 itemnumber => $itemnumber,
2049 found => { not => undef },
2053 ## Increment the priority of all other non-waiting
2054 ## reserves for this bib record
2055 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2056 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2058 ## Fix up the currently waiting reserve
2063 waitingdate => undef,
2064 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2068 _FixPriority( { biblionumber => $hold->biblionumber } );
2077 branchcode => $branchcode,
2078 borrowernumber => $borrowernumber,
2079 biblionumber => $biblionumber,
2080 [ itemnumber => $itemnumber, ]
2081 [ barcode => $barcode, ]
2085 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2087 The letter code will be HOLD_SLIP, and the following tables are
2088 available within the slip:
2101 my $branchcode = $args->{branchcode};
2102 my $reserve_id = $args->{reserve_id};
2104 my $hold = Koha::Holds->find($reserve_id);
2105 return unless $hold;
2107 my $patron = $hold->borrower;
2108 my $reserve = $hold->unblessed;
2110 return C4::Letters::GetPreparedLetter (
2111 module => 'circulation',
2112 letter_code => 'HOLD_SLIP',
2113 branchcode => $branchcode,
2114 lang => $patron->lang,
2116 'reserves' => $reserve,
2117 'branches' => $reserve->{branchcode},
2118 'borrowers' => $reserve->{borrowernumber},
2119 'biblio' => $reserve->{biblionumber},
2120 'biblioitems' => $reserve->{biblionumber},
2121 'items' => $reserve->{itemnumber},
2126 =head2 GetReservesControlBranch
2128 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2130 Return the branchcode to be used to determine which reserves
2131 policy applies to a transaction.
2133 C<$item> is a hashref for an item. Only 'homebranch' is used.
2135 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2139 sub GetReservesControlBranch {
2140 my ( $item, $borrower ) = @_;
2142 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2145 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2146 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2152 =head2 CalculatePriority
2154 my $p = CalculatePriority($biblionumber, $resdate);
2156 Calculate priority for a new reserve on biblionumber, placing it at
2157 the end of the line of all holds whose start date falls before
2158 the current system time and that are neither on the hold shelf
2161 The reserve date parameter is optional; if it is supplied, the
2162 priority is based on the set of holds whose start date falls before
2163 the parameter value.
2165 After calculation of this priority, it is recommended to call
2166 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2171 sub CalculatePriority {
2172 my ( $biblionumber, $resdate ) = @_;
2175 SELECT COUNT(*) FROM reserves
2176 WHERE biblionumber = ?
2178 AND (found IS NULL OR found = '')
2180 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2182 $sql.= ' AND ( reservedate <= ? )';
2185 $sql.= ' AND ( reservedate < NOW() )';
2187 my $dbh = C4::Context->dbh();
2188 my @row = $dbh->selectrow_array(
2191 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2194 return @row ? $row[0]+1 : 1;
2197 =head2 IsItemOnHoldAndFound
2199 my $bool = IsItemFoundHold( $itemnumber );
2201 Returns true if the item is currently on hold
2202 and that hold has a non-null found status ( W, T, etc. )
2206 sub IsItemOnHoldAndFound {
2207 my ($itemnumber) = @_;
2209 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2211 my $found = $rs->count(
2213 itemnumber => $itemnumber,
2214 found => { '!=' => undef }
2221 =head2 GetMaxPatronHoldsForRecord
2223 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2225 For multiple holds on a given record for a given patron, the max
2226 number of record level holds that a patron can be placed is the highest
2227 value of the holds_per_record rule for each item if the record for that
2228 patron. This subroutine finds and returns the highest holds_per_record
2229 rule value for a given patron id and record id.
2233 sub GetMaxPatronHoldsForRecord {
2234 my ( $borrowernumber, $biblionumber ) = @_;
2236 my $patron = Koha::Patrons->find($borrowernumber);
2237 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2239 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2241 my $categorycode = $patron->categorycode;
2243 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2246 foreach my $item (@items) {
2247 my $itemtype = $item->effective_itemtype();
2249 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2251 my $rule = Koha::CirculationRules->get_effective_rule({
2252 categorycode => $categorycode,
2253 itemtype => $itemtype,
2254 branchcode => $branchcode,
2255 rule_name => 'holds_per_record'
2257 my $holds_per_record = $rule ? $rule->rule_value : 0;
2258 $max = $holds_per_record if $holds_per_record > $max;
2266 Koha Development Team <http://koha-community.org/>