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>.
25 #use warnings; FIXME - Bug 2505
34 use C4::Members::Messaging;
36 use Koha::Account::Lines;
39 use Koha::CirculationRules;
44 use Koha::IssuingRules;
53 use List::MoreUtils qw( firstidx any );
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
59 C4::Reserves - Koha functions for dealing with reservation.
67 This modules provides somes functions to deal with reservations.
69 Reserves are stored in reserves table.
70 The following columns contains important values :
71 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
72 =0 : then the reserve is being dealed
73 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
74 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
75 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
76 F(inished) : the reserve has been completed, and is done
77 - itemnumber : empty : the reserve is still unaffected to an item
78 filled: the reserve is attached to an item
79 The complete workflow is :
80 ==== 1st use case ====
81 patron request a document, 1st available : P >0, F=NULL, I=NULL
82 a library having it run "transfertodo", and clic on the list
83 if there is no transfer to do, the reserve waiting
84 patron can pick it up P =0, F=W, I=filled
85 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
86 The pickup library receive the book, it check in P =0, F=W, I=filled
87 The patron borrow the book P =0, F=F, I=filled
89 ==== 2nd use case ====
90 patron requests a document, a given item,
91 If pickup is holding branch P =0, F=W, I=filled
92 If transfer needed, write in branchtransfer P =0, F=T, I=filled
93 The pickup library receive the book, it checks it in P =0, F=W, I=filled
94 The patron borrow the book P =0, F=F, I=filled
115 &ModReserveMinusPriority
121 &CanReserveBeCanceledFromOpac
122 &CancelExpiredReserves
124 &AutoUnsuspendReserves
126 &IsAvailableForItemLevelRequest
129 &ToggleLowestPriority
135 &GetReservesControlBranch
139 GetMaxPatronHoldsForRecord
141 @EXPORT_OK = qw( MergeHolds );
146 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
148 Adds reserve and generates HOLDPLACED message.
150 The following tables are available witin the HOLDPLACED message:
163 $branch, $borrowernumber, $biblionumber, $bibitems,
164 $priority, $resdate, $expdate, $notes,
165 $title, $checkitem, $found, $itemtype
168 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
169 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
171 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
173 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
174 # of the document, we force the value $priority and $found .
175 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
176 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
179 # If item is already checked out, it cannot be set waiting
182 # The item can't be waiting if it needs a transfer
183 && $item->holdingbranch eq $branch
185 # Similarly, if in transit it can't be waiting
186 && !$item->get_transfer
188 # If we can't hold damaged items, and it is damaged, it can't be waiting
189 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
191 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
192 && !$item->current_holds->count )
199 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
201 # Make room in reserves for this before those of a later reserve date
202 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
207 # If the reserv had the waiting status, we had the value of the resdate
208 if ( $found eq 'W' ) {
209 $waitingdate = $resdate;
212 # Don't add itemtype limit if specific item is selected
213 $itemtype = undef if $checkitem;
215 # updates take place here
216 my $hold = Koha::Hold->new(
218 borrowernumber => $borrowernumber,
219 biblionumber => $biblionumber,
220 reservedate => $resdate,
221 branchcode => $branch,
222 priority => $priority,
223 reservenotes => $notes,
224 itemnumber => $checkitem,
226 waitingdate => $waitingdate,
227 expirationdate => $expdate,
228 itemtype => $itemtype,
229 item_level_hold => $checkitem ? 1 : 0,
232 $hold->set_waiting() if $found eq 'W';
234 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
235 if C4::Context->preference('HoldsLog');
237 my $reserve_id = $hold->id();
239 # add a reserve fee if needed
240 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
241 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
242 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
245 _FixPriority({ biblionumber => $biblionumber});
247 # Send e-mail to librarian if syspref is active
248 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
249 my $patron = Koha::Patrons->find( $borrowernumber );
250 my $library = $patron->library;
251 if ( my $letter = C4::Letters::GetPreparedLetter (
252 module => 'reserves',
253 letter_code => 'HOLDPLACED',
254 branchcode => $branch,
255 lang => $patron->lang,
257 'branches' => $library->unblessed,
258 'borrowers' => $patron->unblessed,
259 'biblio' => $biblionumber,
260 'biblioitems' => $biblionumber,
261 'items' => $checkitem,
262 'reserves' => $hold->unblessed,
266 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
268 C4::Letters::EnqueueLetter(
270 borrowernumber => $borrowernumber,
271 message_transport_type => 'email',
272 from_address => $admin_email_address,
273 to_address => $admin_email_address,
282 =head2 CanBookBeReserved
284 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
285 if ($canReserve eq 'OK') { #We can reserve this Item! }
287 $params are passed directly through to CanItemBeReserved
289 See CanItemBeReserved() for possible return values.
293 sub CanBookBeReserved{
294 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
296 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
297 #get items linked via host records
298 my @hostitems = get_hostitemnumbers_of($biblionumber);
300 push (@itemnumbers, @hostitems);
303 my $canReserve = { status => '' };
304 foreach my $itemnumber (@itemnumbers) {
305 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
306 return { status => 'OK' } if $canReserve->{status} eq 'OK';
311 =head2 CanItemBeReserved
313 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
314 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
316 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
317 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
318 current checkout against the high holds threshold
320 @RETURNS { status => OK }, if the Item can be reserved.
321 { status => ageRestricted }, if the Item is age restricted for this borrower.
322 { status => damaged }, if the Item is damaged.
323 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
324 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
325 { status => notReservable }, if holds on this item are not allowed
326 { status => libraryNotFound }, if given branchcode is not an existing library
327 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
328 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
332 sub CanItemBeReserved {
333 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
335 my $dbh = C4::Context->dbh;
336 my $ruleitemtype; # itemtype of the matching issuing rule
337 my $allowedreserves = 0; # Total number of holds allowed across all records
338 my $holds_per_record = 1; # Total number of holds allowed for this one given record
339 my $holds_per_day; # Default to unlimited
341 # we retrieve borrowers and items informations #
342 # item->{itype} will come for biblioitems if necessery
343 my $item = Koha::Items->find($itemnumber);
344 my $biblio = $item->biblio;
345 my $patron = Koha::Patrons->find( $borrowernumber );
346 my $borrower = $patron->unblessed;
348 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
349 return { status =>'damaged' }
351 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
353 # Check for the age restriction
354 my ( $ageRestriction, $daysToAgeRestriction ) =
355 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
356 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
358 # Check that the patron doesn't have an item level hold on this item already
359 return { status =>'itemAlreadyOnHold' }
360 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
362 my $controlbranch = C4::Context->preference('ReservesControlBranch');
365 SELECT count(*) AS count
367 LEFT JOIN items USING (itemnumber)
368 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
369 LEFT JOIN borrowers USING (borrowernumber)
370 WHERE borrowernumber = ?
374 my $branchfield = "reserves.branchcode";
376 if ( $controlbranch eq "ItemHomeLibrary" ) {
377 $branchfield = "items.homebranch";
378 $branchcode = $item->homebranch;
380 elsif ( $controlbranch eq "PatronLibrary" ) {
381 $branchfield = "borrowers.branchcode";
382 $branchcode = $borrower->{branchcode};
386 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
387 $ruleitemtype = $rights->{itemtype};
388 $allowedreserves = $rights->{reservesallowed};
389 $holds_per_record = $rights->{holds_per_record};
390 $holds_per_day = $rights->{holds_per_day};
396 my $search_params = {
397 borrowernumber => $borrowernumber,
398 biblionumber => $item->biblionumber,
400 $search_params->{found} = undef if $params->{ignore_found_holds};
402 my $holds = Koha::Holds->search($search_params);
403 if ( $holds->count() >= $holds_per_record ) {
404 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
407 my $today_holds = Koha::Holds->search({
408 borrowernumber => $borrowernumber,
409 reservedate => dt_from_string->date
412 if ( defined $holds_per_day &&
413 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
414 or ( $holds_per_day == 0 ) )
416 return { status => 'tooManyReservesToday', limit => $holds_per_day };
421 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
423 # If using item-level itypes, fall back to the record
424 # level itemtype if the hold has no associated item
426 C4::Context->preference('item-level_itypes')
427 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
428 : " AND biblioitems.itemtype = ?"
429 if ( $ruleitemtype ne "*" );
431 my $sthcount = $dbh->prepare($querycount);
433 if ( $ruleitemtype eq "*" ) {
434 $sthcount->execute( $borrowernumber, $branchcode );
437 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
440 my $reservecount = "0";
441 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
442 $reservecount = $rowcount->{count};
445 # we check if it's ok or not
446 if ( $reservecount >= $allowedreserves ) {
447 return { status => 'tooManyReserves', limit => $allowedreserves };
450 # Now we need to check hold limits by patron category
451 my $rule = Koha::CirculationRules->get_effective_rule(
453 categorycode => $borrower->{categorycode},
454 branchcode => $branchcode,
455 rule_name => 'max_holds',
458 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
459 my $total_holds_count = Koha::Holds->search(
461 borrowernumber => $borrower->{borrowernumber}
465 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
468 my $reserves_control_branch =
469 GetReservesControlBranch( $item->unblessed(), $borrower );
471 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
473 if ( $branchitemrule->{holdallowed} == 0 ) {
474 return { status => 'notReservable' };
477 if ( $branchitemrule->{holdallowed} == 1
478 && $borrower->{branchcode} ne $item->homebranch )
480 return { status => 'cannotReserveFromOtherBranches' };
483 # If reservecount is ok, we check item branch if IndependentBranches is ON
484 # and canreservefromotherbranches is OFF
485 if ( C4::Context->preference('IndependentBranches')
486 and !C4::Context->preference('canreservefromotherbranches') )
488 if ( $item->homebranch ne $borrower->{branchcode} ) {
489 return { status => 'cannotReserveFromOtherBranches' };
493 if ($pickup_branchcode) {
494 my $destination = Koha::Libraries->find({
495 branchcode => $pickup_branchcode,
498 unless ($destination) {
499 return { status => 'libraryNotFound' };
501 unless ($destination->pickup_location) {
502 return { status => 'libraryNotPickupLocation' };
504 unless ($item->can_be_transferred({ to => $destination })) {
505 return { status => 'cannotBeTransferred' };
509 return { status => 'OK' };
512 =head2 CanReserveBeCanceledFromOpac
514 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
516 returns 1 if reserve can be cancelled by user from OPAC.
517 First check if reserve belongs to user, next checks if reserve is not in
518 transfer or waiting status
522 sub CanReserveBeCanceledFromOpac {
523 my ($reserve_id, $borrowernumber) = @_;
525 return unless $reserve_id and $borrowernumber;
526 my $reserve = Koha::Holds->find($reserve_id);
528 return 0 unless $reserve->borrowernumber == $borrowernumber;
529 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
535 =head2 GetOtherReserves
537 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
539 Check queued list of this document and check if this document must be transferred
543 sub GetOtherReserves {
544 my ($itemnumber) = @_;
547 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
548 if ($checkreserves) {
549 my $item = Koha::Items->find($itemnumber);
550 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
551 $messages->{'transfert'} = $checkreserves->{'branchcode'};
552 #minus priorities of others reservs
553 ModReserveMinusPriority(
555 $checkreserves->{'reserve_id'},
558 #launch the subroutine dotransfer
559 C4::Items::ModItemTransfer(
561 $item->holdingbranch,
562 $checkreserves->{'branchcode'}
567 #step 2b : case of a reservation on the same branch, set the waiting status
569 $messages->{'waiting'} = 1;
570 ModReserveMinusPriority(
572 $checkreserves->{'reserve_id'},
574 ModReserveStatus($itemnumber,'W');
577 $nextreservinfo = $checkreserves;
580 return ( $messages, $nextreservinfo );
583 =head2 ChargeReserveFee
585 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
587 Charge the fee for a reserve (if $fee > 0)
591 sub ChargeReserveFee {
592 my ( $borrowernumber, $fee, $title ) = @_;
593 return if !$fee || $fee == 0; # the last test is needed to include 0.00
594 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
597 description => $title,
599 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
600 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
601 interface => C4::Context->interface,
602 invoice_type => undef,
611 $fee = GetReserveFee( $borrowernumber, $biblionumber );
613 Calculate the fee for a reserve (if applicable).
618 my ( $borrowernumber, $biblionumber ) = @_;
620 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
623 SELECT COUNT(*) FROM items
624 LEFT JOIN issues USING (itemnumber)
625 WHERE items.biblionumber=? AND issues.issue_id IS NULL
628 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
631 my $dbh = C4::Context->dbh;
632 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
633 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
634 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
635 # This is a reconstruction of the old code:
636 # Compare number of items with items issued, and optionally check holds
637 # If not all items are issued and there are no holds: charge no fee
638 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
639 my ( $notissued, $reserved );
640 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
643 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
644 ( $biblionumber, $borrowernumber ) );
645 $fee = 0 if $reserved == 0;
651 =head2 GetReserveStatus
653 $reservestatus = GetReserveStatus($itemnumber);
655 Takes an itemnumber and returns the status of the reserve placed on it.
656 If several reserves exist, the reserve with the lower priority is given.
660 ## FIXME: I don't think this does what it thinks it does.
661 ## It only ever checks the first reserve result, even though
662 ## multiple reserves for that bib can have the itemnumber set
663 ## the sub is only used once in the codebase.
664 sub GetReserveStatus {
665 my ($itemnumber) = @_;
667 my $dbh = C4::Context->dbh;
669 my ($sth, $found, $priority);
671 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
672 $sth->execute($itemnumber);
673 ($found, $priority) = $sth->fetchrow_array;
677 return 'Waiting' if $found eq 'W' and $priority == 0;
678 return 'Finished' if $found eq 'F';
681 return 'Reserved' if $priority > 0;
683 return ''; # empty string here will remove need for checking undef, or less log lines
688 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
689 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
690 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
692 Find a book in the reserves.
694 C<$itemnumber> is the book's item number.
695 C<$lookahead> is the number of days to look in advance for future reserves.
697 As I understand it, C<&CheckReserves> looks for the given item in the
698 reserves. If it is found, that's a match, and C<$status> is set to
701 Otherwise, it finds the most important item in the reserves with the
702 same biblio number as this book (I'm not clear on this) and returns it
703 with C<$status> set to C<Reserved>.
705 C<&CheckReserves> returns a two-element list:
707 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
709 C<$reserve> is the reserve item that matched. It is a
710 reference-to-hash whose keys are mostly the fields of the reserves
711 table in the Koha database.
716 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
717 my $dbh = C4::Context->dbh;
720 if (C4::Context->preference('item-level_itypes')){
722 SELECT items.biblionumber,
723 items.biblioitemnumber,
724 itemtypes.notforloan,
725 items.notforloan AS itemnotforloan,
731 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
732 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
737 SELECT items.biblionumber,
738 items.biblioitemnumber,
739 itemtypes.notforloan,
740 items.notforloan AS itemnotforloan,
746 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
747 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
752 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
753 $sth->execute($item);
756 $sth = $dbh->prepare("$select WHERE barcode = ?");
757 $sth->execute($barcode);
759 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
760 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
761 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
763 return unless $itemnumber; # bail if we got nothing.
764 # if item is not for loan it cannot be reserved either.....
765 # except where items.notforloan < 0 : This indicates the item is holdable.
767 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
768 return if $dont_trap or $notforloan_per_itemtype;
770 # Find this item in the reserves
771 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
773 # $priority and $highest are used to find the most important item
774 # in the list returned by &_Findgroupreserve. (The lower $priority,
775 # the more important the item.)
776 # $highest is the most important item we've seen so far.
779 if (scalar @reserves) {
780 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
781 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
782 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
784 my $priority = 10000000;
785 foreach my $res (@reserves) {
786 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
787 if ($res->{'found'} eq 'W') {
788 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
790 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
795 my $local_hold_match;
797 if ($LocalHoldsPriority) {
798 $patron = Koha::Patrons->find( $res->{borrowernumber} );
799 $item = Koha::Items->find($itemnumber);
801 my $local_holds_priority_item_branchcode =
802 $item->$LocalHoldsPriorityItemControl;
803 my $local_holds_priority_patron_branchcode =
804 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
806 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
807 ? $patron->branchcode
810 $local_holds_priority_item_branchcode eq
811 $local_holds_priority_patron_branchcode;
814 # See if this item is more important than what we've got so far
815 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
816 $item ||= Koha::Items->find($itemnumber);
817 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
818 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
819 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
820 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
821 next if ($branchitemrule->{'holdallowed'} == 0);
822 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
823 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
825 if $hold_fulfillment_policy ne 'any'
827 $hold_fulfillment_policy eq ''
828 || ( $res->{branchcode} ne
829 $item->$hold_fulfillment_policy )
831 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
832 $priority = $res->{'priority'};
834 last if $local_hold_match;
840 # If we get this far, then no exact match was found.
841 # We return the most important (i.e. next) reservation.
843 $highest->{'itemnumber'} = $item;
844 return ( "Reserved", $highest, \@reserves );
850 =head2 CancelExpiredReserves
852 CancelExpiredReserves();
854 Cancels all reserves with an expiration date from before today.
858 sub CancelExpiredReserves {
859 my $today = dt_from_string();
860 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
861 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
863 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
864 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
865 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
867 # FIXME To move to Koha::Holds->search_expired (?)
868 my $holds = Koha::Holds->search( $params );
870 while ( my $hold = $holds->next ) {
871 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
873 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
875 my $cancel_params = {};
876 if ( $hold->found eq 'W' ) {
877 $cancel_params->{charge_cancel_fee} = 1;
879 $hold->cancel( $cancel_params );
883 =head2 AutoUnsuspendReserves
885 AutoUnsuspendReserves();
887 Unsuspends all suspended reserves with a suspend_until date from before today.
891 sub AutoUnsuspendReserves {
892 my $today = dt_from_string();
894 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
896 map { $_->resume() } @holds;
901 ModReserve({ rank => $rank,
902 reserve_id => $reserve_id,
903 branchcode => $branchcode
904 [, itemnumber => $itemnumber ]
905 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
908 Change a hold request's priority or cancel it.
910 C<$rank> specifies the effect of the change. If C<$rank>
911 is 'W' or 'n', nothing happens. This corresponds to leaving a
912 request alone when changing its priority in the holds queue
915 If C<$rank> is 'del', the hold request is cancelled.
917 If C<$rank> is an integer greater than zero, the priority of
918 the request is set to that value. Since priority != 0 means
919 that the item is not waiting on the hold shelf, setting the
920 priority to a non-zero value also sets the request's found
921 status and waiting date to NULL.
923 The optional C<$itemnumber> parameter is used only when
924 C<$rank> is a non-zero integer; if supplied, the itemnumber
925 of the hold request is set accordingly; if omitted, the itemnumber
928 B<FIXME:> Note that the forgoing can have the effect of causing
929 item-level hold requests to turn into title-level requests. This
930 will be fixed once reserves has separate columns for requested
931 itemnumber and supplying itemnumber.
938 my $rank = $params->{'rank'};
939 my $reserve_id = $params->{'reserve_id'};
940 my $branchcode = $params->{'branchcode'};
941 my $itemnumber = $params->{'itemnumber'};
942 my $suspend_until = $params->{'suspend_until'};
943 my $borrowernumber = $params->{'borrowernumber'};
944 my $biblionumber = $params->{'biblionumber'};
946 return if $rank eq "W";
947 return if $rank eq "n";
949 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
952 unless ( $reserve_id ) {
953 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
954 return unless $holds->count; # FIXME Should raise an exception
955 $hold = $holds->next;
956 $reserve_id = $hold->reserve_id;
959 $hold ||= Koha::Holds->find($reserve_id);
961 if ( $rank eq "del" ) {
964 elsif ($rank =~ /^\d+/ and $rank > 0) {
965 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
966 if C4::Context->preference('HoldsLog');
970 branchcode => $branchcode,
971 itemnumber => $itemnumber,
975 if (exists $params->{reservedate}) {
976 $properties->{reservedate} = $params->{reservedate} || undef;
978 if (exists $params->{expirationdate}) {
979 $properties->{expirationdate} = $params->{expirationdate} || undef;
982 $hold->set($properties)->store();
984 if ( defined( $suspend_until ) ) {
985 if ( $suspend_until ) {
986 $suspend_until = eval { dt_from_string( $suspend_until ) };
987 $hold->suspend_hold( $suspend_until );
989 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
990 # If the hold is not suspended, this does nothing.
991 $hold->set( { suspend_until => undef } )->store();
995 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
999 =head2 ModReserveFill
1001 &ModReserveFill($reserve);
1003 Fill a reserve. If I understand this correctly, this means that the
1004 reserved book has been found and given to the patron who reserved it.
1006 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1007 whose keys are fields from the reserves table in the Koha database.
1011 sub ModReserveFill {
1013 my $reserve_id = $res->{'reserve_id'};
1015 my $hold = Koha::Holds->find($reserve_id);
1016 # get the priority on this record....
1017 my $priority = $hold->priority;
1019 # update the hold statuses, no need to store it though, we will be deleting it anyway
1027 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1028 if C4::Context->preference('HoldsLog');
1030 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1031 Koha::Old::Hold->new( $hold->unblessed() )->store();
1035 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1036 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1037 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1040 # now fix the priority on the others (if the priority wasn't
1041 # already sorted!)....
1042 unless ( $priority == 0 ) {
1043 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1047 =head2 ModReserveStatus
1049 &ModReserveStatus($itemnumber, $newstatus);
1051 Update the reserve status for the active (priority=0) reserve.
1053 $itemnumber is the itemnumber the reserve is on
1055 $newstatus is the new status.
1059 sub ModReserveStatus {
1061 #first : check if we have a reservation for this item .
1062 my ($itemnumber, $newstatus) = @_;
1063 my $dbh = C4::Context->dbh;
1065 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1066 my $sth_set = $dbh->prepare($query);
1067 $sth_set->execute( $newstatus, $itemnumber );
1069 my $item = Koha::Items->find($itemnumber);
1070 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) && $newstatus ) {
1071 CartToShelf( $itemnumber );
1075 =head2 ModReserveAffect
1077 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1079 This function affect an item and a status for a given reserve, either fetched directly
1080 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1081 is given, only first reserve returned is affected, which is ok for anything but
1084 if $transferToDo is not set, then the status is set to "Waiting" as well.
1085 otherwise, a transfer is on the way, and the end of the transfer will
1086 take care of the waiting status
1090 sub ModReserveAffect {
1091 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1092 my $dbh = C4::Context->dbh;
1094 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1095 # attached to $itemnumber
1096 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1097 $sth->execute($itemnumber);
1098 my ($biblionumber) = $sth->fetchrow;
1100 # get request - need to find out if item is already
1101 # waiting in order to not send duplicate hold filled notifications
1104 # Find hold by id if we have it
1105 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1106 # Find item level hold for this item if there is one
1107 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1108 # Find record level hold if there is no item level hold
1109 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1111 return unless $hold;
1113 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1115 $hold->itemnumber($itemnumber);
1116 $hold->set_waiting($transferToDo);
1118 if( !$transferToDo ){
1119 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1120 my $transfers = Koha::Item::Transfers->search({
1121 itemnumber => $itemnumber,
1122 datearrived => undef
1124 while( my $transfer = $transfers->next ){
1125 $transfer->datearrived( dt_from_string() )->store;
1130 _FixPriority( { biblionumber => $biblionumber } );
1131 my $item = Koha::Items->find($itemnumber);
1132 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) ) {
1133 CartToShelf( $itemnumber );
1136 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1137 if C4::Context->preference('HoldsLog');
1142 =head2 ModReserveCancelAll
1144 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1146 function to cancel reserv,check other reserves, and transfer document if it's necessary
1150 sub ModReserveCancelAll {
1153 my ( $itemnumber, $borrowernumber ) = @_;
1155 #step 1 : cancel the reservation
1156 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1157 return unless $holds->count;
1158 $holds->next->cancel;
1160 #step 2 launch the subroutine of the others reserves
1161 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1163 return ( $messages, $nextreservinfo->{borrowernumber} );
1166 =head2 ModReserveMinusPriority
1168 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1170 Reduce the values of queued list
1174 sub ModReserveMinusPriority {
1175 my ( $itemnumber, $reserve_id ) = @_;
1177 #first step update the value of the first person on reserv
1178 my $dbh = C4::Context->dbh;
1181 SET priority = 0 , itemnumber = ?
1182 WHERE reserve_id = ?
1184 my $sth_upd = $dbh->prepare($query);
1185 $sth_upd->execute( $itemnumber, $reserve_id );
1186 # second step update all others reserves
1187 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1190 =head2 IsAvailableForItemLevelRequest
1192 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1194 Checks whether a given item record is available for an
1195 item-level hold request. An item is available if
1197 * it is not lost AND
1198 * it is not damaged AND
1199 * it is not withdrawn AND
1200 * a waiting or in transit reserve is placed on
1201 * does not have a not for loan value > 0
1203 Need to check the issuingrules onshelfholds column,
1204 if this is set items on the shelf can be placed on hold
1206 Note that IsAvailableForItemLevelRequest() does not
1207 check if the staff operator is authorized to place
1208 a request on the item - in particular,
1209 this routine does not check IndependentBranches
1210 and canreservefromotherbranches.
1214 sub IsAvailableForItemLevelRequest {
1215 my ( $item, $patron, $pickup_branchcode ) = @_;
1217 my $dbh = C4::Context->dbh;
1218 # must check the notforloan setting of the itemtype
1219 # FIXME - a lot of places in the code do this
1220 # or something similar - need to be
1222 my $itemtype = $item->effective_itemtype;
1223 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1226 $notforloan_per_itemtype ||
1228 $item->notforloan > 0 ||
1230 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1232 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1234 if ($pickup_branchcode) {
1235 my $destination = Koha::Libraries->find($pickup_branchcode);
1236 return 0 unless $destination;
1237 return 0 unless $destination->pickup_location;
1238 return 0 unless $item->can_be_transferred( { to => $destination } );
1241 if ( $on_shelf_holds == 1 ) {
1243 } elsif ( $on_shelf_holds == 2 ) {
1245 Koha::Items->search( { biblionumber => $item->biblionumber } );
1247 my $any_available = 0;
1249 foreach my $i (@items) {
1250 my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1251 my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1255 || $i->notforloan > 0
1258 || IsItemOnHoldAndFound( $i->id )
1260 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1261 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1262 || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch;
1265 return $any_available ? 0 : 1;
1266 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1267 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1275 if (C4::Context->preference('item-level_itypes')) {
1276 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1277 # When GetItem is fixed, we can remove this
1278 $itype = $item->{itype};
1281 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1282 # So if we already have a biblioitems join when calling this function,
1283 # we don't need to access the database again
1284 $itype = $item->{itemtype};
1287 my $dbh = C4::Context->dbh;
1288 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1289 my $sth = $dbh->prepare($query);
1290 $sth->execute($item->{biblioitemnumber});
1291 if (my $data = $sth->fetchrow_hashref()){
1292 $itype = $data->{itemtype};
1298 =head2 AlterPriority
1300 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1302 This function changes a reserve's priority up, down, to the top, or to the bottom.
1303 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1308 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1310 my $hold = Koha::Holds->find( $reserve_id );
1311 return unless $hold;
1313 if ( $hold->cancellationdate ) {
1314 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1318 if ( $where eq 'up' ) {
1319 return unless $prev_priority;
1320 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1321 } elsif ( $where eq 'down' ) {
1322 return unless $next_priority;
1323 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1324 } elsif ( $where eq 'top' ) {
1325 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1326 } elsif ( $where eq 'bottom' ) {
1327 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1330 # FIXME Should return the new priority
1333 =head2 ToggleLowestPriority
1335 ToggleLowestPriority( $borrowernumber, $biblionumber );
1337 This function sets the lowestPriority field to true if is false, and false if it is true.
1341 sub ToggleLowestPriority {
1342 my ( $reserve_id ) = @_;
1344 my $dbh = C4::Context->dbh;
1346 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1347 $sth->execute( $reserve_id );
1349 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1352 =head2 ToggleSuspend
1354 ToggleSuspend( $reserve_id );
1356 This function sets the suspend field to true if is false, and false if it is true.
1357 If the reserve is currently suspended with a suspend_until date, that date will
1358 be cleared when it is unsuspended.
1363 my ( $reserve_id, $suspend_until ) = @_;
1365 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1367 my $hold = Koha::Holds->find( $reserve_id );
1369 if ( $hold->is_suspended ) {
1372 $hold->suspend_hold( $suspend_until );
1379 borrowernumber => $borrowernumber,
1380 [ biblionumber => $biblionumber, ]
1381 [ suspend_until => $suspend_until, ]
1382 [ suspend => $suspend ]
1385 This function accepts a set of hash keys as its parameters.
1386 It requires either borrowernumber or biblionumber, or both.
1388 suspend_until is wholly optional.
1395 my $borrowernumber = $params{'borrowernumber'} || undef;
1396 my $biblionumber = $params{'biblionumber'} || undef;
1397 my $suspend_until = $params{'suspend_until'} || undef;
1398 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1400 $suspend_until = eval { dt_from_string($suspend_until) }
1401 if ( defined($suspend_until) );
1403 return unless ( $borrowernumber || $biblionumber );
1406 $params->{found} = undef;
1407 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1408 $params->{biblionumber} = $biblionumber if $biblionumber;
1410 my @holds = Koha::Holds->search($params);
1413 map { $_->suspend_hold($suspend_until) } @holds;
1416 map { $_->resume() } @holds;
1424 reserve_id => $reserve_id,
1426 [ignoreSetLowestRank => $ignoreSetLowestRank]
1431 _FixPriority({ biblionumber => $biblionumber});
1433 This routine adjusts the priority of a hold request and holds
1436 In the first form, where a reserve_id is passed, the priority of the
1437 hold is set to supplied rank, and other holds for that bib are adjusted
1438 accordingly. If the rank is "del", the hold is cancelled. If no rank
1439 is supplied, all of the holds on that bib have their priority adjusted
1440 as if the second form had been used.
1442 In the second form, where a biblionumber is passed, the holds on that
1443 bib (that are not captured) are sorted in order of increasing priority,
1444 then have reserves.priority set so that the first non-captured hold
1445 has its priority set to 1, the second non-captured hold has its priority
1446 set to 2, and so forth.
1448 In both cases, holds that have the lowestPriority flag on are have their
1449 priority adjusted to ensure that they remain at the end of the line.
1451 Note that the ignoreSetLowestRank parameter is meant to be used only
1452 when _FixPriority calls itself.
1457 my ( $params ) = @_;
1458 my $reserve_id = $params->{reserve_id};
1459 my $rank = $params->{rank} // '';
1460 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1461 my $biblionumber = $params->{biblionumber};
1463 my $dbh = C4::Context->dbh;
1466 if ( $reserve_id ) {
1467 $hold = Koha::Holds->find( $reserve_id );
1468 if (!defined $hold){
1469 # may have already been checked out and hold fulfilled
1470 $hold = Koha::Old::Holds->find( $reserve_id );
1472 return unless $hold;
1475 unless ( $biblionumber ) { # FIXME This is a very weird API
1476 $biblionumber = $hold->biblionumber;
1479 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1482 elsif ( $rank eq "W" || $rank eq "0" ) {
1484 # make sure priority for waiting or in-transit items is 0
1488 WHERE reserve_id = ?
1489 AND found IN ('W', 'T')
1491 my $sth = $dbh->prepare($query);
1492 $sth->execute( $reserve_id );
1498 SELECT reserve_id, borrowernumber, reservedate
1500 WHERE biblionumber = ?
1501 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1502 ORDER BY priority ASC
1504 my $sth = $dbh->prepare($query);
1505 $sth->execute( $biblionumber );
1506 while ( my $line = $sth->fetchrow_hashref ) {
1507 push( @priority, $line );
1510 # To find the matching index
1512 my $key = -1; # to allow for 0 to be a valid result
1513 for ( $i = 0 ; $i < @priority ; $i++ ) {
1514 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1515 $key = $i; # save the index
1520 # if index exists in array then move it to new position
1521 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1522 my $new_rank = $rank -
1523 1; # $new_rank is what you want the new index to be in the array
1524 my $moving_item = splice( @priority, $key, 1 );
1525 splice( @priority, $new_rank, 0, $moving_item );
1528 # now fix the priority on those that are left....
1532 WHERE reserve_id = ?
1534 $sth = $dbh->prepare($query);
1535 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1538 $priority[$j]->{'reserve_id'}
1542 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1545 unless ( $ignoreSetLowestRank ) {
1546 while ( my $res = $sth->fetchrow_hashref() ) {
1548 reserve_id => $res->{'reserve_id'},
1550 ignoreSetLowestRank => 1
1556 =head2 _Findgroupreserve
1558 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1560 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1561 first match found. If neither, then we look for non-holds-queue based holds.
1562 Lookahead is the number of days to look in advance.
1564 C<&_Findgroupreserve> returns :
1565 C<@results> is an array of references-to-hash whose keys are mostly
1566 fields from the reserves table of the Koha database, plus
1567 C<biblioitemnumber>.
1569 This routine with either return:
1570 1 - Item specific holds from the holds queue
1571 2 - Title level holds from the holds queue
1572 3 - All holds for this biblionumber
1574 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1578 sub _Findgroupreserve {
1579 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1580 my $dbh = C4::Context->dbh;
1582 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1583 # check for exact targeted match
1584 my $item_level_target_query = qq{
1585 SELECT reserves.biblionumber AS biblionumber,
1586 reserves.borrowernumber AS borrowernumber,
1587 reserves.reservedate AS reservedate,
1588 reserves.branchcode AS branchcode,
1589 reserves.cancellationdate AS cancellationdate,
1590 reserves.found AS found,
1591 reserves.reservenotes AS reservenotes,
1592 reserves.priority AS priority,
1593 reserves.timestamp AS timestamp,
1594 biblioitems.biblioitemnumber AS biblioitemnumber,
1595 reserves.itemnumber AS itemnumber,
1596 reserves.reserve_id AS reserve_id,
1597 reserves.itemtype AS itemtype
1599 JOIN biblioitems USING (biblionumber)
1600 JOIN hold_fill_targets USING (reserve_id)
1603 AND item_level_request = 1
1604 AND hold_fill_targets.itemnumber = ?
1605 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1609 my $sth = $dbh->prepare($item_level_target_query);
1610 $sth->execute($itemnumber, $lookahead||0);
1612 if ( my $data = $sth->fetchrow_hashref ) {
1613 push( @results, $data )
1614 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1616 return @results if @results;
1618 # check for title-level targeted match
1619 my $title_level_target_query = qq{
1620 SELECT reserves.biblionumber AS biblionumber,
1621 reserves.borrowernumber AS borrowernumber,
1622 reserves.reservedate AS reservedate,
1623 reserves.branchcode AS branchcode,
1624 reserves.cancellationdate AS cancellationdate,
1625 reserves.found AS found,
1626 reserves.reservenotes AS reservenotes,
1627 reserves.priority AS priority,
1628 reserves.timestamp AS timestamp,
1629 biblioitems.biblioitemnumber AS biblioitemnumber,
1630 reserves.itemnumber AS itemnumber,
1631 reserves.reserve_id AS reserve_id,
1632 reserves.itemtype AS itemtype
1634 JOIN biblioitems USING (biblionumber)
1635 JOIN hold_fill_targets USING (reserve_id)
1638 AND item_level_request = 0
1639 AND hold_fill_targets.itemnumber = ?
1640 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1644 $sth = $dbh->prepare($title_level_target_query);
1645 $sth->execute($itemnumber, $lookahead||0);
1647 if ( my $data = $sth->fetchrow_hashref ) {
1648 push( @results, $data )
1649 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1651 return @results if @results;
1654 SELECT reserves.biblionumber AS biblionumber,
1655 reserves.borrowernumber AS borrowernumber,
1656 reserves.reservedate AS reservedate,
1657 reserves.waitingdate AS waitingdate,
1658 reserves.branchcode AS branchcode,
1659 reserves.cancellationdate AS cancellationdate,
1660 reserves.found AS found,
1661 reserves.reservenotes AS reservenotes,
1662 reserves.priority AS priority,
1663 reserves.timestamp AS timestamp,
1664 reserves.itemnumber AS itemnumber,
1665 reserves.reserve_id AS reserve_id,
1666 reserves.itemtype AS itemtype
1668 WHERE reserves.biblionumber = ?
1669 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1670 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1674 $sth = $dbh->prepare($query);
1675 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1677 while ( my $data = $sth->fetchrow_hashref ) {
1678 push( @results, $data )
1679 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1684 =head2 _koha_notify_reserve
1686 _koha_notify_reserve( $hold->reserve_id );
1688 Sends a notification to the patron that their hold has been filled (through
1689 ModReserveAffect, _not_ ModReserveFill)
1691 The letter code for this notice may be found using the following query:
1693 select distinct letter_code
1694 from message_transports
1695 inner join message_attributes using (message_attribute_id)
1696 where message_name = 'Hold_Filled'
1698 This will probably sipmly be 'HOLD', but because it is defined in the database,
1699 it is subject to addition or change.
1701 The following tables are availalbe witin the notice:
1712 sub _koha_notify_reserve {
1713 my $reserve_id = shift;
1714 my $hold = Koha::Holds->find($reserve_id);
1715 my $borrowernumber = $hold->borrowernumber;
1717 my $patron = Koha::Patrons->find( $borrowernumber );
1719 # Try to get the borrower's email address
1720 my $to_address = $patron->notice_email_address;
1722 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1723 borrowernumber => $borrowernumber,
1724 message_name => 'Hold_Filled'
1727 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1729 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1731 my %letter_params = (
1732 module => 'reserves',
1733 branchcode => $hold->branchcode,
1734 lang => $patron->lang,
1736 'branches' => $library,
1737 'borrowers' => $patron->unblessed,
1738 'biblio' => $hold->biblionumber,
1739 'biblioitems' => $hold->biblionumber,
1740 'reserves' => $hold->unblessed,
1741 'items' => $hold->itemnumber,
1745 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.
1746 my $send_notification = sub {
1747 my ( $mtt, $letter_code ) = (@_);
1748 return unless defined $letter_code;
1749 $letter_params{letter_code} = $letter_code;
1750 $letter_params{message_transport_type} = $mtt;
1751 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1753 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1757 C4::Letters::EnqueueLetter( {
1759 borrowernumber => $borrowernumber,
1760 from_address => $admin_email_address,
1761 message_transport_type => $mtt,
1765 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1767 ( $mtt eq 'email' and not $to_address ) # No email address
1768 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1769 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1772 &$send_notification($mtt, $letter_code);
1773 $notification_sent++;
1775 #Making sure that a print notification is sent if no other transport types can be utilized.
1776 if (! $notification_sent) {
1777 &$send_notification('print', 'HOLD');
1782 =head2 _ShiftPriorityByDateAndPriority
1784 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1786 This increments the priority of all reserves after the one
1787 with either the lowest date after C<$reservedate>
1788 or the lowest priority after C<$priority>.
1790 It effectively makes room for a new reserve to be inserted with a certain
1791 priority, which is returned.
1793 This is most useful when the reservedate can be set by the user. It allows
1794 the new reserve to be placed before other reserves that have a later
1795 reservedate. Since priority also is set by the form in reserves/request.pl
1796 the sub accounts for that too.
1800 sub _ShiftPriorityByDateAndPriority {
1801 my ( $biblio, $resdate, $new_priority ) = @_;
1803 my $dbh = C4::Context->dbh;
1804 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1805 my $sth = $dbh->prepare( $query );
1806 $sth->execute( $biblio, $resdate, $new_priority );
1807 my $min_priority = $sth->fetchrow;
1808 # if no such matches are found, $new_priority remains as original value
1809 $new_priority = $min_priority if ( $min_priority );
1811 # Shift the priority up by one; works in conjunction with the next SQL statement
1812 $query = "UPDATE reserves
1813 SET priority = priority+1
1814 WHERE biblionumber = ?
1815 AND borrowernumber = ?
1818 my $sth_update = $dbh->prepare( $query );
1820 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1821 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1822 $sth = $dbh->prepare( $query );
1823 $sth->execute( $new_priority, $biblio );
1824 while ( my $row = $sth->fetchrow_hashref ) {
1825 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1828 return $new_priority; # so the caller knows what priority they wind up receiving
1833 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1835 Use when checking out an item to handle reserves
1836 If $cancelreserve boolean is set to true, it will remove existing reserve
1841 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1843 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1844 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1847 my $biblionumber = $res->{biblionumber};
1849 if ($res->{borrowernumber} == $borrowernumber) {
1850 ModReserveFill($res);
1854 # The item is reserved by someone else.
1855 # Find this item in the reserves
1857 my $borr_res = Koha::Holds->search({
1858 borrowernumber => $borrowernumber,
1859 biblionumber => $biblionumber,
1861 order_by => 'priority'
1865 # The item is reserved by the current patron
1866 ModReserveFill($borr_res->unblessed);
1869 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1870 RevertWaitingStatus({ itemnumber => $itemnumber });
1872 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1873 my $hold = Koha::Holds->find( $res->{reserve_id} );
1881 MergeHolds($dbh,$to_biblio, $from_biblio);
1883 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1888 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1889 my $sth = $dbh->prepare(
1890 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1892 $sth->execute($from_biblio);
1893 if ( my $data = $sth->fetchrow_hashref() ) {
1895 # holds exist on old record, if not we don't need to do anything
1896 $sth = $dbh->prepare(
1897 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1898 $sth->execute( $to_biblio, $from_biblio );
1901 # don't reorder those already waiting
1903 $sth = $dbh->prepare(
1904 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1906 my $upd_sth = $dbh->prepare(
1907 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1908 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1910 $sth->execute( $to_biblio, 'W', 'T' );
1912 while ( my $reserve = $sth->fetchrow_hashref() ) {
1914 $priority, $to_biblio,
1915 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1916 $reserve->{'itemnumber'}
1923 =head2 RevertWaitingStatus
1925 RevertWaitingStatus({ itemnumber => $itemnumber });
1927 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1929 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1930 item level hold, even if it was only a bibliolevel hold to
1931 begin with. This is because we can no longer know if a hold
1932 was item-level or bib-level after a hold has been set to
1937 sub RevertWaitingStatus {
1938 my ( $params ) = @_;
1939 my $itemnumber = $params->{'itemnumber'};
1941 return unless ( $itemnumber );
1943 my $dbh = C4::Context->dbh;
1945 ## Get the waiting reserve we want to revert
1947 SELECT * FROM reserves
1948 WHERE itemnumber = ?
1949 AND found IS NOT NULL
1951 my $sth = $dbh->prepare( $query );
1952 $sth->execute( $itemnumber );
1953 my $reserve = $sth->fetchrow_hashref();
1955 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1957 ## Increment the priority of all other non-waiting
1958 ## reserves for this bib record
1962 priority = priority + 1
1968 $sth = $dbh->prepare( $query );
1969 $sth->execute( $reserve->{'biblionumber'} );
1975 waitingdate => undef,
1976 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
1980 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1989 branchcode => $branchcode,
1990 borrowernumber => $borrowernumber,
1991 biblionumber => $biblionumber,
1992 [ itemnumber => $itemnumber, ]
1993 [ barcode => $barcode, ]
1997 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1999 The letter code will be HOLD_SLIP, and the following tables are
2000 available within the slip:
2013 my $branchcode = $args->{branchcode};
2014 my $reserve_id = $args->{reserve_id};
2016 my $hold = Koha::Holds->find($reserve_id);
2017 return unless $hold;
2019 my $patron = $hold->borrower;
2020 my $reserve = $hold->unblessed;
2022 return C4::Letters::GetPreparedLetter (
2023 module => 'circulation',
2024 letter_code => 'HOLD_SLIP',
2025 branchcode => $branchcode,
2026 lang => $patron->lang,
2028 'reserves' => $reserve,
2029 'branches' => $reserve->{branchcode},
2030 'borrowers' => $reserve->{borrowernumber},
2031 'biblio' => $reserve->{biblionumber},
2032 'biblioitems' => $reserve->{biblionumber},
2033 'items' => $reserve->{itemnumber},
2038 =head2 GetReservesControlBranch
2040 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2042 Return the branchcode to be used to determine which reserves
2043 policy applies to a transaction.
2045 C<$item> is a hashref for an item. Only 'homebranch' is used.
2047 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2051 sub GetReservesControlBranch {
2052 my ( $item, $borrower ) = @_;
2054 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2057 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2058 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2064 =head2 CalculatePriority
2066 my $p = CalculatePriority($biblionumber, $resdate);
2068 Calculate priority for a new reserve on biblionumber, placing it at
2069 the end of the line of all holds whose start date falls before
2070 the current system time and that are neither on the hold shelf
2073 The reserve date parameter is optional; if it is supplied, the
2074 priority is based on the set of holds whose start date falls before
2075 the parameter value.
2077 After calculation of this priority, it is recommended to call
2078 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2083 sub CalculatePriority {
2084 my ( $biblionumber, $resdate ) = @_;
2087 SELECT COUNT(*) FROM reserves
2088 WHERE biblionumber = ?
2090 AND (found IS NULL OR found = '')
2092 #skip found==W or found==T (waiting or transit holds)
2094 $sql.= ' AND ( reservedate <= ? )';
2097 $sql.= ' AND ( reservedate < NOW() )';
2099 my $dbh = C4::Context->dbh();
2100 my @row = $dbh->selectrow_array(
2103 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2106 return @row ? $row[0]+1 : 1;
2109 =head2 IsItemOnHoldAndFound
2111 my $bool = IsItemFoundHold( $itemnumber );
2113 Returns true if the item is currently on hold
2114 and that hold has a non-null found status ( W, T, etc. )
2118 sub IsItemOnHoldAndFound {
2119 my ($itemnumber) = @_;
2121 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2123 my $found = $rs->count(
2125 itemnumber => $itemnumber,
2126 found => { '!=' => undef }
2133 =head2 GetMaxPatronHoldsForRecord
2135 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2137 For multiple holds on a given record for a given patron, the max
2138 number of record level holds that a patron can be placed is the highest
2139 value of the holds_per_record rule for each item if the record for that
2140 patron. This subroutine finds and returns the highest holds_per_record
2141 rule value for a given patron id and record id.
2145 sub GetMaxPatronHoldsForRecord {
2146 my ( $borrowernumber, $biblionumber ) = @_;
2148 my $patron = Koha::Patrons->find($borrowernumber);
2149 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2151 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2153 my $categorycode = $patron->categorycode;
2155 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2158 foreach my $item (@items) {
2159 my $itemtype = $item->effective_itemtype();
2161 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2163 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2164 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2165 $max = $holds_per_record if $holds_per_record > $max;
2173 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2175 Returns the matching hold related issuingrule fields for a given
2176 patron category, itemtype, and library.
2181 my ( $categorycode, $itemtype, $branchcode ) = @_;
2183 my $dbh = C4::Context->dbh;
2185 my $sth = $dbh->prepare(
2187 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2189 WHERE (categorycode in (?,'*') )
2190 AND (itemtype IN (?,'*'))
2191 AND (branchcode IN (?,'*'))
2192 ORDER BY categorycode DESC,
2198 $sth->execute( $categorycode, $itemtype, $branchcode );
2200 return $sth->fetchrow_hashref();
2205 Koha Development Team <http://koha-community.org/>