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
33 # for _koha_notify_reserve
34 use C4::Members::Messaging;
47 use Koha::IssuingRules;
52 use List::MoreUtils qw( firstidx any );
56 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
60 C4::Reserves - Koha functions for dealing with reservation.
68 This modules provides somes functions to deal with reservations.
70 Reserves are stored in reserves table.
71 The following columns contains important values :
72 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
73 =0 : then the reserve is being dealed
74 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
75 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
76 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
77 F(inished) : the reserve has been completed, and is done
78 - itemnumber : empty : the reserve is still unaffected to an item
79 filled: the reserve is attached to an item
80 The complete workflow is :
81 ==== 1st use case ====
82 patron request a document, 1st available : P >0, F=NULL, I=NULL
83 a library having it run "transfertodo", and clic on the list
84 if there is no transfer to do, the reserve waiting
85 patron can pick it up P =0, F=W, I=filled
86 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
87 The pickup library receive the book, it check in P =0, F=W, I=filled
88 The patron borrow the book P =0, F=F, I=filled
90 ==== 2nd use case ====
91 patron requests a document, a given item,
92 If pickup is holding branch P =0, F=W, I=filled
93 If transfer needed, write in branchtransfer P =0, F=T, I=filled
94 The pickup library receive the book, it checks it in P =0, F=W, I=filled
95 The patron borrow the book P =0, F=F, I=filled
107 &GetReservesForBranch
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
130 &OPACItemHoldsAllowed
133 &ToggleLowestPriority
139 &GetReservesControlBranch
143 GetMaxPatronHoldsForRecord
145 @EXPORT_OK = qw( MergeHolds );
150 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
152 Adds reserve and generates HOLDPLACED message.
154 The following tables are available witin the HOLDPLACED message:
167 $branch, $borrowernumber, $biblionumber, $bibitems,
168 $priority, $resdate, $expdate, $notes,
169 $title, $checkitem, $found, $itemtype
172 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
173 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
175 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
177 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
178 # of the document, we force the value $priority and $found .
179 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
181 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
182 if ( $item->holdingbranch eq $branch ) {
187 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
189 # Make room in reserves for this before those of a later reserve date
190 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
195 # If the reserv had the waiting status, we had the value of the resdate
196 if ( $found eq 'W' ) {
197 $waitingdate = $resdate;
200 # Don't add itemtype limit if specific item is selected
201 $itemtype = undef if $checkitem;
203 # updates take place here
204 my $hold = Koha::Hold->new(
206 borrowernumber => $borrowernumber,
207 biblionumber => $biblionumber,
208 reservedate => $resdate,
209 branchcode => $branch,
210 priority => $priority,
211 reservenotes => $notes,
212 itemnumber => $checkitem,
214 waitingdate => $waitingdate,
215 expirationdate => $expdate,
216 itemtype => $itemtype,
219 $hold->set_waiting() if $found eq 'W';
221 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
222 if C4::Context->preference('HoldsLog');
224 my $reserve_id = $hold->id();
226 # add a reserve fee if needed
227 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
228 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
229 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
232 _FixPriority({ biblionumber => $biblionumber});
234 # Send e-mail to librarian if syspref is active
235 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
236 my $patron = Koha::Patrons->find( $borrowernumber );
237 my $library = $patron->library;
238 if ( my $letter = C4::Letters::GetPreparedLetter (
239 module => 'reserves',
240 letter_code => 'HOLDPLACED',
241 branchcode => $branch,
242 lang => $patron->lang,
244 'branches' => $library->unblessed,
245 'borrowers' => $patron->unblessed,
246 'biblio' => $biblionumber,
247 'biblioitems' => $biblionumber,
248 'items' => $checkitem,
249 'reserves' => $hold->unblessed,
253 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
255 C4::Letters::EnqueueLetter(
257 borrowernumber => $borrowernumber,
258 message_transport_type => 'email',
259 from_address => $admin_email_address,
260 to_address => $admin_email_address,
269 =head2 CanBookBeReserved
271 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
272 if ($canReserve eq 'OK') { #We can reserve this Item! }
274 See CanItemBeReserved() for possible return values.
278 sub CanBookBeReserved{
279 my ($borrowernumber, $biblionumber) = @_;
281 my $items = GetItemnumbersForBiblio($biblionumber);
282 #get items linked via host records
283 my @hostitems = get_hostitemnumbers_of($biblionumber);
285 push (@$items,@hostitems);
289 foreach my $item (@$items) {
290 $canReserve = CanItemBeReserved( $borrowernumber, $item );
291 return 'OK' if $canReserve eq 'OK';
296 =head2 CanItemBeReserved
298 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
299 if ($canReserve eq 'OK') { #We can reserve this Item! }
301 @RETURNS OK, if the Item can be reserved.
302 ageRestricted, if the Item is age restricted for this borrower.
303 damaged, if the Item is damaged.
304 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
305 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
306 notReservable, if holds on this item are not allowed
310 sub CanItemBeReserved {
311 my ( $borrowernumber, $itemnumber ) = @_;
313 my $dbh = C4::Context->dbh;
314 my $ruleitemtype; # itemtype of the matching issuing rule
315 my $allowedreserves = 0; # Total number of holds allowed across all records
316 my $holds_per_record = 1; # Total number of holds allowed for this one given record
318 # we retrieve borrowers and items informations #
319 # item->{itype} will come for biblioitems if necessery
320 my $item = GetItem($itemnumber);
321 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
322 my $patron = Koha::Patrons->find( $borrowernumber );
323 my $borrower = $patron->unblessed;
325 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
327 if ( $item->{damaged}
328 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
330 # Check for the age restriction
331 my ( $ageRestriction, $daysToAgeRestriction ) =
332 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
333 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
335 # Check that the patron doesn't have an item level hold on this item already
336 return 'itemAlreadyOnHold'
337 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
339 my $controlbranch = C4::Context->preference('ReservesControlBranch');
342 SELECT count(*) AS count
344 LEFT JOIN items USING (itemnumber)
345 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
346 LEFT JOIN borrowers USING (borrowernumber)
347 WHERE borrowernumber = ?
351 my $branchfield = "reserves.branchcode";
353 if ( $controlbranch eq "ItemHomeLibrary" ) {
354 $branchfield = "items.homebranch";
355 $branchcode = $item->{homebranch};
357 elsif ( $controlbranch eq "PatronLibrary" ) {
358 $branchfield = "borrowers.branchcode";
359 $branchcode = $borrower->{branchcode};
363 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
364 $ruleitemtype = $rights->{itemtype};
365 $allowedreserves = $rights->{reservesallowed};
366 $holds_per_record = $rights->{holds_per_record};
372 $item = Koha::Items->find( $itemnumber );
373 my $holds = Koha::Holds->search(
375 borrowernumber => $borrowernumber,
376 biblionumber => $item->biblionumber,
377 found => undef, # Found holds don't count against a patron's holds limit
380 if ( $holds->count() >= $holds_per_record ) {
381 return "tooManyHoldsForThisRecord";
386 $querycount .= "AND $branchfield = ?";
388 # If using item-level itypes, fall back to the record
389 # level itemtype if the hold has no associated item
391 C4::Context->preference('item-level_itypes')
392 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
393 : " AND biblioitems.itemtype = ?"
394 if ( $ruleitemtype ne "*" );
396 my $sthcount = $dbh->prepare($querycount);
398 if ( $ruleitemtype eq "*" ) {
399 $sthcount->execute( $borrowernumber, $branchcode );
402 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
405 my $reservecount = "0";
406 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
407 $reservecount = $rowcount->{count};
410 # we check if it's ok or not
411 if ( $reservecount >= $allowedreserves ) {
412 return 'tooManyReserves';
415 my $circ_control_branch =
416 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
418 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
420 if ( $branchitemrule->{holdallowed} == 0 ) {
421 return 'notReservable';
424 if ( $branchitemrule->{holdallowed} == 1
425 && $borrower->{branchcode} ne $item->homebranch )
427 return 'cannotReserveFromOtherBranches';
430 # If reservecount is ok, we check item branch if IndependentBranches is ON
431 # and canreservefromotherbranches is OFF
432 if ( C4::Context->preference('IndependentBranches')
433 and !C4::Context->preference('canreservefromotherbranches') )
435 my $itembranch = $item->homebranch;
436 if ( $itembranch ne $borrower->{branchcode} ) {
437 return 'cannotReserveFromOtherBranches';
444 =head2 CanReserveBeCanceledFromOpac
446 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
448 returns 1 if reserve can be cancelled by user from OPAC.
449 First check if reserve belongs to user, next checks if reserve is not in
450 transfer or waiting status
454 sub CanReserveBeCanceledFromOpac {
455 my ($reserve_id, $borrowernumber) = @_;
457 return unless $reserve_id and $borrowernumber;
458 my $reserve = Koha::Holds->find($reserve_id);
460 return 0 unless $reserve->borrowernumber == $borrowernumber;
461 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
467 =head2 GetOtherReserves
469 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
471 Check queued list of this document and check if this document must be transferred
475 sub GetOtherReserves {
476 my ($itemnumber) = @_;
479 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
480 if ($checkreserves) {
481 my $iteminfo = GetItem($itemnumber);
482 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
483 $messages->{'transfert'} = $checkreserves->{'branchcode'};
484 #minus priorities of others reservs
485 ModReserveMinusPriority(
487 $checkreserves->{'reserve_id'},
490 #launch the subroutine dotransfer
491 C4::Items::ModItemTransfer(
493 $iteminfo->{'holdingbranch'},
494 $checkreserves->{'branchcode'}
499 #step 2b : case of a reservation on the same branch, set the waiting status
501 $messages->{'waiting'} = 1;
502 ModReserveMinusPriority(
504 $checkreserves->{'reserve_id'},
506 ModReserveStatus($itemnumber,'W');
509 $nextreservinfo = $checkreserves->{'borrowernumber'};
512 return ( $messages, $nextreservinfo );
515 =head2 ChargeReserveFee
517 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
519 Charge the fee for a reserve (if $fee > 0)
523 sub ChargeReserveFee {
524 my ( $borrowernumber, $fee, $title ) = @_;
525 return if !$fee || $fee==0; # the last test is needed to include 0.00
527 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
529 my $dbh = C4::Context->dbh;
530 my $nextacctno = &getnextacctno( $borrowernumber );
531 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
536 $fee = GetReserveFee( $borrowernumber, $biblionumber );
538 Calculate the fee for a reserve (if applicable).
543 my ( $borrowernumber, $biblionumber ) = @_;
545 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
548 SELECT COUNT(*) FROM items
549 LEFT JOIN issues USING (itemnumber)
550 WHERE items.biblionumber=? AND issues.issue_id IS NULL
553 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
556 my $dbh = C4::Context->dbh;
557 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
558 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
559 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
560 # This is a reconstruction of the old code:
561 # Compare number of items with items issued, and optionally check holds
562 # If not all items are issued and there are no holds: charge no fee
563 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
564 my ( $notissued, $reserved );
565 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
568 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
569 ( $biblionumber, $borrowernumber ) );
570 $fee = 0 if $reserved == 0;
576 =head2 GetReservesForBranch
578 @transreserv = GetReservesForBranch($frombranch);
582 sub GetReservesForBranch {
583 my ($frombranch) = @_;
584 my $dbh = C4::Context->dbh;
587 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
592 $query .= " AND branchcode=? " if ( $frombranch );
593 $query .= "ORDER BY waitingdate" ;
595 my $sth = $dbh->prepare($query);
597 $sth->execute($frombranch);
604 while ( my $data = $sth->fetchrow_hashref ) {
605 $transreserv[$i] = $data;
608 return (@transreserv);
611 =head2 GetReserveStatus
613 $reservestatus = GetReserveStatus($itemnumber);
615 Takes an itemnumber and returns the status of the reserve placed on it.
616 If several reserves exist, the reserve with the lower priority is given.
620 ## FIXME: I don't think this does what it thinks it does.
621 ## It only ever checks the first reserve result, even though
622 ## multiple reserves for that bib can have the itemnumber set
623 ## the sub is only used once in the codebase.
624 sub GetReserveStatus {
625 my ($itemnumber) = @_;
627 my $dbh = C4::Context->dbh;
629 my ($sth, $found, $priority);
631 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
632 $sth->execute($itemnumber);
633 ($found, $priority) = $sth->fetchrow_array;
637 return 'Waiting' if $found eq 'W' and $priority == 0;
638 return 'Finished' if $found eq 'F';
641 return 'Reserved' if $priority > 0;
643 return ''; # empty string here will remove need for checking undef, or less log lines
648 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
649 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
650 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
652 Find a book in the reserves.
654 C<$itemnumber> is the book's item number.
655 C<$lookahead> is the number of days to look in advance for future reserves.
657 As I understand it, C<&CheckReserves> looks for the given item in the
658 reserves. If it is found, that's a match, and C<$status> is set to
661 Otherwise, it finds the most important item in the reserves with the
662 same biblio number as this book (I'm not clear on this) and returns it
663 with C<$status> set to C<Reserved>.
665 C<&CheckReserves> returns a two-element list:
667 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
669 C<$reserve> is the reserve item that matched. It is a
670 reference-to-hash whose keys are mostly the fields of the reserves
671 table in the Koha database.
676 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
677 my $dbh = C4::Context->dbh;
680 if (C4::Context->preference('item-level_itypes')){
682 SELECT items.biblionumber,
683 items.biblioitemnumber,
684 itemtypes.notforloan,
685 items.notforloan AS itemnotforloan,
691 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
692 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
697 SELECT items.biblionumber,
698 items.biblioitemnumber,
699 itemtypes.notforloan,
700 items.notforloan AS itemnotforloan,
706 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
707 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
712 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
713 $sth->execute($item);
716 $sth = $dbh->prepare("$select WHERE barcode = ?");
717 $sth->execute($barcode);
719 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
720 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
722 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
724 return unless $itemnumber; # bail if we got nothing.
726 # if item is not for loan it cannot be reserved either.....
727 # except where items.notforloan < 0 : This indicates the item is holdable.
728 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
730 # Find this item in the reserves
731 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
733 # $priority and $highest are used to find the most important item
734 # in the list returned by &_Findgroupreserve. (The lower $priority,
735 # the more important the item.)
736 # $highest is the most important item we've seen so far.
738 if (scalar @reserves) {
739 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
740 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
741 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
743 my $priority = 10000000;
744 foreach my $res (@reserves) {
745 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
746 if ($res->{'found'} eq 'W') {
747 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
749 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
754 my $local_hold_match;
756 if ($LocalHoldsPriority) {
757 $patron = Koha::Patrons->find( $res->{borrowernumber} );
758 $iteminfo = C4::Items::GetItem($itemnumber);
760 my $local_holds_priority_item_branchcode =
761 $iteminfo->{$LocalHoldsPriorityItemControl};
762 my $local_holds_priority_patron_branchcode =
763 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
765 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
766 ? $patron->branchcode
769 $local_holds_priority_item_branchcode eq
770 $local_holds_priority_patron_branchcode;
773 # See if this item is more important than what we've got so far
774 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
775 $iteminfo ||= C4::Items::GetItem($itemnumber);
776 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
777 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
778 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
779 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
780 next if ($branchitemrule->{'holdallowed'} == 0);
781 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
782 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
783 $priority = $res->{'priority'};
785 last if $local_hold_match;
791 # If we get this far, then no exact match was found.
792 # We return the most important (i.e. next) reservation.
794 $highest->{'itemnumber'} = $item;
795 return ( "Reserved", $highest, \@reserves );
801 =head2 CancelExpiredReserves
803 CancelExpiredReserves();
805 Cancels all reserves with an expiration date from before today.
809 sub CancelExpiredReserves {
810 my $today = dt_from_string();
811 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
812 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
814 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
815 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
816 $params->{found} = undef unless $expireWaiting;
818 # FIXME To move to Koha::Holds->search_expired (?)
819 my $holds = Koha::Holds->search( $params );
821 while ( my $hold = $holds->next ) {
822 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
824 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
826 my $cancel_params = {};
827 if ( $hold->found eq 'W' ) {
828 $cancel_params->{charge_cancel_fee} = 1;
830 $hold->cancel( $cancel_params );
834 =head2 AutoUnsuspendReserves
836 AutoUnsuspendReserves();
838 Unsuspends all suspended reserves with a suspend_until date from before today.
842 sub AutoUnsuspendReserves {
843 my $today = dt_from_string();
845 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
847 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
852 ModReserve({ rank => $rank,
853 reserve_id => $reserve_id,
854 branchcode => $branchcode
855 [, itemnumber => $itemnumber ]
856 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
859 Change a hold request's priority or cancel it.
861 C<$rank> specifies the effect of the change. If C<$rank>
862 is 'W' or 'n', nothing happens. This corresponds to leaving a
863 request alone when changing its priority in the holds queue
866 If C<$rank> is 'del', the hold request is cancelled.
868 If C<$rank> is an integer greater than zero, the priority of
869 the request is set to that value. Since priority != 0 means
870 that the item is not waiting on the hold shelf, setting the
871 priority to a non-zero value also sets the request's found
872 status and waiting date to NULL.
874 The optional C<$itemnumber> parameter is used only when
875 C<$rank> is a non-zero integer; if supplied, the itemnumber
876 of the hold request is set accordingly; if omitted, the itemnumber
879 B<FIXME:> Note that the forgoing can have the effect of causing
880 item-level hold requests to turn into title-level requests. This
881 will be fixed once reserves has separate columns for requested
882 itemnumber and supplying itemnumber.
889 my $rank = $params->{'rank'};
890 my $reserve_id = $params->{'reserve_id'};
891 my $branchcode = $params->{'branchcode'};
892 my $itemnumber = $params->{'itemnumber'};
893 my $suspend_until = $params->{'suspend_until'};
894 my $borrowernumber = $params->{'borrowernumber'};
895 my $biblionumber = $params->{'biblionumber'};
897 return if $rank eq "W";
898 return if $rank eq "n";
900 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
903 unless ( $reserve_id ) {
904 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
905 return unless $holds->count; # FIXME Should raise an exception
906 $hold = $holds->next;
907 $reserve_id = $hold->reserve_id;
910 $hold ||= Koha::Holds->find($reserve_id);
912 if ( $rank eq "del" ) {
915 elsif ($rank =~ /^\d+/ and $rank > 0) {
916 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
917 if C4::Context->preference('HoldsLog');
922 branchcode => $branchcode,
923 itemnumber => $itemnumber,
929 if ( defined( $suspend_until ) ) {
930 if ( $suspend_until ) {
931 $suspend_until = eval { dt_from_string( $suspend_until ) };
932 $hold->suspend_hold( $suspend_until );
934 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
935 # If the hold is not suspended, this does nothing.
936 $hold->set( { suspend_until => undef } )->store();
940 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
944 =head2 ModReserveFill
946 &ModReserveFill($reserve);
948 Fill a reserve. If I understand this correctly, this means that the
949 reserved book has been found and given to the patron who reserved it.
951 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
952 whose keys are fields from the reserves table in the Koha database.
958 my $reserve_id = $res->{'reserve_id'};
960 my $hold = Koha::Holds->find($reserve_id);
962 # get the priority on this record....
963 my $priority = $hold->priority;
965 # update the hold statuses, no need to store it though, we will be deleting it anyway
973 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
974 Koha::Old::Hold->new( $hold->unblessed() )->store();
978 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
979 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
980 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
983 # now fix the priority on the others (if the priority wasn't
984 # already sorted!)....
985 unless ( $priority == 0 ) {
986 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
990 =head2 ModReserveStatus
992 &ModReserveStatus($itemnumber, $newstatus);
994 Update the reserve status for the active (priority=0) reserve.
996 $itemnumber is the itemnumber the reserve is on
998 $newstatus is the new status.
1002 sub ModReserveStatus {
1004 #first : check if we have a reservation for this item .
1005 my ($itemnumber, $newstatus) = @_;
1006 my $dbh = C4::Context->dbh;
1008 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1009 my $sth_set = $dbh->prepare($query);
1010 $sth_set->execute( $newstatus, $itemnumber );
1012 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1013 CartToShelf( $itemnumber );
1017 =head2 ModReserveAffect
1019 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1021 This function affect an item and a status for a given reserve, either fetched directly
1022 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1023 is given, only first reserve returned is affected, which is ok for anything but
1026 if $transferToDo is not set, then the status is set to "Waiting" as well.
1027 otherwise, a transfer is on the way, and the end of the transfer will
1028 take care of the waiting status
1032 sub ModReserveAffect {
1033 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1034 my $dbh = C4::Context->dbh;
1036 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1037 # attached to $itemnumber
1038 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1039 $sth->execute($itemnumber);
1040 my ($biblionumber) = $sth->fetchrow;
1042 # get request - need to find out if item is already
1043 # waiting in order to not send duplicate hold filled notifications
1046 # Find hold by id if we have it
1047 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1048 # Find item level hold for this item if there is one
1049 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1050 # Find record level hold if there is no item level hold
1051 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1053 return unless $hold;
1055 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1057 $hold->itemnumber($itemnumber);
1058 $hold->set_waiting($transferToDo);
1060 _koha_notify_reserve( $hold->reserve_id )
1061 if ( !$transferToDo && !$already_on_shelf );
1063 _FixPriority( { biblionumber => $biblionumber } );
1065 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1066 CartToShelf($itemnumber);
1072 =head2 ModReserveCancelAll
1074 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1076 function to cancel reserv,check other reserves, and transfer document if it's necessary
1080 sub ModReserveCancelAll {
1083 my ( $itemnumber, $borrowernumber ) = @_;
1085 #step 1 : cancel the reservation
1086 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1087 return unless $holds->count;
1088 $holds->next->cancel;
1090 #step 2 launch the subroutine of the others reserves
1091 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1093 return ( $messages, $nextreservinfo );
1096 =head2 ModReserveMinusPriority
1098 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1100 Reduce the values of queued list
1104 sub ModReserveMinusPriority {
1105 my ( $itemnumber, $reserve_id ) = @_;
1107 #first step update the value of the first person on reserv
1108 my $dbh = C4::Context->dbh;
1111 SET priority = 0 , itemnumber = ?
1112 WHERE reserve_id = ?
1114 my $sth_upd = $dbh->prepare($query);
1115 $sth_upd->execute( $itemnumber, $reserve_id );
1116 # second step update all others reserves
1117 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1120 =head2 IsAvailableForItemLevelRequest
1122 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1124 Checks whether a given item record is available for an
1125 item-level hold request. An item is available if
1127 * it is not lost AND
1128 * it is not damaged AND
1129 * it is not withdrawn AND
1130 * a waiting or in transit reserve is placed on
1131 * does not have a not for loan value > 0
1133 Need to check the issuingrules onshelfholds column,
1134 if this is set items on the shelf can be placed on hold
1136 Note that IsAvailableForItemLevelRequest() does not
1137 check if the staff operator is authorized to place
1138 a request on the item - in particular,
1139 this routine does not check IndependentBranches
1140 and canreservefromotherbranches.
1144 sub IsAvailableForItemLevelRequest {
1146 my $borrower = shift;
1148 my $dbh = C4::Context->dbh;
1149 # must check the notforloan setting of the itemtype
1150 # FIXME - a lot of places in the code do this
1151 # or something similar - need to be
1153 my $itype = _get_itype($item);
1154 my $notforloan_per_itemtype
1155 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1159 $notforloan_per_itemtype ||
1160 $item->{itemlost} ||
1161 $item->{notforloan} > 0 ||
1162 $item->{withdrawn} ||
1163 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1165 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1167 if ( $on_shelf_holds == 1 ) {
1169 } elsif ( $on_shelf_holds == 2 ) {
1171 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1173 my $any_available = 0;
1175 foreach my $i (@items) {
1177 my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
1178 my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
1182 || $i->notforloan > 0
1185 || IsItemOnHoldAndFound( $i->id )
1187 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1188 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1189 || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
1192 return $any_available ? 0 : 1;
1193 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1194 return $item->{onloan} || IsItemOnHoldAndFound( $item->{itemnumber} );
1198 =head2 OnShelfHoldsAllowed
1200 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1202 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1203 holds are allowed, returns true if so.
1207 sub OnShelfHoldsAllowed {
1208 my ($item, $borrower) = @_;
1210 my $itype = _get_itype($item);
1211 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1218 if (C4::Context->preference('item-level_itypes')) {
1219 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1220 # When GetItem is fixed, we can remove this
1221 $itype = $item->{itype};
1224 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1225 # So if we already have a biblioitems join when calling this function,
1226 # we don't need to access the database again
1227 $itype = $item->{itemtype};
1230 my $dbh = C4::Context->dbh;
1231 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1232 my $sth = $dbh->prepare($query);
1233 $sth->execute($item->{biblioitemnumber});
1234 if (my $data = $sth->fetchrow_hashref()){
1235 $itype = $data->{itemtype};
1241 sub _OnShelfHoldsAllowed {
1242 my ($itype,$borrowercategory,$branchcode) = @_;
1244 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1245 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1248 =head2 AlterPriority
1250 AlterPriority( $where, $reserve_id );
1252 This function changes a reserve's priority up, down, to the top, or to the bottom.
1253 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1258 my ( $where, $reserve_id ) = @_;
1260 my $hold = Koha::Holds->find( $reserve_id );
1261 return unless $hold;
1263 if ( $hold->cancellationdate ) {
1264 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1268 if ( $where eq 'up' || $where eq 'down' ) {
1270 my $priority = $hold->priority;
1271 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1272 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1274 } elsif ( $where eq 'top' ) {
1276 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1278 } elsif ( $where eq 'bottom' ) {
1280 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1283 # FIXME Should return the new priority
1286 =head2 ToggleLowestPriority
1288 ToggleLowestPriority( $borrowernumber, $biblionumber );
1290 This function sets the lowestPriority field to true if is false, and false if it is true.
1294 sub ToggleLowestPriority {
1295 my ( $reserve_id ) = @_;
1297 my $dbh = C4::Context->dbh;
1299 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1300 $sth->execute( $reserve_id );
1302 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1305 =head2 ToggleSuspend
1307 ToggleSuspend( $reserve_id );
1309 This function sets the suspend field to true if is false, and false if it is true.
1310 If the reserve is currently suspended with a suspend_until date, that date will
1311 be cleared when it is unsuspended.
1316 my ( $reserve_id, $suspend_until ) = @_;
1318 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1320 my $hold = Koha::Holds->find( $reserve_id );
1322 if ( $hold->is_suspended ) {
1325 $hold->suspend_hold( $suspend_until );
1332 borrowernumber => $borrowernumber,
1333 [ biblionumber => $biblionumber, ]
1334 [ suspend_until => $suspend_until, ]
1335 [ suspend => $suspend ]
1338 This function accepts a set of hash keys as its parameters.
1339 It requires either borrowernumber or biblionumber, or both.
1341 suspend_until is wholly optional.
1348 my $borrowernumber = $params{'borrowernumber'} || undef;
1349 my $biblionumber = $params{'biblionumber'} || undef;
1350 my $suspend_until = $params{'suspend_until'} || undef;
1351 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1353 $suspend_until = eval { dt_from_string($suspend_until) }
1354 if ( defined($suspend_until) );
1356 return unless ( $borrowernumber || $biblionumber );
1359 $params->{found} = undef;
1360 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1361 $params->{biblionumber} = $biblionumber if $biblionumber;
1363 my @holds = Koha::Holds->search($params);
1366 map { $_->suspend_hold($suspend_until) } @holds;
1369 map { $_->resume() } @holds;
1377 reserve_id => $reserve_id,
1379 [ignoreSetLowestRank => $ignoreSetLowestRank]
1384 _FixPriority({ biblionumber => $biblionumber});
1386 This routine adjusts the priority of a hold request and holds
1389 In the first form, where a reserve_id is passed, the priority of the
1390 hold is set to supplied rank, and other holds for that bib are adjusted
1391 accordingly. If the rank is "del", the hold is cancelled. If no rank
1392 is supplied, all of the holds on that bib have their priority adjusted
1393 as if the second form had been used.
1395 In the second form, where a biblionumber is passed, the holds on that
1396 bib (that are not captured) are sorted in order of increasing priority,
1397 then have reserves.priority set so that the first non-captured hold
1398 has its priority set to 1, the second non-captured hold has its priority
1399 set to 2, and so forth.
1401 In both cases, holds that have the lowestPriority flag on are have their
1402 priority adjusted to ensure that they remain at the end of the line.
1404 Note that the ignoreSetLowestRank parameter is meant to be used only
1405 when _FixPriority calls itself.
1410 my ( $params ) = @_;
1411 my $reserve_id = $params->{reserve_id};
1412 my $rank = $params->{rank} // '';
1413 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1414 my $biblionumber = $params->{biblionumber};
1416 my $dbh = C4::Context->dbh;
1419 if ( $reserve_id ) {
1420 $hold = Koha::Holds->find( $reserve_id );
1421 return unless $hold;
1424 unless ( $biblionumber ) { # FIXME This is a very weird API
1425 $biblionumber = $hold->biblionumber;
1428 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1431 elsif ( $rank eq "W" || $rank eq "0" ) {
1433 # make sure priority for waiting or in-transit items is 0
1437 WHERE reserve_id = ?
1438 AND found IN ('W', 'T')
1440 my $sth = $dbh->prepare($query);
1441 $sth->execute( $reserve_id );
1447 SELECT reserve_id, borrowernumber, reservedate
1449 WHERE biblionumber = ?
1450 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1451 ORDER BY priority ASC
1453 my $sth = $dbh->prepare($query);
1454 $sth->execute( $biblionumber );
1455 while ( my $line = $sth->fetchrow_hashref ) {
1456 push( @priority, $line );
1459 # To find the matching index
1461 my $key = -1; # to allow for 0 to be a valid result
1462 for ( $i = 0 ; $i < @priority ; $i++ ) {
1463 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1464 $key = $i; # save the index
1469 # if index exists in array then move it to new position
1470 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1471 my $new_rank = $rank -
1472 1; # $new_rank is what you want the new index to be in the array
1473 my $moving_item = splice( @priority, $key, 1 );
1474 splice( @priority, $new_rank, 0, $moving_item );
1477 # now fix the priority on those that are left....
1481 WHERE reserve_id = ?
1483 $sth = $dbh->prepare($query);
1484 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1487 $priority[$j]->{'reserve_id'}
1491 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1494 unless ( $ignoreSetLowestRank ) {
1495 while ( my $res = $sth->fetchrow_hashref() ) {
1497 reserve_id => $res->{'reserve_id'},
1499 ignoreSetLowestRank => 1
1505 =head2 _Findgroupreserve
1507 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1509 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1510 first match found. If neither, then we look for non-holds-queue based holds.
1511 Lookahead is the number of days to look in advance.
1513 C<&_Findgroupreserve> returns :
1514 C<@results> is an array of references-to-hash whose keys are mostly
1515 fields from the reserves table of the Koha database, plus
1516 C<biblioitemnumber>.
1520 sub _Findgroupreserve {
1521 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1522 my $dbh = C4::Context->dbh;
1524 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1525 # check for exact targeted match
1526 my $item_level_target_query = qq{
1527 SELECT reserves.biblionumber AS biblionumber,
1528 reserves.borrowernumber AS borrowernumber,
1529 reserves.reservedate AS reservedate,
1530 reserves.branchcode AS branchcode,
1531 reserves.cancellationdate AS cancellationdate,
1532 reserves.found AS found,
1533 reserves.reservenotes AS reservenotes,
1534 reserves.priority AS priority,
1535 reserves.timestamp AS timestamp,
1536 biblioitems.biblioitemnumber AS biblioitemnumber,
1537 reserves.itemnumber AS itemnumber,
1538 reserves.reserve_id AS reserve_id,
1539 reserves.itemtype AS itemtype
1541 JOIN biblioitems USING (biblionumber)
1542 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1545 AND item_level_request = 1
1547 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1551 my $sth = $dbh->prepare($item_level_target_query);
1552 $sth->execute($itemnumber, $lookahead||0);
1554 if ( my $data = $sth->fetchrow_hashref ) {
1555 push( @results, $data )
1556 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1558 return @results if @results;
1560 # check for title-level targeted match
1561 my $title_level_target_query = qq{
1562 SELECT reserves.biblionumber AS biblionumber,
1563 reserves.borrowernumber AS borrowernumber,
1564 reserves.reservedate AS reservedate,
1565 reserves.branchcode AS branchcode,
1566 reserves.cancellationdate AS cancellationdate,
1567 reserves.found AS found,
1568 reserves.reservenotes AS reservenotes,
1569 reserves.priority AS priority,
1570 reserves.timestamp AS timestamp,
1571 biblioitems.biblioitemnumber AS biblioitemnumber,
1572 reserves.itemnumber AS itemnumber,
1573 reserves.reserve_id AS reserve_id,
1574 reserves.itemtype AS itemtype
1576 JOIN biblioitems USING (biblionumber)
1577 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1580 AND item_level_request = 0
1581 AND hold_fill_targets.itemnumber = ?
1582 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1586 $sth = $dbh->prepare($title_level_target_query);
1587 $sth->execute($itemnumber, $lookahead||0);
1589 if ( my $data = $sth->fetchrow_hashref ) {
1590 push( @results, $data )
1591 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1593 return @results if @results;
1596 SELECT reserves.biblionumber AS biblionumber,
1597 reserves.borrowernumber AS borrowernumber,
1598 reserves.reservedate AS reservedate,
1599 reserves.waitingdate AS waitingdate,
1600 reserves.branchcode AS branchcode,
1601 reserves.cancellationdate AS cancellationdate,
1602 reserves.found AS found,
1603 reserves.reservenotes AS reservenotes,
1604 reserves.priority AS priority,
1605 reserves.timestamp AS timestamp,
1606 reserves.itemnumber AS itemnumber,
1607 reserves.reserve_id AS reserve_id,
1608 reserves.itemtype AS itemtype
1610 WHERE reserves.biblionumber = ?
1611 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1612 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1616 $sth = $dbh->prepare($query);
1617 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1619 while ( my $data = $sth->fetchrow_hashref ) {
1620 push( @results, $data )
1621 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1626 =head2 _koha_notify_reserve
1628 _koha_notify_reserve( $hold->reserve_id );
1630 Sends a notification to the patron that their hold has been filled (through
1631 ModReserveAffect, _not_ ModReserveFill)
1633 The letter code for this notice may be found using the following query:
1635 select distinct letter_code
1636 from message_transports
1637 inner join message_attributes using (message_attribute_id)
1638 where message_name = 'Hold_Filled'
1640 This will probably sipmly be 'HOLD', but because it is defined in the database,
1641 it is subject to addition or change.
1643 The following tables are availalbe witin the notice:
1654 sub _koha_notify_reserve {
1655 my $reserve_id = shift;
1656 my $hold = Koha::Holds->find($reserve_id);
1657 my $borrowernumber = $hold->borrowernumber;
1659 my $patron = Koha::Patrons->find( $borrowernumber );
1661 # Try to get the borrower's email address
1662 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1664 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1665 borrowernumber => $borrowernumber,
1666 message_name => 'Hold_Filled'
1669 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1671 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1673 my %letter_params = (
1674 module => 'reserves',
1675 branchcode => $hold->branchcode,
1676 lang => $patron->lang,
1678 'branches' => $library,
1679 'borrowers' => $patron->unblessed,
1680 'biblio' => $hold->biblionumber,
1681 'biblioitems' => $hold->biblionumber,
1682 'reserves' => $hold->unblessed,
1683 'items' => $hold->itemnumber,
1687 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.
1688 my $send_notification = sub {
1689 my ( $mtt, $letter_code ) = (@_);
1690 return unless defined $letter_code;
1691 $letter_params{letter_code} = $letter_code;
1692 $letter_params{message_transport_type} = $mtt;
1693 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1695 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1699 C4::Letters::EnqueueLetter( {
1701 borrowernumber => $borrowernumber,
1702 from_address => $admin_email_address,
1703 message_transport_type => $mtt,
1707 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1709 ( $mtt eq 'email' and not $to_address ) # No email address
1710 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1711 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1714 &$send_notification($mtt, $letter_code);
1715 $notification_sent++;
1717 #Making sure that a print notification is sent if no other transport types can be utilized.
1718 if (! $notification_sent) {
1719 &$send_notification('print', 'HOLD');
1724 =head2 _ShiftPriorityByDateAndPriority
1726 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1728 This increments the priority of all reserves after the one
1729 with either the lowest date after C<$reservedate>
1730 or the lowest priority after C<$priority>.
1732 It effectively makes room for a new reserve to be inserted with a certain
1733 priority, which is returned.
1735 This is most useful when the reservedate can be set by the user. It allows
1736 the new reserve to be placed before other reserves that have a later
1737 reservedate. Since priority also is set by the form in reserves/request.pl
1738 the sub accounts for that too.
1742 sub _ShiftPriorityByDateAndPriority {
1743 my ( $biblio, $resdate, $new_priority ) = @_;
1745 my $dbh = C4::Context->dbh;
1746 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1747 my $sth = $dbh->prepare( $query );
1748 $sth->execute( $biblio, $resdate, $new_priority );
1749 my $min_priority = $sth->fetchrow;
1750 # if no such matches are found, $new_priority remains as original value
1751 $new_priority = $min_priority if ( $min_priority );
1753 # Shift the priority up by one; works in conjunction with the next SQL statement
1754 $query = "UPDATE reserves
1755 SET priority = priority+1
1756 WHERE biblionumber = ?
1757 AND borrowernumber = ?
1760 my $sth_update = $dbh->prepare( $query );
1762 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1763 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1764 $sth = $dbh->prepare( $query );
1765 $sth->execute( $new_priority, $biblio );
1766 while ( my $row = $sth->fetchrow_hashref ) {
1767 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1770 return $new_priority; # so the caller knows what priority they wind up receiving
1773 =head2 OPACItemHoldsAllowed
1775 OPACItemHoldsAllowed($item_record,$borrower_record);
1777 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1778 if specific item holds are allowed, returns true if so.
1782 sub OPACItemHoldsAllowed {
1783 my ($item,$borrower) = @_;
1785 my $branchcode = $item->{homebranch} or die "No homebranch";
1787 my $dbh = C4::Context->dbh;
1788 if (C4::Context->preference('item-level_itypes')) {
1789 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1790 # When GetItem is fixed, we can remove this
1791 $itype = $item->{itype};
1794 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1795 my $sth = $dbh->prepare($query);
1796 $sth->execute($item->{biblioitemnumber});
1797 if (my $data = $sth->fetchrow_hashref()){
1798 $itype = $data->{itemtype};
1802 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1803 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1805 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1807 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1809 issuingrules.categorycode desc,
1810 issuingrules.itemtype desc,
1811 issuingrules.branchcode desc
1813 my $sth = $dbh->prepare($query);
1814 $sth->execute($borrower->{categorycode},$itype,$branchcode);
1815 my $data = $sth->fetchrow_hashref;
1816 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1817 return '' if $opacitemholds eq 'N';
1818 return $opacitemholds;
1823 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1825 Use when checking out an item to handle reserves
1826 If $cancelreserve boolean is set to true, it will remove existing reserve
1831 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1833 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1834 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1837 my $biblionumber = $res->{biblionumber};
1839 if ($res->{borrowernumber} == $borrowernumber) {
1840 ModReserveFill($res);
1844 # The item is reserved by someone else.
1845 # Find this item in the reserves
1848 foreach (@$all_reserves) {
1849 $_->{'borrowernumber'} == $borrowernumber or next;
1850 $_->{'biblionumber'} == $biblionumber or next;
1857 # The item is reserved by the current patron
1858 ModReserveFill($borr_res);
1861 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1862 RevertWaitingStatus({ itemnumber => $itemnumber });
1864 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1865 my $hold = Koha::Holds->find( $res->{reserve_id} );
1873 MergeHolds($dbh,$to_biblio, $from_biblio);
1875 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1880 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1881 my $sth = $dbh->prepare(
1882 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1884 $sth->execute($from_biblio);
1885 if ( my $data = $sth->fetchrow_hashref() ) {
1887 # holds exist on old record, if not we don't need to do anything
1888 $sth = $dbh->prepare(
1889 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1890 $sth->execute( $to_biblio, $from_biblio );
1893 # don't reorder those already waiting
1895 $sth = $dbh->prepare(
1896 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1898 my $upd_sth = $dbh->prepare(
1899 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1900 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1902 $sth->execute( $to_biblio, 'W', 'T' );
1904 while ( my $reserve = $sth->fetchrow_hashref() ) {
1906 $priority, $to_biblio,
1907 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1908 $reserve->{'itemnumber'}
1915 =head2 RevertWaitingStatus
1917 RevertWaitingStatus({ itemnumber => $itemnumber });
1919 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1921 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1922 item level hold, even if it was only a bibliolevel hold to
1923 begin with. This is because we can no longer know if a hold
1924 was item-level or bib-level after a hold has been set to
1929 sub RevertWaitingStatus {
1930 my ( $params ) = @_;
1931 my $itemnumber = $params->{'itemnumber'};
1933 return unless ( $itemnumber );
1935 my $dbh = C4::Context->dbh;
1937 ## Get the waiting reserve we want to revert
1939 SELECT * FROM reserves
1940 WHERE itemnumber = ?
1941 AND found IS NOT NULL
1943 my $sth = $dbh->prepare( $query );
1944 $sth->execute( $itemnumber );
1945 my $reserve = $sth->fetchrow_hashref();
1947 ## Increment the priority of all other non-waiting
1948 ## reserves for this bib record
1952 priority = priority + 1
1958 $sth = $dbh->prepare( $query );
1959 $sth->execute( $reserve->{'biblionumber'} );
1961 ## Fix up the currently waiting reserve
1971 $sth = $dbh->prepare( $query );
1972 $sth->execute( $reserve->{'reserve_id'} );
1973 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1980 branchcode => $branchcode,
1981 borrowernumber => $borrowernumber,
1982 biblionumber => $biblionumber,
1983 [ itemnumber => $itemnumber, ]
1984 [ barcode => $barcode, ]
1988 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1990 The letter code will be HOLD_SLIP, and the following tables are
1991 available within the slip:
2004 my $branchcode = $args->{branchcode};
2005 my $borrowernumber = $args->{borrowernumber};
2006 my $biblionumber = $args->{biblionumber};
2007 my $itemnumber = $args->{itemnumber};
2008 my $barcode = $args->{barcode};
2011 my $patron = Koha::Patrons->find($borrowernumber);
2014 if ($itemnumber || $barcode ) {
2015 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2017 $hold = Koha::Holds->search(
2019 biblionumber => $biblionumber,
2020 borrowernumber => $borrowernumber,
2021 itemnumber => $itemnumber
2026 $hold = Koha::Holds->search(
2028 biblionumber => $biblionumber,
2029 borrowernumber => $borrowernumber
2034 return unless $hold;
2035 my $reserve = $hold->unblessed;
2037 return C4::Letters::GetPreparedLetter (
2038 module => 'circulation',
2039 letter_code => 'HOLD_SLIP',
2040 branchcode => $branchcode,
2041 lang => $patron->lang,
2043 'reserves' => $reserve,
2044 'branches' => $reserve->{branchcode},
2045 'borrowers' => $reserve->{borrowernumber},
2046 'biblio' => $reserve->{biblionumber},
2047 'biblioitems' => $reserve->{biblionumber},
2048 'items' => $reserve->{itemnumber},
2053 =head2 GetReservesControlBranch
2055 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2057 Return the branchcode to be used to determine which reserves
2058 policy applies to a transaction.
2060 C<$item> is a hashref for an item. Only 'homebranch' is used.
2062 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2066 sub GetReservesControlBranch {
2067 my ( $item, $borrower ) = @_;
2069 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2072 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2073 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2079 =head2 CalculatePriority
2081 my $p = CalculatePriority($biblionumber, $resdate);
2083 Calculate priority for a new reserve on biblionumber, placing it at
2084 the end of the line of all holds whose start date falls before
2085 the current system time and that are neither on the hold shelf
2088 The reserve date parameter is optional; if it is supplied, the
2089 priority is based on the set of holds whose start date falls before
2090 the parameter value.
2092 After calculation of this priority, it is recommended to call
2093 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2098 sub CalculatePriority {
2099 my ( $biblionumber, $resdate ) = @_;
2102 SELECT COUNT(*) FROM reserves
2103 WHERE biblionumber = ?
2105 AND (found IS NULL OR found = '')
2107 #skip found==W or found==T (waiting or transit holds)
2109 $sql.= ' AND ( reservedate <= ? )';
2112 $sql.= ' AND ( reservedate < NOW() )';
2114 my $dbh = C4::Context->dbh();
2115 my @row = $dbh->selectrow_array(
2118 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2121 return @row ? $row[0]+1 : 1;
2124 =head2 IsItemOnHoldAndFound
2126 my $bool = IsItemFoundHold( $itemnumber );
2128 Returns true if the item is currently on hold
2129 and that hold has a non-null found status ( W, T, etc. )
2133 sub IsItemOnHoldAndFound {
2134 my ($itemnumber) = @_;
2136 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2138 my $found = $rs->count(
2140 itemnumber => $itemnumber,
2141 found => { '!=' => undef }
2148 =head2 GetMaxPatronHoldsForRecord
2150 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2152 For multiple holds on a given record for a given patron, the max
2153 number of record level holds that a patron can be placed is the highest
2154 value of the holds_per_record rule for each item if the record for that
2155 patron. This subroutine finds and returns the highest holds_per_record
2156 rule value for a given patron id and record id.
2160 sub GetMaxPatronHoldsForRecord {
2161 my ( $borrowernumber, $biblionumber ) = @_;
2163 my $patron = Koha::Patrons->find($borrowernumber);
2164 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2166 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2168 my $categorycode = $patron->categorycode;
2170 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2173 foreach my $item (@items) {
2174 my $itemtype = $item->effective_itemtype();
2176 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2178 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2179 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2180 $max = $holds_per_record if $holds_per_record > $max;
2188 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2190 Returns the matching hold related issuingrule fields for a given
2191 patron category, itemtype, and library.
2196 my ( $categorycode, $itemtype, $branchcode ) = @_;
2198 my $dbh = C4::Context->dbh;
2200 my $sth = $dbh->prepare(
2202 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2204 WHERE (categorycode in (?,'*') )
2205 AND (itemtype IN (?,'*'))
2206 AND (branchcode IN (?,'*'))
2207 ORDER BY categorycode DESC,
2213 $sth->execute( $categorycode, $itemtype, $branchcode );
2215 return $sth->fetchrow_hashref();
2220 Koha Development Team <http://koha-community.org/>