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 @EXPORT_OK = qw( MergeHolds );
139 AddReserve($branch,$borrowernumber,$biblionumber,$constraint,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
145 $branch, $borrowernumber, $biblionumber,
146 $constraint, $bibitems, $priority, $resdate, $expdate, $notes,
147 $title, $checkitem, $found
150 GetReserveFee($borrowernumber, $biblionumber, $constraint,
152 my $dbh = C4::Context->dbh;
153 my $const = lc substr( $constraint, 0, 1 );
154 $resdate = format_date_in_iso( $resdate ) if ( $resdate );
155 $resdate = C4::Dates->today( 'iso' ) unless ( $resdate );
157 $expdate = format_date_in_iso( $expdate );
159 undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
161 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
162 # Make room in reserves for this before those of a later reserve date
163 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
167 # If the reserv had the waiting status, we had the value of the resdate
168 if ( $found eq 'W' ) {
169 $waitingdate = $resdate;
173 # updates take place here
175 my $nextacctno = &getnextacctno( $borrowernumber );
177 INSERT INTO accountlines
178 (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
180 (?,?,now(),?,?,'Res',?)
182 my $usth = $dbh->prepare($query);
183 $usth->execute( $borrowernumber, $nextacctno, $fee,
184 "Reserve Charge - $title", $fee );
190 (borrowernumber,biblionumber,reservedate,branchcode,constrainttype,
191 priority,reservenotes,itemnumber,found,waitingdate,expirationdate)
196 my $sth = $dbh->prepare($query);
198 $borrowernumber, $biblionumber, $resdate, $branch,
199 $const, $priority, $notes, $checkitem,
200 $found, $waitingdate, $expdate
203 # Send e-mail to librarian if syspref is active
204 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
205 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
206 my $branch_details = C4::Branch::GetBranchDetail($borrower->{branchcode});
207 if ( my $letter = C4::Letters::GetPreparedLetter (
208 module => 'reserves',
209 letter_code => 'HOLDPLACED',
210 branchcode => $branch,
212 'branches' => $branch_details,
213 'borrowers' => $borrower,
214 'biblio' => $biblionumber,
218 my $admin_email_address =$branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
220 C4::Letters::EnqueueLetter(
222 borrowernumber => $borrowernumber,
223 message_transport_type => 'email',
224 from_address => $admin_email_address,
225 to_address => $admin_email_address,
232 ($const eq "o" || $const eq "e") or return; # FIXME: why not have a useful return value?
234 INSERT INTO reserveconstraints
235 (borrowernumber,biblionumber,reservedate,biblioitemnumber)
239 $sth = $dbh->prepare($query); # keep prepare outside the loop!
240 foreach (@$bibitems) {
241 $sth->execute($borrowernumber, $biblionumber, $resdate, $_);
244 return; # FIXME: why not have a useful return value?
247 =head2 GetReservesFromBiblionumber
249 ($count, $title_reserves) = &GetReserves($biblionumber);
251 This function gets the list of reservations for one C<$biblionumber>, returning a count
252 of the reserves and an arrayref pointing to the reserves for C<$biblionumber>.
256 sub GetReservesFromBiblionumber {
257 my ($biblionumber) = shift or return (0, []);
258 my ($all_dates) = shift;
259 my $dbh = C4::Context->dbh;
261 # Find the desired items in the reserves
264 timestamp AS rtimestamp,
278 WHERE biblionumber = ? ";
279 unless ( $all_dates ) {
280 $query .= "AND reservedate <= CURRENT_DATE()";
282 $query .= "ORDER BY priority";
283 my $sth = $dbh->prepare($query);
284 $sth->execute($biblionumber);
287 while ( my $data = $sth->fetchrow_hashref ) {
289 # FIXME - What is this doing? How do constraints work?
290 if ($data->{constrainttype} eq 'o') {
292 SELECT biblioitemnumber
293 FROM reserveconstraints
294 WHERE biblionumber = ?
295 AND borrowernumber = ?
298 my $csth = $dbh->prepare($query);
299 $csth->execute($data->{biblionumber}, $data->{borrowernumber}, $data->{reservedate});
301 while ( my $bibitemnos = $csth->fetchrow_array ) {
302 push( @bibitemno, $bibitemnos ); # FIXME: inefficient: use fetchall_arrayref
304 my $count = scalar @bibitemno;
306 # if we have two or more different specific itemtypes
307 # reserved by same person on same day
310 $bdata = GetBiblioItemData( $bibitemno[$i] ); # FIXME: This doesn't make sense.
311 $i++; # $i can increase each pass, but the next @bibitemno might be smaller?
314 # Look up the book we just found.
315 $bdata = GetBiblioItemData( $bibitemno[0] );
317 # Add the results of this latest search to the current
319 # FIXME - An 'each' would probably be more efficient.
320 foreach my $key ( keys %$bdata ) {
321 $data->{$key} = $bdata->{$key};
324 push @results, $data;
326 return ( $#results + 1, \@results );
329 =head2 GetReservesFromItemnumber
331 ( $reservedate, $borrowernumber, $branchcode ) = GetReservesFromItemnumber($itemnumber);
333 TODO :: Description here
337 sub GetReservesFromItemnumber {
338 my ( $itemnumber, $all_dates ) = @_;
339 my $dbh = C4::Context->dbh;
341 SELECT reservedate,borrowernumber,branchcode
345 unless ( $all_dates ) {
346 $query .= " AND reservedate <= CURRENT_DATE()";
348 my $sth_res = $dbh->prepare($query);
349 $sth_res->execute($itemnumber);
350 my ( $reservedate, $borrowernumber,$branchcode ) = $sth_res->fetchrow_array;
351 return ( $reservedate, $borrowernumber, $branchcode );
354 =head2 GetReservesFromBorrowernumber
356 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
362 sub GetReservesFromBorrowernumber {
363 my ( $borrowernumber, $status ) = @_;
364 my $dbh = C4::Context->dbh;
367 $sth = $dbh->prepare("
370 WHERE borrowernumber=?
374 $sth->execute($borrowernumber,$status);
376 $sth = $dbh->prepare("
379 WHERE borrowernumber=?
382 $sth->execute($borrowernumber);
384 my $data = $sth->fetchall_arrayref({});
387 #-------------------------------------------------------------------------------------
388 =head2 CanBookBeReserved
390 $error = &CanBookBeReserved($borrowernumber, $biblionumber)
394 sub CanBookBeReserved{
395 my ($borrowernumber, $biblionumber) = @_;
397 my $items = GetItemnumbersForBiblio($biblionumber);
398 #get items linked via host records
399 my @hostitems = get_hostitemnumbers_of($biblionumber);
401 push (@$items,@hostitems);
404 foreach my $item (@$items){
405 return 1 if CanItemBeReserved($borrowernumber, $item);
410 =head2 CanItemBeReserved
412 $error = &CanItemBeReserved($borrowernumber, $itemnumber)
414 This function return 1 if an item can be issued by this borrower.
418 sub CanItemBeReserved{
419 my ($borrowernumber, $itemnumber) = @_;
421 my $dbh = C4::Context->dbh;
422 my $allowedreserves = 0;
424 my $controlbranch = C4::Context->preference('ReservesControlBranch');
425 my $itype = C4::Context->preference('item-level_itypes') ? "itype" : "itemtype";
427 # we retrieve borrowers and items informations #
428 my $item = GetItem($itemnumber);
429 my $borrower = C4::Members::GetMember('borrowernumber'=>$borrowernumber);
431 # we retrieve user rights on this itemtype and branchcode
432 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
434 WHERE (categorycode in (?,'*') )
435 AND (itemtype IN (?,'*'))
436 AND (branchcode IN (?,'*'))
443 my $querycount ="SELECT
446 LEFT JOIN items USING (itemnumber)
447 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
448 LEFT JOIN borrowers USING (borrowernumber)
449 WHERE borrowernumber = ?
453 my $itemtype = $item->{$itype};
454 my $categorycode = $borrower->{categorycode};
456 my $branchfield = "reserves.branchcode";
458 if( $controlbranch eq "ItemHomeLibrary" ){
459 $branchfield = "items.homebranch";
460 $branchcode = $item->{homebranch};
461 }elsif( $controlbranch eq "PatronLibrary" ){
462 $branchfield = "borrowers.branchcode";
463 $branchcode = $borrower->{branchcode};
467 $sth->execute($categorycode, $itemtype, $branchcode);
468 if(my $rights = $sth->fetchrow_hashref()){
469 $itemtype = $rights->{itemtype};
470 $allowedreserves = $rights->{reservesallowed};
477 $querycount .= "AND $branchfield = ?";
479 $querycount .= " AND $itype = ?" if ($itemtype ne "*");
480 my $sthcount = $dbh->prepare($querycount);
482 if($itemtype eq "*"){
483 $sthcount->execute($borrowernumber, $branchcode);
485 $sthcount->execute($borrowernumber, $branchcode, $itemtype);
488 my $reservecount = "0";
489 if(my $rowcount = $sthcount->fetchrow_hashref()){
490 $reservecount = $rowcount->{count};
493 # we check if it's ok or not
494 if( $reservecount >= $allowedreserves ){
498 # If reservecount is ok, we check item branch if IndependentBranches is ON
499 # and canreservefromotherbranches is OFF
500 if ( C4::Context->preference('IndependentBranches')
501 and !C4::Context->preference('canreservefromotherbranches') )
503 my $itembranch = $item->{homebranch};
504 if ($itembranch ne $borrower->{branchcode}) {
511 #--------------------------------------------------------------------------------
512 =head2 GetReserveCount
514 $number = &GetReserveCount($borrowernumber);
516 this function returns the number of reservation for a borrower given on input arg.
520 sub GetReserveCount {
521 my ($borrowernumber) = @_;
523 my $dbh = C4::Context->dbh;
526 SELECT COUNT(*) AS counter
528 WHERE borrowernumber = ?
530 my $sth = $dbh->prepare($query);
531 $sth->execute($borrowernumber);
532 my $row = $sth->fetchrow_hashref;
533 return $row->{counter};
536 =head2 GetOtherReserves
538 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
540 Check queued list of this document and check if this document must be transfered
544 sub GetOtherReserves {
545 my ($itemnumber) = @_;
548 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
549 if ($checkreserves) {
550 my $iteminfo = GetItem($itemnumber);
551 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
552 $messages->{'transfert'} = $checkreserves->{'branchcode'};
553 #minus priorities of others reservs
554 ModReserveMinusPriority(
556 $checkreserves->{'borrowernumber'},
557 $iteminfo->{'biblionumber'}
560 #launch the subroutine dotransfer
561 C4::Items::ModItemTransfer(
563 $iteminfo->{'holdingbranch'},
564 $checkreserves->{'branchcode'}
569 #step 2b : case of a reservation on the same branch, set the waiting status
571 $messages->{'waiting'} = 1;
572 ModReserveMinusPriority(
574 $checkreserves->{'borrowernumber'},
575 $iteminfo->{'biblionumber'}
577 ModReserveStatus($itemnumber,'W');
580 $nextreservinfo = $checkreserves->{'borrowernumber'};
583 return ( $messages, $nextreservinfo );
588 $fee = GetReserveFee($borrowernumber,$biblionumber,$constraint,$biblionumber);
590 Calculate the fee for a reserve
595 my ($borrowernumber, $biblionumber, $constraint, $bibitems ) = @_;
598 my $dbh = C4::Context->dbh;
599 my $const = lc substr( $constraint, 0, 1 );
601 SELECT * FROM borrowers
602 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
603 WHERE borrowernumber = ?
605 my $sth = $dbh->prepare($query);
606 $sth->execute($borrowernumber);
607 my $data = $sth->fetchrow_hashref;
609 my $fee = $data->{'reservefee'};
610 my $cntitems = @- > $bibitems;
614 # check for items on issue
615 # first find biblioitem records
617 my $sth1 = $dbh->prepare(
618 "SELECT * FROM biblio LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
619 WHERE (biblio.biblionumber = ?)"
621 $sth1->execute($biblionumber);
622 while ( my $data1 = $sth1->fetchrow_hashref ) {
623 if ( $const eq "a" ) {
624 push @biblioitems, $data1;
629 while ( $x < $cntitems ) {
630 if ( @$bibitems->{'biblioitemnumber'} ==
631 $data->{'biblioitemnumber'} )
637 if ( $const eq 'o' ) {
639 push @biblioitems, $data1;
644 push @biblioitems, $data1;
650 my $cntitemsfound = @biblioitems;
654 while ( $x < $cntitemsfound ) {
655 my $bitdata = $biblioitems[$x];
656 my $sth2 = $dbh->prepare(
658 WHERE biblioitemnumber = ?"
660 $sth2->execute( $bitdata->{'biblioitemnumber'} );
661 while ( my $itdata = $sth2->fetchrow_hashref ) {
662 my $sth3 = $dbh->prepare(
663 "SELECT * FROM issues
664 WHERE itemnumber = ?"
666 $sth3->execute( $itdata->{'itemnumber'} );
667 if ( my $isdata = $sth3->fetchrow_hashref ) {
675 if ( $allissued == 0 ) {
677 $dbh->prepare("SELECT * FROM reserves WHERE biblionumber = ?");
678 $rsth->execute($biblionumber);
679 if ( my $rdata = $rsth->fetchrow_hashref ) {
689 =head2 GetReservesToBranch
691 @transreserv = GetReservesToBranch( $frombranch );
693 Get reserve list for a given branch
697 sub GetReservesToBranch {
698 my ( $frombranch ) = @_;
699 my $dbh = C4::Context->dbh;
700 my $sth = $dbh->prepare(
701 "SELECT borrowernumber,reservedate,itemnumber,timestamp
706 $sth->execute( $frombranch );
709 while ( my $data = $sth->fetchrow_hashref ) {
710 $transreserv[$i] = $data;
713 return (@transreserv);
716 =head2 GetReservesForBranch
718 @transreserv = GetReservesForBranch($frombranch);
722 sub GetReservesForBranch {
723 my ($frombranch) = @_;
724 my $dbh = C4::Context->dbh;
725 my $query = "SELECT borrowernumber,reservedate,itemnumber,waitingdate
730 $query .= " AND branchcode=? ";
732 $query .= "ORDER BY waitingdate" ;
733 my $sth = $dbh->prepare($query);
735 $sth->execute($frombranch);
742 while ( my $data = $sth->fetchrow_hashref ) {
743 $transreserv[$i] = $data;
746 return (@transreserv);
749 =head2 GetReserveStatus
751 $reservestatus = GetReserveStatus($itemnumber, $biblionumber);
753 Take an itemnumber or a biblionumber and return the status of the reserve places on it.
754 If several reserves exist, the reserve with the lower priority is given.
758 sub GetReserveStatus {
759 my ($itemnumber, $biblionumber) = @_;
761 my $dbh = C4::Context->dbh;
763 my ($sth, $found, $priority);
765 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
766 $sth->execute($itemnumber);
767 ($found, $priority) = $sth->fetchrow_array;
770 if ( $biblionumber and not defined $found and not defined $priority ) {
771 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE biblionumber = ? order by priority LIMIT 1");
772 $sth->execute($biblionumber);
773 ($found, $priority) = $sth->fetchrow_array;
777 return 'Waiting' if $found eq 'W' and $priority == 0;
778 return 'Finished' if $found eq 'F';
779 return 'Reserved' if $priority > 0;
782 #empty string here will remove need for checking undef, or less log lines
787 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
788 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
790 Find a book in the reserves.
792 C<$itemnumber> is the book's item number.
794 As I understand it, C<&CheckReserves> looks for the given item in the
795 reserves. If it is found, that's a match, and C<$status> is set to
798 Otherwise, it finds the most important item in the reserves with the
799 same biblio number as this book (I'm not clear on this) and returns it
800 with C<$status> set to C<Reserved>.
802 C<&CheckReserves> returns a two-element list:
804 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
806 C<$reserve> is the reserve item that matched. It is a
807 reference-to-hash whose keys are mostly the fields of the reserves
808 table in the Koha database.
813 my ( $item, $barcode ) = @_;
814 my $dbh = C4::Context->dbh;
817 if (C4::Context->preference('item-level_itypes')){
819 SELECT items.biblionumber,
820 items.biblioitemnumber,
821 itemtypes.notforloan,
822 items.notforloan AS itemnotforloan,
825 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
826 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
831 SELECT items.biblionumber,
832 items.biblioitemnumber,
833 itemtypes.notforloan,
834 items.notforloan AS itemnotforloan,
837 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
838 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
843 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
844 $sth->execute($item);
847 $sth = $dbh->prepare("$select WHERE barcode = ?");
848 $sth->execute($barcode);
850 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
851 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber ) = $sth->fetchrow_array;
853 return ( '' ) unless $itemnumber; # bail if we got nothing.
855 # if item is not for loan it cannot be reserved either.....
856 # execpt where items.notforloan < 0 : This indicates the item is holdable.
857 return ( '' ) if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
859 # Find this item in the reserves
860 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber );
862 # $priority and $highest are used to find the most important item
863 # in the list returned by &_Findgroupreserve. (The lower $priority,
864 # the more important the item.)
865 # $highest is the most important item we've seen so far.
867 if (scalar @reserves) {
868 my $priority = 10000000;
869 foreach my $res (@reserves) {
870 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
871 return ( "Waiting", $res, \@reserves ); # Found it
873 # See if this item is more important than what we've got so far
874 if ( $res->{'priority'} && $res->{'priority'} < $priority ) {
875 my $borrowerinfo=C4::Members::GetMember(borrowernumber => $res->{'borrowernumber'});
876 my $iteminfo=C4::Items::GetItem($itemnumber);
877 my $branch=C4::Circulation::_GetCircControlBranch($iteminfo,$borrowerinfo);
878 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
879 next if ($branchitemrule->{'holdallowed'} == 0);
880 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
881 $priority = $res->{'priority'};
888 # If we get this far, then no exact match was found.
889 # We return the most important (i.e. next) reservation.
891 $highest->{'itemnumber'} = $item;
892 return ( "Reserved", $highest, \@reserves );
898 =head2 CancelExpiredReserves
900 CancelExpiredReserves();
902 Cancels all reserves with an expiration date from before today.
906 sub CancelExpiredReserves {
908 # Cancel reserves that have passed their expiration date.
909 my $dbh = C4::Context->dbh;
910 my $sth = $dbh->prepare( "
911 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
912 AND expirationdate IS NOT NULL
917 while ( my $res = $sth->fetchrow_hashref() ) {
918 CancelReserve( $res->{'biblionumber'}, '', $res->{'borrowernumber'} );
921 # Cancel reserves that have been waiting too long
922 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
923 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
924 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
926 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
927 $sth = $dbh->prepare( $query );
928 $sth->execute( $max_pickup_delay );
930 while (my $res = $sth->fetchrow_hashref ) {
932 manualinvoice($res->{'borrowernumber'}, $res->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
935 CancelReserve( $res->{'biblionumber'}, '', $res->{'borrowernumber'} );
941 =head2 AutoUnsuspendReserves
943 AutoUnsuspendReserves();
945 Unsuspends all suspended reserves with a suspend_until date from before today.
949 sub AutoUnsuspendReserves {
951 my $dbh = C4::Context->dbh;
953 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
954 my $sth = $dbh->prepare( $query );
961 &CancelReserve($biblionumber, $itemnumber, $borrowernumber);
965 Use either C<$biblionumber> or C<$itemnumber> to specify the item to
966 cancel, but not both: if both are given, C<&CancelReserve> uses
969 C<$borrowernumber> is the borrower number of the patron on whose
970 behalf the book was reserved.
972 If C<$biblionumber> was given, C<&CancelReserve> also adjusts the
973 priorities of the other people who are waiting on the book.
978 my ( $biblio, $item, $borr ) = @_;
979 my $dbh = C4::Context->dbh;
980 if ( $item and $borr ) {
981 # removing a waiting reserve record....
982 # update the database...
985 SET cancellationdate = now(),
989 AND borrowernumber = ?
991 my $sth = $dbh->prepare($query);
992 $sth->execute( $item, $borr );
995 INSERT INTO old_reserves
996 SELECT * FROM reserves
998 AND borrowernumber = ?
1000 $sth = $dbh->prepare($query);
1001 $sth->execute( $item, $borr );
1003 DELETE FROM reserves
1004 WHERE itemnumber = ?
1005 AND borrowernumber = ?
1007 $sth = $dbh->prepare($query);
1008 $sth->execute( $item, $borr );
1011 # removing a reserve record....
1012 # get the prioritiy on this record....
1015 SELECT priority FROM reserves
1016 WHERE biblionumber = ?
1017 AND borrowernumber = ?
1018 AND cancellationdate IS NULL
1019 AND itemnumber IS NULL
1021 my $sth = $dbh->prepare($query);
1022 $sth->execute( $biblio, $borr );
1023 ($priority) = $sth->fetchrow_array;
1027 SET cancellationdate = now(),
1030 WHERE biblionumber = ?
1031 AND borrowernumber = ?
1034 # update the database, removing the record...
1035 $sth = $dbh->prepare($query);
1036 $sth->execute( $biblio, $borr );
1040 INSERT INTO old_reserves
1041 SELECT * FROM reserves
1042 WHERE biblionumber = ?
1043 AND borrowernumber = ?
1045 $sth = $dbh->prepare($query);
1046 $sth->execute( $biblio, $borr );
1049 DELETE FROM reserves
1050 WHERE biblionumber = ?
1051 AND borrowernumber = ?
1053 $sth = $dbh->prepare($query);
1054 $sth->execute( $biblio, $borr );
1056 # now fix the priority on the others....
1057 _FixPriority( $biblio, $borr );
1063 ModReserve($rank, $biblio, $borrower, $branch[, $itemnumber])
1065 Change a hold request's priority or cancel it.
1067 C<$rank> specifies the effect of the change. If C<$rank>
1068 is 'W' or 'n', nothing happens. This corresponds to leaving a
1069 request alone when changing its priority in the holds queue
1072 If C<$rank> is 'del', the hold request is cancelled.
1074 If C<$rank> is an integer greater than zero, the priority of
1075 the request is set to that value. Since priority != 0 means
1076 that the item is not waiting on the hold shelf, setting the
1077 priority to a non-zero value also sets the request's found
1078 status and waiting date to NULL.
1080 The optional C<$itemnumber> parameter is used only when
1081 C<$rank> is a non-zero integer; if supplied, the itemnumber
1082 of the hold request is set accordingly; if omitted, the itemnumber
1085 B<FIXME:> Note that the forgoing can have the effect of causing
1086 item-level hold requests to turn into title-level requests. This
1087 will be fixed once reserves has separate columns for requested
1088 itemnumber and supplying itemnumber.
1093 #subroutine to update a reserve
1094 my ( $rank, $biblio, $borrower, $branch , $itemnumber, $suspend_until) = @_;
1095 return if $rank eq "W";
1096 return if $rank eq "n";
1097 my $dbh = C4::Context->dbh;
1098 if ( $rank eq "del" ) {
1101 SET cancellationdate=now()
1102 WHERE biblionumber = ?
1103 AND borrowernumber = ?
1105 my $sth = $dbh->prepare($query);
1106 $sth->execute( $biblio, $borrower );
1109 INSERT INTO old_reserves
1112 WHERE biblionumber = ?
1113 AND borrowernumber = ?
1115 $sth = $dbh->prepare($query);
1116 $sth->execute( $biblio, $borrower );
1118 DELETE FROM reserves
1119 WHERE biblionumber = ?
1120 AND borrowernumber = ?
1122 $sth = $dbh->prepare($query);
1123 $sth->execute( $biblio, $borrower );
1126 elsif ($rank =~ /^\d+/ and $rank > 0) {
1128 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1129 WHERE biblionumber = ?
1130 AND borrowernumber = ?
1132 my $sth = $dbh->prepare($query);
1133 $sth->execute( $rank, $branch,$itemnumber, $biblio, $borrower);
1136 if ( defined( $suspend_until ) ) {
1137 if ( $suspend_until ) {
1138 $suspend_until = C4::Dates->new( $suspend_until )->output("iso");
1139 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE biblionumber = ? AND borrowernumber = ?", undef, ( $suspend_until, $biblio, $borrower ) );
1141 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE biblionumber = ? AND borrowernumber = ?", undef, ( $biblio, $borrower ) );
1145 _FixPriority( $biblio, $borrower, $rank);
1149 =head2 ModReserveFill
1151 &ModReserveFill($reserve);
1153 Fill a reserve. If I understand this correctly, this means that the
1154 reserved book has been found and given to the patron who reserved it.
1156 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1157 whose keys are fields from the reserves table in the Koha database.
1161 sub ModReserveFill {
1163 my $dbh = C4::Context->dbh;
1164 # fill in a reserve record....
1165 my $biblionumber = $res->{'biblionumber'};
1166 my $borrowernumber = $res->{'borrowernumber'};
1167 my $resdate = $res->{'reservedate'};
1169 # get the priority on this record....
1171 my $query = "SELECT priority
1173 WHERE biblionumber = ?
1174 AND borrowernumber = ?
1175 AND reservedate = ?";
1176 my $sth = $dbh->prepare($query);
1177 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1178 ($priority) = $sth->fetchrow_array;
1181 # update the database...
1182 $query = "UPDATE reserves
1185 WHERE biblionumber = ?
1187 AND borrowernumber = ?
1189 $sth = $dbh->prepare($query);
1190 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1193 # move to old_reserves
1194 $query = "INSERT INTO old_reserves
1195 SELECT * FROM reserves
1196 WHERE biblionumber = ?
1198 AND borrowernumber = ?
1200 $sth = $dbh->prepare($query);
1201 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1202 $query = "DELETE FROM reserves
1203 WHERE biblionumber = ?
1205 AND borrowernumber = ?
1207 $sth = $dbh->prepare($query);
1208 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1210 # now fix the priority on the others (if the priority wasn't
1211 # already sorted!)....
1212 unless ( $priority == 0 ) {
1213 _FixPriority( $biblionumber, $borrowernumber );
1217 =head2 ModReserveStatus
1219 &ModReserveStatus($itemnumber, $newstatus);
1221 Update the reserve status for the active (priority=0) reserve.
1223 $itemnumber is the itemnumber the reserve is on
1225 $newstatus is the new status.
1229 sub ModReserveStatus {
1231 #first : check if we have a reservation for this item .
1232 my ($itemnumber, $newstatus) = @_;
1233 my $dbh = C4::Context->dbh;
1235 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1236 my $sth_set = $dbh->prepare($query);
1237 $sth_set->execute( $newstatus, $itemnumber );
1239 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1240 CartToShelf( $itemnumber );
1244 =head2 ModReserveAffect
1246 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1248 This function affect an item and a status for a given reserve
1249 The itemnumber parameter is used to find the biblionumber.
1250 with the biblionumber & the borrowernumber, we can affect the itemnumber
1251 to the correct reserve.
1253 if $transferToDo is not set, then the status is set to "Waiting" as well.
1254 otherwise, a transfer is on the way, and the end of the transfer will
1255 take care of the waiting status
1259 sub ModReserveAffect {
1260 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1261 my $dbh = C4::Context->dbh;
1263 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1264 # attached to $itemnumber
1265 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1266 $sth->execute($itemnumber);
1267 my ($biblionumber) = $sth->fetchrow;
1269 # get request - need to find out if item is already
1270 # waiting in order to not send duplicate hold filled notifications
1271 my $request = GetReserveInfo($borrowernumber, $biblionumber);
1272 my $already_on_shelf = ($request && $request->{found} eq 'W') ? 1 : 0;
1274 # If we affect a reserve that has to be transfered, don't set to Waiting
1276 if ($transferToDo) {
1282 WHERE borrowernumber = ?
1283 AND biblionumber = ?
1287 # affect the reserve to Waiting as well.
1292 waitingdate = NOW(),
1294 WHERE borrowernumber = ?
1295 AND biblionumber = ?
1298 $sth = $dbh->prepare($query);
1299 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1300 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1302 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1303 CartToShelf( $itemnumber );
1309 =head2 ModReserveCancelAll
1311 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1313 function to cancel reserv,check other reserves, and transfer document if it's necessary
1317 sub ModReserveCancelAll {
1320 my ( $itemnumber, $borrowernumber ) = @_;
1322 #step 1 : cancel the reservation
1323 my $CancelReserve = CancelReserve( undef, $itemnumber, $borrowernumber );
1325 #step 2 launch the subroutine of the others reserves
1326 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1328 return ( $messages, $nextreservinfo );
1331 =head2 ModReserveMinusPriority
1333 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1335 Reduce the values of queuded list
1339 sub ModReserveMinusPriority {
1340 my ( $itemnumber, $borrowernumber, $biblionumber ) = @_;
1342 #first step update the value of the first person on reserv
1343 my $dbh = C4::Context->dbh;
1346 SET priority = 0 , itemnumber = ?
1347 WHERE borrowernumber=?
1350 my $sth_upd = $dbh->prepare($query);
1351 $sth_upd->execute( $itemnumber, $borrowernumber, $biblionumber );
1352 # second step update all others reservs
1353 _FixPriority($biblionumber, $borrowernumber, '0');
1356 =head2 GetReserveInfo
1358 &GetReserveInfo($borrowernumber,$biblionumber);
1360 Get item and borrower details for a current hold.
1361 Current implementation this query should have a single result.
1365 sub GetReserveInfo {
1366 my ( $borrowernumber, $biblionumber ) = @_;
1367 my $dbh = C4::Context->dbh;
1371 reserves.borrowernumber,
1372 reserves.biblionumber,
1373 reserves.branchcode,
1374 reserves.waitingdate,
1390 items.holdingbranch,
1391 items.itemcallnumber,
1397 LEFT JOIN items USING(itemnumber)
1398 LEFT JOIN borrowers USING(borrowernumber)
1399 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1401 reserves.borrowernumber=?
1402 AND reserves.biblionumber=?";
1403 my $sth = $dbh->prepare($strsth);
1404 $sth->execute($borrowernumber,$biblionumber);
1406 my $data = $sth->fetchrow_hashref;
1411 =head2 IsAvailableForItemLevelRequest
1413 my $is_available = IsAvailableForItemLevelRequest($itemnumber);
1415 Checks whether a given item record is available for an
1416 item-level hold request. An item is available if
1418 * it is not lost AND
1419 * it is not damaged AND
1420 * it is not withdrawn AND
1421 * does not have a not for loan value > 0
1423 Whether or not the item is currently on loan is
1424 also checked - if the AllowOnShelfHolds system preference
1425 is ON, an item can be requested even if it is currently
1426 on loan to somebody else. If the system preference
1427 is OFF, an item that is currently checked out cannot
1428 be the target of an item-level hold request.
1430 Note that IsAvailableForItemLevelRequest() does not
1431 check if the staff operator is authorized to place
1432 a request on the item - in particular,
1433 this routine does not check IndependantBranches
1434 and canreservefromotherbranches.
1438 sub IsAvailableForItemLevelRequest {
1439 my $itemnumber = shift;
1441 my $item = GetItem($itemnumber);
1443 # must check the notforloan setting of the itemtype
1444 # FIXME - a lot of places in the code do this
1445 # or something similar - need to be
1447 my $dbh = C4::Context->dbh;
1448 my $notforloan_query;
1449 if (C4::Context->preference('item-level_itypes')) {
1450 $notforloan_query = "SELECT itemtypes.notforloan
1452 JOIN itemtypes ON (itemtypes.itemtype = items.itype)
1453 WHERE itemnumber = ?";
1455 $notforloan_query = "SELECT itemtypes.notforloan
1457 JOIN biblioitems USING (biblioitemnumber)
1458 JOIN itemtypes USING (itemtype)
1459 WHERE itemnumber = ?";
1461 my $sth = $dbh->prepare($notforloan_query);
1462 $sth->execute($itemnumber);
1463 my $notforloan_per_itemtype = 0;
1464 if (my ($notforloan) = $sth->fetchrow_array) {
1465 $notforloan_per_itemtype = 1 if $notforloan;
1468 my $available_per_item = 1;
1469 $available_per_item = 0 if $item->{itemlost} or
1470 ( $item->{notforloan} > 0 ) or
1471 ($item->{damaged} and not C4::Context->preference('AllowHoldsOnDamagedItems')) or
1472 $item->{wthdrawn} or
1473 $notforloan_per_itemtype;
1476 if (C4::Context->preference('AllowOnShelfHolds')) {
1477 return $available_per_item;
1479 return ($available_per_item and ($item->{onloan} or GetReserveStatus($itemnumber) eq "Waiting"));
1483 =head2 AlterPriority
1485 AlterPriority( $where, $borrowernumber, $biblionumber, $reservedate );
1487 This function changes a reserve's priority up, down, to the top, or to the bottom.
1488 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1493 my ( $where, $borrowernumber, $biblionumber ) = @_;
1495 my $dbh = C4::Context->dbh;
1497 ## Find this reserve
1498 my $sth = $dbh->prepare('SELECT * FROM reserves WHERE biblionumber = ? AND borrowernumber = ? AND cancellationdate IS NULL');
1499 $sth->execute( $biblionumber, $borrowernumber );
1500 my $reserve = $sth->fetchrow_hashref();
1503 if ( $where eq 'up' || $where eq 'down' ) {
1505 my $priority = $reserve->{'priority'};
1506 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1507 _FixPriority( $biblionumber, $borrowernumber, $priority )
1509 } elsif ( $where eq 'top' ) {
1511 _FixPriority( $biblionumber, $borrowernumber, '1' )
1513 } elsif ( $where eq 'bottom' ) {
1515 _FixPriority( $biblionumber, $borrowernumber, '999999' )
1520 =head2 ToggleLowestPriority
1522 ToggleLowestPriority( $borrowernumber, $biblionumber );
1524 This function sets the lowestPriority field to true if is false, and false if it is true.
1528 sub ToggleLowestPriority {
1529 my ( $borrowernumber, $biblionumber ) = @_;
1531 my $dbh = C4::Context->dbh;
1533 my $sth = $dbh->prepare(
1534 "UPDATE reserves SET lowestPriority = NOT lowestPriority
1535 WHERE biblionumber = ?
1536 AND borrowernumber = ?"
1544 _FixPriority( $biblionumber, $borrowernumber, '999999' );
1547 =head2 ToggleSuspend
1549 ToggleSuspend( $borrowernumber, $biblionumber );
1551 This function sets the suspend field to true if is false, and false if it is true.
1552 If the reserve is currently suspended with a suspend_until date, that date will
1553 be cleared when it is unsuspended.
1558 my ( $borrowernumber, $biblionumber, $suspend_until ) = @_;
1560 $suspend_until = output_pref( dt_from_string( $suspend_until ), 'iso' ) if ( $suspend_until );
1562 my $do_until = ( $suspend_until ) ? '?' : 'NULL';
1564 my $dbh = C4::Context->dbh;
1566 my $sth = $dbh->prepare(
1567 "UPDATE reserves SET suspend = NOT suspend,
1568 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1569 WHERE biblionumber = ?
1570 AND borrowernumber = ?
1574 push( @params, $suspend_until ) if ( $suspend_until );
1575 push( @params, $biblionumber );
1576 push( @params, $borrowernumber );
1578 $sth->execute( @params );
1585 borrowernumber => $borrowernumber,
1586 [ biblionumber => $biblionumber, ]
1587 [ suspend_until => $suspend_until, ]
1588 [ suspend => $suspend ]
1591 This function accepts a set of hash keys as its parameters.
1592 It requires either borrowernumber or biblionumber, or both.
1594 suspend_until is wholly optional.
1601 my $borrowernumber = $params{'borrowernumber'} || undef;
1602 my $biblionumber = $params{'biblionumber'} || undef;
1603 my $suspend_until = $params{'suspend_until'} || undef;
1604 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1606 $suspend_until = C4::Dates->new( $suspend_until )->output("iso") if ( defined( $suspend_until ) );
1608 return unless ( $borrowernumber || $biblionumber );
1610 my ( $query, $sth, $dbh, @query_params );
1612 $query = "UPDATE reserves SET suspend = ? ";
1613 push( @query_params, $suspend );
1615 $query .= ", suspend_until = NULL ";
1616 } elsif ( $suspend_until ) {
1617 $query .= ", suspend_until = ? ";
1618 push( @query_params, $suspend_until );
1620 $query .= " WHERE ";
1621 if ( $borrowernumber ) {
1622 $query .= " borrowernumber = ? ";
1623 push( @query_params, $borrowernumber );
1625 $query .= " AND " if ( $borrowernumber && $biblionumber );
1626 if ( $biblionumber ) {
1627 $query .= " biblionumber = ? ";
1628 push( @query_params, $biblionumber );
1630 $query .= " AND found IS NULL ";
1632 $dbh = C4::Context->dbh;
1633 $sth = $dbh->prepare( $query );
1634 $sth->execute( @query_params );
1641 &_FixPriority($biblio,$borrowernumber,$rank,$ignoreSetLowestRank);
1643 Only used internally (so don't export it)
1644 Changed how this functions works #
1645 Now just gets an array of reserves in the rank order and updates them with
1646 the array index (+1 as array starts from 0)
1647 and if $rank is supplied will splice item from the array and splice it back in again
1648 in new priority rank
1653 my ( $biblio, $borrowernumber, $rank, $ignoreSetLowestRank ) = @_;
1654 my $dbh = C4::Context->dbh;
1655 if ( $rank eq "del" ) {
1656 CancelReserve( $biblio, undef, $borrowernumber );
1658 if ( $rank eq "W" || $rank eq "0" ) {
1660 # make sure priority for waiting or in-transit items is 0
1664 WHERE biblionumber = ?
1665 AND borrowernumber = ?
1666 AND found IN ('W', 'T')
1668 my $sth = $dbh->prepare($query);
1669 $sth->execute( $biblio, $borrowernumber );
1675 # FIXME adding a new security in returned elements for changing priority,
1676 # now, we don't care anymore any reservations with itemnumber linked (suppose a waiting reserve)
1677 # This is wrong a waiting reserve has W set
1678 # The assumption that having an itemnumber set means waiting is wrong and should be corrected any place it occurs
1680 SELECT borrowernumber, reservedate, constrainttype
1682 WHERE biblionumber = ?
1683 AND ((found <> 'W' AND found <> 'T') or found is NULL)
1684 ORDER BY priority ASC
1686 my $sth = $dbh->prepare($query);
1687 $sth->execute($biblio);
1688 while ( my $line = $sth->fetchrow_hashref ) {
1689 push( @reservedates, $line );
1690 push( @priority, $line );
1693 # To find the matching index
1695 my $key = -1; # to allow for 0 to be a valid result
1696 for ( $i = 0 ; $i < @priority ; $i++ ) {
1697 if ( $borrowernumber == $priority[$i]->{'borrowernumber'} ) {
1698 $key = $i; # save the index
1703 # if index exists in array then move it to new position
1704 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1705 my $new_rank = $rank -
1706 1; # $new_rank is what you want the new index to be in the array
1707 my $moving_item = splice( @priority, $key, 1 );
1708 splice( @priority, $new_rank, 0, $moving_item );
1711 # now fix the priority on those that are left....
1715 WHERE biblionumber = ?
1716 AND borrowernumber = ?
1720 $sth = $dbh->prepare($query);
1721 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1724 $priority[$j]->{'borrowernumber'},
1725 $priority[$j]->{'reservedate'}
1730 $sth = $dbh->prepare( "SELECT borrowernumber FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1733 unless ( $ignoreSetLowestRank ) {
1734 while ( my $res = $sth->fetchrow_hashref() ) {
1735 _FixPriority( $biblio, $res->{'borrowernumber'}, '999999', 1 );
1740 =head2 _Findgroupreserve
1742 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber);
1744 Looks for an item-specific match first, then for a title-level match, returning the
1745 first match found. If neither, then we look for a 3rd kind of match based on
1746 reserve constraints.
1748 TODO: add more explanation about reserve constraints
1750 C<&_Findgroupreserve> returns :
1751 C<@results> is an array of references-to-hash whose keys are mostly
1752 fields from the reserves table of the Koha database, plus
1753 C<biblioitemnumber>.
1757 sub _Findgroupreserve {
1758 my ( $bibitem, $biblio, $itemnumber ) = @_;
1759 my $dbh = C4::Context->dbh;
1761 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1762 # check for exact targetted match
1763 my $item_level_target_query = qq/
1764 SELECT reserves.biblionumber AS biblionumber,
1765 reserves.borrowernumber AS borrowernumber,
1766 reserves.reservedate AS reservedate,
1767 reserves.branchcode AS branchcode,
1768 reserves.cancellationdate AS cancellationdate,
1769 reserves.found AS found,
1770 reserves.reservenotes AS reservenotes,
1771 reserves.priority AS priority,
1772 reserves.timestamp AS timestamp,
1773 biblioitems.biblioitemnumber AS biblioitemnumber,
1774 reserves.itemnumber AS itemnumber
1776 JOIN biblioitems USING (biblionumber)
1777 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1780 AND item_level_request = 1
1782 AND reservedate <= CURRENT_DATE()
1785 my $sth = $dbh->prepare($item_level_target_query);
1786 $sth->execute($itemnumber);
1788 if ( my $data = $sth->fetchrow_hashref ) {
1789 push( @results, $data );
1791 return @results if @results;
1793 # check for title-level targetted match
1794 my $title_level_target_query = qq/
1795 SELECT reserves.biblionumber AS biblionumber,
1796 reserves.borrowernumber AS borrowernumber,
1797 reserves.reservedate AS reservedate,
1798 reserves.branchcode AS branchcode,
1799 reserves.cancellationdate AS cancellationdate,
1800 reserves.found AS found,
1801 reserves.reservenotes AS reservenotes,
1802 reserves.priority AS priority,
1803 reserves.timestamp AS timestamp,
1804 biblioitems.biblioitemnumber AS biblioitemnumber,
1805 reserves.itemnumber AS itemnumber
1807 JOIN biblioitems USING (biblionumber)
1808 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1811 AND item_level_request = 0
1812 AND hold_fill_targets.itemnumber = ?
1813 AND reservedate <= CURRENT_DATE()
1816 $sth = $dbh->prepare($title_level_target_query);
1817 $sth->execute($itemnumber);
1819 if ( my $data = $sth->fetchrow_hashref ) {
1820 push( @results, $data );
1822 return @results if @results;
1825 SELECT reserves.biblionumber AS biblionumber,
1826 reserves.borrowernumber AS borrowernumber,
1827 reserves.reservedate AS reservedate,
1828 reserves.waitingdate AS waitingdate,
1829 reserves.branchcode AS branchcode,
1830 reserves.cancellationdate AS cancellationdate,
1831 reserves.found AS found,
1832 reserves.reservenotes AS reservenotes,
1833 reserves.priority AS priority,
1834 reserves.timestamp AS timestamp,
1835 reserveconstraints.biblioitemnumber AS biblioitemnumber,
1836 reserves.itemnumber AS itemnumber
1838 LEFT JOIN reserveconstraints ON reserves.biblionumber = reserveconstraints.biblionumber
1839 WHERE reserves.biblionumber = ?
1840 AND ( ( reserveconstraints.biblioitemnumber = ?
1841 AND reserves.borrowernumber = reserveconstraints.borrowernumber
1842 AND reserves.reservedate = reserveconstraints.reservedate )
1843 OR reserves.constrainttype='a' )
1844 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1845 AND reserves.reservedate <= CURRENT_DATE()
1848 $sth = $dbh->prepare($query);
1849 $sth->execute( $biblio, $bibitem, $itemnumber );
1851 while ( my $data = $sth->fetchrow_hashref ) {
1852 push( @results, $data );
1857 =head2 _koha_notify_reserve
1859 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1861 Sends a notification to the patron that their hold has been filled (through
1862 ModReserveAffect, _not_ ModReserveFill)
1866 sub _koha_notify_reserve {
1867 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1869 my $dbh = C4::Context->dbh;
1870 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1872 # Try to get the borrower's email address
1873 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1878 if ( $to_address || $borrower->{'smsalertnumber'} ) {
1879 $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $borrowernumber, message_name => 'Hold_Filled' } );
1884 my $sth = $dbh->prepare("
1887 WHERE borrowernumber = ?
1888 AND biblionumber = ?
1890 $sth->execute( $borrowernumber, $biblionumber );
1891 my $reserve = $sth->fetchrow_hashref;
1892 my $branch_details = GetBranchDetail( $reserve->{'branchcode'} );
1894 my $admin_email_address = $branch_details->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
1896 my %letter_params = (
1897 module => 'reserves',
1898 branchcode => $reserve->{branchcode},
1900 'branches' => $branch_details,
1901 'borrowers' => $borrower,
1902 'biblio' => $biblionumber,
1903 'reserves' => $reserve,
1904 'items', $reserve->{'itemnumber'},
1906 substitute => { today => C4::Dates->new()->output() },
1910 if ( $print_mode ) {
1911 $letter_params{ 'letter_code' } = 'HOLD_PRINT';
1912 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1914 C4::Letters::EnqueueLetter( {
1916 borrowernumber => $borrowernumber,
1917 message_transport_type => 'print',
1923 if ( $to_address && defined $messagingprefs->{transports}->{'email'} ) {
1924 $letter_params{ 'letter_code' } = $messagingprefs->{transports}->{'email'};
1925 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1927 C4::Letters::EnqueueLetter(
1928 { letter => $letter,
1929 borrowernumber => $borrowernumber,
1930 message_transport_type => 'email',
1931 from_address => $admin_email_address,
1936 if ( $borrower->{'smsalertnumber'} && defined $messagingprefs->{transports}->{'sms'} ) {
1937 $letter_params{ 'letter_code' } = $messagingprefs->{transports}->{'sms'};
1938 my $letter = C4::Letters::GetPreparedLetter ( %letter_params ) or die "Could not find a letter called '$letter_params{'letter_code'}' in the 'reserves' module";
1940 C4::Letters::EnqueueLetter(
1941 { letter => $letter,
1942 borrowernumber => $borrowernumber,
1943 message_transport_type => 'sms',
1949 =head2 _ShiftPriorityByDateAndPriority
1951 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1953 This increments the priority of all reserves after the one
1954 with either the lowest date after C<$reservedate>
1955 or the lowest priority after C<$priority>.
1957 It effectively makes room for a new reserve to be inserted with a certain
1958 priority, which is returned.
1960 This is most useful when the reservedate can be set by the user. It allows
1961 the new reserve to be placed before other reserves that have a later
1962 reservedate. Since priority also is set by the form in reserves/request.pl
1963 the sub accounts for that too.
1967 sub _ShiftPriorityByDateAndPriority {
1968 my ( $biblio, $resdate, $new_priority ) = @_;
1970 my $dbh = C4::Context->dbh;
1971 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1972 my $sth = $dbh->prepare( $query );
1973 $sth->execute( $biblio, $resdate, $new_priority );
1974 my $min_priority = $sth->fetchrow;
1975 # if no such matches are found, $new_priority remains as original value
1976 $new_priority = $min_priority if ( $min_priority );
1978 # Shift the priority up by one; works in conjunction with the next SQL statement
1979 $query = "UPDATE reserves
1980 SET priority = priority+1
1981 WHERE biblionumber = ?
1982 AND borrowernumber = ?
1985 my $sth_update = $dbh->prepare( $query );
1987 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1988 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1989 $sth = $dbh->prepare( $query );
1990 $sth->execute( $new_priority, $biblio );
1991 while ( my $row = $sth->fetchrow_hashref ) {
1992 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1995 return $new_priority; # so the caller knows what priority they wind up receiving
2000 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2002 Use when checking out an item to handle reserves
2003 If $cancelreserve boolean is set to true, it will remove existing reserve
2008 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2010 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber );
2013 my $biblionumber = $res->{biblionumber};
2014 my $biblioitemnumber = $res->{biblioitemnumber};
2016 if ($res->{borrowernumber} == $borrowernumber) {
2017 ModReserveFill($res);
2021 # The item is reserved by someone else.
2022 # Find this item in the reserves
2025 foreach (@$all_reserves) {
2026 $_->{'borrowernumber'} == $borrowernumber or next;
2027 $_->{'biblionumber'} == $biblionumber or next;
2034 # The item is reserved by the current patron
2035 ModReserveFill($borr_res);
2038 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2039 RevertWaitingStatus({ itemnumber => $itemnumber });
2041 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2042 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
2043 CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
2050 MergeHolds($dbh,$to_biblio, $from_biblio);
2052 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2057 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2058 my $sth = $dbh->prepare(
2059 "SELECT count(*) as reservenumber FROM reserves WHERE biblionumber = ?"
2061 $sth->execute($from_biblio);
2062 if ( my $data = $sth->fetchrow_hashref() ) {
2064 # holds exist on old record, if not we don't need to do anything
2065 $sth = $dbh->prepare(
2066 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2067 $sth->execute( $to_biblio, $from_biblio );
2070 # don't reorder those already waiting
2072 $sth = $dbh->prepare(
2073 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2075 my $upd_sth = $dbh->prepare(
2076 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2077 AND reservedate = ? AND constrainttype = ? AND (itemnumber = ? or itemnumber is NULL) "
2079 $sth->execute( $to_biblio, 'W', 'T' );
2081 while ( my $reserve = $sth->fetchrow_hashref() ) {
2083 $priority, $to_biblio,
2084 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2085 $reserve->{'constrainttype'}, $reserve->{'itemnumber'}
2092 =head2 RevertWaitingStatus
2094 $success = RevertWaitingStatus({ itemnumber => $itemnumber });
2096 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2098 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2099 item level hold, even if it was only a bibliolevel hold to
2100 begin with. This is because we can no longer know if a hold
2101 was item-level or bib-level after a hold has been set to
2106 sub RevertWaitingStatus {
2107 my ( $params ) = @_;
2108 my $itemnumber = $params->{'itemnumber'};
2110 return unless ( $itemnumber );
2112 my $dbh = C4::Context->dbh;
2114 ## Get the waiting reserve we want to revert
2116 SELECT * FROM reserves
2117 WHERE itemnumber = ?
2118 AND found IS NOT NULL
2120 my $sth = $dbh->prepare( $query );
2121 $sth->execute( $itemnumber );
2122 my $reserve = $sth->fetchrow_hashref();
2124 ## Increment the priority of all other non-waiting
2125 ## reserves for this bib record
2129 priority = priority + 1
2135 $sth = $dbh->prepare( $query );
2136 $sth->execute( $reserve->{'biblionumber'} );
2138 ## Fix up the currently waiting reserve
2148 $sth = $dbh->prepare( $query );
2149 return $sth->execute( $reserve->{'reserve_id'} );
2154 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2156 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2161 my ($branch, $borrowernumber, $biblionumber) = @_;
2163 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2165 my $reserve = GetReserveInfo($borrowernumber,$biblionumber )
2168 return C4::Letters::GetPreparedLetter (
2169 module => 'circulation',
2170 letter_code => 'RESERVESLIP',
2171 branchcode => $branch,
2173 'reserves' => $reserve,
2174 'branches' => $reserve->{branchcode},
2175 'borrowers' => $reserve->{borrowernumber},
2176 'biblio' => $reserve->{biblionumber},
2177 'items' => $reserve->{itemnumber},
2184 Koha Development Team <http://koha-community.org/>