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;
37 use C4::Branch qw( GetBranchDetail );
45 use List::MoreUtils qw( firstidx any );
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
52 C4::Reserves - Koha functions for dealing with reservation.
60 This modules provides somes functions to deal with reservations.
62 Reserves are stored in reserves table.
63 The following columns contains important values :
64 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
65 =0 : then the reserve is being dealed
66 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
67 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
68 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
69 F(inished) : the reserve has been completed, and is done
70 - itemnumber : empty : the reserve is still unaffected to an item
71 filled: the reserve is attached to an item
72 The complete workflow is :
73 ==== 1st use case ====
74 patron request a document, 1st available : P >0, F=NULL, I=NULL
75 a library having it run "transfertodo", and clic on the list
76 if there is no transfer to do, the reserve waiting
77 patron can pick it up P =0, F=W, I=filled
78 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
79 The pickup library receive the book, it check in P =0, F=W, I=filled
80 The patron borrow the book P =0, F=F, I=filled
82 ==== 2nd use case ====
83 patron requests a document, a given item,
84 If pickup is holding branch P =0, F=W, I=filled
85 If transfer needed, write in branchtransfer P =0, F=T, I=filled
86 The pickup library receive the book, it checks it in P =0, F=W, I=filled
87 The patron borrow the book P =0, F=F, I=filled
94 # set the version for version checking
95 $VERSION = 3.07.00.049;
102 &GetReservesFromItemnumber
103 &GetReservesFromBiblionumber
104 &GetReservesFromBorrowernumber
105 &GetReservesForBranch
118 &ModReserveMinusPriority
124 &CanReserveBeCanceledFromOpac
126 &CancelExpiredReserves
128 &AutoUnsuspendReserves
130 &IsAvailableForItemLevelRequest
132 &OPACItemHoldsAllowed
135 &ToggleLowestPriority
141 &GetReservesControlBranch
145 @EXPORT_OK = qw( MergeHolds );
150 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
156 $branch, $borrowernumber, $biblionumber,
157 $bibitems, $priority, $resdate, $expdate, $notes,
158 $title, $checkitem, $found
161 if ( Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->count() > 0 ) {
162 carp("AddReserve: borrower $borrowernumber already has a hold for biblionumber $biblionumber");
166 my $dbh = C4::Context->dbh;
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 ( C4::Context->preference('AllowHoldDateInFuture') ) {
175 # Make room in reserves for this before those of a later reserve date
176 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
181 # If the reserv had the waiting status, we had the value of the resdate
182 if ( $found eq 'W' ) {
183 $waitingdate = $resdate;
186 # updates take place here
187 my $hold = Koha::Hold->new(
189 borrowernumber => $borrowernumber,
190 biblionumber => $biblionumber,
191 reservedate => $resdate,
192 branchcode => $branch,
193 priority => $priority,
194 reservenotes => $notes,
195 itemnumber => $checkitem,
197 waitingdate => $waitingdate,
198 expirationdate => $expdate
201 my $reserve_id = $hold->id();
203 # add a reserve fee if needed
204 my $fee = GetReserveFee( $borrowernumber, $biblionumber );
205 ChargeReserveFee( $borrowernumber, $fee, $title );
207 _FixPriority({ biblionumber => $biblionumber});
209 # Send e-mail to librarian if syspref is active
210 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
211 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
212 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
213 if ( my $letter = C4::Letters::GetPreparedLetter (
214 module => 'reserves',
215 letter_code => 'HOLDPLACED',
216 branchcode => $branch,
218 'branches' => $branch_details,
219 'borrowers' => $borrower,
220 'biblio' => $biblionumber,
221 'items' => $checkitem,
225 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
227 C4::Letters::EnqueueLetter(
229 borrowernumber => $borrowernumber,
230 message_transport_type => 'email',
231 from_address => $admin_email_address,
232 to_address => $admin_email_address,
243 $res = GetReserve( $reserve_id );
245 Return the current reserve.
250 my ($reserve_id) = @_;
252 my $dbh = C4::Context->dbh;
253 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
254 my $sth = $dbh->prepare( $query );
255 $sth->execute( $reserve_id );
256 return $sth->fetchrow_hashref();
259 =head2 GetReservesFromBiblionumber
261 my $reserves = GetReservesFromBiblionumber({
262 biblionumber => $biblionumber,
263 [ itemnumber => $itemnumber, ]
267 This function gets the list of reservations for one C<$biblionumber>,
268 returning an arrayref pointing to the reserves for C<$biblionumber>.
270 By default, only reserves whose start date falls before the current
271 time are returned. To return all reserves, including future ones,
272 the C<all_dates> parameter can be included and set to a true value.
274 If the C<itemnumber> parameter is supplied, reserves must be targeted
275 to that item or not targeted to any item at all; otherwise, they
276 are excluded from the list.
280 sub GetReservesFromBiblionumber {
282 my $biblionumber = $params->{biblionumber} or return [];
283 my $itemnumber = $params->{itemnumber};
284 my $all_dates = $params->{all_dates} // 0;
285 my $dbh = C4::Context->dbh;
287 # Find the desired items in the reserves
292 timestamp AS rtimestamp,
305 WHERE biblionumber = ? ";
306 push( @params, $biblionumber );
307 unless ( $all_dates ) {
308 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
311 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
312 push( @params, $itemnumber );
314 $query .= "ORDER BY priority";
315 my $sth = $dbh->prepare($query);
316 $sth->execute( @params );
318 while ( my $data = $sth->fetchrow_hashref ) {
319 push @results, $data;
324 =head2 GetReservesFromItemnumber
326 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
328 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
330 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
334 sub GetReservesFromItemnumber {
335 my ($itemnumber) = @_;
337 my $schema = Koha::Database->new()->schema();
339 my $r = $schema->resultset('Reserve')->search(
341 itemnumber => $itemnumber,
344 reservedate => \'<= CAST( NOW() AS DATE )',
345 waitingdate => { '!=', undef }
349 order_by => 'priority',
357 $r->get_column('borrowernumber'),
358 $r->get_column('branchcode'),
364 =head2 GetReservesFromBorrowernumber
366 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
372 sub GetReservesFromBorrowernumber {
373 my ( $borrowernumber, $status ) = @_;
374 my $dbh = C4::Context->dbh;
377 $sth = $dbh->prepare("
380 WHERE borrowernumber=?
384 $sth->execute($borrowernumber,$status);
386 $sth = $dbh->prepare("
389 WHERE borrowernumber=?
392 $sth->execute($borrowernumber);
394 my $data = $sth->fetchall_arrayref({});
398 =head2 CanBookBeReserved
400 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
401 if ($canReserve eq 'OK') { #We can reserve this Item! }
403 See CanItemBeReserved() for possible return values.
407 sub CanBookBeReserved{
408 my ($borrowernumber, $biblionumber) = @_;
410 my $items = GetItemnumbersForBiblio($biblionumber);
411 #get items linked via host records
412 my @hostitems = get_hostitemnumbers_of($biblionumber);
414 push (@$items,@hostitems);
418 foreach my $item (@$items) {
419 $canReserve = CanItemBeReserved( $borrowernumber, $item );
420 return 'OK' if $canReserve eq 'OK';
425 =head2 CanItemBeReserved
427 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
428 if ($canReserve eq 'OK') { #We can reserve this Item! }
430 @RETURNS OK, if the Item can be reserved.
431 ageRestricted, if the Item is age restricted for this borrower.
432 damaged, if the Item is damaged.
433 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
434 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
435 notReservable, if holds on this item are not allowed
439 sub CanItemBeReserved{
440 my ($borrowernumber, $itemnumber) = @_;
442 my $dbh = C4::Context->dbh;
443 my $ruleitemtype; # itemtype of the matching issuing rule
444 my $allowedreserves = 0;
446 # we retrieve borrowers and items informations #
447 # item->{itype} will come for biblioitems if necessery
448 my $item = GetItem($itemnumber);
449 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
450 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
452 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
453 return 'damaged' if ( $item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems') );
455 #Check for the age restriction
456 my ($ageRestriction, $daysToAgeRestriction) = C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
457 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
459 my $controlbranch = C4::Context->preference('ReservesControlBranch');
461 # we retrieve user rights on this itemtype and branchcode
462 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
464 WHERE (categorycode in (?,'*') )
465 AND (itemtype IN (?,'*'))
466 AND (branchcode IN (?,'*'))
473 my $querycount ="SELECT
476 LEFT JOIN items USING (itemnumber)
477 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
478 LEFT JOIN borrowers USING (borrowernumber)
479 WHERE borrowernumber = ?
484 my $branchfield = "reserves.branchcode";
486 if( $controlbranch eq "ItemHomeLibrary" ){
487 $branchfield = "items.homebranch";
488 $branchcode = $item->{homebranch};
489 }elsif( $controlbranch eq "PatronLibrary" ){
490 $branchfield = "borrowers.branchcode";
491 $branchcode = $borrower->{branchcode};
495 $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
496 if(my $rights = $sth->fetchrow_hashref()){
497 $ruleitemtype = $rights->{itemtype};
498 $allowedreserves = $rights->{reservesallowed};
505 $querycount .= "AND $branchfield = ?";
507 # If using item-level itypes, fall back to the record
508 # level itemtype if the hold has no associated item
510 C4::Context->preference('item-level_itypes')
511 ? " AND COALESCE( itype, itemtype ) = ?"
512 : " AND itemtype = ?"
513 if ( $ruleitemtype ne "*" );
515 my $sthcount = $dbh->prepare($querycount);
517 if($ruleitemtype eq "*"){
518 $sthcount->execute($borrowernumber, $branchcode);
520 $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
523 my $reservecount = "0";
524 if(my $rowcount = $sthcount->fetchrow_hashref()){
525 $reservecount = $rowcount->{count};
527 # we check if it's ok or not
528 if( $reservecount >= $allowedreserves ){
529 return 'tooManyReserves';
532 my $circ_control_branch = C4::Circulation::_GetCircControlBranch($item,
534 my $branchitemrule = C4::Circulation::GetBranchItemRule($circ_control_branch,
537 if ( $branchitemrule->{holdallowed} == 0 ) {
538 return 'notReservable';
541 if ( $branchitemrule->{holdallowed} == 1
542 && $borrower->{branchcode} ne $item->{homebranch} )
544 return 'cannotReserveFromOtherBranches';
547 # If reservecount is ok, we check item branch if IndependentBranches is ON
548 # and canreservefromotherbranches is OFF
549 if ( C4::Context->preference('IndependentBranches')
550 and !C4::Context->preference('canreservefromotherbranches') )
552 my $itembranch = $item->{homebranch};
553 if ($itembranch ne $borrower->{branchcode}) {
554 return 'cannotReserveFromOtherBranches';
561 =head2 CanReserveBeCanceledFromOpac
563 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
565 returns 1 if reserve can be cancelled by user from OPAC.
566 First check if reserve belongs to user, next checks if reserve is not in
567 transfer or waiting status
571 sub CanReserveBeCanceledFromOpac {
572 my ($reserve_id, $borrowernumber) = @_;
574 return unless $reserve_id and $borrowernumber;
575 my $reserve = GetReserve($reserve_id);
577 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
578 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
584 =head2 GetReserveCount
586 $number = &GetReserveCount($borrowernumber);
588 this function returns the number of reservation for a borrower given on input arg.
592 sub GetReserveCount {
593 my ($borrowernumber) = @_;
595 my $dbh = C4::Context->dbh;
598 SELECT COUNT(*) AS counter
600 WHERE borrowernumber = ?
602 my $sth = $dbh->prepare($query);
603 $sth->execute($borrowernumber);
604 my $row = $sth->fetchrow_hashref;
605 return $row->{counter};
608 =head2 GetOtherReserves
610 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
612 Check queued list of this document and check if this document must be transferred
616 sub GetOtherReserves {
617 my ($itemnumber) = @_;
620 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
621 if ($checkreserves) {
622 my $iteminfo = GetItem($itemnumber);
623 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
624 $messages->{'transfert'} = $checkreserves->{'branchcode'};
625 #minus priorities of others reservs
626 ModReserveMinusPriority(
628 $checkreserves->{'reserve_id'},
631 #launch the subroutine dotransfer
632 C4::Items::ModItemTransfer(
634 $iteminfo->{'holdingbranch'},
635 $checkreserves->{'branchcode'}
640 #step 2b : case of a reservation on the same branch, set the waiting status
642 $messages->{'waiting'} = 1;
643 ModReserveMinusPriority(
645 $checkreserves->{'reserve_id'},
647 ModReserveStatus($itemnumber,'W');
650 $nextreservinfo = $checkreserves->{'borrowernumber'};
653 return ( $messages, $nextreservinfo );
656 =head2 ChargeReserveFee
658 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
660 Charge the fee for a reserve (if $fee > 0)
664 sub ChargeReserveFee {
665 my ( $borrowernumber, $fee, $title ) = @_;
666 return if !$fee || $fee==0; # the last test is needed to include 0.00
668 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
670 my $dbh = C4::Context->dbh;
671 my $nextacctno = &getnextacctno( $borrowernumber );
672 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
677 $fee = GetReserveFee( $borrowernumber, $biblionumber );
679 Calculate the fee for a reserve (if applicable).
684 my ( $borrowernumber, $biblionumber ) = @_;
686 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
689 SELECT COUNT(*) FROM items
690 LEFT JOIN issues USING (itemnumber)
691 WHERE items.biblionumber=? AND issues.issue_id IS NULL
694 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
697 my $dbh = C4::Context->dbh;
698 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
699 if( $fee && $fee > 0 ) {
700 # This is a reconstruction of the old code:
701 # Compare number of items with items issued, and optionally check holds
702 # If not all items are issued and there are no holds: charge no fee
703 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
704 my ( $notissued, $reserved );
705 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
708 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
709 ( $biblionumber, $borrowernumber ) );
710 $fee = 0 if $reserved == 0;
716 =head2 GetReservesToBranch
718 @transreserv = GetReservesToBranch( $frombranch );
720 Get reserve list for a given branch
724 sub GetReservesToBranch {
725 my ( $frombranch ) = @_;
726 my $dbh = C4::Context->dbh;
727 my $sth = $dbh->prepare(
728 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
733 $sth->execute( $frombranch );
736 while ( my $data = $sth->fetchrow_hashref ) {
737 $transreserv[$i] = $data;
740 return (@transreserv);
743 =head2 GetReservesForBranch
745 @transreserv = GetReservesForBranch($frombranch);
749 sub GetReservesForBranch {
750 my ($frombranch) = @_;
751 my $dbh = C4::Context->dbh;
754 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
759 $query .= " AND branchcode=? " if ( $frombranch );
760 $query .= "ORDER BY waitingdate" ;
762 my $sth = $dbh->prepare($query);
764 $sth->execute($frombranch);
771 while ( my $data = $sth->fetchrow_hashref ) {
772 $transreserv[$i] = $data;
775 return (@transreserv);
778 =head2 GetReserveStatus
780 $reservestatus = GetReserveStatus($itemnumber);
782 Takes an itemnumber and returns the status of the reserve placed on it.
783 If several reserves exist, the reserve with the lower priority is given.
787 ## FIXME: I don't think this does what it thinks it does.
788 ## It only ever checks the first reserve result, even though
789 ## multiple reserves for that bib can have the itemnumber set
790 ## the sub is only used once in the codebase.
791 sub GetReserveStatus {
792 my ($itemnumber) = @_;
794 my $dbh = C4::Context->dbh;
796 my ($sth, $found, $priority);
798 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
799 $sth->execute($itemnumber);
800 ($found, $priority) = $sth->fetchrow_array;
804 return 'Waiting' if $found eq 'W' and $priority == 0;
805 return 'Finished' if $found eq 'F';
808 return 'Reserved' if $priority > 0;
810 return ''; # empty string here will remove need for checking undef, or less log lines
815 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
816 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
817 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
819 Find a book in the reserves.
821 C<$itemnumber> is the book's item number.
822 C<$lookahead> is the number of days to look in advance for future reserves.
824 As I understand it, C<&CheckReserves> looks for the given item in the
825 reserves. If it is found, that's a match, and C<$status> is set to
828 Otherwise, it finds the most important item in the reserves with the
829 same biblio number as this book (I'm not clear on this) and returns it
830 with C<$status> set to C<Reserved>.
832 C<&CheckReserves> returns a two-element list:
834 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
836 C<$reserve> is the reserve item that matched. It is a
837 reference-to-hash whose keys are mostly the fields of the reserves
838 table in the Koha database.
843 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
844 my $dbh = C4::Context->dbh;
847 if (C4::Context->preference('item-level_itypes')){
849 SELECT items.biblionumber,
850 items.biblioitemnumber,
851 itemtypes.notforloan,
852 items.notforloan AS itemnotforloan,
858 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
859 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
864 SELECT items.biblionumber,
865 items.biblioitemnumber,
866 itemtypes.notforloan,
867 items.notforloan AS itemnotforloan,
873 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
874 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
879 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
880 $sth->execute($item);
883 $sth = $dbh->prepare("$select WHERE barcode = ?");
884 $sth->execute($barcode);
886 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
887 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
889 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
891 return unless $itemnumber; # bail if we got nothing.
893 # if item is not for loan it cannot be reserved either.....
894 # except where items.notforloan < 0 : This indicates the item is holdable.
895 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
897 # Find this item in the reserves
898 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
900 # $priority and $highest are used to find the most important item
901 # in the list returned by &_Findgroupreserve. (The lower $priority,
902 # the more important the item.)
903 # $highest is the most important item we've seen so far.
905 if (scalar @reserves) {
906 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
907 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
908 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
910 my $priority = 10000000;
911 foreach my $res (@reserves) {
912 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
913 return ( "Waiting", $res, \@reserves ); # Found it
917 my $local_hold_match;
919 if ($LocalHoldsPriority) {
920 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
921 $iteminfo = C4::Items::GetItem($itemnumber);
923 my $local_holds_priority_item_branchcode =
924 $iteminfo->{$LocalHoldsPriorityItemControl};
925 my $local_holds_priority_patron_branchcode =
926 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
928 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
929 ? $borrowerinfo->{branchcode}
932 $local_holds_priority_item_branchcode eq
933 $local_holds_priority_patron_branchcode;
936 # See if this item is more important than what we've got so far
937 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
938 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
939 $iteminfo ||= C4::Items::GetItem($itemnumber);
940 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
941 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
942 next if ($branchitemrule->{'holdallowed'} == 0);
943 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
944 $priority = $res->{'priority'};
946 last if $local_hold_match;
952 # If we get this far, then no exact match was found.
953 # We return the most important (i.e. next) reservation.
955 $highest->{'itemnumber'} = $item;
956 return ( "Reserved", $highest, \@reserves );
962 =head2 CancelExpiredReserves
964 CancelExpiredReserves();
966 Cancels all reserves with an expiration date from before today.
970 sub CancelExpiredReserves {
972 # Cancel reserves that have passed their expiration date.
973 my $dbh = C4::Context->dbh;
974 my $sth = $dbh->prepare( "
975 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
976 AND expirationdate IS NOT NULL
981 while ( my $res = $sth->fetchrow_hashref() ) {
982 CancelReserve({ reserve_id => $res->{'reserve_id'} });
985 # Cancel reserves that have been waiting too long
986 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
987 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
988 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
990 my $today = dt_from_string();
992 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
993 $sth = $dbh->prepare( $query );
994 $sth->execute( $max_pickup_delay );
996 while ( my $res = $sth->fetchrow_hashref ) {
998 unless ( $cancel_on_holidays ) {
999 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
1000 my $is_holiday = $calendar->is_holiday( $today );
1002 if ( $is_holiday ) {
1008 CancelReserve({ reserve_id => $res->{'reserve_id'}, charge_cancel_fee => 1 });
1015 =head2 AutoUnsuspendReserves
1017 AutoUnsuspendReserves();
1019 Unsuspends all suspended reserves with a suspend_until date from before today.
1023 sub AutoUnsuspendReserves {
1025 my $dbh = C4::Context->dbh;
1027 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
1028 my $sth = $dbh->prepare( $query );
1033 =head2 CancelReserve
1035 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
1037 Cancels a reserve. If C<charge_cancel_fee> is passed and the C<ExpireReservesMaxPickUpDelayCharge> syspref is set, charge that fee to the patron's account.
1042 my ( $params ) = @_;
1044 my $reserve_id = $params->{'reserve_id'};
1045 # Filter out only the desired keys; this will insert undefined values for elements missing in
1046 # \%params, but GetReserveId filters them out anyway.
1047 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
1049 return unless ( $reserve_id );
1051 my $dbh = C4::Context->dbh;
1053 my $reserve = GetReserve( $reserve_id );
1057 SET cancellationdate = now(),
1059 WHERE reserve_id = ?
1061 my $sth = $dbh->prepare($query);
1062 $sth->execute( $reserve_id );
1065 INSERT INTO old_reserves
1066 SELECT * FROM reserves
1067 WHERE reserve_id = ?
1069 $sth = $dbh->prepare($query);
1070 $sth->execute( $reserve_id );
1073 DELETE FROM reserves
1074 WHERE reserve_id = ?
1076 $sth = $dbh->prepare($query);
1077 $sth->execute( $reserve_id );
1079 # now fix the priority on the others....
1080 _FixPriority({ biblionumber => $reserve->{biblionumber} });
1082 # and, if desired, charge a cancel fee
1083 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
1084 if ( $charge && $params->{'charge_cancel_fee'} ) {
1085 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, '', 'HE', $charge);
1094 ModReserve({ rank => $rank,
1095 reserve_id => $reserve_id,
1096 branchcode => $branchcode
1097 [, itemnumber => $itemnumber ]
1098 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1101 Change a hold request's priority or cancel it.
1103 C<$rank> specifies the effect of the change. If C<$rank>
1104 is 'W' or 'n', nothing happens. This corresponds to leaving a
1105 request alone when changing its priority in the holds queue
1108 If C<$rank> is 'del', the hold request is cancelled.
1110 If C<$rank> is an integer greater than zero, the priority of
1111 the request is set to that value. Since priority != 0 means
1112 that the item is not waiting on the hold shelf, setting the
1113 priority to a non-zero value also sets the request's found
1114 status and waiting date to NULL.
1116 The optional C<$itemnumber> parameter is used only when
1117 C<$rank> is a non-zero integer; if supplied, the itemnumber
1118 of the hold request is set accordingly; if omitted, the itemnumber
1121 B<FIXME:> Note that the forgoing can have the effect of causing
1122 item-level hold requests to turn into title-level requests. This
1123 will be fixed once reserves has separate columns for requested
1124 itemnumber and supplying itemnumber.
1129 my ( $params ) = @_;
1131 my $rank = $params->{'rank'};
1132 my $reserve_id = $params->{'reserve_id'};
1133 my $branchcode = $params->{'branchcode'};
1134 my $itemnumber = $params->{'itemnumber'};
1135 my $suspend_until = $params->{'suspend_until'};
1136 my $borrowernumber = $params->{'borrowernumber'};
1137 my $biblionumber = $params->{'biblionumber'};
1139 return if $rank eq "W";
1140 return if $rank eq "n";
1142 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1143 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1145 my $dbh = C4::Context->dbh;
1146 if ( $rank eq "del" ) {
1147 CancelReserve({ reserve_id => $reserve_id });
1149 elsif ($rank =~ /^\d+/ and $rank > 0) {
1151 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1152 WHERE reserve_id = ?
1154 my $sth = $dbh->prepare($query);
1155 $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
1157 if ( defined( $suspend_until ) ) {
1158 if ( $suspend_until ) {
1159 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until ), dateonly => 1, dateformat => 'iso' }); };
1160 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
1162 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
1166 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1170 =head2 ModReserveFill
1172 &ModReserveFill($reserve);
1174 Fill a reserve. If I understand this correctly, this means that the
1175 reserved book has been found and given to the patron who reserved it.
1177 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1178 whose keys are fields from the reserves table in the Koha database.
1182 sub ModReserveFill {
1184 my $dbh = C4::Context->dbh;
1185 # fill in a reserve record....
1186 my $reserve_id = $res->{'reserve_id'};
1187 my $biblionumber = $res->{'biblionumber'};
1188 my $borrowernumber = $res->{'borrowernumber'};
1189 my $resdate = $res->{'reservedate'};
1191 # get the priority on this record....
1193 my $query = "SELECT priority
1195 WHERE biblionumber = ?
1196 AND borrowernumber = ?
1197 AND reservedate = ?";
1198 my $sth = $dbh->prepare($query);
1199 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1200 ($priority) = $sth->fetchrow_array;
1202 # update the database...
1203 $query = "UPDATE reserves
1206 WHERE biblionumber = ?
1208 AND borrowernumber = ?
1210 $sth = $dbh->prepare($query);
1211 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1213 # move to old_reserves
1214 $query = "INSERT INTO old_reserves
1215 SELECT * FROM reserves
1216 WHERE biblionumber = ?
1218 AND borrowernumber = ?
1220 $sth = $dbh->prepare($query);
1221 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1222 $query = "DELETE FROM reserves
1223 WHERE biblionumber = ?
1225 AND borrowernumber = ?
1227 $sth = $dbh->prepare($query);
1228 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1230 # now fix the priority on the others (if the priority wasn't
1231 # already sorted!)....
1232 unless ( $priority == 0 ) {
1233 _FixPriority({ reserve_id => $reserve_id, biblionumber => $biblionumber });
1237 =head2 ModReserveStatus
1239 &ModReserveStatus($itemnumber, $newstatus);
1241 Update the reserve status for the active (priority=0) reserve.
1243 $itemnumber is the itemnumber the reserve is on
1245 $newstatus is the new status.
1249 sub ModReserveStatus {
1251 #first : check if we have a reservation for this item .
1252 my ($itemnumber, $newstatus) = @_;
1253 my $dbh = C4::Context->dbh;
1255 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1256 my $sth_set = $dbh->prepare($query);
1257 $sth_set->execute( $newstatus, $itemnumber );
1259 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1260 CartToShelf( $itemnumber );
1264 =head2 ModReserveAffect
1266 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1268 This function affect an item and a status for a given reserve
1269 The itemnumber parameter is used to find the biblionumber.
1270 with the biblionumber & the borrowernumber, we can affect the itemnumber
1271 to the correct reserve.
1273 if $transferToDo is not set, then the status is set to "Waiting" as well.
1274 otherwise, a transfer is on the way, and the end of the transfer will
1275 take care of the waiting status
1279 sub ModReserveAffect {
1280 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1281 my $dbh = C4::Context->dbh;
1283 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1284 # attached to $itemnumber
1285 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1286 $sth->execute($itemnumber);
1287 my ($biblionumber) = $sth->fetchrow;
1289 # get request - need to find out if item is already
1290 # waiting in order to not send duplicate hold filled notifications
1291 my $reserve_id = GetReserveId({
1292 borrowernumber => $borrowernumber,
1293 biblionumber => $biblionumber,
1295 return unless defined $reserve_id;
1296 my $request = GetReserveInfo($reserve_id);
1297 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1299 # If we affect a reserve that has to be transferred, don't set to Waiting
1301 if ($transferToDo) {
1307 WHERE borrowernumber = ?
1308 AND biblionumber = ?
1312 # affect the reserve to Waiting as well.
1317 waitingdate = NOW(),
1319 WHERE borrowernumber = ?
1320 AND biblionumber = ?
1323 $sth = $dbh->prepare($query);
1324 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1325 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1326 _FixPriority( { biblionumber => $biblionumber } );
1327 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1328 CartToShelf( $itemnumber );
1334 =head2 ModReserveCancelAll
1336 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1338 function to cancel reserv,check other reserves, and transfer document if it's necessary
1342 sub ModReserveCancelAll {
1345 my ( $itemnumber, $borrowernumber ) = @_;
1347 #step 1 : cancel the reservation
1348 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1350 #step 2 launch the subroutine of the others reserves
1351 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1353 return ( $messages, $nextreservinfo );
1356 =head2 ModReserveMinusPriority
1358 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1360 Reduce the values of queued list
1364 sub ModReserveMinusPriority {
1365 my ( $itemnumber, $reserve_id ) = @_;
1367 #first step update the value of the first person on reserv
1368 my $dbh = C4::Context->dbh;
1371 SET priority = 0 , itemnumber = ?
1372 WHERE reserve_id = ?
1374 my $sth_upd = $dbh->prepare($query);
1375 $sth_upd->execute( $itemnumber, $reserve_id );
1376 # second step update all others reserves
1377 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1380 =head2 GetReserveInfo
1382 &GetReserveInfo($reserve_id);
1384 Get item and borrower details for a current hold.
1385 Current implementation this query should have a single result.
1389 sub GetReserveInfo {
1390 my ( $reserve_id ) = @_;
1391 my $dbh = C4::Context->dbh;
1396 reserves.borrowernumber,
1397 reserves.biblionumber,
1398 reserves.branchcode,
1399 reserves.waitingdate,
1415 items.holdingbranch,
1416 items.itemcallnumber,
1422 LEFT JOIN items USING(itemnumber)
1423 LEFT JOIN borrowers USING(borrowernumber)
1424 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1425 WHERE reserves.reserve_id = ?";
1426 my $sth = $dbh->prepare($strsth);
1427 $sth->execute($reserve_id);
1429 my $data = $sth->fetchrow_hashref;
1433 =head2 IsAvailableForItemLevelRequest
1435 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1437 Checks whether a given item record is available for an
1438 item-level hold request. An item is available if
1440 * it is not lost AND
1441 * it is not damaged AND
1442 * it is not withdrawn AND
1443 * does not have a not for loan value > 0
1445 Need to check the issuingrules onshelfholds column,
1446 if this is set items on the shelf can be placed on hold
1448 Note that IsAvailableForItemLevelRequest() does not
1449 check if the staff operator is authorized to place
1450 a request on the item - in particular,
1451 this routine does not check IndependentBranches
1452 and canreservefromotherbranches.
1456 sub IsAvailableForItemLevelRequest {
1458 my $borrower = shift;
1460 my $dbh = C4::Context->dbh;
1461 # must check the notforloan setting of the itemtype
1462 # FIXME - a lot of places in the code do this
1463 # or something similar - need to be
1465 my $itype = _get_itype($item);
1466 my $notforloan_per_itemtype
1467 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1471 $notforloan_per_itemtype ||
1472 $item->{itemlost} ||
1473 $item->{notforloan} > 0 ||
1474 $item->{withdrawn} ||
1475 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1478 return 1 if _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1480 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1483 =head2 OnShelfHoldsAllowed
1485 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1487 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1488 holds are allowed, returns true if so.
1492 sub OnShelfHoldsAllowed {
1493 my ($item, $borrower) = @_;
1495 my $itype = _get_itype($item);
1496 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1503 if (C4::Context->preference('item-level_itypes')) {
1504 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1505 # When GetItem is fixed, we can remove this
1506 $itype = $item->{itype};
1509 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1510 # So if we already have a biblioitems join when calling this function,
1511 # we don't need to access the database again
1512 $itype = $item->{itemtype};
1515 my $dbh = C4::Context->dbh;
1516 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1517 my $sth = $dbh->prepare($query);
1518 $sth->execute($item->{biblioitemnumber});
1519 if (my $data = $sth->fetchrow_hashref()){
1520 $itype = $data->{itemtype};
1526 sub _OnShelfHoldsAllowed {
1527 my ($itype,$borrowercategory,$branchcode) = @_;
1529 my $rule = C4::Circulation::GetIssuingRule($borrowercategory, $itype, $branchcode);
1530 return $rule->{onshelfholds};
1533 =head2 AlterPriority
1535 AlterPriority( $where, $reserve_id );
1537 This function changes a reserve's priority up, down, to the top, or to the bottom.
1538 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1543 my ( $where, $reserve_id ) = @_;
1545 my $dbh = C4::Context->dbh;
1547 my $reserve = GetReserve( $reserve_id );
1549 if ( $reserve->{cancellationdate} ) {
1550 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1554 if ( $where eq 'up' || $where eq 'down' ) {
1556 my $priority = $reserve->{'priority'};
1557 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1558 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1560 } elsif ( $where eq 'top' ) {
1562 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1564 } elsif ( $where eq 'bottom' ) {
1566 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1571 =head2 ToggleLowestPriority
1573 ToggleLowestPriority( $borrowernumber, $biblionumber );
1575 This function sets the lowestPriority field to true if is false, and false if it is true.
1579 sub ToggleLowestPriority {
1580 my ( $reserve_id ) = @_;
1582 my $dbh = C4::Context->dbh;
1584 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1585 $sth->execute( $reserve_id );
1587 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1590 =head2 ToggleSuspend
1592 ToggleSuspend( $reserve_id );
1594 This function sets the suspend field to true if is false, and false if it is true.
1595 If the reserve is currently suspended with a suspend_until date, that date will
1596 be cleared when it is unsuspended.
1601 my ( $reserve_id, $suspend_until ) = @_;
1603 $suspend_until = output_pref(
1605 dt => dt_from_string($suspend_until),
1606 dateformat => 'iso',
1609 ) if ($suspend_until);
1611 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1613 my $dbh = C4::Context->dbh;
1615 my $sth = $dbh->prepare(
1616 "UPDATE reserves SET suspend = NOT suspend,
1617 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1618 WHERE reserve_id = ?
1622 push( @params, $suspend_until ) if ( $suspend_until );
1623 push( @params, $reserve_id );
1625 $sth->execute( @params );
1631 borrowernumber => $borrowernumber,
1632 [ biblionumber => $biblionumber, ]
1633 [ suspend_until => $suspend_until, ]
1634 [ suspend => $suspend ]
1637 This function accepts a set of hash keys as its parameters.
1638 It requires either borrowernumber or biblionumber, or both.
1640 suspend_until is wholly optional.
1647 my $borrowernumber = $params{'borrowernumber'} || undef;
1648 my $biblionumber = $params{'biblionumber'} || undef;
1649 my $suspend_until = $params{'suspend_until'} || undef;
1650 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1652 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until), dateonly => 1, dateformat => 'iso' } ); }
1653 if ( defined( $suspend_until ) );
1655 return unless ( $borrowernumber || $biblionumber );
1657 my ( $query, $sth, $dbh, @query_params );
1659 $query = "UPDATE reserves SET suspend = ? ";
1660 push( @query_params, $suspend );
1662 $query .= ", suspend_until = NULL ";
1663 } elsif ( $suspend_until ) {
1664 $query .= ", suspend_until = ? ";
1665 push( @query_params, $suspend_until );
1667 $query .= " WHERE ";
1668 if ( $borrowernumber ) {
1669 $query .= " borrowernumber = ? ";
1670 push( @query_params, $borrowernumber );
1672 $query .= " AND " if ( $borrowernumber && $biblionumber );
1673 if ( $biblionumber ) {
1674 $query .= " biblionumber = ? ";
1675 push( @query_params, $biblionumber );
1677 $query .= " AND found IS NULL ";
1679 $dbh = C4::Context->dbh;
1680 $sth = $dbh->prepare( $query );
1681 $sth->execute( @query_params );
1688 reserve_id => $reserve_id,
1690 [ignoreSetLowestRank => $ignoreSetLowestRank]
1695 _FixPriority({ biblionumber => $biblionumber});
1697 This routine adjusts the priority of a hold request and holds
1700 In the first form, where a reserve_id is passed, the priority of the
1701 hold is set to supplied rank, and other holds for that bib are adjusted
1702 accordingly. If the rank is "del", the hold is cancelled. If no rank
1703 is supplied, all of the holds on that bib have their priority adjusted
1704 as if the second form had been used.
1706 In the second form, where a biblionumber is passed, the holds on that
1707 bib (that are not captured) are sorted in order of increasing priority,
1708 then have reserves.priority set so that the first non-captured hold
1709 has its priority set to 1, the second non-captured hold has its priority
1710 set to 2, and so forth.
1712 In both cases, holds that have the lowestPriority flag on are have their
1713 priority adjusted to ensure that they remain at the end of the line.
1715 Note that the ignoreSetLowestRank parameter is meant to be used only
1716 when _FixPriority calls itself.
1721 my ( $params ) = @_;
1722 my $reserve_id = $params->{reserve_id};
1723 my $rank = $params->{rank} // '';
1724 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1725 my $biblionumber = $params->{biblionumber};
1727 my $dbh = C4::Context->dbh;
1729 unless ( $biblionumber ) {
1730 my $res = GetReserve( $reserve_id );
1731 $biblionumber = $res->{biblionumber};
1734 if ( $rank eq "del" ) {
1735 CancelReserve({ reserve_id => $reserve_id });
1737 elsif ( $rank eq "W" || $rank eq "0" ) {
1739 # make sure priority for waiting or in-transit items is 0
1743 WHERE reserve_id = ?
1744 AND found IN ('W', 'T')
1746 my $sth = $dbh->prepare($query);
1747 $sth->execute( $reserve_id );
1753 SELECT reserve_id, borrowernumber, reservedate
1755 WHERE biblionumber = ?
1756 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1757 ORDER BY priority ASC
1759 my $sth = $dbh->prepare($query);
1760 $sth->execute( $biblionumber );
1761 while ( my $line = $sth->fetchrow_hashref ) {
1762 push( @priority, $line );
1765 # To find the matching index
1767 my $key = -1; # to allow for 0 to be a valid result
1768 for ( $i = 0 ; $i < @priority ; $i++ ) {
1769 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1770 $key = $i; # save the index
1775 # if index exists in array then move it to new position
1776 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1777 my $new_rank = $rank -
1778 1; # $new_rank is what you want the new index to be in the array
1779 my $moving_item = splice( @priority, $key, 1 );
1780 splice( @priority, $new_rank, 0, $moving_item );
1783 # now fix the priority on those that are left....
1787 WHERE reserve_id = ?
1789 $sth = $dbh->prepare($query);
1790 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1793 $priority[$j]->{'reserve_id'}
1797 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1800 unless ( $ignoreSetLowestRank ) {
1801 while ( my $res = $sth->fetchrow_hashref() ) {
1803 reserve_id => $res->{'reserve_id'},
1805 ignoreSetLowestRank => 1
1811 =head2 _Findgroupreserve
1813 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1815 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1816 first match found. If neither, then we look for non-holds-queue based holds.
1817 Lookahead is the number of days to look in advance.
1819 C<&_Findgroupreserve> returns :
1820 C<@results> is an array of references-to-hash whose keys are mostly
1821 fields from the reserves table of the Koha database, plus
1822 C<biblioitemnumber>.
1826 sub _Findgroupreserve {
1827 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1828 my $dbh = C4::Context->dbh;
1830 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1831 # check for exact targeted match
1832 my $item_level_target_query = qq{
1833 SELECT reserves.biblionumber AS biblionumber,
1834 reserves.borrowernumber AS borrowernumber,
1835 reserves.reservedate AS reservedate,
1836 reserves.branchcode AS branchcode,
1837 reserves.cancellationdate AS cancellationdate,
1838 reserves.found AS found,
1839 reserves.reservenotes AS reservenotes,
1840 reserves.priority AS priority,
1841 reserves.timestamp AS timestamp,
1842 biblioitems.biblioitemnumber AS biblioitemnumber,
1843 reserves.itemnumber AS itemnumber,
1844 reserves.reserve_id AS reserve_id
1846 JOIN biblioitems USING (biblionumber)
1847 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1850 AND item_level_request = 1
1852 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1856 my $sth = $dbh->prepare($item_level_target_query);
1857 $sth->execute($itemnumber, $lookahead||0);
1859 if ( my $data = $sth->fetchrow_hashref ) {
1860 push( @results, $data )
1861 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1863 return @results if @results;
1865 # check for title-level targeted match
1866 my $title_level_target_query = qq{
1867 SELECT reserves.biblionumber AS biblionumber,
1868 reserves.borrowernumber AS borrowernumber,
1869 reserves.reservedate AS reservedate,
1870 reserves.branchcode AS branchcode,
1871 reserves.cancellationdate AS cancellationdate,
1872 reserves.found AS found,
1873 reserves.reservenotes AS reservenotes,
1874 reserves.priority AS priority,
1875 reserves.timestamp AS timestamp,
1876 biblioitems.biblioitemnumber AS biblioitemnumber,
1877 reserves.itemnumber AS itemnumber,
1878 reserves.reserve_id AS reserve_id
1880 JOIN biblioitems USING (biblionumber)
1881 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1884 AND item_level_request = 0
1885 AND hold_fill_targets.itemnumber = ?
1886 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1890 $sth = $dbh->prepare($title_level_target_query);
1891 $sth->execute($itemnumber, $lookahead||0);
1893 if ( my $data = $sth->fetchrow_hashref ) {
1894 push( @results, $data )
1895 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1897 return @results if @results;
1900 SELECT reserves.biblionumber AS biblionumber,
1901 reserves.borrowernumber AS borrowernumber,
1902 reserves.reservedate AS reservedate,
1903 reserves.waitingdate AS waitingdate,
1904 reserves.branchcode AS branchcode,
1905 reserves.cancellationdate AS cancellationdate,
1906 reserves.found AS found,
1907 reserves.reservenotes AS reservenotes,
1908 reserves.priority AS priority,
1909 reserves.timestamp AS timestamp,
1910 reserves.itemnumber AS itemnumber,
1911 reserves.reserve_id AS reserve_id
1913 WHERE reserves.biblionumber = ?
1914 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1915 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1919 $sth = $dbh->prepare($query);
1920 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1922 while ( my $data = $sth->fetchrow_hashref ) {
1923 push( @results, $data )
1924 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1929 =head2 _koha_notify_reserve
1931 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1933 Sends a notification to the patron that their hold has been filled (through
1934 ModReserveAffect, _not_ ModReserveFill)
1938 sub _koha_notify_reserve {
1939 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1941 my $dbh = C4::Context->dbh;
1942 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1944 # Try to get the borrower's email address
1945 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1947 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1948 borrowernumber => $borrowernumber,
1949 message_name => 'Hold_Filled'
1952 my $sth = $dbh->prepare("
1955 WHERE borrowernumber = ?
1956 AND biblionumber = ?
1958 $sth->execute( $borrowernumber, $biblionumber );
1959 my $reserve = $sth->fetchrow_hashref;
1960 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1962 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1964 my %letter_params = (
1965 module => 'reserves',
1966 branchcode => $reserve->{branchcode},
1968 'branches' => $branch_details,
1969 'borrowers' => $borrower,
1970 'biblio' => $biblionumber,
1971 'reserves' => $reserve,
1972 'items', $reserve->{'itemnumber'},
1974 substitute => { today => output_pref( { dt => dt_from_string, dateonly => 1 } ) },
1977 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.
1978 my $send_notification = sub {
1979 my ( $mtt, $letter_code ) = (@_);
1980 return unless defined $letter_code;
1981 $letter_params{letter_code} = $letter_code;
1982 $letter_params{message_transport_type} = $mtt;
1983 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1985 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1989 C4::Letters::EnqueueLetter( {
1991 borrowernumber => $borrowernumber,
1992 from_address => $admin_email_address,
1993 message_transport_type => $mtt,
1997 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1999 ( $mtt eq 'email' and not $to_address ) # No email address
2000 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
2001 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
2004 &$send_notification($mtt, $letter_code);
2005 $notification_sent++;
2007 #Making sure that a print notification is sent if no other transport types can be utilized.
2008 if (! $notification_sent) {
2009 &$send_notification('print', 'HOLD');
2014 =head2 _ShiftPriorityByDateAndPriority
2016 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
2018 This increments the priority of all reserves after the one
2019 with either the lowest date after C<$reservedate>
2020 or the lowest priority after C<$priority>.
2022 It effectively makes room for a new reserve to be inserted with a certain
2023 priority, which is returned.
2025 This is most useful when the reservedate can be set by the user. It allows
2026 the new reserve to be placed before other reserves that have a later
2027 reservedate. Since priority also is set by the form in reserves/request.pl
2028 the sub accounts for that too.
2032 sub _ShiftPriorityByDateAndPriority {
2033 my ( $biblio, $resdate, $new_priority ) = @_;
2035 my $dbh = C4::Context->dbh;
2036 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2037 my $sth = $dbh->prepare( $query );
2038 $sth->execute( $biblio, $resdate, $new_priority );
2039 my $min_priority = $sth->fetchrow;
2040 # if no such matches are found, $new_priority remains as original value
2041 $new_priority = $min_priority if ( $min_priority );
2043 # Shift the priority up by one; works in conjunction with the next SQL statement
2044 $query = "UPDATE reserves
2045 SET priority = priority+1
2046 WHERE biblionumber = ?
2047 AND borrowernumber = ?
2050 my $sth_update = $dbh->prepare( $query );
2052 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2053 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2054 $sth = $dbh->prepare( $query );
2055 $sth->execute( $new_priority, $biblio );
2056 while ( my $row = $sth->fetchrow_hashref ) {
2057 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2060 return $new_priority; # so the caller knows what priority they wind up receiving
2063 =head2 OPACItemHoldsAllowed
2065 OPACItemHoldsAllowed($item_record,$borrower_record);
2067 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
2068 if specific item holds are allowed, returns true if so.
2072 sub OPACItemHoldsAllowed {
2073 my ($item,$borrower) = @_;
2075 my $branchcode = $item->{homebranch} or die "No homebranch";
2077 my $dbh = C4::Context->dbh;
2078 if (C4::Context->preference('item-level_itypes')) {
2079 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
2080 # When GetItem is fixed, we can remove this
2081 $itype = $item->{itype};
2084 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
2085 my $sth = $dbh->prepare($query);
2086 $sth->execute($item->{biblioitemnumber});
2087 if (my $data = $sth->fetchrow_hashref()){
2088 $itype = $data->{itemtype};
2092 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
2093 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
2095 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2097 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
2099 issuingrules.categorycode desc,
2100 issuingrules.itemtype desc,
2101 issuingrules.branchcode desc
2103 my $sth = $dbh->prepare($query);
2104 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2105 my $data = $sth->fetchrow_hashref;
2106 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2107 return '' if $opacitemholds eq 'N';
2108 return $opacitemholds;
2113 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2115 Use when checking out an item to handle reserves
2116 If $cancelreserve boolean is set to true, it will remove existing reserve
2121 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2123 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2124 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2127 my $biblionumber = $res->{biblionumber};
2128 my $biblioitemnumber = $res->{biblioitemnumber};
2130 if ($res->{borrowernumber} == $borrowernumber) {
2131 ModReserveFill($res);
2135 # The item is reserved by someone else.
2136 # Find this item in the reserves
2139 foreach (@$all_reserves) {
2140 $_->{'borrowernumber'} == $borrowernumber or next;
2141 $_->{'biblionumber'} == $biblionumber or next;
2148 # The item is reserved by the current patron
2149 ModReserveFill($borr_res);
2152 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2153 RevertWaitingStatus({ itemnumber => $itemnumber });
2155 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2156 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2163 MergeHolds($dbh,$to_biblio, $from_biblio);
2165 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2170 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2171 my $sth = $dbh->prepare(
2172 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2174 $sth->execute($from_biblio);
2175 if ( my $data = $sth->fetchrow_hashref() ) {
2177 # holds exist on old record, if not we don't need to do anything
2178 $sth = $dbh->prepare(
2179 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2180 $sth->execute( $to_biblio, $from_biblio );
2183 # don't reorder those already waiting
2185 $sth = $dbh->prepare(
2186 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2188 my $upd_sth = $dbh->prepare(
2189 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2190 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2192 $sth->execute( $to_biblio, 'W', 'T' );
2194 while ( my $reserve = $sth->fetchrow_hashref() ) {
2196 $priority, $to_biblio,
2197 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2198 $reserve->{'itemnumber'}
2205 =head2 RevertWaitingStatus
2207 RevertWaitingStatus({ itemnumber => $itemnumber });
2209 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2211 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2212 item level hold, even if it was only a bibliolevel hold to
2213 begin with. This is because we can no longer know if a hold
2214 was item-level or bib-level after a hold has been set to
2219 sub RevertWaitingStatus {
2220 my ( $params ) = @_;
2221 my $itemnumber = $params->{'itemnumber'};
2223 return unless ( $itemnumber );
2225 my $dbh = C4::Context->dbh;
2227 ## Get the waiting reserve we want to revert
2229 SELECT * FROM reserves
2230 WHERE itemnumber = ?
2231 AND found IS NOT NULL
2233 my $sth = $dbh->prepare( $query );
2234 $sth->execute( $itemnumber );
2235 my $reserve = $sth->fetchrow_hashref();
2237 ## Increment the priority of all other non-waiting
2238 ## reserves for this bib record
2242 priority = priority + 1
2248 $sth = $dbh->prepare( $query );
2249 $sth->execute( $reserve->{'biblionumber'} );
2251 ## Fix up the currently waiting reserve
2261 $sth = $dbh->prepare( $query );
2262 $sth->execute( $reserve->{'reserve_id'} );
2263 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2268 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2270 Returnes the first reserve id that matches the given criteria
2275 my ( $params ) = @_;
2277 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2279 my $dbh = C4::Context->dbh();
2281 my $sql = "SELECT reserve_id FROM reserves WHERE ";
2285 foreach my $key ( keys %$params ) {
2286 if ( defined( $params->{$key} ) ) {
2287 push( @limits, "$key = ?" );
2288 push( @params, $params->{$key} );
2292 $sql .= join( " AND ", @limits );
2294 my $sth = $dbh->prepare( $sql );
2295 $sth->execute( @params );
2296 my $row = $sth->fetchrow_hashref();
2298 return $row->{'reserve_id'};
2303 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2305 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2310 my ($branch, $borrowernumber, $biblionumber) = @_;
2312 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2314 my $reserve_id = GetReserveId({
2315 biblionumber => $biblionumber,
2316 borrowernumber => $borrowernumber
2318 my $reserve = GetReserveInfo($reserve_id) or return;
2320 return C4::Letters::GetPreparedLetter (
2321 module => 'circulation',
2322 letter_code => 'RESERVESLIP',
2323 branchcode => $branch,
2325 'reserves' => $reserve,
2326 'branches' => $reserve->{branchcode},
2327 'borrowers' => $reserve->{borrowernumber},
2328 'biblio' => $reserve->{biblionumber},
2329 'items' => $reserve->{itemnumber},
2334 =head2 GetReservesControlBranch
2336 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2338 Return the branchcode to be used to determine which reserves
2339 policy applies to a transaction.
2341 C<$item> is a hashref for an item. Only 'homebranch' is used.
2343 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2347 sub GetReservesControlBranch {
2348 my ( $item, $borrower ) = @_;
2350 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2353 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2354 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2360 =head2 CalculatePriority
2362 my $p = CalculatePriority($biblionumber, $resdate);
2364 Calculate priority for a new reserve on biblionumber, placing it at
2365 the end of the line of all holds whose start date falls before
2366 the current system time and that are neither on the hold shelf
2369 The reserve date parameter is optional; if it is supplied, the
2370 priority is based on the set of holds whose start date falls before
2371 the parameter value.
2373 After calculation of this priority, it is recommended to call
2374 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2379 sub CalculatePriority {
2380 my ( $biblionumber, $resdate ) = @_;
2383 SELECT COUNT(*) FROM reserves
2384 WHERE biblionumber = ?
2386 AND (found IS NULL OR found = '')
2388 #skip found==W or found==T (waiting or transit holds)
2390 $sql.= ' AND ( reservedate <= ? )';
2393 $sql.= ' AND ( reservedate < NOW() )';
2395 my $dbh = C4::Context->dbh();
2396 my @row = $dbh->selectrow_array(
2399 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2402 return @row ? $row[0]+1 : 1;
2405 =head2 IsItemOnHoldAndFound
2407 my $bool = IsItemFoundHold( $itemnumber );
2409 Returns true if the item is currently on hold
2410 and that hold has a non-null found status ( W, T, etc. )
2414 sub IsItemOnHoldAndFound {
2415 my ($itemnumber) = @_;
2417 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2419 my $found = $rs->count(
2421 itemnumber => $itemnumber,
2422 found => { '!=' => undef }
2431 Koha Development Team <http://koha-community.org/>