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 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
114 &ModReserveMinusPriority
120 &CanReserveBeCanceledFromOpac
121 &CancelExpiredReserves
123 &AutoUnsuspendReserves
125 &IsAvailableForItemLevelRequest
126 ItemsAnyAvailableAndNotRestricted
129 &ToggleLowestPriority
135 &GetReservesControlBranch
139 GetMaxPatronHoldsForRecord
141 @EXPORT_OK = qw( MergeHolds );
148 branchcode => $branchcode,
149 borrowernumber => $borrowernumber,
150 biblionumber => $biblionumber,
151 priority => $priority,
152 reservation_date => $reservation_date,
153 expiration_date => $expiration_date,
156 itemnumber => $itemnumber,
158 itemtype => $itemtype,
162 Adds reserve and generates HOLDPLACED message.
164 The following tables are available witin the HOLDPLACED message:
177 my $branch = $params->{branchcode};
178 my $borrowernumber = $params->{borrowernumber};
179 my $biblionumber = $params->{biblionumber};
180 my $priority = $params->{priority};
181 my $resdate = $params->{reservation_date};
182 my $expdate = $params->{expiration_date};
183 my $notes = $params->{notes};
184 my $title = $params->{title};
185 my $checkitem = $params->{itemnumber};
186 my $found = $params->{found};
187 my $itemtype = $params->{itemtype};
188 my $non_priority = $params->{non_priority};
190 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
191 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
193 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
195 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
196 # of the document, we force the value $priority and $found .
197 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
198 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
201 # If item is already checked out, it cannot be set waiting
204 # The item can't be waiting if it needs a transfer
205 && $item->holdingbranch eq $branch
207 # Similarly, if in transit it can't be waiting
208 && !$item->get_transfer
210 # If we can't hold damaged items, and it is damaged, it can't be waiting
211 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
213 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
214 && !$item->current_holds->count )
221 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
223 # Make room in reserves for this before those of a later reserve date
224 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
229 # If the reserv had the waiting status, we had the value of the resdate
230 if ( $found && $found eq 'W' ) {
231 $waitingdate = $resdate;
234 # Don't add itemtype limit if specific item is selected
235 $itemtype = undef if $checkitem;
237 # updates take place here
238 my $hold = Koha::Hold->new(
240 borrowernumber => $borrowernumber,
241 biblionumber => $biblionumber,
242 reservedate => $resdate,
243 branchcode => $branch,
244 priority => $priority,
245 reservenotes => $notes,
246 itemnumber => $checkitem,
248 waitingdate => $waitingdate,
249 expirationdate => $expdate,
250 itemtype => $itemtype,
251 item_level_hold => $checkitem ? 1 : 0,
252 non_priority => $non_priority ? 1 : 0,
255 $hold->set_waiting() if $found && $found eq 'W';
257 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
258 if C4::Context->preference('HoldsLog');
260 my $reserve_id = $hold->id();
262 # add a reserve fee if needed
263 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
264 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
265 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
268 _FixPriority({ biblionumber => $biblionumber});
270 # Send e-mail to librarian if syspref is active
271 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
272 my $patron = Koha::Patrons->find( $borrowernumber );
273 my $library = $patron->library;
274 if ( my $letter = C4::Letters::GetPreparedLetter (
275 module => 'reserves',
276 letter_code => 'HOLDPLACED',
277 branchcode => $branch,
278 lang => $patron->lang,
280 'branches' => $library->unblessed,
281 'borrowers' => $patron->unblessed,
282 'biblio' => $biblionumber,
283 'biblioitems' => $biblionumber,
284 'items' => $checkitem,
285 'reserves' => $hold->unblessed,
289 my $branch_email_address = $library->inbound_email_address;
291 C4::Letters::EnqueueLetter(
294 borrowernumber => $borrowernumber,
295 message_transport_type => 'email',
296 to_address => $branch_email_address,
302 Koha::Plugins->call('after_hold_create', $hold);
307 =head2 CanBookBeReserved
309 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
310 if ($canReserve eq 'OK') { #We can reserve this Item! }
312 $params are passed directly through to CanItemBeReserved
314 See CanItemBeReserved() for possible return values.
318 sub CanBookBeReserved{
319 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
321 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
322 #get items linked via host records
323 my @hostitems = get_hostitemnumbers_of($biblionumber);
325 push (@itemnumbers, @hostitems);
328 my $canReserve = { status => '' };
329 foreach my $itemnumber (@itemnumbers) {
330 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
331 return { status => 'OK' } if $canReserve->{status} eq 'OK';
336 =head2 CanItemBeReserved
338 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
339 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
341 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
342 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
343 current checkout against the high holds threshold
345 @RETURNS { status => OK }, if the Item can be reserved.
346 { status => ageRestricted }, if the Item is age restricted for this borrower.
347 { status => damaged }, if the Item is damaged.
348 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
349 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
350 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
351 { status => notReservable }, if holds on this item are not allowed
352 { status => libraryNotFound }, if given branchcode is not an existing library
353 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
354 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
355 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
359 sub CanItemBeReserved {
360 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
362 my $dbh = C4::Context->dbh;
363 my $ruleitemtype; # itemtype of the matching issuing rule
364 my $allowedreserves = 0; # Total number of holds allowed across all records
365 my $holds_per_record = 1; # Total number of holds allowed for this one given record
366 my $holds_per_day; # Default to unlimited
368 # we retrieve borrowers and items informations #
369 # item->{itype} will come for biblioitems if necessery
370 my $item = Koha::Items->find($itemnumber);
371 my $biblio = $item->biblio;
372 my $patron = Koha::Patrons->find( $borrowernumber );
373 my $borrower = $patron->unblessed;
375 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
376 return { status =>'damaged' }
378 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
380 # Check for the age restriction
381 my ( $ageRestriction, $daysToAgeRestriction ) =
382 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
383 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
385 # Check that the patron doesn't have an item level hold on this item already
386 return { status =>'itemAlreadyOnHold' }
387 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
389 my $controlbranch = C4::Context->preference('ReservesControlBranch');
392 SELECT count(*) AS count
394 LEFT JOIN items USING (itemnumber)
395 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
396 LEFT JOIN borrowers USING (borrowernumber)
397 WHERE borrowernumber = ?
401 my $branchfield = "reserves.branchcode";
403 if ( $controlbranch eq "ItemHomeLibrary" ) {
404 $branchfield = "items.homebranch";
405 $branchcode = $item->homebranch;
407 elsif ( $controlbranch eq "PatronLibrary" ) {
408 $branchfield = "borrowers.branchcode";
409 $branchcode = $borrower->{branchcode};
413 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
414 $ruleitemtype = $rights->{itemtype};
415 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
416 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
417 $holds_per_day = $rights->{holds_per_day};
420 $ruleitemtype = undef;
423 my $search_params = {
424 borrowernumber => $borrowernumber,
425 biblionumber => $item->biblionumber,
427 $search_params->{found} = undef if $params->{ignore_found_holds};
429 my $holds = Koha::Holds->search($search_params);
430 if ( defined $holds_per_record && $holds_per_record ne ''
431 && $holds->count() >= $holds_per_record ) {
432 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
435 my $today_holds = Koha::Holds->search({
436 borrowernumber => $borrowernumber,
437 reservedate => dt_from_string->date
440 if ( defined $holds_per_day && $holds_per_day ne ''
441 && $today_holds->count() >= $holds_per_day )
443 return { status => 'tooManyReservesToday', limit => $holds_per_day };
448 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
450 # If using item-level itypes, fall back to the record
451 # level itemtype if the hold has no associated item
453 C4::Context->preference('item-level_itypes')
454 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
455 : " AND biblioitems.itemtype = ?"
456 if defined $ruleitemtype;
458 my $sthcount = $dbh->prepare($querycount);
460 if ( defined $ruleitemtype ) {
461 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
464 $sthcount->execute( $borrowernumber, $branchcode );
467 my $reservecount = "0";
468 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
469 $reservecount = $rowcount->{count};
472 # we check if it's ok or not
473 if ( defined $allowedreserves && $allowedreserves ne ''
474 && $reservecount >= $allowedreserves ) {
475 return { status => 'tooManyReserves', limit => $allowedreserves };
478 # Now we need to check hold limits by patron category
479 my $rule = Koha::CirculationRules->get_effective_rule(
481 categorycode => $borrower->{categorycode},
482 branchcode => $branchcode,
483 rule_name => 'max_holds',
486 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
487 my $total_holds_count = Koha::Holds->search(
489 borrowernumber => $borrower->{borrowernumber}
493 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
496 my $reserves_control_branch =
497 GetReservesControlBranch( $item->unblessed(), $borrower );
499 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
501 if ( $branchitemrule->{holdallowed} == 0 ) {
502 return { status => 'notReservable' };
505 if ( $branchitemrule->{holdallowed} == 1
506 && $borrower->{branchcode} ne $item->homebranch )
508 return { status => 'cannotReserveFromOtherBranches' };
511 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
512 if ( $branchitemrule->{holdallowed} == 3) {
513 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
514 return { status => 'branchNotInHoldGroup' };
518 # If reservecount is ok, we check item branch if IndependentBranches is ON
519 # and canreservefromotherbranches is OFF
520 if ( C4::Context->preference('IndependentBranches')
521 and !C4::Context->preference('canreservefromotherbranches') )
523 if ( $item->homebranch ne $borrower->{branchcode} ) {
524 return { status => 'cannotReserveFromOtherBranches' };
528 if ($pickup_branchcode) {
529 my $destination = Koha::Libraries->find({
530 branchcode => $pickup_branchcode,
533 unless ($destination) {
534 return { status => 'libraryNotFound' };
536 unless ($destination->pickup_location) {
537 return { status => 'libraryNotPickupLocation' };
539 unless ($item->can_be_transferred({ to => $destination })) {
540 return { status => 'cannotBeTransferred' };
542 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
543 return { status => 'pickupNotInHoldGroup' };
545 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
546 return { status => 'pickupNotInHoldGroup' };
550 return { status => 'OK' };
553 =head2 CanReserveBeCanceledFromOpac
555 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
557 returns 1 if reserve can be cancelled by user from OPAC.
558 First check if reserve belongs to user, next checks if reserve is not in
559 transfer or waiting status
563 sub CanReserveBeCanceledFromOpac {
564 my ($reserve_id, $borrowernumber) = @_;
566 return unless $reserve_id and $borrowernumber;
567 my $reserve = Koha::Holds->find($reserve_id);
569 return 0 unless $reserve->borrowernumber == $borrowernumber;
570 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
576 =head2 GetOtherReserves
578 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
580 Check queued list of this document and check if this document must be transferred
584 sub GetOtherReserves {
585 my ($itemnumber) = @_;
588 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
589 if ($checkreserves) {
590 my $item = Koha::Items->find($itemnumber);
591 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
592 $messages->{'transfert'} = $checkreserves->{'branchcode'};
593 #minus priorities of others reservs
594 ModReserveMinusPriority(
596 $checkreserves->{'reserve_id'},
599 #launch the subroutine dotransfer
600 C4::Items::ModItemTransfer(
602 $item->holdingbranch,
603 $checkreserves->{'branchcode'},
609 #step 2b : case of a reservation on the same branch, set the waiting status
611 $messages->{'waiting'} = 1;
612 ModReserveMinusPriority(
614 $checkreserves->{'reserve_id'},
616 ModReserveStatus($itemnumber,'W');
619 $nextreservinfo = $checkreserves;
622 return ( $messages, $nextreservinfo );
625 =head2 ChargeReserveFee
627 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
629 Charge the fee for a reserve (if $fee > 0)
633 sub ChargeReserveFee {
634 my ( $borrowernumber, $fee, $title ) = @_;
635 return if !$fee || $fee == 0; # the last test is needed to include 0.00
636 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
639 description => $title,
641 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
642 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
643 interface => C4::Context->interface,
644 invoice_type => undef,
653 $fee = GetReserveFee( $borrowernumber, $biblionumber );
655 Calculate the fee for a reserve (if applicable).
660 my ( $borrowernumber, $biblionumber ) = @_;
662 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
665 SELECT COUNT(*) FROM items
666 LEFT JOIN issues USING (itemnumber)
667 WHERE items.biblionumber=? AND issues.issue_id IS NULL
670 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
673 my $dbh = C4::Context->dbh;
674 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
675 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
676 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
677 # This is a reconstruction of the old code:
678 # Compare number of items with items issued, and optionally check holds
679 # If not all items are issued and there are no holds: charge no fee
680 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
681 my ( $notissued, $reserved );
682 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
685 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
686 ( $biblionumber, $borrowernumber ) );
687 $fee = 0 if $reserved == 0;
693 =head2 GetReserveStatus
695 $reservestatus = GetReserveStatus($itemnumber);
697 Takes an itemnumber and returns the status of the reserve placed on it.
698 If several reserves exist, the reserve with the lower priority is given.
702 ## FIXME: I don't think this does what it thinks it does.
703 ## It only ever checks the first reserve result, even though
704 ## multiple reserves for that bib can have the itemnumber set
705 ## the sub is only used once in the codebase.
706 sub GetReserveStatus {
707 my ($itemnumber) = @_;
709 my $dbh = C4::Context->dbh;
711 my ($sth, $found, $priority);
713 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
714 $sth->execute($itemnumber);
715 ($found, $priority) = $sth->fetchrow_array;
719 return 'Waiting' if $found eq 'W' and $priority == 0;
720 return 'Finished' if $found eq 'F';
723 return 'Reserved' if defined $priority && $priority > 0;
725 return ''; # empty string here will remove need for checking undef, or less log lines
730 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
731 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
732 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
734 Find a book in the reserves.
736 C<$itemnumber> is the book's item number.
737 C<$lookahead> is the number of days to look in advance for future reserves.
739 As I understand it, C<&CheckReserves> looks for the given item in the
740 reserves. If it is found, that's a match, and C<$status> is set to
743 Otherwise, it finds the most important item in the reserves with the
744 same biblio number as this book (I'm not clear on this) and returns it
745 with C<$status> set to C<Reserved>.
747 C<&CheckReserves> returns a two-element list:
749 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
751 C<$reserve> is the reserve item that matched. It is a
752 reference-to-hash whose keys are mostly the fields of the reserves
753 table in the Koha database.
758 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
759 my $dbh = C4::Context->dbh;
762 if (C4::Context->preference('item-level_itypes')){
764 SELECT items.biblionumber,
765 items.biblioitemnumber,
766 itemtypes.notforloan,
767 items.notforloan AS itemnotforloan,
773 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
774 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
779 SELECT items.biblionumber,
780 items.biblioitemnumber,
781 itemtypes.notforloan,
782 items.notforloan AS itemnotforloan,
788 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
789 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
794 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
795 $sth->execute($item);
798 $sth = $dbh->prepare("$select WHERE barcode = ?");
799 $sth->execute($barcode);
801 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
802 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
803 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
805 return unless $itemnumber; # bail if we got nothing.
806 # if item is not for loan it cannot be reserved either.....
807 # except where items.notforloan < 0 : This indicates the item is holdable.
809 my @SkipHoldTrapOnNotForLoanValue = split( '|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
810 return if @SkipHoldTrapOnNotForLoanValue && grep( $notforloan_per_item, @SkipHoldTrapOnNotForLoanValue );
812 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
813 return if $dont_trap or $notforloan_per_itemtype;
815 # Find this item in the reserves
816 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
818 # $priority and $highest are used to find the most important item
819 # in the list returned by &_Findgroupreserve. (The lower $priority,
820 # the more important the item.)
821 # $highest is the most important item we've seen so far.
824 if (scalar @reserves) {
825 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
826 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
827 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
829 my $priority = 10000000;
830 foreach my $res (@reserves) {
831 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
832 if ($res->{'found'} eq 'W') {
833 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
835 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
840 my $local_hold_match;
842 if ($LocalHoldsPriority) {
843 $patron = Koha::Patrons->find( $res->{borrowernumber} );
844 $item = Koha::Items->find($itemnumber);
846 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
847 my $local_holds_priority_item_branchcode =
848 $item->$LocalHoldsPriorityItemControl;
849 my $local_holds_priority_patron_branchcode =
850 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
852 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
853 ? $patron->branchcode
856 $local_holds_priority_item_branchcode eq
857 $local_holds_priority_patron_branchcode;
861 # See if this item is more important than what we've got so far
862 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
863 $item ||= Koha::Items->find($itemnumber);
864 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
865 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
866 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
867 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
868 next if ($branchitemrule->{'holdallowed'} == 0);
869 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
870 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
871 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
872 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
873 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
874 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
875 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
876 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
877 $priority = $res->{'priority'};
879 last if $local_hold_match;
885 # If we get this far, then no exact match was found.
886 # We return the most important (i.e. next) reservation.
888 $highest->{'itemnumber'} = $item;
889 return ( "Reserved", $highest, \@reserves );
895 =head2 CancelExpiredReserves
897 CancelExpiredReserves();
899 Cancels all reserves with an expiration date from before today.
903 sub CancelExpiredReserves {
904 my $today = dt_from_string();
905 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
906 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
908 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
909 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
910 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
912 # FIXME To move to Koha::Holds->search_expired (?)
913 my $holds = Koha::Holds->search( $params );
915 while ( my $hold = $holds->next ) {
916 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
918 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
920 my $cancel_params = {};
921 if ( $hold->found eq 'W' ) {
922 $cancel_params->{charge_cancel_fee} = 1;
924 $hold->cancel( $cancel_params );
928 =head2 AutoUnsuspendReserves
930 AutoUnsuspendReserves();
932 Unsuspends all suspended reserves with a suspend_until date from before today.
936 sub AutoUnsuspendReserves {
937 my $today = dt_from_string();
939 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
941 map { $_->resume() } @holds;
946 ModReserve({ rank => $rank,
947 reserve_id => $reserve_id,
948 branchcode => $branchcode
949 [, itemnumber => $itemnumber ]
950 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
953 Change a hold request's priority or cancel it.
955 C<$rank> specifies the effect of the change. If C<$rank>
956 is 'W' or 'n', nothing happens. This corresponds to leaving a
957 request alone when changing its priority in the holds queue
960 If C<$rank> is 'del', the hold request is cancelled.
962 If C<$rank> is an integer greater than zero, the priority of
963 the request is set to that value. Since priority != 0 means
964 that the item is not waiting on the hold shelf, setting the
965 priority to a non-zero value also sets the request's found
966 status and waiting date to NULL.
968 The optional C<$itemnumber> parameter is used only when
969 C<$rank> is a non-zero integer; if supplied, the itemnumber
970 of the hold request is set accordingly; if omitted, the itemnumber
973 B<FIXME:> Note that the forgoing can have the effect of causing
974 item-level hold requests to turn into title-level requests. This
975 will be fixed once reserves has separate columns for requested
976 itemnumber and supplying itemnumber.
983 my $rank = $params->{'rank'};
984 my $reserve_id = $params->{'reserve_id'};
985 my $branchcode = $params->{'branchcode'};
986 my $itemnumber = $params->{'itemnumber'};
987 my $suspend_until = $params->{'suspend_until'};
988 my $borrowernumber = $params->{'borrowernumber'};
989 my $biblionumber = $params->{'biblionumber'};
990 my $cancellation_reason = $params->{'cancellation_reason'};
992 return if $rank eq "W";
993 return if $rank eq "n";
995 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
998 unless ( $reserve_id ) {
999 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1000 return unless $holds->count; # FIXME Should raise an exception
1001 $hold = $holds->next;
1002 $reserve_id = $hold->reserve_id;
1005 $hold ||= Koha::Holds->find($reserve_id);
1007 if ( $rank eq "del" ) {
1008 $hold->cancel({ cancellation_reason => $cancellation_reason });
1010 elsif ($rank =~ /^\d+/ and $rank > 0) {
1011 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1012 if C4::Context->preference('HoldsLog');
1016 branchcode => $branchcode,
1017 itemnumber => $itemnumber,
1019 waitingdate => undef
1021 if (exists $params->{reservedate}) {
1022 $properties->{reservedate} = $params->{reservedate} || undef;
1024 if (exists $params->{expirationdate}) {
1025 $properties->{expirationdate} = $params->{expirationdate} || undef;
1028 $hold->set($properties)->store();
1030 if ( defined( $suspend_until ) ) {
1031 if ( $suspend_until ) {
1032 $suspend_until = eval { dt_from_string( $suspend_until ) };
1033 $hold->suspend_hold( $suspend_until );
1035 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1036 # If the hold is not suspended, this does nothing.
1037 $hold->set( { suspend_until => undef } )->store();
1041 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1045 =head2 ModReserveFill
1047 &ModReserveFill($reserve);
1049 Fill a reserve. If I understand this correctly, this means that the
1050 reserved book has been found and given to the patron who reserved it.
1052 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1053 whose keys are fields from the reserves table in the Koha database.
1057 sub ModReserveFill {
1059 my $reserve_id = $res->{'reserve_id'};
1061 my $hold = Koha::Holds->find($reserve_id);
1062 # get the priority on this record....
1063 my $priority = $hold->priority;
1065 # update the hold statuses, no need to store it though, we will be deleting it anyway
1073 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1074 if C4::Context->preference('HoldsLog');
1076 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1077 Koha::Old::Hold->new( $hold->unblessed() )->store();
1081 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1082 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1083 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1086 # now fix the priority on the others (if the priority wasn't
1087 # already sorted!)....
1088 unless ( $priority == 0 ) {
1089 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1093 =head2 ModReserveStatus
1095 &ModReserveStatus($itemnumber, $newstatus);
1097 Update the reserve status for the active (priority=0) reserve.
1099 $itemnumber is the itemnumber the reserve is on
1101 $newstatus is the new status.
1105 sub ModReserveStatus {
1107 #first : check if we have a reservation for this item .
1108 my ($itemnumber, $newstatus) = @_;
1109 my $dbh = C4::Context->dbh;
1111 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1112 my $sth_set = $dbh->prepare($query);
1113 $sth_set->execute( $newstatus, $itemnumber );
1115 my $item = Koha::Items->find($itemnumber);
1116 if ( $item->location && $item->location eq 'CART'
1117 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1119 CartToShelf( $itemnumber );
1123 =head2 ModReserveAffect
1125 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1127 This function affect an item and a status for a given reserve, either fetched directly
1128 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1129 is given, only first reserve returned is affected, which is ok for anything but
1132 if $transferToDo is not set, then the status is set to "Waiting" as well.
1133 otherwise, a transfer is on the way, and the end of the transfer will
1134 take care of the waiting status
1138 sub ModReserveAffect {
1139 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1140 my $dbh = C4::Context->dbh;
1142 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1143 # attached to $itemnumber
1144 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1145 $sth->execute($itemnumber);
1146 my ($biblionumber) = $sth->fetchrow;
1148 # get request - need to find out if item is already
1149 # waiting in order to not send duplicate hold filled notifications
1152 # Find hold by id if we have it
1153 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1154 # Find item level hold for this item if there is one
1155 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1156 # Find record level hold if there is no item level hold
1157 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1159 return unless $hold;
1161 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1163 $hold->itemnumber($itemnumber);
1165 if( !$transferToDo ){
1166 $hold->set_waiting();
1167 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1168 my $transfers = Koha::Item::Transfers->search({
1169 itemnumber => $itemnumber,
1170 datearrived => undef
1172 while( my $transfer = $transfers->next ){
1173 $transfer->datearrived( dt_from_string() )->store;
1176 $hold->set_transfer();
1180 _FixPriority( { biblionumber => $biblionumber } );
1181 my $item = Koha::Items->find($itemnumber);
1182 if ( $item->location && $item->location eq 'CART'
1183 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1184 CartToShelf( $itemnumber );
1187 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1188 if C4::Context->preference('HoldsLog');
1193 =head2 ModReserveCancelAll
1195 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1197 function to cancel reserv,check other reserves, and transfer document if it's necessary
1201 sub ModReserveCancelAll {
1204 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1206 #step 1 : cancel the reservation
1207 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1208 return unless $holds->count;
1209 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1211 #step 2 launch the subroutine of the others reserves
1212 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1214 return ( $messages, $nextreservinfo->{borrowernumber} );
1217 =head2 ModReserveMinusPriority
1219 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1221 Reduce the values of queued list
1225 sub ModReserveMinusPriority {
1226 my ( $itemnumber, $reserve_id ) = @_;
1228 #first step update the value of the first person on reserv
1229 my $dbh = C4::Context->dbh;
1232 SET priority = 0 , itemnumber = ?
1233 WHERE reserve_id = ?
1235 my $sth_upd = $dbh->prepare($query);
1236 $sth_upd->execute( $itemnumber, $reserve_id );
1237 # second step update all others reserves
1238 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1241 =head2 IsAvailableForItemLevelRequest
1243 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1245 Checks whether a given item record is available for an
1246 item-level hold request. An item is available if
1248 * it is not lost AND
1249 * it is not damaged AND
1250 * it is not withdrawn AND
1251 * a waiting or in transit reserve is placed on
1252 * does not have a not for loan value > 0
1254 Need to check the issuingrules onshelfholds column,
1255 if this is set items on the shelf can be placed on hold
1257 Note that IsAvailableForItemLevelRequest() does not
1258 check if the staff operator is authorized to place
1259 a request on the item - in particular,
1260 this routine does not check IndependentBranches
1261 and canreservefromotherbranches.
1263 Note also that this subroutine does not checks smart
1264 rules limits for item by reservesallowed/holds_per_record
1265 values, this complemented in calling code with calls and
1266 checks with CanItemBeReserved or CanBookBeReserved.
1270 sub IsAvailableForItemLevelRequest {
1273 my $pickup_branchcode = shift;
1274 # items_any_available is precalculated status passed from request.pl when set of items
1275 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1276 my $items_any_available = shift;
1278 my $dbh = C4::Context->dbh;
1279 # must check the notforloan setting of the itemtype
1280 # FIXME - a lot of places in the code do this
1281 # or something similar - need to be
1283 my $itemtype = $item->effective_itemtype;
1284 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1287 $notforloan_per_itemtype ||
1289 $item->notforloan > 0 ||
1291 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1293 if ($pickup_branchcode) {
1294 my $destination = Koha::Libraries->find($pickup_branchcode);
1295 return 0 unless $destination;
1296 return 0 unless $destination->pickup_location;
1297 return 0 unless $item->can_be_transferred( { to => $destination } );
1298 my $reserves_control_branch =
1299 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1300 my $branchitemrule =
1301 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1302 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1303 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1306 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1308 if ( $on_shelf_holds == 1 ) {
1310 } elsif ( $on_shelf_holds == 2 ) {
1312 # if we have this param predefined from outer caller sub, we just need
1313 # to return it, so we saving from having loop inside other loop:
1314 return $items_any_available ? 0 : 1
1315 if defined $items_any_available;
1317 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1318 return $any_available ? 0 : 1;
1319 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1320 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1324 =head2 ItemsAnyAvailableAndNotRestricted
1326 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1328 This function checks all items for specified biblionumber (numeric) against patron (object)
1329 and returns true (1) if at least one item available for loan/check out/present/not held
1330 and also checks other parameters logic which not restricts item for hold at all (for ex.
1331 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1335 sub ItemsAnyAvailableAndNotRestricted {
1338 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1340 foreach my $i (@items) {
1341 my $reserves_control_branch =
1342 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1343 my $branchitemrule =
1344 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1345 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1347 # we can return (end the loop) when first one found:
1350 || $i->notforloan > 0
1353 || IsItemOnHoldAndFound( $i->id )
1355 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1356 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1357 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1358 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1359 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1365 =head2 AlterPriority
1367 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1369 This function changes a reserve's priority up, down, to the top, or to the bottom.
1370 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1375 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1377 my $hold = Koha::Holds->find( $reserve_id );
1378 return unless $hold;
1380 if ( $hold->cancellationdate ) {
1381 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1385 if ( $where eq 'up' ) {
1386 return unless $prev_priority;
1387 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1388 } elsif ( $where eq 'down' ) {
1389 return unless $next_priority;
1390 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1391 } elsif ( $where eq 'top' ) {
1392 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1393 } elsif ( $where eq 'bottom' ) {
1394 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1397 # FIXME Should return the new priority
1400 =head2 ToggleLowestPriority
1402 ToggleLowestPriority( $borrowernumber, $biblionumber );
1404 This function sets the lowestPriority field to true if is false, and false if it is true.
1408 sub ToggleLowestPriority {
1409 my ( $reserve_id ) = @_;
1411 my $dbh = C4::Context->dbh;
1413 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1414 $sth->execute( $reserve_id );
1416 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1419 =head2 ToggleSuspend
1421 ToggleSuspend( $reserve_id );
1423 This function sets the suspend field to true if is false, and false if it is true.
1424 If the reserve is currently suspended with a suspend_until date, that date will
1425 be cleared when it is unsuspended.
1430 my ( $reserve_id, $suspend_until ) = @_;
1432 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1434 my $hold = Koha::Holds->find( $reserve_id );
1436 if ( $hold->is_suspended ) {
1439 $hold->suspend_hold( $suspend_until );
1446 borrowernumber => $borrowernumber,
1447 [ biblionumber => $biblionumber, ]
1448 [ suspend_until => $suspend_until, ]
1449 [ suspend => $suspend ]
1452 This function accepts a set of hash keys as its parameters.
1453 It requires either borrowernumber or biblionumber, or both.
1455 suspend_until is wholly optional.
1462 my $borrowernumber = $params{'borrowernumber'} || undef;
1463 my $biblionumber = $params{'biblionumber'} || undef;
1464 my $suspend_until = $params{'suspend_until'} || undef;
1465 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1467 $suspend_until = eval { dt_from_string($suspend_until) }
1468 if ( defined($suspend_until) );
1470 return unless ( $borrowernumber || $biblionumber );
1473 $params->{found} = undef;
1474 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1475 $params->{biblionumber} = $biblionumber if $biblionumber;
1477 my @holds = Koha::Holds->search($params);
1480 map { $_->suspend_hold($suspend_until) } @holds;
1483 map { $_->resume() } @holds;
1491 reserve_id => $reserve_id,
1493 [ignoreSetLowestRank => $ignoreSetLowestRank]
1498 _FixPriority({ biblionumber => $biblionumber});
1500 This routine adjusts the priority of a hold request and holds
1503 In the first form, where a reserve_id is passed, the priority of the
1504 hold is set to supplied rank, and other holds for that bib are adjusted
1505 accordingly. If the rank is "del", the hold is cancelled. If no rank
1506 is supplied, all of the holds on that bib have their priority adjusted
1507 as if the second form had been used.
1509 In the second form, where a biblionumber is passed, the holds on that
1510 bib (that are not captured) are sorted in order of increasing priority,
1511 then have reserves.priority set so that the first non-captured hold
1512 has its priority set to 1, the second non-captured hold has its priority
1513 set to 2, and so forth.
1515 In both cases, holds that have the lowestPriority flag on are have their
1516 priority adjusted to ensure that they remain at the end of the line.
1518 Note that the ignoreSetLowestRank parameter is meant to be used only
1519 when _FixPriority calls itself.
1524 my ( $params ) = @_;
1525 my $reserve_id = $params->{reserve_id};
1526 my $rank = $params->{rank} // '';
1527 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1528 my $biblionumber = $params->{biblionumber};
1530 my $dbh = C4::Context->dbh;
1533 if ( $reserve_id ) {
1534 $hold = Koha::Holds->find( $reserve_id );
1535 if (!defined $hold){
1536 # may have already been checked out and hold fulfilled
1537 $hold = Koha::Old::Holds->find( $reserve_id );
1539 return unless $hold;
1542 unless ( $biblionumber ) { # FIXME This is a very weird API
1543 $biblionumber = $hold->biblionumber;
1546 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1549 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1551 # make sure priority for waiting or in-transit items is 0
1555 WHERE reserve_id = ?
1556 AND found IN ('W', 'T')
1558 my $sth = $dbh->prepare($query);
1559 $sth->execute( $reserve_id );
1565 SELECT reserve_id, borrowernumber, reservedate
1567 WHERE biblionumber = ?
1568 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1569 ORDER BY priority ASC
1571 my $sth = $dbh->prepare($query);
1572 $sth->execute( $biblionumber );
1573 while ( my $line = $sth->fetchrow_hashref ) {
1574 push( @priority, $line );
1577 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1578 # To find the matching index
1580 my $key = -1; # to allow for 0 to be a valid result
1581 for ( $i = 0 ; $i < @priority ; $i++ ) {
1582 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1583 $key = $i; # save the index
1588 # if index exists in array then move it to new position
1589 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1590 my $new_rank = $rank -
1591 1; # $new_rank is what you want the new index to be in the array
1592 my $moving_item = splice( @priority, $key, 1 );
1593 splice( @priority, $new_rank, 0, $moving_item );
1596 # now fix the priority on those that are left....
1600 WHERE reserve_id = ?
1602 $sth = $dbh->prepare($query);
1603 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1606 $priority[$j]->{'reserve_id'}
1610 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1613 unless ( $ignoreSetLowestRank ) {
1614 while ( my $res = $sth->fetchrow_hashref() ) {
1616 reserve_id => $res->{'reserve_id'},
1618 ignoreSetLowestRank => 1
1624 =head2 _Findgroupreserve
1626 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1628 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1629 first match found. If neither, then we look for non-holds-queue based holds.
1630 Lookahead is the number of days to look in advance.
1632 C<&_Findgroupreserve> returns :
1633 C<@results> is an array of references-to-hash whose keys are mostly
1634 fields from the reserves table of the Koha database, plus
1635 C<biblioitemnumber>.
1637 This routine with either return:
1638 1 - Item specific holds from the holds queue
1639 2 - Title level holds from the holds queue
1640 3 - All holds for this biblionumber
1642 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1646 sub _Findgroupreserve {
1647 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1648 my $dbh = C4::Context->dbh;
1650 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1651 # check for exact targeted match
1652 my $item_level_target_query = qq{
1653 SELECT reserves.biblionumber AS biblionumber,
1654 reserves.borrowernumber AS borrowernumber,
1655 reserves.reservedate AS reservedate,
1656 reserves.branchcode AS branchcode,
1657 reserves.cancellationdate AS cancellationdate,
1658 reserves.found AS found,
1659 reserves.reservenotes AS reservenotes,
1660 reserves.priority AS priority,
1661 reserves.timestamp AS timestamp,
1662 biblioitems.biblioitemnumber AS biblioitemnumber,
1663 reserves.itemnumber AS itemnumber,
1664 reserves.reserve_id AS reserve_id,
1665 reserves.itemtype AS itemtype,
1666 reserves.non_priority AS non_priority
1668 JOIN biblioitems USING (biblionumber)
1669 JOIN hold_fill_targets USING (reserve_id)
1672 AND item_level_request = 1
1673 AND hold_fill_targets.itemnumber = ?
1674 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1678 my $sth = $dbh->prepare($item_level_target_query);
1679 $sth->execute($itemnumber, $lookahead||0);
1681 if ( my $data = $sth->fetchrow_hashref ) {
1682 push( @results, $data )
1683 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1685 return @results if @results;
1687 # check for title-level targeted match
1688 my $title_level_target_query = qq{
1689 SELECT reserves.biblionumber AS biblionumber,
1690 reserves.borrowernumber AS borrowernumber,
1691 reserves.reservedate AS reservedate,
1692 reserves.branchcode AS branchcode,
1693 reserves.cancellationdate AS cancellationdate,
1694 reserves.found AS found,
1695 reserves.reservenotes AS reservenotes,
1696 reserves.priority AS priority,
1697 reserves.timestamp AS timestamp,
1698 biblioitems.biblioitemnumber AS biblioitemnumber,
1699 reserves.itemnumber AS itemnumber,
1700 reserves.reserve_id AS reserve_id,
1701 reserves.itemtype AS itemtype,
1702 reserves.non_priority AS non_priority
1704 JOIN biblioitems USING (biblionumber)
1705 JOIN hold_fill_targets USING (reserve_id)
1708 AND item_level_request = 0
1709 AND hold_fill_targets.itemnumber = ?
1710 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1714 $sth = $dbh->prepare($title_level_target_query);
1715 $sth->execute($itemnumber, $lookahead||0);
1717 if ( my $data = $sth->fetchrow_hashref ) {
1718 push( @results, $data )
1719 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1721 return @results if @results;
1724 SELECT reserves.biblionumber AS biblionumber,
1725 reserves.borrowernumber AS borrowernumber,
1726 reserves.reservedate AS reservedate,
1727 reserves.waitingdate AS waitingdate,
1728 reserves.branchcode AS branchcode,
1729 reserves.cancellationdate AS cancellationdate,
1730 reserves.found AS found,
1731 reserves.reservenotes AS reservenotes,
1732 reserves.priority AS priority,
1733 reserves.timestamp AS timestamp,
1734 reserves.itemnumber AS itemnumber,
1735 reserves.reserve_id AS reserve_id,
1736 reserves.itemtype AS itemtype,
1737 reserves.non_priority AS non_priority
1739 WHERE reserves.biblionumber = ?
1740 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1741 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1745 $sth = $dbh->prepare($query);
1746 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1748 while ( my $data = $sth->fetchrow_hashref ) {
1749 push( @results, $data )
1750 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1755 =head2 _koha_notify_reserve
1757 _koha_notify_reserve( $hold->reserve_id );
1759 Sends a notification to the patron that their hold has been filled (through
1760 ModReserveAffect, _not_ ModReserveFill)
1762 The letter code for this notice may be found using the following query:
1764 select distinct letter_code
1765 from message_transports
1766 inner join message_attributes using (message_attribute_id)
1767 where message_name = 'Hold_Filled'
1769 This will probably sipmly be 'HOLD', but because it is defined in the database,
1770 it is subject to addition or change.
1772 The following tables are availalbe witin the notice:
1783 sub _koha_notify_reserve {
1784 my $reserve_id = shift;
1785 my $hold = Koha::Holds->find($reserve_id);
1786 my $borrowernumber = $hold->borrowernumber;
1788 my $patron = Koha::Patrons->find( $borrowernumber );
1790 # Try to get the borrower's email address
1791 my $to_address = $patron->notice_email_address;
1793 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1794 borrowernumber => $borrowernumber,
1795 message_name => 'Hold_Filled'
1798 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1800 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1802 my %letter_params = (
1803 module => 'reserves',
1804 branchcode => $hold->branchcode,
1805 lang => $patron->lang,
1807 'branches' => $library,
1808 'borrowers' => $patron->unblessed,
1809 'biblio' => $hold->biblionumber,
1810 'biblioitems' => $hold->biblionumber,
1811 'reserves' => $hold->unblessed,
1812 'items' => $hold->itemnumber,
1816 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.
1817 my $send_notification = sub {
1818 my ( $mtt, $letter_code ) = (@_);
1819 return unless defined $letter_code;
1820 $letter_params{letter_code} = $letter_code;
1821 $letter_params{message_transport_type} = $mtt;
1822 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1824 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1828 C4::Letters::EnqueueLetter( {
1830 borrowernumber => $borrowernumber,
1831 from_address => $admin_email_address,
1832 message_transport_type => $mtt,
1836 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1838 ( $mtt eq 'email' and not $to_address ) # No email address
1839 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1840 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1843 &$send_notification($mtt, $letter_code);
1844 $notification_sent++;
1846 #Making sure that a print notification is sent if no other transport types can be utilized.
1847 if (! $notification_sent) {
1848 &$send_notification('print', 'HOLD');
1853 =head2 _ShiftPriorityByDateAndPriority
1855 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1857 This increments the priority of all reserves after the one
1858 with either the lowest date after C<$reservedate>
1859 or the lowest priority after C<$priority>.
1861 It effectively makes room for a new reserve to be inserted with a certain
1862 priority, which is returned.
1864 This is most useful when the reservedate can be set by the user. It allows
1865 the new reserve to be placed before other reserves that have a later
1866 reservedate. Since priority also is set by the form in reserves/request.pl
1867 the sub accounts for that too.
1871 sub _ShiftPriorityByDateAndPriority {
1872 my ( $biblio, $resdate, $new_priority ) = @_;
1874 my $dbh = C4::Context->dbh;
1875 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1876 my $sth = $dbh->prepare( $query );
1877 $sth->execute( $biblio, $resdate, $new_priority );
1878 my $min_priority = $sth->fetchrow;
1879 # if no such matches are found, $new_priority remains as original value
1880 $new_priority = $min_priority if ( $min_priority );
1882 # Shift the priority up by one; works in conjunction with the next SQL statement
1883 $query = "UPDATE reserves
1884 SET priority = priority+1
1885 WHERE biblionumber = ?
1886 AND borrowernumber = ?
1889 my $sth_update = $dbh->prepare( $query );
1891 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1892 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1893 $sth = $dbh->prepare( $query );
1894 $sth->execute( $new_priority, $biblio );
1895 while ( my $row = $sth->fetchrow_hashref ) {
1896 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1899 return $new_priority; # so the caller knows what priority they wind up receiving
1904 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1906 Use when checking out an item to handle reserves
1907 If $cancelreserve boolean is set to true, it will remove existing reserve
1912 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1914 $cancelreserve //= 0;
1916 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1917 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1920 my $biblionumber = $res->{biblionumber};
1922 if ($res->{borrowernumber} == $borrowernumber) {
1923 ModReserveFill($res);
1927 # The item is reserved by someone else.
1928 # Find this item in the reserves
1930 my $borr_res = Koha::Holds->search({
1931 borrowernumber => $borrowernumber,
1932 biblionumber => $biblionumber,
1934 order_by => 'priority'
1938 # The item is reserved by the current patron
1939 ModReserveFill($borr_res->unblessed);
1942 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1943 RevertWaitingStatus({ itemnumber => $itemnumber });
1945 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1946 my $hold = Koha::Holds->find( $res->{reserve_id} );
1954 MergeHolds($dbh,$to_biblio, $from_biblio);
1956 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1961 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1962 my $sth = $dbh->prepare(
1963 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1965 $sth->execute($from_biblio);
1966 if ( my $data = $sth->fetchrow_hashref() ) {
1968 # holds exist on old record, if not we don't need to do anything
1969 $sth = $dbh->prepare(
1970 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1971 $sth->execute( $to_biblio, $from_biblio );
1974 # don't reorder those already waiting
1976 $sth = $dbh->prepare(
1977 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1979 my $upd_sth = $dbh->prepare(
1980 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1981 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1983 $sth->execute( $to_biblio, 'W', 'T' );
1985 while ( my $reserve = $sth->fetchrow_hashref() ) {
1987 $priority, $to_biblio,
1988 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1989 $reserve->{'itemnumber'}
1996 =head2 RevertWaitingStatus
1998 RevertWaitingStatus({ itemnumber => $itemnumber });
2000 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2002 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2003 item level hold, even if it was only a bibliolevel hold to
2004 begin with. This is because we can no longer know if a hold
2005 was item-level or bib-level after a hold has been set to
2010 sub RevertWaitingStatus {
2011 my ( $params ) = @_;
2012 my $itemnumber = $params->{'itemnumber'};
2014 return unless ( $itemnumber );
2016 my $dbh = C4::Context->dbh;
2018 ## Get the waiting reserve we want to revert
2019 my $hold = Koha::Holds->search(
2021 itemnumber => $itemnumber,
2022 found => { not => undef },
2026 ## Increment the priority of all other non-waiting
2027 ## reserves for this bib record
2028 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2029 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2031 ## Fix up the currently waiting reserve
2036 waitingdate => undef,
2037 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2041 _FixPriority( { biblionumber => $hold->biblionumber } );
2050 branchcode => $branchcode,
2051 borrowernumber => $borrowernumber,
2052 biblionumber => $biblionumber,
2053 [ itemnumber => $itemnumber, ]
2054 [ barcode => $barcode, ]
2058 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2060 The letter code will be HOLD_SLIP, and the following tables are
2061 available within the slip:
2074 my $branchcode = $args->{branchcode};
2075 my $reserve_id = $args->{reserve_id};
2077 my $hold = Koha::Holds->find($reserve_id);
2078 return unless $hold;
2080 my $patron = $hold->borrower;
2081 my $reserve = $hold->unblessed;
2083 return C4::Letters::GetPreparedLetter (
2084 module => 'circulation',
2085 letter_code => 'HOLD_SLIP',
2086 branchcode => $branchcode,
2087 lang => $patron->lang,
2089 'reserves' => $reserve,
2090 'branches' => $reserve->{branchcode},
2091 'borrowers' => $reserve->{borrowernumber},
2092 'biblio' => $reserve->{biblionumber},
2093 'biblioitems' => $reserve->{biblionumber},
2094 'items' => $reserve->{itemnumber},
2099 =head2 GetReservesControlBranch
2101 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2103 Return the branchcode to be used to determine which reserves
2104 policy applies to a transaction.
2106 C<$item> is a hashref for an item. Only 'homebranch' is used.
2108 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2112 sub GetReservesControlBranch {
2113 my ( $item, $borrower ) = @_;
2115 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2118 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2119 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2125 =head2 CalculatePriority
2127 my $p = CalculatePriority($biblionumber, $resdate);
2129 Calculate priority for a new reserve on biblionumber, placing it at
2130 the end of the line of all holds whose start date falls before
2131 the current system time and that are neither on the hold shelf
2134 The reserve date parameter is optional; if it is supplied, the
2135 priority is based on the set of holds whose start date falls before
2136 the parameter value.
2138 After calculation of this priority, it is recommended to call
2139 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2144 sub CalculatePriority {
2145 my ( $biblionumber, $resdate ) = @_;
2148 SELECT COUNT(*) FROM reserves
2149 WHERE biblionumber = ?
2151 AND (found IS NULL OR found = '')
2153 #skip found==W or found==T (waiting or transit holds)
2155 $sql.= ' AND ( reservedate <= ? )';
2158 $sql.= ' AND ( reservedate < NOW() )';
2160 my $dbh = C4::Context->dbh();
2161 my @row = $dbh->selectrow_array(
2164 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2167 return @row ? $row[0]+1 : 1;
2170 =head2 IsItemOnHoldAndFound
2172 my $bool = IsItemFoundHold( $itemnumber );
2174 Returns true if the item is currently on hold
2175 and that hold has a non-null found status ( W, T, etc. )
2179 sub IsItemOnHoldAndFound {
2180 my ($itemnumber) = @_;
2182 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2184 my $found = $rs->count(
2186 itemnumber => $itemnumber,
2187 found => { '!=' => undef }
2194 =head2 GetMaxPatronHoldsForRecord
2196 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2198 For multiple holds on a given record for a given patron, the max
2199 number of record level holds that a patron can be placed is the highest
2200 value of the holds_per_record rule for each item if the record for that
2201 patron. This subroutine finds and returns the highest holds_per_record
2202 rule value for a given patron id and record id.
2206 sub GetMaxPatronHoldsForRecord {
2207 my ( $borrowernumber, $biblionumber ) = @_;
2209 my $patron = Koha::Patrons->find($borrowernumber);
2210 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2212 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2214 my $categorycode = $patron->categorycode;
2216 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2219 foreach my $item (@items) {
2220 my $itemtype = $item->effective_itemtype();
2222 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2224 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2225 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2226 $max = $holds_per_record if $holds_per_record > $max;
2234 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2236 Returns the matching hold related issuingrule fields for a given
2237 patron category, itemtype, and library.
2242 my ( $categorycode, $itemtype, $branchcode ) = @_;
2244 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2246 itemtype => $itemtype,
2247 categorycode => $categorycode,
2248 branchcode => $branchcode,
2249 rule_name => 'reservesallowed',
2251 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2257 if ( $reservesallowed ) {
2258 $rules->{reservesallowed} = $reservesallowed->rule_value;
2259 $rules->{itemtype} = $reservesallowed->itemtype;
2260 $rules->{categorycode} = $reservesallowed->categorycode;
2261 $rules->{branchcode} = $reservesallowed->branchcode;
2264 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2266 itemtype => $itemtype,
2267 categorycode => $categorycode,
2268 branchcode => $branchcode,
2269 rules => ['holds_per_record', 'holds_per_day'],
2271 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2275 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2276 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2283 Koha Development Team <http://koha-community.org/>