3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25 #use warnings; FIXME - Bug 2505
33 # for _koha_notify_reserve
34 use C4::Members::Messaging;
47 use Koha::IssuingRules;
52 use List::MoreUtils qw( firstidx any );
56 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
60 C4::Reserves - Koha functions for dealing with reservation.
68 This modules provides somes functions to deal with reservations.
70 Reserves are stored in reserves table.
71 The following columns contains important values :
72 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
73 =0 : then the reserve is being dealed
74 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
75 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
76 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
77 F(inished) : the reserve has been completed, and is done
78 - itemnumber : empty : the reserve is still unaffected to an item
79 filled: the reserve is attached to an item
80 The complete workflow is :
81 ==== 1st use case ====
82 patron request a document, 1st available : P >0, F=NULL, I=NULL
83 a library having it run "transfertodo", and clic on the list
84 if there is no transfer to do, the reserve waiting
85 patron can pick it up P =0, F=W, I=filled
86 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
87 The pickup library receive the book, it check in P =0, F=W, I=filled
88 The patron borrow the book P =0, F=F, I=filled
90 ==== 2nd use case ====
91 patron requests a document, a given item,
92 If pickup is holding branch P =0, F=W, I=filled
93 If transfer needed, write in branchtransfer P =0, F=T, I=filled
94 The pickup library receive the book, it checks it in P =0, F=W, I=filled
95 The patron borrow the book P =0, F=F, I=filled
108 &GetReservesForBranch
121 &ModReserveMinusPriority
127 &CanReserveBeCanceledFromOpac
129 &CancelExpiredReserves
131 &AutoUnsuspendReserves
133 &IsAvailableForItemLevelRequest
135 &OPACItemHoldsAllowed
138 &ToggleLowestPriority
144 &GetReservesControlBranch
148 GetMaxPatronHoldsForRecord
150 @EXPORT_OK = qw( MergeHolds );
155 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
157 Adds reserve and generates HOLDPLACED message.
159 The following tables are available witin the HOLDPLACED message:
172 $branch, $borrowernumber, $biblionumber, $bibitems,
173 $priority, $resdate, $expdate, $notes,
174 $title, $checkitem, $found, $itemtype
177 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
178 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
180 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
182 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
184 # Make room in reserves for this before those of a later reserve date
185 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
190 # If the reserv had the waiting status, we had the value of the resdate
191 if ( $found eq 'W' ) {
192 $waitingdate = $resdate;
195 # Don't add itemtype limit if specific item is selected
196 $itemtype = undef if $checkitem;
198 # updates take place here
199 my $hold = Koha::Hold->new(
201 borrowernumber => $borrowernumber,
202 biblionumber => $biblionumber,
203 reservedate => $resdate,
204 branchcode => $branch,
205 priority => $priority,
206 reservenotes => $notes,
207 itemnumber => $checkitem,
209 waitingdate => $waitingdate,
210 expirationdate => $expdate,
211 itemtype => $itemtype,
215 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
216 if C4::Context->preference('HoldsLog');
218 my $reserve_id = $hold->id();
220 # add a reserve fee if needed
221 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
222 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
223 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
226 _FixPriority({ biblionumber => $biblionumber});
228 # Send e-mail to librarian if syspref is active
229 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
230 my $patron = Koha::Patrons->find( $borrowernumber );
231 my $library = $patron->library;
232 if ( my $letter = C4::Letters::GetPreparedLetter (
233 module => 'reserves',
234 letter_code => 'HOLDPLACED',
235 branchcode => $branch,
236 lang => $patron->lang,
238 'branches' => $library->unblessed,
239 'borrowers' => $patron->unblessed,
240 'biblio' => $biblionumber,
241 'biblioitems' => $biblionumber,
242 'items' => $checkitem,
243 'reserves' => $hold->unblessed,
247 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
249 C4::Letters::EnqueueLetter(
251 borrowernumber => $borrowernumber,
252 message_transport_type => 'email',
253 from_address => $admin_email_address,
254 to_address => $admin_email_address,
265 $res = GetReserve( $reserve_id );
267 Return the current reserve.
272 my ($reserve_id) = @_;
274 my $dbh = C4::Context->dbh;
276 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
277 my $sth = $dbh->prepare( $query );
278 $sth->execute( $reserve_id );
279 return $sth->fetchrow_hashref();
282 =head2 CanBookBeReserved
284 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
285 if ($canReserve eq 'OK') { #We can reserve this Item! }
287 See CanItemBeReserved() for possible return values.
291 sub CanBookBeReserved{
292 my ($borrowernumber, $biblionumber) = @_;
294 my $items = GetItemnumbersForBiblio($biblionumber);
295 #get items linked via host records
296 my @hostitems = get_hostitemnumbers_of($biblionumber);
298 push (@$items,@hostitems);
302 foreach my $item (@$items) {
303 $canReserve = CanItemBeReserved( $borrowernumber, $item );
304 return 'OK' if $canReserve eq 'OK';
309 =head2 CanItemBeReserved
311 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
312 if ($canReserve eq 'OK') { #We can reserve this Item! }
314 @RETURNS OK, if the Item can be reserved.
315 ageRestricted, if the Item is age restricted for this borrower.
316 damaged, if the Item is damaged.
317 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
318 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
319 notReservable, if holds on this item are not allowed
323 sub CanItemBeReserved {
324 my ( $borrowernumber, $itemnumber ) = @_;
326 my $dbh = C4::Context->dbh;
327 my $ruleitemtype; # itemtype of the matching issuing rule
328 my $allowedreserves = 0; # Total number of holds allowed across all records
329 my $holds_per_record = 1; # Total number of holds allowed for this one given record
331 # we retrieve borrowers and items informations #
332 # item->{itype} will come for biblioitems if necessery
333 my $item = GetItem($itemnumber);
334 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
335 my $patron = Koha::Patrons->find( $borrowernumber );
336 my $borrower = $patron->unblessed;
338 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
340 if ( $item->{damaged}
341 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
343 # Check for the age restriction
344 my ( $ageRestriction, $daysToAgeRestriction ) =
345 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
346 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
348 # Check that the patron doesn't have an item level hold on this item already
349 return 'itemAlreadyOnHold'
350 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
352 my $controlbranch = C4::Context->preference('ReservesControlBranch');
355 SELECT count(*) AS count
357 LEFT JOIN items USING (itemnumber)
358 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
359 LEFT JOIN borrowers USING (borrowernumber)
360 WHERE borrowernumber = ?
364 my $branchfield = "reserves.branchcode";
366 if ( $controlbranch eq "ItemHomeLibrary" ) {
367 $branchfield = "items.homebranch";
368 $branchcode = $item->{homebranch};
370 elsif ( $controlbranch eq "PatronLibrary" ) {
371 $branchfield = "borrowers.branchcode";
372 $branchcode = $borrower->{branchcode};
376 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
377 $ruleitemtype = $rights->{itemtype};
378 $allowedreserves = $rights->{reservesallowed};
379 $holds_per_record = $rights->{holds_per_record};
385 $item = Koha::Items->find( $itemnumber );
386 my $holds = Koha::Holds->search(
388 borrowernumber => $borrowernumber,
389 biblionumber => $item->biblionumber,
390 found => undef, # Found holds don't count against a patron's holds limit
393 if ( $holds->count() >= $holds_per_record ) {
394 return "tooManyHoldsForThisRecord";
399 $querycount .= "AND $branchfield = ?";
401 # If using item-level itypes, fall back to the record
402 # level itemtype if the hold has no associated item
404 C4::Context->preference('item-level_itypes')
405 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
406 : " AND biblioitems.itemtype = ?"
407 if ( $ruleitemtype ne "*" );
409 my $sthcount = $dbh->prepare($querycount);
411 if ( $ruleitemtype eq "*" ) {
412 $sthcount->execute( $borrowernumber, $branchcode );
415 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
418 my $reservecount = "0";
419 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
420 $reservecount = $rowcount->{count};
423 # we check if it's ok or not
424 if ( $reservecount >= $allowedreserves ) {
425 return 'tooManyReserves';
428 my $circ_control_branch =
429 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
431 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
433 if ( $branchitemrule->{holdallowed} == 0 ) {
434 return 'notReservable';
437 if ( $branchitemrule->{holdallowed} == 1
438 && $borrower->{branchcode} ne $item->homebranch )
440 return 'cannotReserveFromOtherBranches';
443 # If reservecount is ok, we check item branch if IndependentBranches is ON
444 # and canreservefromotherbranches is OFF
445 if ( C4::Context->preference('IndependentBranches')
446 and !C4::Context->preference('canreservefromotherbranches') )
448 my $itembranch = $item->homebranch;
449 if ( $itembranch ne $borrower->{branchcode} ) {
450 return 'cannotReserveFromOtherBranches';
457 =head2 CanReserveBeCanceledFromOpac
459 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
461 returns 1 if reserve can be cancelled by user from OPAC.
462 First check if reserve belongs to user, next checks if reserve is not in
463 transfer or waiting status
467 sub CanReserveBeCanceledFromOpac {
468 my ($reserve_id, $borrowernumber) = @_;
470 return unless $reserve_id and $borrowernumber;
471 my $reserve = GetReserve($reserve_id);
473 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
474 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
480 =head2 GetReserveCount
482 $number = &GetReserveCount($borrowernumber);
484 this function returns the number of reservation for a borrower given on input arg.
488 sub GetReserveCount {
489 my ($borrowernumber) = @_;
491 my $dbh = C4::Context->dbh;
494 SELECT COUNT(*) AS counter
496 WHERE borrowernumber = ?
498 my $sth = $dbh->prepare($query);
499 $sth->execute($borrowernumber);
500 my $row = $sth->fetchrow_hashref;
501 return $row->{counter};
504 =head2 GetOtherReserves
506 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
508 Check queued list of this document and check if this document must be transferred
512 sub GetOtherReserves {
513 my ($itemnumber) = @_;
516 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
517 if ($checkreserves) {
518 my $iteminfo = GetItem($itemnumber);
519 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
520 $messages->{'transfert'} = $checkreserves->{'branchcode'};
521 #minus priorities of others reservs
522 ModReserveMinusPriority(
524 $checkreserves->{'reserve_id'},
527 #launch the subroutine dotransfer
528 C4::Items::ModItemTransfer(
530 $iteminfo->{'holdingbranch'},
531 $checkreserves->{'branchcode'}
536 #step 2b : case of a reservation on the same branch, set the waiting status
538 $messages->{'waiting'} = 1;
539 ModReserveMinusPriority(
541 $checkreserves->{'reserve_id'},
543 ModReserveStatus($itemnumber,'W');
546 $nextreservinfo = $checkreserves->{'borrowernumber'};
549 return ( $messages, $nextreservinfo );
552 =head2 ChargeReserveFee
554 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
556 Charge the fee for a reserve (if $fee > 0)
560 sub ChargeReserveFee {
561 my ( $borrowernumber, $fee, $title ) = @_;
562 return if !$fee || $fee==0; # the last test is needed to include 0.00
564 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
566 my $dbh = C4::Context->dbh;
567 my $nextacctno = &getnextacctno( $borrowernumber );
568 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
573 $fee = GetReserveFee( $borrowernumber, $biblionumber );
575 Calculate the fee for a reserve (if applicable).
580 my ( $borrowernumber, $biblionumber ) = @_;
582 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
585 SELECT COUNT(*) FROM items
586 LEFT JOIN issues USING (itemnumber)
587 WHERE items.biblionumber=? AND issues.issue_id IS NULL
590 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
593 my $dbh = C4::Context->dbh;
594 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
595 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
596 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
597 # This is a reconstruction of the old code:
598 # Compare number of items with items issued, and optionally check holds
599 # If not all items are issued and there are no holds: charge no fee
600 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
601 my ( $notissued, $reserved );
602 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
605 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
606 ( $biblionumber, $borrowernumber ) );
607 $fee = 0 if $reserved == 0;
613 =head2 GetReservesToBranch
615 @transreserv = GetReservesToBranch( $frombranch );
617 Get reserve list for a given branch
621 sub GetReservesToBranch {
622 my ( $frombranch ) = @_;
623 my $dbh = C4::Context->dbh;
624 my $sth = $dbh->prepare(
625 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
630 $sth->execute( $frombranch );
633 while ( my $data = $sth->fetchrow_hashref ) {
634 $transreserv[$i] = $data;
637 return (@transreserv);
640 =head2 GetReservesForBranch
642 @transreserv = GetReservesForBranch($frombranch);
646 sub GetReservesForBranch {
647 my ($frombranch) = @_;
648 my $dbh = C4::Context->dbh;
651 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
656 $query .= " AND branchcode=? " if ( $frombranch );
657 $query .= "ORDER BY waitingdate" ;
659 my $sth = $dbh->prepare($query);
661 $sth->execute($frombranch);
668 while ( my $data = $sth->fetchrow_hashref ) {
669 $transreserv[$i] = $data;
672 return (@transreserv);
675 =head2 GetReserveStatus
677 $reservestatus = GetReserveStatus($itemnumber);
679 Takes an itemnumber and returns the status of the reserve placed on it.
680 If several reserves exist, the reserve with the lower priority is given.
684 ## FIXME: I don't think this does what it thinks it does.
685 ## It only ever checks the first reserve result, even though
686 ## multiple reserves for that bib can have the itemnumber set
687 ## the sub is only used once in the codebase.
688 sub GetReserveStatus {
689 my ($itemnumber) = @_;
691 my $dbh = C4::Context->dbh;
693 my ($sth, $found, $priority);
695 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
696 $sth->execute($itemnumber);
697 ($found, $priority) = $sth->fetchrow_array;
701 return 'Waiting' if $found eq 'W' and $priority == 0;
702 return 'Finished' if $found eq 'F';
705 return 'Reserved' if $priority > 0;
707 return ''; # empty string here will remove need for checking undef, or less log lines
712 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
713 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
714 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
716 Find a book in the reserves.
718 C<$itemnumber> is the book's item number.
719 C<$lookahead> is the number of days to look in advance for future reserves.
721 As I understand it, C<&CheckReserves> looks for the given item in the
722 reserves. If it is found, that's a match, and C<$status> is set to
725 Otherwise, it finds the most important item in the reserves with the
726 same biblio number as this book (I'm not clear on this) and returns it
727 with C<$status> set to C<Reserved>.
729 C<&CheckReserves> returns a two-element list:
731 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
733 C<$reserve> is the reserve item that matched. It is a
734 reference-to-hash whose keys are mostly the fields of the reserves
735 table in the Koha database.
740 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
741 my $dbh = C4::Context->dbh;
744 if (C4::Context->preference('item-level_itypes')){
746 SELECT items.biblionumber,
747 items.biblioitemnumber,
748 itemtypes.notforloan,
749 items.notforloan AS itemnotforloan,
755 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
756 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
761 SELECT items.biblionumber,
762 items.biblioitemnumber,
763 itemtypes.notforloan,
764 items.notforloan AS itemnotforloan,
770 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
771 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
776 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
777 $sth->execute($item);
780 $sth = $dbh->prepare("$select WHERE barcode = ?");
781 $sth->execute($barcode);
783 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
784 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
786 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
788 return unless $itemnumber; # bail if we got nothing.
790 # if item is not for loan it cannot be reserved either.....
791 # except where items.notforloan < 0 : This indicates the item is holdable.
792 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
794 # Find this item in the reserves
795 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
797 # $priority and $highest are used to find the most important item
798 # in the list returned by &_Findgroupreserve. (The lower $priority,
799 # the more important the item.)
800 # $highest is the most important item we've seen so far.
802 if (scalar @reserves) {
803 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
804 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
805 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
807 my $priority = 10000000;
808 foreach my $res (@reserves) {
809 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
810 return ( "Waiting", $res, \@reserves ); # Found it
814 my $local_hold_match;
816 if ($LocalHoldsPriority) {
817 $patron = Koha::Patrons->find( $res->{borrowernumber} );
818 $iteminfo = C4::Items::GetItem($itemnumber);
820 my $local_holds_priority_item_branchcode =
821 $iteminfo->{$LocalHoldsPriorityItemControl};
822 my $local_holds_priority_patron_branchcode =
823 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
825 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
826 ? $patron->branchcode
829 $local_holds_priority_item_branchcode eq
830 $local_holds_priority_patron_branchcode;
833 # See if this item is more important than what we've got so far
834 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
835 $iteminfo ||= C4::Items::GetItem($itemnumber);
836 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
837 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
838 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
839 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
840 next if ($branchitemrule->{'holdallowed'} == 0);
841 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
842 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
843 $priority = $res->{'priority'};
845 last if $local_hold_match;
851 # If we get this far, then no exact match was found.
852 # We return the most important (i.e. next) reservation.
854 $highest->{'itemnumber'} = $item;
855 return ( "Reserved", $highest, \@reserves );
861 =head2 CancelExpiredReserves
863 CancelExpiredReserves();
865 Cancels all reserves with an expiration date from before today.
869 sub CancelExpiredReserves {
871 my $today = dt_from_string();
872 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
874 my $dbh = C4::Context->dbh;
875 my $sth = $dbh->prepare( "
876 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
877 AND expirationdate IS NOT NULL
881 while ( my $res = $sth->fetchrow_hashref() ) {
882 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
883 my $cancel_params = { reserve_id => $res->{'reserve_id'} };
885 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
887 if ( $res->{found} eq 'W' ) {
888 $cancel_params->{charge_cancel_fee} = 1;
891 CancelReserve($cancel_params);
895 =head2 AutoUnsuspendReserves
897 AutoUnsuspendReserves();
899 Unsuspends all suspended reserves with a suspend_until date from before today.
903 sub AutoUnsuspendReserves {
904 my $today = dt_from_string();
906 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
908 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
913 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
915 Cancels a reserve. If C<charge_cancel_fee> is passed and the C<ExpireReservesMaxPickUpDelayCharge> syspref is set, charge that fee to the patron's account.
922 my $reserve_id = $params->{'reserve_id'};
923 # Filter out only the desired keys; this will insert undefined values for elements missing in
924 # \%params, but GetReserveId filters them out anyway.
925 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
927 return unless ( $reserve_id );
929 my $dbh = C4::Context->dbh;
931 my $reserve = GetReserve( $reserve_id );
934 my $hold = Koha::Holds->find( $reserve_id );
935 logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
936 if C4::Context->preference('HoldsLog');
940 SET cancellationdate = now(),
944 my $sth = $dbh->prepare($query);
945 $sth->execute( $reserve_id );
948 INSERT INTO old_reserves
949 SELECT * FROM reserves
952 $sth = $dbh->prepare($query);
953 $sth->execute( $reserve_id );
959 $sth = $dbh->prepare($query);
960 $sth->execute( $reserve_id );
962 # now fix the priority on the others....
963 _FixPriority({ biblionumber => $reserve->{biblionumber} });
965 # and, if desired, charge a cancel fee
966 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
967 if ( $charge && $params->{'charge_cancel_fee'} ) {
968 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, '', 'HE', $charge);
977 ModReserve({ rank => $rank,
978 reserve_id => $reserve_id,
979 branchcode => $branchcode
980 [, itemnumber => $itemnumber ]
981 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
984 Change a hold request's priority or cancel it.
986 C<$rank> specifies the effect of the change. If C<$rank>
987 is 'W' or 'n', nothing happens. This corresponds to leaving a
988 request alone when changing its priority in the holds queue
991 If C<$rank> is 'del', the hold request is cancelled.
993 If C<$rank> is an integer greater than zero, the priority of
994 the request is set to that value. Since priority != 0 means
995 that the item is not waiting on the hold shelf, setting the
996 priority to a non-zero value also sets the request's found
997 status and waiting date to NULL.
999 The optional C<$itemnumber> parameter is used only when
1000 C<$rank> is a non-zero integer; if supplied, the itemnumber
1001 of the hold request is set accordingly; if omitted, the itemnumber
1004 B<FIXME:> Note that the forgoing can have the effect of causing
1005 item-level hold requests to turn into title-level requests. This
1006 will be fixed once reserves has separate columns for requested
1007 itemnumber and supplying itemnumber.
1012 my ( $params ) = @_;
1014 my $rank = $params->{'rank'};
1015 my $reserve_id = $params->{'reserve_id'};
1016 my $branchcode = $params->{'branchcode'};
1017 my $itemnumber = $params->{'itemnumber'};
1018 my $suspend_until = $params->{'suspend_until'};
1019 my $borrowernumber = $params->{'borrowernumber'};
1020 my $biblionumber = $params->{'biblionumber'};
1022 return if $rank eq "W";
1023 return if $rank eq "n";
1025 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1026 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1028 if ( $rank eq "del" ) {
1029 CancelReserve({ reserve_id => $reserve_id });
1031 elsif ($rank =~ /^\d+/ and $rank > 0) {
1032 my $hold = Koha::Holds->find($reserve_id);
1033 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1034 if C4::Context->preference('HoldsLog');
1039 branchcode => $branchcode,
1040 itemnumber => $itemnumber,
1042 waitingdate => undef
1046 if ( defined( $suspend_until ) ) {
1047 if ( $suspend_until ) {
1048 $suspend_until = eval { dt_from_string( $suspend_until ) };
1049 $hold->suspend_hold( $suspend_until );
1051 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1052 # If the hold is not suspended, this does nothing.
1053 $hold->set( { suspend_until => undef } )->store();
1057 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1061 =head2 ModReserveFill
1063 &ModReserveFill($reserve);
1065 Fill a reserve. If I understand this correctly, this means that the
1066 reserved book has been found and given to the patron who reserved it.
1068 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1069 whose keys are fields from the reserves table in the Koha database.
1073 sub ModReserveFill {
1075 my $reserve_id = $res->{'reserve_id'};
1077 my $hold = Koha::Holds->find($reserve_id);
1079 # get the priority on this record....
1080 my $priority = $hold->priority;
1082 # update the hold statuses, no need to store it though, we will be deleting it anyway
1090 Koha::Old::Hold->new( $hold->unblessed() )->store();
1094 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1095 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1096 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1099 # now fix the priority on the others (if the priority wasn't
1100 # already sorted!)....
1101 unless ( $priority == 0 ) {
1102 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1106 =head2 ModReserveStatus
1108 &ModReserveStatus($itemnumber, $newstatus);
1110 Update the reserve status for the active (priority=0) reserve.
1112 $itemnumber is the itemnumber the reserve is on
1114 $newstatus is the new status.
1118 sub ModReserveStatus {
1120 #first : check if we have a reservation for this item .
1121 my ($itemnumber, $newstatus) = @_;
1122 my $dbh = C4::Context->dbh;
1124 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1125 my $sth_set = $dbh->prepare($query);
1126 $sth_set->execute( $newstatus, $itemnumber );
1128 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1129 CartToShelf( $itemnumber );
1133 =head2 ModReserveAffect
1135 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1137 This function affect an item and a status for a given reserve, either fetched directly
1138 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1139 is given, only first reserve returned is affected, which is ok for anything but
1142 if $transferToDo is not set, then the status is set to "Waiting" as well.
1143 otherwise, a transfer is on the way, and the end of the transfer will
1144 take care of the waiting status
1148 sub ModReserveAffect {
1149 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1150 my $dbh = C4::Context->dbh;
1152 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1153 # attached to $itemnumber
1154 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1155 $sth->execute($itemnumber);
1156 my ($biblionumber) = $sth->fetchrow;
1158 # get request - need to find out if item is already
1159 # waiting in order to not send duplicate hold filled notifications
1162 # Find hold by id if we have it
1163 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1164 # Find item level hold for this item if there is one
1165 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1166 # Find record level hold if there is no item level hold
1167 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1169 return unless $hold;
1171 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1173 $hold->itemnumber($itemnumber);
1174 $hold->set_waiting($transferToDo);
1176 _koha_notify_reserve( $hold->reserve_id )
1177 if ( !$transferToDo && !$already_on_shelf );
1179 _FixPriority( { biblionumber => $biblionumber } );
1181 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1182 CartToShelf($itemnumber);
1188 =head2 ModReserveCancelAll
1190 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1192 function to cancel reserv,check other reserves, and transfer document if it's necessary
1196 sub ModReserveCancelAll {
1199 my ( $itemnumber, $borrowernumber ) = @_;
1201 #step 1 : cancel the reservation
1202 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1204 #step 2 launch the subroutine of the others reserves
1205 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1207 return ( $messages, $nextreservinfo );
1210 =head2 ModReserveMinusPriority
1212 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1214 Reduce the values of queued list
1218 sub ModReserveMinusPriority {
1219 my ( $itemnumber, $reserve_id ) = @_;
1221 #first step update the value of the first person on reserv
1222 my $dbh = C4::Context->dbh;
1225 SET priority = 0 , itemnumber = ?
1226 WHERE reserve_id = ?
1228 my $sth_upd = $dbh->prepare($query);
1229 $sth_upd->execute( $itemnumber, $reserve_id );
1230 # second step update all others reserves
1231 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1234 =head2 GetReserveInfo
1236 &GetReserveInfo($reserve_id);
1238 Get item and borrower details for a current hold.
1239 Current implementation this query should have a single result.
1243 sub GetReserveInfo {
1244 my ( $reserve_id ) = @_;
1245 my $dbh = C4::Context->dbh;
1250 reserves.borrowernumber,
1251 reserves.biblionumber,
1252 reserves.branchcode,
1253 reserves.waitingdate,
1269 items.holdingbranch,
1270 items.itemcallnumber,
1276 LEFT JOIN items USING(itemnumber)
1277 LEFT JOIN borrowers USING(borrowernumber)
1278 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1279 WHERE reserves.reserve_id = ?";
1280 my $sth = $dbh->prepare($strsth);
1281 $sth->execute($reserve_id);
1283 my $data = $sth->fetchrow_hashref;
1287 =head2 IsAvailableForItemLevelRequest
1289 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1291 Checks whether a given item record is available for an
1292 item-level hold request. An item is available if
1294 * it is not lost AND
1295 * it is not damaged AND
1296 * it is not withdrawn AND
1297 * does not have a not for loan value > 0
1299 Need to check the issuingrules onshelfholds column,
1300 if this is set items on the shelf can be placed on hold
1302 Note that IsAvailableForItemLevelRequest() does not
1303 check if the staff operator is authorized to place
1304 a request on the item - in particular,
1305 this routine does not check IndependentBranches
1306 and canreservefromotherbranches.
1310 sub IsAvailableForItemLevelRequest {
1312 my $borrower = shift;
1314 my $dbh = C4::Context->dbh;
1315 # must check the notforloan setting of the itemtype
1316 # FIXME - a lot of places in the code do this
1317 # or something similar - need to be
1319 my $itype = _get_itype($item);
1320 my $notforloan_per_itemtype
1321 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1325 $notforloan_per_itemtype ||
1326 $item->{itemlost} ||
1327 $item->{notforloan} > 0 ||
1328 $item->{withdrawn} ||
1329 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1331 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1333 if ( $on_shelf_holds == 1 ) {
1335 } elsif ( $on_shelf_holds == 2 ) {
1337 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1339 my $any_available = 0;
1341 foreach my $i (@items) {
1344 || $i->notforloan > 0
1347 || IsItemOnHoldAndFound( $i->id )
1349 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1350 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1353 return $any_available ? 0 : 1;
1356 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1359 =head2 OnShelfHoldsAllowed
1361 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1363 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1364 holds are allowed, returns true if so.
1368 sub OnShelfHoldsAllowed {
1369 my ($item, $borrower) = @_;
1371 my $itype = _get_itype($item);
1372 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1379 if (C4::Context->preference('item-level_itypes')) {
1380 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1381 # When GetItem is fixed, we can remove this
1382 $itype = $item->{itype};
1385 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1386 # So if we already have a biblioitems join when calling this function,
1387 # we don't need to access the database again
1388 $itype = $item->{itemtype};
1391 my $dbh = C4::Context->dbh;
1392 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1393 my $sth = $dbh->prepare($query);
1394 $sth->execute($item->{biblioitemnumber});
1395 if (my $data = $sth->fetchrow_hashref()){
1396 $itype = $data->{itemtype};
1402 sub _OnShelfHoldsAllowed {
1403 my ($itype,$borrowercategory,$branchcode) = @_;
1405 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1406 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1409 =head2 AlterPriority
1411 AlterPriority( $where, $reserve_id );
1413 This function changes a reserve's priority up, down, to the top, or to the bottom.
1414 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1419 my ( $where, $reserve_id ) = @_;
1421 my $reserve = GetReserve( $reserve_id );
1423 if ( $reserve->{cancellationdate} ) {
1424 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1428 if ( $where eq 'up' || $where eq 'down' ) {
1430 my $priority = $reserve->{'priority'};
1431 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1432 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1434 } elsif ( $where eq 'top' ) {
1436 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1438 } elsif ( $where eq 'bottom' ) {
1440 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1445 =head2 ToggleLowestPriority
1447 ToggleLowestPriority( $borrowernumber, $biblionumber );
1449 This function sets the lowestPriority field to true if is false, and false if it is true.
1453 sub ToggleLowestPriority {
1454 my ( $reserve_id ) = @_;
1456 my $dbh = C4::Context->dbh;
1458 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1459 $sth->execute( $reserve_id );
1461 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1464 =head2 ToggleSuspend
1466 ToggleSuspend( $reserve_id );
1468 This function sets the suspend field to true if is false, and false if it is true.
1469 If the reserve is currently suspended with a suspend_until date, that date will
1470 be cleared when it is unsuspended.
1475 my ( $reserve_id, $suspend_until ) = @_;
1477 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1479 my $hold = Koha::Holds->find( $reserve_id );
1481 if ( $hold->is_suspended ) {
1484 $hold->suspend_hold( $suspend_until );
1491 borrowernumber => $borrowernumber,
1492 [ biblionumber => $biblionumber, ]
1493 [ suspend_until => $suspend_until, ]
1494 [ suspend => $suspend ]
1497 This function accepts a set of hash keys as its parameters.
1498 It requires either borrowernumber or biblionumber, or both.
1500 suspend_until is wholly optional.
1507 my $borrowernumber = $params{'borrowernumber'} || undef;
1508 my $biblionumber = $params{'biblionumber'} || undef;
1509 my $suspend_until = $params{'suspend_until'} || undef;
1510 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1512 $suspend_until = eval { dt_from_string($suspend_until) }
1513 if ( defined($suspend_until) );
1515 return unless ( $borrowernumber || $biblionumber );
1518 $params->{found} = undef;
1519 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1520 $params->{biblionumber} = $biblionumber if $biblionumber;
1522 my @holds = Koha::Holds->search($params);
1525 map { $_->suspend_hold($suspend_until) } @holds;
1528 map { $_->resume() } @holds;
1536 reserve_id => $reserve_id,
1538 [ignoreSetLowestRank => $ignoreSetLowestRank]
1543 _FixPriority({ biblionumber => $biblionumber});
1545 This routine adjusts the priority of a hold request and holds
1548 In the first form, where a reserve_id is passed, the priority of the
1549 hold is set to supplied rank, and other holds for that bib are adjusted
1550 accordingly. If the rank is "del", the hold is cancelled. If no rank
1551 is supplied, all of the holds on that bib have their priority adjusted
1552 as if the second form had been used.
1554 In the second form, where a biblionumber is passed, the holds on that
1555 bib (that are not captured) are sorted in order of increasing priority,
1556 then have reserves.priority set so that the first non-captured hold
1557 has its priority set to 1, the second non-captured hold has its priority
1558 set to 2, and so forth.
1560 In both cases, holds that have the lowestPriority flag on are have their
1561 priority adjusted to ensure that they remain at the end of the line.
1563 Note that the ignoreSetLowestRank parameter is meant to be used only
1564 when _FixPriority calls itself.
1569 my ( $params ) = @_;
1570 my $reserve_id = $params->{reserve_id};
1571 my $rank = $params->{rank} // '';
1572 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1573 my $biblionumber = $params->{biblionumber};
1575 my $dbh = C4::Context->dbh;
1577 unless ( $biblionumber ) {
1578 my $res = GetReserve( $reserve_id );
1579 $biblionumber = $res->{biblionumber};
1582 if ( $rank eq "del" ) {
1583 CancelReserve({ reserve_id => $reserve_id });
1585 elsif ( $rank eq "W" || $rank eq "0" ) {
1587 # make sure priority for waiting or in-transit items is 0
1591 WHERE reserve_id = ?
1592 AND found IN ('W', 'T')
1594 my $sth = $dbh->prepare($query);
1595 $sth->execute( $reserve_id );
1601 SELECT reserve_id, borrowernumber, reservedate
1603 WHERE biblionumber = ?
1604 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1605 ORDER BY priority ASC
1607 my $sth = $dbh->prepare($query);
1608 $sth->execute( $biblionumber );
1609 while ( my $line = $sth->fetchrow_hashref ) {
1610 push( @priority, $line );
1613 # To find the matching index
1615 my $key = -1; # to allow for 0 to be a valid result
1616 for ( $i = 0 ; $i < @priority ; $i++ ) {
1617 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1618 $key = $i; # save the index
1623 # if index exists in array then move it to new position
1624 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1625 my $new_rank = $rank -
1626 1; # $new_rank is what you want the new index to be in the array
1627 my $moving_item = splice( @priority, $key, 1 );
1628 splice( @priority, $new_rank, 0, $moving_item );
1631 # now fix the priority on those that are left....
1635 WHERE reserve_id = ?
1637 $sth = $dbh->prepare($query);
1638 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1641 $priority[$j]->{'reserve_id'}
1645 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1648 unless ( $ignoreSetLowestRank ) {
1649 while ( my $res = $sth->fetchrow_hashref() ) {
1651 reserve_id => $res->{'reserve_id'},
1653 ignoreSetLowestRank => 1
1659 =head2 _Findgroupreserve
1661 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1663 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1664 first match found. If neither, then we look for non-holds-queue based holds.
1665 Lookahead is the number of days to look in advance.
1667 C<&_Findgroupreserve> returns :
1668 C<@results> is an array of references-to-hash whose keys are mostly
1669 fields from the reserves table of the Koha database, plus
1670 C<biblioitemnumber>.
1674 sub _Findgroupreserve {
1675 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1676 my $dbh = C4::Context->dbh;
1678 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1679 # check for exact targeted match
1680 my $item_level_target_query = qq{
1681 SELECT reserves.biblionumber AS biblionumber,
1682 reserves.borrowernumber AS borrowernumber,
1683 reserves.reservedate AS reservedate,
1684 reserves.branchcode AS branchcode,
1685 reserves.cancellationdate AS cancellationdate,
1686 reserves.found AS found,
1687 reserves.reservenotes AS reservenotes,
1688 reserves.priority AS priority,
1689 reserves.timestamp AS timestamp,
1690 biblioitems.biblioitemnumber AS biblioitemnumber,
1691 reserves.itemnumber AS itemnumber,
1692 reserves.reserve_id AS reserve_id,
1693 reserves.itemtype AS itemtype
1695 JOIN biblioitems USING (biblionumber)
1696 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1699 AND item_level_request = 1
1701 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1705 my $sth = $dbh->prepare($item_level_target_query);
1706 $sth->execute($itemnumber, $lookahead||0);
1708 if ( my $data = $sth->fetchrow_hashref ) {
1709 push( @results, $data )
1710 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1712 return @results if @results;
1714 # check for title-level targeted match
1715 my $title_level_target_query = qq{
1716 SELECT reserves.biblionumber AS biblionumber,
1717 reserves.borrowernumber AS borrowernumber,
1718 reserves.reservedate AS reservedate,
1719 reserves.branchcode AS branchcode,
1720 reserves.cancellationdate AS cancellationdate,
1721 reserves.found AS found,
1722 reserves.reservenotes AS reservenotes,
1723 reserves.priority AS priority,
1724 reserves.timestamp AS timestamp,
1725 biblioitems.biblioitemnumber AS biblioitemnumber,
1726 reserves.itemnumber AS itemnumber,
1727 reserves.reserve_id AS reserve_id,
1728 reserves.itemtype AS itemtype
1730 JOIN biblioitems USING (biblionumber)
1731 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1734 AND item_level_request = 0
1735 AND hold_fill_targets.itemnumber = ?
1736 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1740 $sth = $dbh->prepare($title_level_target_query);
1741 $sth->execute($itemnumber, $lookahead||0);
1743 if ( my $data = $sth->fetchrow_hashref ) {
1744 push( @results, $data )
1745 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1747 return @results if @results;
1750 SELECT reserves.biblionumber AS biblionumber,
1751 reserves.borrowernumber AS borrowernumber,
1752 reserves.reservedate AS reservedate,
1753 reserves.waitingdate AS waitingdate,
1754 reserves.branchcode AS branchcode,
1755 reserves.cancellationdate AS cancellationdate,
1756 reserves.found AS found,
1757 reserves.reservenotes AS reservenotes,
1758 reserves.priority AS priority,
1759 reserves.timestamp AS timestamp,
1760 reserves.itemnumber AS itemnumber,
1761 reserves.reserve_id AS reserve_id,
1762 reserves.itemtype AS itemtype
1764 WHERE reserves.biblionumber = ?
1765 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1766 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1770 $sth = $dbh->prepare($query);
1771 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1773 while ( my $data = $sth->fetchrow_hashref ) {
1774 push( @results, $data )
1775 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1780 =head2 _koha_notify_reserve
1782 _koha_notify_reserve( $hold->reserve_id );
1784 Sends a notification to the patron that their hold has been filled (through
1785 ModReserveAffect, _not_ ModReserveFill)
1787 The letter code for this notice may be found using the following query:
1789 select distinct letter_code
1790 from message_transports
1791 inner join message_attributes using (message_attribute_id)
1792 where message_name = 'Hold_Filled'
1794 This will probably sipmly be 'HOLD', but because it is defined in the database,
1795 it is subject to addition or change.
1797 The following tables are availalbe witin the notice:
1808 sub _koha_notify_reserve {
1809 my $reserve_id = shift;
1810 my $hold = Koha::Holds->find($reserve_id);
1811 my $borrowernumber = $hold->borrowernumber;
1813 my $patron = Koha::Patrons->find( $borrowernumber );
1815 # Try to get the borrower's email address
1816 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1818 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1819 borrowernumber => $borrowernumber,
1820 message_name => 'Hold_Filled'
1823 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1825 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1827 my %letter_params = (
1828 module => 'reserves',
1829 branchcode => $hold->branchcode,
1830 lang => $patron->lang,
1832 'branches' => $library,
1833 'borrowers' => $patron->unblessed,
1834 'biblio' => $hold->biblionumber,
1835 'biblioitems' => $hold->biblionumber,
1836 'reserves' => $hold->unblessed,
1837 'items' => $hold->itemnumber,
1841 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.
1842 my $send_notification = sub {
1843 my ( $mtt, $letter_code ) = (@_);
1844 return unless defined $letter_code;
1845 $letter_params{letter_code} = $letter_code;
1846 $letter_params{message_transport_type} = $mtt;
1847 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1849 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1853 C4::Letters::EnqueueLetter( {
1855 borrowernumber => $borrowernumber,
1856 from_address => $admin_email_address,
1857 message_transport_type => $mtt,
1861 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1863 ( $mtt eq 'email' and not $to_address ) # No email address
1864 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1865 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1868 &$send_notification($mtt, $letter_code);
1869 $notification_sent++;
1871 #Making sure that a print notification is sent if no other transport types can be utilized.
1872 if (! $notification_sent) {
1873 &$send_notification('print', 'HOLD');
1878 =head2 _ShiftPriorityByDateAndPriority
1880 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1882 This increments the priority of all reserves after the one
1883 with either the lowest date after C<$reservedate>
1884 or the lowest priority after C<$priority>.
1886 It effectively makes room for a new reserve to be inserted with a certain
1887 priority, which is returned.
1889 This is most useful when the reservedate can be set by the user. It allows
1890 the new reserve to be placed before other reserves that have a later
1891 reservedate. Since priority also is set by the form in reserves/request.pl
1892 the sub accounts for that too.
1896 sub _ShiftPriorityByDateAndPriority {
1897 my ( $biblio, $resdate, $new_priority ) = @_;
1899 my $dbh = C4::Context->dbh;
1900 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1901 my $sth = $dbh->prepare( $query );
1902 $sth->execute( $biblio, $resdate, $new_priority );
1903 my $min_priority = $sth->fetchrow;
1904 # if no such matches are found, $new_priority remains as original value
1905 $new_priority = $min_priority if ( $min_priority );
1907 # Shift the priority up by one; works in conjunction with the next SQL statement
1908 $query = "UPDATE reserves
1909 SET priority = priority+1
1910 WHERE biblionumber = ?
1911 AND borrowernumber = ?
1914 my $sth_update = $dbh->prepare( $query );
1916 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1917 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1918 $sth = $dbh->prepare( $query );
1919 $sth->execute( $new_priority, $biblio );
1920 while ( my $row = $sth->fetchrow_hashref ) {
1921 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1924 return $new_priority; # so the caller knows what priority they wind up receiving
1927 =head2 OPACItemHoldsAllowed
1929 OPACItemHoldsAllowed($item_record,$borrower_record);
1931 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1932 if specific item holds are allowed, returns true if so.
1936 sub OPACItemHoldsAllowed {
1937 my ($item,$borrower) = @_;
1939 my $branchcode = $item->{homebranch} or die "No homebranch";
1941 my $dbh = C4::Context->dbh;
1942 if (C4::Context->preference('item-level_itypes')) {
1943 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1944 # When GetItem is fixed, we can remove this
1945 $itype = $item->{itype};
1948 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1949 my $sth = $dbh->prepare($query);
1950 $sth->execute($item->{biblioitemnumber});
1951 if (my $data = $sth->fetchrow_hashref()){
1952 $itype = $data->{itemtype};
1956 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1957 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1959 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1961 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1963 issuingrules.categorycode desc,
1964 issuingrules.itemtype desc,
1965 issuingrules.branchcode desc
1967 my $sth = $dbh->prepare($query);
1968 $sth->execute($borrower->{categorycode},$itype,$branchcode);
1969 my $data = $sth->fetchrow_hashref;
1970 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1971 return '' if $opacitemholds eq 'N';
1972 return $opacitemholds;
1977 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1979 Use when checking out an item to handle reserves
1980 If $cancelreserve boolean is set to true, it will remove existing reserve
1985 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1987 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1988 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1991 my $biblionumber = $res->{biblionumber};
1993 if ($res->{borrowernumber} == $borrowernumber) {
1994 ModReserveFill($res);
1998 # The item is reserved by someone else.
1999 # Find this item in the reserves
2002 foreach (@$all_reserves) {
2003 $_->{'borrowernumber'} == $borrowernumber or next;
2004 $_->{'biblionumber'} == $biblionumber or next;
2011 # The item is reserved by the current patron
2012 ModReserveFill($borr_res);
2015 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2016 RevertWaitingStatus({ itemnumber => $itemnumber });
2018 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2019 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2026 MergeHolds($dbh,$to_biblio, $from_biblio);
2028 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2033 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2034 my $sth = $dbh->prepare(
2035 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2037 $sth->execute($from_biblio);
2038 if ( my $data = $sth->fetchrow_hashref() ) {
2040 # holds exist on old record, if not we don't need to do anything
2041 $sth = $dbh->prepare(
2042 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2043 $sth->execute( $to_biblio, $from_biblio );
2046 # don't reorder those already waiting
2048 $sth = $dbh->prepare(
2049 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2051 my $upd_sth = $dbh->prepare(
2052 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2053 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2055 $sth->execute( $to_biblio, 'W', 'T' );
2057 while ( my $reserve = $sth->fetchrow_hashref() ) {
2059 $priority, $to_biblio,
2060 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2061 $reserve->{'itemnumber'}
2068 =head2 RevertWaitingStatus
2070 RevertWaitingStatus({ itemnumber => $itemnumber });
2072 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2074 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2075 item level hold, even if it was only a bibliolevel hold to
2076 begin with. This is because we can no longer know if a hold
2077 was item-level or bib-level after a hold has been set to
2082 sub RevertWaitingStatus {
2083 my ( $params ) = @_;
2084 my $itemnumber = $params->{'itemnumber'};
2086 return unless ( $itemnumber );
2088 my $dbh = C4::Context->dbh;
2090 ## Get the waiting reserve we want to revert
2092 SELECT * FROM reserves
2093 WHERE itemnumber = ?
2094 AND found IS NOT NULL
2096 my $sth = $dbh->prepare( $query );
2097 $sth->execute( $itemnumber );
2098 my $reserve = $sth->fetchrow_hashref();
2100 ## Increment the priority of all other non-waiting
2101 ## reserves for this bib record
2105 priority = priority + 1
2111 $sth = $dbh->prepare( $query );
2112 $sth->execute( $reserve->{'biblionumber'} );
2114 ## Fix up the currently waiting reserve
2124 $sth = $dbh->prepare( $query );
2125 $sth->execute( $reserve->{'reserve_id'} );
2126 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2131 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2133 Returnes the first reserve id that matches the given criteria
2138 my ( $params ) = @_;
2140 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2142 foreach my $key ( keys %$params ) {
2143 delete $params->{$key} unless defined( $params->{$key} );
2146 my $hold = Koha::Holds->search( $params )->next();
2148 return unless $hold;
2155 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2157 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2159 The letter code will be HOLD_SLIP, and the following tables are
2160 available within the slip:
2172 my ($branch, $borrowernumber, $biblionumber) = @_;
2174 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2175 my $patron = Koha::Patrons->find( $borrowernumber );
2177 my $reserve_id = GetReserveId({
2178 biblionumber => $biblionumber,
2179 borrowernumber => $borrowernumber
2181 my $reserve = GetReserveInfo($reserve_id) or return;
2183 return C4::Letters::GetPreparedLetter (
2184 module => 'circulation',
2185 letter_code => 'HOLD_SLIP',
2186 branchcode => $branch,
2187 lang => $patron->lang,
2189 'reserves' => $reserve,
2190 'branches' => $reserve->{branchcode},
2191 'borrowers' => $reserve->{borrowernumber},
2192 'biblio' => $reserve->{biblionumber},
2193 'biblioitems' => $reserve->{biblionumber},
2194 'items' => $reserve->{itemnumber},
2199 =head2 GetReservesControlBranch
2201 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2203 Return the branchcode to be used to determine which reserves
2204 policy applies to a transaction.
2206 C<$item> is a hashref for an item. Only 'homebranch' is used.
2208 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2212 sub GetReservesControlBranch {
2213 my ( $item, $borrower ) = @_;
2215 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2218 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2219 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2225 =head2 CalculatePriority
2227 my $p = CalculatePriority($biblionumber, $resdate);
2229 Calculate priority for a new reserve on biblionumber, placing it at
2230 the end of the line of all holds whose start date falls before
2231 the current system time and that are neither on the hold shelf
2234 The reserve date parameter is optional; if it is supplied, the
2235 priority is based on the set of holds whose start date falls before
2236 the parameter value.
2238 After calculation of this priority, it is recommended to call
2239 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2244 sub CalculatePriority {
2245 my ( $biblionumber, $resdate ) = @_;
2248 SELECT COUNT(*) FROM reserves
2249 WHERE biblionumber = ?
2251 AND (found IS NULL OR found = '')
2253 #skip found==W or found==T (waiting or transit holds)
2255 $sql.= ' AND ( reservedate <= ? )';
2258 $sql.= ' AND ( reservedate < NOW() )';
2260 my $dbh = C4::Context->dbh();
2261 my @row = $dbh->selectrow_array(
2264 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2267 return @row ? $row[0]+1 : 1;
2270 =head2 IsItemOnHoldAndFound
2272 my $bool = IsItemFoundHold( $itemnumber );
2274 Returns true if the item is currently on hold
2275 and that hold has a non-null found status ( W, T, etc. )
2279 sub IsItemOnHoldAndFound {
2280 my ($itemnumber) = @_;
2282 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2284 my $found = $rs->count(
2286 itemnumber => $itemnumber,
2287 found => { '!=' => undef }
2294 =head2 GetMaxPatronHoldsForRecord
2296 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2298 For multiple holds on a given record for a given patron, the max
2299 number of record level holds that a patron can be placed is the highest
2300 value of the holds_per_record rule for each item if the record for that
2301 patron. This subroutine finds and returns the highest holds_per_record
2302 rule value for a given patron id and record id.
2306 sub GetMaxPatronHoldsForRecord {
2307 my ( $borrowernumber, $biblionumber ) = @_;
2309 my $patron = Koha::Patrons->find($borrowernumber);
2310 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2312 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2314 my $categorycode = $patron->categorycode;
2316 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2319 foreach my $item (@items) {
2320 my $itemtype = $item->effective_itemtype();
2322 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2324 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2325 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2326 $max = $holds_per_record if $holds_per_record > $max;
2334 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2336 Returns the matching hold related issuingrule fields for a given
2337 patron category, itemtype, and library.
2342 my ( $categorycode, $itemtype, $branchcode ) = @_;
2344 my $dbh = C4::Context->dbh;
2346 my $sth = $dbh->prepare(
2348 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2350 WHERE (categorycode in (?,'*') )
2351 AND (itemtype IN (?,'*'))
2352 AND (branchcode IN (?,'*'))
2353 ORDER BY categorycode DESC,
2359 $sth->execute( $categorycode, $itemtype, $branchcode );
2361 return $sth->fetchrow_hashref();
2366 Koha Development Team <http://koha-community.org/>