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)
152 Adds reserve and generates HOLDPLACED message.
154 The following tables are available witin the HOLDPLACED message:
166 $branch, $borrowernumber, $biblionumber,
167 $bibitems, $priority, $resdate, $expdate, $notes,
168 $title, $checkitem, $found
171 if ( Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->count() > 0 ) {
172 carp("AddReserve: borrower $borrowernumber already has a hold for biblionumber $biblionumber");
176 my $dbh = C4::Context->dbh;
178 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
179 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
181 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
183 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
185 # Make room in reserves for this before those of a later reserve date
186 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
191 # If the reserv had the waiting status, we had the value of the resdate
192 if ( $found eq 'W' ) {
193 $waitingdate = $resdate;
196 # updates take place here
197 my $hold = Koha::Hold->new(
199 borrowernumber => $borrowernumber,
200 biblionumber => $biblionumber,
201 reservedate => $resdate,
202 branchcode => $branch,
203 priority => $priority,
204 reservenotes => $notes,
205 itemnumber => $checkitem,
207 waitingdate => $waitingdate,
208 expirationdate => $expdate
211 my $reserve_id = $hold->id();
213 # add a reserve fee if needed
214 my $fee = GetReserveFee( $borrowernumber, $biblionumber );
215 ChargeReserveFee( $borrowernumber, $fee, $title );
217 _FixPriority({ biblionumber => $biblionumber});
219 # Send e-mail to librarian if syspref is active
220 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
221 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
222 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
223 if ( my $letter = C4::Letters::GetPreparedLetter (
224 module => 'reserves',
225 letter_code => 'HOLDPLACED',
226 branchcode => $branch,
228 'branches' => $branch_details,
229 'borrowers' => $borrower,
230 'biblio' => $biblionumber,
231 'biblioitems' => $biblionumber,
232 'items' => $checkitem,
236 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
238 C4::Letters::EnqueueLetter(
240 borrowernumber => $borrowernumber,
241 message_transport_type => 'email',
242 from_address => $admin_email_address,
243 to_address => $admin_email_address,
254 $res = GetReserve( $reserve_id );
256 Return the current reserve.
261 my ($reserve_id) = @_;
263 my $dbh = C4::Context->dbh;
264 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
265 my $sth = $dbh->prepare( $query );
266 $sth->execute( $reserve_id );
267 return $sth->fetchrow_hashref();
270 =head2 GetReservesFromBiblionumber
272 my $reserves = GetReservesFromBiblionumber({
273 biblionumber => $biblionumber,
274 [ itemnumber => $itemnumber, ]
278 This function gets the list of reservations for one C<$biblionumber>,
279 returning an arrayref pointing to the reserves for C<$biblionumber>.
281 By default, only reserves whose start date falls before the current
282 time are returned. To return all reserves, including future ones,
283 the C<all_dates> parameter can be included and set to a true value.
285 If the C<itemnumber> parameter is supplied, reserves must be targeted
286 to that item or not targeted to any item at all; otherwise, they
287 are excluded from the list.
291 sub GetReservesFromBiblionumber {
293 my $biblionumber = $params->{biblionumber} or return [];
294 my $itemnumber = $params->{itemnumber};
295 my $all_dates = $params->{all_dates} // 0;
296 my $dbh = C4::Context->dbh;
298 # Find the desired items in the reserves
303 timestamp AS rtimestamp,
316 WHERE biblionumber = ? ";
317 push( @params, $biblionumber );
318 unless ( $all_dates ) {
319 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
322 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
323 push( @params, $itemnumber );
325 $query .= "ORDER BY priority";
326 my $sth = $dbh->prepare($query);
327 $sth->execute( @params );
329 while ( my $data = $sth->fetchrow_hashref ) {
330 push @results, $data;
335 =head2 GetReservesFromItemnumber
337 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
339 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
341 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
345 sub GetReservesFromItemnumber {
346 my ($itemnumber) = @_;
348 my $schema = Koha::Database->new()->schema();
350 my $r = $schema->resultset('Reserve')->search(
352 itemnumber => $itemnumber,
355 reservedate => \'<= CAST( NOW() AS DATE )',
356 waitingdate => { '!=', undef }
360 order_by => 'priority',
368 $r->get_column('borrowernumber'),
369 $r->get_column('branchcode'),
375 =head2 GetReservesFromBorrowernumber
377 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
383 sub GetReservesFromBorrowernumber {
384 my ( $borrowernumber, $status ) = @_;
385 my $dbh = C4::Context->dbh;
388 $sth = $dbh->prepare("
391 WHERE borrowernumber=?
395 $sth->execute($borrowernumber,$status);
397 $sth = $dbh->prepare("
400 WHERE borrowernumber=?
403 $sth->execute($borrowernumber);
405 my $data = $sth->fetchall_arrayref({});
409 =head2 CanBookBeReserved
411 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
412 if ($canReserve eq 'OK') { #We can reserve this Item! }
414 See CanItemBeReserved() for possible return values.
418 sub CanBookBeReserved{
419 my ($borrowernumber, $biblionumber) = @_;
421 my $items = GetItemnumbersForBiblio($biblionumber);
422 #get items linked via host records
423 my @hostitems = get_hostitemnumbers_of($biblionumber);
425 push (@$items,@hostitems);
429 foreach my $item (@$items) {
430 $canReserve = CanItemBeReserved( $borrowernumber, $item );
431 return 'OK' if $canReserve eq 'OK';
436 =head2 CanItemBeReserved
438 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
439 if ($canReserve eq 'OK') { #We can reserve this Item! }
441 @RETURNS OK, if the Item can be reserved.
442 ageRestricted, if the Item is age restricted for this borrower.
443 damaged, if the Item is damaged.
444 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
445 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
446 notReservable, if holds on this item are not allowed
450 sub CanItemBeReserved{
451 my ($borrowernumber, $itemnumber) = @_;
453 my $dbh = C4::Context->dbh;
454 my $ruleitemtype; # itemtype of the matching issuing rule
455 my $allowedreserves = 0;
457 # we retrieve borrowers and items informations #
458 # item->{itype} will come for biblioitems if necessery
459 my $item = GetItem($itemnumber);
460 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
461 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
463 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
464 return 'damaged' if ( $item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems') );
466 #Check for the age restriction
467 my ($ageRestriction, $daysToAgeRestriction) = C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
468 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
470 my $controlbranch = C4::Context->preference('ReservesControlBranch');
472 # we retrieve user rights on this itemtype and branchcode
473 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
475 WHERE (categorycode in (?,'*') )
476 AND (itemtype IN (?,'*'))
477 AND (branchcode IN (?,'*'))
484 my $querycount ="SELECT
487 LEFT JOIN items USING (itemnumber)
488 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
489 LEFT JOIN borrowers USING (borrowernumber)
490 WHERE borrowernumber = ?
495 my $branchfield = "reserves.branchcode";
497 if( $controlbranch eq "ItemHomeLibrary" ){
498 $branchfield = "items.homebranch";
499 $branchcode = $item->{homebranch};
500 }elsif( $controlbranch eq "PatronLibrary" ){
501 $branchfield = "borrowers.branchcode";
502 $branchcode = $borrower->{branchcode};
506 $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
507 if(my $rights = $sth->fetchrow_hashref()){
508 $ruleitemtype = $rights->{itemtype};
509 $allowedreserves = $rights->{reservesallowed};
516 $querycount .= "AND $branchfield = ?";
518 # If using item-level itypes, fall back to the record
519 # level itemtype if the hold has no associated item
521 C4::Context->preference('item-level_itypes')
522 ? " AND COALESCE( itype, itemtype ) = ?"
523 : " AND itemtype = ?"
524 if ( $ruleitemtype ne "*" );
526 my $sthcount = $dbh->prepare($querycount);
528 if($ruleitemtype eq "*"){
529 $sthcount->execute($borrowernumber, $branchcode);
531 $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
534 my $reservecount = "0";
535 if(my $rowcount = $sthcount->fetchrow_hashref()){
536 $reservecount = $rowcount->{count};
538 # we check if it's ok or not
539 if( $reservecount >= $allowedreserves ){
540 return 'tooManyReserves';
543 my $circ_control_branch = C4::Circulation::_GetCircControlBranch($item,
545 my $branchitemrule = C4::Circulation::GetBranchItemRule($circ_control_branch,
548 if ( $branchitemrule->{holdallowed} == 0 ) {
549 return 'notReservable';
552 if ( $branchitemrule->{holdallowed} == 1
553 && $borrower->{branchcode} ne $item->{homebranch} )
555 return 'cannotReserveFromOtherBranches';
558 # If reservecount is ok, we check item branch if IndependentBranches is ON
559 # and canreservefromotherbranches is OFF
560 if ( C4::Context->preference('IndependentBranches')
561 and !C4::Context->preference('canreservefromotherbranches') )
563 my $itembranch = $item->{homebranch};
564 if ($itembranch ne $borrower->{branchcode}) {
565 return 'cannotReserveFromOtherBranches';
572 =head2 CanReserveBeCanceledFromOpac
574 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
576 returns 1 if reserve can be cancelled by user from OPAC.
577 First check if reserve belongs to user, next checks if reserve is not in
578 transfer or waiting status
582 sub CanReserveBeCanceledFromOpac {
583 my ($reserve_id, $borrowernumber) = @_;
585 return unless $reserve_id and $borrowernumber;
586 my $reserve = GetReserve($reserve_id);
588 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
589 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
595 =head2 GetReserveCount
597 $number = &GetReserveCount($borrowernumber);
599 this function returns the number of reservation for a borrower given on input arg.
603 sub GetReserveCount {
604 my ($borrowernumber) = @_;
606 my $dbh = C4::Context->dbh;
609 SELECT COUNT(*) AS counter
611 WHERE borrowernumber = ?
613 my $sth = $dbh->prepare($query);
614 $sth->execute($borrowernumber);
615 my $row = $sth->fetchrow_hashref;
616 return $row->{counter};
619 =head2 GetOtherReserves
621 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
623 Check queued list of this document and check if this document must be transferred
627 sub GetOtherReserves {
628 my ($itemnumber) = @_;
631 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
632 if ($checkreserves) {
633 my $iteminfo = GetItem($itemnumber);
634 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
635 $messages->{'transfert'} = $checkreserves->{'branchcode'};
636 #minus priorities of others reservs
637 ModReserveMinusPriority(
639 $checkreserves->{'reserve_id'},
642 #launch the subroutine dotransfer
643 C4::Items::ModItemTransfer(
645 $iteminfo->{'holdingbranch'},
646 $checkreserves->{'branchcode'}
651 #step 2b : case of a reservation on the same branch, set the waiting status
653 $messages->{'waiting'} = 1;
654 ModReserveMinusPriority(
656 $checkreserves->{'reserve_id'},
658 ModReserveStatus($itemnumber,'W');
661 $nextreservinfo = $checkreserves->{'borrowernumber'};
664 return ( $messages, $nextreservinfo );
667 =head2 ChargeReserveFee
669 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
671 Charge the fee for a reserve (if $fee > 0)
675 sub ChargeReserveFee {
676 my ( $borrowernumber, $fee, $title ) = @_;
677 return if !$fee || $fee==0; # the last test is needed to include 0.00
679 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
681 my $dbh = C4::Context->dbh;
682 my $nextacctno = &getnextacctno( $borrowernumber );
683 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
688 $fee = GetReserveFee( $borrowernumber, $biblionumber );
690 Calculate the fee for a reserve (if applicable).
695 my ( $borrowernumber, $biblionumber ) = @_;
697 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
700 SELECT COUNT(*) FROM items
701 LEFT JOIN issues USING (itemnumber)
702 WHERE items.biblionumber=? AND issues.issue_id IS NULL
705 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
708 my $dbh = C4::Context->dbh;
709 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
710 if( $fee && $fee > 0 ) {
711 # This is a reconstruction of the old code:
712 # Compare number of items with items issued, and optionally check holds
713 # If not all items are issued and there are no holds: charge no fee
714 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
715 my ( $notissued, $reserved );
716 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
719 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
720 ( $biblionumber, $borrowernumber ) );
721 $fee = 0 if $reserved == 0;
727 =head2 GetReservesToBranch
729 @transreserv = GetReservesToBranch( $frombranch );
731 Get reserve list for a given branch
735 sub GetReservesToBranch {
736 my ( $frombranch ) = @_;
737 my $dbh = C4::Context->dbh;
738 my $sth = $dbh->prepare(
739 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
744 $sth->execute( $frombranch );
747 while ( my $data = $sth->fetchrow_hashref ) {
748 $transreserv[$i] = $data;
751 return (@transreserv);
754 =head2 GetReservesForBranch
756 @transreserv = GetReservesForBranch($frombranch);
760 sub GetReservesForBranch {
761 my ($frombranch) = @_;
762 my $dbh = C4::Context->dbh;
765 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
770 $query .= " AND branchcode=? " if ( $frombranch );
771 $query .= "ORDER BY waitingdate" ;
773 my $sth = $dbh->prepare($query);
775 $sth->execute($frombranch);
782 while ( my $data = $sth->fetchrow_hashref ) {
783 $transreserv[$i] = $data;
786 return (@transreserv);
789 =head2 GetReserveStatus
791 $reservestatus = GetReserveStatus($itemnumber);
793 Takes an itemnumber and returns the status of the reserve placed on it.
794 If several reserves exist, the reserve with the lower priority is given.
798 ## FIXME: I don't think this does what it thinks it does.
799 ## It only ever checks the first reserve result, even though
800 ## multiple reserves for that bib can have the itemnumber set
801 ## the sub is only used once in the codebase.
802 sub GetReserveStatus {
803 my ($itemnumber) = @_;
805 my $dbh = C4::Context->dbh;
807 my ($sth, $found, $priority);
809 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
810 $sth->execute($itemnumber);
811 ($found, $priority) = $sth->fetchrow_array;
815 return 'Waiting' if $found eq 'W' and $priority == 0;
816 return 'Finished' if $found eq 'F';
819 return 'Reserved' if $priority > 0;
821 return ''; # empty string here will remove need for checking undef, or less log lines
826 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
827 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
828 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
830 Find a book in the reserves.
832 C<$itemnumber> is the book's item number.
833 C<$lookahead> is the number of days to look in advance for future reserves.
835 As I understand it, C<&CheckReserves> looks for the given item in the
836 reserves. If it is found, that's a match, and C<$status> is set to
839 Otherwise, it finds the most important item in the reserves with the
840 same biblio number as this book (I'm not clear on this) and returns it
841 with C<$status> set to C<Reserved>.
843 C<&CheckReserves> returns a two-element list:
845 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
847 C<$reserve> is the reserve item that matched. It is a
848 reference-to-hash whose keys are mostly the fields of the reserves
849 table in the Koha database.
854 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
855 my $dbh = C4::Context->dbh;
858 if (C4::Context->preference('item-level_itypes')){
860 SELECT items.biblionumber,
861 items.biblioitemnumber,
862 itemtypes.notforloan,
863 items.notforloan AS itemnotforloan,
869 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
870 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
875 SELECT items.biblionumber,
876 items.biblioitemnumber,
877 itemtypes.notforloan,
878 items.notforloan AS itemnotforloan,
884 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
885 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
890 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
891 $sth->execute($item);
894 $sth = $dbh->prepare("$select WHERE barcode = ?");
895 $sth->execute($barcode);
897 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
898 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
900 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
902 return unless $itemnumber; # bail if we got nothing.
904 # if item is not for loan it cannot be reserved either.....
905 # except where items.notforloan < 0 : This indicates the item is holdable.
906 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
908 # Find this item in the reserves
909 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
911 # $priority and $highest are used to find the most important item
912 # in the list returned by &_Findgroupreserve. (The lower $priority,
913 # the more important the item.)
914 # $highest is the most important item we've seen so far.
916 if (scalar @reserves) {
917 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
918 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
919 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
921 my $priority = 10000000;
922 foreach my $res (@reserves) {
923 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
924 return ( "Waiting", $res, \@reserves ); # Found it
928 my $local_hold_match;
930 if ($LocalHoldsPriority) {
931 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
932 $iteminfo = C4::Items::GetItem($itemnumber);
934 my $local_holds_priority_item_branchcode =
935 $iteminfo->{$LocalHoldsPriorityItemControl};
936 my $local_holds_priority_patron_branchcode =
937 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
939 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
940 ? $borrowerinfo->{branchcode}
943 $local_holds_priority_item_branchcode eq
944 $local_holds_priority_patron_branchcode;
947 # See if this item is more important than what we've got so far
948 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
949 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
950 $iteminfo ||= C4::Items::GetItem($itemnumber);
951 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
952 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
953 next if ($branchitemrule->{'holdallowed'} == 0);
954 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
955 $priority = $res->{'priority'};
957 last if $local_hold_match;
963 # If we get this far, then no exact match was found.
964 # We return the most important (i.e. next) reservation.
966 $highest->{'itemnumber'} = $item;
967 return ( "Reserved", $highest, \@reserves );
973 =head2 CancelExpiredReserves
975 CancelExpiredReserves();
977 Cancels all reserves with an expiration date from before today.
981 sub CancelExpiredReserves {
983 # Cancel reserves that have passed their expiration date.
984 my $dbh = C4::Context->dbh;
985 my $sth = $dbh->prepare( "
986 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
987 AND expirationdate IS NOT NULL
992 while ( my $res = $sth->fetchrow_hashref() ) {
993 CancelReserve({ reserve_id => $res->{'reserve_id'} });
996 # Cancel reserves that have been waiting too long
997 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
998 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
999 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
1001 my $today = dt_from_string();
1003 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
1004 $sth = $dbh->prepare( $query );
1005 $sth->execute( $max_pickup_delay );
1007 while ( my $res = $sth->fetchrow_hashref ) {
1009 unless ( $cancel_on_holidays ) {
1010 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
1011 my $is_holiday = $calendar->is_holiday( $today );
1013 if ( $is_holiday ) {
1019 CancelReserve({ reserve_id => $res->{'reserve_id'}, charge_cancel_fee => 1 });
1026 =head2 AutoUnsuspendReserves
1028 AutoUnsuspendReserves();
1030 Unsuspends all suspended reserves with a suspend_until date from before today.
1034 sub AutoUnsuspendReserves {
1036 my $dbh = C4::Context->dbh;
1038 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
1039 my $sth = $dbh->prepare( $query );
1044 =head2 CancelReserve
1046 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
1048 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.
1053 my ( $params ) = @_;
1055 my $reserve_id = $params->{'reserve_id'};
1056 # Filter out only the desired keys; this will insert undefined values for elements missing in
1057 # \%params, but GetReserveId filters them out anyway.
1058 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
1060 return unless ( $reserve_id );
1062 my $dbh = C4::Context->dbh;
1064 my $reserve = GetReserve( $reserve_id );
1068 SET cancellationdate = now(),
1071 WHERE reserve_id = ?
1073 my $sth = $dbh->prepare($query);
1074 $sth->execute( $reserve_id );
1077 INSERT INTO old_reserves
1078 SELECT * FROM reserves
1079 WHERE reserve_id = ?
1081 $sth = $dbh->prepare($query);
1082 $sth->execute( $reserve_id );
1085 DELETE FROM reserves
1086 WHERE reserve_id = ?
1088 $sth = $dbh->prepare($query);
1089 $sth->execute( $reserve_id );
1091 # now fix the priority on the others....
1092 _FixPriority({ biblionumber => $reserve->{biblionumber} });
1094 # and, if desired, charge a cancel fee
1095 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
1096 if ( $charge && $params->{'charge_cancel_fee'} ) {
1097 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
1106 ModReserve({ rank => $rank,
1107 reserve_id => $reserve_id,
1108 branchcode => $branchcode
1109 [, itemnumber => $itemnumber ]
1110 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1113 Change a hold request's priority or cancel it.
1115 C<$rank> specifies the effect of the change. If C<$rank>
1116 is 'W' or 'n', nothing happens. This corresponds to leaving a
1117 request alone when changing its priority in the holds queue
1120 If C<$rank> is 'del', the hold request is cancelled.
1122 If C<$rank> is an integer greater than zero, the priority of
1123 the request is set to that value. Since priority != 0 means
1124 that the item is not waiting on the hold shelf, setting the
1125 priority to a non-zero value also sets the request's found
1126 status and waiting date to NULL.
1128 The optional C<$itemnumber> parameter is used only when
1129 C<$rank> is a non-zero integer; if supplied, the itemnumber
1130 of the hold request is set accordingly; if omitted, the itemnumber
1133 B<FIXME:> Note that the forgoing can have the effect of causing
1134 item-level hold requests to turn into title-level requests. This
1135 will be fixed once reserves has separate columns for requested
1136 itemnumber and supplying itemnumber.
1141 my ( $params ) = @_;
1143 my $rank = $params->{'rank'};
1144 my $reserve_id = $params->{'reserve_id'};
1145 my $branchcode = $params->{'branchcode'};
1146 my $itemnumber = $params->{'itemnumber'};
1147 my $suspend_until = $params->{'suspend_until'};
1148 my $borrowernumber = $params->{'borrowernumber'};
1149 my $biblionumber = $params->{'biblionumber'};
1151 return if $rank eq "W";
1152 return if $rank eq "n";
1154 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1155 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1157 my $dbh = C4::Context->dbh;
1158 if ( $rank eq "del" ) {
1159 CancelReserve({ reserve_id => $reserve_id });
1161 elsif ($rank =~ /^\d+/ and $rank > 0) {
1163 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1164 WHERE reserve_id = ?
1166 my $sth = $dbh->prepare($query);
1167 $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
1169 if ( defined( $suspend_until ) ) {
1170 if ( $suspend_until ) {
1171 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until ), dateonly => 1, dateformat => 'iso' }); };
1172 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
1174 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
1178 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1182 =head2 ModReserveFill
1184 &ModReserveFill($reserve);
1186 Fill a reserve. If I understand this correctly, this means that the
1187 reserved book has been found and given to the patron who reserved it.
1189 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1190 whose keys are fields from the reserves table in the Koha database.
1194 sub ModReserveFill {
1196 my $dbh = C4::Context->dbh;
1197 # fill in a reserve record....
1198 my $reserve_id = $res->{'reserve_id'};
1199 my $biblionumber = $res->{'biblionumber'};
1200 my $borrowernumber = $res->{'borrowernumber'};
1201 my $resdate = $res->{'reservedate'};
1203 # get the priority on this record....
1205 my $query = "SELECT priority
1207 WHERE biblionumber = ?
1208 AND borrowernumber = ?
1209 AND reservedate = ?";
1210 my $sth = $dbh->prepare($query);
1211 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1212 ($priority) = $sth->fetchrow_array;
1214 # update the database...
1215 $query = "UPDATE reserves
1218 WHERE biblionumber = ?
1220 AND borrowernumber = ?
1222 $sth = $dbh->prepare($query);
1223 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1225 # move to old_reserves
1226 $query = "INSERT INTO old_reserves
1227 SELECT * FROM reserves
1228 WHERE biblionumber = ?
1230 AND borrowernumber = ?
1232 $sth = $dbh->prepare($query);
1233 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1234 $query = "DELETE FROM reserves
1235 WHERE biblionumber = ?
1237 AND borrowernumber = ?
1239 $sth = $dbh->prepare($query);
1240 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1242 # now fix the priority on the others (if the priority wasn't
1243 # already sorted!)....
1244 unless ( $priority == 0 ) {
1245 _FixPriority({ reserve_id => $reserve_id, biblionumber => $biblionumber });
1249 =head2 ModReserveStatus
1251 &ModReserveStatus($itemnumber, $newstatus);
1253 Update the reserve status for the active (priority=0) reserve.
1255 $itemnumber is the itemnumber the reserve is on
1257 $newstatus is the new status.
1261 sub ModReserveStatus {
1263 #first : check if we have a reservation for this item .
1264 my ($itemnumber, $newstatus) = @_;
1265 my $dbh = C4::Context->dbh;
1267 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1268 my $sth_set = $dbh->prepare($query);
1269 $sth_set->execute( $newstatus, $itemnumber );
1271 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1272 CartToShelf( $itemnumber );
1276 =head2 ModReserveAffect
1278 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1280 This function affect an item and a status for a given reserve
1281 The itemnumber parameter is used to find the biblionumber.
1282 with the biblionumber & the borrowernumber, we can affect the itemnumber
1283 to the correct reserve.
1285 if $transferToDo is not set, then the status is set to "Waiting" as well.
1286 otherwise, a transfer is on the way, and the end of the transfer will
1287 take care of the waiting status
1291 sub ModReserveAffect {
1292 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1293 my $dbh = C4::Context->dbh;
1295 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1296 # attached to $itemnumber
1297 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1298 $sth->execute($itemnumber);
1299 my ($biblionumber) = $sth->fetchrow;
1301 # get request - need to find out if item is already
1302 # waiting in order to not send duplicate hold filled notifications
1303 my $reserve_id = GetReserveId({
1304 borrowernumber => $borrowernumber,
1305 biblionumber => $biblionumber,
1307 return unless defined $reserve_id;
1308 my $request = GetReserveInfo($reserve_id);
1309 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1311 # If we affect a reserve that has to be transferred, don't set to Waiting
1313 if ($transferToDo) {
1319 WHERE borrowernumber = ?
1320 AND biblionumber = ?
1324 # affect the reserve to Waiting as well.
1329 waitingdate = NOW(),
1331 WHERE borrowernumber = ?
1332 AND biblionumber = ?
1335 $sth = $dbh->prepare($query);
1336 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1337 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1338 _FixPriority( { biblionumber => $biblionumber } );
1339 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1340 CartToShelf( $itemnumber );
1346 =head2 ModReserveCancelAll
1348 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1350 function to cancel reserv,check other reserves, and transfer document if it's necessary
1354 sub ModReserveCancelAll {
1357 my ( $itemnumber, $borrowernumber ) = @_;
1359 #step 1 : cancel the reservation
1360 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1362 #step 2 launch the subroutine of the others reserves
1363 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1365 return ( $messages, $nextreservinfo );
1368 =head2 ModReserveMinusPriority
1370 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1372 Reduce the values of queued list
1376 sub ModReserveMinusPriority {
1377 my ( $itemnumber, $reserve_id ) = @_;
1379 #first step update the value of the first person on reserv
1380 my $dbh = C4::Context->dbh;
1383 SET priority = 0 , itemnumber = ?
1384 WHERE reserve_id = ?
1386 my $sth_upd = $dbh->prepare($query);
1387 $sth_upd->execute( $itemnumber, $reserve_id );
1388 # second step update all others reserves
1389 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1392 =head2 GetReserveInfo
1394 &GetReserveInfo($reserve_id);
1396 Get item and borrower details for a current hold.
1397 Current implementation this query should have a single result.
1401 sub GetReserveInfo {
1402 my ( $reserve_id ) = @_;
1403 my $dbh = C4::Context->dbh;
1408 reserves.borrowernumber,
1409 reserves.biblionumber,
1410 reserves.branchcode,
1411 reserves.waitingdate,
1427 items.holdingbranch,
1428 items.itemcallnumber,
1434 LEFT JOIN items USING(itemnumber)
1435 LEFT JOIN borrowers USING(borrowernumber)
1436 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1437 WHERE reserves.reserve_id = ?";
1438 my $sth = $dbh->prepare($strsth);
1439 $sth->execute($reserve_id);
1441 my $data = $sth->fetchrow_hashref;
1445 =head2 IsAvailableForItemLevelRequest
1447 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1449 Checks whether a given item record is available for an
1450 item-level hold request. An item is available if
1452 * it is not lost AND
1453 * it is not damaged AND
1454 * it is not withdrawn AND
1455 * does not have a not for loan value > 0
1457 Need to check the issuingrules onshelfholds column,
1458 if this is set items on the shelf can be placed on hold
1460 Note that IsAvailableForItemLevelRequest() does not
1461 check if the staff operator is authorized to place
1462 a request on the item - in particular,
1463 this routine does not check IndependentBranches
1464 and canreservefromotherbranches.
1468 sub IsAvailableForItemLevelRequest {
1470 my $borrower = shift;
1472 my $dbh = C4::Context->dbh;
1473 # must check the notforloan setting of the itemtype
1474 # FIXME - a lot of places in the code do this
1475 # or something similar - need to be
1477 my $itype = _get_itype($item);
1478 my $notforloan_per_itemtype
1479 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1483 $notforloan_per_itemtype ||
1484 $item->{itemlost} ||
1485 $item->{notforloan} > 0 ||
1486 $item->{withdrawn} ||
1487 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1490 return 1 if _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1492 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1495 =head2 OnShelfHoldsAllowed
1497 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1499 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1500 holds are allowed, returns true if so.
1504 sub OnShelfHoldsAllowed {
1505 my ($item, $borrower) = @_;
1507 my $itype = _get_itype($item);
1508 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1515 if (C4::Context->preference('item-level_itypes')) {
1516 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1517 # When GetItem is fixed, we can remove this
1518 $itype = $item->{itype};
1521 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1522 # So if we already have a biblioitems join when calling this function,
1523 # we don't need to access the database again
1524 $itype = $item->{itemtype};
1527 my $dbh = C4::Context->dbh;
1528 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1529 my $sth = $dbh->prepare($query);
1530 $sth->execute($item->{biblioitemnumber});
1531 if (my $data = $sth->fetchrow_hashref()){
1532 $itype = $data->{itemtype};
1538 sub _OnShelfHoldsAllowed {
1539 my ($itype,$borrowercategory,$branchcode) = @_;
1541 my $rule = C4::Circulation::GetIssuingRule($borrowercategory, $itype, $branchcode);
1542 return $rule->{onshelfholds};
1545 =head2 AlterPriority
1547 AlterPriority( $where, $reserve_id );
1549 This function changes a reserve's priority up, down, to the top, or to the bottom.
1550 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1555 my ( $where, $reserve_id ) = @_;
1557 my $dbh = C4::Context->dbh;
1559 my $reserve = GetReserve( $reserve_id );
1561 if ( $reserve->{cancellationdate} ) {
1562 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1566 if ( $where eq 'up' || $where eq 'down' ) {
1568 my $priority = $reserve->{'priority'};
1569 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1570 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1572 } elsif ( $where eq 'top' ) {
1574 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1576 } elsif ( $where eq 'bottom' ) {
1578 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1583 =head2 ToggleLowestPriority
1585 ToggleLowestPriority( $borrowernumber, $biblionumber );
1587 This function sets the lowestPriority field to true if is false, and false if it is true.
1591 sub ToggleLowestPriority {
1592 my ( $reserve_id ) = @_;
1594 my $dbh = C4::Context->dbh;
1596 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1597 $sth->execute( $reserve_id );
1599 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1602 =head2 ToggleSuspend
1604 ToggleSuspend( $reserve_id );
1606 This function sets the suspend field to true if is false, and false if it is true.
1607 If the reserve is currently suspended with a suspend_until date, that date will
1608 be cleared when it is unsuspended.
1613 my ( $reserve_id, $suspend_until ) = @_;
1615 $suspend_until = output_pref(
1617 dt => dt_from_string($suspend_until),
1618 dateformat => 'iso',
1621 ) if ($suspend_until);
1623 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1625 my $dbh = C4::Context->dbh;
1627 my $sth = $dbh->prepare(
1628 "UPDATE reserves SET suspend = NOT suspend,
1629 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1630 WHERE reserve_id = ?
1634 push( @params, $suspend_until ) if ( $suspend_until );
1635 push( @params, $reserve_id );
1637 $sth->execute( @params );
1643 borrowernumber => $borrowernumber,
1644 [ biblionumber => $biblionumber, ]
1645 [ suspend_until => $suspend_until, ]
1646 [ suspend => $suspend ]
1649 This function accepts a set of hash keys as its parameters.
1650 It requires either borrowernumber or biblionumber, or both.
1652 suspend_until is wholly optional.
1659 my $borrowernumber = $params{'borrowernumber'} || undef;
1660 my $biblionumber = $params{'biblionumber'} || undef;
1661 my $suspend_until = $params{'suspend_until'} || undef;
1662 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1664 $suspend_until = eval { output_pref( { dt => dt_from_string( $suspend_until), dateonly => 1, dateformat => 'iso' } ); }
1665 if ( defined( $suspend_until ) );
1667 return unless ( $borrowernumber || $biblionumber );
1669 my ( $query, $sth, $dbh, @query_params );
1671 $query = "UPDATE reserves SET suspend = ? ";
1672 push( @query_params, $suspend );
1674 $query .= ", suspend_until = NULL ";
1675 } elsif ( $suspend_until ) {
1676 $query .= ", suspend_until = ? ";
1677 push( @query_params, $suspend_until );
1679 $query .= " WHERE ";
1680 if ( $borrowernumber ) {
1681 $query .= " borrowernumber = ? ";
1682 push( @query_params, $borrowernumber );
1684 $query .= " AND " if ( $borrowernumber && $biblionumber );
1685 if ( $biblionumber ) {
1686 $query .= " biblionumber = ? ";
1687 push( @query_params, $biblionumber );
1689 $query .= " AND found IS NULL ";
1691 $dbh = C4::Context->dbh;
1692 $sth = $dbh->prepare( $query );
1693 $sth->execute( @query_params );
1700 reserve_id => $reserve_id,
1702 [ignoreSetLowestRank => $ignoreSetLowestRank]
1707 _FixPriority({ biblionumber => $biblionumber});
1709 This routine adjusts the priority of a hold request and holds
1712 In the first form, where a reserve_id is passed, the priority of the
1713 hold is set to supplied rank, and other holds for that bib are adjusted
1714 accordingly. If the rank is "del", the hold is cancelled. If no rank
1715 is supplied, all of the holds on that bib have their priority adjusted
1716 as if the second form had been used.
1718 In the second form, where a biblionumber is passed, the holds on that
1719 bib (that are not captured) are sorted in order of increasing priority,
1720 then have reserves.priority set so that the first non-captured hold
1721 has its priority set to 1, the second non-captured hold has its priority
1722 set to 2, and so forth.
1724 In both cases, holds that have the lowestPriority flag on are have their
1725 priority adjusted to ensure that they remain at the end of the line.
1727 Note that the ignoreSetLowestRank parameter is meant to be used only
1728 when _FixPriority calls itself.
1733 my ( $params ) = @_;
1734 my $reserve_id = $params->{reserve_id};
1735 my $rank = $params->{rank} // '';
1736 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1737 my $biblionumber = $params->{biblionumber};
1739 my $dbh = C4::Context->dbh;
1741 unless ( $biblionumber ) {
1742 my $res = GetReserve( $reserve_id );
1743 $biblionumber = $res->{biblionumber};
1746 if ( $rank eq "del" ) {
1747 CancelReserve({ reserve_id => $reserve_id });
1749 elsif ( $rank eq "W" || $rank eq "0" ) {
1751 # make sure priority for waiting or in-transit items is 0
1755 WHERE reserve_id = ?
1756 AND found IN ('W', 'T')
1758 my $sth = $dbh->prepare($query);
1759 $sth->execute( $reserve_id );
1765 SELECT reserve_id, borrowernumber, reservedate
1767 WHERE biblionumber = ?
1768 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1769 ORDER BY priority ASC
1771 my $sth = $dbh->prepare($query);
1772 $sth->execute( $biblionumber );
1773 while ( my $line = $sth->fetchrow_hashref ) {
1774 push( @priority, $line );
1777 # To find the matching index
1779 my $key = -1; # to allow for 0 to be a valid result
1780 for ( $i = 0 ; $i < @priority ; $i++ ) {
1781 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1782 $key = $i; # save the index
1787 # if index exists in array then move it to new position
1788 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1789 my $new_rank = $rank -
1790 1; # $new_rank is what you want the new index to be in the array
1791 my $moving_item = splice( @priority, $key, 1 );
1792 splice( @priority, $new_rank, 0, $moving_item );
1795 # now fix the priority on those that are left....
1799 WHERE reserve_id = ?
1801 $sth = $dbh->prepare($query);
1802 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1805 $priority[$j]->{'reserve_id'}
1809 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1812 unless ( $ignoreSetLowestRank ) {
1813 while ( my $res = $sth->fetchrow_hashref() ) {
1815 reserve_id => $res->{'reserve_id'},
1817 ignoreSetLowestRank => 1
1823 =head2 _Findgroupreserve
1825 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1827 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1828 first match found. If neither, then we look for non-holds-queue based holds.
1829 Lookahead is the number of days to look in advance.
1831 C<&_Findgroupreserve> returns :
1832 C<@results> is an array of references-to-hash whose keys are mostly
1833 fields from the reserves table of the Koha database, plus
1834 C<biblioitemnumber>.
1838 sub _Findgroupreserve {
1839 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1840 my $dbh = C4::Context->dbh;
1842 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1843 # check for exact targeted match
1844 my $item_level_target_query = qq{
1845 SELECT reserves.biblionumber AS biblionumber,
1846 reserves.borrowernumber AS borrowernumber,
1847 reserves.reservedate AS reservedate,
1848 reserves.branchcode AS branchcode,
1849 reserves.cancellationdate AS cancellationdate,
1850 reserves.found AS found,
1851 reserves.reservenotes AS reservenotes,
1852 reserves.priority AS priority,
1853 reserves.timestamp AS timestamp,
1854 biblioitems.biblioitemnumber AS biblioitemnumber,
1855 reserves.itemnumber AS itemnumber,
1856 reserves.reserve_id AS reserve_id
1858 JOIN biblioitems USING (biblionumber)
1859 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1862 AND item_level_request = 1
1864 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1868 my $sth = $dbh->prepare($item_level_target_query);
1869 $sth->execute($itemnumber, $lookahead||0);
1871 if ( my $data = $sth->fetchrow_hashref ) {
1872 push( @results, $data )
1873 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1875 return @results if @results;
1877 # check for title-level targeted match
1878 my $title_level_target_query = qq{
1879 SELECT reserves.biblionumber AS biblionumber,
1880 reserves.borrowernumber AS borrowernumber,
1881 reserves.reservedate AS reservedate,
1882 reserves.branchcode AS branchcode,
1883 reserves.cancellationdate AS cancellationdate,
1884 reserves.found AS found,
1885 reserves.reservenotes AS reservenotes,
1886 reserves.priority AS priority,
1887 reserves.timestamp AS timestamp,
1888 biblioitems.biblioitemnumber AS biblioitemnumber,
1889 reserves.itemnumber AS itemnumber,
1890 reserves.reserve_id AS reserve_id
1892 JOIN biblioitems USING (biblionumber)
1893 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1896 AND item_level_request = 0
1897 AND hold_fill_targets.itemnumber = ?
1898 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1902 $sth = $dbh->prepare($title_level_target_query);
1903 $sth->execute($itemnumber, $lookahead||0);
1905 if ( my $data = $sth->fetchrow_hashref ) {
1906 push( @results, $data )
1907 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1909 return @results if @results;
1912 SELECT reserves.biblionumber AS biblionumber,
1913 reserves.borrowernumber AS borrowernumber,
1914 reserves.reservedate AS reservedate,
1915 reserves.waitingdate AS waitingdate,
1916 reserves.branchcode AS branchcode,
1917 reserves.cancellationdate AS cancellationdate,
1918 reserves.found AS found,
1919 reserves.reservenotes AS reservenotes,
1920 reserves.priority AS priority,
1921 reserves.timestamp AS timestamp,
1922 reserves.itemnumber AS itemnumber,
1923 reserves.reserve_id AS reserve_id
1925 WHERE reserves.biblionumber = ?
1926 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1927 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1931 $sth = $dbh->prepare($query);
1932 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1934 while ( my $data = $sth->fetchrow_hashref ) {
1935 push( @results, $data )
1936 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1941 =head2 _koha_notify_reserve
1943 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1945 Sends a notification to the patron that their hold has been filled (through
1946 ModReserveAffect, _not_ ModReserveFill)
1948 The letter code for this notice may be found using the following query:
1950 select distinct letter_code
1951 from message_transports
1952 inner join message_attributes using (message_attribute_id)
1953 where message_name = 'Hold_Filled'
1955 This will probably sipmly be 'HOLD', but because it is defined in the database,
1956 it is subject to addition or change.
1958 The following tables are availalbe witin the notice:
1969 sub _koha_notify_reserve {
1970 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1972 my $dbh = C4::Context->dbh;
1973 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1975 # Try to get the borrower's email address
1976 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1978 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1979 borrowernumber => $borrowernumber,
1980 message_name => 'Hold_Filled'
1983 my $sth = $dbh->prepare("
1986 WHERE borrowernumber = ?
1987 AND biblionumber = ?
1989 $sth->execute( $borrowernumber, $biblionumber );
1990 my $reserve = $sth->fetchrow_hashref;
1991 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1993 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1995 my %letter_params = (
1996 module => 'reserves',
1997 branchcode => $reserve->{branchcode},
1999 'branches' => $branch_details,
2000 'borrowers' => $borrower,
2001 'biblio' => $biblionumber,
2002 'biblioitems' => $biblionumber,
2003 'reserves' => $reserve,
2004 'items', $reserve->{'itemnumber'},
2006 substitute => { today => output_pref( { dt => dt_from_string, dateonly => 1 } ) },
2009 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.
2010 my $send_notification = sub {
2011 my ( $mtt, $letter_code ) = (@_);
2012 return unless defined $letter_code;
2013 $letter_params{letter_code} = $letter_code;
2014 $letter_params{message_transport_type} = $mtt;
2015 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
2017 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
2021 C4::Letters::EnqueueLetter( {
2023 borrowernumber => $borrowernumber,
2024 from_address => $admin_email_address,
2025 message_transport_type => $mtt,
2029 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
2031 ( $mtt eq 'email' and not $to_address ) # No email address
2032 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
2033 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
2036 &$send_notification($mtt, $letter_code);
2037 $notification_sent++;
2039 #Making sure that a print notification is sent if no other transport types can be utilized.
2040 if (! $notification_sent) {
2041 &$send_notification('print', 'HOLD');
2046 =head2 _ShiftPriorityByDateAndPriority
2048 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
2050 This increments the priority of all reserves after the one
2051 with either the lowest date after C<$reservedate>
2052 or the lowest priority after C<$priority>.
2054 It effectively makes room for a new reserve to be inserted with a certain
2055 priority, which is returned.
2057 This is most useful when the reservedate can be set by the user. It allows
2058 the new reserve to be placed before other reserves that have a later
2059 reservedate. Since priority also is set by the form in reserves/request.pl
2060 the sub accounts for that too.
2064 sub _ShiftPriorityByDateAndPriority {
2065 my ( $biblio, $resdate, $new_priority ) = @_;
2067 my $dbh = C4::Context->dbh;
2068 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2069 my $sth = $dbh->prepare( $query );
2070 $sth->execute( $biblio, $resdate, $new_priority );
2071 my $min_priority = $sth->fetchrow;
2072 # if no such matches are found, $new_priority remains as original value
2073 $new_priority = $min_priority if ( $min_priority );
2075 # Shift the priority up by one; works in conjunction with the next SQL statement
2076 $query = "UPDATE reserves
2077 SET priority = priority+1
2078 WHERE biblionumber = ?
2079 AND borrowernumber = ?
2082 my $sth_update = $dbh->prepare( $query );
2084 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2085 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2086 $sth = $dbh->prepare( $query );
2087 $sth->execute( $new_priority, $biblio );
2088 while ( my $row = $sth->fetchrow_hashref ) {
2089 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2092 return $new_priority; # so the caller knows what priority they wind up receiving
2095 =head2 OPACItemHoldsAllowed
2097 OPACItemHoldsAllowed($item_record,$borrower_record);
2099 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
2100 if specific item holds are allowed, returns true if so.
2104 sub OPACItemHoldsAllowed {
2105 my ($item,$borrower) = @_;
2107 my $branchcode = $item->{homebranch} or die "No homebranch";
2109 my $dbh = C4::Context->dbh;
2110 if (C4::Context->preference('item-level_itypes')) {
2111 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
2112 # When GetItem is fixed, we can remove this
2113 $itype = $item->{itype};
2116 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
2117 my $sth = $dbh->prepare($query);
2118 $sth->execute($item->{biblioitemnumber});
2119 if (my $data = $sth->fetchrow_hashref()){
2120 $itype = $data->{itemtype};
2124 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
2125 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
2127 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2129 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
2131 issuingrules.categorycode desc,
2132 issuingrules.itemtype desc,
2133 issuingrules.branchcode desc
2135 my $sth = $dbh->prepare($query);
2136 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2137 my $data = $sth->fetchrow_hashref;
2138 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2139 return '' if $opacitemholds eq 'N';
2140 return $opacitemholds;
2145 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2147 Use when checking out an item to handle reserves
2148 If $cancelreserve boolean is set to true, it will remove existing reserve
2153 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2155 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2156 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2159 my $biblionumber = $res->{biblionumber};
2160 my $biblioitemnumber = $res->{biblioitemnumber};
2162 if ($res->{borrowernumber} == $borrowernumber) {
2163 ModReserveFill($res);
2167 # The item is reserved by someone else.
2168 # Find this item in the reserves
2171 foreach (@$all_reserves) {
2172 $_->{'borrowernumber'} == $borrowernumber or next;
2173 $_->{'biblionumber'} == $biblionumber or next;
2180 # The item is reserved by the current patron
2181 ModReserveFill($borr_res);
2184 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2185 RevertWaitingStatus({ itemnumber => $itemnumber });
2187 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2188 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2195 MergeHolds($dbh,$to_biblio, $from_biblio);
2197 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2202 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2203 my $sth = $dbh->prepare(
2204 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2206 $sth->execute($from_biblio);
2207 if ( my $data = $sth->fetchrow_hashref() ) {
2209 # holds exist on old record, if not we don't need to do anything
2210 $sth = $dbh->prepare(
2211 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2212 $sth->execute( $to_biblio, $from_biblio );
2215 # don't reorder those already waiting
2217 $sth = $dbh->prepare(
2218 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2220 my $upd_sth = $dbh->prepare(
2221 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2222 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2224 $sth->execute( $to_biblio, 'W', 'T' );
2226 while ( my $reserve = $sth->fetchrow_hashref() ) {
2228 $priority, $to_biblio,
2229 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2230 $reserve->{'itemnumber'}
2237 =head2 RevertWaitingStatus
2239 RevertWaitingStatus({ itemnumber => $itemnumber });
2241 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2243 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2244 item level hold, even if it was only a bibliolevel hold to
2245 begin with. This is because we can no longer know if a hold
2246 was item-level or bib-level after a hold has been set to
2251 sub RevertWaitingStatus {
2252 my ( $params ) = @_;
2253 my $itemnumber = $params->{'itemnumber'};
2255 return unless ( $itemnumber );
2257 my $dbh = C4::Context->dbh;
2259 ## Get the waiting reserve we want to revert
2261 SELECT * FROM reserves
2262 WHERE itemnumber = ?
2263 AND found IS NOT NULL
2265 my $sth = $dbh->prepare( $query );
2266 $sth->execute( $itemnumber );
2267 my $reserve = $sth->fetchrow_hashref();
2269 ## Increment the priority of all other non-waiting
2270 ## reserves for this bib record
2274 priority = priority + 1
2280 $sth = $dbh->prepare( $query );
2281 $sth->execute( $reserve->{'biblionumber'} );
2283 ## Fix up the currently waiting reserve
2293 $sth = $dbh->prepare( $query );
2294 $sth->execute( $reserve->{'reserve_id'} );
2295 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2300 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2302 Returnes the first reserve id that matches the given criteria
2307 my ( $params ) = @_;
2309 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2311 my $dbh = C4::Context->dbh();
2313 my $sql = "SELECT reserve_id FROM reserves WHERE ";
2317 foreach my $key ( keys %$params ) {
2318 if ( defined( $params->{$key} ) ) {
2319 push( @limits, "$key = ?" );
2320 push( @params, $params->{$key} );
2324 $sql .= join( " AND ", @limits );
2326 my $sth = $dbh->prepare( $sql );
2327 $sth->execute( @params );
2328 my $row = $sth->fetchrow_hashref();
2330 return $row->{'reserve_id'};
2335 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2337 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2339 The letter code will be RESERVESLIP, and the following tables are
2340 available within the slip:
2352 my ($branch, $borrowernumber, $biblionumber) = @_;
2354 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2356 my $reserve_id = GetReserveId({
2357 biblionumber => $biblionumber,
2358 borrowernumber => $borrowernumber
2360 my $reserve = GetReserveInfo($reserve_id) or return;
2362 return C4::Letters::GetPreparedLetter (
2363 module => 'circulation',
2364 letter_code => 'RESERVESLIP',
2365 branchcode => $branch,
2367 'reserves' => $reserve,
2368 'branches' => $reserve->{branchcode},
2369 'borrowers' => $reserve->{borrowernumber},
2370 'biblio' => $reserve->{biblionumber},
2371 'biblioitems' => $reserve->{biblionumber},
2372 'items' => $reserve->{itemnumber},
2377 =head2 GetReservesControlBranch
2379 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2381 Return the branchcode to be used to determine which reserves
2382 policy applies to a transaction.
2384 C<$item> is a hashref for an item. Only 'homebranch' is used.
2386 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2390 sub GetReservesControlBranch {
2391 my ( $item, $borrower ) = @_;
2393 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2396 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2397 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2403 =head2 CalculatePriority
2405 my $p = CalculatePriority($biblionumber, $resdate);
2407 Calculate priority for a new reserve on biblionumber, placing it at
2408 the end of the line of all holds whose start date falls before
2409 the current system time and that are neither on the hold shelf
2412 The reserve date parameter is optional; if it is supplied, the
2413 priority is based on the set of holds whose start date falls before
2414 the parameter value.
2416 After calculation of this priority, it is recommended to call
2417 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2422 sub CalculatePriority {
2423 my ( $biblionumber, $resdate ) = @_;
2426 SELECT COUNT(*) FROM reserves
2427 WHERE biblionumber = ?
2429 AND (found IS NULL OR found = '')
2431 #skip found==W or found==T (waiting or transit holds)
2433 $sql.= ' AND ( reservedate <= ? )';
2436 $sql.= ' AND ( reservedate < NOW() )';
2438 my $dbh = C4::Context->dbh();
2439 my @row = $dbh->selectrow_array(
2442 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2445 return @row ? $row[0]+1 : 1;
2448 =head2 IsItemOnHoldAndFound
2450 my $bool = IsItemFoundHold( $itemnumber );
2452 Returns true if the item is currently on hold
2453 and that hold has a non-null found status ( W, T, etc. )
2457 sub IsItemOnHoldAndFound {
2458 my ($itemnumber) = @_;
2460 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2462 my $found = $rs->count(
2464 itemnumber => $itemnumber,
2465 found => { '!=' => undef }
2474 Koha Development Team <http://koha-community.org/>