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
116 &ModReserveMinusPriority
122 &CanReserveBeCanceledFromOpac
123 &CancelExpiredReserves
125 &AutoUnsuspendReserves
127 &IsAvailableForItemLevelRequest
130 &ToggleLowestPriority
136 &GetReservesControlBranch
140 GetMaxPatronHoldsForRecord
142 @EXPORT_OK = qw( MergeHolds );
147 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
149 Adds reserve and generates HOLDPLACED message.
151 The following tables are available witin the HOLDPLACED message:
164 $branch, $borrowernumber, $biblionumber, $bibitems,
165 $priority, $resdate, $expdate, $notes,
166 $title, $checkitem, $found, $itemtype
169 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
170 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
172 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
174 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
176 # Make room in reserves for this before those of a later reserve date
177 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
182 # If the reserv had the waiting status, we had the value of the resdate
183 if ( $found eq 'W' ) {
184 $waitingdate = $resdate;
187 # Don't add itemtype limit if specific item is selected
188 $itemtype = undef if $checkitem;
190 # updates take place here
191 my $hold = Koha::Hold->new(
193 borrowernumber => $borrowernumber,
194 biblionumber => $biblionumber,
195 reservedate => $resdate,
196 branchcode => $branch,
197 priority => $priority,
198 reservenotes => $notes,
199 itemnumber => $checkitem,
201 waitingdate => $waitingdate,
202 expirationdate => $expdate,
203 itemtype => $itemtype,
207 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
208 if C4::Context->preference('HoldsLog');
210 my $reserve_id = $hold->id();
212 # add a reserve fee if needed
213 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
214 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
215 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
218 _FixPriority({ biblionumber => $biblionumber});
220 # Send e-mail to librarian if syspref is active
221 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
222 my $patron = Koha::Patrons->find( $borrowernumber );
223 my $library = $patron->library;
224 if ( my $letter = C4::Letters::GetPreparedLetter (
225 module => 'reserves',
226 letter_code => 'HOLDPLACED',
227 branchcode => $branch,
228 lang => $patron->lang,
230 'branches' => $library->unblessed,
231 'borrowers' => $patron->unblessed,
232 'biblio' => $biblionumber,
233 'biblioitems' => $biblionumber,
234 'items' => $checkitem,
235 'reserves' => $hold->unblessed,
239 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
241 C4::Letters::EnqueueLetter(
243 borrowernumber => $borrowernumber,
244 message_transport_type => 'email',
245 from_address => $admin_email_address,
246 to_address => $admin_email_address,
255 =head2 CanBookBeReserved
257 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
258 if ($canReserve eq 'OK') { #We can reserve this Item! }
260 See CanItemBeReserved() for possible return values.
264 sub CanBookBeReserved{
265 my ($borrowernumber, $biblionumber) = @_;
267 my $items = GetItemnumbersForBiblio($biblionumber);
268 #get items linked via host records
269 my @hostitems = get_hostitemnumbers_of($biblionumber);
271 push (@$items,@hostitems);
275 foreach my $item (@$items) {
276 $canReserve = CanItemBeReserved( $borrowernumber, $item );
277 return 'OK' if $canReserve eq 'OK';
282 =head2 CanItemBeReserved
284 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
285 if ($canReserve eq 'OK') { #We can reserve this Item! }
287 @RETURNS OK, if the Item can be reserved.
288 ageRestricted, if the Item is age restricted for this borrower.
289 damaged, if the Item is damaged.
290 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
291 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
292 notReservable, if holds on this item are not allowed
296 sub CanItemBeReserved {
297 my ( $borrowernumber, $itemnumber ) = @_;
299 my $dbh = C4::Context->dbh;
300 my $ruleitemtype; # itemtype of the matching issuing rule
301 my $allowedreserves = 0; # Total number of holds allowed across all records
302 my $holds_per_record = 1; # Total number of holds allowed for this one given record
304 # we retrieve borrowers and items informations #
305 # item->{itype} will come for biblioitems if necessery
306 my $item = GetItem($itemnumber);
307 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
308 my $patron = Koha::Patrons->find( $borrowernumber );
309 my $borrower = $patron->unblessed;
311 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
313 if ( $item->{damaged}
314 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
316 # Check for the age restriction
317 my ( $ageRestriction, $daysToAgeRestriction ) =
318 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
319 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
321 # Check that the patron doesn't have an item level hold on this item already
322 return 'itemAlreadyOnHold'
323 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
325 my $controlbranch = C4::Context->preference('ReservesControlBranch');
328 SELECT count(*) AS count
330 LEFT JOIN items USING (itemnumber)
331 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
332 LEFT JOIN borrowers USING (borrowernumber)
333 WHERE borrowernumber = ?
337 my $branchfield = "reserves.branchcode";
339 if ( $controlbranch eq "ItemHomeLibrary" ) {
340 $branchfield = "items.homebranch";
341 $branchcode = $item->{homebranch};
343 elsif ( $controlbranch eq "PatronLibrary" ) {
344 $branchfield = "borrowers.branchcode";
345 $branchcode = $borrower->{branchcode};
349 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
350 $ruleitemtype = $rights->{itemtype};
351 $allowedreserves = $rights->{reservesallowed};
352 $holds_per_record = $rights->{holds_per_record};
358 $item = Koha::Items->find( $itemnumber );
359 my $holds = Koha::Holds->search(
361 borrowernumber => $borrowernumber,
362 biblionumber => $item->biblionumber,
363 found => undef, # Found holds don't count against a patron's holds limit
366 if ( $holds->count() >= $holds_per_record ) {
367 return "tooManyHoldsForThisRecord";
372 $querycount .= "AND $branchfield = ?";
374 # If using item-level itypes, fall back to the record
375 # level itemtype if the hold has no associated item
377 C4::Context->preference('item-level_itypes')
378 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
379 : " AND biblioitems.itemtype = ?"
380 if ( $ruleitemtype ne "*" );
382 my $sthcount = $dbh->prepare($querycount);
384 if ( $ruleitemtype eq "*" ) {
385 $sthcount->execute( $borrowernumber, $branchcode );
388 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
391 my $reservecount = "0";
392 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
393 $reservecount = $rowcount->{count};
396 # we check if it's ok or not
397 if ( $reservecount >= $allowedreserves ) {
398 return 'tooManyReserves';
401 my $circ_control_branch =
402 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
404 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
406 if ( $branchitemrule->{holdallowed} == 0 ) {
407 return 'notReservable';
410 if ( $branchitemrule->{holdallowed} == 1
411 && $borrower->{branchcode} ne $item->homebranch )
413 return 'cannotReserveFromOtherBranches';
416 # If reservecount is ok, we check item branch if IndependentBranches is ON
417 # and canreservefromotherbranches is OFF
418 if ( C4::Context->preference('IndependentBranches')
419 and !C4::Context->preference('canreservefromotherbranches') )
421 my $itembranch = $item->homebranch;
422 if ( $itembranch ne $borrower->{branchcode} ) {
423 return 'cannotReserveFromOtherBranches';
430 =head2 CanReserveBeCanceledFromOpac
432 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
434 returns 1 if reserve can be cancelled by user from OPAC.
435 First check if reserve belongs to user, next checks if reserve is not in
436 transfer or waiting status
440 sub CanReserveBeCanceledFromOpac {
441 my ($reserve_id, $borrowernumber) = @_;
443 return unless $reserve_id and $borrowernumber;
444 my $reserve = Koha::Holds->find($reserve_id);
446 return 0 unless $reserve->borrowernumber == $borrowernumber;
447 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
453 =head2 GetOtherReserves
455 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
457 Check queued list of this document and check if this document must be transferred
461 sub GetOtherReserves {
462 my ($itemnumber) = @_;
465 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
466 if ($checkreserves) {
467 my $iteminfo = GetItem($itemnumber);
468 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
469 $messages->{'transfert'} = $checkreserves->{'branchcode'};
470 #minus priorities of others reservs
471 ModReserveMinusPriority(
473 $checkreserves->{'reserve_id'},
476 #launch the subroutine dotransfer
477 C4::Items::ModItemTransfer(
479 $iteminfo->{'holdingbranch'},
480 $checkreserves->{'branchcode'}
485 #step 2b : case of a reservation on the same branch, set the waiting status
487 $messages->{'waiting'} = 1;
488 ModReserveMinusPriority(
490 $checkreserves->{'reserve_id'},
492 ModReserveStatus($itemnumber,'W');
495 $nextreservinfo = $checkreserves->{'borrowernumber'};
498 return ( $messages, $nextreservinfo );
501 =head2 ChargeReserveFee
503 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
505 Charge the fee for a reserve (if $fee > 0)
509 sub ChargeReserveFee {
510 my ( $borrowernumber, $fee, $title ) = @_;
511 return if !$fee || $fee==0; # the last test is needed to include 0.00
513 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
515 my $dbh = C4::Context->dbh;
516 my $nextacctno = &getnextacctno( $borrowernumber );
517 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
522 $fee = GetReserveFee( $borrowernumber, $biblionumber );
524 Calculate the fee for a reserve (if applicable).
529 my ( $borrowernumber, $biblionumber ) = @_;
531 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
534 SELECT COUNT(*) FROM items
535 LEFT JOIN issues USING (itemnumber)
536 WHERE items.biblionumber=? AND issues.issue_id IS NULL
539 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
542 my $dbh = C4::Context->dbh;
543 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
544 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
545 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
546 # This is a reconstruction of the old code:
547 # Compare number of items with items issued, and optionally check holds
548 # If not all items are issued and there are no holds: charge no fee
549 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
550 my ( $notissued, $reserved );
551 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
554 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
555 ( $biblionumber, $borrowernumber ) );
556 $fee = 0 if $reserved == 0;
562 =head2 GetReserveStatus
564 $reservestatus = GetReserveStatus($itemnumber);
566 Takes an itemnumber and returns the status of the reserve placed on it.
567 If several reserves exist, the reserve with the lower priority is given.
571 ## FIXME: I don't think this does what it thinks it does.
572 ## It only ever checks the first reserve result, even though
573 ## multiple reserves for that bib can have the itemnumber set
574 ## the sub is only used once in the codebase.
575 sub GetReserveStatus {
576 my ($itemnumber) = @_;
578 my $dbh = C4::Context->dbh;
580 my ($sth, $found, $priority);
582 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
583 $sth->execute($itemnumber);
584 ($found, $priority) = $sth->fetchrow_array;
588 return 'Waiting' if $found eq 'W' and $priority == 0;
589 return 'Finished' if $found eq 'F';
592 return 'Reserved' if $priority > 0;
594 return ''; # empty string here will remove need for checking undef, or less log lines
599 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
600 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
601 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
603 Find a book in the reserves.
605 C<$itemnumber> is the book's item number.
606 C<$lookahead> is the number of days to look in advance for future reserves.
608 As I understand it, C<&CheckReserves> looks for the given item in the
609 reserves. If it is found, that's a match, and C<$status> is set to
612 Otherwise, it finds the most important item in the reserves with the
613 same biblio number as this book (I'm not clear on this) and returns it
614 with C<$status> set to C<Reserved>.
616 C<&CheckReserves> returns a two-element list:
618 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
620 C<$reserve> is the reserve item that matched. It is a
621 reference-to-hash whose keys are mostly the fields of the reserves
622 table in the Koha database.
627 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
628 my $dbh = C4::Context->dbh;
631 if (C4::Context->preference('item-level_itypes')){
633 SELECT items.biblionumber,
634 items.biblioitemnumber,
635 itemtypes.notforloan,
636 items.notforloan AS itemnotforloan,
642 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
643 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
648 SELECT items.biblionumber,
649 items.biblioitemnumber,
650 itemtypes.notforloan,
651 items.notforloan AS itemnotforloan,
657 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
658 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
663 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
664 $sth->execute($item);
667 $sth = $dbh->prepare("$select WHERE barcode = ?");
668 $sth->execute($barcode);
670 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
671 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
673 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
675 return unless $itemnumber; # bail if we got nothing.
677 # if item is not for loan it cannot be reserved either.....
678 # except where items.notforloan < 0 : This indicates the item is holdable.
679 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
681 # Find this item in the reserves
682 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
684 # $priority and $highest are used to find the most important item
685 # in the list returned by &_Findgroupreserve. (The lower $priority,
686 # the more important the item.)
687 # $highest is the most important item we've seen so far.
689 if (scalar @reserves) {
690 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
691 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
692 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
694 my $priority = 10000000;
695 foreach my $res (@reserves) {
696 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
697 if ($res->{'found'} eq 'W') {
698 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
700 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
705 my $local_hold_match;
707 if ($LocalHoldsPriority) {
708 $patron = Koha::Patrons->find( $res->{borrowernumber} );
709 $iteminfo = C4::Items::GetItem($itemnumber);
711 my $local_holds_priority_item_branchcode =
712 $iteminfo->{$LocalHoldsPriorityItemControl};
713 my $local_holds_priority_patron_branchcode =
714 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
716 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
717 ? $patron->branchcode
720 $local_holds_priority_item_branchcode eq
721 $local_holds_priority_patron_branchcode;
724 # See if this item is more important than what we've got so far
725 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
726 $iteminfo ||= C4::Items::GetItem($itemnumber);
727 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
728 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
729 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
730 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
731 next if ($branchitemrule->{'holdallowed'} == 0);
732 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
733 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
734 $priority = $res->{'priority'};
736 last if $local_hold_match;
742 # If we get this far, then no exact match was found.
743 # We return the most important (i.e. next) reservation.
745 $highest->{'itemnumber'} = $item;
746 return ( "Reserved", $highest, \@reserves );
752 =head2 CancelExpiredReserves
754 CancelExpiredReserves();
756 Cancels all reserves with an expiration date from before today.
760 sub CancelExpiredReserves {
761 my $today = dt_from_string();
762 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
763 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
765 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
766 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
767 $params->{found} = undef unless $expireWaiting;
769 # FIXME To move to Koha::Holds->search_expired (?)
770 my $holds = Koha::Holds->search( $params );
772 while ( my $hold = $holds->next ) {
773 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
775 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
777 my $cancel_params = {};
778 if ( $hold->found eq 'W' ) {
779 $cancel_params->{charge_cancel_fee} = 1;
781 $hold->cancel( $cancel_params );
785 =head2 AutoUnsuspendReserves
787 AutoUnsuspendReserves();
789 Unsuspends all suspended reserves with a suspend_until date from before today.
793 sub AutoUnsuspendReserves {
794 my $today = dt_from_string();
796 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
798 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
803 ModReserve({ rank => $rank,
804 reserve_id => $reserve_id,
805 branchcode => $branchcode
806 [, itemnumber => $itemnumber ]
807 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
810 Change a hold request's priority or cancel it.
812 C<$rank> specifies the effect of the change. If C<$rank>
813 is 'W' or 'n', nothing happens. This corresponds to leaving a
814 request alone when changing its priority in the holds queue
817 If C<$rank> is 'del', the hold request is cancelled.
819 If C<$rank> is an integer greater than zero, the priority of
820 the request is set to that value. Since priority != 0 means
821 that the item is not waiting on the hold shelf, setting the
822 priority to a non-zero value also sets the request's found
823 status and waiting date to NULL.
825 The optional C<$itemnumber> parameter is used only when
826 C<$rank> is a non-zero integer; if supplied, the itemnumber
827 of the hold request is set accordingly; if omitted, the itemnumber
830 B<FIXME:> Note that the forgoing can have the effect of causing
831 item-level hold requests to turn into title-level requests. This
832 will be fixed once reserves has separate columns for requested
833 itemnumber and supplying itemnumber.
840 my $rank = $params->{'rank'};
841 my $reserve_id = $params->{'reserve_id'};
842 my $branchcode = $params->{'branchcode'};
843 my $itemnumber = $params->{'itemnumber'};
844 my $suspend_until = $params->{'suspend_until'};
845 my $borrowernumber = $params->{'borrowernumber'};
846 my $biblionumber = $params->{'biblionumber'};
848 return if $rank eq "W";
849 return if $rank eq "n";
851 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
854 unless ( $reserve_id ) {
855 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
856 return unless $holds->count; # FIXME Should raise an exception
857 $hold = $holds->next;
858 $reserve_id = $hold->reserve_id;
861 $hold ||= Koha::Holds->find($reserve_id);
863 if ( $rank eq "del" ) {
866 elsif ($rank =~ /^\d+/ and $rank > 0) {
867 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
868 if C4::Context->preference('HoldsLog');
873 branchcode => $branchcode,
874 itemnumber => $itemnumber,
880 if ( defined( $suspend_until ) ) {
881 if ( $suspend_until ) {
882 $suspend_until = eval { dt_from_string( $suspend_until ) };
883 $hold->suspend_hold( $suspend_until );
885 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
886 # If the hold is not suspended, this does nothing.
887 $hold->set( { suspend_until => undef } )->store();
891 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
895 =head2 ModReserveFill
897 &ModReserveFill($reserve);
899 Fill a reserve. If I understand this correctly, this means that the
900 reserved book has been found and given to the patron who reserved it.
902 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
903 whose keys are fields from the reserves table in the Koha database.
909 my $reserve_id = $res->{'reserve_id'};
911 my $hold = Koha::Holds->find($reserve_id);
913 # get the priority on this record....
914 my $priority = $hold->priority;
916 # update the hold statuses, no need to store it though, we will be deleting it anyway
924 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
925 Koha::Old::Hold->new( $hold->unblessed() )->store();
929 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
930 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
931 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
934 # now fix the priority on the others (if the priority wasn't
935 # already sorted!)....
936 unless ( $priority == 0 ) {
937 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
941 =head2 ModReserveStatus
943 &ModReserveStatus($itemnumber, $newstatus);
945 Update the reserve status for the active (priority=0) reserve.
947 $itemnumber is the itemnumber the reserve is on
949 $newstatus is the new status.
953 sub ModReserveStatus {
955 #first : check if we have a reservation for this item .
956 my ($itemnumber, $newstatus) = @_;
957 my $dbh = C4::Context->dbh;
959 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
960 my $sth_set = $dbh->prepare($query);
961 $sth_set->execute( $newstatus, $itemnumber );
963 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
964 CartToShelf( $itemnumber );
968 =head2 ModReserveAffect
970 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
972 This function affect an item and a status for a given reserve, either fetched directly
973 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
974 is given, only first reserve returned is affected, which is ok for anything but
977 if $transferToDo is not set, then the status is set to "Waiting" as well.
978 otherwise, a transfer is on the way, and the end of the transfer will
979 take care of the waiting status
983 sub ModReserveAffect {
984 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
985 my $dbh = C4::Context->dbh;
987 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
988 # attached to $itemnumber
989 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
990 $sth->execute($itemnumber);
991 my ($biblionumber) = $sth->fetchrow;
993 # get request - need to find out if item is already
994 # waiting in order to not send duplicate hold filled notifications
997 # Find hold by id if we have it
998 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
999 # Find item level hold for this item if there is one
1000 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1001 # Find record level hold if there is no item level hold
1002 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1004 return unless $hold;
1006 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1008 $hold->itemnumber($itemnumber);
1009 $hold->set_waiting($transferToDo);
1011 _koha_notify_reserve( $hold->reserve_id )
1012 if ( !$transferToDo && !$already_on_shelf );
1014 _FixPriority( { biblionumber => $biblionumber } );
1016 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1017 CartToShelf($itemnumber);
1023 =head2 ModReserveCancelAll
1025 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1027 function to cancel reserv,check other reserves, and transfer document if it's necessary
1031 sub ModReserveCancelAll {
1034 my ( $itemnumber, $borrowernumber ) = @_;
1036 #step 1 : cancel the reservation
1037 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1038 return unless $holds->count;
1039 $holds->next->cancel;
1041 #step 2 launch the subroutine of the others reserves
1042 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1044 return ( $messages, $nextreservinfo );
1047 =head2 ModReserveMinusPriority
1049 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1051 Reduce the values of queued list
1055 sub ModReserveMinusPriority {
1056 my ( $itemnumber, $reserve_id ) = @_;
1058 #first step update the value of the first person on reserv
1059 my $dbh = C4::Context->dbh;
1062 SET priority = 0 , itemnumber = ?
1063 WHERE reserve_id = ?
1065 my $sth_upd = $dbh->prepare($query);
1066 $sth_upd->execute( $itemnumber, $reserve_id );
1067 # second step update all others reserves
1068 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1071 =head2 IsAvailableForItemLevelRequest
1073 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1075 Checks whether a given item record is available for an
1076 item-level hold request. An item is available if
1078 * it is not lost AND
1079 * it is not damaged AND
1080 * it is not withdrawn AND
1081 * a waiting or in transit reserve is placed on
1082 * does not have a not for loan value > 0
1084 Need to check the issuingrules onshelfholds column,
1085 if this is set items on the shelf can be placed on hold
1087 Note that IsAvailableForItemLevelRequest() does not
1088 check if the staff operator is authorized to place
1089 a request on the item - in particular,
1090 this routine does not check IndependentBranches
1091 and canreservefromotherbranches.
1095 sub IsAvailableForItemLevelRequest {
1097 my $borrower = shift;
1099 my $dbh = C4::Context->dbh;
1100 # must check the notforloan setting of the itemtype
1101 # FIXME - a lot of places in the code do this
1102 # or something similar - need to be
1104 my $itype = _get_itype($item);
1105 my $notforloan_per_itemtype
1106 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1110 $notforloan_per_itemtype ||
1111 $item->{itemlost} ||
1112 $item->{notforloan} > 0 ||
1113 $item->{withdrawn} ||
1114 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1116 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1118 if ( $on_shelf_holds == 1 ) {
1120 } elsif ( $on_shelf_holds == 2 ) {
1122 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1124 my $any_available = 0;
1126 foreach my $i (@items) {
1128 my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
1129 my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
1133 || $i->notforloan > 0
1136 || IsItemOnHoldAndFound( $i->id )
1138 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1139 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1140 || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
1143 return $any_available ? 0 : 1;
1146 if ($item->{onloan}) {
1150 if ( Koha::Holds->search({itemnumber => $item->{itemnumber},
1151 found => ['W', 'T']})->count ) {
1158 =head2 OnShelfHoldsAllowed
1160 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1162 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1163 holds are allowed, returns true if so.
1167 sub OnShelfHoldsAllowed {
1168 my ($item, $borrower) = @_;
1170 my $itype = _get_itype($item);
1171 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1178 if (C4::Context->preference('item-level_itypes')) {
1179 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1180 # When GetItem is fixed, we can remove this
1181 $itype = $item->{itype};
1184 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1185 # So if we already have a biblioitems join when calling this function,
1186 # we don't need to access the database again
1187 $itype = $item->{itemtype};
1190 my $dbh = C4::Context->dbh;
1191 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1192 my $sth = $dbh->prepare($query);
1193 $sth->execute($item->{biblioitemnumber});
1194 if (my $data = $sth->fetchrow_hashref()){
1195 $itype = $data->{itemtype};
1201 sub _OnShelfHoldsAllowed {
1202 my ($itype,$borrowercategory,$branchcode) = @_;
1204 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1205 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1208 =head2 AlterPriority
1210 AlterPriority( $where, $reserve_id );
1212 This function changes a reserve's priority up, down, to the top, or to the bottom.
1213 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1218 my ( $where, $reserve_id ) = @_;
1220 my $hold = Koha::Holds->find( $reserve_id );
1221 return unless $hold;
1223 if ( $hold->cancellationdate ) {
1224 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1228 if ( $where eq 'up' || $where eq 'down' ) {
1230 my $priority = $hold->priority;
1231 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1232 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1234 } elsif ( $where eq 'top' ) {
1236 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1238 } elsif ( $where eq 'bottom' ) {
1240 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1243 # FIXME Should return the new priority
1246 =head2 ToggleLowestPriority
1248 ToggleLowestPriority( $borrowernumber, $biblionumber );
1250 This function sets the lowestPriority field to true if is false, and false if it is true.
1254 sub ToggleLowestPriority {
1255 my ( $reserve_id ) = @_;
1257 my $dbh = C4::Context->dbh;
1259 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1260 $sth->execute( $reserve_id );
1262 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1265 =head2 ToggleSuspend
1267 ToggleSuspend( $reserve_id );
1269 This function sets the suspend field to true if is false, and false if it is true.
1270 If the reserve is currently suspended with a suspend_until date, that date will
1271 be cleared when it is unsuspended.
1276 my ( $reserve_id, $suspend_until ) = @_;
1278 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1280 my $hold = Koha::Holds->find( $reserve_id );
1282 if ( $hold->is_suspended ) {
1285 $hold->suspend_hold( $suspend_until );
1292 borrowernumber => $borrowernumber,
1293 [ biblionumber => $biblionumber, ]
1294 [ suspend_until => $suspend_until, ]
1295 [ suspend => $suspend ]
1298 This function accepts a set of hash keys as its parameters.
1299 It requires either borrowernumber or biblionumber, or both.
1301 suspend_until is wholly optional.
1308 my $borrowernumber = $params{'borrowernumber'} || undef;
1309 my $biblionumber = $params{'biblionumber'} || undef;
1310 my $suspend_until = $params{'suspend_until'} || undef;
1311 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1313 $suspend_until = eval { dt_from_string($suspend_until) }
1314 if ( defined($suspend_until) );
1316 return unless ( $borrowernumber || $biblionumber );
1319 $params->{found} = undef;
1320 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1321 $params->{biblionumber} = $biblionumber if $biblionumber;
1323 my @holds = Koha::Holds->search($params);
1326 map { $_->suspend_hold($suspend_until) } @holds;
1329 map { $_->resume() } @holds;
1337 reserve_id => $reserve_id,
1339 [ignoreSetLowestRank => $ignoreSetLowestRank]
1344 _FixPriority({ biblionumber => $biblionumber});
1346 This routine adjusts the priority of a hold request and holds
1349 In the first form, where a reserve_id is passed, the priority of the
1350 hold is set to supplied rank, and other holds for that bib are adjusted
1351 accordingly. If the rank is "del", the hold is cancelled. If no rank
1352 is supplied, all of the holds on that bib have their priority adjusted
1353 as if the second form had been used.
1355 In the second form, where a biblionumber is passed, the holds on that
1356 bib (that are not captured) are sorted in order of increasing priority,
1357 then have reserves.priority set so that the first non-captured hold
1358 has its priority set to 1, the second non-captured hold has its priority
1359 set to 2, and so forth.
1361 In both cases, holds that have the lowestPriority flag on are have their
1362 priority adjusted to ensure that they remain at the end of the line.
1364 Note that the ignoreSetLowestRank parameter is meant to be used only
1365 when _FixPriority calls itself.
1370 my ( $params ) = @_;
1371 my $reserve_id = $params->{reserve_id};
1372 my $rank = $params->{rank} // '';
1373 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1374 my $biblionumber = $params->{biblionumber};
1376 my $dbh = C4::Context->dbh;
1379 if ( $reserve_id ) {
1380 $hold = Koha::Holds->find( $reserve_id );
1381 return unless $hold;
1384 unless ( $biblionumber ) { # FIXME This is a very weird API
1385 $biblionumber = $hold->biblionumber;
1388 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1391 elsif ( $rank eq "W" || $rank eq "0" ) {
1393 # make sure priority for waiting or in-transit items is 0
1397 WHERE reserve_id = ?
1398 AND found IN ('W', 'T')
1400 my $sth = $dbh->prepare($query);
1401 $sth->execute( $reserve_id );
1407 SELECT reserve_id, borrowernumber, reservedate
1409 WHERE biblionumber = ?
1410 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1411 ORDER BY priority ASC
1413 my $sth = $dbh->prepare($query);
1414 $sth->execute( $biblionumber );
1415 while ( my $line = $sth->fetchrow_hashref ) {
1416 push( @priority, $line );
1419 # To find the matching index
1421 my $key = -1; # to allow for 0 to be a valid result
1422 for ( $i = 0 ; $i < @priority ; $i++ ) {
1423 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1424 $key = $i; # save the index
1429 # if index exists in array then move it to new position
1430 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1431 my $new_rank = $rank -
1432 1; # $new_rank is what you want the new index to be in the array
1433 my $moving_item = splice( @priority, $key, 1 );
1434 splice( @priority, $new_rank, 0, $moving_item );
1437 # now fix the priority on those that are left....
1441 WHERE reserve_id = ?
1443 $sth = $dbh->prepare($query);
1444 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1447 $priority[$j]->{'reserve_id'}
1451 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1454 unless ( $ignoreSetLowestRank ) {
1455 while ( my $res = $sth->fetchrow_hashref() ) {
1457 reserve_id => $res->{'reserve_id'},
1459 ignoreSetLowestRank => 1
1465 =head2 _Findgroupreserve
1467 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1469 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1470 first match found. If neither, then we look for non-holds-queue based holds.
1471 Lookahead is the number of days to look in advance.
1473 C<&_Findgroupreserve> returns :
1474 C<@results> is an array of references-to-hash whose keys are mostly
1475 fields from the reserves table of the Koha database, plus
1476 C<biblioitemnumber>.
1480 sub _Findgroupreserve {
1481 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1482 my $dbh = C4::Context->dbh;
1484 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1485 # check for exact targeted match
1486 my $item_level_target_query = qq{
1487 SELECT reserves.biblionumber AS biblionumber,
1488 reserves.borrowernumber AS borrowernumber,
1489 reserves.reservedate AS reservedate,
1490 reserves.branchcode AS branchcode,
1491 reserves.cancellationdate AS cancellationdate,
1492 reserves.found AS found,
1493 reserves.reservenotes AS reservenotes,
1494 reserves.priority AS priority,
1495 reserves.timestamp AS timestamp,
1496 biblioitems.biblioitemnumber AS biblioitemnumber,
1497 reserves.itemnumber AS itemnumber,
1498 reserves.reserve_id AS reserve_id,
1499 reserves.itemtype AS itemtype
1501 JOIN biblioitems USING (biblionumber)
1502 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1505 AND item_level_request = 1
1507 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1511 my $sth = $dbh->prepare($item_level_target_query);
1512 $sth->execute($itemnumber, $lookahead||0);
1514 if ( my $data = $sth->fetchrow_hashref ) {
1515 push( @results, $data )
1516 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1518 return @results if @results;
1520 # check for title-level targeted match
1521 my $title_level_target_query = qq{
1522 SELECT reserves.biblionumber AS biblionumber,
1523 reserves.borrowernumber AS borrowernumber,
1524 reserves.reservedate AS reservedate,
1525 reserves.branchcode AS branchcode,
1526 reserves.cancellationdate AS cancellationdate,
1527 reserves.found AS found,
1528 reserves.reservenotes AS reservenotes,
1529 reserves.priority AS priority,
1530 reserves.timestamp AS timestamp,
1531 biblioitems.biblioitemnumber AS biblioitemnumber,
1532 reserves.itemnumber AS itemnumber,
1533 reserves.reserve_id AS reserve_id,
1534 reserves.itemtype AS itemtype
1536 JOIN biblioitems USING (biblionumber)
1537 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1540 AND item_level_request = 0
1541 AND hold_fill_targets.itemnumber = ?
1542 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1546 $sth = $dbh->prepare($title_level_target_query);
1547 $sth->execute($itemnumber, $lookahead||0);
1549 if ( my $data = $sth->fetchrow_hashref ) {
1550 push( @results, $data )
1551 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1553 return @results if @results;
1556 SELECT reserves.biblionumber AS biblionumber,
1557 reserves.borrowernumber AS borrowernumber,
1558 reserves.reservedate AS reservedate,
1559 reserves.waitingdate AS waitingdate,
1560 reserves.branchcode AS branchcode,
1561 reserves.cancellationdate AS cancellationdate,
1562 reserves.found AS found,
1563 reserves.reservenotes AS reservenotes,
1564 reserves.priority AS priority,
1565 reserves.timestamp AS timestamp,
1566 reserves.itemnumber AS itemnumber,
1567 reserves.reserve_id AS reserve_id,
1568 reserves.itemtype AS itemtype
1570 WHERE reserves.biblionumber = ?
1571 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1572 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1576 $sth = $dbh->prepare($query);
1577 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1579 while ( my $data = $sth->fetchrow_hashref ) {
1580 push( @results, $data )
1581 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1586 =head2 _koha_notify_reserve
1588 _koha_notify_reserve( $hold->reserve_id );
1590 Sends a notification to the patron that their hold has been filled (through
1591 ModReserveAffect, _not_ ModReserveFill)
1593 The letter code for this notice may be found using the following query:
1595 select distinct letter_code
1596 from message_transports
1597 inner join message_attributes using (message_attribute_id)
1598 where message_name = 'Hold_Filled'
1600 This will probably sipmly be 'HOLD', but because it is defined in the database,
1601 it is subject to addition or change.
1603 The following tables are availalbe witin the notice:
1614 sub _koha_notify_reserve {
1615 my $reserve_id = shift;
1616 my $hold = Koha::Holds->find($reserve_id);
1617 my $borrowernumber = $hold->borrowernumber;
1619 my $patron = Koha::Patrons->find( $borrowernumber );
1621 # Try to get the borrower's email address
1622 my $to_address = $patron->notice_email_address;
1624 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1625 borrowernumber => $borrowernumber,
1626 message_name => 'Hold_Filled'
1629 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1631 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1633 my %letter_params = (
1634 module => 'reserves',
1635 branchcode => $hold->branchcode,
1636 lang => $patron->lang,
1638 'branches' => $library,
1639 'borrowers' => $patron->unblessed,
1640 'biblio' => $hold->biblionumber,
1641 'biblioitems' => $hold->biblionumber,
1642 'reserves' => $hold->unblessed,
1643 'items' => $hold->itemnumber,
1647 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.
1648 my $send_notification = sub {
1649 my ( $mtt, $letter_code ) = (@_);
1650 return unless defined $letter_code;
1651 $letter_params{letter_code} = $letter_code;
1652 $letter_params{message_transport_type} = $mtt;
1653 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1655 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1659 C4::Letters::EnqueueLetter( {
1661 borrowernumber => $borrowernumber,
1662 from_address => $admin_email_address,
1663 message_transport_type => $mtt,
1667 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1669 ( $mtt eq 'email' and not $to_address ) # No email address
1670 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1671 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1674 &$send_notification($mtt, $letter_code);
1675 $notification_sent++;
1677 #Making sure that a print notification is sent if no other transport types can be utilized.
1678 if (! $notification_sent) {
1679 &$send_notification('print', 'HOLD');
1684 =head2 _ShiftPriorityByDateAndPriority
1686 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1688 This increments the priority of all reserves after the one
1689 with either the lowest date after C<$reservedate>
1690 or the lowest priority after C<$priority>.
1692 It effectively makes room for a new reserve to be inserted with a certain
1693 priority, which is returned.
1695 This is most useful when the reservedate can be set by the user. It allows
1696 the new reserve to be placed before other reserves that have a later
1697 reservedate. Since priority also is set by the form in reserves/request.pl
1698 the sub accounts for that too.
1702 sub _ShiftPriorityByDateAndPriority {
1703 my ( $biblio, $resdate, $new_priority ) = @_;
1705 my $dbh = C4::Context->dbh;
1706 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1707 my $sth = $dbh->prepare( $query );
1708 $sth->execute( $biblio, $resdate, $new_priority );
1709 my $min_priority = $sth->fetchrow;
1710 # if no such matches are found, $new_priority remains as original value
1711 $new_priority = $min_priority if ( $min_priority );
1713 # Shift the priority up by one; works in conjunction with the next SQL statement
1714 $query = "UPDATE reserves
1715 SET priority = priority+1
1716 WHERE biblionumber = ?
1717 AND borrowernumber = ?
1720 my $sth_update = $dbh->prepare( $query );
1722 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1723 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1724 $sth = $dbh->prepare( $query );
1725 $sth->execute( $new_priority, $biblio );
1726 while ( my $row = $sth->fetchrow_hashref ) {
1727 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1730 return $new_priority; # so the caller knows what priority they wind up receiving
1735 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1737 Use when checking out an item to handle reserves
1738 If $cancelreserve boolean is set to true, it will remove existing reserve
1743 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1745 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1746 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1749 my $biblionumber = $res->{biblionumber};
1751 if ($res->{borrowernumber} == $borrowernumber) {
1752 ModReserveFill($res);
1756 # The item is reserved by someone else.
1757 # Find this item in the reserves
1760 foreach (@$all_reserves) {
1761 $_->{'borrowernumber'} == $borrowernumber or next;
1762 $_->{'biblionumber'} == $biblionumber or next;
1769 # The item is reserved by the current patron
1770 ModReserveFill($borr_res);
1773 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1774 RevertWaitingStatus({ itemnumber => $itemnumber });
1776 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1777 my $hold = Koha::Holds->find( $res->{reserve_id} );
1785 MergeHolds($dbh,$to_biblio, $from_biblio);
1787 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1792 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1793 my $sth = $dbh->prepare(
1794 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1796 $sth->execute($from_biblio);
1797 if ( my $data = $sth->fetchrow_hashref() ) {
1799 # holds exist on old record, if not we don't need to do anything
1800 $sth = $dbh->prepare(
1801 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1802 $sth->execute( $to_biblio, $from_biblio );
1805 # don't reorder those already waiting
1807 $sth = $dbh->prepare(
1808 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1810 my $upd_sth = $dbh->prepare(
1811 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1812 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1814 $sth->execute( $to_biblio, 'W', 'T' );
1816 while ( my $reserve = $sth->fetchrow_hashref() ) {
1818 $priority, $to_biblio,
1819 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1820 $reserve->{'itemnumber'}
1827 =head2 RevertWaitingStatus
1829 RevertWaitingStatus({ itemnumber => $itemnumber });
1831 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1833 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1834 item level hold, even if it was only a bibliolevel hold to
1835 begin with. This is because we can no longer know if a hold
1836 was item-level or bib-level after a hold has been set to
1841 sub RevertWaitingStatus {
1842 my ( $params ) = @_;
1843 my $itemnumber = $params->{'itemnumber'};
1845 return unless ( $itemnumber );
1847 my $dbh = C4::Context->dbh;
1849 ## Get the waiting reserve we want to revert
1851 SELECT * FROM reserves
1852 WHERE itemnumber = ?
1853 AND found IS NOT NULL
1855 my $sth = $dbh->prepare( $query );
1856 $sth->execute( $itemnumber );
1857 my $reserve = $sth->fetchrow_hashref();
1859 ## Increment the priority of all other non-waiting
1860 ## reserves for this bib record
1864 priority = priority + 1
1870 $sth = $dbh->prepare( $query );
1871 $sth->execute( $reserve->{'biblionumber'} );
1873 ## Fix up the currently waiting reserve
1883 $sth = $dbh->prepare( $query );
1884 $sth->execute( $reserve->{'reserve_id'} );
1885 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1890 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
1892 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1894 The letter code will be HOLD_SLIP, and the following tables are
1895 available within the slip:
1907 my ($branch, $borrowernumber, $biblionumber) = @_;
1909 # return unless ( C4::Context->boolean_preference('printreserveslips') );
1910 my $patron = Koha::Patrons->find( $borrowernumber );
1912 my $hold = Koha::Holds->search({biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next;
1913 return unless $hold;
1914 my $reserve = $hold->unblessed;
1916 return C4::Letters::GetPreparedLetter (
1917 module => 'circulation',
1918 letter_code => 'HOLD_SLIP',
1919 branchcode => $branch,
1920 lang => $patron->lang,
1922 'reserves' => $reserve,
1923 'branches' => $reserve->{branchcode},
1924 'borrowers' => $reserve->{borrowernumber},
1925 'biblio' => $reserve->{biblionumber},
1926 'biblioitems' => $reserve->{biblionumber},
1927 'items' => $reserve->{itemnumber},
1932 =head2 GetReservesControlBranch
1934 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
1936 Return the branchcode to be used to determine which reserves
1937 policy applies to a transaction.
1939 C<$item> is a hashref for an item. Only 'homebranch' is used.
1941 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
1945 sub GetReservesControlBranch {
1946 my ( $item, $borrower ) = @_;
1948 my $reserves_control = C4::Context->preference('ReservesControlBranch');
1951 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
1952 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
1958 =head2 CalculatePriority
1960 my $p = CalculatePriority($biblionumber, $resdate);
1962 Calculate priority for a new reserve on biblionumber, placing it at
1963 the end of the line of all holds whose start date falls before
1964 the current system time and that are neither on the hold shelf
1967 The reserve date parameter is optional; if it is supplied, the
1968 priority is based on the set of holds whose start date falls before
1969 the parameter value.
1971 After calculation of this priority, it is recommended to call
1972 _ShiftPriorityByDateAndPriority. Note that this is currently done in
1977 sub CalculatePriority {
1978 my ( $biblionumber, $resdate ) = @_;
1981 SELECT COUNT(*) FROM reserves
1982 WHERE biblionumber = ?
1984 AND (found IS NULL OR found = '')
1986 #skip found==W or found==T (waiting or transit holds)
1988 $sql.= ' AND ( reservedate <= ? )';
1991 $sql.= ' AND ( reservedate < NOW() )';
1993 my $dbh = C4::Context->dbh();
1994 my @row = $dbh->selectrow_array(
1997 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2000 return @row ? $row[0]+1 : 1;
2003 =head2 IsItemOnHoldAndFound
2005 my $bool = IsItemFoundHold( $itemnumber );
2007 Returns true if the item is currently on hold
2008 and that hold has a non-null found status ( W, T, etc. )
2012 sub IsItemOnHoldAndFound {
2013 my ($itemnumber) = @_;
2015 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2017 my $found = $rs->count(
2019 itemnumber => $itemnumber,
2020 found => { '!=' => undef }
2027 =head2 GetMaxPatronHoldsForRecord
2029 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2031 For multiple holds on a given record for a given patron, the max
2032 number of record level holds that a patron can be placed is the highest
2033 value of the holds_per_record rule for each item if the record for that
2034 patron. This subroutine finds and returns the highest holds_per_record
2035 rule value for a given patron id and record id.
2039 sub GetMaxPatronHoldsForRecord {
2040 my ( $borrowernumber, $biblionumber ) = @_;
2042 my $patron = Koha::Patrons->find($borrowernumber);
2043 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2045 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2047 my $categorycode = $patron->categorycode;
2049 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2052 foreach my $item (@items) {
2053 my $itemtype = $item->effective_itemtype();
2055 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2057 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2058 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2059 $max = $holds_per_record if $holds_per_record > $max;
2067 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2069 Returns the matching hold related issuingrule fields for a given
2070 patron category, itemtype, and library.
2075 my ( $categorycode, $itemtype, $branchcode ) = @_;
2077 my $dbh = C4::Context->dbh;
2079 my $sth = $dbh->prepare(
2081 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2083 WHERE (categorycode in (?,'*') )
2084 AND (itemtype IN (?,'*'))
2085 AND (branchcode IN (?,'*'))
2086 ORDER BY categorycode DESC,
2092 $sth->execute( $categorycode, $itemtype, $branchcode );
2094 return $sth->fetchrow_hashref();
2099 Koha Development Team <http://koha-community.org/>