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 = eval { output_pref( { dt => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' }); }
170 $resdate = eval { output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' }); }
174 $expdate = eval { output_pref( { dt => dt_from_string( $expdate), dateonly => 1, dateformat => 'iso' } ); };
176 undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
179 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
181 # Make room in reserves for this before those of a later reserve date
182 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
187 # If the reserv had the waiting status, we had the value of the resdate
188 if ( $found eq 'W' ) {
189 $waitingdate = $resdate;
192 # updates take place here
193 my $hold = Koha::Hold->new(
195 borrowernumber => $borrowernumber,
196 biblionumber => $biblionumber,
197 reservedate => $resdate,
198 branchcode => $branch,
199 priority => $priority,
200 reservenotes => $notes,
201 itemnumber => $checkitem,
203 waitingdate => $waitingdate,
204 expirationdate => $expdate
207 my $reserve_id = $hold->id();
209 # add a reserve fee if needed
210 my $fee = GetReserveFee( $borrowernumber, $biblionumber );
211 ChargeReserveFee( $borrowernumber, $fee, $title );
213 _FixPriority({ biblionumber => $biblionumber});
215 # Send e-mail to librarian if syspref is active
216 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
217 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
218 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
219 if ( my $letter = C4::Letters::GetPreparedLetter (
220 module => 'reserves',
221 letter_code => 'HOLDPLACED',
222 branchcode => $branch,
224 'branches' => $branch_details,
225 'borrowers' => $borrower,
226 'biblio' => $biblionumber,
227 'items' => $checkitem,
231 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
233 C4::Letters::EnqueueLetter(
235 borrowernumber => $borrowernumber,
236 message_transport_type => 'email',
237 from_address => $admin_email_address,
238 to_address => $admin_email_address,
249 $res = GetReserve( $reserve_id );
251 Return the current reserve.
256 my ($reserve_id) = @_;
258 my $dbh = C4::Context->dbh;
259 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
260 my $sth = $dbh->prepare( $query );
261 $sth->execute( $reserve_id );
262 return $sth->fetchrow_hashref();
265 =head2 GetReservesFromBiblionumber
267 my $reserves = GetReservesFromBiblionumber({
268 biblionumber => $biblionumber,
269 [ itemnumber => $itemnumber, ]
273 This function gets the list of reservations for one C<$biblionumber>,
274 returning an arrayref pointing to the reserves for C<$biblionumber>.
276 By default, only reserves whose start date falls before the current
277 time are returned. To return all reserves, including future ones,
278 the C<all_dates> parameter can be included and set to a true value.
280 If the C<itemnumber> parameter is supplied, reserves must be targeted
281 to that item or not targeted to any item at all; otherwise, they
282 are excluded from the list.
286 sub GetReservesFromBiblionumber {
288 my $biblionumber = $params->{biblionumber} or return [];
289 my $itemnumber = $params->{itemnumber};
290 my $all_dates = $params->{all_dates} // 0;
291 my $dbh = C4::Context->dbh;
293 # Find the desired items in the reserves
298 timestamp AS rtimestamp,
311 WHERE biblionumber = ? ";
312 push( @params, $biblionumber );
313 unless ( $all_dates ) {
314 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
317 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
318 push( @params, $itemnumber );
320 $query .= "ORDER BY priority";
321 my $sth = $dbh->prepare($query);
322 $sth->execute( @params );
324 while ( my $data = $sth->fetchrow_hashref ) {
325 push @results, $data;
330 =head2 GetReservesFromItemnumber
332 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
334 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
336 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
340 sub GetReservesFromItemnumber {
341 my ($itemnumber) = @_;
343 my $schema = Koha::Database->new()->schema();
345 my $r = $schema->resultset('Reserve')->search(
347 itemnumber => $itemnumber,
350 reservedate => \'<= CAST( NOW() AS DATE )',
351 waitingdate => { '!=', undef }
355 order_by => 'priority',
363 $r->get_column('borrowernumber'),
364 $r->get_column('branchcode'),
370 =head2 GetReservesFromBorrowernumber
372 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
378 sub GetReservesFromBorrowernumber {
379 my ( $borrowernumber, $status ) = @_;
380 my $dbh = C4::Context->dbh;
383 $sth = $dbh->prepare("
386 WHERE borrowernumber=?
390 $sth->execute($borrowernumber,$status);
392 $sth = $dbh->prepare("
395 WHERE borrowernumber=?
398 $sth->execute($borrowernumber);
400 my $data = $sth->fetchall_arrayref({});
404 =head2 CanBookBeReserved
406 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
407 if ($canReserve eq 'OK') { #We can reserve this Item! }
409 See CanItemBeReserved() for possible return values.
413 sub CanBookBeReserved{
414 my ($borrowernumber, $biblionumber) = @_;
416 my $items = GetItemnumbersForBiblio($biblionumber);
417 #get items linked via host records
418 my @hostitems = get_hostitemnumbers_of($biblionumber);
420 push (@$items,@hostitems);
424 foreach my $item (@$items) {
425 $canReserve = CanItemBeReserved( $borrowernumber, $item );
426 return 'OK' if $canReserve eq 'OK';
431 =head2 CanItemBeReserved
433 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
434 if ($canReserve eq 'OK') { #We can reserve this Item! }
436 @RETURNS OK, if the Item can be reserved.
437 ageRestricted, if the Item is age restricted for this borrower.
438 damaged, if the Item is damaged.
439 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
440 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
441 notReservable, if holds on this item are not allowed
445 sub CanItemBeReserved{
446 my ($borrowernumber, $itemnumber) = @_;
448 my $dbh = C4::Context->dbh;
449 my $ruleitemtype; # itemtype of the matching issuing rule
450 my $allowedreserves = 0;
452 # we retrieve borrowers and items informations #
453 # item->{itype} will come for biblioitems if necessery
454 my $item = GetItem($itemnumber);
455 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
456 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
458 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
459 return 'damaged' if ( $item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems') );
461 #Check for the age restriction
462 my ($ageRestriction, $daysToAgeRestriction) = C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
463 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
465 my $controlbranch = C4::Context->preference('ReservesControlBranch');
467 # we retrieve user rights on this itemtype and branchcode
468 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
470 WHERE (categorycode in (?,'*') )
471 AND (itemtype IN (?,'*'))
472 AND (branchcode IN (?,'*'))
479 my $querycount ="SELECT
482 LEFT JOIN items USING (itemnumber)
483 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
484 LEFT JOIN borrowers USING (borrowernumber)
485 WHERE borrowernumber = ?
490 my $branchfield = "reserves.branchcode";
492 if( $controlbranch eq "ItemHomeLibrary" ){
493 $branchfield = "items.homebranch";
494 $branchcode = $item->{homebranch};
495 }elsif( $controlbranch eq "PatronLibrary" ){
496 $branchfield = "borrowers.branchcode";
497 $branchcode = $borrower->{branchcode};
501 $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
502 if(my $rights = $sth->fetchrow_hashref()){
503 $ruleitemtype = $rights->{itemtype};
504 $allowedreserves = $rights->{reservesallowed};
511 $querycount .= "AND $branchfield = ?";
513 # If using item-level itypes, fall back to the record
514 # level itemtype if the hold has no associated item
516 C4::Context->preference('item-level_itypes')
517 ? " AND COALESCE( itype, itemtype ) = ?"
518 : " AND itemtype = ?"
519 if ( $ruleitemtype ne "*" );
521 my $sthcount = $dbh->prepare($querycount);
523 if($ruleitemtype eq "*"){
524 $sthcount->execute($borrowernumber, $branchcode);
526 $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
529 my $reservecount = "0";
530 if(my $rowcount = $sthcount->fetchrow_hashref()){
531 $reservecount = $rowcount->{count};
533 # we check if it's ok or not
534 if( $reservecount >= $allowedreserves ){
535 return 'tooManyReserves';
538 my $circ_control_branch = C4::Circulation::_GetCircControlBranch($item,
540 my $branchitemrule = C4::Circulation::GetBranchItemRule($circ_control_branch,
543 if ( $branchitemrule->{holdallowed} == 0 ) {
544 return 'notReservable';
547 if ( $branchitemrule->{holdallowed} == 1
548 && $borrower->{branchcode} ne $item->{homebranch} )
550 return 'cannotReserveFromOtherBranches';
553 # If reservecount is ok, we check item branch if IndependentBranches is ON
554 # and canreservefromotherbranches is OFF
555 if ( C4::Context->preference('IndependentBranches')
556 and !C4::Context->preference('canreservefromotherbranches') )
558 my $itembranch = $item->{homebranch};
559 if ($itembranch ne $borrower->{branchcode}) {
560 return 'cannotReserveFromOtherBranches';
567 =head2 CanReserveBeCanceledFromOpac
569 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
571 returns 1 if reserve can be cancelled by user from OPAC.
572 First check if reserve belongs to user, next checks if reserve is not in
573 transfer or waiting status
577 sub CanReserveBeCanceledFromOpac {
578 my ($reserve_id, $borrowernumber) = @_;
580 return unless $reserve_id and $borrowernumber;
581 my $reserve = GetReserve($reserve_id);
583 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
584 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
590 =head2 GetReserveCount
592 $number = &GetReserveCount($borrowernumber);
594 this function returns the number of reservation for a borrower given on input arg.
598 sub GetReserveCount {
599 my ($borrowernumber) = @_;
601 my $dbh = C4::Context->dbh;
604 SELECT COUNT(*) AS counter
606 WHERE borrowernumber = ?
608 my $sth = $dbh->prepare($query);
609 $sth->execute($borrowernumber);
610 my $row = $sth->fetchrow_hashref;
611 return $row->{counter};
614 =head2 GetOtherReserves
616 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
618 Check queued list of this document and check if this document must be transferred
622 sub GetOtherReserves {
623 my ($itemnumber) = @_;
626 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
627 if ($checkreserves) {
628 my $iteminfo = GetItem($itemnumber);
629 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
630 $messages->{'transfert'} = $checkreserves->{'branchcode'};
631 #minus priorities of others reservs
632 ModReserveMinusPriority(
634 $checkreserves->{'reserve_id'},
637 #launch the subroutine dotransfer
638 C4::Items::ModItemTransfer(
640 $iteminfo->{'holdingbranch'},
641 $checkreserves->{'branchcode'}
646 #step 2b : case of a reservation on the same branch, set the waiting status
648 $messages->{'waiting'} = 1;
649 ModReserveMinusPriority(
651 $checkreserves->{'reserve_id'},
653 ModReserveStatus($itemnumber,'W');
656 $nextreservinfo = $checkreserves->{'borrowernumber'};
659 return ( $messages, $nextreservinfo );
662 =head2 ChargeReserveFee
664 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
666 Charge the fee for a reserve (if $fee > 0)
670 sub ChargeReserveFee {
671 my ( $borrowernumber, $fee, $title ) = @_;
672 return if !$fee || $fee==0; # the last test is needed to include 0.00
674 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
676 my $dbh = C4::Context->dbh;
677 my $nextacctno = &getnextacctno( $borrowernumber );
678 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
683 $fee = GetReserveFee( $borrowernumber, $biblionumber );
685 Calculate the fee for a reserve (if applicable).
690 my ( $borrowernumber, $biblionumber ) = @_;
692 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
695 SELECT COUNT(*) FROM items
696 LEFT JOIN issues USING (itemnumber)
697 WHERE items.biblionumber=? AND issues.issue_id IS NULL
700 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
703 my $dbh = C4::Context->dbh;
704 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
705 if( $fee && $fee > 0 ) {
706 # This is a reconstruction of the old code:
707 # Compare number of items with items issued, and optionally check holds
708 # If not all items are issued and there are no holds: charge no fee
709 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
710 my ( $notissued, $reserved );
711 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
714 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
715 ( $biblionumber, $borrowernumber ) );
716 $fee = 0 if $reserved == 0;
722 =head2 GetReservesToBranch
724 @transreserv = GetReservesToBranch( $frombranch );
726 Get reserve list for a given branch
730 sub GetReservesToBranch {
731 my ( $frombranch ) = @_;
732 my $dbh = C4::Context->dbh;
733 my $sth = $dbh->prepare(
734 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
739 $sth->execute( $frombranch );
742 while ( my $data = $sth->fetchrow_hashref ) {
743 $transreserv[$i] = $data;
746 return (@transreserv);
749 =head2 GetReservesForBranch
751 @transreserv = GetReservesForBranch($frombranch);
755 sub GetReservesForBranch {
756 my ($frombranch) = @_;
757 my $dbh = C4::Context->dbh;
760 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
765 $query .= " AND branchcode=? " if ( $frombranch );
766 $query .= "ORDER BY waitingdate" ;
768 my $sth = $dbh->prepare($query);
770 $sth->execute($frombranch);
777 while ( my $data = $sth->fetchrow_hashref ) {
778 $transreserv[$i] = $data;
781 return (@transreserv);
784 =head2 GetReserveStatus
786 $reservestatus = GetReserveStatus($itemnumber);
788 Takes an itemnumber and returns the status of the reserve placed on it.
789 If several reserves exist, the reserve with the lower priority is given.
793 ## FIXME: I don't think this does what it thinks it does.
794 ## It only ever checks the first reserve result, even though
795 ## multiple reserves for that bib can have the itemnumber set
796 ## the sub is only used once in the codebase.
797 sub GetReserveStatus {
798 my ($itemnumber) = @_;
800 my $dbh = C4::Context->dbh;
802 my ($sth, $found, $priority);
804 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
805 $sth->execute($itemnumber);
806 ($found, $priority) = $sth->fetchrow_array;
810 return 'Waiting' if $found eq 'W' and $priority == 0;
811 return 'Finished' if $found eq 'F';
814 return 'Reserved' if $priority > 0;
816 return ''; # empty string here will remove need for checking undef, or less log lines
821 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
822 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
823 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
825 Find a book in the reserves.
827 C<$itemnumber> is the book's item number.
828 C<$lookahead> is the number of days to look in advance for future reserves.
830 As I understand it, C<&CheckReserves> looks for the given item in the
831 reserves. If it is found, that's a match, and C<$status> is set to
834 Otherwise, it finds the most important item in the reserves with the
835 same biblio number as this book (I'm not clear on this) and returns it
836 with C<$status> set to C<Reserved>.
838 C<&CheckReserves> returns a two-element list:
840 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
842 C<$reserve> is the reserve item that matched. It is a
843 reference-to-hash whose keys are mostly the fields of the reserves
844 table in the Koha database.
849 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
850 my $dbh = C4::Context->dbh;
853 if (C4::Context->preference('item-level_itypes')){
855 SELECT items.biblionumber,
856 items.biblioitemnumber,
857 itemtypes.notforloan,
858 items.notforloan AS itemnotforloan,
864 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
865 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
870 SELECT items.biblionumber,
871 items.biblioitemnumber,
872 itemtypes.notforloan,
873 items.notforloan AS itemnotforloan,
879 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
880 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
885 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
886 $sth->execute($item);
889 $sth = $dbh->prepare("$select WHERE barcode = ?");
890 $sth->execute($barcode);
892 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
893 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
895 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
897 return unless $itemnumber; # bail if we got nothing.
899 # if item is not for loan it cannot be reserved either.....
900 # except where items.notforloan < 0 : This indicates the item is holdable.
901 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
903 # Find this item in the reserves
904 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
906 # $priority and $highest are used to find the most important item
907 # in the list returned by &_Findgroupreserve. (The lower $priority,
908 # the more important the item.)
909 # $highest is the most important item we've seen so far.
911 if (scalar @reserves) {
912 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
913 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
914 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
916 my $priority = 10000000;
917 foreach my $res (@reserves) {
918 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
919 return ( "Waiting", $res, \@reserves ); # Found it
923 my $local_hold_match;
925 if ($LocalHoldsPriority) {
926 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
927 $iteminfo = C4::Items::GetItem($itemnumber);
929 my $local_holds_priority_item_branchcode =
930 $iteminfo->{$LocalHoldsPriorityItemControl};
931 my $local_holds_priority_patron_branchcode =
932 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
934 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
935 ? $borrowerinfo->{branchcode}
938 $local_holds_priority_item_branchcode eq
939 $local_holds_priority_patron_branchcode;
942 # See if this item is more important than what we've got so far
943 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
944 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
945 $iteminfo ||= C4::Items::GetItem($itemnumber);
946 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
947 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
948 next if ($branchitemrule->{'holdallowed'} == 0);
949 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
950 $priority = $res->{'priority'};
952 last if $local_hold_match;
958 # If we get this far, then no exact match was found.
959 # We return the most important (i.e. next) reservation.
961 $highest->{'itemnumber'} = $item;
962 return ( "Reserved", $highest, \@reserves );
968 =head2 CancelExpiredReserves
970 CancelExpiredReserves();
972 Cancels all reserves with an expiration date from before today.
976 sub CancelExpiredReserves {
978 # Cancel reserves that have passed their expiration date.
979 my $dbh = C4::Context->dbh;
980 my $sth = $dbh->prepare( "
981 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
982 AND expirationdate IS NOT NULL
987 while ( my $res = $sth->fetchrow_hashref() ) {
988 CancelReserve({ reserve_id => $res->{'reserve_id'} });
991 # Cancel reserves that have been waiting too long
992 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
993 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
994 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
996 my $today = dt_from_string();
998 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
999 $sth = $dbh->prepare( $query );
1000 $sth->execute( $max_pickup_delay );
1002 while ( my $res = $sth->fetchrow_hashref ) {
1004 unless ( $cancel_on_holidays ) {
1005 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
1006 my $is_holiday = $calendar->is_holiday( $today );
1008 if ( $is_holiday ) {
1014 CancelReserve({ reserve_id => $res->{'reserve_id'}, charge_cancel_fee => 1 });
1021 =head2 AutoUnsuspendReserves
1023 AutoUnsuspendReserves();
1025 Unsuspends all suspended reserves with a suspend_until date from before today.
1029 sub AutoUnsuspendReserves {
1031 my $dbh = C4::Context->dbh;
1033 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
1034 my $sth = $dbh->prepare( $query );
1039 =head2 CancelReserve
1041 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
1043 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.
1048 my ( $params ) = @_;
1050 my $reserve_id = $params->{'reserve_id'};
1051 # Filter out only the desired keys; this will insert undefined values for elements missing in
1052 # \%params, but GetReserveId filters them out anyway.
1053 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
1055 return unless ( $reserve_id );
1057 my $dbh = C4::Context->dbh;
1059 my $reserve = GetReserve( $reserve_id );
1063 SET cancellationdate = now(),
1066 WHERE reserve_id = ?
1068 my $sth = $dbh->prepare($query);
1069 $sth->execute( $reserve_id );
1072 INSERT INTO old_reserves
1073 SELECT * FROM reserves
1074 WHERE reserve_id = ?
1076 $sth = $dbh->prepare($query);
1077 $sth->execute( $reserve_id );
1080 DELETE FROM reserves
1081 WHERE reserve_id = ?
1083 $sth = $dbh->prepare($query);
1084 $sth->execute( $reserve_id );
1086 # now fix the priority on the others....
1087 _FixPriority({ biblionumber => $reserve->{biblionumber} });
1089 # and, if desired, charge a cancel fee
1090 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
1091 if ( $charge && $params->{'charge_cancel_fee'} ) {
1092 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
1101 ModReserve({ rank => $rank,
1102 reserve_id => $reserve_id,
1103 branchcode => $branchcode
1104 [, itemnumber => $itemnumber ]
1105 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1108 Change a hold request's priority or cancel it.
1110 C<$rank> specifies the effect of the change. If C<$rank>
1111 is 'W' or 'n', nothing happens. This corresponds to leaving a
1112 request alone when changing its priority in the holds queue
1115 If C<$rank> is 'del', the hold request is cancelled.
1117 If C<$rank> is an integer greater than zero, the priority of
1118 the request is set to that value. Since priority != 0 means
1119 that the item is not waiting on the hold shelf, setting the
1120 priority to a non-zero value also sets the request's found
1121 status and waiting date to NULL.
1123 The optional C<$itemnumber> parameter is used only when
1124 C<$rank> is a non-zero integer; if supplied, the itemnumber
1125 of the hold request is set accordingly; if omitted, the itemnumber
1128 B<FIXME:> Note that the forgoing can have the effect of causing
1129 item-level hold requests to turn into title-level requests. This
1130 will be fixed once reserves has separate columns for requested
1131 itemnumber and supplying itemnumber.
1136 my ( $params ) = @_;
1138 my $rank = $params->{'rank'};
1139 my $reserve_id = $params->{'reserve_id'};
1140 my $branchcode = $params->{'branchcode'};
1141 my $itemnumber = $params->{'itemnumber'};
1142 my $suspend_until = $params->{'suspend_until'};
1143 my $borrowernumber = $params->{'borrowernumber'};
1144 my $biblionumber = $params->{'biblionumber'};
1146 return if $rank eq "W";
1147 return if $rank eq "n";
1149 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1150 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1152 my $dbh = C4::Context->dbh;
1153 if ( $rank eq "del" ) {
1154 CancelReserve({ reserve_id => $reserve_id });
1156 elsif ($rank =~ /^\d+/ and $rank > 0) {
1158 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1159 WHERE reserve_id = ?
1161 my $sth = $dbh->prepare($query);
1162 $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
1164 if ( defined( $suspend_until ) ) {
1165 if ( $suspend_until ) {
1166 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until ), dateonly => 1 }); };
1167 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
1169 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
1173 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1177 =head2 ModReserveFill
1179 &ModReserveFill($reserve);
1181 Fill a reserve. If I understand this correctly, this means that the
1182 reserved book has been found and given to the patron who reserved it.
1184 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1185 whose keys are fields from the reserves table in the Koha database.
1189 sub ModReserveFill {
1191 my $dbh = C4::Context->dbh;
1192 # fill in a reserve record....
1193 my $reserve_id = $res->{'reserve_id'};
1194 my $biblionumber = $res->{'biblionumber'};
1195 my $borrowernumber = $res->{'borrowernumber'};
1196 my $resdate = $res->{'reservedate'};
1198 # get the priority on this record....
1200 my $query = "SELECT priority
1202 WHERE biblionumber = ?
1203 AND borrowernumber = ?
1204 AND reservedate = ?";
1205 my $sth = $dbh->prepare($query);
1206 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1207 ($priority) = $sth->fetchrow_array;
1209 # update the database...
1210 $query = "UPDATE reserves
1213 WHERE biblionumber = ?
1215 AND borrowernumber = ?
1217 $sth = $dbh->prepare($query);
1218 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1220 # move to old_reserves
1221 $query = "INSERT INTO old_reserves
1222 SELECT * FROM reserves
1223 WHERE biblionumber = ?
1225 AND borrowernumber = ?
1227 $sth = $dbh->prepare($query);
1228 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1229 $query = "DELETE FROM reserves
1230 WHERE biblionumber = ?
1232 AND borrowernumber = ?
1234 $sth = $dbh->prepare($query);
1235 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1237 # now fix the priority on the others (if the priority wasn't
1238 # already sorted!)....
1239 unless ( $priority == 0 ) {
1240 _FixPriority({ reserve_id => $reserve_id, biblionumber => $biblionumber });
1244 =head2 ModReserveStatus
1246 &ModReserveStatus($itemnumber, $newstatus);
1248 Update the reserve status for the active (priority=0) reserve.
1250 $itemnumber is the itemnumber the reserve is on
1252 $newstatus is the new status.
1256 sub ModReserveStatus {
1258 #first : check if we have a reservation for this item .
1259 my ($itemnumber, $newstatus) = @_;
1260 my $dbh = C4::Context->dbh;
1262 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1263 my $sth_set = $dbh->prepare($query);
1264 $sth_set->execute( $newstatus, $itemnumber );
1266 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1267 CartToShelf( $itemnumber );
1271 =head2 ModReserveAffect
1273 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1275 This function affect an item and a status for a given reserve
1276 The itemnumber parameter is used to find the biblionumber.
1277 with the biblionumber & the borrowernumber, we can affect the itemnumber
1278 to the correct reserve.
1280 if $transferToDo is not set, then the status is set to "Waiting" as well.
1281 otherwise, a transfer is on the way, and the end of the transfer will
1282 take care of the waiting status
1286 sub ModReserveAffect {
1287 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1288 my $dbh = C4::Context->dbh;
1290 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1291 # attached to $itemnumber
1292 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1293 $sth->execute($itemnumber);
1294 my ($biblionumber) = $sth->fetchrow;
1296 # get request - need to find out if item is already
1297 # waiting in order to not send duplicate hold filled notifications
1298 my $reserve_id = GetReserveId({
1299 borrowernumber => $borrowernumber,
1300 biblionumber => $biblionumber,
1302 return unless defined $reserve_id;
1303 my $request = GetReserveInfo($reserve_id);
1304 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1306 # If we affect a reserve that has to be transferred, don't set to Waiting
1308 if ($transferToDo) {
1314 WHERE borrowernumber = ?
1315 AND biblionumber = ?
1319 # affect the reserve to Waiting as well.
1324 waitingdate = NOW(),
1326 WHERE borrowernumber = ?
1327 AND biblionumber = ?
1330 $sth = $dbh->prepare($query);
1331 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1332 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1333 _FixPriority( { biblionumber => $biblionumber } );
1334 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1335 CartToShelf( $itemnumber );
1341 =head2 ModReserveCancelAll
1343 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1345 function to cancel reserv,check other reserves, and transfer document if it's necessary
1349 sub ModReserveCancelAll {
1352 my ( $itemnumber, $borrowernumber ) = @_;
1354 #step 1 : cancel the reservation
1355 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1357 #step 2 launch the subroutine of the others reserves
1358 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1360 return ( $messages, $nextreservinfo );
1363 =head2 ModReserveMinusPriority
1365 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1367 Reduce the values of queued list
1371 sub ModReserveMinusPriority {
1372 my ( $itemnumber, $reserve_id ) = @_;
1374 #first step update the value of the first person on reserv
1375 my $dbh = C4::Context->dbh;
1378 SET priority = 0 , itemnumber = ?
1379 WHERE reserve_id = ?
1381 my $sth_upd = $dbh->prepare($query);
1382 $sth_upd->execute( $itemnumber, $reserve_id );
1383 # second step update all others reserves
1384 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1387 =head2 GetReserveInfo
1389 &GetReserveInfo($reserve_id);
1391 Get item and borrower details for a current hold.
1392 Current implementation this query should have a single result.
1396 sub GetReserveInfo {
1397 my ( $reserve_id ) = @_;
1398 my $dbh = C4::Context->dbh;
1403 reserves.borrowernumber,
1404 reserves.biblionumber,
1405 reserves.branchcode,
1406 reserves.waitingdate,
1422 items.holdingbranch,
1423 items.itemcallnumber,
1429 LEFT JOIN items USING(itemnumber)
1430 LEFT JOIN borrowers USING(borrowernumber)
1431 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1432 WHERE reserves.reserve_id = ?";
1433 my $sth = $dbh->prepare($strsth);
1434 $sth->execute($reserve_id);
1436 my $data = $sth->fetchrow_hashref;
1440 =head2 IsAvailableForItemLevelRequest
1442 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1444 Checks whether a given item record is available for an
1445 item-level hold request. An item is available if
1447 * it is not lost AND
1448 * it is not damaged AND
1449 * it is not withdrawn AND
1450 * does not have a not for loan value > 0
1452 Need to check the issuingrules onshelfholds column,
1453 if this is set items on the shelf can be placed on hold
1455 Note that IsAvailableForItemLevelRequest() does not
1456 check if the staff operator is authorized to place
1457 a request on the item - in particular,
1458 this routine does not check IndependentBranches
1459 and canreservefromotherbranches.
1463 sub IsAvailableForItemLevelRequest {
1465 my $borrower = shift;
1467 my $dbh = C4::Context->dbh;
1468 # must check the notforloan setting of the itemtype
1469 # FIXME - a lot of places in the code do this
1470 # or something similar - need to be
1472 my $itype = _get_itype($item);
1473 my $notforloan_per_itemtype
1474 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1478 $notforloan_per_itemtype ||
1479 $item->{itemlost} ||
1480 $item->{notforloan} > 0 ||
1481 $item->{withdrawn} ||
1482 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1485 return 1 if _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1487 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1490 =head2 OnShelfHoldsAllowed
1492 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1494 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1495 holds are allowed, returns true if so.
1499 sub OnShelfHoldsAllowed {
1500 my ($item, $borrower) = @_;
1502 my $itype = _get_itype($item);
1503 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1510 if (C4::Context->preference('item-level_itypes')) {
1511 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1512 # When GetItem is fixed, we can remove this
1513 $itype = $item->{itype};
1516 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1517 # So if we already have a biblioitems join when calling this function,
1518 # we don't need to access the database again
1519 $itype = $item->{itemtype};
1522 my $dbh = C4::Context->dbh;
1523 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1524 my $sth = $dbh->prepare($query);
1525 $sth->execute($item->{biblioitemnumber});
1526 if (my $data = $sth->fetchrow_hashref()){
1527 $itype = $data->{itemtype};
1533 sub _OnShelfHoldsAllowed {
1534 my ($itype,$borrowercategory,$branchcode) = @_;
1536 my $rule = C4::Circulation::GetIssuingRule($borrowercategory, $itype, $branchcode);
1537 return $rule->{onshelfholds};
1540 =head2 AlterPriority
1542 AlterPriority( $where, $reserve_id );
1544 This function changes a reserve's priority up, down, to the top, or to the bottom.
1545 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1550 my ( $where, $reserve_id ) = @_;
1552 my $dbh = C4::Context->dbh;
1554 my $reserve = GetReserve( $reserve_id );
1556 if ( $reserve->{cancellationdate} ) {
1557 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1561 if ( $where eq 'up' || $where eq 'down' ) {
1563 my $priority = $reserve->{'priority'};
1564 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1565 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1567 } elsif ( $where eq 'top' ) {
1569 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1571 } elsif ( $where eq 'bottom' ) {
1573 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1578 =head2 ToggleLowestPriority
1580 ToggleLowestPriority( $borrowernumber, $biblionumber );
1582 This function sets the lowestPriority field to true if is false, and false if it is true.
1586 sub ToggleLowestPriority {
1587 my ( $reserve_id ) = @_;
1589 my $dbh = C4::Context->dbh;
1591 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1592 $sth->execute( $reserve_id );
1594 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1597 =head2 ToggleSuspend
1599 ToggleSuspend( $reserve_id );
1601 This function sets the suspend field to true if is false, and false if it is true.
1602 If the reserve is currently suspended with a suspend_until date, that date will
1603 be cleared when it is unsuspended.
1608 my ( $reserve_id, $suspend_until ) = @_;
1610 $suspend_until = output_pref(
1612 dt => dt_from_string($suspend_until),
1613 dateformat => 'iso',
1616 ) if ($suspend_until);
1618 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1620 my $dbh = C4::Context->dbh;
1622 my $sth = $dbh->prepare(
1623 "UPDATE reserves SET suspend = NOT suspend,
1624 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1625 WHERE reserve_id = ?
1629 push( @params, $suspend_until ) if ( $suspend_until );
1630 push( @params, $reserve_id );
1632 $sth->execute( @params );
1638 borrowernumber => $borrowernumber,
1639 [ biblionumber => $biblionumber, ]
1640 [ suspend_until => $suspend_until, ]
1641 [ suspend => $suspend ]
1644 This function accepts a set of hash keys as its parameters.
1645 It requires either borrowernumber or biblionumber, or both.
1647 suspend_until is wholly optional.
1654 my $borrowernumber = $params{'borrowernumber'} || undef;
1655 my $biblionumber = $params{'biblionumber'} || undef;
1656 my $suspend_until = $params{'suspend_until'} || undef;
1657 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1659 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until), dateonly => 1, dateformat => 'iso' } ); }
1660 if ( defined( $suspend_until ) );
1662 return unless ( $borrowernumber || $biblionumber );
1664 my ( $query, $sth, $dbh, @query_params );
1666 $query = "UPDATE reserves SET suspend = ? ";
1667 push( @query_params, $suspend );
1669 $query .= ", suspend_until = NULL ";
1670 } elsif ( $suspend_until ) {
1671 $query .= ", suspend_until = ? ";
1672 push( @query_params, $suspend_until );
1674 $query .= " WHERE ";
1675 if ( $borrowernumber ) {
1676 $query .= " borrowernumber = ? ";
1677 push( @query_params, $borrowernumber );
1679 $query .= " AND " if ( $borrowernumber && $biblionumber );
1680 if ( $biblionumber ) {
1681 $query .= " biblionumber = ? ";
1682 push( @query_params, $biblionumber );
1684 $query .= " AND found IS NULL ";
1686 $dbh = C4::Context->dbh;
1687 $sth = $dbh->prepare( $query );
1688 $sth->execute( @query_params );
1695 reserve_id => $reserve_id,
1697 [ignoreSetLowestRank => $ignoreSetLowestRank]
1702 _FixPriority({ biblionumber => $biblionumber});
1704 This routine adjusts the priority of a hold request and holds
1707 In the first form, where a reserve_id is passed, the priority of the
1708 hold is set to supplied rank, and other holds for that bib are adjusted
1709 accordingly. If the rank is "del", the hold is cancelled. If no rank
1710 is supplied, all of the holds on that bib have their priority adjusted
1711 as if the second form had been used.
1713 In the second form, where a biblionumber is passed, the holds on that
1714 bib (that are not captured) are sorted in order of increasing priority,
1715 then have reserves.priority set so that the first non-captured hold
1716 has its priority set to 1, the second non-captured hold has its priority
1717 set to 2, and so forth.
1719 In both cases, holds that have the lowestPriority flag on are have their
1720 priority adjusted to ensure that they remain at the end of the line.
1722 Note that the ignoreSetLowestRank parameter is meant to be used only
1723 when _FixPriority calls itself.
1728 my ( $params ) = @_;
1729 my $reserve_id = $params->{reserve_id};
1730 my $rank = $params->{rank} // '';
1731 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1732 my $biblionumber = $params->{biblionumber};
1734 my $dbh = C4::Context->dbh;
1736 unless ( $biblionumber ) {
1737 my $res = GetReserve( $reserve_id );
1738 $biblionumber = $res->{biblionumber};
1741 if ( $rank eq "del" ) {
1742 CancelReserve({ reserve_id => $reserve_id });
1744 elsif ( $rank eq "W" || $rank eq "0" ) {
1746 # make sure priority for waiting or in-transit items is 0
1750 WHERE reserve_id = ?
1751 AND found IN ('W', 'T')
1753 my $sth = $dbh->prepare($query);
1754 $sth->execute( $reserve_id );
1760 SELECT reserve_id, borrowernumber, reservedate
1762 WHERE biblionumber = ?
1763 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1764 ORDER BY priority ASC
1766 my $sth = $dbh->prepare($query);
1767 $sth->execute( $biblionumber );
1768 while ( my $line = $sth->fetchrow_hashref ) {
1769 push( @priority, $line );
1772 # To find the matching index
1774 my $key = -1; # to allow for 0 to be a valid result
1775 for ( $i = 0 ; $i < @priority ; $i++ ) {
1776 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1777 $key = $i; # save the index
1782 # if index exists in array then move it to new position
1783 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1784 my $new_rank = $rank -
1785 1; # $new_rank is what you want the new index to be in the array
1786 my $moving_item = splice( @priority, $key, 1 );
1787 splice( @priority, $new_rank, 0, $moving_item );
1790 # now fix the priority on those that are left....
1794 WHERE reserve_id = ?
1796 $sth = $dbh->prepare($query);
1797 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1800 $priority[$j]->{'reserve_id'}
1804 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1807 unless ( $ignoreSetLowestRank ) {
1808 while ( my $res = $sth->fetchrow_hashref() ) {
1810 reserve_id => $res->{'reserve_id'},
1812 ignoreSetLowestRank => 1
1818 =head2 _Findgroupreserve
1820 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1822 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1823 first match found. If neither, then we look for non-holds-queue based holds.
1824 Lookahead is the number of days to look in advance.
1826 C<&_Findgroupreserve> returns :
1827 C<@results> is an array of references-to-hash whose keys are mostly
1828 fields from the reserves table of the Koha database, plus
1829 C<biblioitemnumber>.
1833 sub _Findgroupreserve {
1834 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1835 my $dbh = C4::Context->dbh;
1837 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1838 # check for exact targeted match
1839 my $item_level_target_query = qq{
1840 SELECT reserves.biblionumber AS biblionumber,
1841 reserves.borrowernumber AS borrowernumber,
1842 reserves.reservedate AS reservedate,
1843 reserves.branchcode AS branchcode,
1844 reserves.cancellationdate AS cancellationdate,
1845 reserves.found AS found,
1846 reserves.reservenotes AS reservenotes,
1847 reserves.priority AS priority,
1848 reserves.timestamp AS timestamp,
1849 biblioitems.biblioitemnumber AS biblioitemnumber,
1850 reserves.itemnumber AS itemnumber,
1851 reserves.reserve_id AS reserve_id
1853 JOIN biblioitems USING (biblionumber)
1854 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1857 AND item_level_request = 1
1859 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1863 my $sth = $dbh->prepare($item_level_target_query);
1864 $sth->execute($itemnumber, $lookahead||0);
1866 if ( my $data = $sth->fetchrow_hashref ) {
1867 push( @results, $data )
1868 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1870 return @results if @results;
1872 # check for title-level targeted match
1873 my $title_level_target_query = qq{
1874 SELECT reserves.biblionumber AS biblionumber,
1875 reserves.borrowernumber AS borrowernumber,
1876 reserves.reservedate AS reservedate,
1877 reserves.branchcode AS branchcode,
1878 reserves.cancellationdate AS cancellationdate,
1879 reserves.found AS found,
1880 reserves.reservenotes AS reservenotes,
1881 reserves.priority AS priority,
1882 reserves.timestamp AS timestamp,
1883 biblioitems.biblioitemnumber AS biblioitemnumber,
1884 reserves.itemnumber AS itemnumber,
1885 reserves.reserve_id AS reserve_id
1887 JOIN biblioitems USING (biblionumber)
1888 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1891 AND item_level_request = 0
1892 AND hold_fill_targets.itemnumber = ?
1893 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1897 $sth = $dbh->prepare($title_level_target_query);
1898 $sth->execute($itemnumber, $lookahead||0);
1900 if ( my $data = $sth->fetchrow_hashref ) {
1901 push( @results, $data )
1902 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1904 return @results if @results;
1907 SELECT reserves.biblionumber AS biblionumber,
1908 reserves.borrowernumber AS borrowernumber,
1909 reserves.reservedate AS reservedate,
1910 reserves.waitingdate AS waitingdate,
1911 reserves.branchcode AS branchcode,
1912 reserves.cancellationdate AS cancellationdate,
1913 reserves.found AS found,
1914 reserves.reservenotes AS reservenotes,
1915 reserves.priority AS priority,
1916 reserves.timestamp AS timestamp,
1917 reserves.itemnumber AS itemnumber,
1918 reserves.reserve_id AS reserve_id
1920 WHERE reserves.biblionumber = ?
1921 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1922 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1926 $sth = $dbh->prepare($query);
1927 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1929 while ( my $data = $sth->fetchrow_hashref ) {
1930 push( @results, $data )
1931 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1936 =head2 _koha_notify_reserve
1938 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1940 Sends a notification to the patron that their hold has been filled (through
1941 ModReserveAffect, _not_ ModReserveFill)
1945 sub _koha_notify_reserve {
1946 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1948 my $dbh = C4::Context->dbh;
1949 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1951 # Try to get the borrower's email address
1952 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1954 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1955 borrowernumber => $borrowernumber,
1956 message_name => 'Hold_Filled'
1959 my $sth = $dbh->prepare("
1962 WHERE borrowernumber = ?
1963 AND biblionumber = ?
1965 $sth->execute( $borrowernumber, $biblionumber );
1966 my $reserve = $sth->fetchrow_hashref;
1967 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1969 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1971 my %letter_params = (
1972 module => 'reserves',
1973 branchcode => $reserve->{branchcode},
1975 'branches' => $branch_details,
1976 'borrowers' => $borrower,
1977 'biblio' => $biblionumber,
1978 'reserves' => $reserve,
1979 'items', $reserve->{'itemnumber'},
1981 substitute => { today => eval { output_pref( { dt => dt_from_string, dateonly => 1 } ); } },
1984 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.
1985 my $send_notification = sub {
1986 my ( $mtt, $letter_code ) = (@_);
1987 return unless defined $letter_code;
1988 $letter_params{letter_code} = $letter_code;
1989 $letter_params{message_transport_type} = $mtt;
1990 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1992 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1996 C4::Letters::EnqueueLetter( {
1998 borrowernumber => $borrowernumber,
1999 from_address => $admin_email_address,
2000 message_transport_type => $mtt,
2004 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
2006 ( $mtt eq 'email' and not $to_address ) # No email address
2007 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
2008 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
2011 &$send_notification($mtt, $letter_code);
2012 $notification_sent++;
2014 #Making sure that a print notification is sent if no other transport types can be utilized.
2015 if (! $notification_sent) {
2016 &$send_notification('print', 'HOLD');
2021 =head2 _ShiftPriorityByDateAndPriority
2023 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
2025 This increments the priority of all reserves after the one
2026 with either the lowest date after C<$reservedate>
2027 or the lowest priority after C<$priority>.
2029 It effectively makes room for a new reserve to be inserted with a certain
2030 priority, which is returned.
2032 This is most useful when the reservedate can be set by the user. It allows
2033 the new reserve to be placed before other reserves that have a later
2034 reservedate. Since priority also is set by the form in reserves/request.pl
2035 the sub accounts for that too.
2039 sub _ShiftPriorityByDateAndPriority {
2040 my ( $biblio, $resdate, $new_priority ) = @_;
2042 my $dbh = C4::Context->dbh;
2043 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2044 my $sth = $dbh->prepare( $query );
2045 $sth->execute( $biblio, $resdate, $new_priority );
2046 my $min_priority = $sth->fetchrow;
2047 # if no such matches are found, $new_priority remains as original value
2048 $new_priority = $min_priority if ( $min_priority );
2050 # Shift the priority up by one; works in conjunction with the next SQL statement
2051 $query = "UPDATE reserves
2052 SET priority = priority+1
2053 WHERE biblionumber = ?
2054 AND borrowernumber = ?
2057 my $sth_update = $dbh->prepare( $query );
2059 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2060 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2061 $sth = $dbh->prepare( $query );
2062 $sth->execute( $new_priority, $biblio );
2063 while ( my $row = $sth->fetchrow_hashref ) {
2064 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2067 return $new_priority; # so the caller knows what priority they wind up receiving
2070 =head2 OPACItemHoldsAllowed
2072 OPACItemHoldsAllowed($item_record,$borrower_record);
2074 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
2075 if specific item holds are allowed, returns true if so.
2079 sub OPACItemHoldsAllowed {
2080 my ($item,$borrower) = @_;
2082 my $branchcode = $item->{homebranch} or die "No homebranch";
2084 my $dbh = C4::Context->dbh;
2085 if (C4::Context->preference('item-level_itypes')) {
2086 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
2087 # When GetItem is fixed, we can remove this
2088 $itype = $item->{itype};
2091 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
2092 my $sth = $dbh->prepare($query);
2093 $sth->execute($item->{biblioitemnumber});
2094 if (my $data = $sth->fetchrow_hashref()){
2095 $itype = $data->{itemtype};
2099 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
2100 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
2102 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2104 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
2106 issuingrules.categorycode desc,
2107 issuingrules.itemtype desc,
2108 issuingrules.branchcode desc
2110 my $sth = $dbh->prepare($query);
2111 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2112 my $data = $sth->fetchrow_hashref;
2113 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2114 return '' if $opacitemholds eq 'N';
2115 return $opacitemholds;
2120 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2122 Use when checking out an item to handle reserves
2123 If $cancelreserve boolean is set to true, it will remove existing reserve
2128 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2130 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2131 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2134 my $biblionumber = $res->{biblionumber};
2135 my $biblioitemnumber = $res->{biblioitemnumber};
2137 if ($res->{borrowernumber} == $borrowernumber) {
2138 ModReserveFill($res);
2142 # The item is reserved by someone else.
2143 # Find this item in the reserves
2146 foreach (@$all_reserves) {
2147 $_->{'borrowernumber'} == $borrowernumber or next;
2148 $_->{'biblionumber'} == $biblionumber or next;
2155 # The item is reserved by the current patron
2156 ModReserveFill($borr_res);
2159 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2160 RevertWaitingStatus({ itemnumber => $itemnumber });
2162 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2163 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2170 MergeHolds($dbh,$to_biblio, $from_biblio);
2172 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2177 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2178 my $sth = $dbh->prepare(
2179 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2181 $sth->execute($from_biblio);
2182 if ( my $data = $sth->fetchrow_hashref() ) {
2184 # holds exist on old record, if not we don't need to do anything
2185 $sth = $dbh->prepare(
2186 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2187 $sth->execute( $to_biblio, $from_biblio );
2190 # don't reorder those already waiting
2192 $sth = $dbh->prepare(
2193 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2195 my $upd_sth = $dbh->prepare(
2196 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2197 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2199 $sth->execute( $to_biblio, 'W', 'T' );
2201 while ( my $reserve = $sth->fetchrow_hashref() ) {
2203 $priority, $to_biblio,
2204 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2205 $reserve->{'itemnumber'}
2212 =head2 RevertWaitingStatus
2214 RevertWaitingStatus({ itemnumber => $itemnumber });
2216 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2218 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2219 item level hold, even if it was only a bibliolevel hold to
2220 begin with. This is because we can no longer know if a hold
2221 was item-level or bib-level after a hold has been set to
2226 sub RevertWaitingStatus {
2227 my ( $params ) = @_;
2228 my $itemnumber = $params->{'itemnumber'};
2230 return unless ( $itemnumber );
2232 my $dbh = C4::Context->dbh;
2234 ## Get the waiting reserve we want to revert
2236 SELECT * FROM reserves
2237 WHERE itemnumber = ?
2238 AND found IS NOT NULL
2240 my $sth = $dbh->prepare( $query );
2241 $sth->execute( $itemnumber );
2242 my $reserve = $sth->fetchrow_hashref();
2244 ## Increment the priority of all other non-waiting
2245 ## reserves for this bib record
2249 priority = priority + 1
2255 $sth = $dbh->prepare( $query );
2256 $sth->execute( $reserve->{'biblionumber'} );
2258 ## Fix up the currently waiting reserve
2268 $sth = $dbh->prepare( $query );
2269 $sth->execute( $reserve->{'reserve_id'} );
2270 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2275 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2277 Returnes the first reserve id that matches the given criteria
2282 my ( $params ) = @_;
2284 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2286 my $dbh = C4::Context->dbh();
2288 my $sql = "SELECT reserve_id FROM reserves WHERE ";
2292 foreach my $key ( keys %$params ) {
2293 if ( defined( $params->{$key} ) ) {
2294 push( @limits, "$key = ?" );
2295 push( @params, $params->{$key} );
2299 $sql .= join( " AND ", @limits );
2301 my $sth = $dbh->prepare( $sql );
2302 $sth->execute( @params );
2303 my $row = $sth->fetchrow_hashref();
2305 return $row->{'reserve_id'};
2310 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2312 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2317 my ($branch, $borrowernumber, $biblionumber) = @_;
2319 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2321 my $reserve_id = GetReserveId({
2322 biblionumber => $biblionumber,
2323 borrowernumber => $borrowernumber
2325 my $reserve = GetReserveInfo($reserve_id) or return;
2327 return C4::Letters::GetPreparedLetter (
2328 module => 'circulation',
2329 letter_code => 'RESERVESLIP',
2330 branchcode => $branch,
2332 'reserves' => $reserve,
2333 'branches' => $reserve->{branchcode},
2334 'borrowers' => $reserve->{borrowernumber},
2335 'biblio' => $reserve->{biblionumber},
2336 'items' => $reserve->{itemnumber},
2341 =head2 GetReservesControlBranch
2343 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2345 Return the branchcode to be used to determine which reserves
2346 policy applies to a transaction.
2348 C<$item> is a hashref for an item. Only 'homebranch' is used.
2350 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2354 sub GetReservesControlBranch {
2355 my ( $item, $borrower ) = @_;
2357 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2360 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2361 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2367 =head2 CalculatePriority
2369 my $p = CalculatePriority($biblionumber, $resdate);
2371 Calculate priority for a new reserve on biblionumber, placing it at
2372 the end of the line of all holds whose start date falls before
2373 the current system time and that are neither on the hold shelf
2376 The reserve date parameter is optional; if it is supplied, the
2377 priority is based on the set of holds whose start date falls before
2378 the parameter value.
2380 After calculation of this priority, it is recommended to call
2381 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2386 sub CalculatePriority {
2387 my ( $biblionumber, $resdate ) = @_;
2390 SELECT COUNT(*) FROM reserves
2391 WHERE biblionumber = ?
2393 AND (found IS NULL OR found = '')
2395 #skip found==W or found==T (waiting or transit holds)
2397 $sql.= ' AND ( reservedate <= ? )';
2400 $sql.= ' AND ( reservedate < NOW() )';
2402 my $dbh = C4::Context->dbh();
2403 my @row = $dbh->selectrow_array(
2406 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2409 return @row ? $row[0]+1 : 1;
2412 =head2 IsItemOnHoldAndFound
2414 my $bool = IsItemFoundHold( $itemnumber );
2416 Returns true if the item is currently on hold
2417 and that hold has a non-null found status ( W, T, etc. )
2421 sub IsItemOnHoldAndFound {
2422 my ($itemnumber) = @_;
2424 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2426 my $found = $rs->count(
2428 itemnumber => $itemnumber,
2429 found => { '!=' => undef }
2438 Koha Development Team <http://koha-community.org/>