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 under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along
20 # with Koha; if not, write to the Free Software Foundation, Inc.,
21 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 );
42 use List::MoreUtils qw( firstidx );
44 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
48 C4::Reserves - Koha functions for dealing with reservation.
56 This modules provides somes functions to deal with reservations.
58 Reserves are stored in reserves table.
59 The following columns contains important values :
60 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
61 =0 : then the reserve is being dealed
62 - found : NULL : means the patron requested the 1st available, and we haven't choosen the item
63 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
64 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
65 F(inished) : the reserve has been completed, and is done
66 - itemnumber : empty : the reserve is still unaffected to an item
67 filled: the reserve is attached to an item
68 The complete workflow is :
69 ==== 1st use case ====
70 patron request a document, 1st available : P >0, F=NULL, I=NULL
71 a library having it run "transfertodo", and clic on the list
72 if there is no transfer to do, the reserve waiting
73 patron can pick it up P =0, F=W, I=filled
74 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
75 The pickup library recieve the book, it check in P =0, F=W, I=filled
76 The patron borrow the book P =0, F=F, I=filled
78 ==== 2nd use case ====
79 patron requests a document, a given item,
80 If pickup is holding branch P =0, F=W, I=filled
81 If transfer needed, write in branchtransfer P =0, F=T, I=filled
82 The pickup library receive the book, it checks it in P =0, F=W, I=filled
83 The patron borrow the book P =0, F=F, I=filled
90 # set the version for version checking
91 $VERSION = 3.07.00.049;
97 &GetReservesFromItemnumber
98 &GetReservesFromBiblionumber
99 &GetReservesFromBorrowernumber
100 &GetReservesForBranch
114 &ModReserveMinusPriority
121 &CancelExpiredReserves
123 &AutoUnsuspendReserves
125 &IsAvailableForItemLevelRequest
128 &ToggleLowestPriority
134 &GetReservesControlBranch
136 @EXPORT_OK = qw( MergeHolds );
141 AddReserve($branch,$borrowernumber,$biblionumber,$constraint,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
147 $branch, $borrowernumber, $biblionumber,
148 $constraint, $bibitems, $priority, $resdate, $expdate, $notes,
149 $title, $checkitem, $found
152 GetReserveFee($borrowernumber, $biblionumber, $constraint,
154 my $dbh = C4::Context->dbh;
155 my $const = lc substr( $constraint, 0, 1 );
156 $resdate = format_date_in_iso( $resdate ) if ( $resdate );
157 $resdate = C4::Dates->today( 'iso' ) unless ( $resdate );
159 $expdate = format_date_in_iso( $expdate );
161 undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
163 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
164 # Make room in reserves for this before those of a later reserve date
165 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
169 # If the reserv had the waiting status, we had the value of the resdate
170 if ( $found eq 'W' ) {
171 $waitingdate = $resdate;
175 # updates take place here
177 my $nextacctno = &getnextacctno( $borrowernumber );
179 INSERT INTO accountlines
180 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
182 (?,?,now(),?,?,'Res',?)
184 my $usth = $dbh->prepare($query);
185 $usth->execute( $borrowernumber, $nextacctno, $fee,
186 "Reserve Charge - $title", $fee );
192 (borrowernumber,biblionumber,reservedate,branchcode,constrainttype,
193 priority,reservenotes,itemnumber,found,waitingdate,expirationdate)
198 my $sth = $dbh->prepare($query);
200 $borrowernumber, $biblionumber, $resdate, $branch,
201 $const, $priority, $notes, $checkitem,
202 $found, $waitingdate, $expdate
205 # Send e-mail to librarian if syspref is active
206 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
207 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
208 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
209 if ( my $letter = C4::Letters::GetPreparedLetter (
210 module => 'reserves',
211 letter_code => 'HOLDPLACED',
212 branchcode => $branch,
214 'branches' => $branch_details,
215 'borrowers' => $borrower,
216 'biblio' => $biblionumber,
220 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
222 C4::Letters::EnqueueLetter(
224 borrowernumber => $borrowernumber,
225 message_transport_type => 'email',
226 from_address => $admin_email_address,
227 to_address => $admin_email_address,
234 ($const eq "o" || $const eq "e") or return; # FIXME: why not have a useful return value?
236 INSERT INTO reserveconstraints
237 (borrowernumber,biblionumber,reservedate,biblioitemnumber)
241 $sth = $dbh->prepare($query); # keep prepare outside the loop!
242 foreach (@$bibitems) {
243 $sth->execute($borrowernumber, $biblionumber, $resdate, $_);
246 return; # FIXME: why not have a useful return value?
249 =head2 GetReservesFromBiblionumber
251 ($count, $title_reserves) = &GetReserves($biblionumber);
253 This function gets the list of reservations for one C<$biblionumber>, returning a count
254 of the reserves and an arrayref pointing to the reserves for C<$biblionumber>.
258 sub GetReservesFromBiblionumber {
259 my ($biblionumber) = shift or return (0, []);
260 my ($all_dates) = shift;
261 my $dbh = C4::Context->dbh;
263 # Find the desired items in the reserves
266 timestamp AS rtimestamp,
280 WHERE biblionumber = ? ";
281 unless ( $all_dates ) {
282 $query .= "AND reservedate <= CURRENT_DATE()";
284 $query .= "ORDER BY priority";
285 my $sth = $dbh->prepare($query);
286 $sth->execute($biblionumber);
289 while ( my $data = $sth->fetchrow_hashref ) {
291 # FIXME - What is this doing? How do constraints work?
292 if ($data->{constrainttype} eq 'o') {
294 SELECT biblioitemnumber
295 FROM reserveconstraints
296 WHERE biblionumber = ?
297 AND borrowernumber = ?
300 my $csth = $dbh->prepare($query);
301 $csth->execute($data->{biblionumber}, $data->{borrowernumber}, $data->{reservedate});
303 while ( my $bibitemnos = $csth->fetchrow_array ) {
304 push( @bibitemno, $bibitemnos ); # FIXME: inefficient: use fetchall_arrayref
306 my $count = scalar @bibitemno;
308 # if we have two or more different specific itemtypes
309 # reserved by same person on same day
312 $bdata = GetBiblioItemData( $bibitemno[$i] ); # FIXME: This doesn't make sense.
313 $i++; # $i can increase each pass, but the next @bibitemno might be smaller?
316 # Look up the book we just found.
317 $bdata = GetBiblioItemData( $bibitemno[0] );
319 # Add the results of this latest search to the current
321 # FIXME - An 'each' would probably be more efficient.
322 foreach my $key ( keys %$bdata ) {
323 $data->{$key} = $bdata->{$key};
326 push @results, $data;
328 return ( $#results + 1, \@results );
331 =head2 GetReservesFromItemnumber
333 ( $reservedate, $borrowernumber, $branchcode ) = GetReservesFromItemnumber($itemnumber);
335 TODO :: Description here
339 sub GetReservesFromItemnumber {
340 my ( $itemnumber, $all_dates ) = @_;
341 my $dbh = C4::Context->dbh;
343 SELECT reservedate,borrowernumber,branchcode
347 unless ( $all_dates ) {
348 $query .= " AND reservedate <= CURRENT_DATE()";
350 my $sth_res = $dbh->prepare($query);
351 $sth_res->execute($itemnumber);
352 my ( $reservedate, $borrowernumber,$branchcode ) = $sth_res->fetchrow_array;
353 return ( $reservedate, $borrowernumber, $branchcode );
356 =head2 GetReservesFromBorrowernumber
358 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
364 sub GetReservesFromBorrowernumber {
365 my ( $borrowernumber, $status ) = @_;
366 my $dbh = C4::Context->dbh;
369 $sth = $dbh->prepare("
372 WHERE borrowernumber=?
376 $sth->execute($borrowernumber,$status);
378 $sth = $dbh->prepare("
381 WHERE borrowernumber=?
384 $sth->execute($borrowernumber);
386 my $data = $sth->fetchall_arrayref({});
389 #-------------------------------------------------------------------------------------
390 =head2 CanBookBeReserved
392 $error = &CanBookBeReserved($borrowernumber, $biblionumber)
396 sub CanBookBeReserved{
397 my ($borrowernumber, $biblionumber) = @_;
399 my $items = GetItemnumbersForBiblio($biblionumber);
400 #get items linked via host records
401 my @hostitems = get_hostitemnumbers_of($biblionumber);
403 push (@$items,@hostitems);
406 foreach my $item (@$items){
407 return 1 if CanItemBeReserved($borrowernumber, $item);
412 =head2 CanItemBeReserved
414 $error = &CanItemBeReserved($borrowernumber, $itemnumber)
416 This function return 1 if an item can be issued by this borrower.
420 sub CanItemBeReserved{
421 my ($borrowernumber, $itemnumber) = @_;
423 my $dbh = C4::Context->dbh;
424 my $allowedreserves = 0;
426 my $controlbranch = C4::Context->preference('ReservesControlBranch');
427 my $itype = C4::Context->preference('item-level_itypes') ? "itype" : "itemtype";
429 # we retrieve borrowers and items informations #
430 my $item = GetItem($itemnumber);
431 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
433 # we retrieve user rights on this itemtype and branchcode
434 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
436 WHERE (categorycode in (?,'*') )
437 AND (itemtype IN (?,'*'))
438 AND (branchcode IN (?,'*'))
445 my $querycount ="SELECT
448 LEFT JOIN items USING (itemnumber)
449 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
450 LEFT JOIN borrowers USING (borrowernumber)
451 WHERE borrowernumber = ?
455 my $itemtype = $item->{$itype};
456 my $categorycode = $borrower->{categorycode};
458 my $branchfield = "reserves.branchcode";
460 if( $controlbranch eq "ItemHomeLibrary" ){
461 $branchfield = "items.homebranch";
462 $branchcode = $item->{homebranch};
463 }elsif( $controlbranch eq "PatronLibrary" ){
464 $branchfield = "borrowers.branchcode";
465 $branchcode = $borrower->{branchcode};
469 $sth->execute($categorycode, $itemtype, $branchcode);
470 if(my $rights = $sth->fetchrow_hashref()){
471 $itemtype = $rights->{itemtype};
472 $allowedreserves = $rights->{reservesallowed};
479 $querycount .= "AND $branchfield = ?";
481 $querycount .= " AND $itype = ?" if ($itemtype ne "*");
482 my $sthcount = $dbh->prepare($querycount);
484 if($itemtype eq "*"){
485 $sthcount->execute($borrowernumber, $branchcode);
487 $sthcount->execute($borrowernumber, $branchcode, $itemtype);
490 my $reservecount = "0";
491 if(my $rowcount = $sthcount->fetchrow_hashref()){
492 $reservecount = $rowcount->{count};
495 # we check if it's ok or not
496 if( $reservecount >= $allowedreserves ){
500 # If reservecount is ok, we check item branch if IndependentBranches is ON
501 # and canreservefromotherbranches is OFF
502 if ( C4::Context->preference('IndependentBranches')
503 and !C4::Context->preference('canreservefromotherbranches') )
505 my $itembranch = $item->{homebranch};
506 if ($itembranch ne $borrower->{branchcode}) {
513 #--------------------------------------------------------------------------------
514 =head2 GetReserveCount
516 $number = &GetReserveCount($borrowernumber);
518 this function returns the number of reservation for a borrower given on input arg.
522 sub GetReserveCount {
523 my ($borrowernumber) = @_;
525 my $dbh = C4::Context->dbh;
528 SELECT COUNT(*) AS counter
530 WHERE borrowernumber = ?
532 my $sth = $dbh->prepare($query);
533 $sth->execute($borrowernumber);
534 my $row = $sth->fetchrow_hashref;
535 return $row->{counter};
538 =head2 GetOtherReserves
540 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
542 Check queued list of this document and check if this document must be transfered
546 sub GetOtherReserves {
547 my ($itemnumber) = @_;
550 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
551 if ($checkreserves) {
552 my $iteminfo = GetItem($itemnumber);
553 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
554 $messages->{'transfert'} = $checkreserves->{'branchcode'};
555 #minus priorities of others reservs
556 ModReserveMinusPriority(
558 $checkreserves->{'borrowernumber'},
559 $iteminfo->{'biblionumber'}
562 #launch the subroutine dotransfer
563 C4::Items::ModItemTransfer(
565 $iteminfo->{'holdingbranch'},
566 $checkreserves->{'branchcode'}
571 #step 2b : case of a reservation on the same branch, set the waiting status
573 $messages->{'waiting'} = 1;
574 ModReserveMinusPriority(
576 $checkreserves->{'borrowernumber'},
577 $iteminfo->{'biblionumber'}
579 ModReserveStatus($itemnumber,'W');
582 $nextreservinfo = $checkreserves->{'borrowernumber'};
585 return ( $messages, $nextreservinfo );
590 $fee = GetReserveFee($borrowernumber,$biblionumber,$constraint,$biblionumber);
592 Calculate the fee for a reserve
597 my ($borrowernumber, $biblionumber, $constraint, $bibitems ) = @_;
600 my $dbh = C4::Context->dbh;
601 my $const = lc substr( $constraint, 0, 1 );
603 SELECT * FROM borrowers
604 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
605 WHERE borrowernumber = ?
607 my $sth = $dbh->prepare($query);
608 $sth->execute($borrowernumber);
609 my $data = $sth->fetchrow_hashref;
611 my $fee = $data->{'reservefee'};
612 my $cntitems = @- > $bibitems;
616 # check for items on issue
617 # first find biblioitem records
619 my $sth1 = $dbh->prepare(
620 "SELECT * FROM biblio LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
621 WHERE (biblio.biblionumber = ?)"
623 $sth1->execute($biblionumber);
624 while ( my $data1 = $sth1->fetchrow_hashref ) {
625 if ( $const eq "a" ) {
626 push @biblioitems, $data1;
631 while ( $x < $cntitems ) {
632 if ( @$bibitems->{'biblioitemnumber'} ==
633 $data->{'biblioitemnumber'} )
639 if ( $const eq 'o' ) {
641 push @biblioitems, $data1;
646 push @biblioitems, $data1;
652 my $cntitemsfound = @biblioitems;
656 while ( $x < $cntitemsfound ) {
657 my $bitdata = $biblioitems[$x];
658 my $sth2 = $dbh->prepare(
660 WHERE biblioitemnumber = ?"
662 $sth2->execute( $bitdata->{'biblioitemnumber'} );
663 while ( my $itdata = $sth2->fetchrow_hashref ) {
664 my $sth3 = $dbh->prepare(
665 "SELECT * FROM issues
666 WHERE itemnumber = ?"
668 $sth3->execute( $itdata->{'itemnumber'} );
669 if ( my $isdata = $sth3->fetchrow_hashref ) {
677 if ( $allissued == 0 ) {
679 $dbh->prepare("SELECT * FROM reserves WHERE biblionumber = ?");
680 $rsth->execute($biblionumber);
681 if ( my $rdata = $rsth->fetchrow_hashref ) {
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 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;
727 my $query = "SELECT borrowernumber,reservedate,itemnumber,waitingdate
732 $query .= " AND branchcode=? ";
734 $query .= "ORDER BY waitingdate" ;
735 my $sth = $dbh->prepare($query);
737 $sth->execute($frombranch);
744 while ( my $data = $sth->fetchrow_hashref ) {
745 $transreserv[$i] = $data;
748 return (@transreserv);
751 =head2 GetReserveStatus
753 $reservestatus = GetReserveStatus($itemnumber, $biblionumber);
755 Take an itemnumber or a biblionumber and return the status of the reserve places on it.
756 If several reserves exist, the reserve with the lower priority is given.
760 sub GetReserveStatus {
761 my ($itemnumber, $biblionumber) = @_;
763 my $dbh = C4::Context->dbh;
765 my ($sth, $found, $priority);
767 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
768 $sth->execute($itemnumber);
769 ($found, $priority) = $sth->fetchrow_array;
772 if ( $biblionumber and not defined $found and not defined $priority ) {
773 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE biblionumber = ? order by priority LIMIT 1");
774 $sth->execute($biblionumber);
775 ($found, $priority) = $sth->fetchrow_array;
779 return 'Waiting' if $found eq 'W' and $priority == 0;
780 return 'Finished' if $found eq 'F';
781 return 'Reserved' if $priority > 0;
784 #empty string here will remove need for checking undef, or less log lines
789 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
790 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
792 Find a book in the reserves.
794 C<$itemnumber> is the book's item number.
796 As I understand it, C<&CheckReserves> looks for the given item in the
797 reserves. If it is found, that's a match, and C<$status> is set to
800 Otherwise, it finds the most important item in the reserves with the
801 same biblio number as this book (I'm not clear on this) and returns it
802 with C<$status> set to C<Reserved>.
804 C<&CheckReserves> returns a two-element list:
806 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
808 C<$reserve> is the reserve item that matched. It is a
809 reference-to-hash whose keys are mostly the fields of the reserves
810 table in the Koha database.
815 my ( $item, $barcode ) = @_;
816 my $dbh = C4::Context->dbh;
819 if (C4::Context->preference('item-level_itypes')){
821 SELECT items.biblionumber,
822 items.biblioitemnumber,
823 itemtypes.notforloan,
824 items.notforloan AS itemnotforloan,
827 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
828 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
833 SELECT items.biblionumber,
834 items.biblioitemnumber,
835 itemtypes.notforloan,
836 items.notforloan AS itemnotforloan,
839 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
840 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
845 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
846 $sth->execute($item);
849 $sth = $dbh->prepare("$select WHERE barcode = ?");
850 $sth->execute($barcode);
852 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
853 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber ) = $sth->fetchrow_array;
855 return ( '' ) unless $itemnumber; # bail if we got nothing.
857 # if item is not for loan it cannot be reserved either.....
858 # execpt where items.notforloan < 0 : This indicates the item is holdable.
859 return ( '' ) if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
861 # Find this item in the reserves
862 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber );
864 # $priority and $highest are used to find the most important item
865 # in the list returned by &_Findgroupreserve. (The lower $priority,
866 # the more important the item.)
867 # $highest is the most important item we've seen so far.
869 if (scalar @reserves) {
870 my $priority = 10000000;
871 foreach my $res (@reserves) {
872 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
873 return ( "Waiting", $res, \@reserves ); # Found it
875 # See if this item is more important than what we've got so far
876 if ( $res->{'priority'} && $res->{'priority'} < $priority ) {
877 my $borrowerinfo=C4::Members::GetMember(borrowernumber => $res->{'borrowernumber'});
878 my $iteminfo=C4::Items::GetItem($itemnumber);
879 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
880 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
881 next if ($branchitemrule->{'holdallowed'} == 0);
882 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
883 $priority = $res->{'priority'};
890 # If we get this far, then no exact match was found.
891 # We return the most important (i.e. next) reservation.
893 $highest->{'itemnumber'} = $item;
894 return ( "Reserved", $highest, \@reserves );
900 =head2 CancelExpiredReserves
902 CancelExpiredReserves();
904 Cancels all reserves with an expiration date from before today.
908 sub CancelExpiredReserves {
910 # Cancel reserves that have passed their expiration date.
911 my $dbh = C4::Context->dbh;
912 my $sth = $dbh->prepare( "
913 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
914 AND expirationdate IS NOT NULL
919 while ( my $res = $sth->fetchrow_hashref() ) {
920 CancelReserve( $res->{'biblionumber'}, '', $res->{'borrowernumber'} );
923 # Cancel reserves that have been waiting too long
924 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
925 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
926 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
928 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
929 $sth = $dbh->prepare( $query );
930 $sth->execute( $max_pickup_delay );
932 while (my $res = $sth->fetchrow_hashref ) {
934 manualinvoice($res->{'borrowernumber'}, $res->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
937 CancelReserve( $res->{'biblionumber'}, '', $res->{'borrowernumber'} );
943 =head2 AutoUnsuspendReserves
945 AutoUnsuspendReserves();
947 Unsuspends all suspended reserves with a suspend_until date from before today.
951 sub AutoUnsuspendReserves {
953 my $dbh = C4::Context->dbh;
955 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
956 my $sth = $dbh->prepare( $query );
963 &CancelReserve($biblionumber, $itemnumber, $borrowernumber);
967 Use either C<$biblionumber> or C<$itemnumber> to specify the item to
968 cancel, but not both: if both are given, C<&CancelReserve> uses
971 C<$borrowernumber> is the borrower number of the patron on whose
972 behalf the book was reserved.
974 If C<$biblionumber> was given, C<&CancelReserve> also adjusts the
975 priorities of the other people who are waiting on the book.
980 my ( $biblio, $item, $borr ) = @_;
981 my $dbh = C4::Context->dbh;
982 if ( $item and $borr ) {
983 # removing a waiting reserve record....
984 # update the database...
987 SET cancellationdate = now(),
991 AND borrowernumber = ?
993 my $sth = $dbh->prepare($query);
994 $sth->execute( $item, $borr );
997 INSERT INTO old_reserves
998 SELECT * FROM reserves
1000 AND borrowernumber = ?
1002 $sth = $dbh->prepare($query);
1003 $sth->execute( $item, $borr );
1005 DELETE FROM reserves
1006 WHERE itemnumber = ?
1007 AND borrowernumber = ?
1009 $sth = $dbh->prepare($query);
1010 $sth->execute( $item, $borr );
1013 # removing a reserve record....
1014 # get the prioritiy on this record....
1017 SELECT priority FROM reserves
1018 WHERE biblionumber = ?
1019 AND borrowernumber = ?
1020 AND cancellationdate IS NULL
1021 AND itemnumber IS NULL
1023 my $sth = $dbh->prepare($query);
1024 $sth->execute( $biblio, $borr );
1025 ($priority) = $sth->fetchrow_array;
1029 SET cancellationdate = now(),
1032 WHERE biblionumber = ?
1033 AND borrowernumber = ?
1036 # update the database, removing the record...
1037 $sth = $dbh->prepare($query);
1038 $sth->execute( $biblio, $borr );
1042 INSERT INTO old_reserves
1043 SELECT * FROM reserves
1044 WHERE biblionumber = ?
1045 AND borrowernumber = ?
1047 $sth = $dbh->prepare($query);
1048 $sth->execute( $biblio, $borr );
1051 DELETE FROM reserves
1052 WHERE biblionumber = ?
1053 AND borrowernumber = ?
1055 $sth = $dbh->prepare($query);
1056 $sth->execute( $biblio, $borr );
1058 # now fix the priority on the others....
1059 _FixPriority( $biblio, $borr );
1065 ModReserve($rank, $biblio, $borrower, $branch[, $itemnumber])
1067 Change a hold request's priority or cancel it.
1069 C<$rank> specifies the effect of the change. If C<$rank>
1070 is 'W' or 'n', nothing happens. This corresponds to leaving a
1071 request alone when changing its priority in the holds queue
1074 If C<$rank> is 'del', the hold request is cancelled.
1076 If C<$rank> is an integer greater than zero, the priority of
1077 the request is set to that value. Since priority != 0 means
1078 that the item is not waiting on the hold shelf, setting the
1079 priority to a non-zero value also sets the request's found
1080 status and waiting date to NULL.
1082 The optional C<$itemnumber> parameter is used only when
1083 C<$rank> is a non-zero integer; if supplied, the itemnumber
1084 of the hold request is set accordingly; if omitted, the itemnumber
1087 B<FIXME:> Note that the forgoing can have the effect of causing
1088 item-level hold requests to turn into title-level requests. This
1089 will be fixed once reserves has separate columns for requested
1090 itemnumber and supplying itemnumber.
1095 #subroutine to update a reserve
1096 my ( $rank, $biblio, $borrower, $branch , $itemnumber, $suspend_until) = @_;
1097 return if $rank eq "W";
1098 return if $rank eq "n";
1099 my $dbh = C4::Context->dbh;
1100 if ( $rank eq "del" ) {
1103 SET cancellationdate=now()
1104 WHERE biblionumber = ?
1105 AND borrowernumber = ?
1107 my $sth = $dbh->prepare($query);
1108 $sth->execute( $biblio, $borrower );
1111 INSERT INTO old_reserves
1114 WHERE biblionumber = ?
1115 AND borrowernumber = ?
1117 $sth = $dbh->prepare($query);
1118 $sth->execute( $biblio, $borrower );
1120 DELETE FROM reserves
1121 WHERE biblionumber = ?
1122 AND borrowernumber = ?
1124 $sth = $dbh->prepare($query);
1125 $sth->execute( $biblio, $borrower );
1128 elsif ($rank =~ /^\d+/ and $rank > 0) {
1130 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1131 WHERE biblionumber = ?
1132 AND borrowernumber = ?
1134 my $sth = $dbh->prepare($query);
1135 $sth->execute( $rank, $branch,$itemnumber, $biblio, $borrower);
1138 if ( defined( $suspend_until ) ) {
1139 if ( $suspend_until ) {
1140 $suspend_until = C4::Dates->new( $suspend_until )->output("iso");
1141 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE biblionumber = ? AND borrowernumber = ?", undef, ( $suspend_until, $biblio, $borrower ) );
1143 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE biblionumber = ? AND borrowernumber = ?", undef, ( $biblio, $borrower ) );
1147 _FixPriority( $biblio, $borrower, $rank);
1151 =head2 ModReserveFill
1153 &ModReserveFill($reserve);
1155 Fill a reserve. If I understand this correctly, this means that the
1156 reserved book has been found and given to the patron who reserved it.
1158 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1159 whose keys are fields from the reserves table in the Koha database.
1163 sub ModReserveFill {
1165 my $dbh = C4::Context->dbh;
1166 # fill in a reserve record....
1167 my $biblionumber = $res->{'biblionumber'};
1168 my $borrowernumber = $res->{'borrowernumber'};
1169 my $resdate = $res->{'reservedate'};
1171 # get the priority on this record....
1173 my $query = "SELECT priority
1175 WHERE biblionumber = ?
1176 AND borrowernumber = ?
1177 AND reservedate = ?";
1178 my $sth = $dbh->prepare($query);
1179 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1180 ($priority) = $sth->fetchrow_array;
1183 # update the database...
1184 $query = "UPDATE reserves
1187 WHERE biblionumber = ?
1189 AND borrowernumber = ?
1191 $sth = $dbh->prepare($query);
1192 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1195 # move to old_reserves
1196 $query = "INSERT INTO old_reserves
1197 SELECT * FROM reserves
1198 WHERE biblionumber = ?
1200 AND borrowernumber = ?
1202 $sth = $dbh->prepare($query);
1203 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1204 $query = "DELETE FROM reserves
1205 WHERE biblionumber = ?
1207 AND borrowernumber = ?
1209 $sth = $dbh->prepare($query);
1210 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1212 # now fix the priority on the others (if the priority wasn't
1213 # already sorted!)....
1214 unless ( $priority == 0 ) {
1215 _FixPriority( $biblionumber, $borrowernumber );
1219 =head2 ModReserveStatus
1221 &ModReserveStatus($itemnumber, $newstatus);
1223 Update the reserve status for the active (priority=0) reserve.
1225 $itemnumber is the itemnumber the reserve is on
1227 $newstatus is the new status.
1231 sub ModReserveStatus {
1233 #first : check if we have a reservation for this item .
1234 my ($itemnumber, $newstatus) = @_;
1235 my $dbh = C4::Context->dbh;
1237 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1238 my $sth_set = $dbh->prepare($query);
1239 $sth_set->execute( $newstatus, $itemnumber );
1241 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1242 CartToShelf( $itemnumber );
1246 =head2 ModReserveAffect
1248 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1250 This function affect an item and a status for a given reserve
1251 The itemnumber parameter is used to find the biblionumber.
1252 with the biblionumber & the borrowernumber, we can affect the itemnumber
1253 to the correct reserve.
1255 if $transferToDo is not set, then the status is set to "Waiting" as well.
1256 otherwise, a transfer is on the way, and the end of the transfer will
1257 take care of the waiting status
1261 sub ModReserveAffect {
1262 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1263 my $dbh = C4::Context->dbh;
1265 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1266 # attached to $itemnumber
1267 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1268 $sth->execute($itemnumber);
1269 my ($biblionumber) = $sth->fetchrow;
1271 # get request - need to find out if item is already
1272 # waiting in order to not send duplicate hold filled notifications
1273 my $request = GetReserveInfo($borrowernumber, $biblionumber);
1274 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1276 # If we affect a reserve that has to be transfered, don't set to Waiting
1278 if ($transferToDo) {
1284 WHERE borrowernumber = ?
1285 AND biblionumber = ?
1289 # affect the reserve to Waiting as well.
1294 waitingdate = NOW(),
1296 WHERE borrowernumber = ?
1297 AND biblionumber = ?
1300 $sth = $dbh->prepare($query);
1301 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1302 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1304 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1305 CartToShelf( $itemnumber );
1311 =head2 ModReserveCancelAll
1313 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1315 function to cancel reserv,check other reserves, and transfer document if it's necessary
1319 sub ModReserveCancelAll {
1322 my ( $itemnumber, $borrowernumber ) = @_;
1324 #step 1 : cancel the reservation
1325 my $CancelReserve = CancelReserve( undef, $itemnumber, $borrowernumber );
1327 #step 2 launch the subroutine of the others reserves
1328 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1330 return ( $messages, $nextreservinfo );
1333 =head2 ModReserveMinusPriority
1335 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1337 Reduce the values of queuded list
1341 sub ModReserveMinusPriority {
1342 my ( $itemnumber, $borrowernumber, $biblionumber ) = @_;
1344 #first step update the value of the first person on reserv
1345 my $dbh = C4::Context->dbh;
1348 SET priority = 0 , itemnumber = ?
1349 WHERE borrowernumber=?
1352 my $sth_upd = $dbh->prepare($query);
1353 $sth_upd->execute( $itemnumber, $borrowernumber, $biblionumber );
1354 # second step update all others reservs
1355 _FixPriority($biblionumber, $borrowernumber, '0');
1358 =head2 GetReserveInfo
1360 &GetReserveInfo($borrowernumber,$biblionumber);
1362 Get item and borrower details for a current hold.
1363 Current implementation this query should have a single result.
1367 sub GetReserveInfo {
1368 my ( $borrowernumber, $biblionumber ) = @_;
1369 my $dbh = C4::Context->dbh;
1373 reserves.borrowernumber,
1374 reserves.biblionumber,
1375 reserves.branchcode,
1376 reserves.waitingdate,
1392 items.holdingbranch,
1393 items.itemcallnumber,
1399 LEFT JOIN items USING(itemnumber)
1400 LEFT JOIN borrowers USING(borrowernumber)
1401 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1403 reserves.borrowernumber=?
1404 AND reserves.biblionumber=?";
1405 my $sth = $dbh->prepare($strsth);
1406 $sth->execute($borrowernumber,$biblionumber);
1408 my $data = $sth->fetchrow_hashref;
1413 =head2 IsAvailableForItemLevelRequest
1415 my $is_available = IsAvailableForItemLevelRequest($itemnumber);
1417 Checks whether a given item record is available for an
1418 item-level hold request. An item is available if
1420 * it is not lost AND
1421 * it is not damaged AND
1422 * it is not withdrawn AND
1423 * does not have a not for loan value > 0
1425 Whether or not the item is currently on loan is
1426 also checked - if the AllowOnShelfHolds system preference
1427 is ON, an item can be requested even if it is currently
1428 on loan to somebody else. If the system preference
1429 is OFF, an item that is currently checked out cannot
1430 be the target of an item-level hold request.
1432 Note that IsAvailableForItemLevelRequest() does not
1433 check if the staff operator is authorized to place
1434 a request on the item - in particular,
1435 this routine does not check IndependantBranches
1436 and canreservefromotherbranches.
1440 sub IsAvailableForItemLevelRequest {
1441 my $itemnumber = shift;
1443 my $item = GetItem($itemnumber);
1445 # must check the notforloan setting of the itemtype
1446 # FIXME - a lot of places in the code do this
1447 # or something similar - need to be
1449 my $dbh = C4::Context->dbh;
1450 my $notforloan_query;
1451 if (C4::Context->preference('item-level_itypes')) {
1452 $notforloan_query = "SELECT itemtypes.notforloan
1454 JOIN itemtypes ON (itemtypes.itemtype = items.itype)
1455 WHERE itemnumber = ?";
1457 $notforloan_query = "SELECT itemtypes.notforloan
1459 JOIN biblioitems USING (biblioitemnumber)
1460 JOIN itemtypes USING (itemtype)
1461 WHERE itemnumber = ?";
1463 my $sth = $dbh->prepare($notforloan_query);
1464 $sth->execute($itemnumber);
1465 my $notforloan_per_itemtype = 0;
1466 if (my ($notforloan) = $sth->fetchrow_array) {
1467 $notforloan_per_itemtype = 1 if $notforloan;
1470 my $available_per_item = 1;
1471 $available_per_item = 0 if $item->{itemlost} or
1472 ( $item->{notforloan} > 0 ) or
1473 ($item->{damaged} and not C4::Context->preference('AllowHoldsOnDamagedItems')) or
1474 $item->{wthdrawn} or
1475 $notforloan_per_itemtype;
1478 if (C4::Context->preference('AllowOnShelfHolds')) {
1479 return $available_per_item;
1481 return ($available_per_item and ($item->{onloan} or GetReserveStatus($itemnumber) eq "Waiting"));
1485 =head2 AlterPriority
1487 AlterPriority( $where, $borrowernumber, $biblionumber, $reservedate );
1489 This function changes a reserve's priority up, down, to the top, or to the bottom.
1490 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1495 my ( $where, $borrowernumber, $biblionumber ) = @_;
1497 my $dbh = C4::Context->dbh;
1499 ## Find this reserve
1500 my $sth = $dbh->prepare('SELECT * FROM reserves WHERE biblionumber = ? AND borrowernumber = ? AND cancellationdate IS NULL');
1501 $sth->execute( $biblionumber, $borrowernumber );
1502 my $reserve = $sth->fetchrow_hashref();
1505 if ( $where eq 'up' || $where eq 'down' ) {
1507 my $priority = $reserve->{'priority'};
1508 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1509 _FixPriority( $biblionumber, $borrowernumber, $priority )
1511 } elsif ( $where eq 'top' ) {
1513 _FixPriority( $biblionumber, $borrowernumber, '1' )
1515 } elsif ( $where eq 'bottom' ) {
1517 _FixPriority( $biblionumber, $borrowernumber, '999999' )
1522 =head2 ToggleLowestPriority
1524 ToggleLowestPriority( $borrowernumber, $biblionumber );
1526 This function sets the lowestPriority field to true if is false, and false if it is true.
1530 sub ToggleLowestPriority {
1531 my ( $borrowernumber, $biblionumber ) = @_;
1533 my $dbh = C4::Context->dbh;
1535 my $sth = $dbh->prepare(
1536 "UPDATE reserves SET lowestPriority = NOT lowestPriority
1537 WHERE biblionumber = ?
1538 AND borrowernumber = ?"
1546 _FixPriority( $biblionumber, $borrowernumber, '999999' );
1549 =head2 ToggleSuspend
1551 ToggleSuspend( $borrowernumber, $biblionumber );
1553 This function sets the suspend field to true if is false, and false if it is true.
1554 If the reserve is currently suspended with a suspend_until date, that date will
1555 be cleared when it is unsuspended.
1560 my ( $borrowernumber, $biblionumber, $suspend_until ) = @_;
1562 $suspend_until = output_pref( dt_from_string( $suspend_until ), 'iso' ) if ( $suspend_until );
1564 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1566 my $dbh = C4::Context->dbh;
1568 my $sth = $dbh->prepare(
1569 "UPDATE reserves SET suspend = NOT suspend,
1570 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1571 WHERE biblionumber = ?
1572 AND borrowernumber = ?
1576 push( @params, $suspend_until ) if ( $suspend_until );
1577 push( @params, $biblionumber );
1578 push( @params, $borrowernumber );
1580 $sth->execute( @params );
1587 borrowernumber => $borrowernumber,
1588 [ biblionumber => $biblionumber, ]
1589 [ suspend_until => $suspend_until, ]
1590 [ suspend => $suspend ]
1593 This function accepts a set of hash keys as its parameters.
1594 It requires either borrowernumber or biblionumber, or both.
1596 suspend_until is wholly optional.
1603 my $borrowernumber = $params{'borrowernumber'} || undef;
1604 my $biblionumber = $params{'biblionumber'} || undef;
1605 my $suspend_until = $params{'suspend_until'} || undef;
1606 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1608 $suspend_until = C4::Dates->new( $suspend_until )->output("iso") if ( defined( $suspend_until ) );
1610 return unless ( $borrowernumber || $biblionumber );
1612 my ( $query, $sth, $dbh, @query_params );
1614 $query = "UPDATE reserves SET suspend = ? ";
1615 push( @query_params, $suspend );
1617 $query .= ", suspend_until = NULL ";
1618 } elsif ( $suspend_until ) {
1619 $query .= ", suspend_until = ? ";
1620 push( @query_params, $suspend_until );
1622 $query .= " WHERE ";
1623 if ( $borrowernumber ) {
1624 $query .= " borrowernumber = ? ";
1625 push( @query_params, $borrowernumber );
1627 $query .= " AND " if ( $borrowernumber && $biblionumber );
1628 if ( $biblionumber ) {
1629 $query .= " biblionumber = ? ";
1630 push( @query_params, $biblionumber );
1632 $query .= " AND found IS NULL ";
1634 $dbh = C4::Context->dbh;
1635 $sth = $dbh->prepare( $query );
1636 $sth->execute( @query_params );
1643 &_FixPriority($biblio,$borrowernumber,$rank,$ignoreSetLowestRank);
1645 Only used internally (so don't export it)
1646 Changed how this functions works #
1647 Now just gets an array of reserves in the rank order and updates them with
1648 the array index (+1 as array starts from 0)
1649 and if $rank is supplied will splice item from the array and splice it back in again
1650 in new priority rank
1655 my ( $biblio, $borrowernumber, $rank, $ignoreSetLowestRank ) = @_;
1656 my $dbh = C4::Context->dbh;
1657 if ( $rank eq "del" ) {
1658 CancelReserve( $biblio, undef, $borrowernumber );
1660 if ( $rank eq "W" || $rank eq "0" ) {
1662 # make sure priority for waiting or in-transit items is 0
1666 WHERE biblionumber = ?
1667 AND borrowernumber = ?
1668 AND found IN ('W', 'T')
1670 my $sth = $dbh->prepare($query);
1671 $sth->execute( $biblio, $borrowernumber );
1677 # FIXME adding a new security in returned elements for changing priority,
1678 # now, we don't care anymore any reservations with itemnumber linked (suppose a waiting reserve)
1679 # This is wrong a waiting reserve has W set
1680 # The assumption that having an itemnumber set means waiting is wrong and should be corrected any place it occurs
1682 SELECT borrowernumber, reservedate, constrainttype
1684 WHERE biblionumber = ?
1685 AND ((found <> 'W' AND found <> 'T') or found is NULL)
1686 ORDER BY priority ASC
1688 my $sth = $dbh->prepare($query);
1689 $sth->execute($biblio);
1690 while ( my $line = $sth->fetchrow_hashref ) {
1691 push( @reservedates, $line );
1692 push( @priority, $line );
1695 # To find the matching index
1697 my $key = -1; # to allow for 0 to be a valid result
1698 for ( $i = 0 ; $i < @priority ; $i++ ) {
1699 if ( $borrowernumber == $priority[$i]->{'borrowernumber'} ) {
1700 $key = $i; # save the index
1705 # if index exists in array then move it to new position
1706 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1707 my $new_rank = $rank -
1708 1; # $new_rank is what you want the new index to be in the array
1709 my $moving_item = splice( @priority, $key, 1 );
1710 splice( @priority, $new_rank, 0, $moving_item );
1713 # now fix the priority on those that are left....
1717 WHERE biblionumber = ?
1718 AND borrowernumber = ?
1722 $sth = $dbh->prepare($query);
1723 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1726 $priority[$j]->{'borrowernumber'},
1727 $priority[$j]->{'reservedate'}
1732 $sth = $dbh->prepare( "SELECT borrowernumber FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1735 unless ( $ignoreSetLowestRank ) {
1736 while ( my $res = $sth->fetchrow_hashref() ) {
1737 _FixPriority( $biblio, $res->{'borrowernumber'}, '999999', 1 );
1742 =head2 _Findgroupreserve
1744 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber);
1746 Looks for an item-specific match first, then for a title-level match, returning the
1747 first match found. If neither, then we look for a 3rd kind of match based on
1748 reserve constraints.
1750 TODO: add more explanation about reserve constraints
1752 C<&_Findgroupreserve> returns :
1753 C<@results> is an array of references-to-hash whose keys are mostly
1754 fields from the reserves table of the Koha database, plus
1755 C<biblioitemnumber>.
1759 sub _Findgroupreserve {
1760 my ( $bibitem, $biblio, $itemnumber ) = @_;
1761 my $dbh = C4::Context->dbh;
1763 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1764 # check for exact targetted match
1765 my $item_level_target_query = qq/
1766 SELECT reserves.biblionumber AS biblionumber,
1767 reserves.borrowernumber AS borrowernumber,
1768 reserves.reservedate AS reservedate,
1769 reserves.branchcode AS branchcode,
1770 reserves.cancellationdate AS cancellationdate,
1771 reserves.found AS found,
1772 reserves.reservenotes AS reservenotes,
1773 reserves.priority AS priority,
1774 reserves.timestamp AS timestamp,
1775 biblioitems.biblioitemnumber AS biblioitemnumber,
1776 reserves.itemnumber AS itemnumber
1778 JOIN biblioitems USING (biblionumber)
1779 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1782 AND item_level_request = 1
1784 AND reservedate <= CURRENT_DATE()
1787 my $sth = $dbh->prepare($item_level_target_query);
1788 $sth->execute($itemnumber);
1790 if ( my $data = $sth->fetchrow_hashref ) {
1791 push( @results, $data );
1793 return @results if @results;
1795 # check for title-level targetted match
1796 my $title_level_target_query = qq/
1797 SELECT reserves.biblionumber AS biblionumber,
1798 reserves.borrowernumber AS borrowernumber,
1799 reserves.reservedate AS reservedate,
1800 reserves.branchcode AS branchcode,
1801 reserves.cancellationdate AS cancellationdate,
1802 reserves.found AS found,
1803 reserves.reservenotes AS reservenotes,
1804 reserves.priority AS priority,
1805 reserves.timestamp AS timestamp,
1806 biblioitems.biblioitemnumber AS biblioitemnumber,
1807 reserves.itemnumber AS itemnumber
1809 JOIN biblioitems USING (biblionumber)
1810 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1813 AND item_level_request = 0
1814 AND hold_fill_targets.itemnumber = ?
1815 AND reservedate <= CURRENT_DATE()
1818 $sth = $dbh->prepare($title_level_target_query);
1819 $sth->execute($itemnumber);
1821 if ( my $data = $sth->fetchrow_hashref ) {
1822 push( @results, $data );
1824 return @results if @results;
1827 SELECT reserves.biblionumber AS biblionumber,
1828 reserves.borrowernumber AS borrowernumber,
1829 reserves.reservedate AS reservedate,
1830 reserves.waitingdate AS waitingdate,
1831 reserves.branchcode AS branchcode,
1832 reserves.cancellationdate AS cancellationdate,
1833 reserves.found AS found,
1834 reserves.reservenotes AS reservenotes,
1835 reserves.priority AS priority,
1836 reserves.timestamp AS timestamp,
1837 reserveconstraints.biblioitemnumber AS biblioitemnumber,
1838 reserves.itemnumber AS itemnumber
1840 LEFT JOIN reserveconstraints ON reserves.biblionumber = reserveconstraints.biblionumber
1841 WHERE reserves.biblionumber = ?
1842 AND ( ( reserveconstraints.biblioitemnumber = ?
1843 AND reserves.borrowernumber = reserveconstraints.borrowernumber
1844 AND reserves.reservedate = reserveconstraints.reservedate )
1845 OR reserves.constrainttype='a' )
1846 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1847 AND reserves.reservedate <= CURRENT_DATE()
1850 $sth = $dbh->prepare($query);
1851 $sth->execute( $biblio, $bibitem, $itemnumber );
1853 while ( my $data = $sth->fetchrow_hashref ) {
1854 push( @results, $data );
1859 =head2 _koha_notify_reserve
1861 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1863 Sends a notification to the patron that their hold has been filled (through
1864 ModReserveAffect, _not_ ModReserveFill)
1868 sub _koha_notify_reserve {
1869 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1871 my $dbh = C4::Context->dbh;
1872 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1874 # Try to get the borrower's email address
1875 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1880 if ( $to_address || $borrower->{'smsalertnumber'} ) {
1881 $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber, message_name => 'Hold_Filled' } );
1886 my $sth = $dbh->prepare("
1889 WHERE borrowernumber = ?
1890 AND biblionumber = ?
1892 $sth->execute( $borrowernumber, $biblionumber );
1893 my $reserve = $sth->fetchrow_hashref;
1894 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1896 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1898 my %letter_params = (
1899 module => 'reserves',
1900 branchcode => $reserve->{branchcode},
1902 'branches' => $branch_details,
1903 'borrowers' => $borrower,
1904 'biblio' => $biblionumber,
1905 'reserves' => $reserve,
1906 'items', $reserve->{'itemnumber'},
1908 substitute => { today => C4::Dates->new()->output() },
1912 if ( $print_mode ) {
1913 $letter_params{ 'letter_code' } = 'HOLD_PRINT';
1914 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1916 C4::Letters::EnqueueLetter( {
1918 borrowernumber => $borrowernumber,
1919 message_transport_type => 'print',
1925 if ( $to_address && defined $messagingprefs->{transports}->{'email'} ) {
1926 $letter_params{ 'letter_code' } = $messagingprefs->{transports}->{'email'};
1927 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1929 C4::Letters::EnqueueLetter(
1930 { letter => $letter,
1931 borrowernumber => $borrowernumber,
1932 message_transport_type => 'email',
1933 from_address => $admin_email_address,
1938 if ( $borrower->{'smsalertnumber'} && defined $messagingprefs->{transports}->{'sms'} ) {
1939 $letter_params{ 'letter_code' } = $messagingprefs->{transports}->{'sms'};
1940 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1942 C4::Letters::EnqueueLetter(
1943 { letter => $letter,
1944 borrowernumber => $borrowernumber,
1945 message_transport_type => 'sms',
1951 =head2 _ShiftPriorityByDateAndPriority
1953 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1955 This increments the priority of all reserves after the one
1956 with either the lowest date after C<$reservedate>
1957 or the lowest priority after C<$priority>.
1959 It effectively makes room for a new reserve to be inserted with a certain
1960 priority, which is returned.
1962 This is most useful when the reservedate can be set by the user. It allows
1963 the new reserve to be placed before other reserves that have a later
1964 reservedate. Since priority also is set by the form in reserves/request.pl
1965 the sub accounts for that too.
1969 sub _ShiftPriorityByDateAndPriority {
1970 my ( $biblio, $resdate, $new_priority ) = @_;
1972 my $dbh = C4::Context->dbh;
1973 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1974 my $sth = $dbh->prepare( $query );
1975 $sth->execute( $biblio, $resdate, $new_priority );
1976 my $min_priority = $sth->fetchrow;
1977 # if no such matches are found, $new_priority remains as original value
1978 $new_priority = $min_priority if ( $min_priority );
1980 # Shift the priority up by one; works in conjunction with the next SQL statement
1981 $query = "UPDATE reserves
1982 SET priority = priority+1
1983 WHERE biblionumber = ?
1984 AND borrowernumber = ?
1987 my $sth_update = $dbh->prepare( $query );
1989 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1990 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1991 $sth = $dbh->prepare( $query );
1992 $sth->execute( $new_priority, $biblio );
1993 while ( my $row = $sth->fetchrow_hashref ) {
1994 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1997 return $new_priority; # so the caller knows what priority they wind up receiving
2002 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2004 Use when checking out an item to handle reserves
2005 If $cancelreserve boolean is set to true, it will remove existing reserve
2010 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2012 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber );
2015 my $biblionumber = $res->{biblionumber};
2016 my $biblioitemnumber = $res->{biblioitemnumber};
2018 if ($res->{borrowernumber} == $borrowernumber) {
2019 ModReserveFill($res);
2023 # The item is reserved by someone else.
2024 # Find this item in the reserves
2027 foreach (@$all_reserves) {
2028 $_->{'borrowernumber'} == $borrowernumber or next;
2029 $_->{'biblionumber'} == $biblionumber or next;
2036 # The item is reserved by the current patron
2037 ModReserveFill($borr_res);
2040 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2041 RevertWaitingStatus({ itemnumber => $itemnumber });
2043 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2044 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
2045 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
2052 MergeHolds($dbh,$to_biblio, $from_biblio);
2054 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2059 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2060 my $sth = $dbh->prepare(
2061 "SELECT count(*) as reservenumber FROM reserves WHERE biblionumber = ?"
2063 $sth->execute($from_biblio);
2064 if ( my $data = $sth->fetchrow_hashref() ) {
2066 # holds exist on old record, if not we don't need to do anything
2067 $sth = $dbh->prepare(
2068 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2069 $sth->execute( $to_biblio, $from_biblio );
2072 # don't reorder those already waiting
2074 $sth = $dbh->prepare(
2075 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2077 my $upd_sth = $dbh->prepare(
2078 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2079 AND reservedate = ? AND constrainttype = ? AND (itemnumber = ? or itemnumber is NULL) "
2081 $sth->execute( $to_biblio, 'W', 'T' );
2083 while ( my $reserve = $sth->fetchrow_hashref() ) {
2085 $priority, $to_biblio,
2086 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2087 $reserve->{'constrainttype'}, $reserve->{'itemnumber'}
2094 =head2 RevertWaitingStatus
2096 $success = RevertWaitingStatus({ itemnumber => $itemnumber });
2098 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2100 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2101 item level hold, even if it was only a bibliolevel hold to
2102 begin with. This is because we can no longer know if a hold
2103 was item-level or bib-level after a hold has been set to
2108 sub RevertWaitingStatus {
2109 my ( $params ) = @_;
2110 my $itemnumber = $params->{'itemnumber'};
2112 return unless ( $itemnumber );
2114 my $dbh = C4::Context->dbh;
2116 ## Get the waiting reserve we want to revert
2118 SELECT * FROM reserves
2119 WHERE itemnumber = ?
2120 AND found IS NOT NULL
2122 my $sth = $dbh->prepare( $query );
2123 $sth->execute( $itemnumber );
2124 my $reserve = $sth->fetchrow_hashref();
2126 ## Increment the priority of all other non-waiting
2127 ## reserves for this bib record
2131 priority = priority + 1
2137 $sth = $dbh->prepare( $query );
2138 $sth->execute( $reserve->{'biblionumber'} );
2140 ## Fix up the currently waiting reserve
2150 $sth = $dbh->prepare( $query );
2151 return $sth->execute( $reserve->{'reserve_id'} );
2156 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2158 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2163 my ($branch, $borrowernumber, $biblionumber) = @_;
2165 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2167 my $reserve = GetReserveInfo($borrowernumber,$biblionumber )
2170 return C4::Letters::GetPreparedLetter (
2171 module => 'circulation',
2172 letter_code => 'RESERVESLIP',
2173 branchcode => $branch,
2175 'reserves' => $reserve,
2176 'branches' => $reserve->{branchcode},
2177 'borrowers' => $reserve->{borrowernumber},
2178 'biblio' => $reserve->{biblionumber},
2179 'items' => $reserve->{itemnumber},
2184 =head2 GetReservesControlBranch
2186 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2188 Return the branchcode to be used to determine which reserves
2189 policy applies to a transaction.
2191 C<$item> is a hashref for an item. Only 'homebranch' is used.
2193 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2197 sub GetReservesControlBranch {
2198 my ( $item, $borrower ) = @_;
2200 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2203 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2204 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2212 Koha Development Team <http://koha-community.org/>