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;
51 use List::MoreUtils qw( firstidx any );
53 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
57 C4::Reserves - Koha functions for dealing with reservation.
65 This modules provides somes functions to deal with reservations.
67 Reserves are stored in reserves table.
68 The following columns contains important values :
69 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
70 =0 : then the reserve is being dealed
71 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
72 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
73 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
74 F(inished) : the reserve has been completed, and is done
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
113 &ModReserveMinusPriority
119 &CanReserveBeCanceledFromOpac
120 &CancelExpiredReserves
122 &AutoUnsuspendReserves
124 &IsAvailableForItemLevelRequest
125 ItemsAnyAvailableAndNotRestricted
128 &ToggleLowestPriority
134 &GetReservesControlBranch
138 GetMaxPatronHoldsForRecord
140 @EXPORT_OK = qw( MergeHolds );
147 branchcode => $branchcode,
148 borrowernumber => $borrowernumber,
149 biblionumber => $biblionumber,
150 priority => $priority,
151 reservation_date => $reservation_date,
152 expiration_date => $expiration_date,
155 itemnumber => $itemnumber,
157 itemtype => $itemtype,
161 Adds reserve and generates HOLDPLACED message.
163 The following tables are available witin the HOLDPLACED message:
176 my $branch = $params->{branchcode};
177 my $borrowernumber = $params->{borrowernumber};
178 my $biblionumber = $params->{biblionumber};
179 my $priority = $params->{priority};
180 my $resdate = $params->{reservation_date};
181 my $expdate = $params->{expiration_date};
182 my $notes = $params->{notes};
183 my $title = $params->{title};
184 my $checkitem = $params->{itemnumber};
185 my $found = $params->{found};
186 my $itemtype = $params->{itemtype};
188 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
189 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
191 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
193 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
194 # of the document, we force the value $priority and $found .
195 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
196 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
199 # If item is already checked out, it cannot be set waiting
202 # The item can't be waiting if it needs a transfer
203 && $item->holdingbranch eq $branch
205 # Similarly, if in transit it can't be waiting
206 && !$item->get_transfer
208 # If we can't hold damaged items, and it is damaged, it can't be waiting
209 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
211 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
212 && !$item->current_holds->count )
219 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
221 # Make room in reserves for this before those of a later reserve date
222 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
227 # If the reserv had the waiting status, we had the value of the resdate
228 if ( $found && $found eq 'W' ) {
229 $waitingdate = $resdate;
232 # Don't add itemtype limit if specific item is selected
233 $itemtype = undef if $checkitem;
235 # updates take place here
236 my $hold = Koha::Hold->new(
238 borrowernumber => $borrowernumber,
239 biblionumber => $biblionumber,
240 reservedate => $resdate,
241 branchcode => $branch,
242 priority => $priority,
243 reservenotes => $notes,
244 itemnumber => $checkitem,
246 waitingdate => $waitingdate,
247 expirationdate => $expdate,
248 itemtype => $itemtype,
249 item_level_hold => $checkitem ? 1 : 0,
252 $hold->set_waiting() if $found && $found eq 'W';
254 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
255 if C4::Context->preference('HoldsLog');
257 my $reserve_id = $hold->id();
259 # add a reserve fee if needed
260 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
261 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
262 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
265 _FixPriority({ biblionumber => $biblionumber});
267 # Send e-mail to librarian if syspref is active
268 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
269 my $patron = Koha::Patrons->find( $borrowernumber );
270 my $library = $patron->library;
271 if ( my $letter = C4::Letters::GetPreparedLetter (
272 module => 'reserves',
273 letter_code => 'HOLDPLACED',
274 branchcode => $branch,
275 lang => $patron->lang,
277 'branches' => $library->unblessed,
278 'borrowers' => $patron->unblessed,
279 'biblio' => $biblionumber,
280 'biblioitems' => $biblionumber,
281 'items' => $checkitem,
282 'reserves' => $hold->unblessed,
286 my $branch_email_address = $library->inbound_email_address;
288 C4::Letters::EnqueueLetter(
291 borrowernumber => $borrowernumber,
292 message_transport_type => 'email',
293 to_address => $branch_email_address,
302 =head2 CanBookBeReserved
304 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
305 if ($canReserve eq 'OK') { #We can reserve this Item! }
307 $params are passed directly through to CanItemBeReserved
309 See CanItemBeReserved() for possible return values.
313 sub CanBookBeReserved{
314 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
316 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
317 #get items linked via host records
318 my @hostitems = get_hostitemnumbers_of($biblionumber);
320 push (@itemnumbers, @hostitems);
323 my $canReserve = { status => '' };
324 foreach my $itemnumber (@itemnumbers) {
325 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
326 return { status => 'OK' } if $canReserve->{status} eq 'OK';
331 =head2 CanItemBeReserved
333 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
334 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
336 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
337 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
338 current checkout against the high holds threshold
340 @RETURNS { status => OK }, if the Item can be reserved.
341 { status => ageRestricted }, if the Item is age restricted for this borrower.
342 { status => damaged }, if the Item is damaged.
343 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
344 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
345 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
346 { status => notReservable }, if holds on this item are not allowed
347 { status => libraryNotFound }, if given branchcode is not an existing library
348 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
349 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
350 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
354 sub CanItemBeReserved {
355 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
357 my $dbh = C4::Context->dbh;
358 my $ruleitemtype; # itemtype of the matching issuing rule
359 my $allowedreserves = 0; # Total number of holds allowed across all records
360 my $holds_per_record = 1; # Total number of holds allowed for this one given record
361 my $holds_per_day; # Default to unlimited
363 # we retrieve borrowers and items informations #
364 # item->{itype} will come for biblioitems if necessery
365 my $item = Koha::Items->find($itemnumber);
366 my $biblio = $item->biblio;
367 my $patron = Koha::Patrons->find( $borrowernumber );
368 my $borrower = $patron->unblessed;
370 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
371 return { status =>'damaged' }
373 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
375 # Check for the age restriction
376 my ( $ageRestriction, $daysToAgeRestriction ) =
377 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
378 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
380 # Check that the patron doesn't have an item level hold on this item already
381 return { status =>'itemAlreadyOnHold' }
382 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
384 my $controlbranch = C4::Context->preference('ReservesControlBranch');
387 SELECT count(*) AS count
389 LEFT JOIN items USING (itemnumber)
390 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
391 LEFT JOIN borrowers USING (borrowernumber)
392 WHERE borrowernumber = ?
396 my $branchfield = "reserves.branchcode";
398 if ( $controlbranch eq "ItemHomeLibrary" ) {
399 $branchfield = "items.homebranch";
400 $branchcode = $item->homebranch;
402 elsif ( $controlbranch eq "PatronLibrary" ) {
403 $branchfield = "borrowers.branchcode";
404 $branchcode = $borrower->{branchcode};
408 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
409 $ruleitemtype = $rights->{itemtype};
410 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
411 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
412 $holds_per_day = $rights->{holds_per_day};
415 $ruleitemtype = undef;
418 my $search_params = {
419 borrowernumber => $borrowernumber,
420 biblionumber => $item->biblionumber,
422 $search_params->{found} = undef if $params->{ignore_found_holds};
424 my $holds = Koha::Holds->search($search_params);
425 if ( defined $holds_per_record && $holds_per_record ne ''
426 && $holds->count() >= $holds_per_record ) {
427 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
430 my $today_holds = Koha::Holds->search({
431 borrowernumber => $borrowernumber,
432 reservedate => dt_from_string->date
435 if ( defined $holds_per_day && $holds_per_day ne ''
436 && $today_holds->count() >= $holds_per_day )
438 return { status => 'tooManyReservesToday', limit => $holds_per_day };
443 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
445 # If using item-level itypes, fall back to the record
446 # level itemtype if the hold has no associated item
448 C4::Context->preference('item-level_itypes')
449 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
450 : " AND biblioitems.itemtype = ?"
451 if defined $ruleitemtype;
453 my $sthcount = $dbh->prepare($querycount);
455 if ( defined $ruleitemtype ) {
456 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
459 $sthcount->execute( $borrowernumber, $branchcode );
462 my $reservecount = "0";
463 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
464 $reservecount = $rowcount->{count};
467 # we check if it's ok or not
468 if ( defined $allowedreserves && $allowedreserves ne ''
469 && $reservecount >= $allowedreserves ) {
470 return { status => 'tooManyReserves', limit => $allowedreserves };
473 # Now we need to check hold limits by patron category
474 my $rule = Koha::CirculationRules->get_effective_rule(
476 categorycode => $borrower->{categorycode},
477 branchcode => $branchcode,
478 rule_name => 'max_holds',
481 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
482 my $total_holds_count = Koha::Holds->search(
484 borrowernumber => $borrower->{borrowernumber}
488 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
491 my $reserves_control_branch =
492 GetReservesControlBranch( $item->unblessed(), $borrower );
494 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
496 if ( $branchitemrule->{holdallowed} == 0 ) {
497 return { status => 'notReservable' };
500 if ( $branchitemrule->{holdallowed} == 1
501 && $borrower->{branchcode} ne $item->homebranch )
503 return { status => 'cannotReserveFromOtherBranches' };
506 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
507 if ( $branchitemrule->{holdallowed} == 3) {
508 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
509 return { status => 'branchNotInHoldGroup' };
513 # If reservecount is ok, we check item branch if IndependentBranches is ON
514 # and canreservefromotherbranches is OFF
515 if ( C4::Context->preference('IndependentBranches')
516 and !C4::Context->preference('canreservefromotherbranches') )
518 if ( $item->homebranch ne $borrower->{branchcode} ) {
519 return { status => 'cannotReserveFromOtherBranches' };
523 if ($pickup_branchcode) {
524 my $destination = Koha::Libraries->find({
525 branchcode => $pickup_branchcode,
528 unless ($destination) {
529 return { status => 'libraryNotFound' };
531 unless ($destination->pickup_location) {
532 return { status => 'libraryNotPickupLocation' };
534 unless ($item->can_be_transferred({ to => $destination })) {
535 return { status => 'cannotBeTransferred' };
537 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
538 return { status => 'pickupNotInHoldGroup' };
540 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
541 return { status => 'pickupNotInHoldGroup' };
545 return { status => 'OK' };
548 =head2 CanReserveBeCanceledFromOpac
550 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
552 returns 1 if reserve can be cancelled by user from OPAC.
553 First check if reserve belongs to user, next checks if reserve is not in
554 transfer or waiting status
558 sub CanReserveBeCanceledFromOpac {
559 my ($reserve_id, $borrowernumber) = @_;
561 return unless $reserve_id and $borrowernumber;
562 my $reserve = Koha::Holds->find($reserve_id);
564 return 0 unless $reserve->borrowernumber == $borrowernumber;
565 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
571 =head2 GetOtherReserves
573 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
575 Check queued list of this document and check if this document must be transferred
579 sub GetOtherReserves {
580 my ($itemnumber) = @_;
583 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
584 if ($checkreserves) {
585 my $item = Koha::Items->find($itemnumber);
586 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
587 $messages->{'transfert'} = $checkreserves->{'branchcode'};
588 #minus priorities of others reservs
589 ModReserveMinusPriority(
591 $checkreserves->{'reserve_id'},
594 #launch the subroutine dotransfer
595 C4::Items::ModItemTransfer(
597 $item->holdingbranch,
598 $checkreserves->{'branchcode'},
604 #step 2b : case of a reservation on the same branch, set the waiting status
606 $messages->{'waiting'} = 1;
607 ModReserveMinusPriority(
609 $checkreserves->{'reserve_id'},
611 ModReserveStatus($itemnumber,'W');
614 $nextreservinfo = $checkreserves;
617 return ( $messages, $nextreservinfo );
620 =head2 ChargeReserveFee
622 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
624 Charge the fee for a reserve (if $fee > 0)
628 sub ChargeReserveFee {
629 my ( $borrowernumber, $fee, $title ) = @_;
630 return if !$fee || $fee == 0; # the last test is needed to include 0.00
631 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
634 description => $title,
636 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
637 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
638 interface => C4::Context->interface,
639 invoice_type => undef,
648 $fee = GetReserveFee( $borrowernumber, $biblionumber );
650 Calculate the fee for a reserve (if applicable).
655 my ( $borrowernumber, $biblionumber ) = @_;
657 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
660 SELECT COUNT(*) FROM items
661 LEFT JOIN issues USING (itemnumber)
662 WHERE items.biblionumber=? AND issues.issue_id IS NULL
665 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
668 my $dbh = C4::Context->dbh;
669 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
670 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
671 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
672 # This is a reconstruction of the old code:
673 # Compare number of items with items issued, and optionally check holds
674 # If not all items are issued and there are no holds: charge no fee
675 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
676 my ( $notissued, $reserved );
677 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
680 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
681 ( $biblionumber, $borrowernumber ) );
682 $fee = 0 if $reserved == 0;
688 =head2 GetReserveStatus
690 $reservestatus = GetReserveStatus($itemnumber);
692 Takes an itemnumber and returns the status of the reserve placed on it.
693 If several reserves exist, the reserve with the lower priority is given.
697 ## FIXME: I don't think this does what it thinks it does.
698 ## It only ever checks the first reserve result, even though
699 ## multiple reserves for that bib can have the itemnumber set
700 ## the sub is only used once in the codebase.
701 sub GetReserveStatus {
702 my ($itemnumber) = @_;
704 my $dbh = C4::Context->dbh;
706 my ($sth, $found, $priority);
708 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
709 $sth->execute($itemnumber);
710 ($found, $priority) = $sth->fetchrow_array;
714 return 'Waiting' if $found eq 'W' and $priority == 0;
715 return 'Finished' if $found eq 'F';
718 return 'Reserved' if defined $priority && $priority > 0;
720 return ''; # empty string here will remove need for checking undef, or less log lines
725 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
726 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
727 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
729 Find a book in the reserves.
731 C<$itemnumber> is the book's item number.
732 C<$lookahead> is the number of days to look in advance for future reserves.
734 As I understand it, C<&CheckReserves> looks for the given item in the
735 reserves. If it is found, that's a match, and C<$status> is set to
738 Otherwise, it finds the most important item in the reserves with the
739 same biblio number as this book (I'm not clear on this) and returns it
740 with C<$status> set to C<Reserved>.
742 C<&CheckReserves> returns a two-element list:
744 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
746 C<$reserve> is the reserve item that matched. It is a
747 reference-to-hash whose keys are mostly the fields of the reserves
748 table in the Koha database.
753 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
754 my $dbh = C4::Context->dbh;
757 if (C4::Context->preference('item-level_itypes')){
759 SELECT items.biblionumber,
760 items.biblioitemnumber,
761 itemtypes.notforloan,
762 items.notforloan AS itemnotforloan,
768 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
769 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
774 SELECT items.biblionumber,
775 items.biblioitemnumber,
776 itemtypes.notforloan,
777 items.notforloan AS itemnotforloan,
783 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
784 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
789 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
790 $sth->execute($item);
793 $sth = $dbh->prepare("$select WHERE barcode = ?");
794 $sth->execute($barcode);
796 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
797 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
798 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
800 return unless $itemnumber; # bail if we got nothing.
801 # if item is not for loan it cannot be reserved either.....
802 # except where items.notforloan < 0 : This indicates the item is holdable.
804 my @SkipHoldTrapOnNotForLoanValue = split( '|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
805 return if @SkipHoldTrapOnNotForLoanValue && grep( $notforloan_per_item, @SkipHoldTrapOnNotForLoanValue );
807 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
808 return if $dont_trap or $notforloan_per_itemtype;
810 # Find this item in the reserves
811 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
813 # $priority and $highest are used to find the most important item
814 # in the list returned by &_Findgroupreserve. (The lower $priority,
815 # the more important the item.)
816 # $highest is the most important item we've seen so far.
819 if (scalar @reserves) {
820 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
821 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
822 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
824 my $priority = 10000000;
825 foreach my $res (@reserves) {
826 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
827 if ($res->{'found'} eq 'W') {
828 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
830 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
835 my $local_hold_match;
837 if ($LocalHoldsPriority) {
838 $patron = Koha::Patrons->find( $res->{borrowernumber} );
839 $item = Koha::Items->find($itemnumber);
841 my $local_holds_priority_item_branchcode =
842 $item->$LocalHoldsPriorityItemControl;
843 my $local_holds_priority_patron_branchcode =
844 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
846 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
847 ? $patron->branchcode
850 $local_holds_priority_item_branchcode eq
851 $local_holds_priority_patron_branchcode;
854 # See if this item is more important than what we've got so far
855 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
856 $item ||= Koha::Items->find($itemnumber);
857 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
858 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
859 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
860 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
861 next if ($branchitemrule->{'holdallowed'} == 0);
862 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
863 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
864 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
865 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
866 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
867 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
868 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
869 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
870 $priority = $res->{'priority'};
872 last if $local_hold_match;
878 # If we get this far, then no exact match was found.
879 # We return the most important (i.e. next) reservation.
881 $highest->{'itemnumber'} = $item;
882 return ( "Reserved", $highest, \@reserves );
888 =head2 CancelExpiredReserves
890 CancelExpiredReserves();
892 Cancels all reserves with an expiration date from before today.
896 sub CancelExpiredReserves {
897 my $today = dt_from_string();
898 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
899 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
901 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
902 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
903 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
905 # FIXME To move to Koha::Holds->search_expired (?)
906 my $holds = Koha::Holds->search( $params );
908 while ( my $hold = $holds->next ) {
909 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
911 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
913 my $cancel_params = {};
914 if ( $hold->found eq 'W' ) {
915 $cancel_params->{charge_cancel_fee} = 1;
917 $hold->cancel( $cancel_params );
921 =head2 AutoUnsuspendReserves
923 AutoUnsuspendReserves();
925 Unsuspends all suspended reserves with a suspend_until date from before today.
929 sub AutoUnsuspendReserves {
930 my $today = dt_from_string();
932 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
934 map { $_->resume() } @holds;
939 ModReserve({ rank => $rank,
940 reserve_id => $reserve_id,
941 branchcode => $branchcode
942 [, itemnumber => $itemnumber ]
943 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
946 Change a hold request's priority or cancel it.
948 C<$rank> specifies the effect of the change. If C<$rank>
949 is 'W' or 'n', nothing happens. This corresponds to leaving a
950 request alone when changing its priority in the holds queue
953 If C<$rank> is 'del', the hold request is cancelled.
955 If C<$rank> is an integer greater than zero, the priority of
956 the request is set to that value. Since priority != 0 means
957 that the item is not waiting on the hold shelf, setting the
958 priority to a non-zero value also sets the request's found
959 status and waiting date to NULL.
961 The optional C<$itemnumber> parameter is used only when
962 C<$rank> is a non-zero integer; if supplied, the itemnumber
963 of the hold request is set accordingly; if omitted, the itemnumber
966 B<FIXME:> Note that the forgoing can have the effect of causing
967 item-level hold requests to turn into title-level requests. This
968 will be fixed once reserves has separate columns for requested
969 itemnumber and supplying itemnumber.
976 my $rank = $params->{'rank'};
977 my $reserve_id = $params->{'reserve_id'};
978 my $branchcode = $params->{'branchcode'};
979 my $itemnumber = $params->{'itemnumber'};
980 my $suspend_until = $params->{'suspend_until'};
981 my $borrowernumber = $params->{'borrowernumber'};
982 my $biblionumber = $params->{'biblionumber'};
984 return if $rank eq "W";
985 return if $rank eq "n";
987 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
990 unless ( $reserve_id ) {
991 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
992 return unless $holds->count; # FIXME Should raise an exception
993 $hold = $holds->next;
994 $reserve_id = $hold->reserve_id;
997 $hold ||= Koha::Holds->find($reserve_id);
999 if ( $rank eq "del" ) {
1002 elsif ($rank =~ /^\d+/ and $rank > 0) {
1003 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1004 if C4::Context->preference('HoldsLog');
1008 branchcode => $branchcode,
1009 itemnumber => $itemnumber,
1011 waitingdate => undef
1013 if (exists $params->{reservedate}) {
1014 $properties->{reservedate} = $params->{reservedate} || undef;
1016 if (exists $params->{expirationdate}) {
1017 $properties->{expirationdate} = $params->{expirationdate} || undef;
1020 $hold->set($properties)->store();
1022 if ( defined( $suspend_until ) ) {
1023 if ( $suspend_until ) {
1024 $suspend_until = eval { dt_from_string( $suspend_until ) };
1025 $hold->suspend_hold( $suspend_until );
1027 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1028 # If the hold is not suspended, this does nothing.
1029 $hold->set( { suspend_until => undef } )->store();
1033 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1037 =head2 ModReserveFill
1039 &ModReserveFill($reserve);
1041 Fill a reserve. If I understand this correctly, this means that the
1042 reserved book has been found and given to the patron who reserved it.
1044 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1045 whose keys are fields from the reserves table in the Koha database.
1049 sub ModReserveFill {
1051 my $reserve_id = $res->{'reserve_id'};
1053 my $hold = Koha::Holds->find($reserve_id);
1054 # get the priority on this record....
1055 my $priority = $hold->priority;
1057 # update the hold statuses, no need to store it though, we will be deleting it anyway
1065 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1066 if C4::Context->preference('HoldsLog');
1068 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1069 Koha::Old::Hold->new( $hold->unblessed() )->store();
1073 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1074 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1075 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1078 # now fix the priority on the others (if the priority wasn't
1079 # already sorted!)....
1080 unless ( $priority == 0 ) {
1081 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1085 =head2 ModReserveStatus
1087 &ModReserveStatus($itemnumber, $newstatus);
1089 Update the reserve status for the active (priority=0) reserve.
1091 $itemnumber is the itemnumber the reserve is on
1093 $newstatus is the new status.
1097 sub ModReserveStatus {
1099 #first : check if we have a reservation for this item .
1100 my ($itemnumber, $newstatus) = @_;
1101 my $dbh = C4::Context->dbh;
1103 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1104 my $sth_set = $dbh->prepare($query);
1105 $sth_set->execute( $newstatus, $itemnumber );
1107 my $item = Koha::Items->find($itemnumber);
1108 if ( $item->location && $item->location eq 'CART'
1109 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1111 CartToShelf( $itemnumber );
1115 =head2 ModReserveAffect
1117 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1119 This function affect an item and a status for a given reserve, either fetched directly
1120 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1121 is given, only first reserve returned is affected, which is ok for anything but
1124 if $transferToDo is not set, then the status is set to "Waiting" as well.
1125 otherwise, a transfer is on the way, and the end of the transfer will
1126 take care of the waiting status
1130 sub ModReserveAffect {
1131 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1132 my $dbh = C4::Context->dbh;
1134 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1135 # attached to $itemnumber
1136 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1137 $sth->execute($itemnumber);
1138 my ($biblionumber) = $sth->fetchrow;
1140 # get request - need to find out if item is already
1141 # waiting in order to not send duplicate hold filled notifications
1144 # Find hold by id if we have it
1145 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1146 # Find item level hold for this item if there is one
1147 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1148 # Find record level hold if there is no item level hold
1149 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1151 return unless $hold;
1153 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1155 $hold->itemnumber($itemnumber);
1156 $hold->set_waiting($transferToDo);
1158 if( !$transferToDo ){
1159 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1160 my $transfers = Koha::Item::Transfers->search({
1161 itemnumber => $itemnumber,
1162 datearrived => undef
1164 while( my $transfer = $transfers->next ){
1165 $transfer->datearrived( dt_from_string() )->store;
1170 _FixPriority( { biblionumber => $biblionumber } );
1171 my $item = Koha::Items->find($itemnumber);
1172 if ( $item->location && $item->location eq 'CART'
1173 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1174 CartToShelf( $itemnumber );
1177 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1178 if C4::Context->preference('HoldsLog');
1183 =head2 ModReserveCancelAll
1185 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1187 function to cancel reserv,check other reserves, and transfer document if it's necessary
1191 sub ModReserveCancelAll {
1194 my ( $itemnumber, $borrowernumber ) = @_;
1196 #step 1 : cancel the reservation
1197 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1198 return unless $holds->count;
1199 $holds->next->cancel;
1201 #step 2 launch the subroutine of the others reserves
1202 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1204 return ( $messages, $nextreservinfo->{borrowernumber} );
1207 =head2 ModReserveMinusPriority
1209 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1211 Reduce the values of queued list
1215 sub ModReserveMinusPriority {
1216 my ( $itemnumber, $reserve_id ) = @_;
1218 #first step update the value of the first person on reserv
1219 my $dbh = C4::Context->dbh;
1222 SET priority = 0 , itemnumber = ?
1223 WHERE reserve_id = ?
1225 my $sth_upd = $dbh->prepare($query);
1226 $sth_upd->execute( $itemnumber, $reserve_id );
1227 # second step update all others reserves
1228 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1231 =head2 IsAvailableForItemLevelRequest
1233 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1235 Checks whether a given item record is available for an
1236 item-level hold request. An item is available if
1238 * it is not lost AND
1239 * it is not damaged AND
1240 * it is not withdrawn AND
1241 * a waiting or in transit reserve is placed on
1242 * does not have a not for loan value > 0
1244 Need to check the issuingrules onshelfholds column,
1245 if this is set items on the shelf can be placed on hold
1247 Note that IsAvailableForItemLevelRequest() does not
1248 check if the staff operator is authorized to place
1249 a request on the item - in particular,
1250 this routine does not check IndependentBranches
1251 and canreservefromotherbranches.
1253 Note also that this subroutine does not checks smart
1254 rules limits for item by reservesallowed/holds_per_record
1255 values, this complemented in calling code with calls and
1256 checks with CanItemBeReserved or CanBookBeReserved.
1260 sub IsAvailableForItemLevelRequest {
1263 my $pickup_branchcode = shift;
1264 # items_any_available is precalculated status passed from request.pl when set of items
1265 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1266 my $items_any_available = shift;
1268 my $dbh = C4::Context->dbh;
1269 # must check the notforloan setting of the itemtype
1270 # FIXME - a lot of places in the code do this
1271 # or something similar - need to be
1273 my $itemtype = $item->effective_itemtype;
1274 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1277 $notforloan_per_itemtype ||
1279 $item->notforloan > 0 ||
1281 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1283 if ($pickup_branchcode) {
1284 my $destination = Koha::Libraries->find($pickup_branchcode);
1285 return 0 unless $destination;
1286 return 0 unless $destination->pickup_location;
1287 return 0 unless $item->can_be_transferred( { to => $destination } );
1288 my $reserves_control_branch =
1289 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1290 my $branchitemrule =
1291 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1292 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1293 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1296 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1298 if ( $on_shelf_holds == 1 ) {
1300 } elsif ( $on_shelf_holds == 2 ) {
1302 # if we have this param predefined from outer caller sub, we just need
1303 # to return it, so we saving from having loop inside other loop:
1304 return $items_any_available ? 0 : 1
1305 if defined $items_any_available;
1307 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1308 return $any_available ? 0 : 1;
1309 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1310 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1314 =head2 ItemsAnyAvailableAndNotRestricted
1316 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1318 This function checks all items for specified biblionumber (numeric) against patron (object)
1319 and returns true (1) if at least one item available for loan/check out/present/not held
1320 and also checks other parameters logic which not restricts item for hold at all (for ex.
1321 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1325 sub ItemsAnyAvailableAndNotRestricted {
1328 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1330 foreach my $i (@items) {
1331 my $reserves_control_branch =
1332 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1333 my $branchitemrule =
1334 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1335 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1337 # we can return (end the loop) when first one found:
1340 || $i->notforloan > 0
1343 || IsItemOnHoldAndFound( $i->id )
1345 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1346 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1347 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1348 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1349 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1355 =head2 AlterPriority
1357 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1359 This function changes a reserve's priority up, down, to the top, or to the bottom.
1360 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1365 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1367 my $hold = Koha::Holds->find( $reserve_id );
1368 return unless $hold;
1370 if ( $hold->cancellationdate ) {
1371 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1375 if ( $where eq 'up' ) {
1376 return unless $prev_priority;
1377 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1378 } elsif ( $where eq 'down' ) {
1379 return unless $next_priority;
1380 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1381 } elsif ( $where eq 'top' ) {
1382 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1383 } elsif ( $where eq 'bottom' ) {
1384 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1387 # FIXME Should return the new priority
1390 =head2 ToggleLowestPriority
1392 ToggleLowestPriority( $borrowernumber, $biblionumber );
1394 This function sets the lowestPriority field to true if is false, and false if it is true.
1398 sub ToggleLowestPriority {
1399 my ( $reserve_id ) = @_;
1401 my $dbh = C4::Context->dbh;
1403 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1404 $sth->execute( $reserve_id );
1406 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1409 =head2 ToggleSuspend
1411 ToggleSuspend( $reserve_id );
1413 This function sets the suspend field to true if is false, and false if it is true.
1414 If the reserve is currently suspended with a suspend_until date, that date will
1415 be cleared when it is unsuspended.
1420 my ( $reserve_id, $suspend_until ) = @_;
1422 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1424 my $hold = Koha::Holds->find( $reserve_id );
1426 if ( $hold->is_suspended ) {
1429 $hold->suspend_hold( $suspend_until );
1436 borrowernumber => $borrowernumber,
1437 [ biblionumber => $biblionumber, ]
1438 [ suspend_until => $suspend_until, ]
1439 [ suspend => $suspend ]
1442 This function accepts a set of hash keys as its parameters.
1443 It requires either borrowernumber or biblionumber, or both.
1445 suspend_until is wholly optional.
1452 my $borrowernumber = $params{'borrowernumber'} || undef;
1453 my $biblionumber = $params{'biblionumber'} || undef;
1454 my $suspend_until = $params{'suspend_until'} || undef;
1455 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1457 $suspend_until = eval { dt_from_string($suspend_until) }
1458 if ( defined($suspend_until) );
1460 return unless ( $borrowernumber || $biblionumber );
1463 $params->{found} = undef;
1464 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1465 $params->{biblionumber} = $biblionumber if $biblionumber;
1467 my @holds = Koha::Holds->search($params);
1470 map { $_->suspend_hold($suspend_until) } @holds;
1473 map { $_->resume() } @holds;
1481 reserve_id => $reserve_id,
1483 [ignoreSetLowestRank => $ignoreSetLowestRank]
1488 _FixPriority({ biblionumber => $biblionumber});
1490 This routine adjusts the priority of a hold request and holds
1493 In the first form, where a reserve_id is passed, the priority of the
1494 hold is set to supplied rank, and other holds for that bib are adjusted
1495 accordingly. If the rank is "del", the hold is cancelled. If no rank
1496 is supplied, all of the holds on that bib have their priority adjusted
1497 as if the second form had been used.
1499 In the second form, where a biblionumber is passed, the holds on that
1500 bib (that are not captured) are sorted in order of increasing priority,
1501 then have reserves.priority set so that the first non-captured hold
1502 has its priority set to 1, the second non-captured hold has its priority
1503 set to 2, and so forth.
1505 In both cases, holds that have the lowestPriority flag on are have their
1506 priority adjusted to ensure that they remain at the end of the line.
1508 Note that the ignoreSetLowestRank parameter is meant to be used only
1509 when _FixPriority calls itself.
1514 my ( $params ) = @_;
1515 my $reserve_id = $params->{reserve_id};
1516 my $rank = $params->{rank} // '';
1517 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1518 my $biblionumber = $params->{biblionumber};
1520 my $dbh = C4::Context->dbh;
1523 if ( $reserve_id ) {
1524 $hold = Koha::Holds->find( $reserve_id );
1525 if (!defined $hold){
1526 # may have already been checked out and hold fulfilled
1527 $hold = Koha::Old::Holds->find( $reserve_id );
1529 return unless $hold;
1532 unless ( $biblionumber ) { # FIXME This is a very weird API
1533 $biblionumber = $hold->biblionumber;
1536 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1539 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1541 # make sure priority for waiting or in-transit items is 0
1545 WHERE reserve_id = ?
1546 AND found IN ('W', 'T')
1548 my $sth = $dbh->prepare($query);
1549 $sth->execute( $reserve_id );
1555 SELECT reserve_id, borrowernumber, reservedate
1557 WHERE biblionumber = ?
1558 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1559 ORDER BY priority ASC
1561 my $sth = $dbh->prepare($query);
1562 $sth->execute( $biblionumber );
1563 while ( my $line = $sth->fetchrow_hashref ) {
1564 push( @priority, $line );
1567 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1568 # To find the matching index
1570 my $key = -1; # to allow for 0 to be a valid result
1571 for ( $i = 0 ; $i < @priority ; $i++ ) {
1572 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1573 $key = $i; # save the index
1578 # if index exists in array then move it to new position
1579 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1580 my $new_rank = $rank -
1581 1; # $new_rank is what you want the new index to be in the array
1582 my $moving_item = splice( @priority, $key, 1 );
1583 splice( @priority, $new_rank, 0, $moving_item );
1586 # now fix the priority on those that are left....
1590 WHERE reserve_id = ?
1592 $sth = $dbh->prepare($query);
1593 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1596 $priority[$j]->{'reserve_id'}
1600 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1603 unless ( $ignoreSetLowestRank ) {
1604 while ( my $res = $sth->fetchrow_hashref() ) {
1606 reserve_id => $res->{'reserve_id'},
1608 ignoreSetLowestRank => 1
1614 =head2 _Findgroupreserve
1616 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1618 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1619 first match found. If neither, then we look for non-holds-queue based holds.
1620 Lookahead is the number of days to look in advance.
1622 C<&_Findgroupreserve> returns :
1623 C<@results> is an array of references-to-hash whose keys are mostly
1624 fields from the reserves table of the Koha database, plus
1625 C<biblioitemnumber>.
1627 This routine with either return:
1628 1 - Item specific holds from the holds queue
1629 2 - Title level holds from the holds queue
1630 3 - All holds for this biblionumber
1632 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1636 sub _Findgroupreserve {
1637 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1638 my $dbh = C4::Context->dbh;
1640 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1641 # check for exact targeted match
1642 my $item_level_target_query = qq{
1643 SELECT reserves.biblionumber AS biblionumber,
1644 reserves.borrowernumber AS borrowernumber,
1645 reserves.reservedate AS reservedate,
1646 reserves.branchcode AS branchcode,
1647 reserves.cancellationdate AS cancellationdate,
1648 reserves.found AS found,
1649 reserves.reservenotes AS reservenotes,
1650 reserves.priority AS priority,
1651 reserves.timestamp AS timestamp,
1652 biblioitems.biblioitemnumber AS biblioitemnumber,
1653 reserves.itemnumber AS itemnumber,
1654 reserves.reserve_id AS reserve_id,
1655 reserves.itemtype AS itemtype
1657 JOIN biblioitems USING (biblionumber)
1658 JOIN hold_fill_targets USING (reserve_id)
1661 AND item_level_request = 1
1662 AND hold_fill_targets.itemnumber = ?
1663 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1667 my $sth = $dbh->prepare($item_level_target_query);
1668 $sth->execute($itemnumber, $lookahead||0);
1670 if ( my $data = $sth->fetchrow_hashref ) {
1671 push( @results, $data )
1672 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1674 return @results if @results;
1676 # check for title-level targeted match
1677 my $title_level_target_query = qq{
1678 SELECT reserves.biblionumber AS biblionumber,
1679 reserves.borrowernumber AS borrowernumber,
1680 reserves.reservedate AS reservedate,
1681 reserves.branchcode AS branchcode,
1682 reserves.cancellationdate AS cancellationdate,
1683 reserves.found AS found,
1684 reserves.reservenotes AS reservenotes,
1685 reserves.priority AS priority,
1686 reserves.timestamp AS timestamp,
1687 biblioitems.biblioitemnumber AS biblioitemnumber,
1688 reserves.itemnumber AS itemnumber,
1689 reserves.reserve_id AS reserve_id,
1690 reserves.itemtype AS itemtype
1692 JOIN biblioitems USING (biblionumber)
1693 JOIN hold_fill_targets USING (reserve_id)
1696 AND item_level_request = 0
1697 AND hold_fill_targets.itemnumber = ?
1698 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1702 $sth = $dbh->prepare($title_level_target_query);
1703 $sth->execute($itemnumber, $lookahead||0);
1705 if ( my $data = $sth->fetchrow_hashref ) {
1706 push( @results, $data )
1707 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1709 return @results if @results;
1712 SELECT reserves.biblionumber AS biblionumber,
1713 reserves.borrowernumber AS borrowernumber,
1714 reserves.reservedate AS reservedate,
1715 reserves.waitingdate AS waitingdate,
1716 reserves.branchcode AS branchcode,
1717 reserves.cancellationdate AS cancellationdate,
1718 reserves.found AS found,
1719 reserves.reservenotes AS reservenotes,
1720 reserves.priority AS priority,
1721 reserves.timestamp AS timestamp,
1722 reserves.itemnumber AS itemnumber,
1723 reserves.reserve_id AS reserve_id,
1724 reserves.itemtype AS itemtype
1726 WHERE reserves.biblionumber = ?
1727 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1728 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1732 $sth = $dbh->prepare($query);
1733 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1735 while ( my $data = $sth->fetchrow_hashref ) {
1736 push( @results, $data )
1737 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1742 =head2 _koha_notify_reserve
1744 _koha_notify_reserve( $hold->reserve_id );
1746 Sends a notification to the patron that their hold has been filled (through
1747 ModReserveAffect, _not_ ModReserveFill)
1749 The letter code for this notice may be found using the following query:
1751 select distinct letter_code
1752 from message_transports
1753 inner join message_attributes using (message_attribute_id)
1754 where message_name = 'Hold_Filled'
1756 This will probably sipmly be 'HOLD', but because it is defined in the database,
1757 it is subject to addition or change.
1759 The following tables are availalbe witin the notice:
1770 sub _koha_notify_reserve {
1771 my $reserve_id = shift;
1772 my $hold = Koha::Holds->find($reserve_id);
1773 my $borrowernumber = $hold->borrowernumber;
1775 my $patron = Koha::Patrons->find( $borrowernumber );
1777 # Try to get the borrower's email address
1778 my $to_address = $patron->notice_email_address;
1780 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1781 borrowernumber => $borrowernumber,
1782 message_name => 'Hold_Filled'
1785 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1787 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1789 my %letter_params = (
1790 module => 'reserves',
1791 branchcode => $hold->branchcode,
1792 lang => $patron->lang,
1794 'branches' => $library,
1795 'borrowers' => $patron->unblessed,
1796 'biblio' => $hold->biblionumber,
1797 'biblioitems' => $hold->biblionumber,
1798 'reserves' => $hold->unblessed,
1799 'items' => $hold->itemnumber,
1803 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.
1804 my $send_notification = sub {
1805 my ( $mtt, $letter_code ) = (@_);
1806 return unless defined $letter_code;
1807 $letter_params{letter_code} = $letter_code;
1808 $letter_params{message_transport_type} = $mtt;
1809 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1811 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1815 C4::Letters::EnqueueLetter( {
1817 borrowernumber => $borrowernumber,
1818 from_address => $admin_email_address,
1819 message_transport_type => $mtt,
1823 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1825 ( $mtt eq 'email' and not $to_address ) # No email address
1826 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1827 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1830 &$send_notification($mtt, $letter_code);
1831 $notification_sent++;
1833 #Making sure that a print notification is sent if no other transport types can be utilized.
1834 if (! $notification_sent) {
1835 &$send_notification('print', 'HOLD');
1840 =head2 _ShiftPriorityByDateAndPriority
1842 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1844 This increments the priority of all reserves after the one
1845 with either the lowest date after C<$reservedate>
1846 or the lowest priority after C<$priority>.
1848 It effectively makes room for a new reserve to be inserted with a certain
1849 priority, which is returned.
1851 This is most useful when the reservedate can be set by the user. It allows
1852 the new reserve to be placed before other reserves that have a later
1853 reservedate. Since priority also is set by the form in reserves/request.pl
1854 the sub accounts for that too.
1858 sub _ShiftPriorityByDateAndPriority {
1859 my ( $biblio, $resdate, $new_priority ) = @_;
1861 my $dbh = C4::Context->dbh;
1862 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1863 my $sth = $dbh->prepare( $query );
1864 $sth->execute( $biblio, $resdate, $new_priority );
1865 my $min_priority = $sth->fetchrow;
1866 # if no such matches are found, $new_priority remains as original value
1867 $new_priority = $min_priority if ( $min_priority );
1869 # Shift the priority up by one; works in conjunction with the next SQL statement
1870 $query = "UPDATE reserves
1871 SET priority = priority+1
1872 WHERE biblionumber = ?
1873 AND borrowernumber = ?
1876 my $sth_update = $dbh->prepare( $query );
1878 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1879 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1880 $sth = $dbh->prepare( $query );
1881 $sth->execute( $new_priority, $biblio );
1882 while ( my $row = $sth->fetchrow_hashref ) {
1883 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1886 return $new_priority; # so the caller knows what priority they wind up receiving
1891 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1893 Use when checking out an item to handle reserves
1894 If $cancelreserve boolean is set to true, it will remove existing reserve
1899 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1901 $cancelreserve //= 0;
1903 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1904 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1907 my $biblionumber = $res->{biblionumber};
1909 if ($res->{borrowernumber} == $borrowernumber) {
1910 ModReserveFill($res);
1914 # The item is reserved by someone else.
1915 # Find this item in the reserves
1917 my $borr_res = Koha::Holds->search({
1918 borrowernumber => $borrowernumber,
1919 biblionumber => $biblionumber,
1921 order_by => 'priority'
1925 # The item is reserved by the current patron
1926 ModReserveFill($borr_res->unblessed);
1929 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1930 RevertWaitingStatus({ itemnumber => $itemnumber });
1932 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1933 my $hold = Koha::Holds->find( $res->{reserve_id} );
1941 MergeHolds($dbh,$to_biblio, $from_biblio);
1943 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1948 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1949 my $sth = $dbh->prepare(
1950 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1952 $sth->execute($from_biblio);
1953 if ( my $data = $sth->fetchrow_hashref() ) {
1955 # holds exist on old record, if not we don't need to do anything
1956 $sth = $dbh->prepare(
1957 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1958 $sth->execute( $to_biblio, $from_biblio );
1961 # don't reorder those already waiting
1963 $sth = $dbh->prepare(
1964 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1966 my $upd_sth = $dbh->prepare(
1967 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1968 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1970 $sth->execute( $to_biblio, 'W', 'T' );
1972 while ( my $reserve = $sth->fetchrow_hashref() ) {
1974 $priority, $to_biblio,
1975 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1976 $reserve->{'itemnumber'}
1983 =head2 RevertWaitingStatus
1985 RevertWaitingStatus({ itemnumber => $itemnumber });
1987 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1989 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1990 item level hold, even if it was only a bibliolevel hold to
1991 begin with. This is because we can no longer know if a hold
1992 was item-level or bib-level after a hold has been set to
1997 sub RevertWaitingStatus {
1998 my ( $params ) = @_;
1999 my $itemnumber = $params->{'itemnumber'};
2001 return unless ( $itemnumber );
2003 my $dbh = C4::Context->dbh;
2005 ## Get the waiting reserve we want to revert
2006 my $hold = Koha::Holds->search(
2008 itemnumber => $itemnumber,
2009 found => { not => undef },
2013 ## Increment the priority of all other non-waiting
2014 ## reserves for this bib record
2015 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2016 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2018 ## Fix up the currently waiting reserve
2023 waitingdate => undef,
2024 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2028 _FixPriority( { biblionumber => $hold->biblionumber } );
2037 branchcode => $branchcode,
2038 borrowernumber => $borrowernumber,
2039 biblionumber => $biblionumber,
2040 [ itemnumber => $itemnumber, ]
2041 [ barcode => $barcode, ]
2045 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2047 The letter code will be HOLD_SLIP, and the following tables are
2048 available within the slip:
2061 my $branchcode = $args->{branchcode};
2062 my $reserve_id = $args->{reserve_id};
2064 my $hold = Koha::Holds->find($reserve_id);
2065 return unless $hold;
2067 my $patron = $hold->borrower;
2068 my $reserve = $hold->unblessed;
2070 return C4::Letters::GetPreparedLetter (
2071 module => 'circulation',
2072 letter_code => 'HOLD_SLIP',
2073 branchcode => $branchcode,
2074 lang => $patron->lang,
2076 'reserves' => $reserve,
2077 'branches' => $reserve->{branchcode},
2078 'borrowers' => $reserve->{borrowernumber},
2079 'biblio' => $reserve->{biblionumber},
2080 'biblioitems' => $reserve->{biblionumber},
2081 'items' => $reserve->{itemnumber},
2086 =head2 GetReservesControlBranch
2088 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2090 Return the branchcode to be used to determine which reserves
2091 policy applies to a transaction.
2093 C<$item> is a hashref for an item. Only 'homebranch' is used.
2095 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2099 sub GetReservesControlBranch {
2100 my ( $item, $borrower ) = @_;
2102 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2105 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2106 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2112 =head2 CalculatePriority
2114 my $p = CalculatePriority($biblionumber, $resdate);
2116 Calculate priority for a new reserve on biblionumber, placing it at
2117 the end of the line of all holds whose start date falls before
2118 the current system time and that are neither on the hold shelf
2121 The reserve date parameter is optional; if it is supplied, the
2122 priority is based on the set of holds whose start date falls before
2123 the parameter value.
2125 After calculation of this priority, it is recommended to call
2126 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2131 sub CalculatePriority {
2132 my ( $biblionumber, $resdate ) = @_;
2135 SELECT COUNT(*) FROM reserves
2136 WHERE biblionumber = ?
2138 AND (found IS NULL OR found = '')
2140 #skip found==W or found==T (waiting or transit holds)
2142 $sql.= ' AND ( reservedate <= ? )';
2145 $sql.= ' AND ( reservedate < NOW() )';
2147 my $dbh = C4::Context->dbh();
2148 my @row = $dbh->selectrow_array(
2151 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2154 return @row ? $row[0]+1 : 1;
2157 =head2 IsItemOnHoldAndFound
2159 my $bool = IsItemFoundHold( $itemnumber );
2161 Returns true if the item is currently on hold
2162 and that hold has a non-null found status ( W, T, etc. )
2166 sub IsItemOnHoldAndFound {
2167 my ($itemnumber) = @_;
2169 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2171 my $found = $rs->count(
2173 itemnumber => $itemnumber,
2174 found => { '!=' => undef }
2181 =head2 GetMaxPatronHoldsForRecord
2183 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2185 For multiple holds on a given record for a given patron, the max
2186 number of record level holds that a patron can be placed is the highest
2187 value of the holds_per_record rule for each item if the record for that
2188 patron. This subroutine finds and returns the highest holds_per_record
2189 rule value for a given patron id and record id.
2193 sub GetMaxPatronHoldsForRecord {
2194 my ( $borrowernumber, $biblionumber ) = @_;
2196 my $patron = Koha::Patrons->find($borrowernumber);
2197 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2199 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2201 my $categorycode = $patron->categorycode;
2203 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2206 foreach my $item (@items) {
2207 my $itemtype = $item->effective_itemtype();
2209 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2211 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2212 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2213 $max = $holds_per_record if $holds_per_record > $max;
2221 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2223 Returns the matching hold related issuingrule fields for a given
2224 patron category, itemtype, and library.
2229 my ( $categorycode, $itemtype, $branchcode ) = @_;
2231 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2233 itemtype => $itemtype,
2234 categorycode => $categorycode,
2235 branchcode => $branchcode,
2236 rule_name => 'reservesallowed',
2238 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2244 if ( $reservesallowed ) {
2245 $rules->{reservesallowed} = $reservesallowed->rule_value;
2246 $rules->{itemtype} = $reservesallowed->itemtype;
2247 $rules->{categorycode} = $reservesallowed->categorycode;
2248 $rules->{branchcode} = $reservesallowed->branchcode;
2251 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2253 itemtype => $itemtype,
2254 categorycode => $categorycode,
2255 branchcode => $branchcode,
2256 rules => ['holds_per_record', 'holds_per_day'],
2258 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2262 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2263 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2270 Koha Development Team <http://koha-community.org/>