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>.
27 use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
29 use C4::Items qw( CartToShelf get_hostitemnumbers_of );
31 use C4::Log qw( logaction );
32 use C4::Members::Messaging;
34 use Koha::Account::Lines;
37 use Koha::CirculationRules;
39 use Koha::DateUtils qw( dt_from_string output_pref );
49 use Data::Dumper qw( Dumper );
50 use List::MoreUtils qw( any );
54 C4::Reserves - Koha functions for dealing with reservation.
62 This modules provides somes functions to deal with reservations.
64 Reserves are stored in reserves table.
65 The following columns contains important values :
66 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
67 =0 : then the reserve is being dealed
68 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
69 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
70 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
71 F(inished) : the reserve has been completed, and is done
72 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
73 by librarian before notice is send and status changed to waiting.
74 Applicable only if HoldsNeedProcessingSIP system preference is set.
75 - itemnumber : empty : the reserve is still unaffected to an item
76 filled: the reserve is attached to an item
77 The complete workflow is :
78 ==== 1st use case ====
79 patron request a document, 1st available : P >0, F=NULL, I=NULL
80 a library having it run "transfertodo", and clic on the list
81 if there is no transfer to do, the reserve waiting
82 patron can pick it up P =0, F=W, I=filled
83 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it check in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
87 ==== 2nd use case ====
88 patron requests a document, a given item,
89 If pickup is holding branch P =0, F=W, I=filled
90 If transfer needed, write in branchtransfer P =0, F=T, I=filled
91 The pickup library receive the book, it checks it in P =0, F=W, I=filled
92 The patron borrow the book P =0, F=F, I=filled
98 our (@ISA, @EXPORT_OK);
116 ModReserveMinusPriority
122 CanReserveBeCanceledFromOpac
123 CancelExpiredReserves
125 AutoUnsuspendReserves
127 IsAvailableForItemLevelRequest
128 ItemsAnyAvailableAndNotRestricted
137 GetReservesControlBranch
143 GetMaxPatronHoldsForRecord
155 branchcode => $branchcode,
156 borrowernumber => $borrowernumber,
157 biblionumber => $biblionumber,
158 priority => $priority,
159 reservation_date => $reservation_date,
160 expiration_date => $expiration_date,
163 itemnumber => $itemnumber,
165 itemtype => $itemtype,
169 Adds reserve and generates HOLDPLACED message.
171 The following tables are available witin the HOLDPLACED message:
184 my $branch = $params->{branchcode};
185 my $borrowernumber = $params->{borrowernumber};
186 my $biblionumber = $params->{biblionumber};
187 my $priority = $params->{priority};
188 my $resdate = $params->{reservation_date};
189 my $expdate = $params->{expiration_date};
190 my $notes = $params->{notes};
191 my $title = $params->{title};
192 my $checkitem = $params->{itemnumber};
193 my $found = $params->{found};
194 my $itemtype = $params->{itemtype};
195 my $non_priority = $params->{non_priority};
197 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
198 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
200 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
202 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
203 # of the document, we force the value $priority and $found .
204 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
205 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
208 # If item is already checked out, it cannot be set waiting
211 # The item can't be waiting if it needs a transfer
212 && $item->holdingbranch eq $branch
214 # Similarly, if in transit it can't be waiting
215 && !$item->get_transfer
217 # If we can't hold damaged items, and it is damaged, it can't be waiting
218 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
220 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
221 && !$item->current_holds->count )
228 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
230 # Make room in reserves for this before those of a later reserve date
231 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
236 # If the reserv had the waiting status, we had the value of the resdate
237 if ( $found && $found eq 'W' ) {
238 $waitingdate = $resdate;
241 # Don't add itemtype limit if specific item is selected
242 $itemtype = undef if $checkitem;
244 # updates take place here
245 my $hold = Koha::Hold->new(
247 borrowernumber => $borrowernumber,
248 biblionumber => $biblionumber,
249 reservedate => $resdate,
250 branchcode => $branch,
251 priority => $priority,
252 reservenotes => $notes,
253 itemnumber => $checkitem,
255 waitingdate => $waitingdate,
256 expirationdate => $expdate,
257 itemtype => $itemtype,
258 item_level_hold => $checkitem ? 1 : 0,
259 non_priority => $non_priority ? 1 : 0,
262 $hold->set_waiting() if $found && $found eq 'W';
264 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
265 if C4::Context->preference('HoldsLog');
267 my $reserve_id = $hold->id();
269 # add a reserve fee if needed
270 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
271 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
272 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
275 _FixPriority({ biblionumber => $biblionumber});
277 # Send e-mail to librarian if syspref is active
278 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
279 my $patron = Koha::Patrons->find( $borrowernumber );
280 my $library = $patron->library;
281 if ( my $letter = C4::Letters::GetPreparedLetter (
282 module => 'reserves',
283 letter_code => 'HOLDPLACED',
284 branchcode => $branch,
285 lang => $patron->lang,
287 'branches' => $library->unblessed,
288 'borrowers' => $patron->unblessed,
289 'biblio' => $biblionumber,
290 'biblioitems' => $biblionumber,
291 'items' => $checkitem,
292 'reserves' => $hold->unblessed,
296 my $branch_email_address = $library->inbound_email_address;
298 C4::Letters::EnqueueLetter(
301 borrowernumber => $borrowernumber,
302 message_transport_type => 'email',
303 to_address => $branch_email_address,
309 Koha::Plugins->call('after_hold_create', $hold);
314 =head2 CanBookBeReserved
316 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
317 if ($canReserve eq 'OK') { #We can reserve this Item! }
319 $params are passed directly through to CanItemBeReserved
321 See CanItemBeReserved() for possible return values.
325 sub CanBookBeReserved{
326 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
328 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
329 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
330 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
331 return { status =>'alreadypossession' };
334 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
335 #get items linked via host records
336 my @hostitems = get_hostitemnumbers_of($biblionumber);
338 push (@itemnumbers, @hostitems);
341 my $canReserve = { status => '' };
342 foreach my $itemnumber (@itemnumbers) {
343 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
344 return { status => 'OK' } if $canReserve->{status} eq 'OK';
349 =head2 CanItemBeReserved
351 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
352 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
355 'ignore_found_holds' - if true holds that have been trapped are not counted
356 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
357 current checkout against the high holds threshold
358 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
359 should not check if there are too many holds as we only csre about reservability
361 @RETURNS { status => OK }, if the Item can be reserved.
362 { status => ageRestricted }, if the Item is age restricted for this borrower.
363 { status => damaged }, if the Item is damaged.
364 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
365 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
366 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
367 { status => notReservable }, if holds on this item are not allowed
368 { status => libraryNotFound }, if given branchcode is not an existing library
369 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
370 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
371 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
375 sub CanItemBeReserved {
376 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
378 my $dbh = C4::Context->dbh;
379 my $ruleitemtype; # itemtype of the matching issuing rule
380 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
382 # we retrieve borrowers and items informations #
383 # item->{itype} will come for biblioitems if necessery
384 my $item = Koha::Items->find($itemnumber);
385 my $biblio = $item->biblio;
386 my $patron = Koha::Patrons->find( $borrowernumber );
387 my $borrower = $patron->unblessed;
389 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
390 return { status =>'damaged' }
392 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
394 # Check for the age restriction
395 my ( $ageRestriction, $daysToAgeRestriction ) =
396 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
397 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
399 # Check that the patron doesn't have an item level hold on this item already
400 return { status =>'itemAlreadyOnHold' }
401 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count() );
403 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
404 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
405 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
406 return { status =>'alreadypossession' };
409 my $controlbranch = C4::Context->preference('ReservesControlBranch');
412 SELECT count(*) AS count
414 LEFT JOIN items USING (itemnumber)
415 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
416 LEFT JOIN borrowers USING (borrowernumber)
417 WHERE borrowernumber = ?
421 my $branchfield = "reserves.branchcode";
423 if ( $controlbranch eq "ItemHomeLibrary" ) {
424 $branchfield = "items.homebranch";
425 $branchcode = $item->homebranch;
427 elsif ( $controlbranch eq "PatronLibrary" ) {
428 $branchfield = "borrowers.branchcode";
429 $branchcode = $borrower->{branchcode};
434 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
435 itemtype => $item->effective_itemtype,
436 categorycode => $borrower->{categorycode},
437 branchcode => $branchcode,
438 rule_name => 'reservesallowed',
441 $ruleitemtype = $reservesallowed->itemtype;
442 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
445 $ruleitemtype = undef;
448 my $rights = Koha::CirculationRules->get_effective_rules({
449 categorycode => $borrower->{'categorycode'},
450 itemtype => $item->effective_itemtype,
451 branchcode => $branchcode,
452 rules => ['holds_per_record','holds_per_day']
454 my $holds_per_record = $rights->{holds_per_record} // 1;
455 my $holds_per_day = $rights->{holds_per_day};
457 my $search_params = {
458 borrowernumber => $borrowernumber,
459 biblionumber => $item->biblionumber,
461 $search_params->{found} = undef if $params->{ignore_found_holds};
463 my $holds = Koha::Holds->search($search_params);
464 if ( defined $holds_per_record && $holds_per_record ne '' ){
465 if ( $holds_per_record == 0 ) {
466 return { status => "noReservesAllowed" };
468 if ( !$params->{ignore_hold_counts} && $holds->count() >= $holds_per_record ) {
469 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
473 my $today_holds = Koha::Holds->search({
474 borrowernumber => $borrowernumber,
475 reservedate => dt_from_string->date
478 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne ''
479 && $today_holds->count() >= $holds_per_day )
481 return { status => 'tooManyReservesToday', limit => $holds_per_day };
486 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
488 # If using item-level itypes, fall back to the record
489 # level itemtype if the hold has no associated item
491 C4::Context->preference('item-level_itypes')
492 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
493 : " AND biblioitems.itemtype = ?"
494 if defined $ruleitemtype;
496 my $sthcount = $dbh->prepare($querycount);
498 if ( defined $ruleitemtype ) {
499 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
502 $sthcount->execute( $borrowernumber, $branchcode );
505 my $reservecount = "0";
506 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
507 $reservecount = $rowcount->{count};
510 # we check if it's ok or not
511 if ( defined $allowedreserves && $allowedreserves ne '' ){
512 if( $allowedreserves == 0 ){
513 return { status => 'noReservesAllowed' };
515 if ( !$params->{ignore_hold_counts} && $reservecount >= $allowedreserves ) {
516 return { status => 'tooManyReserves', limit => $allowedreserves };
520 # Now we need to check hold limits by patron category
521 my $rule = Koha::CirculationRules->get_effective_rule(
523 categorycode => $borrower->{categorycode},
524 branchcode => $branchcode,
525 rule_name => 'max_holds',
528 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
529 my $total_holds_count = Koha::Holds->search(
531 borrowernumber => $borrower->{borrowernumber}
535 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
538 my $reserves_control_branch =
539 GetReservesControlBranch( $item->unblessed(), $borrower );
541 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
543 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
544 return { status => 'notReservable' };
547 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
548 && $borrower->{branchcode} ne $item->homebranch )
550 return { status => 'cannotReserveFromOtherBranches' };
553 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
554 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
555 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
556 return { status => 'branchNotInHoldGroup' };
560 # If reservecount is ok, we check item branch if IndependentBranches is ON
561 # and canreservefromotherbranches is OFF
562 if ( C4::Context->preference('IndependentBranches')
563 and !C4::Context->preference('canreservefromotherbranches') )
565 if ( $item->homebranch ne $borrower->{branchcode} ) {
566 return { status => 'cannotReserveFromOtherBranches' };
570 if ($pickup_branchcode) {
571 my $destination = Koha::Libraries->find({
572 branchcode => $pickup_branchcode,
575 unless ($destination) {
576 return { status => 'libraryNotFound' };
578 unless ($destination->pickup_location) {
579 return { status => 'libraryNotPickupLocation' };
581 unless ($item->can_be_transferred({ to => $destination })) {
582 return { status => 'cannotBeTransferred' };
584 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
585 return { status => 'pickupNotInHoldGroup' };
587 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
588 return { status => 'pickupNotInHoldGroup' };
592 return { status => 'OK' };
595 =head2 CanReserveBeCanceledFromOpac
597 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
599 returns 1 if reserve can be cancelled by user from OPAC.
600 First check if reserve belongs to user, next checks if reserve is not in
601 transfer or waiting status
605 sub CanReserveBeCanceledFromOpac {
606 my ($reserve_id, $borrowernumber) = @_;
608 return unless $reserve_id and $borrowernumber;
609 my $reserve = Koha::Holds->find($reserve_id) or return;
611 return 0 unless $reserve->borrowernumber == $borrowernumber;
612 return $reserve->is_cancelable_from_opac;
615 =head2 GetOtherReserves
617 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
619 Check queued list of this document and check if this document must be transferred
623 sub GetOtherReserves {
624 my ($itemnumber) = @_;
627 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
628 if ($checkreserves) {
629 my $item = Koha::Items->find($itemnumber);
630 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
631 $messages->{'transfert'} = $checkreserves->{'branchcode'};
632 #minus priorities of others reservs
633 ModReserveMinusPriority(
635 $checkreserves->{'reserve_id'},
638 #launch the subroutine dotransfer
639 C4::Items::ModItemTransfer(
641 $item->holdingbranch,
642 $checkreserves->{'branchcode'},
648 #step 2b : case of a reservation on the same branch, set the waiting status
650 $messages->{'waiting'} = 1;
651 ModReserveMinusPriority(
653 $checkreserves->{'reserve_id'},
655 ModReserveStatus($itemnumber,'W');
658 $nextreservinfo = $checkreserves;
661 return ( $messages, $nextreservinfo );
664 =head2 ChargeReserveFee
666 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
668 Charge the fee for a reserve (if $fee > 0)
672 sub ChargeReserveFee {
673 my ( $borrowernumber, $fee, $title ) = @_;
674 return if !$fee || $fee == 0; # the last test is needed to include 0.00
675 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
678 description => $title,
680 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
681 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
682 interface => C4::Context->interface,
683 invoice_type => undef,
692 $fee = GetReserveFee( $borrowernumber, $biblionumber );
694 Calculate the fee for a reserve (if applicable).
699 my ( $borrowernumber, $biblionumber ) = @_;
701 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
704 SELECT COUNT(*) FROM items
705 LEFT JOIN issues USING (itemnumber)
706 WHERE items.biblionumber=? AND issues.issue_id IS NULL
709 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
712 my $dbh = C4::Context->dbh;
713 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
714 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
715 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
716 # This is a reconstruction of the old code:
717 # Compare number of items with items issued, and optionally check holds
718 # If not all items are issued and there are no holds: charge no fee
719 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
720 my ( $notissued, $reserved );
721 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
724 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
725 ( $biblionumber, $borrowernumber ) );
726 $fee = 0 if $reserved == 0;
732 =head2 GetReserveStatus
734 $reservestatus = GetReserveStatus($itemnumber);
736 Takes an itemnumber and returns the status of the reserve placed on it.
737 If several reserves exist, the reserve with the lower priority is given.
741 ## FIXME: I don't think this does what it thinks it does.
742 ## It only ever checks the first reserve result, even though
743 ## multiple reserves for that bib can have the itemnumber set
744 ## the sub is only used once in the codebase.
745 sub GetReserveStatus {
746 my ($itemnumber) = @_;
748 my $dbh = C4::Context->dbh;
750 my ($sth, $found, $priority);
752 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
753 $sth->execute($itemnumber);
754 ($found, $priority) = $sth->fetchrow_array;
758 return 'Waiting' if $found eq 'W' and $priority == 0;
759 return 'Processing' if $found eq 'P';
760 return 'Finished' if $found eq 'F';
763 return 'Reserved' if defined $priority && $priority > 0;
765 return ''; # empty string here will remove need for checking undef, or less log lines
770 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
771 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
772 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
774 Find a book in the reserves.
776 C<$itemnumber> is the book's item number.
777 C<$lookahead> is the number of days to look in advance for future reserves.
779 As I understand it, C<&CheckReserves> looks for the given item in the
780 reserves. If it is found, that's a match, and C<$status> is set to
783 Otherwise, it finds the most important item in the reserves with the
784 same biblio number as this book (I'm not clear on this) and returns it
785 with C<$status> set to C<Reserved>.
787 C<&CheckReserves> returns a two-element list:
789 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
791 C<$reserve> is the reserve item that matched. It is a
792 reference-to-hash whose keys are mostly the fields of the reserves
793 table in the Koha database.
798 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
799 my $dbh = C4::Context->dbh;
802 if (C4::Context->preference('item-level_itypes')){
804 SELECT items.biblionumber,
805 items.biblioitemnumber,
806 itemtypes.notforloan,
807 items.notforloan AS itemnotforloan,
813 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
814 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
819 SELECT items.biblionumber,
820 items.biblioitemnumber,
821 itemtypes.notforloan,
822 items.notforloan AS itemnotforloan,
828 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
829 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
834 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
835 $sth->execute($item);
838 $sth = $dbh->prepare("$select WHERE barcode = ?");
839 $sth->execute($barcode);
841 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
842 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
843 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
845 return unless $itemnumber; # bail if we got nothing.
846 # if item is not for loan it cannot be reserved either.....
847 # except where items.notforloan < 0 : This indicates the item is holdable.
849 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
850 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
852 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
853 return if $dont_trap or $notforloan_per_itemtype;
855 # Find this item in the reserves
856 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
858 # $priority and $highest are used to find the most important item
859 # in the list returned by &_Findgroupreserve. (The lower $priority,
860 # the more important the item.)
861 # $highest is the most important item we've seen so far.
864 if (scalar @reserves) {
865 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
866 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
867 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
869 my $priority = 10000000;
870 foreach my $res (@reserves) {
871 if ($res->{'found'} && $res->{'found'} eq 'W') {
872 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
873 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
874 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
875 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
876 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
880 my $local_hold_match;
882 if ($LocalHoldsPriority) {
883 $patron = Koha::Patrons->find( $res->{borrowernumber} );
884 $item = Koha::Items->find($itemnumber);
886 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
887 my $local_holds_priority_item_branchcode =
888 $item->$LocalHoldsPriorityItemControl;
889 my $local_holds_priority_patron_branchcode =
890 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
892 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
893 ? $patron->branchcode
896 $local_holds_priority_item_branchcode eq
897 $local_holds_priority_patron_branchcode;
901 # See if this item is more important than what we've got so far
902 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
903 $item ||= Koha::Items->find($itemnumber);
904 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
905 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
906 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
907 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
908 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
909 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
910 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
911 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
912 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
913 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
914 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
915 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
916 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
917 $priority = $res->{'priority'};
919 last if $local_hold_match;
925 # If we get this far, then no exact match was found.
926 # We return the most important (i.e. next) reservation.
928 $highest->{'itemnumber'} = $item;
929 return ( "Reserved", $highest, \@reserves );
935 =head2 CancelExpiredReserves
937 CancelExpiredReserves();
939 Cancels all reserves with an expiration date from before today.
943 sub CancelExpiredReserves {
944 my $cancellation_reason = shift;
945 my $today = dt_from_string();
946 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
947 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
949 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
950 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
951 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
953 # FIXME To move to Koha::Holds->search_expired (?)
954 my $holds = Koha::Holds->search( $params );
956 while ( my $hold = $holds->next ) {
957 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
959 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
961 my $cancel_params = {};
962 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
963 if ( defined($hold->found) && $hold->found eq 'W' ) {
964 $cancel_params->{charge_cancel_fee} = 1;
966 $hold->cancel( $cancel_params );
970 =head2 AutoUnsuspendReserves
972 AutoUnsuspendReserves();
974 Unsuspends all suspended reserves with a suspend_until date from before today.
978 sub AutoUnsuspendReserves {
979 my $today = dt_from_string();
981 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
983 map { $_->resume() } @holds;
988 ModReserve({ rank => $rank,
989 reserve_id => $reserve_id,
990 branchcode => $branchcode
991 [, itemnumber => $itemnumber ]
992 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
995 Change a hold request's priority or cancel it.
997 C<$rank> specifies the effect of the change. If C<$rank>
998 is 'n', nothing happens. This corresponds to leaving a
999 request alone when changing its priority in the holds queue
1002 If C<$rank> is 'del', the hold request is cancelled.
1004 If C<$rank> is an integer greater than zero, the priority of
1005 the request is set to that value. Since priority != 0 means
1006 that the item is not waiting on the hold shelf, setting the
1007 priority to a non-zero value also sets the request's found
1008 status and waiting date to NULL.
1010 If the hold is 'found' (waiting, in-transit, processing) the
1011 only field that can be updated is the expiration date.
1013 The optional C<$itemnumber> parameter is used only when
1014 C<$rank> is a non-zero integer; if supplied, the itemnumber
1015 of the hold request is set accordingly; if omitted, the itemnumber
1018 B<FIXME:> Note that the forgoing can have the effect of causing
1019 item-level hold requests to turn into title-level requests. This
1020 will be fixed once reserves has separate columns for requested
1021 itemnumber and supplying itemnumber.
1026 my ( $params ) = @_;
1028 my $rank = $params->{'rank'};
1029 my $reserve_id = $params->{'reserve_id'};
1030 my $branchcode = $params->{'branchcode'};
1031 my $itemnumber = $params->{'itemnumber'};
1032 my $suspend_until = $params->{'suspend_until'};
1033 my $borrowernumber = $params->{'borrowernumber'};
1034 my $biblionumber = $params->{'biblionumber'};
1035 my $cancellation_reason = $params->{'cancellation_reason'};
1036 my $date = $params->{expirationdate};
1038 return if $rank eq "n";
1040 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1043 unless ( $reserve_id ) {
1044 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1045 return unless $holds->count; # FIXME Should raise an exception
1046 $hold = $holds->next;
1047 $reserve_id = $hold->reserve_id;
1050 $hold ||= Koha::Holds->find($reserve_id);
1052 if ( $rank eq "del" ) {
1053 $hold->cancel({ cancellation_reason => $cancellation_reason });
1055 elsif ($hold->found && $hold->priority eq '0' && $date) {
1056 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1057 if C4::Context->preference('HoldsLog');
1059 # The only column that can be updated for a found hold is the expiration date
1060 $hold->expirationdate(dt_from_string($date))->store();
1062 elsif ($rank =~ /^\d+/ and $rank > 0) {
1063 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1064 if C4::Context->preference('HoldsLog');
1068 branchcode => $branchcode,
1069 itemnumber => $itemnumber,
1071 waitingdate => undef
1073 if (exists $params->{reservedate}) {
1074 $properties->{reservedate} = $params->{reservedate} || undef;
1076 if (exists $params->{expirationdate}) {
1077 $properties->{expirationdate} = $params->{expirationdate} || undef;
1080 $hold->set($properties)->store();
1082 if ( defined( $suspend_until ) ) {
1083 if ( $suspend_until ) {
1084 $suspend_until = eval { dt_from_string( $suspend_until ) };
1085 $hold->suspend_hold( $suspend_until );
1087 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1088 # If the hold is not suspended, this does nothing.
1089 $hold->set( { suspend_until => undef } )->store();
1093 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1097 =head2 ModReserveFill
1099 &ModReserveFill($reserve);
1101 Fill a reserve. If I understand this correctly, this means that the
1102 reserved book has been found and given to the patron who reserved it.
1104 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1105 whose keys are fields from the reserves table in the Koha database.
1109 sub ModReserveFill {
1111 my $reserve_id = $res->{'reserve_id'};
1113 my $hold = Koha::Holds->find($reserve_id);
1114 # get the priority on this record....
1115 my $priority = $hold->priority;
1117 # update the hold statuses, no need to store it though, we will be deleting it anyway
1125 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1126 if C4::Context->preference('HoldsLog');
1128 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1129 Koha::Old::Hold->new( $hold->unblessed() )->store();
1133 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1134 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1135 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1138 # now fix the priority on the others (if the priority wasn't
1139 # already sorted!)....
1140 unless ( $priority == 0 ) {
1141 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1145 =head2 ModReserveStatus
1147 &ModReserveStatus($itemnumber, $newstatus);
1149 Update the reserve status for the active (priority=0) reserve.
1151 $itemnumber is the itemnumber the reserve is on
1153 $newstatus is the new status.
1157 sub ModReserveStatus {
1159 #first : check if we have a reservation for this item .
1160 my ($itemnumber, $newstatus) = @_;
1161 my $dbh = C4::Context->dbh;
1163 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1164 my $sth_set = $dbh->prepare($query);
1165 $sth_set->execute( $newstatus, $itemnumber );
1167 my $item = Koha::Items->find($itemnumber);
1168 if ( $item->location && $item->location eq 'CART'
1169 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1171 CartToShelf( $itemnumber );
1175 =head2 ModReserveAffect
1177 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1179 This function affect an item and a status for a given reserve, either fetched directly
1180 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1181 is given, only first reserve returned is affected, which is ok for anything but
1184 if $transferToDo is not set, then the status is set to "Waiting" as well.
1185 otherwise, a transfer is on the way, and the end of the transfer will
1186 take care of the waiting status
1188 This function also removes any entry of the hold in holds queue table.
1192 sub ModReserveAffect {
1193 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1194 my $dbh = C4::Context->dbh;
1196 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1197 # attached to $itemnumber
1198 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1199 $sth->execute($itemnumber);
1200 my ($biblionumber) = $sth->fetchrow;
1202 # get request - need to find out if item is already
1203 # waiting in order to not send duplicate hold filled notifications
1206 # Find hold by id if we have it
1207 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1208 # Find item level hold for this item if there is one
1209 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1210 # Find record level hold if there is no item level hold
1211 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1213 return unless $hold;
1215 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1217 $hold->itemnumber($itemnumber);
1219 if ($transferToDo) {
1220 $hold->set_transfer();
1221 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1222 && C4::Context->interface eq 'sip'
1223 && !$already_on_shelf) {
1224 $hold->set_processing();
1226 $hold->set_waiting($desk_id);
1227 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1228 # Complete transfer if one exists
1229 my $transfer = $hold->item->get_transfer;
1230 $transfer->receive if $transfer;
1233 _FixPriority( { biblionumber => $biblionumber } );
1234 my $item = Koha::Items->find($itemnumber);
1235 if ( $item->location && $item->location eq 'CART'
1236 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1237 CartToShelf( $itemnumber );
1240 my $std = $dbh->prepare(q{
1242 FROM tmp_holdsqueue q
1243 INNER JOIN hold_fill_targets t
1244 ON q.borrowernumber = t.borrowernumber
1245 AND q.biblionumber = t.biblionumber
1246 AND q.itemnumber = t.itemnumber
1247 AND q.item_level_request = t.item_level_request
1248 AND q.holdingbranch = t.source_branchcode
1249 WHERE t.reserve_id = ?
1251 $std->execute($hold->reserve_id);
1253 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->get_from_storage->unblessed) )
1254 if C4::Context->preference('HoldsLog');
1259 =head2 ModReserveCancelAll
1261 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1263 function to cancel reserv,check other reserves, and transfer document if it's necessary
1267 sub ModReserveCancelAll {
1270 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1272 #step 1 : cancel the reservation
1273 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1274 return unless $holds->count;
1275 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1277 #step 2 launch the subroutine of the others reserves
1278 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1280 return ( $messages, $nextreservinfo->{borrowernumber} );
1283 =head2 ModReserveMinusPriority
1285 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1287 Reduce the values of queued list
1291 sub ModReserveMinusPriority {
1292 my ( $itemnumber, $reserve_id ) = @_;
1294 #first step update the value of the first person on reserv
1295 my $dbh = C4::Context->dbh;
1298 SET priority = 0 , itemnumber = ?
1299 WHERE reserve_id = ?
1301 my $sth_upd = $dbh->prepare($query);
1302 $sth_upd->execute( $itemnumber, $reserve_id );
1303 # second step update all others reserves
1304 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1307 =head2 IsAvailableForItemLevelRequest
1309 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1311 Checks whether a given item record is available for an
1312 item-level hold request. An item is available if
1314 * it is not lost AND
1315 * it is not damaged AND
1316 * it is not withdrawn AND
1317 * a waiting or in transit reserve is placed on
1318 * does not have a not for loan value > 0
1320 Need to check the issuingrules onshelfholds column,
1321 if this is set items on the shelf can be placed on hold
1323 Note that IsAvailableForItemLevelRequest() does not
1324 check if the staff operator is authorized to place
1325 a request on the item - in particular,
1326 this routine does not check IndependentBranches
1327 and canreservefromotherbranches.
1329 Note also that this subroutine does not checks smart
1330 rules limits for item by reservesallowed/holds_per_record
1331 values, this complemented in calling code with calls and
1332 checks with CanItemBeReserved or CanBookBeReserved.
1336 sub IsAvailableForItemLevelRequest {
1339 my $pickup_branchcode = shift;
1340 # items_any_available is precalculated status passed from request.pl when set of items
1341 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1342 my $items_any_available = shift;
1344 my $dbh = C4::Context->dbh;
1345 # must check the notforloan setting of the itemtype
1346 # FIXME - a lot of places in the code do this
1347 # or something similar - need to be
1349 my $itemtype = $item->effective_itemtype;
1350 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1353 $notforloan_per_itemtype ||
1355 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1357 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1359 if ($pickup_branchcode) {
1360 my $destination = Koha::Libraries->find($pickup_branchcode);
1361 return 0 unless $destination;
1362 return 0 unless $destination->pickup_location;
1363 return 0 unless $item->can_be_transferred( { to => $destination } );
1364 my $reserves_control_branch =
1365 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1366 my $branchitemrule =
1367 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1368 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1369 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1372 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1374 if ( $on_shelf_holds == 1 ) {
1376 } elsif ( $on_shelf_holds == 2 ) {
1378 # if we have this param predefined from outer caller sub, we just need
1379 # to return it, so we saving from having loop inside other loop:
1380 return $items_any_available ? 0 : 1
1381 if defined $items_any_available;
1383 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1384 return $any_available ? 0 : 1;
1385 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1386 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1390 =head2 ItemsAnyAvailableAndNotRestricted
1392 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1394 This function checks all items for specified biblionumber (numeric) against patron (object)
1395 and returns true (1) if at least one item available for loan/check out/present/not held
1396 and also checks other parameters logic which not restricts item for hold at all (for ex.
1397 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1401 sub ItemsAnyAvailableAndNotRestricted {
1404 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1406 foreach my $i (@items) {
1407 my $reserves_control_branch =
1408 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1409 my $branchitemrule =
1410 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1411 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1413 # we can return (end the loop) when first one found:
1416 || $i->notforloan # items with non-zero notforloan cannot be checked out
1419 || IsItemOnHoldAndFound( $i->id )
1421 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1422 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1423 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1424 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1425 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1431 =head2 AlterPriority
1433 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1435 This function changes a reserve's priority up, down, to the top, or to the bottom.
1436 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1441 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1443 my $hold = Koha::Holds->find( $reserve_id );
1444 return unless $hold;
1446 if ( $hold->cancellationdate ) {
1447 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1451 if ( $where eq 'up' ) {
1452 return unless $prev_priority;
1453 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1454 } elsif ( $where eq 'down' ) {
1455 return unless $next_priority;
1456 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1457 } elsif ( $where eq 'top' ) {
1458 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1459 } elsif ( $where eq 'bottom' ) {
1460 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1463 # FIXME Should return the new priority
1466 =head2 ToggleLowestPriority
1468 ToggleLowestPriority( $borrowernumber, $biblionumber );
1470 This function sets the lowestPriority field to true if is false, and false if it is true.
1474 sub ToggleLowestPriority {
1475 my ( $reserve_id ) = @_;
1477 my $dbh = C4::Context->dbh;
1479 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1480 $sth->execute( $reserve_id );
1482 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1485 =head2 ToggleSuspend
1487 ToggleSuspend( $reserve_id );
1489 This function sets the suspend field to true if is false, and false if it is true.
1490 If the reserve is currently suspended with a suspend_until date, that date will
1491 be cleared when it is unsuspended.
1496 my ( $reserve_id, $suspend_until ) = @_;
1498 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1500 my $hold = Koha::Holds->find( $reserve_id );
1502 if ( $hold->is_suspended ) {
1505 $hold->suspend_hold( $suspend_until );
1512 borrowernumber => $borrowernumber,
1513 [ biblionumber => $biblionumber, ]
1514 [ suspend_until => $suspend_until, ]
1515 [ suspend => $suspend ]
1518 This function accepts a set of hash keys as its parameters.
1519 It requires either borrowernumber or biblionumber, or both.
1521 suspend_until is wholly optional.
1528 my $borrowernumber = $params{'borrowernumber'} || undef;
1529 my $biblionumber = $params{'biblionumber'} || undef;
1530 my $suspend_until = $params{'suspend_until'} || undef;
1531 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1533 $suspend_until = eval { dt_from_string($suspend_until) }
1534 if ( defined($suspend_until) );
1536 return unless ( $borrowernumber || $biblionumber );
1539 $params->{found} = undef;
1540 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1541 $params->{biblionumber} = $biblionumber if $biblionumber;
1543 my @holds = Koha::Holds->search($params);
1546 map { $_->suspend_hold($suspend_until) } @holds;
1549 map { $_->resume() } @holds;
1557 reserve_id => $reserve_id,
1559 [ignoreSetLowestRank => $ignoreSetLowestRank]
1564 _FixPriority({ biblionumber => $biblionumber});
1566 This routine adjusts the priority of a hold request and holds
1569 In the first form, where a reserve_id is passed, the priority of the
1570 hold is set to supplied rank, and other holds for that bib are adjusted
1571 accordingly. If the rank is "del", the hold is cancelled. If no rank
1572 is supplied, all of the holds on that bib have their priority adjusted
1573 as if the second form had been used.
1575 In the second form, where a biblionumber is passed, the holds on that
1576 bib (that are not captured) are sorted in order of increasing priority,
1577 then have reserves.priority set so that the first non-captured hold
1578 has its priority set to 1, the second non-captured hold has its priority
1579 set to 2, and so forth.
1581 In both cases, holds that have the lowestPriority flag on are have their
1582 priority adjusted to ensure that they remain at the end of the line.
1584 Note that the ignoreSetLowestRank parameter is meant to be used only
1585 when _FixPriority calls itself.
1590 my ( $params ) = @_;
1591 my $reserve_id = $params->{reserve_id};
1592 my $rank = $params->{rank} // '';
1593 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1594 my $biblionumber = $params->{biblionumber};
1596 my $dbh = C4::Context->dbh;
1599 if ( $reserve_id ) {
1600 $hold = Koha::Holds->find( $reserve_id );
1601 if (!defined $hold){
1602 # may have already been checked out and hold fulfilled
1603 $hold = Koha::Old::Holds->find( $reserve_id );
1605 return unless $hold;
1608 unless ( $biblionumber ) { # FIXME This is a very weird API
1609 $biblionumber = $hold->biblionumber;
1612 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1615 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1617 # make sure priority for waiting or in-transit items is 0
1621 WHERE reserve_id = ?
1622 AND found IN ('W', 'T', 'P')
1624 my $sth = $dbh->prepare($query);
1625 $sth->execute( $reserve_id );
1631 SELECT reserve_id, borrowernumber, reservedate
1633 WHERE biblionumber = ?
1634 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1635 ORDER BY priority ASC
1637 my $sth = $dbh->prepare($query);
1638 $sth->execute( $biblionumber );
1639 while ( my $line = $sth->fetchrow_hashref ) {
1640 push( @priority, $line );
1643 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1644 # To find the matching index
1646 my $key = -1; # to allow for 0 to be a valid result
1647 for ( $i = 0 ; $i < @priority ; $i++ ) {
1648 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1649 $key = $i; # save the index
1654 # if index exists in array then move it to new position
1655 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1656 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1657 my $moving_item = splice( @priority, $key, 1 );
1658 $new_rank = scalar @priority if $new_rank > scalar @priority;
1659 splice( @priority, $new_rank, 0, $moving_item );
1662 # now fix the priority on those that are left....
1666 WHERE reserve_id = ?
1668 $sth = $dbh->prepare($query);
1669 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1672 $priority[$j]->{'reserve_id'}
1676 unless ( $ignoreSetLowestRank ) {
1677 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1678 $sth->execute($biblionumber);
1679 while ( my $res = $sth->fetchrow_hashref() ) {
1681 reserve_id => $res->{'reserve_id'},
1683 ignoreSetLowestRank => 1
1689 =head2 _Findgroupreserve
1691 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1693 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1694 first match found. If neither, then we look for non-holds-queue based holds.
1695 Lookahead is the number of days to look in advance.
1697 C<&_Findgroupreserve> returns :
1698 C<@results> is an array of references-to-hash whose keys are mostly
1699 fields from the reserves table of the Koha database, plus
1700 C<biblioitemnumber>.
1702 This routine with either return:
1703 1 - Item specific holds from the holds queue
1704 2 - Title level holds from the holds queue
1705 3 - All holds for this biblionumber
1707 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1711 sub _Findgroupreserve {
1712 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1713 my $dbh = C4::Context->dbh;
1715 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1716 # check for exact targeted match
1717 my $item_level_target_query = qq{
1718 SELECT reserves.biblionumber AS biblionumber,
1719 reserves.borrowernumber AS borrowernumber,
1720 reserves.reservedate AS reservedate,
1721 reserves.branchcode AS branchcode,
1722 reserves.cancellationdate AS cancellationdate,
1723 reserves.found AS found,
1724 reserves.reservenotes AS reservenotes,
1725 reserves.priority AS priority,
1726 reserves.timestamp AS timestamp,
1727 biblioitems.biblioitemnumber AS biblioitemnumber,
1728 reserves.itemnumber AS itemnumber,
1729 reserves.reserve_id AS reserve_id,
1730 reserves.itemtype AS itemtype,
1731 reserves.non_priority AS non_priority
1733 JOIN biblioitems USING (biblionumber)
1734 JOIN hold_fill_targets USING (reserve_id)
1737 AND item_level_request = 1
1738 AND hold_fill_targets.itemnumber = ?
1739 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1743 my $sth = $dbh->prepare($item_level_target_query);
1744 $sth->execute($itemnumber, $lookahead||0);
1746 if ( my $data = $sth->fetchrow_hashref ) {
1747 push( @results, $data )
1748 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1750 return @results if @results;
1752 # check for title-level targeted match
1753 my $title_level_target_query = qq{
1754 SELECT reserves.biblionumber AS biblionumber,
1755 reserves.borrowernumber AS borrowernumber,
1756 reserves.reservedate AS reservedate,
1757 reserves.branchcode AS branchcode,
1758 reserves.cancellationdate AS cancellationdate,
1759 reserves.found AS found,
1760 reserves.reservenotes AS reservenotes,
1761 reserves.priority AS priority,
1762 reserves.timestamp AS timestamp,
1763 biblioitems.biblioitemnumber AS biblioitemnumber,
1764 reserves.itemnumber AS itemnumber,
1765 reserves.reserve_id AS reserve_id,
1766 reserves.itemtype AS itemtype,
1767 reserves.non_priority AS non_priority
1769 JOIN biblioitems USING (biblionumber)
1770 JOIN hold_fill_targets USING (reserve_id)
1773 AND item_level_request = 0
1774 AND hold_fill_targets.itemnumber = ?
1775 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1779 $sth = $dbh->prepare($title_level_target_query);
1780 $sth->execute($itemnumber, $lookahead||0);
1782 if ( my $data = $sth->fetchrow_hashref ) {
1783 push( @results, $data )
1784 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1786 return @results if @results;
1789 SELECT reserves.biblionumber AS biblionumber,
1790 reserves.borrowernumber AS borrowernumber,
1791 reserves.reservedate AS reservedate,
1792 reserves.waitingdate AS waitingdate,
1793 reserves.branchcode AS branchcode,
1794 reserves.cancellationdate AS cancellationdate,
1795 reserves.found AS found,
1796 reserves.reservenotes AS reservenotes,
1797 reserves.priority AS priority,
1798 reserves.timestamp AS timestamp,
1799 reserves.itemnumber AS itemnumber,
1800 reserves.reserve_id AS reserve_id,
1801 reserves.itemtype AS itemtype,
1802 reserves.non_priority AS non_priority
1804 WHERE reserves.biblionumber = ?
1805 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1806 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1810 $sth = $dbh->prepare($query);
1811 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1813 while ( my $data = $sth->fetchrow_hashref ) {
1814 push( @results, $data )
1815 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1820 =head2 _koha_notify_reserve
1822 _koha_notify_reserve( $hold->reserve_id );
1824 Sends a notification to the patron that their hold has been filled (through
1825 ModReserveAffect, _not_ ModReserveFill)
1827 The letter code for this notice may be found using the following query:
1829 select distinct letter_code
1830 from message_transports
1831 inner join message_attributes using (message_attribute_id)
1832 where message_name = 'Hold_Filled'
1834 This will probably sipmly be 'HOLD', but because it is defined in the database,
1835 it is subject to addition or change.
1837 The following tables are availalbe witin the notice:
1848 sub _koha_notify_reserve {
1849 my $reserve_id = shift;
1850 my $hold = Koha::Holds->find($reserve_id);
1851 my $borrowernumber = $hold->borrowernumber;
1853 my $patron = Koha::Patrons->find( $borrowernumber );
1855 # Try to get the borrower's email address
1856 my $to_address = $patron->notice_email_address;
1858 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1859 borrowernumber => $borrowernumber,
1860 message_name => 'Hold_Filled'
1863 my $library = Koha::Libraries->find( $hold->branchcode );
1864 my $admin_email_address = $library->from_email_address;
1865 $library = $library->unblessed;
1867 my %letter_params = (
1868 module => 'reserves',
1869 branchcode => $hold->branchcode,
1870 lang => $patron->lang,
1872 'branches' => $library,
1873 'borrowers' => $patron->unblessed,
1874 'biblio' => $hold->biblionumber,
1875 'biblioitems' => $hold->biblionumber,
1876 'reserves' => $hold->unblessed,
1877 'items' => $hold->itemnumber,
1881 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.
1882 my $send_notification = sub {
1883 my ( $mtt, $letter_code ) = (@_);
1884 return unless defined $letter_code;
1885 $letter_params{letter_code} = $letter_code;
1886 $letter_params{message_transport_type} = $mtt;
1887 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1889 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1893 C4::Letters::EnqueueLetter( {
1895 borrowernumber => $borrowernumber,
1896 from_address => $admin_email_address,
1897 message_transport_type => $mtt,
1901 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1903 ( $mtt eq 'email' and not $to_address ) # No email address
1904 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1905 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1906 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1909 &$send_notification($mtt, $letter_code);
1910 $notification_sent++;
1912 #Making sure that a print notification is sent if no other transport types can be utilized.
1913 if (! $notification_sent) {
1914 &$send_notification('print', 'HOLD');
1919 =head2 _ShiftPriorityByDateAndPriority
1921 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1923 This increments the priority of all reserves after the one
1924 with either the lowest date after C<$reservedate>
1925 or the lowest priority after C<$priority>.
1927 It effectively makes room for a new reserve to be inserted with a certain
1928 priority, which is returned.
1930 This is most useful when the reservedate can be set by the user. It allows
1931 the new reserve to be placed before other reserves that have a later
1932 reservedate. Since priority also is set by the form in reserves/request.pl
1933 the sub accounts for that too.
1937 sub _ShiftPriorityByDateAndPriority {
1938 my ( $biblio, $resdate, $new_priority ) = @_;
1940 my $dbh = C4::Context->dbh;
1941 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1942 my $sth = $dbh->prepare( $query );
1943 $sth->execute( $biblio, $resdate, $new_priority );
1944 my $min_priority = $sth->fetchrow;
1945 # if no such matches are found, $new_priority remains as original value
1946 $new_priority = $min_priority if ( $min_priority );
1948 # Shift the priority up by one; works in conjunction with the next SQL statement
1949 $query = "UPDATE reserves
1950 SET priority = priority+1
1951 WHERE biblionumber = ?
1952 AND borrowernumber = ?
1955 my $sth_update = $dbh->prepare( $query );
1957 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1958 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1959 $sth = $dbh->prepare( $query );
1960 $sth->execute( $new_priority, $biblio );
1961 while ( my $row = $sth->fetchrow_hashref ) {
1962 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1965 return $new_priority; # so the caller knows what priority they wind up receiving
1970 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1972 Use when checking out an item to handle reserves
1973 If $cancelreserve boolean is set to true, it will remove existing reserve
1978 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1980 $cancelreserve //= 0;
1982 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1983 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1986 my $biblionumber = $res->{biblionumber};
1988 if ($res->{borrowernumber} == $borrowernumber) {
1989 ModReserveFill($res);
1993 # The item is reserved by someone else.
1994 # Find this item in the reserves
1996 my $borr_res = Koha::Holds->search({
1997 borrowernumber => $borrowernumber,
1998 biblionumber => $biblionumber,
2000 order_by => 'priority'
2004 # The item is reserved by the current patron
2005 ModReserveFill($borr_res->unblessed);
2008 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2009 RevertWaitingStatus({ itemnumber => $itemnumber });
2011 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2012 my $hold = Koha::Holds->find( $res->{reserve_id} );
2020 MergeHolds($dbh,$to_biblio, $from_biblio);
2022 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2027 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2028 my $sth = $dbh->prepare(
2029 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2031 $sth->execute($from_biblio);
2032 if ( my $data = $sth->fetchrow_hashref() ) {
2034 # holds exist on old record, if not we don't need to do anything
2035 $sth = $dbh->prepare(
2036 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2037 $sth->execute( $to_biblio, $from_biblio );
2040 # don't reorder those already waiting
2042 $sth = $dbh->prepare(
2043 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2045 my $upd_sth = $dbh->prepare(
2046 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2047 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2049 $sth->execute( $to_biblio );
2051 while ( my $reserve = $sth->fetchrow_hashref() ) {
2053 $priority, $to_biblio,
2054 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2055 $reserve->{'itemnumber'}
2062 =head2 RevertWaitingStatus
2064 RevertWaitingStatus({ itemnumber => $itemnumber });
2066 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2068 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2069 item level hold, even if it was only a bibliolevel hold to
2070 begin with. This is because we can no longer know if a hold
2071 was item-level or bib-level after a hold has been set to
2076 sub RevertWaitingStatus {
2077 my ( $params ) = @_;
2078 my $itemnumber = $params->{'itemnumber'};
2080 return unless ( $itemnumber );
2082 my $dbh = C4::Context->dbh;
2084 ## Get the waiting reserve we want to revert
2085 my $hold = Koha::Holds->search(
2087 itemnumber => $itemnumber,
2088 found => { not => undef },
2092 ## Increment the priority of all other non-waiting
2093 ## reserves for this bib record
2094 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2095 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2097 ## Fix up the currently waiting reserve
2102 waitingdate => undef,
2103 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2107 _FixPriority( { biblionumber => $hold->biblionumber } );
2116 branchcode => $branchcode,
2117 borrowernumber => $borrowernumber,
2118 biblionumber => $biblionumber,
2119 [ itemnumber => $itemnumber, ]
2120 [ barcode => $barcode, ]
2124 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2126 The letter code will be HOLD_SLIP, and the following tables are
2127 available within the slip:
2140 my $branchcode = $args->{branchcode};
2141 my $reserve_id = $args->{reserve_id};
2143 my $hold = Koha::Holds->find($reserve_id);
2144 return unless $hold;
2146 my $patron = $hold->borrower;
2147 my $reserve = $hold->unblessed;
2149 return C4::Letters::GetPreparedLetter (
2150 module => 'circulation',
2151 letter_code => 'HOLD_SLIP',
2152 branchcode => $branchcode,
2153 lang => $patron->lang,
2155 'reserves' => $reserve,
2156 'branches' => $reserve->{branchcode},
2157 'borrowers' => $reserve->{borrowernumber},
2158 'biblio' => $reserve->{biblionumber},
2159 'biblioitems' => $reserve->{biblionumber},
2160 'items' => $reserve->{itemnumber},
2165 =head2 GetReservesControlBranch
2167 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2169 Return the branchcode to be used to determine which reserves
2170 policy applies to a transaction.
2172 C<$item> is a hashref for an item. Only 'homebranch' is used.
2174 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2178 sub GetReservesControlBranch {
2179 my ( $item, $borrower ) = @_;
2181 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2184 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2185 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2191 =head2 CalculatePriority
2193 my $p = CalculatePriority($biblionumber, $resdate);
2195 Calculate priority for a new reserve on biblionumber, placing it at
2196 the end of the line of all holds whose start date falls before
2197 the current system time and that are neither on the hold shelf
2200 The reserve date parameter is optional; if it is supplied, the
2201 priority is based on the set of holds whose start date falls before
2202 the parameter value.
2204 After calculation of this priority, it is recommended to call
2205 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2210 sub CalculatePriority {
2211 my ( $biblionumber, $resdate ) = @_;
2214 SELECT COUNT(*) FROM reserves
2215 WHERE biblionumber = ?
2217 AND (found IS NULL OR found = '')
2219 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2221 $sql.= ' AND ( reservedate <= ? )';
2224 $sql.= ' AND ( reservedate < NOW() )';
2226 my $dbh = C4::Context->dbh();
2227 my @row = $dbh->selectrow_array(
2230 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2233 return @row ? $row[0]+1 : 1;
2236 =head2 IsItemOnHoldAndFound
2238 my $bool = IsItemFoundHold( $itemnumber );
2240 Returns true if the item is currently on hold
2241 and that hold has a non-null found status ( W, T, etc. )
2245 sub IsItemOnHoldAndFound {
2246 my ($itemnumber) = @_;
2248 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2250 my $found = $rs->count(
2252 itemnumber => $itemnumber,
2253 found => { '!=' => undef }
2260 =head2 GetMaxPatronHoldsForRecord
2262 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2264 For multiple holds on a given record for a given patron, the max
2265 number of record level holds that a patron can be placed is the highest
2266 value of the holds_per_record rule for each item if the record for that
2267 patron. This subroutine finds and returns the highest holds_per_record
2268 rule value for a given patron id and record id.
2272 sub GetMaxPatronHoldsForRecord {
2273 my ( $borrowernumber, $biblionumber ) = @_;
2275 my $patron = Koha::Patrons->find($borrowernumber);
2276 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2278 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2280 my $categorycode = $patron->categorycode;
2282 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2285 foreach my $item (@items) {
2286 my $itemtype = $item->effective_itemtype();
2288 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2290 my $rule = Koha::CirculationRules->get_effective_rule({
2291 categorycode => $categorycode,
2292 itemtype => $itemtype,
2293 branchcode => $branchcode,
2294 rule_name => 'holds_per_record'
2296 my $holds_per_record = $rule ? $rule->rule_value : 0;
2297 $max = $holds_per_record if $holds_per_record > $max;
2305 Koha Development Team <http://koha-community.org/>