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 );
44 use List
::MoreUtils
qw( firstidx any );
46 use vars
qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
50 C4::Reserves - Koha functions for dealing with reservation.
58 This modules provides somes functions to deal with reservations.
60 Reserves are stored in reserves table.
61 The following columns contains important values :
62 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
63 =0 : then the reserve is being dealed
64 - found : NULL : means the patron requested the 1st available, and we haven't choosen the item
65 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
66 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
67 F(inished) : the reserve has been completed, and is done
68 - itemnumber : empty : the reserve is still unaffected to an item
69 filled: the reserve is attached to an item
70 The complete workflow is :
71 ==== 1st use case ====
72 patron request a document, 1st available : P >0, F=NULL, I=NULL
73 a library having it run "transfertodo", and clic on the list
74 if there is no transfer to do, the reserve waiting
75 patron can pick it up P =0, F=W, I=filled
76 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
77 The pickup library recieve the book, it check in P =0, F=W, I=filled
78 The patron borrow the book P =0, F=F, I=filled
80 ==== 2nd use case ====
81 patron requests a document, a given item,
82 If pickup is holding branch P =0, F=W, I=filled
83 If transfer needed, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it checks it in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
92 # set the version for version checking
93 $VERSION = 3.07.00.049;
100 &GetReservesFromItemnumber
101 &GetReservesFromBiblionumber
102 &GetReservesFromBorrowernumber
103 &GetReservesForBranch
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
125 &CancelExpiredReserves
127 &AutoUnsuspendReserves
129 &IsAvailableForItemLevelRequest
132 &ToggleLowestPriority
138 &GetReservesControlBranch
142 @EXPORT_OK = qw( MergeHolds );
147 AddReserve($branch,$borrowernumber,$biblionumber,$constraint,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
153 $branch, $borrowernumber, $biblionumber,
154 $constraint, $bibitems, $priority, $resdate, $expdate, $notes,
155 $title, $checkitem, $found
158 GetReserveFee
($borrowernumber, $biblionumber, $constraint,
160 my $dbh = C4
::Context
->dbh;
161 my $const = lc substr( $constraint, 0, 1 );
162 $resdate = format_date_in_iso
( $resdate ) if ( $resdate );
163 $resdate = C4
::Dates
->today( 'iso' ) unless ( $resdate );
165 $expdate = format_date_in_iso
( $expdate );
167 undef $expdate; # make reserves.expirationdate default to null rather than '0000-00-00'
169 if ( C4
::Context
->preference( 'AllowHoldDateInFuture' ) ) {
170 # Make room in reserves for this before those of a later reserve date
171 $priority = _ShiftPriorityByDateAndPriority
( $biblionumber, $resdate, $priority );
175 # If the reserv had the waiting status, we had the value of the resdate
176 if ( $found eq 'W' ) {
177 $waitingdate = $resdate;
181 # updates take place here
183 my $nextacctno = &getnextacctno
( $borrowernumber );
185 INSERT INTO accountlines
186 (borrowernumber
,accountno
,date
,amount
,description
,accounttype
,amountoutstanding
)
188 (?
,?
,now
(),?
,?
,'Res',?
)
190 my $usth = $dbh->prepare($query);
191 $usth->execute( $borrowernumber, $nextacctno, $fee,
192 "Reserve Charge - $title", $fee );
198 (borrowernumber
,biblionumber
,reservedate
,branchcode
,constrainttype
,
199 priority
,reservenotes
,itemnumber
,found
,waitingdate
,expirationdate
)
204 my $sth = $dbh->prepare($query);
206 $borrowernumber, $biblionumber, $resdate, $branch,
207 $const, $priority, $notes, $checkitem,
208 $found, $waitingdate, $expdate
210 my $reserve_id = $sth->{mysql_insertid
};
212 # Send e-mail to librarian if syspref is active
213 if(C4
::Context
->preference("emailLibrarianWhenHoldIsPlaced")){
214 my $borrower = C4
::Members
::GetMember
(borrowernumber
=> $borrowernumber);
215 my $branch_details = C4
::Branch
::GetBranchDetail
($borrower->{branchcode
});
216 if ( my $letter = C4
::Letters
::GetPreparedLetter
(
217 module
=> 'reserves',
218 letter_code
=> 'HOLDPLACED',
219 branchcode
=> $branch,
221 'branches' => $branch_details,
222 'borrowers' => $borrower,
223 'biblio' => $biblionumber,
224 'items' => $checkitem,
228 my $admin_email_address =$branch_details->{'branchemail'} || C4
::Context
->preference('KohaAdminEmailAddress');
230 C4
::Letters
::EnqueueLetter
(
232 borrowernumber
=> $borrowernumber,
233 message_transport_type
=> 'email',
234 from_address
=> $admin_email_address,
235 to_address
=> $admin_email_address,
242 ($const eq "o" || $const eq "e") or return; # FIXME: why not have a useful return value?
244 INSERT INTO reserveconstraints
245 (borrowernumber
,biblionumber
,reservedate
,biblioitemnumber
)
249 $sth = $dbh->prepare($query); # keep prepare outside the loop!
250 foreach (@
$bibitems) {
251 $sth->execute($borrowernumber, $biblionumber, $resdate, $_);
259 $res = GetReserve( $reserve_id );
261 Return the current reserve.
266 my ($reserve_id) = @_;
268 my $dbh = C4
::Context
->dbh;
269 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
270 my $sth = $dbh->prepare( $query );
271 $sth->execute( $reserve_id );
272 return $sth->fetchrow_hashref();
275 =head2 GetReservesFromBiblionumber
277 my $reserves = GetReservesFromBiblionumber({
278 biblionumber => $biblionumber,
279 [ itemnumber => $itemnumber, ]
283 This function gets the list of reservations for one C<$biblionumber>,
284 returning an arrayref pointing to the reserves for C<$biblionumber>.
286 By default, only reserves whose start date falls before the current
287 time are returned. To return all reserves, including future ones,
288 the C<all_dates> parameter can be included and set to a true value.
290 If the C<itemnumber> parameter is supplied, reserves must be targeted
291 to that item or not targeted to any item at all; otherwise, they
292 are excluded from the list.
296 sub GetReservesFromBiblionumber
{
298 my $biblionumber = $params->{biblionumber
} or return [];
299 my $itemnumber = $params->{itemnumber
};
300 my $all_dates = $params->{all_dates
} // 0;
301 my $dbh = C4
::Context
->dbh;
303 # Find the desired items in the reserves
308 timestamp AS rtimestamp,
322 WHERE biblionumber = ? ";
323 push( @params, $biblionumber );
324 unless ( $all_dates ) {
325 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
328 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
329 push( @params, $itemnumber );
331 $query .= "ORDER BY priority";
332 my $sth = $dbh->prepare($query);
333 $sth->execute( @params );
336 while ( my $data = $sth->fetchrow_hashref ) {
338 # FIXME - What is this doing? How do constraints work?
339 if ($data->{constrainttype
} eq 'o') {
341 SELECT biblioitemnumber
342 FROM reserveconstraints
343 WHERE biblionumber = ?
344 AND borrowernumber = ?
347 my $csth = $dbh->prepare($query);
348 $csth->execute($data->{biblionumber
}, $data->{borrowernumber
}, $data->{reservedate
});
350 while ( my $bibitemnos = $csth->fetchrow_array ) {
351 push( @bibitemno, $bibitemnos ); # FIXME: inefficient: use fetchall_arrayref
353 my $count = scalar @bibitemno;
355 # if we have two or more different specific itemtypes
356 # reserved by same person on same day
359 $bdata = GetBiblioItemData
( $bibitemno[$i] ); # FIXME: This doesn't make sense.
360 $i++; # $i can increase each pass, but the next @bibitemno might be smaller?
363 # Look up the book we just found.
364 $bdata = GetBiblioItemData
( $bibitemno[0] );
366 # Add the results of this latest search to the current
368 # FIXME - An 'each' would probably be more efficient.
369 foreach my $key ( keys %$bdata ) {
370 $data->{$key} = $bdata->{$key};
373 push @results, $data;
378 =head2 GetReservesFromItemnumber
380 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
382 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
384 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
388 sub GetReservesFromItemnumber
{
389 my ($itemnumber) = @_;
391 my $schema = Koha
::Database
->new()->schema();
393 my $r = $schema->resultset('Reserve')->search(
395 itemnumber
=> $itemnumber,
398 reservedate
=> \'<= CAST
( NOW
() AS DATE
)',
399 waitingdate => { '!=', undef }
403 order_by => 'priority
',
411 $r->get_column('borrowernumber
'),
412 $r->get_column('branchcode
'),
418 =head2 GetReservesFromBorrowernumber
420 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
426 sub GetReservesFromBorrowernumber {
427 my ( $borrowernumber, $status ) = @_;
428 my $dbh = C4::Context->dbh;
431 $sth = $dbh->prepare("
434 WHERE borrowernumber=?
438 $sth->execute($borrowernumber,$status);
440 $sth = $dbh->prepare("
443 WHERE borrowernumber=?
446 $sth->execute($borrowernumber);
448 my $data = $sth->fetchall_arrayref({});
451 #-------------------------------------------------------------------------------------
452 =head2 CanBookBeReserved
454 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
455 if ($canReserve eq 'OK
') { #We can reserve this Item! }
457 See CanItemBeReserved() for possible return values.
461 sub CanBookBeReserved{
462 my ($borrowernumber, $biblionumber) = @_;
464 my $items = GetItemnumbersForBiblio($biblionumber);
465 #get items linked via host records
466 my @hostitems = get_hostitemnumbers_of($biblionumber);
468 push (@$items,@hostitems);
472 foreach my $item (@$items) {
473 $canReserve = CanItemBeReserved( $borrowernumber, $item );
474 return 'OK
' if $canReserve eq 'OK
';
479 =head2 CanItemBeReserved
481 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
482 if ($canReserve eq 'OK
') { #We can reserve this Item! }
484 @RETURNS OK, if the Item can be reserved.
485 ageRestricted, if the Item is age restricted for this borrower.
486 damaged, if the Item is damaged.
487 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches
' is OK.
488 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
492 sub CanItemBeReserved{
493 my ($borrowernumber, $itemnumber) = @_;
495 my $dbh = C4::Context->dbh;
496 my $ruleitemtype; # itemtype of the matching issuing rule
497 my $allowedreserves = 0;
499 # we retrieve borrowers and items informations #
500 # item->{itype} will come for biblioitems if necessery
501 my $item = GetItem($itemnumber);
502 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
503 my $borrower = C4::Members::GetMember('borrowernumber
'=>$borrowernumber);
505 # If an item is damaged and we don't allow holds on damaged items
, we can stop right here
506 return 'damaged' if ( $item->{damaged
} && !C4
::Context
->preference('AllowHoldsOnDamagedItems') );
508 #Check for the age restriction
509 my ($ageRestriction, $daysToAgeRestriction) = C4
::Circulation
::GetAgeRestriction
( $biblioData->{agerestriction
}, $borrower );
510 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
512 my $controlbranch = C4
::Context
->preference('ReservesControlBranch');
513 my $itemtypefield = C4
::Context
->preference('item-level_itypes') ?
"itype" : "itemtype";
515 # we retrieve user rights on this itemtype and branchcode
516 my $sth = $dbh->prepare("SELECT categorycode, itemtype, branchcode, reservesallowed
518 WHERE (categorycode in (?,'*') )
519 AND (itemtype IN (?,'*'))
520 AND (branchcode IN (?,'*'))
527 my $querycount ="SELECT
530 LEFT JOIN items USING (itemnumber)
531 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
532 LEFT JOIN borrowers USING (borrowernumber)
533 WHERE borrowernumber = ?
538 my $branchfield = "reserves.branchcode";
540 if( $controlbranch eq "ItemHomeLibrary" ){
541 $branchfield = "items.homebranch";
542 $branchcode = $item->{homebranch
};
543 }elsif( $controlbranch eq "PatronLibrary" ){
544 $branchfield = "borrowers.branchcode";
545 $branchcode = $borrower->{branchcode
};
549 $sth->execute($borrower->{'categorycode'}, $item->{'itype'}, $branchcode);
550 if(my $rights = $sth->fetchrow_hashref()){
551 $ruleitemtype = $rights->{itemtype
};
552 $allowedreserves = $rights->{reservesallowed
};
559 $querycount .= "AND $branchfield = ?";
561 $querycount .= " AND $itemtypefield = ?" if ($ruleitemtype ne "*");
562 my $sthcount = $dbh->prepare($querycount);
564 if($ruleitemtype eq "*"){
565 $sthcount->execute($borrowernumber, $branchcode);
567 $sthcount->execute($borrowernumber, $branchcode, $ruleitemtype);
570 my $reservecount = "0";
571 if(my $rowcount = $sthcount->fetchrow_hashref()){
572 $reservecount = $rowcount->{count
};
575 # we check if it's ok or not
576 if( $reservecount >= $allowedreserves ){
577 return 'tooManyReserves';
580 # If reservecount is ok, we check item branch if IndependentBranches is ON
581 # and canreservefromotherbranches is OFF
582 if ( C4
::Context
->preference('IndependentBranches')
583 and !C4
::Context
->preference('canreservefromotherbranches') )
585 my $itembranch = $item->{homebranch
};
586 if ($itembranch ne $borrower->{branchcode
}) {
587 return 'cannotReserveFromOtherBranches';
594 =head2 CanReserveBeCanceledFromOpac
596 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
598 returns 1 if reserve can be cancelled by user from OPAC.
599 First check if reserve belongs to user, next checks if reserve is not in
600 transfer or waiting status
604 sub CanReserveBeCanceledFromOpac
{
605 my ($reserve_id, $borrowernumber) = @_;
607 return unless $reserve_id and $borrowernumber;
608 my $reserve = GetReserve
($reserve_id);
610 return 0 unless $reserve->{borrowernumber
} == $borrowernumber;
611 return 0 if ( $reserve->{found
} eq 'W' ) or ( $reserve->{found
} eq 'T' );
617 #--------------------------------------------------------------------------------
618 =head2 GetReserveCount
620 $number = &GetReserveCount($borrowernumber);
622 this function returns the number of reservation for a borrower given on input arg.
626 sub GetReserveCount
{
627 my ($borrowernumber) = @_;
629 my $dbh = C4
::Context
->dbh;
632 SELECT COUNT(*) AS counter
634 WHERE borrowernumber = ?
636 my $sth = $dbh->prepare($query);
637 $sth->execute($borrowernumber);
638 my $row = $sth->fetchrow_hashref;
639 return $row->{counter
};
642 =head2 GetOtherReserves
644 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
646 Check queued list of this document and check if this document must be transfered
650 sub GetOtherReserves
{
651 my ($itemnumber) = @_;
654 my ( undef, $checkreserves, undef ) = CheckReserves
($itemnumber);
655 if ($checkreserves) {
656 my $iteminfo = GetItem
($itemnumber);
657 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
658 $messages->{'transfert'} = $checkreserves->{'branchcode'};
659 #minus priorities of others reservs
660 ModReserveMinusPriority
(
662 $checkreserves->{'reserve_id'},
665 #launch the subroutine dotransfer
666 C4
::Items
::ModItemTransfer
(
668 $iteminfo->{'holdingbranch'},
669 $checkreserves->{'branchcode'}
674 #step 2b : case of a reservation on the same branch, set the waiting status
676 $messages->{'waiting'} = 1;
677 ModReserveMinusPriority
(
679 $checkreserves->{'reserve_id'},
681 ModReserveStatus
($itemnumber,'W');
684 $nextreservinfo = $checkreserves->{'borrowernumber'};
687 return ( $messages, $nextreservinfo );
692 $fee = GetReserveFee($borrowernumber,$biblionumber,$constraint,$biblionumber);
694 Calculate the fee for a reserve
699 my ($borrowernumber, $biblionumber, $constraint, $bibitems ) = @_;
702 my $dbh = C4
::Context
->dbh;
703 my $const = lc substr( $constraint, 0, 1 );
705 SELECT
* FROM borrowers
706 LEFT JOIN categories ON borrowers
.categorycode
= categories
.categorycode
707 WHERE borrowernumber
= ?
709 my $sth = $dbh->prepare($query);
710 $sth->execute($borrowernumber);
711 my $data = $sth->fetchrow_hashref;
712 my $fee = $data->{'reservefee'};
713 my $cntitems = @
- > $bibitems;
717 # check for items on issue
718 # first find biblioitem records
720 my $sth1 = $dbh->prepare(
721 "SELECT * FROM biblio LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
722 WHERE (biblio.biblionumber = ?)"
724 $sth1->execute($biblionumber);
725 while ( my $data1 = $sth1->fetchrow_hashref ) {
726 if ( $const eq "a" ) {
727 push @biblioitems, $data1;
732 while ( $x < $cntitems ) {
733 if ( @
$bibitems->{'biblioitemnumber'} ==
734 $data->{'biblioitemnumber'} )
740 if ( $const eq 'o' ) {
742 push @biblioitems, $data1;
747 push @biblioitems, $data1;
752 my $cntitemsfound = @biblioitems;
756 while ( $x < $cntitemsfound ) {
757 my $bitdata = $biblioitems[$x];
758 my $sth2 = $dbh->prepare(
760 WHERE biblioitemnumber = ?"
762 $sth2->execute( $bitdata->{'biblioitemnumber'} );
763 while ( my $itdata = $sth2->fetchrow_hashref ) {
764 my $sth3 = $dbh->prepare(
765 "SELECT * FROM issues
766 WHERE itemnumber = ?"
768 $sth3->execute( $itdata->{'itemnumber'} );
769 if ( my $isdata = $sth3->fetchrow_hashref ) {
777 if ( $allissued == 0 ) {
779 $dbh->prepare("SELECT * FROM reserves WHERE biblionumber = ?");
780 $rsth->execute($biblionumber);
781 if ( my $rdata = $rsth->fetchrow_hashref ) {
791 =head2 GetReservesToBranch
793 @transreserv = GetReservesToBranch( $frombranch );
795 Get reserve list for a given branch
799 sub GetReservesToBranch
{
800 my ( $frombranch ) = @_;
801 my $dbh = C4
::Context
->dbh;
802 my $sth = $dbh->prepare(
803 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
808 $sth->execute( $frombranch );
811 while ( my $data = $sth->fetchrow_hashref ) {
812 $transreserv[$i] = $data;
815 return (@transreserv);
818 =head2 GetReservesForBranch
820 @transreserv = GetReservesForBranch($frombranch);
824 sub GetReservesForBranch
{
825 my ($frombranch) = @_;
826 my $dbh = C4
::Context
->dbh;
829 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
834 $query .= " AND branchcode=? " if ( $frombranch );
835 $query .= "ORDER BY waitingdate" ;
837 my $sth = $dbh->prepare($query);
839 $sth->execute($frombranch);
846 while ( my $data = $sth->fetchrow_hashref ) {
847 $transreserv[$i] = $data;
850 return (@transreserv);
853 =head2 GetReserveStatus
855 $reservestatus = GetReserveStatus($itemnumber, $biblionumber);
857 Take an itemnumber or a biblionumber and return the status of the reserve places on it.
858 If several reserves exist, the reserve with the lower priority is given.
862 ## FIXME: I don't think this does what it thinks it does.
863 ## It only ever checks the first reserve result, even though
864 ## multiple reserves for that bib can have the itemnumber set
865 ## the sub is only used once in the codebase.
866 sub GetReserveStatus
{
867 my ($itemnumber, $biblionumber) = @_;
869 my $dbh = C4
::Context
->dbh;
871 my ($sth, $found, $priority);
873 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
874 $sth->execute($itemnumber);
875 ($found, $priority) = $sth->fetchrow_array;
878 if ( $biblionumber and not defined $found and not defined $priority ) {
879 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE biblionumber = ? order by priority LIMIT 1");
880 $sth->execute($biblionumber);
881 ($found, $priority) = $sth->fetchrow_array;
885 return 'Waiting' if $found eq 'W' and $priority == 0;
886 return 'Finished' if $found eq 'F';
889 return 'Reserved' if $priority > 0;
891 return ''; # empty string here will remove need for checking undef, or less log lines
896 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
897 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
898 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
900 Find a book in the reserves.
902 C<$itemnumber> is the book's item number.
903 C<$lookahead> is the number of days to look in advance for future reserves.
905 As I understand it, C<&CheckReserves> looks for the given item in the
906 reserves. If it is found, that's a match, and C<$status> is set to
909 Otherwise, it finds the most important item in the reserves with the
910 same biblio number as this book (I'm not clear on this) and returns it
911 with C<$status> set to C<Reserved>.
913 C<&CheckReserves> returns a two-element list:
915 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
917 C<$reserve> is the reserve item that matched. It is a
918 reference-to-hash whose keys are mostly the fields of the reserves
919 table in the Koha database.
924 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
925 my $dbh = C4
::Context
->dbh;
928 if (C4
::Context
->preference('item-level_itypes')){
930 SELECT items.biblionumber,
931 items.biblioitemnumber,
932 itemtypes.notforloan,
933 items.notforloan AS itemnotforloan,
939 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
940 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
945 SELECT items.biblionumber,
946 items.biblioitemnumber,
947 itemtypes.notforloan,
948 items.notforloan AS itemnotforloan,
954 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
955 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
960 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
961 $sth->execute($item);
964 $sth = $dbh->prepare("$select WHERE barcode = ?");
965 $sth->execute($barcode);
967 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
968 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
970 return if ( $damaged && !C4
::Context
->preference('AllowHoldsOnDamagedItems') );
972 return unless $itemnumber; # bail if we got nothing.
974 # if item is not for loan it cannot be reserved either.....
975 # except where items.notforloan < 0 : This indicates the item is holdable.
976 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
978 # Find this item in the reserves
979 my @reserves = _Findgroupreserve
( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
981 # $priority and $highest are used to find the most important item
982 # in the list returned by &_Findgroupreserve. (The lower $priority,
983 # the more important the item.)
984 # $highest is the most important item we've seen so far.
986 if (scalar @reserves) {
987 my $LocalHoldsPriority = C4
::Context
->preference('LocalHoldsPriority');
988 my $LocalHoldsPriorityPatronControl = C4
::Context
->preference('LocalHoldsPriorityPatronControl');
989 my $LocalHoldsPriorityItemControl = C4
::Context
->preference('LocalHoldsPriorityItemControl');
991 my $priority = 10000000;
992 foreach my $res (@reserves) {
993 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
994 return ( "Waiting", $res, \
@reserves ); # Found it
998 my $local_hold_match;
1000 if ($LocalHoldsPriority) {
1001 $borrowerinfo = C4
::Members
::GetMember
( borrowernumber
=> $res->{'borrowernumber'} );
1002 $iteminfo = C4
::Items
::GetItem
($itemnumber);
1004 my $local_holds_priority_item_branchcode =
1005 $iteminfo->{$LocalHoldsPriorityItemControl};
1006 my $local_holds_priority_patron_branchcode =
1007 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
1008 ?
$res->{branchcode
}
1009 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
1010 ?
$borrowerinfo->{branchcode
}
1013 $local_holds_priority_item_branchcode eq
1014 $local_holds_priority_patron_branchcode;
1017 # See if this item is more important than what we've got so far
1018 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
1019 $borrowerinfo ||= C4
::Members
::GetMember
( borrowernumber
=> $res->{'borrowernumber'} );
1020 $iteminfo ||= C4
::Items
::GetItem
($itemnumber);
1021 my $branch = GetReservesControlBranch
( $iteminfo, $borrowerinfo );
1022 my $branchitemrule = C4
::Circulation
::GetBranchItemRule
($branch,$iteminfo->{'itype'});
1023 next if ($branchitemrule->{'holdallowed'} == 0);
1024 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
1025 $priority = $res->{'priority'};
1027 last if $local_hold_match;
1033 # If we get this far, then no exact match was found.
1034 # We return the most important (i.e. next) reservation.
1036 $highest->{'itemnumber'} = $item;
1037 return ( "Reserved", $highest, \
@reserves );
1043 =head2 CancelExpiredReserves
1045 CancelExpiredReserves();
1047 Cancels all reserves with an expiration date from before today.
1051 sub CancelExpiredReserves
{
1053 # Cancel reserves that have passed their expiration date.
1054 my $dbh = C4
::Context
->dbh;
1055 my $sth = $dbh->prepare( "
1056 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
1057 AND expirationdate IS NOT NULL
1062 while ( my $res = $sth->fetchrow_hashref() ) {
1063 CancelReserve
({ reserve_id
=> $res->{'reserve_id'} });
1066 # Cancel reserves that have been waiting too long
1067 if ( C4
::Context
->preference("ExpireReservesMaxPickUpDelay") ) {
1068 my $max_pickup_delay = C4
::Context
->preference("ReservesMaxPickUpDelay");
1069 my $charge = C4
::Context
->preference("ExpireReservesMaxPickUpDelayCharge");
1070 my $cancel_on_holidays = C4
::Context
->preference('ExpireReservesOnHolidays');
1072 my $today = dt_from_string
();
1074 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
1075 $sth = $dbh->prepare( $query );
1076 $sth->execute( $max_pickup_delay );
1078 while ( my $res = $sth->fetchrow_hashref ) {
1080 unless ( $cancel_on_holidays ) {
1081 my $calendar = Koha
::Calendar
->new( branchcode
=> $res->{'branchcode'} );
1082 my $is_holiday = $calendar->is_holiday( $today );
1084 if ( $is_holiday ) {
1091 manualinvoice
($res->{'borrowernumber'}, $res->{'itemnumber'}, 'Hold waiting too long', 'F', $charge);
1094 CancelReserve
({ reserve_id
=> $res->{'reserve_id'} });
1101 =head2 AutoUnsuspendReserves
1103 AutoUnsuspendReserves();
1105 Unsuspends all suspended reserves with a suspend_until date from before today.
1109 sub AutoUnsuspendReserves
{
1111 my $dbh = C4
::Context
->dbh;
1113 my $query = "UPDATE reserves SET suspend = 0, suspend_until = NULL WHERE DATE( suspend_until ) < DATE( CURDATE() )";
1114 my $sth = $dbh->prepare( $query );
1119 =head2 CancelReserve
1121 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber ] });
1128 my ( $params ) = @_;
1130 my $reserve_id = $params->{'reserve_id'};
1131 $reserve_id = GetReserveId
( $params ) unless ( $reserve_id );
1133 return unless ( $reserve_id );
1135 my $dbh = C4
::Context
->dbh;
1137 my $reserve = GetReserve
( $reserve_id );
1141 SET cancellationdate = now(),
1144 WHERE reserve_id = ?
1146 my $sth = $dbh->prepare($query);
1147 $sth->execute( $reserve_id );
1150 INSERT INTO old_reserves
1151 SELECT * FROM reserves
1152 WHERE reserve_id = ?
1154 $sth = $dbh->prepare($query);
1155 $sth->execute( $reserve_id );
1158 DELETE FROM reserves
1159 WHERE reserve_id = ?
1161 $sth = $dbh->prepare($query);
1162 $sth->execute( $reserve_id );
1164 # now fix the priority on the others....
1165 _FixPriority
({ biblionumber
=> $reserve->{biblionumber
} });
1173 ModReserve({ rank => $rank,
1174 reserve_id => $reserve_id,
1175 branchcode => $branchcode
1176 [, itemnumber => $itemnumber ]
1177 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1180 Change a hold request's priority or cancel it.
1182 C<$rank> specifies the effect of the change. If C<$rank>
1183 is 'W' or 'n', nothing happens. This corresponds to leaving a
1184 request alone when changing its priority in the holds queue
1187 If C<$rank> is 'del', the hold request is cancelled.
1189 If C<$rank> is an integer greater than zero, the priority of
1190 the request is set to that value. Since priority != 0 means
1191 that the item is not waiting on the hold shelf, setting the
1192 priority to a non-zero value also sets the request's found
1193 status and waiting date to NULL.
1195 The optional C<$itemnumber> parameter is used only when
1196 C<$rank> is a non-zero integer; if supplied, the itemnumber
1197 of the hold request is set accordingly; if omitted, the itemnumber
1200 B<FIXME:> Note that the forgoing can have the effect of causing
1201 item-level hold requests to turn into title-level requests. This
1202 will be fixed once reserves has separate columns for requested
1203 itemnumber and supplying itemnumber.
1208 my ( $params ) = @_;
1210 my $rank = $params->{'rank'};
1211 my $reserve_id = $params->{'reserve_id'};
1212 my $branchcode = $params->{'branchcode'};
1213 my $itemnumber = $params->{'itemnumber'};
1214 my $suspend_until = $params->{'suspend_until'};
1215 my $borrowernumber = $params->{'borrowernumber'};
1216 my $biblionumber = $params->{'biblionumber'};
1218 return if $rank eq "W";
1219 return if $rank eq "n";
1221 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1222 $reserve_id = GetReserveId
({ biblionumber
=> $biblionumber, borrowernumber
=> $borrowernumber, itemnumber
=> $itemnumber }) unless ( $reserve_id );
1224 my $dbh = C4
::Context
->dbh;
1225 if ( $rank eq "del" ) {
1226 CancelReserve
({ reserve_id
=> $reserve_id });
1228 elsif ($rank =~ /^\d+/ and $rank > 0) {
1230 UPDATE reserves SET priority = ? ,branchcode = ?, itemnumber = ?, found = NULL, waitingdate = NULL
1231 WHERE reserve_id = ?
1233 my $sth = $dbh->prepare($query);
1234 $sth->execute( $rank, $branchcode, $itemnumber, $reserve_id );
1236 if ( defined( $suspend_until ) ) {
1237 if ( $suspend_until ) {
1238 $suspend_until = C4
::Dates
->new( $suspend_until )->output("iso");
1239 $dbh->do("UPDATE reserves SET suspend = 1, suspend_until = ? WHERE reserve_id = ?", undef, ( $suspend_until, $reserve_id ) );
1241 $dbh->do("UPDATE reserves SET suspend_until = NULL WHERE reserve_id = ?", undef, ( $reserve_id ) );
1245 _FixPriority
({ reserve_id
=> $reserve_id, rank
=>$rank });
1249 =head2 ModReserveFill
1251 &ModReserveFill($reserve);
1253 Fill a reserve. If I understand this correctly, this means that the
1254 reserved book has been found and given to the patron who reserved it.
1256 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1257 whose keys are fields from the reserves table in the Koha database.
1261 sub ModReserveFill
{
1263 my $dbh = C4
::Context
->dbh;
1264 # fill in a reserve record....
1265 my $reserve_id = $res->{'reserve_id'};
1266 my $biblionumber = $res->{'biblionumber'};
1267 my $borrowernumber = $res->{'borrowernumber'};
1268 my $resdate = $res->{'reservedate'};
1270 # get the priority on this record....
1272 my $query = "SELECT priority
1274 WHERE biblionumber = ?
1275 AND borrowernumber = ?
1276 AND reservedate = ?";
1277 my $sth = $dbh->prepare($query);
1278 $sth->execute( $biblionumber, $borrowernumber, $resdate );
1279 ($priority) = $sth->fetchrow_array;
1281 # update the database...
1282 $query = "UPDATE reserves
1285 WHERE biblionumber = ?
1287 AND borrowernumber = ?
1289 $sth = $dbh->prepare($query);
1290 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1292 # move to old_reserves
1293 $query = "INSERT INTO old_reserves
1294 SELECT * FROM reserves
1295 WHERE biblionumber = ?
1297 AND borrowernumber = ?
1299 $sth = $dbh->prepare($query);
1300 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1301 $query = "DELETE FROM reserves
1302 WHERE biblionumber = ?
1304 AND borrowernumber = ?
1306 $sth = $dbh->prepare($query);
1307 $sth->execute( $biblionumber, $resdate, $borrowernumber );
1309 # now fix the priority on the others (if the priority wasn't
1310 # already sorted!)....
1311 unless ( $priority == 0 ) {
1312 _FixPriority
({ reserve_id
=> $reserve_id, biblionumber
=> $biblionumber });
1316 =head2 ModReserveStatus
1318 &ModReserveStatus($itemnumber, $newstatus);
1320 Update the reserve status for the active (priority=0) reserve.
1322 $itemnumber is the itemnumber the reserve is on
1324 $newstatus is the new status.
1328 sub ModReserveStatus
{
1330 #first : check if we have a reservation for this item .
1331 my ($itemnumber, $newstatus) = @_;
1332 my $dbh = C4
::Context
->dbh;
1334 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1335 my $sth_set = $dbh->prepare($query);
1336 $sth_set->execute( $newstatus, $itemnumber );
1338 if ( C4
::Context
->preference("ReturnToShelvingCart") && $newstatus ) {
1339 CartToShelf
( $itemnumber );
1343 =head2 ModReserveAffect
1345 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1347 This function affect an item and a status for a given reserve
1348 The itemnumber parameter is used to find the biblionumber.
1349 with the biblionumber & the borrowernumber, we can affect the itemnumber
1350 to the correct reserve.
1352 if $transferToDo is not set, then the status is set to "Waiting" as well.
1353 otherwise, a transfer is on the way, and the end of the transfer will
1354 take care of the waiting status
1358 sub ModReserveAffect
{
1359 my ( $itemnumber, $borrowernumber,$transferToDo ) = @_;
1360 my $dbh = C4
::Context
->dbh;
1362 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1363 # attached to $itemnumber
1364 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1365 $sth->execute($itemnumber);
1366 my ($biblionumber) = $sth->fetchrow;
1368 # get request - need to find out if item is already
1369 # waiting in order to not send duplicate hold filled notifications
1370 my $reserve_id = GetReserveId
({
1371 borrowernumber
=> $borrowernumber,
1372 biblionumber
=> $biblionumber,
1374 return unless defined $reserve_id;
1375 my $request = GetReserveInfo
($reserve_id);
1376 my $already_on_shelf = ($request && $request->{found
} eq 'W') ?
1 : 0;
1378 # If we affect a reserve that has to be transfered, don't set to Waiting
1380 if ($transferToDo) {
1386 WHERE borrowernumber = ?
1387 AND biblionumber = ?
1391 # affect the reserve to Waiting as well.
1396 waitingdate = NOW(),
1398 WHERE borrowernumber = ?
1399 AND biblionumber = ?
1402 $sth = $dbh->prepare($query);
1403 $sth->execute( $itemnumber, $borrowernumber,$biblionumber);
1404 _koha_notify_reserve
( $itemnumber, $borrowernumber, $biblionumber ) if ( !$transferToDo && !$already_on_shelf );
1405 _FixPriority
( { biblionumber
=> $biblionumber } );
1406 if ( C4
::Context
->preference("ReturnToShelvingCart") ) {
1407 CartToShelf
( $itemnumber );
1413 =head2 ModReserveCancelAll
1415 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1417 function to cancel reserv,check other reserves, and transfer document if it's necessary
1421 sub ModReserveCancelAll
{
1424 my ( $itemnumber, $borrowernumber ) = @_;
1426 #step 1 : cancel the reservation
1427 my $CancelReserve = CancelReserve
({ itemnumber
=> $itemnumber, borrowernumber
=> $borrowernumber });
1429 #step 2 launch the subroutine of the others reserves
1430 ( $messages, $nextreservinfo ) = GetOtherReserves
($itemnumber);
1432 return ( $messages, $nextreservinfo );
1435 =head2 ModReserveMinusPriority
1437 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1439 Reduce the values of queued list
1443 sub ModReserveMinusPriority
{
1444 my ( $itemnumber, $reserve_id ) = @_;
1446 #first step update the value of the first person on reserv
1447 my $dbh = C4
::Context
->dbh;
1450 SET priority = 0 , itemnumber = ?
1451 WHERE reserve_id = ?
1453 my $sth_upd = $dbh->prepare($query);
1454 $sth_upd->execute( $itemnumber, $reserve_id );
1455 # second step update all others reserves
1456 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '0' });
1459 =head2 GetReserveInfo
1461 &GetReserveInfo($reserve_id);
1463 Get item and borrower details for a current hold.
1464 Current implementation this query should have a single result.
1468 sub GetReserveInfo
{
1469 my ( $reserve_id ) = @_;
1470 my $dbh = C4
::Context
->dbh;
1475 reserves.borrowernumber,
1476 reserves.biblionumber,
1477 reserves.branchcode,
1478 reserves.waitingdate,
1494 items.holdingbranch,
1495 items.itemcallnumber,
1501 LEFT JOIN items USING(itemnumber)
1502 LEFT JOIN borrowers USING(borrowernumber)
1503 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1504 WHERE reserves.reserve_id = ?";
1505 my $sth = $dbh->prepare($strsth);
1506 $sth->execute($reserve_id);
1508 my $data = $sth->fetchrow_hashref;
1512 =head2 IsAvailableForItemLevelRequest
1514 my $is_available = IsAvailableForItemLevelRequest($itemnumber);
1516 Checks whether a given item record is available for an
1517 item-level hold request. An item is available if
1519 * it is not lost AND
1520 * it is not damaged AND
1521 * it is not withdrawn AND
1522 * does not have a not for loan value > 0
1524 Whether or not the item is currently on loan is
1525 also checked - if the AllowOnShelfHolds system preference
1526 is ON, an item can be requested even if it is currently
1527 on loan to somebody else. If the system preference
1528 is OFF, an item that is currently checked out cannot
1529 be the target of an item-level hold request.
1531 Note that IsAvailableForItemLevelRequest() does not
1532 check if the staff operator is authorized to place
1533 a request on the item - in particular,
1534 this routine does not check IndependentBranches
1535 and canreservefromotherbranches.
1539 sub IsAvailableForItemLevelRequest
{
1540 my $itemnumber = shift;
1542 my $item = GetItem
($itemnumber);
1544 # must check the notforloan setting of the itemtype
1545 # FIXME - a lot of places in the code do this
1546 # or something similar - need to be
1548 my $dbh = C4
::Context
->dbh;
1549 my $notforloan_query;
1550 if (C4
::Context
->preference('item-level_itypes')) {
1551 $notforloan_query = "SELECT itemtypes.notforloan
1553 JOIN itemtypes ON (itemtypes.itemtype = items.itype)
1554 WHERE itemnumber = ?";
1556 $notforloan_query = "SELECT itemtypes.notforloan
1558 JOIN biblioitems USING (biblioitemnumber)
1559 JOIN itemtypes USING (itemtype)
1560 WHERE itemnumber = ?";
1562 my $sth = $dbh->prepare($notforloan_query);
1563 $sth->execute($itemnumber);
1564 my $notforloan_per_itemtype = 0;
1565 if (my ($notforloan) = $sth->fetchrow_array) {
1566 $notforloan_per_itemtype = 1 if $notforloan;
1569 my $available_per_item = 1;
1570 $available_per_item = 0 if $item->{itemlost
} or
1571 ( $item->{notforloan
} > 0 ) or
1572 ($item->{damaged
} and not C4
::Context
->preference('AllowHoldsOnDamagedItems')) or
1573 $item->{withdrawn
} or
1574 $notforloan_per_itemtype;
1577 if (C4
::Context
->preference('AllowOnShelfHolds')) {
1578 return $available_per_item;
1580 return ($available_per_item and ($item->{onloan
} or GetReserveStatus
($itemnumber) eq "Waiting"));
1584 =head2 AlterPriority
1586 AlterPriority( $where, $reserve_id );
1588 This function changes a reserve's priority up, down, to the top, or to the bottom.
1589 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1594 my ( $where, $reserve_id ) = @_;
1596 my $dbh = C4
::Context
->dbh;
1598 my $reserve = GetReserve
( $reserve_id );
1600 if ( $reserve->{cancellationdate
} ) {
1601 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate
}.')';
1605 if ( $where eq 'up' || $where eq 'down' ) {
1607 my $priority = $reserve->{'priority'};
1608 $priority = $where eq 'up' ?
$priority - 1 : $priority + 1;
1609 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> $priority })
1611 } elsif ( $where eq 'top' ) {
1613 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '1' })
1615 } elsif ( $where eq 'bottom' ) {
1617 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '999999' });
1622 =head2 ToggleLowestPriority
1624 ToggleLowestPriority( $borrowernumber, $biblionumber );
1626 This function sets the lowestPriority field to true if is false, and false if it is true.
1630 sub ToggleLowestPriority
{
1631 my ( $reserve_id ) = @_;
1633 my $dbh = C4
::Context
->dbh;
1635 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1636 $sth->execute( $reserve_id );
1638 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '999999' });
1641 =head2 ToggleSuspend
1643 ToggleSuspend( $reserve_id );
1645 This function sets the suspend field to true if is false, and false if it is true.
1646 If the reserve is currently suspended with a suspend_until date, that date will
1647 be cleared when it is unsuspended.
1652 my ( $reserve_id, $suspend_until ) = @_;
1654 $suspend_until = output_pref
(
1656 dt
=> dt_from_string
($suspend_until),
1657 dateformat
=> 'iso',
1660 ) if ($suspend_until);
1662 my $do_until = ( $suspend_until ) ?
'?' : 'NULL';
1664 my $dbh = C4
::Context
->dbh;
1666 my $sth = $dbh->prepare(
1667 "UPDATE reserves SET suspend = NOT suspend,
1668 suspend_until = CASE WHEN suspend = 0 THEN NULL ELSE $do_until END
1669 WHERE reserve_id = ?
1673 push( @params, $suspend_until ) if ( $suspend_until );
1674 push( @params, $reserve_id );
1676 $sth->execute( @params );
1682 borrowernumber => $borrowernumber,
1683 [ biblionumber => $biblionumber, ]
1684 [ suspend_until => $suspend_until, ]
1685 [ suspend => $suspend ]
1688 This function accepts a set of hash keys as its parameters.
1689 It requires either borrowernumber or biblionumber, or both.
1691 suspend_until is wholly optional.
1698 my $borrowernumber = $params{'borrowernumber'} || undef;
1699 my $biblionumber = $params{'biblionumber'} || undef;
1700 my $suspend_until = $params{'suspend_until'} || undef;
1701 my $suspend = defined( $params{'suspend'} ) ?
$params{'suspend'} : 1;
1703 $suspend_until = C4
::Dates
->new( $suspend_until )->output("iso") if ( defined( $suspend_until ) );
1705 return unless ( $borrowernumber || $biblionumber );
1707 my ( $query, $sth, $dbh, @query_params );
1709 $query = "UPDATE reserves SET suspend = ? ";
1710 push( @query_params, $suspend );
1712 $query .= ", suspend_until = NULL ";
1713 } elsif ( $suspend_until ) {
1714 $query .= ", suspend_until = ? ";
1715 push( @query_params, $suspend_until );
1717 $query .= " WHERE ";
1718 if ( $borrowernumber ) {
1719 $query .= " borrowernumber = ? ";
1720 push( @query_params, $borrowernumber );
1722 $query .= " AND " if ( $borrowernumber && $biblionumber );
1723 if ( $biblionumber ) {
1724 $query .= " biblionumber = ? ";
1725 push( @query_params, $biblionumber );
1727 $query .= " AND found IS NULL ";
1729 $dbh = C4
::Context
->dbh;
1730 $sth = $dbh->prepare( $query );
1731 $sth->execute( @query_params );
1738 reserve_id => $reserve_id,
1740 [ignoreSetLowestRank => $ignoreSetLowestRank]
1745 _FixPriority({ biblionumber => $biblionumber});
1747 This routine adjusts the priority of a hold request and holds
1750 In the first form, where a reserve_id is passed, the priority of the
1751 hold is set to supplied rank, and other holds for that bib are adjusted
1752 accordingly. If the rank is "del", the hold is cancelled. If no rank
1753 is supplied, all of the holds on that bib have their priority adjusted
1754 as if the second form had been used.
1756 In the second form, where a biblionumber is passed, the holds on that
1757 bib (that are not captured) are sorted in order of increasing priority,
1758 then have reserves.priority set so that the first non-captured hold
1759 has its priority set to 1, the second non-captured hold has its priority
1760 set to 2, and so forth.
1762 In both cases, holds that have the lowestPriority flag on are have their
1763 priority adjusted to ensure that they remain at the end of the line.
1765 Note that the ignoreSetLowestRank parameter is meant to be used only
1766 when _FixPriority calls itself.
1771 my ( $params ) = @_;
1772 my $reserve_id = $params->{reserve_id
};
1773 my $rank = $params->{rank
} // '';
1774 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank
};
1775 my $biblionumber = $params->{biblionumber
};
1777 my $dbh = C4
::Context
->dbh;
1779 unless ( $biblionumber ) {
1780 my $res = GetReserve
( $reserve_id );
1781 $biblionumber = $res->{biblionumber
};
1784 if ( $rank eq "del" ) {
1785 CancelReserve
({ reserve_id
=> $reserve_id });
1787 elsif ( $rank eq "W" || $rank eq "0" ) {
1789 # make sure priority for waiting or in-transit items is 0
1793 WHERE reserve_id = ?
1794 AND found IN ('W', 'T')
1796 my $sth = $dbh->prepare($query);
1797 $sth->execute( $reserve_id );
1803 SELECT reserve_id, borrowernumber, reservedate, constrainttype
1805 WHERE biblionumber = ?
1806 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1807 ORDER BY priority ASC
1809 my $sth = $dbh->prepare($query);
1810 $sth->execute( $biblionumber );
1811 while ( my $line = $sth->fetchrow_hashref ) {
1812 push( @priority, $line );
1815 # To find the matching index
1817 my $key = -1; # to allow for 0 to be a valid result
1818 for ( $i = 0 ; $i < @priority ; $i++ ) {
1819 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1820 $key = $i; # save the index
1825 # if index exists in array then move it to new position
1826 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1827 my $new_rank = $rank -
1828 1; # $new_rank is what you want the new index to be in the array
1829 my $moving_item = splice( @priority, $key, 1 );
1830 splice( @priority, $new_rank, 0, $moving_item );
1833 # now fix the priority on those that are left....
1837 WHERE reserve_id = ?
1839 $sth = $dbh->prepare($query);
1840 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1843 $priority[$j]->{'reserve_id'}
1847 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1850 unless ( $ignoreSetLowestRank ) {
1851 while ( my $res = $sth->fetchrow_hashref() ) {
1853 reserve_id
=> $res->{'reserve_id'},
1855 ignoreSetLowestRank
=> 1
1861 =head2 _Findgroupreserve
1863 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1865 Looks for an item-specific match first, then for a title-level match, returning the
1866 first match found. If neither, then we look for a 3rd kind of match based on
1867 reserve constraints.
1868 Lookahead is the number of days to look in advance.
1870 TODO: add more explanation about reserve constraints
1872 C<&_Findgroupreserve> returns :
1873 C<@results> is an array of references-to-hash whose keys are mostly
1874 fields from the reserves table of the Koha database, plus
1875 C<biblioitemnumber>.
1879 sub _Findgroupreserve
{
1880 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1881 my $dbh = C4
::Context
->dbh;
1883 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1884 # check for exact targetted match
1885 my $item_level_target_query = qq/
1886 SELECT reserves
.biblionumber AS biblionumber
,
1887 reserves
.borrowernumber AS borrowernumber
,
1888 reserves
.reservedate AS reservedate
,
1889 reserves
.branchcode AS branchcode
,
1890 reserves
.cancellationdate AS cancellationdate
,
1891 reserves
.found AS found
,
1892 reserves
.reservenotes AS reservenotes
,
1893 reserves
.priority AS priority
,
1894 reserves
.timestamp AS timestamp
,
1895 biblioitems
.biblioitemnumber AS biblioitemnumber
,
1896 reserves
.itemnumber AS itemnumber
,
1897 reserves
.reserve_id AS reserve_id
1899 JOIN biblioitems USING
(biblionumber
)
1900 JOIN hold_fill_targets USING
(biblionumber
, borrowernumber
, itemnumber
)
1903 AND item_level_request
= 1
1905 AND reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1909 my $sth = $dbh->prepare($item_level_target_query);
1910 $sth->execute($itemnumber, $lookahead||0);
1912 if ( my $data = $sth->fetchrow_hashref ) {
1913 push( @results, $data )
1914 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1916 return @results if @results;
1918 # check for title-level targetted match
1919 my $title_level_target_query = qq/
1920 SELECT reserves
.biblionumber AS biblionumber
,
1921 reserves
.borrowernumber AS borrowernumber
,
1922 reserves
.reservedate AS reservedate
,
1923 reserves
.branchcode AS branchcode
,
1924 reserves
.cancellationdate AS cancellationdate
,
1925 reserves
.found AS found
,
1926 reserves
.reservenotes AS reservenotes
,
1927 reserves
.priority AS priority
,
1928 reserves
.timestamp AS timestamp
,
1929 biblioitems
.biblioitemnumber AS biblioitemnumber
,
1930 reserves
.itemnumber AS itemnumber
,
1931 reserves
.reserve_id AS reserve_id
1933 JOIN biblioitems USING
(biblionumber
)
1934 JOIN hold_fill_targets USING
(biblionumber
, borrowernumber
)
1937 AND item_level_request
= 0
1938 AND hold_fill_targets
.itemnumber
= ?
1939 AND reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1943 $sth = $dbh->prepare($title_level_target_query);
1944 $sth->execute($itemnumber, $lookahead||0);
1946 if ( my $data = $sth->fetchrow_hashref ) {
1947 push( @results, $data )
1948 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1950 return @results if @results;
1953 SELECT reserves
.biblionumber AS biblionumber
,
1954 reserves
.borrowernumber AS borrowernumber
,
1955 reserves
.reservedate AS reservedate
,
1956 reserves
.waitingdate AS waitingdate
,
1957 reserves
.branchcode AS branchcode
,
1958 reserves
.cancellationdate AS cancellationdate
,
1959 reserves
.found AS found
,
1960 reserves
.reservenotes AS reservenotes
,
1961 reserves
.priority AS priority
,
1962 reserves
.timestamp AS timestamp
,
1963 reserveconstraints
.biblioitemnumber AS biblioitemnumber
,
1964 reserves
.itemnumber AS itemnumber
,
1965 reserves
.reserve_id AS reserve_id
1967 LEFT JOIN reserveconstraints ON reserves
.biblionumber
= reserveconstraints
.biblionumber
1968 WHERE reserves
.biblionumber
= ?
1969 AND
( ( reserveconstraints
.biblioitemnumber
= ?
1970 AND reserves
.borrowernumber
= reserveconstraints
.borrowernumber
1971 AND reserves
.reservedate
= reserveconstraints
.reservedate
)
1972 OR reserves
.constrainttype
='a' )
1973 AND
(reserves
.itemnumber IS NULL OR reserves
.itemnumber
= ?
)
1974 AND reserves
.reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1978 $sth = $dbh->prepare($query);
1979 $sth->execute( $biblio, $bibitem, $itemnumber, $lookahead||0);
1981 while ( my $data = $sth->fetchrow_hashref ) {
1982 push( @results, $data )
1983 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1988 =head2 _koha_notify_reserve
1990 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1992 Sends a notification to the patron that their hold has been filled (through
1993 ModReserveAffect, _not_ ModReserveFill)
1997 sub _koha_notify_reserve
{
1998 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
2000 my $dbh = C4
::Context
->dbh;
2001 my $borrower = C4
::Members
::GetMember
(borrowernumber
=> $borrowernumber);
2003 # Try to get the borrower's email address
2004 my $to_address = C4
::Members
::GetNoticeEmailAddress
($borrowernumber);
2006 my $messagingprefs = C4
::Members
::Messaging
::GetMessagingPreferences
( {
2007 borrowernumber
=> $borrowernumber,
2008 message_name
=> 'Hold_Filled'
2011 my $sth = $dbh->prepare("
2014 WHERE borrowernumber = ?
2015 AND biblionumber = ?
2017 $sth->execute( $borrowernumber, $biblionumber );
2018 my $reserve = $sth->fetchrow_hashref;
2019 my $branch_details = GetBranchDetail
( $reserve->{'branchcode'} );
2021 my $admin_email_address = $branch_details->{'branchemail'} || C4
::Context
->preference('KohaAdminEmailAddress');
2023 my %letter_params = (
2024 module
=> 'reserves',
2025 branchcode
=> $reserve->{branchcode
},
2027 'branches' => $branch_details,
2028 'borrowers' => $borrower,
2029 'biblio' => $biblionumber,
2030 'reserves' => $reserve,
2031 'items', $reserve->{'itemnumber'},
2033 substitute
=> { today
=> C4
::Dates
->new()->output() },
2036 my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message.
2037 my $send_notification = sub {
2038 my ( $mtt, $letter_code ) = (@_);
2039 return unless defined $letter_code;
2040 $letter_params{letter_code
} = $letter_code;
2041 $letter_params{message_transport_type
} = $mtt;
2042 my $letter = C4
::Letters
::GetPreparedLetter
( %letter_params );
2044 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
2048 C4
::Letters
::EnqueueLetter
( {
2050 borrowernumber
=> $borrowernumber,
2051 from_address
=> $admin_email_address,
2052 message_transport_type
=> $mtt,
2056 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports
} } ) {
2058 ( $mtt eq 'email' and not $to_address ) # No email address
2059 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber
} ) # No SMS number
2060 or ( $mtt eq 'phone' and C4
::Context
->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
2063 &$send_notification($mtt, $letter_code);
2064 $notification_sent++;
2066 #Making sure that a print notification is sent if no other transport types can be utilized.
2067 if (! $notification_sent) {
2068 &$send_notification('print', 'HOLD');
2073 =head2 _ShiftPriorityByDateAndPriority
2075 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
2077 This increments the priority of all reserves after the one
2078 with either the lowest date after C<$reservedate>
2079 or the lowest priority after C<$priority>.
2081 It effectively makes room for a new reserve to be inserted with a certain
2082 priority, which is returned.
2084 This is most useful when the reservedate can be set by the user. It allows
2085 the new reserve to be placed before other reserves that have a later
2086 reservedate. Since priority also is set by the form in reserves/request.pl
2087 the sub accounts for that too.
2091 sub _ShiftPriorityByDateAndPriority
{
2092 my ( $biblio, $resdate, $new_priority ) = @_;
2094 my $dbh = C4
::Context
->dbh;
2095 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2096 my $sth = $dbh->prepare( $query );
2097 $sth->execute( $biblio, $resdate, $new_priority );
2098 my $min_priority = $sth->fetchrow;
2099 # if no such matches are found, $new_priority remains as original value
2100 $new_priority = $min_priority if ( $min_priority );
2102 # Shift the priority up by one; works in conjunction with the next SQL statement
2103 $query = "UPDATE reserves
2104 SET priority = priority+1
2105 WHERE biblionumber = ?
2106 AND borrowernumber = ?
2109 my $sth_update = $dbh->prepare( $query );
2111 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2112 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2113 $sth = $dbh->prepare( $query );
2114 $sth->execute( $new_priority, $biblio );
2115 while ( my $row = $sth->fetchrow_hashref ) {
2116 $sth_update->execute( $biblio, $row->{borrowernumber
}, $row->{reservedate
} );
2119 return $new_priority; # so the caller knows what priority they wind up receiving
2124 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2126 Use when checking out an item to handle reserves
2127 If $cancelreserve boolean is set to true, it will remove existing reserve
2132 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2134 my ( $restype, $res, $all_reserves ) = CheckReserves
( $itemnumber );
2137 my $biblionumber = $res->{biblionumber
};
2138 my $biblioitemnumber = $res->{biblioitemnumber
};
2140 if ($res->{borrowernumber
} == $borrowernumber) {
2141 ModReserveFill
($res);
2145 # The item is reserved by someone else.
2146 # Find this item in the reserves
2149 foreach (@
$all_reserves) {
2150 $_->{'borrowernumber'} == $borrowernumber or next;
2151 $_->{'biblionumber'} == $biblionumber or next;
2158 # The item is reserved by the current patron
2159 ModReserveFill
($borr_res);
2162 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2163 RevertWaitingStatus
({ itemnumber
=> $itemnumber });
2165 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2167 biblionumber
=> $res->{'biblionumber'},
2168 itemnumber
=> $res->{'itemnumber'},
2169 borrowernumber
=> $res->{'borrowernumber'}
2177 MergeHolds($dbh,$to_biblio, $from_biblio);
2179 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2184 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2185 my $sth = $dbh->prepare(
2186 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2188 $sth->execute($from_biblio);
2189 if ( my $data = $sth->fetchrow_hashref() ) {
2191 # holds exist on old record, if not we don't need to do anything
2192 $sth = $dbh->prepare(
2193 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2194 $sth->execute( $to_biblio, $from_biblio );
2197 # don't reorder those already waiting
2199 $sth = $dbh->prepare(
2200 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2202 my $upd_sth = $dbh->prepare(
2203 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2204 AND reservedate = ? AND constrainttype = ? AND (itemnumber = ? or itemnumber is NULL) "
2206 $sth->execute( $to_biblio, 'W', 'T' );
2208 while ( my $reserve = $sth->fetchrow_hashref() ) {
2210 $priority, $to_biblio,
2211 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2212 $reserve->{'constrainttype'}, $reserve->{'itemnumber'}
2219 =head2 RevertWaitingStatus
2221 RevertWaitingStatus({ itemnumber => $itemnumber });
2223 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2225 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2226 item level hold, even if it was only a bibliolevel hold to
2227 begin with. This is because we can no longer know if a hold
2228 was item-level or bib-level after a hold has been set to
2233 sub RevertWaitingStatus
{
2234 my ( $params ) = @_;
2235 my $itemnumber = $params->{'itemnumber'};
2237 return unless ( $itemnumber );
2239 my $dbh = C4
::Context
->dbh;
2241 ## Get the waiting reserve we want to revert
2243 SELECT * FROM reserves
2244 WHERE itemnumber = ?
2245 AND found IS NOT NULL
2247 my $sth = $dbh->prepare( $query );
2248 $sth->execute( $itemnumber );
2249 my $reserve = $sth->fetchrow_hashref();
2251 ## Increment the priority of all other non-waiting
2252 ## reserves for this bib record
2256 priority = priority + 1
2262 $sth = $dbh->prepare( $query );
2263 $sth->execute( $reserve->{'biblionumber'} );
2265 ## Fix up the currently waiting reserve
2275 $sth = $dbh->prepare( $query );
2276 $sth->execute( $reserve->{'reserve_id'} );
2277 _FixPriority
( { biblionumber
=> $reserve->{biblionumber
} } );
2282 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2284 Returnes the first reserve id that matches the given criteria
2289 my ( $params ) = @_;
2291 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2293 my $dbh = C4
::Context
->dbh();
2295 my $sql = "SELECT reserve_id FROM reserves WHERE ";
2299 foreach my $key ( keys %$params ) {
2300 if ( defined( $params->{$key} ) ) {
2301 push( @limits, "$key = ?" );
2302 push( @params, $params->{$key} );
2306 $sql .= join( " AND ", @limits );
2308 my $sth = $dbh->prepare( $sql );
2309 $sth->execute( @params );
2310 my $row = $sth->fetchrow_hashref();
2312 return $row->{'reserve_id'};
2317 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2319 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2324 my ($branch, $borrowernumber, $biblionumber) = @_;
2326 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2328 my $reserve_id = GetReserveId
({
2329 biblionumber
=> $biblionumber,
2330 borrowernumber
=> $borrowernumber
2332 my $reserve = GetReserveInfo
($reserve_id) or return;
2334 return C4
::Letters
::GetPreparedLetter
(
2335 module
=> 'circulation',
2336 letter_code
=> 'RESERVESLIP',
2337 branchcode
=> $branch,
2339 'reserves' => $reserve,
2340 'branches' => $reserve->{branchcode
},
2341 'borrowers' => $reserve->{borrowernumber
},
2342 'biblio' => $reserve->{biblionumber
},
2343 'items' => $reserve->{itemnumber
},
2348 =head2 GetReservesControlBranch
2350 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2352 Return the branchcode to be used to determine which reserves
2353 policy applies to a transaction.
2355 C<$item> is a hashref for an item. Only 'homebranch' is used.
2357 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2361 sub GetReservesControlBranch
{
2362 my ( $item, $borrower ) = @_;
2364 my $reserves_control = C4
::Context
->preference('ReservesControlBranch');
2367 ( $reserves_control eq 'ItemHomeLibrary' ) ?
$item->{'homebranch'}
2368 : ( $reserves_control eq 'PatronLibrary' ) ?
$borrower->{'branchcode'}
2374 =head2 CalculatePriority
2376 my $p = CalculatePriority($biblionumber, $resdate);
2378 Calculate priority for a new reserve on biblionumber, placing it at
2379 the end of the line of all holds whose start date falls before
2380 the current system time and that are neither on the hold shelf
2383 The reserve date parameter is optional; if it is supplied, the
2384 priority is based on the set of holds whose start date falls before
2385 the parameter value.
2387 After calculation of this priority, it is recommended to call
2388 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2393 sub CalculatePriority
{
2394 my ( $biblionumber, $resdate ) = @_;
2397 SELECT COUNT(*) FROM reserves
2398 WHERE biblionumber = ?
2400 AND (found IS NULL OR found = '')
2402 #skip found==W or found==T (waiting or transit holds)
2404 $sql.= ' AND ( reservedate <= ? )';
2407 $sql.= ' AND ( reservedate < NOW() )';
2409 my $dbh = C4
::Context
->dbh();
2410 my @row = $dbh->selectrow_array(
2413 $resdate ?
($biblionumber, $resdate) : ($biblionumber)
2416 return @row ?
$row[0]+1 : 1;
2419 =head2 IsItemOnHoldAndFound
2421 my $bool = IsItemFoundHold( $itemnumber );
2423 Returns true if the item is currently on hold
2424 and that hold has a non-null found status ( W, T, etc. )
2428 sub IsItemOnHoldAndFound
{
2429 my ($itemnumber) = @_;
2431 my $rs = Koha
::Database
->new()->schema()->resultset('Reserve');
2433 my $found = $rs->count(
2435 itemnumber
=> $itemnumber,
2436 found
=> { '!=' => undef }
2445 Koha Development Team <http://koha-community.org/>