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
34 use C4::Members::Messaging;
36 use Koha::Account::Lines;
39 use Koha::CirculationRules;
44 use Koha::IssuingRules;
53 use List::MoreUtils qw( firstidx any );
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
59 C4::Reserves - Koha functions for dealing with reservation.
67 This modules provides somes functions to deal with reservations.
69 Reserves are stored in reserves table.
70 The following columns contains important values :
71 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
72 =0 : then the reserve is being dealed
73 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
74 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
75 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
76 F(inished) : the reserve has been completed, and is done
77 - itemnumber : empty : the reserve is still unaffected to an item
78 filled: the reserve is attached to an item
79 The complete workflow is :
80 ==== 1st use case ====
81 patron request a document, 1st available : P >0, F=NULL, I=NULL
82 a library having it run "transfertodo", and clic on the list
83 if there is no transfer to do, the reserve waiting
84 patron can pick it up P =0, F=W, I=filled
85 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
86 The pickup library receive the book, it check in P =0, F=W, I=filled
87 The patron borrow the book P =0, F=F, I=filled
89 ==== 2nd use case ====
90 patron requests a document, a given item,
91 If pickup is holding branch P =0, F=W, I=filled
92 If transfer needed, write in branchtransfer P =0, F=T, I=filled
93 The pickup library receive the book, it checks it in P =0, F=W, I=filled
94 The patron borrow the book P =0, F=F, I=filled
115 &ModReserveMinusPriority
121 &CanReserveBeCanceledFromOpac
122 &CancelExpiredReserves
124 &AutoUnsuspendReserves
126 &IsAvailableForItemLevelRequest
129 &ToggleLowestPriority
135 &GetReservesControlBranch
139 GetMaxPatronHoldsForRecord
141 @EXPORT_OK = qw( MergeHolds );
146 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
148 Adds reserve and generates HOLDPLACED message.
150 The following tables are available witin the HOLDPLACED message:
163 $branch, $borrowernumber, $biblionumber, $bibitems,
164 $priority, $resdate, $expdate, $notes,
165 $title, $checkitem, $found, $itemtype
168 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
169 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
171 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
173 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
174 # of the document, we force the value $priority and $found .
175 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
177 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
178 if ( $item->holdingbranch eq $branch ) {
183 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
185 # Make room in reserves for this before those of a later reserve date
186 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
191 # If the reserv had the waiting status, we had the value of the resdate
192 if ( $found eq 'W' ) {
193 $waitingdate = $resdate;
196 # Don't add itemtype limit if specific item is selected
197 $itemtype = undef if $checkitem;
199 # updates take place here
200 my $hold = Koha::Hold->new(
202 borrowernumber => $borrowernumber,
203 biblionumber => $biblionumber,
204 reservedate => $resdate,
205 branchcode => $branch,
206 priority => $priority,
207 reservenotes => $notes,
208 itemnumber => $checkitem,
210 waitingdate => $waitingdate,
211 expirationdate => $expdate,
212 itemtype => $itemtype,
215 $hold->set_waiting() if $found eq 'W';
217 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
218 if C4::Context->preference('HoldsLog');
220 my $reserve_id = $hold->id();
222 # add a reserve fee if needed
223 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
224 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
225 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
228 _FixPriority({ biblionumber => $biblionumber});
230 # Send e-mail to librarian if syspref is active
231 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
232 my $patron = Koha::Patrons->find( $borrowernumber );
233 my $library = $patron->library;
234 if ( my $letter = C4::Letters::GetPreparedLetter (
235 module => 'reserves',
236 letter_code => 'HOLDPLACED',
237 branchcode => $branch,
238 lang => $patron->lang,
240 'branches' => $library->unblessed,
241 'borrowers' => $patron->unblessed,
242 'biblio' => $biblionumber,
243 'biblioitems' => $biblionumber,
244 'items' => $checkitem,
245 'reserves' => $hold->unblessed,
249 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
251 C4::Letters::EnqueueLetter(
253 borrowernumber => $borrowernumber,
254 message_transport_type => 'email',
255 from_address => $admin_email_address,
256 to_address => $admin_email_address,
265 =head2 CanBookBeReserved
267 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
268 if ($canReserve eq 'OK') { #We can reserve this Item! }
270 See CanItemBeReserved() for possible return values.
274 sub CanBookBeReserved{
275 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
277 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
278 #get items linked via host records
279 my @hostitems = get_hostitemnumbers_of($biblionumber);
281 push (@itemnumbers, @hostitems);
284 my $canReserve = { status => '' };
285 foreach my $itemnumber (@itemnumbers) {
286 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
287 return { status => 'OK' } if $canReserve->{status} eq 'OK';
292 =head2 CanItemBeReserved
294 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
295 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
297 @RETURNS { status => OK }, if the Item can be reserved.
298 { status => ageRestricted }, if the Item is age restricted for this borrower.
299 { status => damaged }, if the Item is damaged.
300 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
301 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
302 { status => notReservable }, if holds on this item are not allowed
303 { status => libraryNotFound }, if given branchcode is not an existing library
304 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
305 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
309 sub CanItemBeReserved {
310 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
312 my $dbh = C4::Context->dbh;
313 my $ruleitemtype; # itemtype of the matching issuing rule
314 my $allowedreserves = 0; # Total number of holds allowed across all records
315 my $holds_per_record = 1; # Total number of holds allowed for this one given record
316 my $holds_per_day; # Default to unlimited
318 # we retrieve borrowers and items informations #
319 # item->{itype} will come for biblioitems if necessery
320 my $item = Koha::Items->find($itemnumber);
321 my $biblio = $item->biblio;
322 my $patron = Koha::Patrons->find( $borrowernumber );
323 my $borrower = $patron->unblessed;
325 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
326 return { status =>'damaged' }
328 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
330 # Check for the age restriction
331 my ( $ageRestriction, $daysToAgeRestriction ) =
332 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
333 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
335 # Check that the patron doesn't have an item level hold on this item already
336 return { status =>'itemAlreadyOnHold' }
337 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
339 my $controlbranch = C4::Context->preference('ReservesControlBranch');
342 SELECT count(*) AS count
344 LEFT JOIN items USING (itemnumber)
345 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
346 LEFT JOIN borrowers USING (borrowernumber)
347 WHERE borrowernumber = ?
351 my $branchfield = "reserves.branchcode";
353 if ( $controlbranch eq "ItemHomeLibrary" ) {
354 $branchfield = "items.homebranch";
355 $branchcode = $item->homebranch;
357 elsif ( $controlbranch eq "PatronLibrary" ) {
358 $branchfield = "borrowers.branchcode";
359 $branchcode = $borrower->{branchcode};
363 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
364 $ruleitemtype = $rights->{itemtype};
365 $allowedreserves = $rights->{reservesallowed};
366 $holds_per_record = $rights->{holds_per_record};
367 $holds_per_day = $rights->{holds_per_day};
373 my $holds = Koha::Holds->search(
375 borrowernumber => $borrowernumber,
376 biblionumber => $item->biblionumber,
377 found => undef, # Found holds don't count against a patron's holds limit
380 if ( $holds->count() >= $holds_per_record ) {
381 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
384 my $today_holds = Koha::Holds->search({
385 borrowernumber => $borrowernumber,
386 reservedate => dt_from_string->date
389 if ( defined $holds_per_day &&
390 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
391 or ( $holds_per_day == 0 ) )
393 return { status => 'tooManyReservesToday', limit => $holds_per_day };
398 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
400 # If using item-level itypes, fall back to the record
401 # level itemtype if the hold has no associated item
403 C4::Context->preference('item-level_itypes')
404 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
405 : " AND biblioitems.itemtype = ?"
406 if ( $ruleitemtype ne "*" );
408 my $sthcount = $dbh->prepare($querycount);
410 if ( $ruleitemtype eq "*" ) {
411 $sthcount->execute( $borrowernumber, $branchcode );
414 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
417 my $reservecount = "0";
418 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
419 $reservecount = $rowcount->{count};
422 # we check if it's ok or not
423 if ( $reservecount >= $allowedreserves ) {
424 return { status => 'tooManyReserves', limit => $allowedreserves };
427 # Now we need to check hold limits by patron category
428 my $rule = Koha::CirculationRules->get_effective_rule(
430 categorycode => $borrower->{categorycode},
431 branchcode => $branchcode,
432 rule_name => 'max_holds',
435 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
436 my $total_holds_count = Koha::Holds->search(
438 borrowernumber => $borrower->{borrowernumber}
442 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
445 my $circ_control_branch =
446 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
448 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
450 if ( $branchitemrule->{holdallowed} == 0 ) {
451 return { status => 'notReservable' };
454 if ( $branchitemrule->{holdallowed} == 1
455 && $borrower->{branchcode} ne $item->homebranch )
457 return { status => 'cannotReserveFromOtherBranches' };
460 # If reservecount is ok, we check item branch if IndependentBranches is ON
461 # and canreservefromotherbranches is OFF
462 if ( C4::Context->preference('IndependentBranches')
463 and !C4::Context->preference('canreservefromotherbranches') )
465 if ( $item->homebranch ne $borrower->{branchcode} ) {
466 return { status => 'cannotReserveFromOtherBranches' };
470 if ($pickup_branchcode) {
471 my $destination = Koha::Libraries->find({
472 branchcode => $pickup_branchcode,
475 unless ($destination) {
476 return { status => 'libraryNotFound' };
478 unless ($destination->pickup_location) {
479 return { status => 'libraryNotPickupLocation' };
481 unless ($item->can_be_transferred({ to => $destination })) {
482 return { status => 'cannotBeTransferred' };
486 return { status => 'OK' };
489 =head2 CanReserveBeCanceledFromOpac
491 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
493 returns 1 if reserve can be cancelled by user from OPAC.
494 First check if reserve belongs to user, next checks if reserve is not in
495 transfer or waiting status
499 sub CanReserveBeCanceledFromOpac {
500 my ($reserve_id, $borrowernumber) = @_;
502 return unless $reserve_id and $borrowernumber;
503 my $reserve = Koha::Holds->find($reserve_id);
505 return 0 unless $reserve->borrowernumber == $borrowernumber;
506 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
512 =head2 GetOtherReserves
514 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
516 Check queued list of this document and check if this document must be transferred
520 sub GetOtherReserves {
521 my ($itemnumber) = @_;
524 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
525 if ($checkreserves) {
526 my $item = Koha::Items->find($itemnumber);
527 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
528 $messages->{'transfert'} = $checkreserves->{'branchcode'};
529 #minus priorities of others reservs
530 ModReserveMinusPriority(
532 $checkreserves->{'reserve_id'},
535 #launch the subroutine dotransfer
536 C4::Items::ModItemTransfer(
538 $item->holdingbranch,
539 $checkreserves->{'branchcode'}
544 #step 2b : case of a reservation on the same branch, set the waiting status
546 $messages->{'waiting'} = 1;
547 ModReserveMinusPriority(
549 $checkreserves->{'reserve_id'},
551 ModReserveStatus($itemnumber,'W');
554 $nextreservinfo = $checkreserves->{'borrowernumber'};
557 return ( $messages, $nextreservinfo );
560 =head2 ChargeReserveFee
562 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
564 Charge the fee for a reserve (if $fee > 0)
568 sub ChargeReserveFee {
569 my ( $borrowernumber, $fee, $title ) = @_;
570 return if !$fee || $fee == 0; # the last test is needed to include 0.00
571 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
574 description => $title,
576 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
577 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
578 interface => C4::Context->interface,
580 invoice_type => undef,
589 $fee = GetReserveFee( $borrowernumber, $biblionumber );
591 Calculate the fee for a reserve (if applicable).
596 my ( $borrowernumber, $biblionumber ) = @_;
598 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
601 SELECT COUNT(*) FROM items
602 LEFT JOIN issues USING (itemnumber)
603 WHERE items.biblionumber=? AND issues.issue_id IS NULL
606 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
609 my $dbh = C4::Context->dbh;
610 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
611 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
612 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
613 # This is a reconstruction of the old code:
614 # Compare number of items with items issued, and optionally check holds
615 # If not all items are issued and there are no holds: charge no fee
616 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
617 my ( $notissued, $reserved );
618 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
621 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
622 ( $biblionumber, $borrowernumber ) );
623 $fee = 0 if $reserved == 0;
629 =head2 GetReserveStatus
631 $reservestatus = GetReserveStatus($itemnumber);
633 Takes an itemnumber and returns the status of the reserve placed on it.
634 If several reserves exist, the reserve with the lower priority is given.
638 ## FIXME: I don't think this does what it thinks it does.
639 ## It only ever checks the first reserve result, even though
640 ## multiple reserves for that bib can have the itemnumber set
641 ## the sub is only used once in the codebase.
642 sub GetReserveStatus {
643 my ($itemnumber) = @_;
645 my $dbh = C4::Context->dbh;
647 my ($sth, $found, $priority);
649 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
650 $sth->execute($itemnumber);
651 ($found, $priority) = $sth->fetchrow_array;
655 return 'Waiting' if $found eq 'W' and $priority == 0;
656 return 'Finished' if $found eq 'F';
659 return 'Reserved' if $priority > 0;
661 return ''; # empty string here will remove need for checking undef, or less log lines
666 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
667 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
668 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
670 Find a book in the reserves.
672 C<$itemnumber> is the book's item number.
673 C<$lookahead> is the number of days to look in advance for future reserves.
675 As I understand it, C<&CheckReserves> looks for the given item in the
676 reserves. If it is found, that's a match, and C<$status> is set to
679 Otherwise, it finds the most important item in the reserves with the
680 same biblio number as this book (I'm not clear on this) and returns it
681 with C<$status> set to C<Reserved>.
683 C<&CheckReserves> returns a two-element list:
685 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
687 C<$reserve> is the reserve item that matched. It is a
688 reference-to-hash whose keys are mostly the fields of the reserves
689 table in the Koha database.
694 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
695 my $dbh = C4::Context->dbh;
698 if (C4::Context->preference('item-level_itypes')){
700 SELECT items.biblionumber,
701 items.biblioitemnumber,
702 itemtypes.notforloan,
703 items.notforloan AS itemnotforloan,
709 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
710 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
715 SELECT items.biblionumber,
716 items.biblioitemnumber,
717 itemtypes.notforloan,
718 items.notforloan AS itemnotforloan,
724 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
725 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
730 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
731 $sth->execute($item);
734 $sth = $dbh->prepare("$select WHERE barcode = ?");
735 $sth->execute($barcode);
737 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
738 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
740 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
742 return unless $itemnumber; # bail if we got nothing.
744 # if item is not for loan it cannot be reserved either.....
745 # except where items.notforloan < 0 : This indicates the item is holdable.
746 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
748 # Find this item in the reserves
749 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
751 # $priority and $highest are used to find the most important item
752 # in the list returned by &_Findgroupreserve. (The lower $priority,
753 # the more important the item.)
754 # $highest is the most important item we've seen so far.
756 if (scalar @reserves) {
757 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
758 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
759 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
761 my $priority = 10000000;
762 foreach my $res (@reserves) {
763 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
764 if ($res->{'found'} eq 'W') {
765 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
767 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
772 my $local_hold_match;
774 if ($LocalHoldsPriority) {
775 $patron = Koha::Patrons->find( $res->{borrowernumber} );
776 $item = Koha::Items->find($itemnumber);
778 my $local_holds_priority_item_branchcode =
779 $item->$LocalHoldsPriorityItemControl;
780 my $local_holds_priority_patron_branchcode =
781 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
783 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
784 ? $patron->branchcode
787 $local_holds_priority_item_branchcode eq
788 $local_holds_priority_patron_branchcode;
791 # See if this item is more important than what we've got so far
792 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
793 $item ||= Koha::Items->find($itemnumber);
794 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
795 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
796 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
797 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
798 next if ($branchitemrule->{'holdallowed'} == 0);
799 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
800 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
801 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
802 next unless $item->can_be_transferred( { to => scalar Koha::Libraries->find( $res->{branchcode} ) } );
803 $priority = $res->{'priority'};
805 last if $local_hold_match;
811 # If we get this far, then no exact match was found.
812 # We return the most important (i.e. next) reservation.
814 $highest->{'itemnumber'} = $item;
815 return ( "Reserved", $highest, \@reserves );
821 =head2 CancelExpiredReserves
823 CancelExpiredReserves();
825 Cancels all reserves with an expiration date from before today.
829 sub CancelExpiredReserves {
830 my $today = dt_from_string();
831 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
832 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
834 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
835 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
836 $params->{found} = undef unless $expireWaiting;
838 # FIXME To move to Koha::Holds->search_expired (?)
839 my $holds = Koha::Holds->search( $params );
841 while ( my $hold = $holds->next ) {
842 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
844 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
846 my $cancel_params = {};
847 if ( $hold->found eq 'W' ) {
848 $cancel_params->{charge_cancel_fee} = 1;
850 $hold->cancel( $cancel_params );
854 =head2 AutoUnsuspendReserves
856 AutoUnsuspendReserves();
858 Unsuspends all suspended reserves with a suspend_until date from before today.
862 sub AutoUnsuspendReserves {
863 my $today = dt_from_string();
865 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
867 map { $_->resume() } @holds;
872 ModReserve({ rank => $rank,
873 reserve_id => $reserve_id,
874 branchcode => $branchcode
875 [, itemnumber => $itemnumber ]
876 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
879 Change a hold request's priority or cancel it.
881 C<$rank> specifies the effect of the change. If C<$rank>
882 is 'W' or 'n', nothing happens. This corresponds to leaving a
883 request alone when changing its priority in the holds queue
886 If C<$rank> is 'del', the hold request is cancelled.
888 If C<$rank> is an integer greater than zero, the priority of
889 the request is set to that value. Since priority != 0 means
890 that the item is not waiting on the hold shelf, setting the
891 priority to a non-zero value also sets the request's found
892 status and waiting date to NULL.
894 The optional C<$itemnumber> parameter is used only when
895 C<$rank> is a non-zero integer; if supplied, the itemnumber
896 of the hold request is set accordingly; if omitted, the itemnumber
899 B<FIXME:> Note that the forgoing can have the effect of causing
900 item-level hold requests to turn into title-level requests. This
901 will be fixed once reserves has separate columns for requested
902 itemnumber and supplying itemnumber.
909 my $rank = $params->{'rank'};
910 my $reserve_id = $params->{'reserve_id'};
911 my $branchcode = $params->{'branchcode'};
912 my $itemnumber = $params->{'itemnumber'};
913 my $suspend_until = $params->{'suspend_until'};
914 my $borrowernumber = $params->{'borrowernumber'};
915 my $biblionumber = $params->{'biblionumber'};
917 return if $rank eq "W";
918 return if $rank eq "n";
920 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
923 unless ( $reserve_id ) {
924 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
925 return unless $holds->count; # FIXME Should raise an exception
926 $hold = $holds->next;
927 $reserve_id = $hold->reserve_id;
930 $hold ||= Koha::Holds->find($reserve_id);
932 if ( $rank eq "del" ) {
935 elsif ($rank =~ /^\d+/ and $rank > 0) {
936 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
937 if C4::Context->preference('HoldsLog');
942 branchcode => $branchcode,
943 itemnumber => $itemnumber,
949 if ( defined( $suspend_until ) ) {
950 if ( $suspend_until ) {
951 $suspend_until = eval { dt_from_string( $suspend_until ) };
952 $hold->suspend_hold( $suspend_until );
954 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
955 # If the hold is not suspended, this does nothing.
956 $hold->set( { suspend_until => undef } )->store();
960 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
964 =head2 ModReserveFill
966 &ModReserveFill($reserve);
968 Fill a reserve. If I understand this correctly, this means that the
969 reserved book has been found and given to the patron who reserved it.
971 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
972 whose keys are fields from the reserves table in the Koha database.
978 my $reserve_id = $res->{'reserve_id'};
980 my $hold = Koha::Holds->find($reserve_id);
982 # get the priority on this record....
983 my $priority = $hold->priority;
985 # update the hold statuses, no need to store it though, we will be deleting it anyway
993 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
994 Koha::Old::Hold->new( $hold->unblessed() )->store();
998 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
999 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1000 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1003 # now fix the priority on the others (if the priority wasn't
1004 # already sorted!)....
1005 unless ( $priority == 0 ) {
1006 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1010 =head2 ModReserveStatus
1012 &ModReserveStatus($itemnumber, $newstatus);
1014 Update the reserve status for the active (priority=0) reserve.
1016 $itemnumber is the itemnumber the reserve is on
1018 $newstatus is the new status.
1022 sub ModReserveStatus {
1024 #first : check if we have a reservation for this item .
1025 my ($itemnumber, $newstatus) = @_;
1026 my $dbh = C4::Context->dbh;
1028 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1029 my $sth_set = $dbh->prepare($query);
1030 $sth_set->execute( $newstatus, $itemnumber );
1032 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1033 CartToShelf( $itemnumber );
1037 =head2 ModReserveAffect
1039 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1041 This function affect an item and a status for a given reserve, either fetched directly
1042 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1043 is given, only first reserve returned is affected, which is ok for anything but
1046 if $transferToDo is not set, then the status is set to "Waiting" as well.
1047 otherwise, a transfer is on the way, and the end of the transfer will
1048 take care of the waiting status
1052 sub ModReserveAffect {
1053 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1054 my $dbh = C4::Context->dbh;
1056 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1057 # attached to $itemnumber
1058 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1059 $sth->execute($itemnumber);
1060 my ($biblionumber) = $sth->fetchrow;
1062 # get request - need to find out if item is already
1063 # waiting in order to not send duplicate hold filled notifications
1066 # Find hold by id if we have it
1067 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1068 # Find item level hold for this item if there is one
1069 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1070 # Find record level hold if there is no item level hold
1071 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1073 return unless $hold;
1075 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1077 $hold->itemnumber($itemnumber);
1078 $hold->set_waiting($transferToDo);
1080 _koha_notify_reserve( $hold->reserve_id )
1081 if ( !$transferToDo && !$already_on_shelf );
1083 _FixPriority( { biblionumber => $biblionumber } );
1085 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1086 CartToShelf($itemnumber);
1092 =head2 ModReserveCancelAll
1094 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1096 function to cancel reserv,check other reserves, and transfer document if it's necessary
1100 sub ModReserveCancelAll {
1103 my ( $itemnumber, $borrowernumber ) = @_;
1105 #step 1 : cancel the reservation
1106 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1107 return unless $holds->count;
1108 $holds->next->cancel;
1110 #step 2 launch the subroutine of the others reserves
1111 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1113 return ( $messages, $nextreservinfo );
1116 =head2 ModReserveMinusPriority
1118 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1120 Reduce the values of queued list
1124 sub ModReserveMinusPriority {
1125 my ( $itemnumber, $reserve_id ) = @_;
1127 #first step update the value of the first person on reserv
1128 my $dbh = C4::Context->dbh;
1131 SET priority = 0 , itemnumber = ?
1132 WHERE reserve_id = ?
1134 my $sth_upd = $dbh->prepare($query);
1135 $sth_upd->execute( $itemnumber, $reserve_id );
1136 # second step update all others reserves
1137 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1140 =head2 IsAvailableForItemLevelRequest
1142 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1144 Checks whether a given item record is available for an
1145 item-level hold request. An item is available if
1147 * it is not lost AND
1148 * it is not damaged AND
1149 * it is not withdrawn AND
1150 * a waiting or in transit reserve is placed on
1151 * does not have a not for loan value > 0
1153 Need to check the issuingrules onshelfholds column,
1154 if this is set items on the shelf can be placed on hold
1156 Note that IsAvailableForItemLevelRequest() does not
1157 check if the staff operator is authorized to place
1158 a request on the item - in particular,
1159 this routine does not check IndependentBranches
1160 and canreservefromotherbranches.
1164 sub IsAvailableForItemLevelRequest {
1166 my $borrower = shift;
1167 my $pickup_branchcode = shift;
1169 my $dbh = C4::Context->dbh;
1170 # must check the notforloan setting of the itemtype
1171 # FIXME - a lot of places in the code do this
1172 # or something similar - need to be
1174 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
1175 my $item_object = Koha::Items->find( $item->{itemnumber } );
1176 my $itemtype = $item_object->effective_itemtype;
1177 my $notforloan_per_itemtype
1178 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1182 $notforloan_per_itemtype ||
1183 $item->{itemlost} ||
1184 $item->{notforloan} > 0 ||
1185 $item->{withdrawn} ||
1186 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1188 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item_object, patron => $patron } );
1190 if ($pickup_branchcode) {
1191 my $destination = Koha::Libraries->find($pickup_branchcode);
1192 return 0 unless $destination;
1193 return 0 unless $destination->pickup_location;
1194 return 0 unless $item_object->can_be_transferred( { to => $destination } );
1197 if ( $on_shelf_holds == 1 ) {
1199 } elsif ( $on_shelf_holds == 2 ) {
1201 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1203 my $any_available = 0;
1205 foreach my $i (@items) {
1207 my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
1208 my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
1212 || $i->notforloan > 0
1215 || IsItemOnHoldAndFound( $i->id )
1217 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1218 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1219 || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
1222 return $any_available ? 0 : 1;
1223 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1224 return $item->{onloan} || IsItemOnHoldAndFound( $item->{itemnumber} );
1232 if (C4::Context->preference('item-level_itypes')) {
1233 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1234 # When GetItem is fixed, we can remove this
1235 $itype = $item->{itype};
1238 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1239 # So if we already have a biblioitems join when calling this function,
1240 # we don't need to access the database again
1241 $itype = $item->{itemtype};
1244 my $dbh = C4::Context->dbh;
1245 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1246 my $sth = $dbh->prepare($query);
1247 $sth->execute($item->{biblioitemnumber});
1248 if (my $data = $sth->fetchrow_hashref()){
1249 $itype = $data->{itemtype};
1255 =head2 AlterPriority
1257 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1259 This function changes a reserve's priority up, down, to the top, or to the bottom.
1260 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1265 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1267 my $hold = Koha::Holds->find( $reserve_id );
1268 return unless $hold;
1270 if ( $hold->cancellationdate ) {
1271 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1275 if ( $where eq 'up' ) {
1276 return unless $prev_priority;
1277 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1278 } elsif ( $where eq 'down' ) {
1279 return unless $next_priority;
1280 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1281 } elsif ( $where eq 'top' ) {
1282 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1283 } elsif ( $where eq 'bottom' ) {
1284 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1287 # FIXME Should return the new priority
1290 =head2 ToggleLowestPriority
1292 ToggleLowestPriority( $borrowernumber, $biblionumber );
1294 This function sets the lowestPriority field to true if is false, and false if it is true.
1298 sub ToggleLowestPriority {
1299 my ( $reserve_id ) = @_;
1301 my $dbh = C4::Context->dbh;
1303 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1304 $sth->execute( $reserve_id );
1306 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1309 =head2 ToggleSuspend
1311 ToggleSuspend( $reserve_id );
1313 This function sets the suspend field to true if is false, and false if it is true.
1314 If the reserve is currently suspended with a suspend_until date, that date will
1315 be cleared when it is unsuspended.
1320 my ( $reserve_id, $suspend_until ) = @_;
1322 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1324 my $hold = Koha::Holds->find( $reserve_id );
1326 if ( $hold->is_suspended ) {
1329 $hold->suspend_hold( $suspend_until );
1336 borrowernumber => $borrowernumber,
1337 [ biblionumber => $biblionumber, ]
1338 [ suspend_until => $suspend_until, ]
1339 [ suspend => $suspend ]
1342 This function accepts a set of hash keys as its parameters.
1343 It requires either borrowernumber or biblionumber, or both.
1345 suspend_until is wholly optional.
1352 my $borrowernumber = $params{'borrowernumber'} || undef;
1353 my $biblionumber = $params{'biblionumber'} || undef;
1354 my $suspend_until = $params{'suspend_until'} || undef;
1355 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1357 $suspend_until = eval { dt_from_string($suspend_until) }
1358 if ( defined($suspend_until) );
1360 return unless ( $borrowernumber || $biblionumber );
1363 $params->{found} = undef;
1364 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1365 $params->{biblionumber} = $biblionumber if $biblionumber;
1367 my @holds = Koha::Holds->search($params);
1370 map { $_->suspend_hold($suspend_until) } @holds;
1373 map { $_->resume() } @holds;
1381 reserve_id => $reserve_id,
1383 [ignoreSetLowestRank => $ignoreSetLowestRank]
1388 _FixPriority({ biblionumber => $biblionumber});
1390 This routine adjusts the priority of a hold request and holds
1393 In the first form, where a reserve_id is passed, the priority of the
1394 hold is set to supplied rank, and other holds for that bib are adjusted
1395 accordingly. If the rank is "del", the hold is cancelled. If no rank
1396 is supplied, all of the holds on that bib have their priority adjusted
1397 as if the second form had been used.
1399 In the second form, where a biblionumber is passed, the holds on that
1400 bib (that are not captured) are sorted in order of increasing priority,
1401 then have reserves.priority set so that the first non-captured hold
1402 has its priority set to 1, the second non-captured hold has its priority
1403 set to 2, and so forth.
1405 In both cases, holds that have the lowestPriority flag on are have their
1406 priority adjusted to ensure that they remain at the end of the line.
1408 Note that the ignoreSetLowestRank parameter is meant to be used only
1409 when _FixPriority calls itself.
1414 my ( $params ) = @_;
1415 my $reserve_id = $params->{reserve_id};
1416 my $rank = $params->{rank} // '';
1417 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1418 my $biblionumber = $params->{biblionumber};
1420 my $dbh = C4::Context->dbh;
1423 if ( $reserve_id ) {
1424 $hold = Koha::Holds->find( $reserve_id );
1425 return unless $hold;
1428 unless ( $biblionumber ) { # FIXME This is a very weird API
1429 $biblionumber = $hold->biblionumber;
1432 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1435 elsif ( $rank eq "W" || $rank eq "0" ) {
1437 # make sure priority for waiting or in-transit items is 0
1441 WHERE reserve_id = ?
1442 AND found IN ('W', 'T')
1444 my $sth = $dbh->prepare($query);
1445 $sth->execute( $reserve_id );
1451 SELECT reserve_id, borrowernumber, reservedate
1453 WHERE biblionumber = ?
1454 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1455 ORDER BY priority ASC
1457 my $sth = $dbh->prepare($query);
1458 $sth->execute( $biblionumber );
1459 while ( my $line = $sth->fetchrow_hashref ) {
1460 push( @priority, $line );
1463 # To find the matching index
1465 my $key = -1; # to allow for 0 to be a valid result
1466 for ( $i = 0 ; $i < @priority ; $i++ ) {
1467 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1468 $key = $i; # save the index
1473 # if index exists in array then move it to new position
1474 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1475 my $new_rank = $rank -
1476 1; # $new_rank is what you want the new index to be in the array
1477 my $moving_item = splice( @priority, $key, 1 );
1478 splice( @priority, $new_rank, 0, $moving_item );
1481 # now fix the priority on those that are left....
1485 WHERE reserve_id = ?
1487 $sth = $dbh->prepare($query);
1488 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1491 $priority[$j]->{'reserve_id'}
1495 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1498 unless ( $ignoreSetLowestRank ) {
1499 while ( my $res = $sth->fetchrow_hashref() ) {
1501 reserve_id => $res->{'reserve_id'},
1503 ignoreSetLowestRank => 1
1509 =head2 _Findgroupreserve
1511 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1513 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1514 first match found. If neither, then we look for non-holds-queue based holds.
1515 Lookahead is the number of days to look in advance.
1517 C<&_Findgroupreserve> returns :
1518 C<@results> is an array of references-to-hash whose keys are mostly
1519 fields from the reserves table of the Koha database, plus
1520 C<biblioitemnumber>.
1524 sub _Findgroupreserve {
1525 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1526 my $dbh = C4::Context->dbh;
1528 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1529 # check for exact targeted match
1530 my $item_level_target_query = qq{
1531 SELECT reserves.biblionumber AS biblionumber,
1532 reserves.borrowernumber AS borrowernumber,
1533 reserves.reservedate AS reservedate,
1534 reserves.branchcode AS branchcode,
1535 reserves.cancellationdate AS cancellationdate,
1536 reserves.found AS found,
1537 reserves.reservenotes AS reservenotes,
1538 reserves.priority AS priority,
1539 reserves.timestamp AS timestamp,
1540 biblioitems.biblioitemnumber AS biblioitemnumber,
1541 reserves.itemnumber AS itemnumber,
1542 reserves.reserve_id AS reserve_id,
1543 reserves.itemtype AS itemtype
1545 JOIN biblioitems USING (biblionumber)
1546 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1549 AND item_level_request = 1
1551 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1555 my $sth = $dbh->prepare($item_level_target_query);
1556 $sth->execute($itemnumber, $lookahead||0);
1558 if ( my $data = $sth->fetchrow_hashref ) {
1559 push( @results, $data )
1560 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1562 return @results if @results;
1564 # check for title-level targeted match
1565 my $title_level_target_query = qq{
1566 SELECT reserves.biblionumber AS biblionumber,
1567 reserves.borrowernumber AS borrowernumber,
1568 reserves.reservedate AS reservedate,
1569 reserves.branchcode AS branchcode,
1570 reserves.cancellationdate AS cancellationdate,
1571 reserves.found AS found,
1572 reserves.reservenotes AS reservenotes,
1573 reserves.priority AS priority,
1574 reserves.timestamp AS timestamp,
1575 biblioitems.biblioitemnumber AS biblioitemnumber,
1576 reserves.itemnumber AS itemnumber,
1577 reserves.reserve_id AS reserve_id,
1578 reserves.itemtype AS itemtype
1580 JOIN biblioitems USING (biblionumber)
1581 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1584 AND item_level_request = 0
1585 AND hold_fill_targets.itemnumber = ?
1586 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1590 $sth = $dbh->prepare($title_level_target_query);
1591 $sth->execute($itemnumber, $lookahead||0);
1593 if ( my $data = $sth->fetchrow_hashref ) {
1594 push( @results, $data )
1595 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1597 return @results if @results;
1600 SELECT reserves.biblionumber AS biblionumber,
1601 reserves.borrowernumber AS borrowernumber,
1602 reserves.reservedate AS reservedate,
1603 reserves.waitingdate AS waitingdate,
1604 reserves.branchcode AS branchcode,
1605 reserves.cancellationdate AS cancellationdate,
1606 reserves.found AS found,
1607 reserves.reservenotes AS reservenotes,
1608 reserves.priority AS priority,
1609 reserves.timestamp AS timestamp,
1610 reserves.itemnumber AS itemnumber,
1611 reserves.reserve_id AS reserve_id,
1612 reserves.itemtype AS itemtype
1614 WHERE reserves.biblionumber = ?
1615 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1616 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1620 $sth = $dbh->prepare($query);
1621 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1623 while ( my $data = $sth->fetchrow_hashref ) {
1624 push( @results, $data )
1625 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1630 =head2 _koha_notify_reserve
1632 _koha_notify_reserve( $hold->reserve_id );
1634 Sends a notification to the patron that their hold has been filled (through
1635 ModReserveAffect, _not_ ModReserveFill)
1637 The letter code for this notice may be found using the following query:
1639 select distinct letter_code
1640 from message_transports
1641 inner join message_attributes using (message_attribute_id)
1642 where message_name = 'Hold_Filled'
1644 This will probably sipmly be 'HOLD', but because it is defined in the database,
1645 it is subject to addition or change.
1647 The following tables are availalbe witin the notice:
1658 sub _koha_notify_reserve {
1659 my $reserve_id = shift;
1660 my $hold = Koha::Holds->find($reserve_id);
1661 my $borrowernumber = $hold->borrowernumber;
1663 my $patron = Koha::Patrons->find( $borrowernumber );
1665 # Try to get the borrower's email address
1666 my $to_address = $patron->notice_email_address;
1668 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1669 borrowernumber => $borrowernumber,
1670 message_name => 'Hold_Filled'
1673 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1675 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1677 my %letter_params = (
1678 module => 'reserves',
1679 branchcode => $hold->branchcode,
1680 lang => $patron->lang,
1682 'branches' => $library,
1683 'borrowers' => $patron->unblessed,
1684 'biblio' => $hold->biblionumber,
1685 'biblioitems' => $hold->biblionumber,
1686 'reserves' => $hold->unblessed,
1687 'items' => $hold->itemnumber,
1691 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.
1692 my $send_notification = sub {
1693 my ( $mtt, $letter_code ) = (@_);
1694 return unless defined $letter_code;
1695 $letter_params{letter_code} = $letter_code;
1696 $letter_params{message_transport_type} = $mtt;
1697 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1699 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1703 C4::Letters::EnqueueLetter( {
1705 borrowernumber => $borrowernumber,
1706 from_address => $admin_email_address,
1707 message_transport_type => $mtt,
1711 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1713 ( $mtt eq 'email' and not $to_address ) # No email address
1714 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1715 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1718 &$send_notification($mtt, $letter_code);
1719 $notification_sent++;
1721 #Making sure that a print notification is sent if no other transport types can be utilized.
1722 if (! $notification_sent) {
1723 &$send_notification('print', 'HOLD');
1728 =head2 _ShiftPriorityByDateAndPriority
1730 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1732 This increments the priority of all reserves after the one
1733 with either the lowest date after C<$reservedate>
1734 or the lowest priority after C<$priority>.
1736 It effectively makes room for a new reserve to be inserted with a certain
1737 priority, which is returned.
1739 This is most useful when the reservedate can be set by the user. It allows
1740 the new reserve to be placed before other reserves that have a later
1741 reservedate. Since priority also is set by the form in reserves/request.pl
1742 the sub accounts for that too.
1746 sub _ShiftPriorityByDateAndPriority {
1747 my ( $biblio, $resdate, $new_priority ) = @_;
1749 my $dbh = C4::Context->dbh;
1750 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1751 my $sth = $dbh->prepare( $query );
1752 $sth->execute( $biblio, $resdate, $new_priority );
1753 my $min_priority = $sth->fetchrow;
1754 # if no such matches are found, $new_priority remains as original value
1755 $new_priority = $min_priority if ( $min_priority );
1757 # Shift the priority up by one; works in conjunction with the next SQL statement
1758 $query = "UPDATE reserves
1759 SET priority = priority+1
1760 WHERE biblionumber = ?
1761 AND borrowernumber = ?
1764 my $sth_update = $dbh->prepare( $query );
1766 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1767 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1768 $sth = $dbh->prepare( $query );
1769 $sth->execute( $new_priority, $biblio );
1770 while ( my $row = $sth->fetchrow_hashref ) {
1771 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1774 return $new_priority; # so the caller knows what priority they wind up receiving
1779 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1781 Use when checking out an item to handle reserves
1782 If $cancelreserve boolean is set to true, it will remove existing reserve
1787 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1789 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1790 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1793 my $biblionumber = $res->{biblionumber};
1795 if ($res->{borrowernumber} == $borrowernumber) {
1796 ModReserveFill($res);
1800 # The item is reserved by someone else.
1801 # Find this item in the reserves
1804 foreach (@$all_reserves) {
1805 $_->{'borrowernumber'} == $borrowernumber or next;
1806 $_->{'biblionumber'} == $biblionumber or next;
1813 # The item is reserved by the current patron
1814 ModReserveFill($borr_res);
1817 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1818 RevertWaitingStatus({ itemnumber => $itemnumber });
1820 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1821 my $hold = Koha::Holds->find( $res->{reserve_id} );
1829 MergeHolds($dbh,$to_biblio, $from_biblio);
1831 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1836 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1837 my $sth = $dbh->prepare(
1838 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1840 $sth->execute($from_biblio);
1841 if ( my $data = $sth->fetchrow_hashref() ) {
1843 # holds exist on old record, if not we don't need to do anything
1844 $sth = $dbh->prepare(
1845 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1846 $sth->execute( $to_biblio, $from_biblio );
1849 # don't reorder those already waiting
1851 $sth = $dbh->prepare(
1852 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1854 my $upd_sth = $dbh->prepare(
1855 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1856 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1858 $sth->execute( $to_biblio, 'W', 'T' );
1860 while ( my $reserve = $sth->fetchrow_hashref() ) {
1862 $priority, $to_biblio,
1863 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1864 $reserve->{'itemnumber'}
1871 =head2 RevertWaitingStatus
1873 RevertWaitingStatus({ itemnumber => $itemnumber });
1875 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1877 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1878 item level hold, even if it was only a bibliolevel hold to
1879 begin with. This is because we can no longer know if a hold
1880 was item-level or bib-level after a hold has been set to
1885 sub RevertWaitingStatus {
1886 my ( $params ) = @_;
1887 my $itemnumber = $params->{'itemnumber'};
1889 return unless ( $itemnumber );
1891 my $dbh = C4::Context->dbh;
1893 ## Get the waiting reserve we want to revert
1895 SELECT * FROM reserves
1896 WHERE itemnumber = ?
1897 AND found IS NOT NULL
1899 my $sth = $dbh->prepare( $query );
1900 $sth->execute( $itemnumber );
1901 my $reserve = $sth->fetchrow_hashref();
1903 ## Increment the priority of all other non-waiting
1904 ## reserves for this bib record
1908 priority = priority + 1
1914 $sth = $dbh->prepare( $query );
1915 $sth->execute( $reserve->{'biblionumber'} );
1917 ## Fix up the currently waiting reserve
1927 $sth = $dbh->prepare( $query );
1928 $sth->execute( $reserve->{'reserve_id'} );
1929 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1936 branchcode => $branchcode,
1937 borrowernumber => $borrowernumber,
1938 biblionumber => $biblionumber,
1939 [ itemnumber => $itemnumber, ]
1940 [ barcode => $barcode, ]
1944 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1946 The letter code will be HOLD_SLIP, and the following tables are
1947 available within the slip:
1960 my $branchcode = $args->{branchcode};
1961 my $borrowernumber = $args->{borrowernumber};
1962 my $biblionumber = $args->{biblionumber};
1963 my $itemnumber = $args->{itemnumber};
1964 my $barcode = $args->{barcode};
1967 my $patron = Koha::Patrons->find($borrowernumber);
1970 if ($itemnumber || $barcode ) {
1971 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
1973 $hold = Koha::Holds->search(
1975 biblionumber => $biblionumber,
1976 borrowernumber => $borrowernumber,
1977 itemnumber => $itemnumber
1982 $hold = Koha::Holds->search(
1984 biblionumber => $biblionumber,
1985 borrowernumber => $borrowernumber
1990 return unless $hold;
1991 my $reserve = $hold->unblessed;
1993 return C4::Letters::GetPreparedLetter (
1994 module => 'circulation',
1995 letter_code => 'HOLD_SLIP',
1996 branchcode => $branchcode,
1997 lang => $patron->lang,
1999 'reserves' => $reserve,
2000 'branches' => $reserve->{branchcode},
2001 'borrowers' => $reserve->{borrowernumber},
2002 'biblio' => $reserve->{biblionumber},
2003 'biblioitems' => $reserve->{biblionumber},
2004 'items' => $reserve->{itemnumber},
2009 =head2 GetReservesControlBranch
2011 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2013 Return the branchcode to be used to determine which reserves
2014 policy applies to a transaction.
2016 C<$item> is a hashref for an item. Only 'homebranch' is used.
2018 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2022 sub GetReservesControlBranch {
2023 my ( $item, $borrower ) = @_;
2025 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2028 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2029 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2035 =head2 CalculatePriority
2037 my $p = CalculatePriority($biblionumber, $resdate);
2039 Calculate priority for a new reserve on biblionumber, placing it at
2040 the end of the line of all holds whose start date falls before
2041 the current system time and that are neither on the hold shelf
2044 The reserve date parameter is optional; if it is supplied, the
2045 priority is based on the set of holds whose start date falls before
2046 the parameter value.
2048 After calculation of this priority, it is recommended to call
2049 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2054 sub CalculatePriority {
2055 my ( $biblionumber, $resdate ) = @_;
2058 SELECT COUNT(*) FROM reserves
2059 WHERE biblionumber = ?
2061 AND (found IS NULL OR found = '')
2063 #skip found==W or found==T (waiting or transit holds)
2065 $sql.= ' AND ( reservedate <= ? )';
2068 $sql.= ' AND ( reservedate < NOW() )';
2070 my $dbh = C4::Context->dbh();
2071 my @row = $dbh->selectrow_array(
2074 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2077 return @row ? $row[0]+1 : 1;
2080 =head2 IsItemOnHoldAndFound
2082 my $bool = IsItemFoundHold( $itemnumber );
2084 Returns true if the item is currently on hold
2085 and that hold has a non-null found status ( W, T, etc. )
2089 sub IsItemOnHoldAndFound {
2090 my ($itemnumber) = @_;
2092 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2094 my $found = $rs->count(
2096 itemnumber => $itemnumber,
2097 found => { '!=' => undef }
2104 =head2 GetMaxPatronHoldsForRecord
2106 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2108 For multiple holds on a given record for a given patron, the max
2109 number of record level holds that a patron can be placed is the highest
2110 value of the holds_per_record rule for each item if the record for that
2111 patron. This subroutine finds and returns the highest holds_per_record
2112 rule value for a given patron id and record id.
2116 sub GetMaxPatronHoldsForRecord {
2117 my ( $borrowernumber, $biblionumber ) = @_;
2119 my $patron = Koha::Patrons->find($borrowernumber);
2120 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2122 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2124 my $categorycode = $patron->categorycode;
2126 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2129 foreach my $item (@items) {
2130 my $itemtype = $item->effective_itemtype();
2132 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2134 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2135 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2136 $max = $holds_per_record if $holds_per_record > $max;
2144 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2146 Returns the matching hold related issuingrule fields for a given
2147 patron category, itemtype, and library.
2152 my ( $categorycode, $itemtype, $branchcode ) = @_;
2154 my $dbh = C4::Context->dbh;
2156 my $sth = $dbh->prepare(
2158 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2160 WHERE (categorycode in (?,'*') )
2161 AND (itemtype IN (?,'*'))
2162 AND (branchcode IN (?,'*'))
2163 ORDER BY categorycode DESC,
2169 $sth->execute( $categorycode, $itemtype, $branchcode );
2171 return $sth->fetchrow_hashref();
2176 Koha Development Team <http://koha-community.org/>