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 );
38 use C4::Dates qw( format_date_in_iso );
44 use List::MoreUtils qw( firstidx any );
46 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
50 C4::Reserves - Koha functions for dealing with reservation.
58 This modules provides somes functions to deal with reservations.
60 Reserves are stored in reserves table.
61 The following columns contains important values :
62 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
63 =0 : then the reserve is being dealed
64 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
65 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
66 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
67 F(inished) : the reserve has been completed, and is done
68 - itemnumber : empty : the reserve is still unaffected to an item
69 filled: the reserve is attached to an item
70 The complete workflow is :
71 ==== 1st use case ====
72 patron request a document, 1st available : P >0, F=NULL, I=NULL
73 a library having it run "transfertodo", and clic on the list
74 if there is no transfer to do, the reserve waiting
75 patron can pick it up P =0, F=W, I=filled
76 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
77 The pickup library receive the book, it check in P =0, F=W, I=filled
78 The patron borrow the book P =0, F=F, I=filled
80 ==== 2nd use case ====
81 patron requests a document, a given item,
82 If pickup is holding branch P =0, F=W, I=filled
83 If transfer needed, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it checks it in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
92 # set the version for version checking
93 $VERSION = 3.07.00.049;
100 &GetReservesFromItemnumber
101 &GetReservesFromBiblionumber
102 &GetReservesFromBorrowernumber
103 &GetReservesForBranch
116 &ModReserveMinusPriority
122 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
130 &OPACItemHoldsAllowed
133 &ToggleLowestPriority
139 &GetReservesControlBranch
143 @EXPORT_OK = qw( MergeHolds );
148 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
154 $branch, $borrowernumber, $biblionumber,
155 $bibitems, $priority, $resdate, $expdate, $notes,
156 $title, $checkitem, $found
158 my $dbh = C4::Context->dbh;
159 $resdate = format_date_in_iso( $resdate ) if ( $resdate );
160 $resdate = C4::Dates->today( 'iso' ) unless ( $resdate );
162 $expdate = format_date_in_iso( $expdate );
164 undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
166 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
167 # Make room in reserves for this before those of a later reserve date
168 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
172 # If the reserv had the waiting status, we had the value of the resdate
173 if ( $found eq 'W' ) {
174 $waitingdate = $resdate;
177 # updates take place here
180 (borrowernumber,biblionumber,reservedate,branchcode,
181 priority,reservenotes,itemnumber,found,waitingdate,expirationdate)
186 my $sth = $dbh->prepare($query);
188 $borrowernumber, $biblionumber, $resdate, $branch, $priority,
189 $notes, $checkitem, $found, $waitingdate, $expdate
191 my $reserve_id = $sth->{mysql_insertid};
192 # add a reserve fee if needed
193 my $fee = GetReserveFee( $borrowernumber, $biblionumber );
194 ChargeReserveFee( $borrowernumber, $fee, $title );
196 # Send e-mail to librarian if syspref is active
197 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
198 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
199 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
200 if ( my $letter = C4::Letters::GetPreparedLetter (
201 module => 'reserves',
202 letter_code => 'HOLDPLACED',
203 branchcode => $branch,
205 'branches' => $branch_details,
206 'borrowers' => $borrower,
207 'biblio' => $biblionumber,
208 'items' => $checkitem,
212 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
214 C4::Letters::EnqueueLetter(
216 borrowernumber => $borrowernumber,
217 message_transport_type => 'email',
218 from_address => $admin_email_address,
219 to_address => $admin_email_address,
230 $res = GetReserve( $reserve_id );
232 Return the current reserve.
237 my ($reserve_id) = @_;
239 my $dbh = C4::Context->dbh;
240 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
241 my $sth = $dbh->prepare( $query );
242 $sth->execute( $reserve_id );
243 return $sth->fetchrow_hashref();
246 =head2 GetReservesFromBiblionumber
248 my $reserves = GetReservesFromBiblionumber({
249 biblionumber => $biblionumber,
250 [ itemnumber => $itemnumber, ]
254 This function gets the list of reservations for one C<$biblionumber>,
255 returning an arrayref pointing to the reserves for C<$biblionumber>.
257 By default, only reserves whose start date falls before the current
258 time are returned. To return all reserves, including future ones,
259 the C<all_dates> parameter can be included and set to a true value.
261 If the C<itemnumber> parameter is supplied, reserves must be targeted
262 to that item or not targeted to any item at all; otherwise, they
263 are excluded from the list.
267 sub GetReservesFromBiblionumber {
269 my $biblionumber = $params->{biblionumber} or return [];
270 my $itemnumber = $params->{itemnumber};
271 my $all_dates = $params->{all_dates} // 0;
272 my $dbh = C4::Context->dbh;
274 # Find the desired items in the reserves
279 timestamp AS rtimestamp,
292 WHERE biblionumber = ? ";
293 push( @params, $biblionumber );
294 unless ( $all_dates ) {
295 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
298 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
299 push( @params, $itemnumber );
301 $query .= "ORDER BY priority";
302 my $sth = $dbh->prepare($query);
303 $sth->execute( @params );
305 while ( my $data = $sth->fetchrow_hashref ) {
306 push @results, $data;
311 =head2 GetReservesFromItemnumber
313 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
315 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
317 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
321 sub GetReservesFromItemnumber {
322 my ($itemnumber) = @_;
324 my $schema = Koha::Database->new()->schema();
326 my $r = $schema->resultset('Reserve')->search(
328 itemnumber => $itemnumber,
331 reservedate => \'<= CAST( NOW() AS DATE )',
332 waitingdate => { '!=', undef }
336 order_by => 'priority',
344 $r->get_column('borrowernumber'),
345 $r->get_column('branchcode'),
351 =head2 GetReservesFromBorrowernumber
353 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
359 sub GetReservesFromBorrowernumber {
360 my ( $borrowernumber, $status ) = @_;
361 my $dbh = C4::Context->dbh;
364 $sth = $dbh->prepare("
367 WHERE borrowernumber=?
371 $sth->execute($borrowernumber,$status);
373 $sth = $dbh->prepare("
376 WHERE borrowernumber=?
379 $sth->execute($borrowernumber);
381 my $data = $sth->fetchall_arrayref({});
385 =head2 CanBookBeReserved
387 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
388 if ($canReserve eq 'OK') { #We can reserve this Item! }
390 See CanItemBeReserved() for possible return values.
394 sub CanBookBeReserved{
395 my ($borrowernumber, $biblionumber) = @_;
397 my $items = GetItemnumbersForBiblio($biblionumber);
398 #get items linked via host records
399 my @hostitems = get_hostitemnumbers_of($biblionumber);
401 push (@$items,@hostitems);
405 foreach my $item (@$items) {
406 $canReserve = CanItemBeReserved( $borrowernumber, $item );
407 return 'OK' if $canReserve eq 'OK';
412 =head2 CanItemBeReserved
414 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
415 if ($canReserve eq 'OK') { #We can reserve this Item! }
417 @RETURNS OK, if the Item can be reserved.
418 ageRestricted, if the Item is age restricted for this borrower.
419 damaged, if the Item is damaged.
420 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
421 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
422 notReservable, if holds on this item are not allowed
426 sub CanItemBeReserved{
427 my ($borrowernumber, $itemnumber) = @_;
429 my $dbh = C4::Context->dbh;
430 my $ruleitemtype; # itemtype of the matching issuing rule
431 my $allowedreserves = 0;
433 # we retrieve borrowers and items informations #
434 # item->{itype} will come for biblioitems if necessery
435 my $item = GetItem($itemnumber);
436 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
437 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
439 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
440 return 'damaged' if ( $item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems') );
442 #Check for the age restriction
443 my ($ageRestriction, $daysToAgeRestriction) = C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
444 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
446 my $controlbranch = C4::Context->preference('ReservesControlBranch');
448 # we retrieve user rights on this itemtype and branchcode
449 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
451 WHERE (categorycode in (?,'*') )
452 AND (itemtype IN (?,'*'))
453 AND (branchcode IN (?,'*'))
460 my $querycount ="SELECT
463 LEFT JOIN items USING (itemnumber)
464 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
465 LEFT JOIN borrowers USING (borrowernumber)
466 WHERE borrowernumber = ?
471 my $branchfield = "reserves.branchcode";
473 if( $controlbranch eq "ItemHomeLibrary" ){
474 $branchfield = "items.homebranch";
475 $branchcode = $item->{homebranch};
476 }elsif( $controlbranch eq "PatronLibrary" ){
477 $branchfield = "borrowers.branchcode";
478 $branchcode = $borrower->{branchcode};
482 $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
483 if(my $rights = $sth->fetchrow_hashref()){
484 $ruleitemtype = $rights->{itemtype};
485 $allowedreserves = $rights->{reservesallowed};
492 $querycount .= "AND $branchfield = ?";
494 # If using item-level itypes, fall back to the record
495 # level itemtype if the hold has no associated item
497 C4::Context->preference('item-level_itypes')
498 ? " AND COALESCE( itype, itemtype ) = ?"
499 : " AND itemtype = ?"
500 if ( $ruleitemtype ne "*" );
502 my $sthcount = $dbh->prepare($querycount);
504 if($ruleitemtype eq "*"){
505 $sthcount->execute($borrowernumber, $branchcode);
507 $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
510 my $reservecount = "0";
511 if(my $rowcount = $sthcount->fetchrow_hashref()){
512 $reservecount = $rowcount->{count};
514 # we check if it's ok or not
515 if( $reservecount >= $allowedreserves ){
516 return 'tooManyReserves';
519 my $circ_control_branch = C4::Circulation::_GetCircControlBranch($item,
521 my $branchitemrule = C4::Circulation::GetBranchItemRule($circ_control_branch,
524 if ( $branchitemrule->{holdallowed} == 0 ) {
525 return 'notReservable';
528 if ( $branchitemrule->{holdallowed} == 1
529 && $borrower->{branchcode} ne $item->{homebranch} )
531 return 'cannotReserveFromOtherBranches';
534 # If reservecount is ok, we check item branch if IndependentBranches is ON
535 # and canreservefromotherbranches is OFF
536 if ( C4::Context->preference('IndependentBranches')
537 and !C4::Context->preference('canreservefromotherbranches') )
539 my $itembranch = $item->{homebranch};
540 if ($itembranch ne $borrower->{branchcode}) {
541 return 'cannotReserveFromOtherBranches';
548 =head2 CanReserveBeCanceledFromOpac
550 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
552 returns 1 if reserve can be cancelled by user from OPAC.
553 First check if reserve belongs to user, next checks if reserve is not in
554 transfer or waiting status
558 sub CanReserveBeCanceledFromOpac {
559 my ($reserve_id, $borrowernumber) = @_;
561 return unless $reserve_id and $borrowernumber;
562 my $reserve = GetReserve($reserve_id);
564 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
565 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
571 =head2 GetReserveCount
573 $number = &GetReserveCount($borrowernumber);
575 this function returns the number of reservation for a borrower given on input arg.
579 sub GetReserveCount {
580 my ($borrowernumber) = @_;
582 my $dbh = C4::Context->dbh;
585 SELECT COUNT(*) AS counter
587 WHERE borrowernumber = ?
589 my $sth = $dbh->prepare($query);
590 $sth->execute($borrowernumber);
591 my $row = $sth->fetchrow_hashref;
592 return $row->{counter};
595 =head2 GetOtherReserves
597 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
599 Check queued list of this document and check if this document must be transferred
603 sub GetOtherReserves {
604 my ($itemnumber) = @_;
607 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
608 if ($checkreserves) {
609 my $iteminfo = GetItem($itemnumber);
610 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
611 $messages->{'transfert'} = $checkreserves->{'branchcode'};
612 #minus priorities of others reservs
613 ModReserveMinusPriority(
615 $checkreserves->{'reserve_id'},
618 #launch the subroutine dotransfer
619 C4::Items::ModItemTransfer(
621 $iteminfo->{'holdingbranch'},
622 $checkreserves->{'branchcode'}
627 #step 2b : case of a reservation on the same branch, set the waiting status
629 $messages->{'waiting'} = 1;
630 ModReserveMinusPriority(
632 $checkreserves->{'reserve_id'},
634 ModReserveStatus($itemnumber,'W');
637 $nextreservinfo = $checkreserves->{'borrowernumber'};
640 return ( $messages, $nextreservinfo );
643 =head2 ChargeReserveFee
645 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
647 Charge the fee for a reserve (if $fee > 0)
651 sub ChargeReserveFee {
652 my ( $borrowernumber, $fee, $title ) = @_;
655 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
657 my $dbh = C4::Context->dbh;
658 my $nextacctno = &getnextacctno( $borrowernumber );
659 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
664 $fee = GetReserveFee( $borrowernumber, $biblionumber );
666 Calculate the fee for a reserve (if applicable).
671 my ( $borrowernumber, $biblionumber ) = @_;
673 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
676 my $dbh = C4::Context->dbh;
677 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
678 if( $fee && $fee > 0 ) {
679 # This is a reconstruction of the old code:
680 # Calculate number of items, items issued and holds
681 my ( $cnt1 ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM items WHERE biblionumber=?", undef, ( $biblionumber ) );
682 my ( $cnt2 ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM issues LEFT JOIN items USING (itemnumber) WHERE biblionumber=?", undef, ( $biblionumber ));
683 my ( $cnt3 ) = $dbh->selectrow_array( "SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?", undef, ( $biblionumber, $borrowernumber ) );
684 # If not all items are issued and there are no holds: charge no fee
685 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
686 $fee = 0 if $cnt1 - $cnt2 > 0 && $cnt3 == 0;
691 =head2 GetReservesToBranch
693 @transreserv = GetReservesToBranch( $frombranch );
695 Get reserve list for a given branch
699 sub GetReservesToBranch {
700 my ( $frombranch ) = @_;
701 my $dbh = C4::Context->dbh;
702 my $sth = $dbh->prepare(
703 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
708 $sth->execute( $frombranch );
711 while ( my $data = $sth->fetchrow_hashref ) {
712 $transreserv[$i] = $data;
715 return (@transreserv);
718 =head2 GetReservesForBranch
720 @transreserv = GetReservesForBranch($frombranch);
724 sub GetReservesForBranch {
725 my ($frombranch) = @_;
726 my $dbh = C4::Context->dbh;
729 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
734 $query .= " AND branchcode=? " if ( $frombranch );
735 $query .= "ORDER BY waitingdate" ;
737 my $sth = $dbh->prepare($query);
739 $sth->execute($frombranch);
746 while ( my $data = $sth->fetchrow_hashref ) {
747 $transreserv[$i] = $data;
750 return (@transreserv);
753 =head2 GetReserveStatus
755 $reservestatus = GetReserveStatus($itemnumber);
757 Takes an itemnumber and returns the status of the reserve placed on it.
758 If several reserves exist, the reserve with the lower priority is given.
762 ## FIXME: I don't think this does what it thinks it does.
763 ## It only ever checks the first reserve result, even though
764 ## multiple reserves for that bib can have the itemnumber set
765 ## the sub is only used once in the codebase.
766 sub GetReserveStatus {
767 my ($itemnumber) = @_;
769 my $dbh = C4::Context->dbh;
771 my ($sth, $found, $priority);
773 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
774 $sth->execute($itemnumber);
775 ($found, $priority) = $sth->fetchrow_array;
779 return 'Waiting' if $found eq 'W' and $priority == 0;
780 return 'Finished' if $found eq 'F';
783 return 'Reserved' if $priority > 0;
785 return ''; # empty string here will remove need for checking undef, or less log lines
790 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
791 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
792 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
794 Find a book in the reserves.
796 C<$itemnumber> is the book's item number.
797 C<$lookahead> is the number of days to look in advance for future reserves.
799 As I understand it, C<&CheckReserves> looks for the given item in the
800 reserves. If it is found, that's a match, and C<$status> is set to
803 Otherwise, it finds the most important item in the reserves with the
804 same biblio number as this book (I'm not clear on this) and returns it
805 with C<$status> set to C<Reserved>.
807 C<&CheckReserves> returns a two-element list:
809 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
811 C<$reserve> is the reserve item that matched. It is a
812 reference-to-hash whose keys are mostly the fields of the reserves
813 table in the Koha database.
818 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
819 my $dbh = C4::Context->dbh;
822 if (C4::Context->preference('item-level_itypes')){
824 SELECT items.biblionumber,
825 items.biblioitemnumber,
826 itemtypes.notforloan,
827 items.notforloan AS itemnotforloan,
833 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
834 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
839 SELECT items.biblionumber,
840 items.biblioitemnumber,
841 itemtypes.notforloan,
842 items.notforloan AS itemnotforloan,
848 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
849 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
854 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
855 $sth->execute($item);
858 $sth = $dbh->prepare("$select WHERE barcode = ?");
859 $sth->execute($barcode);
861 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
862 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
864 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
866 return unless $itemnumber; # bail if we got nothing.
868 # if item is not for loan it cannot be reserved either.....
869 # except where items.notforloan < 0 : This indicates the item is holdable.
870 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
872 # Find this item in the reserves
873 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
875 # $priority and $highest are used to find the most important item
876 # in the list returned by &_Findgroupreserve. (The lower $priority,
877 # the more important the item.)
878 # $highest is the most important item we've seen so far.
880 if (scalar @reserves) {
881 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
882 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
883 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
885 my $priority = 10000000;
886 foreach my $res (@reserves) {
887 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
888 return ( "Waiting", $res, \@reserves ); # Found it
892 my $local_hold_match;
894 if ($LocalHoldsPriority) {
895 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
896 $iteminfo = C4::Items::GetItem($itemnumber);
898 my $local_holds_priority_item_branchcode =
899 $iteminfo->{$LocalHoldsPriorityItemControl};
900 my $local_holds_priority_patron_branchcode =
901 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
903 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
904 ? $borrowerinfo->{branchcode}
907 $local_holds_priority_item_branchcode eq
908 $local_holds_priority_patron_branchcode;
911 # See if this item is more important than what we've got so far
912 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
913 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
914 $iteminfo ||= C4::Items::GetItem($itemnumber);
915 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
916 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
917 next if ($branchitemrule->{'holdallowed'} == 0);
918 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
919 $priority = $res->{'priority'};
921 last if $local_hold_match;
927 # If we get this far, then no exact match was found.
928 # We return the most important (i.e. next) reservation.
930 $highest->{'itemnumber'} = $item;
931 return ( "Reserved", $highest, \@reserves );
937 =head2 CancelExpiredReserves
939 CancelExpiredReserves();
941 Cancels all reserves with an expiration date from before today.
945 sub CancelExpiredReserves {
947 # Cancel reserves that have passed their expiration date.
948 my $dbh = C4::Context->dbh;
949 my $sth = $dbh->prepare( "
950 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
951 AND expirationdate IS NOT NULL
956 while ( my $res = $sth->fetchrow_hashref() ) {
957 CancelReserve({ reserve_id => $res->{'reserve_id'} });
960 # Cancel reserves that have been waiting too long
961 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
962 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
963 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
965 my $today = dt_from_string();
967 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
968 $sth = $dbh->prepare( $query );
969 $sth->execute( $max_pickup_delay );
971 while ( my $res = $sth->fetchrow_hashref ) {
973 unless ( $cancel_on_holidays ) {
974 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
975 my $is_holiday = $calendar->is_holiday( $today );
983 CancelReserve({ reserve_id => $res->{'reserve_id'}, charge_cancel_fee => 1 });
990 =head2 AutoUnsuspendReserves
992 AutoUnsuspendReserves();
994 Unsuspends all suspended reserves with a suspend_until date from before today.
998 sub AutoUnsuspendReserves {
1000 my $dbh = C4::Context->dbh;
1002 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
1003 my $sth = $dbh->prepare( $query );
1008 =head2 CancelReserve
1010 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
1012 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.
1017 my ( $params ) = @_;
1019 my $reserve_id = $params->{'reserve_id'};
1020 # Filter out only the desired keys; this will insert undefined values for elements missing in
1021 # \%params, but GetReserveId filters them out anyway.
1022 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
1024 return unless ( $reserve_id );
1026 my $dbh = C4::Context->dbh;
1028 my $reserve = GetReserve( $reserve_id );
1032 SET cancellationdate = now(),
1035 WHERE reserve_id = ?
1037 my $sth = $dbh->prepare($query);
1038 $sth->execute( $reserve_id );
1041 INSERT INTO old_reserves
1042 SELECT * FROM reserves
1043 WHERE reserve_id = ?
1045 $sth = $dbh->prepare($query);
1046 $sth->execute( $reserve_id );
1049 DELETE FROM reserves
1050 WHERE reserve_id = ?
1052 $sth = $dbh->prepare($query);
1053 $sth->execute( $reserve_id );
1055 # now fix the priority on the others....
1056 _FixPriority({ biblionumber => $reserve->{biblionumber} });
1058 # and, if desired, charge a cancel fee
1059 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
1060 if ( $charge && $params->{'charge_cancel_fee'} ) {
1061 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
1070 ModReserve({ rank => $rank,
1071 reserve_id => $reserve_id,
1072 branchcode => $branchcode
1073 [, itemnumber => $itemnumber ]
1074 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1077 Change a hold request's priority or cancel it.
1079 C<$rank> specifies the effect of the change. If C<$rank>
1080 is 'W' or 'n', nothing happens. This corresponds to leaving a
1081 request alone when changing its priority in the holds queue
1084 If C<$rank> is 'del', the hold request is cancelled.
1086 If C<$rank> is an integer greater than zero, the priority of
1087 the request is set to that value. Since priority != 0 means
1088 that the item is not waiting on the hold shelf, setting the
1089 priority to a non-zero value also sets the request's found
1090 status and waiting date to NULL.
1092 The optional C<$itemnumber> parameter is used only when
1093 C<$rank> is a non-zero integer; if supplied, the itemnumber
1094 of the hold request is set accordingly; if omitted, the itemnumber
1097 B<FIXME:> Note that the forgoing can have the effect of causing
1098 item-level hold requests to turn into title-level requests. This
1099 will be fixed once reserves has separate columns for requested
1100 itemnumber and supplying itemnumber.
1105 my ( $params ) = @_;
1107 my $rank = $params->{'rank'};
1108 my $reserve_id = $params->{'reserve_id'};
1109 my $branchcode = $params->{'branchcode'};
1110 my $itemnumber = $params->{'itemnumber'};
1111 my $suspend_until = $params->{'suspend_until'};
1112 my $borrowernumber = $params->{'borrowernumber'};
1113 my $biblionumber = $params->{'biblionumber'};
1115 return if $rank eq "W";
1116 return if $rank eq "n";
1118 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1119 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1121 my $dbh = C4::Context->dbh;
1122 if ( $rank eq "del" ) {
1123 CancelReserve({ reserve_id => $reserve_id });
1125 elsif ($rank =~ /^\d+/ and $rank > 0) {
1127 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1128 WHERE reserve_id = ?
1130 my $sth = $dbh->prepare($query);
1131 $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
1133 if ( defined( $suspend_until ) ) {
1134 if ( $suspend_until ) {
1135 $suspend_until = C4::Dates->new( $suspend_until )->output("iso");
1136 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
1138 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
1142 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1146 =head2 ModReserveFill
1148 &ModReserveFill($reserve);
1150 Fill a reserve. If I understand this correctly, this means that the
1151 reserved book has been found and given to the patron who reserved it.
1153 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1154 whose keys are fields from the reserves table in the Koha database.
1158 sub ModReserveFill {
1160 my $dbh = C4::Context->dbh;
1161 # fill in a reserve record....
1162 my $reserve_id = $res->{'reserve_id'};
1163 my $biblionumber = $res->{'biblionumber'};
1164 my $borrowernumber = $res->{'borrowernumber'};
1165 my $resdate = $res->{'reservedate'};
1167 # get the priority on this record....
1169 my $query = "SELECT priority
1171 WHERE biblionumber = ?
1172 AND borrowernumber = ?
1173 AND reservedate = ?";
1174 my $sth = $dbh->prepare($query);
1175 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1176 ($priority) = $sth->fetchrow_array;
1178 # update the database...
1179 $query = "UPDATE reserves
1182 WHERE biblionumber = ?
1184 AND borrowernumber = ?
1186 $sth = $dbh->prepare($query);
1187 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1189 # move to old_reserves
1190 $query = "INSERT INTO old_reserves
1191 SELECT * FROM reserves
1192 WHERE biblionumber = ?
1194 AND borrowernumber = ?
1196 $sth = $dbh->prepare($query);
1197 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1198 $query = "DELETE FROM reserves
1199 WHERE biblionumber = ?
1201 AND borrowernumber = ?
1203 $sth = $dbh->prepare($query);
1204 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1206 # now fix the priority on the others (if the priority wasn't
1207 # already sorted!)....
1208 unless ( $priority == 0 ) {
1209 _FixPriority({ reserve_id => $reserve_id, biblionumber => $biblionumber });
1213 =head2 ModReserveStatus
1215 &ModReserveStatus($itemnumber, $newstatus);
1217 Update the reserve status for the active (priority=0) reserve.
1219 $itemnumber is the itemnumber the reserve is on
1221 $newstatus is the new status.
1225 sub ModReserveStatus {
1227 #first : check if we have a reservation for this item .
1228 my ($itemnumber, $newstatus) = @_;
1229 my $dbh = C4::Context->dbh;
1231 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1232 my $sth_set = $dbh->prepare($query);
1233 $sth_set->execute( $newstatus, $itemnumber );
1235 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1236 CartToShelf( $itemnumber );
1240 =head2 ModReserveAffect
1242 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1244 This function affect an item and a status for a given reserve
1245 The itemnumber parameter is used to find the biblionumber.
1246 with the biblionumber & the borrowernumber, we can affect the itemnumber
1247 to the correct reserve.
1249 if $transferToDo is not set, then the status is set to "Waiting" as well.
1250 otherwise, a transfer is on the way, and the end of the transfer will
1251 take care of the waiting status
1255 sub ModReserveAffect {
1256 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1257 my $dbh = C4::Context->dbh;
1259 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1260 # attached to $itemnumber
1261 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1262 $sth->execute($itemnumber);
1263 my ($biblionumber) = $sth->fetchrow;
1265 # get request - need to find out if item is already
1266 # waiting in order to not send duplicate hold filled notifications
1267 my $reserve_id = GetReserveId({
1268 borrowernumber => $borrowernumber,
1269 biblionumber => $biblionumber,
1271 return unless defined $reserve_id;
1272 my $request = GetReserveInfo($reserve_id);
1273 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1275 # If we affect a reserve that has to be transferred, don't set to Waiting
1277 if ($transferToDo) {
1283 WHERE borrowernumber = ?
1284 AND biblionumber = ?
1288 # affect the reserve to Waiting as well.
1293 waitingdate = NOW(),
1295 WHERE borrowernumber = ?
1296 AND biblionumber = ?
1299 $sth = $dbh->prepare($query);
1300 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1301 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1302 _FixPriority( { biblionumber => $biblionumber } );
1303 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1304 CartToShelf( $itemnumber );
1310 =head2 ModReserveCancelAll
1312 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1314 function to cancel reserv,check other reserves, and transfer document if it's necessary
1318 sub ModReserveCancelAll {
1321 my ( $itemnumber, $borrowernumber ) = @_;
1323 #step 1 : cancel the reservation
1324 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1326 #step 2 launch the subroutine of the others reserves
1327 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1329 return ( $messages, $nextreservinfo );
1332 =head2 ModReserveMinusPriority
1334 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1336 Reduce the values of queued list
1340 sub ModReserveMinusPriority {
1341 my ( $itemnumber, $reserve_id ) = @_;
1343 #first step update the value of the first person on reserv
1344 my $dbh = C4::Context->dbh;
1347 SET priority = 0 , itemnumber = ?
1348 WHERE reserve_id = ?
1350 my $sth_upd = $dbh->prepare($query);
1351 $sth_upd->execute( $itemnumber, $reserve_id );
1352 # second step update all others reserves
1353 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1356 =head2 GetReserveInfo
1358 &GetReserveInfo($reserve_id);
1360 Get item and borrower details for a current hold.
1361 Current implementation this query should have a single result.
1365 sub GetReserveInfo {
1366 my ( $reserve_id ) = @_;
1367 my $dbh = C4::Context->dbh;
1372 reserves.borrowernumber,
1373 reserves.biblionumber,
1374 reserves.branchcode,
1375 reserves.waitingdate,
1391 items.holdingbranch,
1392 items.itemcallnumber,
1398 LEFT JOIN items USING(itemnumber)
1399 LEFT JOIN borrowers USING(borrowernumber)
1400 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1401 WHERE reserves.reserve_id = ?";
1402 my $sth = $dbh->prepare($strsth);
1403 $sth->execute($reserve_id);
1405 my $data = $sth->fetchrow_hashref;
1409 =head2 IsAvailableForItemLevelRequest
1411 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1413 Checks whether a given item record is available for an
1414 item-level hold request. An item is available if
1416 * it is not lost AND
1417 * it is not damaged AND
1418 * it is not withdrawn AND
1419 * does not have a not for loan value > 0
1421 Need to check the issuingrules onshelfholds column,
1422 if this is set items on the shelf can be placed on hold
1424 Note that IsAvailableForItemLevelRequest() does not
1425 check if the staff operator is authorized to place
1426 a request on the item - in particular,
1427 this routine does not check IndependentBranches
1428 and canreservefromotherbranches.
1432 sub IsAvailableForItemLevelRequest {
1434 my $borrower = shift;
1436 my $dbh = C4::Context->dbh;
1437 # must check the notforloan setting of the itemtype
1438 # FIXME - a lot of places in the code do this
1439 # or something similar - need to be
1441 my $itype = _get_itype($item);
1442 my $notforloan_per_itemtype
1443 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1447 $notforloan_per_itemtype ||
1448 $item->{itemlost} ||
1449 $item->{notforloan} > 0 ||
1450 $item->{withdrawn} ||
1451 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1454 return 1 if _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1456 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1459 =head2 OnShelfHoldsAllowed
1461 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1463 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1464 holds are allowed, returns true if so.
1468 sub OnShelfHoldsAllowed {
1469 my ($item, $borrower) = @_;
1471 my $itype = _get_itype($item);
1472 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1479 if (C4::Context->preference('item-level_itypes')) {
1480 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1481 # When GetItem is fixed, we can remove this
1482 $itype = $item->{itype};
1485 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1486 # So if we already have a biblioitems join when calling this function,
1487 # we don't need to access the database again
1488 $itype = $item->{itemtype};
1491 my $dbh = C4::Context->dbh;
1492 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1493 my $sth = $dbh->prepare($query);
1494 $sth->execute($item->{biblioitemnumber});
1495 if (my $data = $sth->fetchrow_hashref()){
1496 $itype = $data->{itemtype};
1502 sub _OnShelfHoldsAllowed {
1503 my ($itype,$borrowercategory,$branchcode) = @_;
1505 my $rule = C4::Circulation::GetIssuingRule($borrowercategory, $itype, $branchcode);
1506 return $rule->{onshelfholds};
1509 =head2 AlterPriority
1511 AlterPriority( $where, $reserve_id );
1513 This function changes a reserve's priority up, down, to the top, or to the bottom.
1514 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1519 my ( $where, $reserve_id ) = @_;
1521 my $dbh = C4::Context->dbh;
1523 my $reserve = GetReserve( $reserve_id );
1525 if ( $reserve->{cancellationdate} ) {
1526 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1530 if ( $where eq 'up' || $where eq 'down' ) {
1532 my $priority = $reserve->{'priority'};
1533 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1534 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1536 } elsif ( $where eq 'top' ) {
1538 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1540 } elsif ( $where eq 'bottom' ) {
1542 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1547 =head2 ToggleLowestPriority
1549 ToggleLowestPriority( $borrowernumber, $biblionumber );
1551 This function sets the lowestPriority field to true if is false, and false if it is true.
1555 sub ToggleLowestPriority {
1556 my ( $reserve_id ) = @_;
1558 my $dbh = C4::Context->dbh;
1560 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1561 $sth->execute( $reserve_id );
1563 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1566 =head2 ToggleSuspend
1568 ToggleSuspend( $reserve_id );
1570 This function sets the suspend field to true if is false, and false if it is true.
1571 If the reserve is currently suspended with a suspend_until date, that date will
1572 be cleared when it is unsuspended.
1577 my ( $reserve_id, $suspend_until ) = @_;
1579 $suspend_until = output_pref(
1581 dt => dt_from_string($suspend_until),
1582 dateformat => 'iso',
1585 ) if ($suspend_until);
1587 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1589 my $dbh = C4::Context->dbh;
1591 my $sth = $dbh->prepare(
1592 "UPDATE reserves SET suspend = NOT suspend,
1593 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1594 WHERE reserve_id = ?
1598 push( @params, $suspend_until ) if ( $suspend_until );
1599 push( @params, $reserve_id );
1601 $sth->execute( @params );
1607 borrowernumber => $borrowernumber,
1608 [ biblionumber => $biblionumber, ]
1609 [ suspend_until => $suspend_until, ]
1610 [ suspend => $suspend ]
1613 This function accepts a set of hash keys as its parameters.
1614 It requires either borrowernumber or biblionumber, or both.
1616 suspend_until is wholly optional.
1623 my $borrowernumber = $params{'borrowernumber'} || undef;
1624 my $biblionumber = $params{'biblionumber'} || undef;
1625 my $suspend_until = $params{'suspend_until'} || undef;
1626 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1628 $suspend_until = C4::Dates->new( $suspend_until )->output("iso") if ( defined( $suspend_until ) );
1630 return unless ( $borrowernumber || $biblionumber );
1632 my ( $query, $sth, $dbh, @query_params );
1634 $query = "UPDATE reserves SET suspend = ? ";
1635 push( @query_params, $suspend );
1637 $query .= ", suspend_until = NULL ";
1638 } elsif ( $suspend_until ) {
1639 $query .= ", suspend_until = ? ";
1640 push( @query_params, $suspend_until );
1642 $query .= " WHERE ";
1643 if ( $borrowernumber ) {
1644 $query .= " borrowernumber = ? ";
1645 push( @query_params, $borrowernumber );
1647 $query .= " AND " if ( $borrowernumber && $biblionumber );
1648 if ( $biblionumber ) {
1649 $query .= " biblionumber = ? ";
1650 push( @query_params, $biblionumber );
1652 $query .= " AND found IS NULL ";
1654 $dbh = C4::Context->dbh;
1655 $sth = $dbh->prepare( $query );
1656 $sth->execute( @query_params );
1663 reserve_id => $reserve_id,
1665 [ignoreSetLowestRank => $ignoreSetLowestRank]
1670 _FixPriority({ biblionumber => $biblionumber});
1672 This routine adjusts the priority of a hold request and holds
1675 In the first form, where a reserve_id is passed, the priority of the
1676 hold is set to supplied rank, and other holds for that bib are adjusted
1677 accordingly. If the rank is "del", the hold is cancelled. If no rank
1678 is supplied, all of the holds on that bib have their priority adjusted
1679 as if the second form had been used.
1681 In the second form, where a biblionumber is passed, the holds on that
1682 bib (that are not captured) are sorted in order of increasing priority,
1683 then have reserves.priority set so that the first non-captured hold
1684 has its priority set to 1, the second non-captured hold has its priority
1685 set to 2, and so forth.
1687 In both cases, holds that have the lowestPriority flag on are have their
1688 priority adjusted to ensure that they remain at the end of the line.
1690 Note that the ignoreSetLowestRank parameter is meant to be used only
1691 when _FixPriority calls itself.
1696 my ( $params ) = @_;
1697 my $reserve_id = $params->{reserve_id};
1698 my $rank = $params->{rank} // '';
1699 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1700 my $biblionumber = $params->{biblionumber};
1702 my $dbh = C4::Context->dbh;
1704 unless ( $biblionumber ) {
1705 my $res = GetReserve( $reserve_id );
1706 $biblionumber = $res->{biblionumber};
1709 if ( $rank eq "del" ) {
1710 CancelReserve({ reserve_id => $reserve_id });
1712 elsif ( $rank eq "W" || $rank eq "0" ) {
1714 # make sure priority for waiting or in-transit items is 0
1718 WHERE reserve_id = ?
1719 AND found IN ('W', 'T')
1721 my $sth = $dbh->prepare($query);
1722 $sth->execute( $reserve_id );
1728 SELECT reserve_id, borrowernumber, reservedate
1730 WHERE biblionumber = ?
1731 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1732 ORDER BY priority ASC
1734 my $sth = $dbh->prepare($query);
1735 $sth->execute( $biblionumber );
1736 while ( my $line = $sth->fetchrow_hashref ) {
1737 push( @priority, $line );
1740 # To find the matching index
1742 my $key = -1; # to allow for 0 to be a valid result
1743 for ( $i = 0 ; $i < @priority ; $i++ ) {
1744 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1745 $key = $i; # save the index
1750 # if index exists in array then move it to new position
1751 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1752 my $new_rank = $rank -
1753 1; # $new_rank is what you want the new index to be in the array
1754 my $moving_item = splice( @priority, $key, 1 );
1755 splice( @priority, $new_rank, 0, $moving_item );
1758 # now fix the priority on those that are left....
1762 WHERE reserve_id = ?
1764 $sth = $dbh->prepare($query);
1765 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1768 $priority[$j]->{'reserve_id'}
1772 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1775 unless ( $ignoreSetLowestRank ) {
1776 while ( my $res = $sth->fetchrow_hashref() ) {
1778 reserve_id => $res->{'reserve_id'},
1780 ignoreSetLowestRank => 1
1786 =head2 _Findgroupreserve
1788 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1790 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1791 first match found. If neither, then we look for non-holds-queue based holds.
1792 Lookahead is the number of days to look in advance.
1794 C<&_Findgroupreserve> returns :
1795 C<@results> is an array of references-to-hash whose keys are mostly
1796 fields from the reserves table of the Koha database, plus
1797 C<biblioitemnumber>.
1801 sub _Findgroupreserve {
1802 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1803 my $dbh = C4::Context->dbh;
1805 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1806 # check for exact targeted match
1807 my $item_level_target_query = qq{
1808 SELECT reserves.biblionumber AS biblionumber,
1809 reserves.borrowernumber AS borrowernumber,
1810 reserves.reservedate AS reservedate,
1811 reserves.branchcode AS branchcode,
1812 reserves.cancellationdate AS cancellationdate,
1813 reserves.found AS found,
1814 reserves.reservenotes AS reservenotes,
1815 reserves.priority AS priority,
1816 reserves.timestamp AS timestamp,
1817 biblioitems.biblioitemnumber AS biblioitemnumber,
1818 reserves.itemnumber AS itemnumber,
1819 reserves.reserve_id AS reserve_id
1821 JOIN biblioitems USING (biblionumber)
1822 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1825 AND item_level_request = 1
1827 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1831 my $sth = $dbh->prepare($item_level_target_query);
1832 $sth->execute($itemnumber, $lookahead||0);
1834 if ( my $data = $sth->fetchrow_hashref ) {
1835 push( @results, $data )
1836 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1838 return @results if @results;
1840 # check for title-level targeted match
1841 my $title_level_target_query = qq{
1842 SELECT reserves.biblionumber AS biblionumber,
1843 reserves.borrowernumber AS borrowernumber,
1844 reserves.reservedate AS reservedate,
1845 reserves.branchcode AS branchcode,
1846 reserves.cancellationdate AS cancellationdate,
1847 reserves.found AS found,
1848 reserves.reservenotes AS reservenotes,
1849 reserves.priority AS priority,
1850 reserves.timestamp AS timestamp,
1851 biblioitems.biblioitemnumber AS biblioitemnumber,
1852 reserves.itemnumber AS itemnumber,
1853 reserves.reserve_id AS reserve_id
1855 JOIN biblioitems USING (biblionumber)
1856 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1859 AND item_level_request = 0
1860 AND hold_fill_targets.itemnumber = ?
1861 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1865 $sth = $dbh->prepare($title_level_target_query);
1866 $sth->execute($itemnumber, $lookahead||0);
1868 if ( my $data = $sth->fetchrow_hashref ) {
1869 push( @results, $data )
1870 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1872 return @results if @results;
1875 SELECT reserves.biblionumber AS biblionumber,
1876 reserves.borrowernumber AS borrowernumber,
1877 reserves.reservedate AS reservedate,
1878 reserves.waitingdate AS waitingdate,
1879 reserves.branchcode AS branchcode,
1880 reserves.cancellationdate AS cancellationdate,
1881 reserves.found AS found,
1882 reserves.reservenotes AS reservenotes,
1883 reserves.priority AS priority,
1884 reserves.timestamp AS timestamp,
1885 reserves.itemnumber AS itemnumber,
1886 reserves.reserve_id AS reserve_id
1888 WHERE reserves.biblionumber = ?
1889 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1890 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1894 $sth = $dbh->prepare($query);
1895 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1897 while ( my $data = $sth->fetchrow_hashref ) {
1898 push( @results, $data )
1899 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1904 =head2 _koha_notify_reserve
1906 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1908 Sends a notification to the patron that their hold has been filled (through
1909 ModReserveAffect, _not_ ModReserveFill)
1913 sub _koha_notify_reserve {
1914 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1916 my $dbh = C4::Context->dbh;
1917 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1919 # Try to get the borrower's email address
1920 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1922 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1923 borrowernumber => $borrowernumber,
1924 message_name => 'Hold_Filled'
1927 my $sth = $dbh->prepare("
1930 WHERE borrowernumber = ?
1931 AND biblionumber = ?
1933 $sth->execute( $borrowernumber, $biblionumber );
1934 my $reserve = $sth->fetchrow_hashref;
1935 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1937 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1939 my %letter_params = (
1940 module => 'reserves',
1941 branchcode => $reserve->{branchcode},
1943 'branches' => $branch_details,
1944 'borrowers' => $borrower,
1945 'biblio' => $biblionumber,
1946 'reserves' => $reserve,
1947 'items', $reserve->{'itemnumber'},
1949 substitute => { today => C4::Dates->new()->output() },
1952 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.
1953 my $send_notification = sub {
1954 my ( $mtt, $letter_code ) = (@_);
1955 return unless defined $letter_code;
1956 $letter_params{letter_code} = $letter_code;
1957 $letter_params{message_transport_type} = $mtt;
1958 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1960 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1964 C4::Letters::EnqueueLetter( {
1966 borrowernumber => $borrowernumber,
1967 from_address => $admin_email_address,
1968 message_transport_type => $mtt,
1972 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1974 ( $mtt eq 'email' and not $to_address ) # No email address
1975 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
1976 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1979 &$send_notification($mtt, $letter_code);
1980 $notification_sent++;
1982 #Making sure that a print notification is sent if no other transport types can be utilized.
1983 if (! $notification_sent) {
1984 &$send_notification('print', 'HOLD');
1989 =head2 _ShiftPriorityByDateAndPriority
1991 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1993 This increments the priority of all reserves after the one
1994 with either the lowest date after C<$reservedate>
1995 or the lowest priority after C<$priority>.
1997 It effectively makes room for a new reserve to be inserted with a certain
1998 priority, which is returned.
2000 This is most useful when the reservedate can be set by the user. It allows
2001 the new reserve to be placed before other reserves that have a later
2002 reservedate. Since priority also is set by the form in reserves/request.pl
2003 the sub accounts for that too.
2007 sub _ShiftPriorityByDateAndPriority {
2008 my ( $biblio, $resdate, $new_priority ) = @_;
2010 my $dbh = C4::Context->dbh;
2011 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2012 my $sth = $dbh->prepare( $query );
2013 $sth->execute( $biblio, $resdate, $new_priority );
2014 my $min_priority = $sth->fetchrow;
2015 # if no such matches are found, $new_priority remains as original value
2016 $new_priority = $min_priority if ( $min_priority );
2018 # Shift the priority up by one; works in conjunction with the next SQL statement
2019 $query = "UPDATE reserves
2020 SET priority = priority+1
2021 WHERE biblionumber = ?
2022 AND borrowernumber = ?
2025 my $sth_update = $dbh->prepare( $query );
2027 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2028 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2029 $sth = $dbh->prepare( $query );
2030 $sth->execute( $new_priority, $biblio );
2031 while ( my $row = $sth->fetchrow_hashref ) {
2032 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2035 return $new_priority; # so the caller knows what priority they wind up receiving
2038 =head2 OPACItemHoldsAllowed
2040 OPACItemHoldsAllowed($item_record,$borrower_record);
2042 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
2043 if specific item holds are allowed, returns true if so.
2047 sub OPACItemHoldsAllowed {
2048 my ($item,$borrower) = @_;
2050 my $branchcode = $item->{homebranch} or die "No homebranch";
2052 my $dbh = C4::Context->dbh;
2053 if (C4::Context->preference('item-level_itypes')) {
2054 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
2055 # When GetItem is fixed, we can remove this
2056 $itype = $item->{itype};
2059 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
2060 my $sth = $dbh->prepare($query);
2061 $sth->execute($item->{biblioitemnumber});
2062 if (my $data = $sth->fetchrow_hashref()){
2063 $itype = $data->{itemtype};
2067 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
2068 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
2070 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2072 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
2074 issuingrules.categorycode desc,
2075 issuingrules.itemtype desc,
2076 issuingrules.branchcode desc
2078 my $sth = $dbh->prepare($query);
2079 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2080 my $data = $sth->fetchrow_hashref;
2081 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2082 return '' if $opacitemholds eq 'N';
2083 return $opacitemholds;
2088 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2090 Use when checking out an item to handle reserves
2091 If $cancelreserve boolean is set to true, it will remove existing reserve
2096 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2098 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2099 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2102 my $biblionumber = $res->{biblionumber};
2103 my $biblioitemnumber = $res->{biblioitemnumber};
2105 if ($res->{borrowernumber} == $borrowernumber) {
2106 ModReserveFill($res);
2110 # The item is reserved by someone else.
2111 # Find this item in the reserves
2114 foreach (@$all_reserves) {
2115 $_->{'borrowernumber'} == $borrowernumber or next;
2116 $_->{'biblionumber'} == $biblionumber or next;
2123 # The item is reserved by the current patron
2124 ModReserveFill($borr_res);
2127 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2128 RevertWaitingStatus({ itemnumber => $itemnumber });
2130 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2132 biblionumber => $res->{'biblionumber'},
2133 itemnumber => $res->{'itemnumber'},
2134 borrowernumber => $res->{'borrowernumber'}
2142 MergeHolds($dbh,$to_biblio, $from_biblio);
2144 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2149 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2150 my $sth = $dbh->prepare(
2151 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2153 $sth->execute($from_biblio);
2154 if ( my $data = $sth->fetchrow_hashref() ) {
2156 # holds exist on old record, if not we don't need to do anything
2157 $sth = $dbh->prepare(
2158 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2159 $sth->execute( $to_biblio, $from_biblio );
2162 # don't reorder those already waiting
2164 $sth = $dbh->prepare(
2165 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2167 my $upd_sth = $dbh->prepare(
2168 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2169 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2171 $sth->execute( $to_biblio, 'W', 'T' );
2173 while ( my $reserve = $sth->fetchrow_hashref() ) {
2175 $priority, $to_biblio,
2176 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2177 $reserve->{'itemnumber'}
2184 =head2 RevertWaitingStatus
2186 RevertWaitingStatus({ itemnumber => $itemnumber });
2188 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2190 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2191 item level hold, even if it was only a bibliolevel hold to
2192 begin with. This is because we can no longer know if a hold
2193 was item-level or bib-level after a hold has been set to
2198 sub RevertWaitingStatus {
2199 my ( $params ) = @_;
2200 my $itemnumber = $params->{'itemnumber'};
2202 return unless ( $itemnumber );
2204 my $dbh = C4::Context->dbh;
2206 ## Get the waiting reserve we want to revert
2208 SELECT * FROM reserves
2209 WHERE itemnumber = ?
2210 AND found IS NOT NULL
2212 my $sth = $dbh->prepare( $query );
2213 $sth->execute( $itemnumber );
2214 my $reserve = $sth->fetchrow_hashref();
2216 ## Increment the priority of all other non-waiting
2217 ## reserves for this bib record
2221 priority = priority + 1
2227 $sth = $dbh->prepare( $query );
2228 $sth->execute( $reserve->{'biblionumber'} );
2230 ## Fix up the currently waiting reserve
2240 $sth = $dbh->prepare( $query );
2241 $sth->execute( $reserve->{'reserve_id'} );
2242 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2247 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2249 Returnes the first reserve id that matches the given criteria
2254 my ( $params ) = @_;
2256 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2258 my $dbh = C4::Context->dbh();
2260 my $sql = "SELECT reserve_id FROM reserves WHERE ";
2264 foreach my $key ( keys %$params ) {
2265 if ( defined( $params->{$key} ) ) {
2266 push( @limits, "$key = ?" );
2267 push( @params, $params->{$key} );
2271 $sql .= join( " AND ", @limits );
2273 my $sth = $dbh->prepare( $sql );
2274 $sth->execute( @params );
2275 my $row = $sth->fetchrow_hashref();
2277 return $row->{'reserve_id'};
2282 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2284 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2289 my ($branch, $borrowernumber, $biblionumber) = @_;
2291 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2293 my $reserve_id = GetReserveId({
2294 biblionumber => $biblionumber,
2295 borrowernumber => $borrowernumber
2297 my $reserve = GetReserveInfo($reserve_id) or return;
2299 return C4::Letters::GetPreparedLetter (
2300 module => 'circulation',
2301 letter_code => 'RESERVESLIP',
2302 branchcode => $branch,
2304 'reserves' => $reserve,
2305 'branches' => $reserve->{branchcode},
2306 'borrowers' => $reserve->{borrowernumber},
2307 'biblio' => $reserve->{biblionumber},
2308 'items' => $reserve->{itemnumber},
2313 =head2 GetReservesControlBranch
2315 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2317 Return the branchcode to be used to determine which reserves
2318 policy applies to a transaction.
2320 C<$item> is a hashref for an item. Only 'homebranch' is used.
2322 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2326 sub GetReservesControlBranch {
2327 my ( $item, $borrower ) = @_;
2329 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2332 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2333 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2339 =head2 CalculatePriority
2341 my $p = CalculatePriority($biblionumber, $resdate);
2343 Calculate priority for a new reserve on biblionumber, placing it at
2344 the end of the line of all holds whose start date falls before
2345 the current system time and that are neither on the hold shelf
2348 The reserve date parameter is optional; if it is supplied, the
2349 priority is based on the set of holds whose start date falls before
2350 the parameter value.
2352 After calculation of this priority, it is recommended to call
2353 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2358 sub CalculatePriority {
2359 my ( $biblionumber, $resdate ) = @_;
2362 SELECT COUNT(*) FROM reserves
2363 WHERE biblionumber = ?
2365 AND (found IS NULL OR found = '')
2367 #skip found==W or found==T (waiting or transit holds)
2369 $sql.= ' AND ( reservedate <= ? )';
2372 $sql.= ' AND ( reservedate < NOW() )';
2374 my $dbh = C4::Context->dbh();
2375 my @row = $dbh->selectrow_array(
2378 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2381 return @row ? $row[0]+1 : 1;
2384 =head2 IsItemOnHoldAndFound
2386 my $bool = IsItemFoundHold( $itemnumber );
2388 Returns true if the item is currently on hold
2389 and that hold has a non-null found status ( W, T, etc. )
2393 sub IsItemOnHoldAndFound {
2394 my ($itemnumber) = @_;
2396 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2398 my $found = $rs->count(
2400 itemnumber => $itemnumber,
2401 found => { '!=' => undef }
2410 Koha Development Team <http://koha-community.org/>