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
107 &GetReservesForBranch
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
130 &OPACItemHoldsAllowed
133 &ToggleLowestPriority
139 &GetReservesControlBranch
143 GetMaxPatronHoldsForRecord
145 @EXPORT_OK = qw( MergeHolds );
150 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
152 Adds reserve and generates HOLDPLACED message.
154 The following tables are available witin the HOLDPLACED message:
167 $branch, $borrowernumber, $biblionumber, $bibitems,
168 $priority, $resdate, $expdate, $notes,
169 $title, $checkitem, $found, $itemtype
172 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
173 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
175 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
177 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
179 # Make room in reserves for this before those of a later reserve date
180 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
185 # If the reserv had the waiting status, we had the value of the resdate
186 if ( $found eq 'W' ) {
187 $waitingdate = $resdate;
190 # Don't add itemtype limit if specific item is selected
191 $itemtype = undef if $checkitem;
193 # updates take place here
194 my $hold = Koha::Hold->new(
196 borrowernumber => $borrowernumber,
197 biblionumber => $biblionumber,
198 reservedate => $resdate,
199 branchcode => $branch,
200 priority => $priority,
201 reservenotes => $notes,
202 itemnumber => $checkitem,
204 waitingdate => $waitingdate,
205 expirationdate => $expdate,
206 itemtype => $itemtype,
210 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
211 if C4::Context->preference('HoldsLog');
213 my $reserve_id = $hold->id();
215 # add a reserve fee if needed
216 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
217 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
218 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
221 _FixPriority({ biblionumber => $biblionumber});
223 # Send e-mail to librarian if syspref is active
224 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
225 my $patron = Koha::Patrons->find( $borrowernumber );
226 my $library = $patron->library;
227 if ( my $letter = C4::Letters::GetPreparedLetter (
228 module => 'reserves',
229 letter_code => 'HOLDPLACED',
230 branchcode => $branch,
231 lang => $patron->lang,
233 'branches' => $library->unblessed,
234 'borrowers' => $patron->unblessed,
235 'biblio' => $biblionumber,
236 'biblioitems' => $biblionumber,
237 'items' => $checkitem,
238 'reserves' => $hold->unblessed,
242 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
244 C4::Letters::EnqueueLetter(
246 borrowernumber => $borrowernumber,
247 message_transport_type => 'email',
248 from_address => $admin_email_address,
249 to_address => $admin_email_address,
258 =head2 CanBookBeReserved
260 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
261 if ($canReserve eq 'OK') { #We can reserve this Item! }
263 See CanItemBeReserved() for possible return values.
267 sub CanBookBeReserved{
268 my ($borrowernumber, $biblionumber) = @_;
270 my $items = GetItemnumbersForBiblio($biblionumber);
271 #get items linked via host records
272 my @hostitems = get_hostitemnumbers_of($biblionumber);
274 push (@$items,@hostitems);
278 foreach my $item (@$items) {
279 $canReserve = CanItemBeReserved( $borrowernumber, $item );
280 return 'OK' if $canReserve eq 'OK';
285 =head2 CanItemBeReserved
287 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
288 if ($canReserve eq 'OK') { #We can reserve this Item! }
290 @RETURNS OK, if the Item can be reserved.
291 ageRestricted, if the Item is age restricted for this borrower.
292 damaged, if the Item is damaged.
293 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
294 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
295 notReservable, if holds on this item are not allowed
299 sub CanItemBeReserved {
300 my ( $borrowernumber, $itemnumber ) = @_;
302 my $dbh = C4::Context->dbh;
303 my $ruleitemtype; # itemtype of the matching issuing rule
304 my $allowedreserves = 0; # Total number of holds allowed across all records
305 my $holds_per_record = 1; # Total number of holds allowed for this one given record
307 # we retrieve borrowers and items informations #
308 # item->{itype} will come for biblioitems if necessery
309 my $item = GetItem($itemnumber);
310 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
311 my $patron = Koha::Patrons->find( $borrowernumber );
312 my $borrower = $patron->unblessed;
314 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
316 if ( $item->{damaged}
317 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
319 # Check for the age restriction
320 my ( $ageRestriction, $daysToAgeRestriction ) =
321 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
322 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
324 # Check that the patron doesn't have an item level hold on this item already
325 return 'itemAlreadyOnHold'
326 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
328 my $controlbranch = C4::Context->preference('ReservesControlBranch');
331 SELECT count(*) AS count
333 LEFT JOIN items USING (itemnumber)
334 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
335 LEFT JOIN borrowers USING (borrowernumber)
336 WHERE borrowernumber = ?
340 my $branchfield = "reserves.branchcode";
342 if ( $controlbranch eq "ItemHomeLibrary" ) {
343 $branchfield = "items.homebranch";
344 $branchcode = $item->{homebranch};
346 elsif ( $controlbranch eq "PatronLibrary" ) {
347 $branchfield = "borrowers.branchcode";
348 $branchcode = $borrower->{branchcode};
352 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
353 $ruleitemtype = $rights->{itemtype};
354 $allowedreserves = $rights->{reservesallowed};
355 $holds_per_record = $rights->{holds_per_record};
361 $item = Koha::Items->find( $itemnumber );
362 my $holds = Koha::Holds->search(
364 borrowernumber => $borrowernumber,
365 biblionumber => $item->biblionumber,
366 found => undef, # Found holds don't count against a patron's holds limit
369 if ( $holds->count() >= $holds_per_record ) {
370 return "tooManyHoldsForThisRecord";
375 $querycount .= "AND $branchfield = ?";
377 # If using item-level itypes, fall back to the record
378 # level itemtype if the hold has no associated item
380 C4::Context->preference('item-level_itypes')
381 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
382 : " AND biblioitems.itemtype = ?"
383 if ( $ruleitemtype ne "*" );
385 my $sthcount = $dbh->prepare($querycount);
387 if ( $ruleitemtype eq "*" ) {
388 $sthcount->execute( $borrowernumber, $branchcode );
391 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
394 my $reservecount = "0";
395 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
396 $reservecount = $rowcount->{count};
399 # we check if it's ok or not
400 if ( $reservecount >= $allowedreserves ) {
401 return 'tooManyReserves';
404 my $circ_control_branch =
405 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
407 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
409 if ( $branchitemrule->{holdallowed} == 0 ) {
410 return 'notReservable';
413 if ( $branchitemrule->{holdallowed} == 1
414 && $borrower->{branchcode} ne $item->homebranch )
416 return 'cannotReserveFromOtherBranches';
419 # If reservecount is ok, we check item branch if IndependentBranches is ON
420 # and canreservefromotherbranches is OFF
421 if ( C4::Context->preference('IndependentBranches')
422 and !C4::Context->preference('canreservefromotherbranches') )
424 my $itembranch = $item->homebranch;
425 if ( $itembranch ne $borrower->{branchcode} ) {
426 return 'cannotReserveFromOtherBranches';
433 =head2 CanReserveBeCanceledFromOpac
435 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
437 returns 1 if reserve can be cancelled by user from OPAC.
438 First check if reserve belongs to user, next checks if reserve is not in
439 transfer or waiting status
443 sub CanReserveBeCanceledFromOpac {
444 my ($reserve_id, $borrowernumber) = @_;
446 return unless $reserve_id and $borrowernumber;
447 my $reserve = Koha::Holds->find($reserve_id);
449 return 0 unless $reserve->borrowernumber == $borrowernumber;
450 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
456 =head2 GetOtherReserves
458 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
460 Check queued list of this document and check if this document must be transferred
464 sub GetOtherReserves {
465 my ($itemnumber) = @_;
468 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
469 if ($checkreserves) {
470 my $iteminfo = GetItem($itemnumber);
471 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
472 $messages->{'transfert'} = $checkreserves->{'branchcode'};
473 #minus priorities of others reservs
474 ModReserveMinusPriority(
476 $checkreserves->{'reserve_id'},
479 #launch the subroutine dotransfer
480 C4::Items::ModItemTransfer(
482 $iteminfo->{'holdingbranch'},
483 $checkreserves->{'branchcode'}
488 #step 2b : case of a reservation on the same branch, set the waiting status
490 $messages->{'waiting'} = 1;
491 ModReserveMinusPriority(
493 $checkreserves->{'reserve_id'},
495 ModReserveStatus($itemnumber,'W');
498 $nextreservinfo = $checkreserves->{'borrowernumber'};
501 return ( $messages, $nextreservinfo );
504 =head2 ChargeReserveFee
506 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
508 Charge the fee for a reserve (if $fee > 0)
512 sub ChargeReserveFee {
513 my ( $borrowernumber, $fee, $title ) = @_;
514 return if !$fee || $fee==0; # the last test is needed to include 0.00
516 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
518 my $dbh = C4::Context->dbh;
519 my $nextacctno = &getnextacctno( $borrowernumber );
520 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
525 $fee = GetReserveFee( $borrowernumber, $biblionumber );
527 Calculate the fee for a reserve (if applicable).
532 my ( $borrowernumber, $biblionumber ) = @_;
534 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
537 SELECT COUNT(*) FROM items
538 LEFT JOIN issues USING (itemnumber)
539 WHERE items.biblionumber=? AND issues.issue_id IS NULL
542 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
545 my $dbh = C4::Context->dbh;
546 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
547 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
548 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
549 # This is a reconstruction of the old code:
550 # Compare number of items with items issued, and optionally check holds
551 # If not all items are issued and there are no holds: charge no fee
552 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
553 my ( $notissued, $reserved );
554 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
557 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
558 ( $biblionumber, $borrowernumber ) );
559 $fee = 0 if $reserved == 0;
565 =head2 GetReservesForBranch
567 @transreserv = GetReservesForBranch($frombranch);
571 sub GetReservesForBranch {
572 my ($frombranch) = @_;
573 my $dbh = C4::Context->dbh;
576 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
581 $query .= " AND branchcode=? " if ( $frombranch );
582 $query .= "ORDER BY waitingdate" ;
584 my $sth = $dbh->prepare($query);
586 $sth->execute($frombranch);
593 while ( my $data = $sth->fetchrow_hashref ) {
594 $transreserv[$i] = $data;
597 return (@transreserv);
600 =head2 GetReserveStatus
602 $reservestatus = GetReserveStatus($itemnumber);
604 Takes an itemnumber and returns the status of the reserve placed on it.
605 If several reserves exist, the reserve with the lower priority is given.
609 ## FIXME: I don't think this does what it thinks it does.
610 ## It only ever checks the first reserve result, even though
611 ## multiple reserves for that bib can have the itemnumber set
612 ## the sub is only used once in the codebase.
613 sub GetReserveStatus {
614 my ($itemnumber) = @_;
616 my $dbh = C4::Context->dbh;
618 my ($sth, $found, $priority);
620 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
621 $sth->execute($itemnumber);
622 ($found, $priority) = $sth->fetchrow_array;
626 return 'Waiting' if $found eq 'W' and $priority == 0;
627 return 'Finished' if $found eq 'F';
630 return 'Reserved' if $priority > 0;
632 return ''; # empty string here will remove need for checking undef, or less log lines
637 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
638 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
639 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
641 Find a book in the reserves.
643 C<$itemnumber> is the book's item number.
644 C<$lookahead> is the number of days to look in advance for future reserves.
646 As I understand it, C<&CheckReserves> looks for the given item in the
647 reserves. If it is found, that's a match, and C<$status> is set to
650 Otherwise, it finds the most important item in the reserves with the
651 same biblio number as this book (I'm not clear on this) and returns it
652 with C<$status> set to C<Reserved>.
654 C<&CheckReserves> returns a two-element list:
656 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
658 C<$reserve> is the reserve item that matched. It is a
659 reference-to-hash whose keys are mostly the fields of the reserves
660 table in the Koha database.
665 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
666 my $dbh = C4::Context->dbh;
669 if (C4::Context->preference('item-level_itypes')){
671 SELECT items.biblionumber,
672 items.biblioitemnumber,
673 itemtypes.notforloan,
674 items.notforloan AS itemnotforloan,
680 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
681 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
686 SELECT items.biblionumber,
687 items.biblioitemnumber,
688 itemtypes.notforloan,
689 items.notforloan AS itemnotforloan,
695 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
696 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
701 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
702 $sth->execute($item);
705 $sth = $dbh->prepare("$select WHERE barcode = ?");
706 $sth->execute($barcode);
708 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
709 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
711 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
713 return unless $itemnumber; # bail if we got nothing.
715 # if item is not for loan it cannot be reserved either.....
716 # except where items.notforloan < 0 : This indicates the item is holdable.
717 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
719 # Find this item in the reserves
720 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
722 # $priority and $highest are used to find the most important item
723 # in the list returned by &_Findgroupreserve. (The lower $priority,
724 # the more important the item.)
725 # $highest is the most important item we've seen so far.
727 if (scalar @reserves) {
728 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
729 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
730 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
732 my $priority = 10000000;
733 foreach my $res (@reserves) {
734 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
735 if ($res->{'found'} eq 'W') {
736 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
738 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
743 my $local_hold_match;
745 if ($LocalHoldsPriority) {
746 $patron = Koha::Patrons->find( $res->{borrowernumber} );
747 $iteminfo = C4::Items::GetItem($itemnumber);
749 my $local_holds_priority_item_branchcode =
750 $iteminfo->{$LocalHoldsPriorityItemControl};
751 my $local_holds_priority_patron_branchcode =
752 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
754 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
755 ? $patron->branchcode
758 $local_holds_priority_item_branchcode eq
759 $local_holds_priority_patron_branchcode;
762 # See if this item is more important than what we've got so far
763 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
764 $iteminfo ||= C4::Items::GetItem($itemnumber);
765 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
766 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
767 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
768 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
769 next if ($branchitemrule->{'holdallowed'} == 0);
770 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
771 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
772 $priority = $res->{'priority'};
774 last if $local_hold_match;
780 # If we get this far, then no exact match was found.
781 # We return the most important (i.e. next) reservation.
783 $highest->{'itemnumber'} = $item;
784 return ( "Reserved", $highest, \@reserves );
790 =head2 CancelExpiredReserves
792 CancelExpiredReserves();
794 Cancels all reserves with an expiration date from before today.
798 sub CancelExpiredReserves {
799 my $today = dt_from_string();
800 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
801 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
803 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
804 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
805 $params->{found} = undef unless $expireWaiting;
807 # FIXME To move to Koha::Holds->search_expired (?)
808 my $holds = Koha::Holds->search( $params );
810 while ( my $hold = $holds->next ) {
811 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
813 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
815 my $cancel_params = {};
816 if ( $hold->found eq 'W' ) {
817 $cancel_params->{charge_cancel_fee} = 1;
819 $hold->cancel( $cancel_params );
823 =head2 AutoUnsuspendReserves
825 AutoUnsuspendReserves();
827 Unsuspends all suspended reserves with a suspend_until date from before today.
831 sub AutoUnsuspendReserves {
832 my $today = dt_from_string();
834 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
836 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
841 ModReserve({ rank => $rank,
842 reserve_id => $reserve_id,
843 branchcode => $branchcode
844 [, itemnumber => $itemnumber ]
845 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
848 Change a hold request's priority or cancel it.
850 C<$rank> specifies the effect of the change. If C<$rank>
851 is 'W' or 'n', nothing happens. This corresponds to leaving a
852 request alone when changing its priority in the holds queue
855 If C<$rank> is 'del', the hold request is cancelled.
857 If C<$rank> is an integer greater than zero, the priority of
858 the request is set to that value. Since priority != 0 means
859 that the item is not waiting on the hold shelf, setting the
860 priority to a non-zero value also sets the request's found
861 status and waiting date to NULL.
863 The optional C<$itemnumber> parameter is used only when
864 C<$rank> is a non-zero integer; if supplied, the itemnumber
865 of the hold request is set accordingly; if omitted, the itemnumber
868 B<FIXME:> Note that the forgoing can have the effect of causing
869 item-level hold requests to turn into title-level requests. This
870 will be fixed once reserves has separate columns for requested
871 itemnumber and supplying itemnumber.
878 my $rank = $params->{'rank'};
879 my $reserve_id = $params->{'reserve_id'};
880 my $branchcode = $params->{'branchcode'};
881 my $itemnumber = $params->{'itemnumber'};
882 my $suspend_until = $params->{'suspend_until'};
883 my $borrowernumber = $params->{'borrowernumber'};
884 my $biblionumber = $params->{'biblionumber'};
886 return if $rank eq "W";
887 return if $rank eq "n";
889 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
892 unless ( $reserve_id ) {
893 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
894 return unless $holds->count; # FIXME Should raise an exception
895 $hold = $holds->next;
896 $reserve_id = $hold->reserve_id;
899 $hold ||= Koha::Holds->find($reserve_id);
901 if ( $rank eq "del" ) {
904 elsif ($rank =~ /^\d+/ and $rank > 0) {
905 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
906 if C4::Context->preference('HoldsLog');
911 branchcode => $branchcode,
912 itemnumber => $itemnumber,
918 if ( defined( $suspend_until ) ) {
919 if ( $suspend_until ) {
920 $suspend_until = eval { dt_from_string( $suspend_until ) };
921 $hold->suspend_hold( $suspend_until );
923 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
924 # If the hold is not suspended, this does nothing.
925 $hold->set( { suspend_until => undef } )->store();
929 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
933 =head2 ModReserveFill
935 &ModReserveFill($reserve);
937 Fill a reserve. If I understand this correctly, this means that the
938 reserved book has been found and given to the patron who reserved it.
940 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
941 whose keys are fields from the reserves table in the Koha database.
947 my $reserve_id = $res->{'reserve_id'};
949 my $hold = Koha::Holds->find($reserve_id);
951 # get the priority on this record....
952 my $priority = $hold->priority;
954 # update the hold statuses, no need to store it though, we will be deleting it anyway
962 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
963 Koha::Old::Hold->new( $hold->unblessed() )->store();
967 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
968 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
969 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
972 # now fix the priority on the others (if the priority wasn't
973 # already sorted!)....
974 unless ( $priority == 0 ) {
975 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
979 =head2 ModReserveStatus
981 &ModReserveStatus($itemnumber, $newstatus);
983 Update the reserve status for the active (priority=0) reserve.
985 $itemnumber is the itemnumber the reserve is on
987 $newstatus is the new status.
991 sub ModReserveStatus {
993 #first : check if we have a reservation for this item .
994 my ($itemnumber, $newstatus) = @_;
995 my $dbh = C4::Context->dbh;
997 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
998 my $sth_set = $dbh->prepare($query);
999 $sth_set->execute( $newstatus, $itemnumber );
1001 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1002 CartToShelf( $itemnumber );
1006 =head2 ModReserveAffect
1008 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1010 This function affect an item and a status for a given reserve, either fetched directly
1011 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1012 is given, only first reserve returned is affected, which is ok for anything but
1015 if $transferToDo is not set, then the status is set to "Waiting" as well.
1016 otherwise, a transfer is on the way, and the end of the transfer will
1017 take care of the waiting status
1021 sub ModReserveAffect {
1022 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1023 my $dbh = C4::Context->dbh;
1025 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1026 # attached to $itemnumber
1027 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1028 $sth->execute($itemnumber);
1029 my ($biblionumber) = $sth->fetchrow;
1031 # get request - need to find out if item is already
1032 # waiting in order to not send duplicate hold filled notifications
1035 # Find hold by id if we have it
1036 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1037 # Find item level hold for this item if there is one
1038 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1039 # Find record level hold if there is no item level hold
1040 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1042 return unless $hold;
1044 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1046 $hold->itemnumber($itemnumber);
1047 $hold->set_waiting($transferToDo);
1049 _koha_notify_reserve( $hold->reserve_id )
1050 if ( !$transferToDo && !$already_on_shelf );
1052 _FixPriority( { biblionumber => $biblionumber } );
1054 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1055 CartToShelf($itemnumber);
1061 =head2 ModReserveCancelAll
1063 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1065 function to cancel reserv,check other reserves, and transfer document if it's necessary
1069 sub ModReserveCancelAll {
1072 my ( $itemnumber, $borrowernumber ) = @_;
1074 #step 1 : cancel the reservation
1075 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1076 return unless $holds->count;
1077 $holds->next->cancel;
1079 #step 2 launch the subroutine of the others reserves
1080 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1082 return ( $messages, $nextreservinfo );
1085 =head2 ModReserveMinusPriority
1087 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1089 Reduce the values of queued list
1093 sub ModReserveMinusPriority {
1094 my ( $itemnumber, $reserve_id ) = @_;
1096 #first step update the value of the first person on reserv
1097 my $dbh = C4::Context->dbh;
1100 SET priority = 0 , itemnumber = ?
1101 WHERE reserve_id = ?
1103 my $sth_upd = $dbh->prepare($query);
1104 $sth_upd->execute( $itemnumber, $reserve_id );
1105 # second step update all others reserves
1106 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1109 =head2 IsAvailableForItemLevelRequest
1111 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1113 Checks whether a given item record is available for an
1114 item-level hold request. An item is available if
1116 * it is not lost AND
1117 * it is not damaged AND
1118 * it is not withdrawn AND
1119 * a waiting or in transit reserve is placed on
1120 * does not have a not for loan value > 0
1122 Need to check the issuingrules onshelfholds column,
1123 if this is set items on the shelf can be placed on hold
1125 Note that IsAvailableForItemLevelRequest() does not
1126 check if the staff operator is authorized to place
1127 a request on the item - in particular,
1128 this routine does not check IndependentBranches
1129 and canreservefromotherbranches.
1133 sub IsAvailableForItemLevelRequest {
1135 my $borrower = shift;
1137 my $dbh = C4::Context->dbh;
1138 # must check the notforloan setting of the itemtype
1139 # FIXME - a lot of places in the code do this
1140 # or something similar - need to be
1142 my $itype = _get_itype($item);
1143 my $notforloan_per_itemtype
1144 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1148 $notforloan_per_itemtype ||
1149 $item->{itemlost} ||
1150 $item->{notforloan} > 0 ||
1151 $item->{withdrawn} ||
1152 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1154 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1156 if ( $on_shelf_holds == 1 ) {
1158 } elsif ( $on_shelf_holds == 2 ) {
1160 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1162 my $any_available = 0;
1164 foreach my $i (@items) {
1166 my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
1167 my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
1171 || $i->notforloan > 0
1174 || IsItemOnHoldAndFound( $i->id )
1176 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1177 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1178 || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
1181 return $any_available ? 0 : 1;
1182 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1183 return $item->{onloan} || IsItemOnHoldAndFound( $item->{itemnumber} );
1187 =head2 OnShelfHoldsAllowed
1189 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1191 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1192 holds are allowed, returns true if so.
1196 sub OnShelfHoldsAllowed {
1197 my ($item, $borrower) = @_;
1199 my $itype = _get_itype($item);
1200 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1207 if (C4::Context->preference('item-level_itypes')) {
1208 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1209 # When GetItem is fixed, we can remove this
1210 $itype = $item->{itype};
1213 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1214 # So if we already have a biblioitems join when calling this function,
1215 # we don't need to access the database again
1216 $itype = $item->{itemtype};
1219 my $dbh = C4::Context->dbh;
1220 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1221 my $sth = $dbh->prepare($query);
1222 $sth->execute($item->{biblioitemnumber});
1223 if (my $data = $sth->fetchrow_hashref()){
1224 $itype = $data->{itemtype};
1230 sub _OnShelfHoldsAllowed {
1231 my ($itype,$borrowercategory,$branchcode) = @_;
1233 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1234 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1237 =head2 AlterPriority
1239 AlterPriority( $where, $reserve_id );
1241 This function changes a reserve's priority up, down, to the top, or to the bottom.
1242 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1247 my ( $where, $reserve_id ) = @_;
1249 my $hold = Koha::Holds->find( $reserve_id );
1250 return unless $hold;
1252 if ( $hold->cancellationdate ) {
1253 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1257 if ( $where eq 'up' || $where eq 'down' ) {
1259 my $priority = $hold->priority;
1260 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1261 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1263 } elsif ( $where eq 'top' ) {
1265 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1267 } elsif ( $where eq 'bottom' ) {
1269 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1272 # FIXME Should return the new priority
1275 =head2 ToggleLowestPriority
1277 ToggleLowestPriority( $borrowernumber, $biblionumber );
1279 This function sets the lowestPriority field to true if is false, and false if it is true.
1283 sub ToggleLowestPriority {
1284 my ( $reserve_id ) = @_;
1286 my $dbh = C4::Context->dbh;
1288 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1289 $sth->execute( $reserve_id );
1291 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1294 =head2 ToggleSuspend
1296 ToggleSuspend( $reserve_id );
1298 This function sets the suspend field to true if is false, and false if it is true.
1299 If the reserve is currently suspended with a suspend_until date, that date will
1300 be cleared when it is unsuspended.
1305 my ( $reserve_id, $suspend_until ) = @_;
1307 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1309 my $hold = Koha::Holds->find( $reserve_id );
1311 if ( $hold->is_suspended ) {
1314 $hold->suspend_hold( $suspend_until );
1321 borrowernumber => $borrowernumber,
1322 [ biblionumber => $biblionumber, ]
1323 [ suspend_until => $suspend_until, ]
1324 [ suspend => $suspend ]
1327 This function accepts a set of hash keys as its parameters.
1328 It requires either borrowernumber or biblionumber, or both.
1330 suspend_until is wholly optional.
1337 my $borrowernumber = $params{'borrowernumber'} || undef;
1338 my $biblionumber = $params{'biblionumber'} || undef;
1339 my $suspend_until = $params{'suspend_until'} || undef;
1340 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1342 $suspend_until = eval { dt_from_string($suspend_until) }
1343 if ( defined($suspend_until) );
1345 return unless ( $borrowernumber || $biblionumber );
1348 $params->{found} = undef;
1349 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1350 $params->{biblionumber} = $biblionumber if $biblionumber;
1352 my @holds = Koha::Holds->search($params);
1355 map { $_->suspend_hold($suspend_until) } @holds;
1358 map { $_->resume() } @holds;
1366 reserve_id => $reserve_id,
1368 [ignoreSetLowestRank => $ignoreSetLowestRank]
1373 _FixPriority({ biblionumber => $biblionumber});
1375 This routine adjusts the priority of a hold request and holds
1378 In the first form, where a reserve_id is passed, the priority of the
1379 hold is set to supplied rank, and other holds for that bib are adjusted
1380 accordingly. If the rank is "del", the hold is cancelled. If no rank
1381 is supplied, all of the holds on that bib have their priority adjusted
1382 as if the second form had been used.
1384 In the second form, where a biblionumber is passed, the holds on that
1385 bib (that are not captured) are sorted in order of increasing priority,
1386 then have reserves.priority set so that the first non-captured hold
1387 has its priority set to 1, the second non-captured hold has its priority
1388 set to 2, and so forth.
1390 In both cases, holds that have the lowestPriority flag on are have their
1391 priority adjusted to ensure that they remain at the end of the line.
1393 Note that the ignoreSetLowestRank parameter is meant to be used only
1394 when _FixPriority calls itself.
1399 my ( $params ) = @_;
1400 my $reserve_id = $params->{reserve_id};
1401 my $rank = $params->{rank} // '';
1402 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1403 my $biblionumber = $params->{biblionumber};
1405 my $dbh = C4::Context->dbh;
1408 if ( $reserve_id ) {
1409 $hold = Koha::Holds->find( $reserve_id );
1410 return unless $hold;
1413 unless ( $biblionumber ) { # FIXME This is a very weird API
1414 $biblionumber = $hold->biblionumber;
1417 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1420 elsif ( $rank eq "W" || $rank eq "0" ) {
1422 # make sure priority for waiting or in-transit items is 0
1426 WHERE reserve_id = ?
1427 AND found IN ('W', 'T')
1429 my $sth = $dbh->prepare($query);
1430 $sth->execute( $reserve_id );
1436 SELECT reserve_id, borrowernumber, reservedate
1438 WHERE biblionumber = ?
1439 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1440 ORDER BY priority ASC
1442 my $sth = $dbh->prepare($query);
1443 $sth->execute( $biblionumber );
1444 while ( my $line = $sth->fetchrow_hashref ) {
1445 push( @priority, $line );
1448 # To find the matching index
1450 my $key = -1; # to allow for 0 to be a valid result
1451 for ( $i = 0 ; $i < @priority ; $i++ ) {
1452 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1453 $key = $i; # save the index
1458 # if index exists in array then move it to new position
1459 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1460 my $new_rank = $rank -
1461 1; # $new_rank is what you want the new index to be in the array
1462 my $moving_item = splice( @priority, $key, 1 );
1463 splice( @priority, $new_rank, 0, $moving_item );
1466 # now fix the priority on those that are left....
1470 WHERE reserve_id = ?
1472 $sth = $dbh->prepare($query);
1473 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1476 $priority[$j]->{'reserve_id'}
1480 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1483 unless ( $ignoreSetLowestRank ) {
1484 while ( my $res = $sth->fetchrow_hashref() ) {
1486 reserve_id => $res->{'reserve_id'},
1488 ignoreSetLowestRank => 1
1494 =head2 _Findgroupreserve
1496 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1498 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1499 first match found. If neither, then we look for non-holds-queue based holds.
1500 Lookahead is the number of days to look in advance.
1502 C<&_Findgroupreserve> returns :
1503 C<@results> is an array of references-to-hash whose keys are mostly
1504 fields from the reserves table of the Koha database, plus
1505 C<biblioitemnumber>.
1509 sub _Findgroupreserve {
1510 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1511 my $dbh = C4::Context->dbh;
1513 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1514 # check for exact targeted match
1515 my $item_level_target_query = qq{
1516 SELECT reserves.biblionumber AS biblionumber,
1517 reserves.borrowernumber AS borrowernumber,
1518 reserves.reservedate AS reservedate,
1519 reserves.branchcode AS branchcode,
1520 reserves.cancellationdate AS cancellationdate,
1521 reserves.found AS found,
1522 reserves.reservenotes AS reservenotes,
1523 reserves.priority AS priority,
1524 reserves.timestamp AS timestamp,
1525 biblioitems.biblioitemnumber AS biblioitemnumber,
1526 reserves.itemnumber AS itemnumber,
1527 reserves.reserve_id AS reserve_id,
1528 reserves.itemtype AS itemtype
1530 JOIN biblioitems USING (biblionumber)
1531 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1534 AND item_level_request = 1
1536 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1540 my $sth = $dbh->prepare($item_level_target_query);
1541 $sth->execute($itemnumber, $lookahead||0);
1543 if ( my $data = $sth->fetchrow_hashref ) {
1544 push( @results, $data )
1545 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1547 return @results if @results;
1549 # check for title-level targeted match
1550 my $title_level_target_query = qq{
1551 SELECT reserves.biblionumber AS biblionumber,
1552 reserves.borrowernumber AS borrowernumber,
1553 reserves.reservedate AS reservedate,
1554 reserves.branchcode AS branchcode,
1555 reserves.cancellationdate AS cancellationdate,
1556 reserves.found AS found,
1557 reserves.reservenotes AS reservenotes,
1558 reserves.priority AS priority,
1559 reserves.timestamp AS timestamp,
1560 biblioitems.biblioitemnumber AS biblioitemnumber,
1561 reserves.itemnumber AS itemnumber,
1562 reserves.reserve_id AS reserve_id,
1563 reserves.itemtype AS itemtype
1565 JOIN biblioitems USING (biblionumber)
1566 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1569 AND item_level_request = 0
1570 AND hold_fill_targets.itemnumber = ?
1571 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1575 $sth = $dbh->prepare($title_level_target_query);
1576 $sth->execute($itemnumber, $lookahead||0);
1578 if ( my $data = $sth->fetchrow_hashref ) {
1579 push( @results, $data )
1580 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1582 return @results if @results;
1585 SELECT reserves.biblionumber AS biblionumber,
1586 reserves.borrowernumber AS borrowernumber,
1587 reserves.reservedate AS reservedate,
1588 reserves.waitingdate AS waitingdate,
1589 reserves.branchcode AS branchcode,
1590 reserves.cancellationdate AS cancellationdate,
1591 reserves.found AS found,
1592 reserves.reservenotes AS reservenotes,
1593 reserves.priority AS priority,
1594 reserves.timestamp AS timestamp,
1595 reserves.itemnumber AS itemnumber,
1596 reserves.reserve_id AS reserve_id,
1597 reserves.itemtype AS itemtype
1599 WHERE reserves.biblionumber = ?
1600 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1601 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1605 $sth = $dbh->prepare($query);
1606 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1608 while ( my $data = $sth->fetchrow_hashref ) {
1609 push( @results, $data )
1610 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1615 =head2 _koha_notify_reserve
1617 _koha_notify_reserve( $hold->reserve_id );
1619 Sends a notification to the patron that their hold has been filled (through
1620 ModReserveAffect, _not_ ModReserveFill)
1622 The letter code for this notice may be found using the following query:
1624 select distinct letter_code
1625 from message_transports
1626 inner join message_attributes using (message_attribute_id)
1627 where message_name = 'Hold_Filled'
1629 This will probably sipmly be 'HOLD', but because it is defined in the database,
1630 it is subject to addition or change.
1632 The following tables are availalbe witin the notice:
1643 sub _koha_notify_reserve {
1644 my $reserve_id = shift;
1645 my $hold = Koha::Holds->find($reserve_id);
1646 my $borrowernumber = $hold->borrowernumber;
1648 my $patron = Koha::Patrons->find( $borrowernumber );
1650 # Try to get the borrower's email address
1651 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1653 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1654 borrowernumber => $borrowernumber,
1655 message_name => 'Hold_Filled'
1658 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1660 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1662 my %letter_params = (
1663 module => 'reserves',
1664 branchcode => $hold->branchcode,
1665 lang => $patron->lang,
1667 'branches' => $library,
1668 'borrowers' => $patron->unblessed,
1669 'biblio' => $hold->biblionumber,
1670 'biblioitems' => $hold->biblionumber,
1671 'reserves' => $hold->unblessed,
1672 'items' => $hold->itemnumber,
1676 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.
1677 my $send_notification = sub {
1678 my ( $mtt, $letter_code ) = (@_);
1679 return unless defined $letter_code;
1680 $letter_params{letter_code} = $letter_code;
1681 $letter_params{message_transport_type} = $mtt;
1682 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1684 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1688 C4::Letters::EnqueueLetter( {
1690 borrowernumber => $borrowernumber,
1691 from_address => $admin_email_address,
1692 message_transport_type => $mtt,
1696 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1698 ( $mtt eq 'email' and not $to_address ) # No email address
1699 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1700 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1703 &$send_notification($mtt, $letter_code);
1704 $notification_sent++;
1706 #Making sure that a print notification is sent if no other transport types can be utilized.
1707 if (! $notification_sent) {
1708 &$send_notification('print', 'HOLD');
1713 =head2 _ShiftPriorityByDateAndPriority
1715 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1717 This increments the priority of all reserves after the one
1718 with either the lowest date after C<$reservedate>
1719 or the lowest priority after C<$priority>.
1721 It effectively makes room for a new reserve to be inserted with a certain
1722 priority, which is returned.
1724 This is most useful when the reservedate can be set by the user. It allows
1725 the new reserve to be placed before other reserves that have a later
1726 reservedate. Since priority also is set by the form in reserves/request.pl
1727 the sub accounts for that too.
1731 sub _ShiftPriorityByDateAndPriority {
1732 my ( $biblio, $resdate, $new_priority ) = @_;
1734 my $dbh = C4::Context->dbh;
1735 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1736 my $sth = $dbh->prepare( $query );
1737 $sth->execute( $biblio, $resdate, $new_priority );
1738 my $min_priority = $sth->fetchrow;
1739 # if no such matches are found, $new_priority remains as original value
1740 $new_priority = $min_priority if ( $min_priority );
1742 # Shift the priority up by one; works in conjunction with the next SQL statement
1743 $query = "UPDATE reserves
1744 SET priority = priority+1
1745 WHERE biblionumber = ?
1746 AND borrowernumber = ?
1749 my $sth_update = $dbh->prepare( $query );
1751 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1752 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1753 $sth = $dbh->prepare( $query );
1754 $sth->execute( $new_priority, $biblio );
1755 while ( my $row = $sth->fetchrow_hashref ) {
1756 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1759 return $new_priority; # so the caller knows what priority they wind up receiving
1762 =head2 OPACItemHoldsAllowed
1764 OPACItemHoldsAllowed($item_record,$borrower_record);
1766 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1767 if specific item holds are allowed, returns true if so.
1771 sub OPACItemHoldsAllowed {
1772 my ($item,$borrower) = @_;
1774 my $branchcode = $item->{homebranch} or die "No homebranch";
1776 my $dbh = C4::Context->dbh;
1777 if (C4::Context->preference('item-level_itypes')) {
1778 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1779 # When GetItem is fixed, we can remove this
1780 $itype = $item->{itype};
1783 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1784 my $sth = $dbh->prepare($query);
1785 $sth->execute($item->{biblioitemnumber});
1786 if (my $data = $sth->fetchrow_hashref()){
1787 $itype = $data->{itemtype};
1791 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1792 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1794 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1796 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1798 issuingrules.categorycode desc,
1799 issuingrules.itemtype desc,
1800 issuingrules.branchcode desc
1802 my $sth = $dbh->prepare($query);
1803 $sth->execute($borrower->{categorycode},$itype,$branchcode);
1804 my $data = $sth->fetchrow_hashref;
1805 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1806 return '' if $opacitemholds eq 'N';
1807 return $opacitemholds;
1812 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1814 Use when checking out an item to handle reserves
1815 If $cancelreserve boolean is set to true, it will remove existing reserve
1820 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1822 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1823 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1826 my $biblionumber = $res->{biblionumber};
1828 if ($res->{borrowernumber} == $borrowernumber) {
1829 ModReserveFill($res);
1833 # The item is reserved by someone else.
1834 # Find this item in the reserves
1837 foreach (@$all_reserves) {
1838 $_->{'borrowernumber'} == $borrowernumber or next;
1839 $_->{'biblionumber'} == $biblionumber or next;
1846 # The item is reserved by the current patron
1847 ModReserveFill($borr_res);
1850 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1851 RevertWaitingStatus({ itemnumber => $itemnumber });
1853 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1854 my $hold = Koha::Holds->find( $res->{reserve_id} );
1862 MergeHolds($dbh,$to_biblio, $from_biblio);
1864 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1869 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1870 my $sth = $dbh->prepare(
1871 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1873 $sth->execute($from_biblio);
1874 if ( my $data = $sth->fetchrow_hashref() ) {
1876 # holds exist on old record, if not we don't need to do anything
1877 $sth = $dbh->prepare(
1878 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1879 $sth->execute( $to_biblio, $from_biblio );
1882 # don't reorder those already waiting
1884 $sth = $dbh->prepare(
1885 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1887 my $upd_sth = $dbh->prepare(
1888 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1889 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1891 $sth->execute( $to_biblio, 'W', 'T' );
1893 while ( my $reserve = $sth->fetchrow_hashref() ) {
1895 $priority, $to_biblio,
1896 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1897 $reserve->{'itemnumber'}
1904 =head2 RevertWaitingStatus
1906 RevertWaitingStatus({ itemnumber => $itemnumber });
1908 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1910 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1911 item level hold, even if it was only a bibliolevel hold to
1912 begin with. This is because we can no longer know if a hold
1913 was item-level or bib-level after a hold has been set to
1918 sub RevertWaitingStatus {
1919 my ( $params ) = @_;
1920 my $itemnumber = $params->{'itemnumber'};
1922 return unless ( $itemnumber );
1924 my $dbh = C4::Context->dbh;
1926 ## Get the waiting reserve we want to revert
1928 SELECT * FROM reserves
1929 WHERE itemnumber = ?
1930 AND found IS NOT NULL
1932 my $sth = $dbh->prepare( $query );
1933 $sth->execute( $itemnumber );
1934 my $reserve = $sth->fetchrow_hashref();
1936 ## Increment the priority of all other non-waiting
1937 ## reserves for this bib record
1941 priority = priority + 1
1947 $sth = $dbh->prepare( $query );
1948 $sth->execute( $reserve->{'biblionumber'} );
1950 ## Fix up the currently waiting reserve
1960 $sth = $dbh->prepare( $query );
1961 $sth->execute( $reserve->{'reserve_id'} );
1962 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1969 branchcode => $branchcode,
1970 borrowernumber => $borrowernumber,
1971 biblionumber => $biblionumber,
1972 [ itemnumber => $itemnumber, ]
1973 [ barcode => $barcode, ]
1977 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1979 The letter code will be HOLD_SLIP, and the following tables are
1980 available within the slip:
1993 my $branchcode = $args->{branchcode};
1994 my $borrowernumber = $args->{borrowernumber};
1995 my $biblionumber = $args->{biblionumber};
1996 my $itemnumber = $args->{itemnumber};
1997 my $barcode = $args->{barcode};
2000 my $patron = Koha::Patrons->find($borrowernumber);
2003 if ($itemnumber || $barcode ) {
2004 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2006 $hold = Koha::Holds->search(
2008 biblionumber => $biblionumber,
2009 borrowernumber => $borrowernumber,
2010 itemnumber => $itemnumber
2015 $hold = Koha::Holds->search(
2017 biblionumber => $biblionumber,
2018 borrowernumber => $borrowernumber
2023 return unless $hold;
2024 my $reserve = $hold->unblessed;
2026 return C4::Letters::GetPreparedLetter (
2027 module => 'circulation',
2028 letter_code => 'HOLD_SLIP',
2029 branchcode => $branchcode,
2030 lang => $patron->lang,
2032 'reserves' => $reserve,
2033 'branches' => $reserve->{branchcode},
2034 'borrowers' => $reserve->{borrowernumber},
2035 'biblio' => $reserve->{biblionumber},
2036 'biblioitems' => $reserve->{biblionumber},
2037 'items' => $reserve->{itemnumber},
2042 =head2 GetReservesControlBranch
2044 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2046 Return the branchcode to be used to determine which reserves
2047 policy applies to a transaction.
2049 C<$item> is a hashref for an item. Only 'homebranch' is used.
2051 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2055 sub GetReservesControlBranch {
2056 my ( $item, $borrower ) = @_;
2058 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2061 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2062 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2068 =head2 CalculatePriority
2070 my $p = CalculatePriority($biblionumber, $resdate);
2072 Calculate priority for a new reserve on biblionumber, placing it at
2073 the end of the line of all holds whose start date falls before
2074 the current system time and that are neither on the hold shelf
2077 The reserve date parameter is optional; if it is supplied, the
2078 priority is based on the set of holds whose start date falls before
2079 the parameter value.
2081 After calculation of this priority, it is recommended to call
2082 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2087 sub CalculatePriority {
2088 my ( $biblionumber, $resdate ) = @_;
2091 SELECT COUNT(*) FROM reserves
2092 WHERE biblionumber = ?
2094 AND (found IS NULL OR found = '')
2096 #skip found==W or found==T (waiting or transit holds)
2098 $sql.= ' AND ( reservedate <= ? )';
2101 $sql.= ' AND ( reservedate < NOW() )';
2103 my $dbh = C4::Context->dbh();
2104 my @row = $dbh->selectrow_array(
2107 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2110 return @row ? $row[0]+1 : 1;
2113 =head2 IsItemOnHoldAndFound
2115 my $bool = IsItemFoundHold( $itemnumber );
2117 Returns true if the item is currently on hold
2118 and that hold has a non-null found status ( W, T, etc. )
2122 sub IsItemOnHoldAndFound {
2123 my ($itemnumber) = @_;
2125 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2127 my $found = $rs->count(
2129 itemnumber => $itemnumber,
2130 found => { '!=' => undef }
2137 =head2 GetMaxPatronHoldsForRecord
2139 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2141 For multiple holds on a given record for a given patron, the max
2142 number of record level holds that a patron can be placed is the highest
2143 value of the holds_per_record rule for each item if the record for that
2144 patron. This subroutine finds and returns the highest holds_per_record
2145 rule value for a given patron id and record id.
2149 sub GetMaxPatronHoldsForRecord {
2150 my ( $borrowernumber, $biblionumber ) = @_;
2152 my $patron = Koha::Patrons->find($borrowernumber);
2153 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2155 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2157 my $categorycode = $patron->categorycode;
2159 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2162 foreach my $item (@items) {
2163 my $itemtype = $item->effective_itemtype();
2165 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2167 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2168 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2169 $max = $holds_per_record if $holds_per_record > $max;
2177 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2179 Returns the matching hold related issuingrule fields for a given
2180 patron category, itemtype, and library.
2185 my ( $categorycode, $itemtype, $branchcode ) = @_;
2187 my $dbh = C4::Context->dbh;
2189 my $sth = $dbh->prepare(
2191 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2193 WHERE (categorycode in (?,'*') )
2194 AND (itemtype IN (?,'*'))
2195 AND (branchcode IN (?,'*'))
2196 ORDER BY categorycode DESC,
2202 $sth->execute( $categorycode, $itemtype, $branchcode );
2204 return $sth->fetchrow_hashref();
2209 Koha Development Team <http://koha-community.org/>