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::Biblio qw( GetMarcFromKohaField );
28 use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
30 use C4::Items qw( CartToShelf get_hostitemnumbers_of );
32 use C4::Log qw( logaction );
33 use C4::Members::Messaging;
35 use Koha::Account::Lines;
36 use Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue;
39 use Koha::Cache::Memory::Lite;
40 use Koha::CirculationRules;
42 use Koha::DateUtils qw( dt_from_string output_pref );
50 use Koha::Policy::Holds;
52 use List::MoreUtils qw( any );
56 C4::Reserves - Koha functions for dealing with reservation.
64 This modules provides somes functions to deal with reservations.
66 Reserves are stored in reserves table.
67 The following columns contains important values :
68 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
69 =0 : then the reserve is being dealed
70 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
71 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
72 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
73 F(inished) : the reserve has been completed, and is done
74 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
75 by librarian before notice is send and status changed to waiting.
76 Applicable only if HoldsNeedProcessingSIP system preference is set.
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
100 our (@ISA, @EXPORT_OK);
116 ModReserveMinusPriority
122 CanReserveBeCanceledFromOpac
123 CancelExpiredReserves
125 AutoUnsuspendReserves
127 IsAvailableForItemLevelRequest
128 ItemsAnyAvailableAndNotRestricted
141 GetMaxPatronHoldsForRecord
153 branchcode => $branchcode,
154 borrowernumber => $borrowernumber,
155 biblionumber => $biblionumber,
156 priority => $priority,
157 reservation_date => $reservation_date,
158 expiration_date => $expiration_date,
161 itemnumber => $itemnumber,
163 itemtype => $itemtype,
164 item_group_id => $item_group_id
168 Adds reserve and generates HOLDPLACED message and HOLDPLACED_PATRON message.
170 The following tables are available witin the HOLDPLACED message:
179 The following tables are available within the HOLDPLACED_PATRON message:
188 my $branch = $params->{branchcode};
189 my $borrowernumber = $params->{borrowernumber};
190 my $biblionumber = $params->{biblionumber};
191 my $priority = $params->{priority};
192 my $resdate = $params->{reservation_date};
193 my $patron_expiration_date = $params->{expiration_date};
194 my $notes = $params->{notes};
195 my $title = $params->{title};
196 my $checkitem = $params->{itemnumber};
197 my $found = $params->{found};
198 my $itemtype = $params->{itemtype};
199 my $non_priority = $params->{non_priority};
200 my $item_group_id = $params->{item_group_id};
202 $resdate ||= dt_from_string;
204 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
205 # of the document, we force the value $priority and $found .
206 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
207 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
210 # If item is already checked out, it cannot be set waiting
213 # The item can't be waiting if it needs a transfer
214 && $item->holdingbranch eq $branch
216 # Similarly, if in transit it can't be waiting
217 && !$item->get_transfer
219 # If we can't hold damaged items, and it is damaged, it can't be waiting
220 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
222 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
223 && !$item->current_holds->count )
229 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
230 # Make room in reserves for this if passed a priority
231 $priority = _ShiftPriority( $biblionumber, $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 item_group_id => $item_group_id,
250 reservedate => $resdate,
251 branchcode => $branch,
252 priority => $priority,
253 reservenotes => $notes,
254 itemnumber => $checkitem,
256 waitingdate => $waitingdate,
257 patron_expiration_date => $patron_expiration_date,
258 itemtype => $itemtype,
259 item_level_hold => $checkitem ? 1 : 0,
260 non_priority => $non_priority ? 1 : 0,
263 $hold->set_waiting() if $found && $found eq 'W';
265 # record patron activity
266 $hold->patron->update_lastseen('hold');
268 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
269 if C4::Context->preference('HoldsLog');
271 my $reserve_id = $hold->id();
273 # add a reserve fee if needed
274 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
275 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
276 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
279 _FixPriority({ biblionumber => $biblionumber});
281 # Send e-mail to librarian if syspref is active
282 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
283 my $patron = $hold->patron;
284 my $library = $patron->library;
285 if ( my $letter = C4::Letters::GetPreparedLetter (
286 module => 'reserves',
287 letter_code => 'HOLDPLACED',
288 branchcode => $branch,
289 lang => $patron->lang,
291 'branches' => $library->unblessed,
292 'borrowers' => $patron->unblessed,
293 'biblio' => $biblionumber,
294 'biblioitems' => $biblionumber,
295 'items' => $checkitem,
296 'reserves' => $hold->unblessed,
300 my $branch_email_address = $library->inbound_email_address;
302 C4::Letters::EnqueueLetter(
305 borrowernumber => $borrowernumber,
306 message_transport_type => 'email',
307 to_address => $branch_email_address,
313 # Send email to patron if syspref is active
314 if ( C4::Context->preference("EmailPatronWhenHoldIsPlaced") ) {
315 my $patron = $hold->patron;
317 my $letter = C4::Letters::GetPreparedLetter(
318 module => 'reserves',
319 letter_code => 'HOLDPLACED_PATRON',
320 branchcode => $branch,
321 lang => $patron->lang,
323 borrowers => $patron->unblessed,
324 reserves => $hold->unblessed,
329 C4::Letters::EnqueueLetter(
332 borrowernumber => $borrowernumber,
333 message_transport_type => 'email',
334 to_address => $patron->notice_email_address,
340 Koha::Plugins->call('after_hold_create', $hold);
345 payload => { hold => $hold->get_from_storage }
349 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
351 biblio_ids => [ $biblionumber ]
353 ) if C4::Context->preference('RealTimeHoldsQueue');
358 =head2 CanBookBeReserved
360 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
361 if ($canReserve eq 'OK') { #We can reserve this Item! }
363 $params are passed directly through to CanItemBeReserved
365 See CanItemBeReserved() for possible return values.
369 sub CanBookBeReserved{
370 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
372 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
373 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
374 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
375 return { status =>'alreadypossession' };
378 if ( $params->{itemtype} ) {
380 # biblio-level, item type-contrained
381 my $patron = Koha::Patrons->find($borrowernumber);
382 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
384 itemtype => $params->{itemtype},
385 categorycode => $patron->categorycode,
386 branchcode => $pickup_branchcode,
387 rule_name => 'reservesallowed',
391 $reservesallowed = ( $reservesallowed eq '' ) ? undef : $reservesallowed;
393 my $count = $patron->holds->search(
396 { 'me.itemtype' => $params->{itemtype} },
397 { 'item.itype' => $params->{itemtype} }
405 return { status => '' }
406 if defined $reservesallowed and $reservesallowed < $count + 1;
410 #get items linked via host records
411 my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
412 if (@hostitemnumbers){
413 $items = Koha::Items->search({
415 biblionumber => $biblionumber,
416 itemnumber => { -in => @hostitemnumbers }
420 $items = Koha::Items->search({ biblionumber => $biblionumber});
423 my $canReserve = { status => '' };
424 my $patron = Koha::Patrons->find( $borrowernumber );
425 while ( my $item = $items->next ) {
426 $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
427 return { status => 'OK' } if $canReserve->{status} eq 'OK';
432 =head2 CanItemBeReserved
434 $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
435 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
438 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
439 should not check if there are too many holds as we only care about reservability
441 @RETURNS { status => OK }, if the Item can be reserved.
442 { status => ageRestricted }, if the Item is age restricted for this borrower.
443 { status => damaged }, if the Item is damaged.
444 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
445 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
446 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
447 { status => notReservable }, if holds on this item are not allowed
448 { status => libraryNotFound }, if given branchcode is not an existing library
449 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
450 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
451 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
452 { status => recall }, if the borrower has already placed a recall on this item
456 our $CanItemBeReserved_cache_key;
459 my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
460 $memory_cache->set_in_cache( $CanItemBeReserved_cache_key, $return );
464 sub CanItemBeReserved {
465 my ( $patron, $item, $pickup_branchcode, $params ) = @_;
467 my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
468 $CanItemBeReserved_cache_key = sprintf "Hold_CanItemBeReserved:%s:%s:%s", $patron->borrowernumber, $item->itemnumber, $pickup_branchcode || "";
469 if ( $params->{get_from_cache} ) {
470 my $cached = $memory_cache->get_from_cache($CanItemBeReserved_cache_key);
471 return $cached if $cached;
474 my $dbh = C4::Context->dbh;
475 my $ruleitemtype; # itemtype of the matching issuing rule
476 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
478 # We check item branch if IndependentBranches is ON
479 # and canreservefromotherbranches is OFF
480 if ( C4::Context->preference('IndependentBranches')
481 and !C4::Context->preference('canreservefromotherbranches') )
483 if ( $item->homebranch ne $patron->branchcode ) {
484 return _cache { status => 'cannotReserveFromOtherBranches' };
488 # we retrieve borrowers and items informations #
489 # item->{itype} will come for biblioitems if necessery
490 my $borrower = $patron->unblessed;
492 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
493 return _cache { status =>'damaged' }
495 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
497 if( GetMarcFromKohaField('biblioitems.agerestriction') ){
498 my $biblio = $item->biblio;
499 # Check for the age restriction
500 my ( $ageRestriction, $daysToAgeRestriction ) =
501 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
502 return _cache { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
505 # Check that the patron doesn't have an item level hold on this item already
506 return _cache { status =>'itemAlreadyOnHold' }
507 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
509 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
510 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
511 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
512 return _cache { status =>'alreadypossession' };
515 # check if a recall exists on this item from this borrower
516 return _cache { status => 'recall' }
517 if $patron->recalls->filter_by_current->search({ item_id => $item->itemnumber })->count;
519 my $controlbranch = C4::Context->preference('ReservesControlBranch');
521 my $reserves_control_branch;
522 my $branchfield = "reserves.branchcode";
524 if ( $controlbranch eq "ItemHomeLibrary" ) {
525 $branchfield = "items.homebranch";
526 $reserves_control_branch = $item->homebranch;
528 elsif ( $controlbranch eq "PatronLibrary" ) {
529 $branchfield = "borrowers.branchcode";
530 $reserves_control_branch = $borrower->{branchcode};
535 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
536 itemtype => $item->effective_itemtype,
537 categorycode => $borrower->{categorycode},
538 branchcode => $reserves_control_branch,
539 rule_name => 'reservesallowed',
542 $ruleitemtype = $reservesallowed->itemtype;
543 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
546 $ruleitemtype = undef;
549 my $rights = Koha::CirculationRules->get_effective_rules({
550 categorycode => $borrower->{'categorycode'},
551 itemtype => $item->effective_itemtype,
552 branchcode => $reserves_control_branch,
553 rules => ['holds_per_record','holds_per_day']
555 my $holds_per_record = $rights->{holds_per_record} // 1;
556 my $holds_per_day = $rights->{holds_per_day};
558 if ( defined $holds_per_record && $holds_per_record ne '' ){
559 if ( $holds_per_record == 0 ) {
560 return _cache { status => "noReservesAllowed" };
562 if ( !$params->{ignore_hold_counts} ) {
563 my $search_params = {
564 borrowernumber => $patron->borrowernumber,
565 biblionumber => $item->biblionumber,
567 my $holds = Koha::Holds->search($search_params);
568 return _cache { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record;
572 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '')
574 my $today_holds = Koha::Holds->search({
575 borrowernumber => $patron->borrowernumber,
576 reservedate => dt_from_string->date
578 return _cache { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day;
581 # we check if it's ok or not
582 if ( defined $allowedreserves && $allowedreserves ne '' ){
583 if( $allowedreserves == 0 ){
584 return _cache { status => 'noReservesAllowed' };
586 if ( !$params->{ignore_hold_counts} ) {
589 SELECT count(*) AS count
591 LEFT JOIN items USING (itemnumber)
592 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
593 LEFT JOIN borrowers USING (borrowernumber)
594 WHERE borrowernumber = ?
596 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
598 # If using item-level itypes, fall back to the record
599 # level itemtype if the hold has no associated item
600 if ( defined $ruleitemtype ) {
601 if ( C4::Context->preference('item-level_itypes') ) {
603 AND ( COALESCE( items.itype, biblioitems.itemtype ) = ?
604 OR reserves.itemtype = ? )
609 AND ( biblioitems.itemtype = ?
610 OR reserves.itemtype = ? )
615 my $sthcount = $dbh->prepare($querycount);
617 if ( defined $ruleitemtype ) {
618 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype, $ruleitemtype );
621 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch );
624 my $reservecount = "0";
625 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
626 $reservecount = $rowcount->{count};
629 return _cache { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves;
633 # Now we need to check hold limits by patron category
634 my $rule = Koha::CirculationRules->get_effective_rule(
636 categorycode => $patron->categorycode,
637 branchcode => $reserves_control_branch,
638 rule_name => 'max_holds',
641 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
642 my $total_holds_count = Koha::Holds->search(
644 borrowernumber => $patron->borrowernumber
648 return _cache { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
652 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
654 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
655 return _cache { status => 'notReservable' };
658 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
659 && $borrower->{branchcode} ne $item->homebranch )
661 return _cache { status => 'cannotReserveFromOtherBranches' };
664 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
665 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
666 if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
667 return _cache { status => 'branchNotInHoldGroup' };
671 if ($pickup_branchcode) {
672 my $destination = Koha::Libraries->find({
673 branchcode => $pickup_branchcode,
676 unless ($destination) {
677 return _cache { status => 'libraryNotFound' };
679 unless ($destination->pickup_location) {
680 return _cache { status => 'libraryNotPickupLocation' };
682 unless ($item->can_be_transferred({ to => $destination })) {
683 return _cache { status => 'cannotBeTransferred' };
685 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
686 return _cache { status => 'pickupNotInHoldGroup' };
688 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
689 return _cache { status => 'pickupNotInHoldGroup' };
693 return _cache { status => 'OK' };
696 =head2 CanReserveBeCanceledFromOpac
698 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
700 returns 1 if reserve can be cancelled by user from OPAC.
701 First check if reserve belongs to user, next checks if reserve is not in
702 transfer or waiting status
706 sub CanReserveBeCanceledFromOpac {
707 my ($reserve_id, $borrowernumber) = @_;
709 return unless $reserve_id and $borrowernumber;
710 my $reserve = Koha::Holds->find($reserve_id) or return;
712 return 0 unless $reserve->borrowernumber == $borrowernumber;
713 return $reserve->is_cancelable_from_opac;
716 =head2 ChargeReserveFee
718 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
720 Charge the fee for a reserve (if $fee > 0)
724 sub ChargeReserveFee {
725 my ( $borrowernumber, $fee, $title ) = @_;
726 return if !$fee || $fee == 0; # the last test is needed to include 0.00
727 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
730 description => $title,
732 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
733 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
734 interface => C4::Context->interface,
735 invoice_type => undef,
744 $fee = GetReserveFee( $borrowernumber, $biblionumber );
746 Calculate the fee for a reserve (if applicable).
751 my ( $borrowernumber, $biblionumber ) = @_;
753 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
756 SELECT COUNT(*) FROM items
757 LEFT JOIN issues USING (itemnumber)
758 WHERE items.biblionumber=? AND issues.issue_id IS NULL
761 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
764 my $dbh = C4::Context->dbh;
765 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
767 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
768 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
769 # This is a reconstruction of the old code:
770 # Compare number of items with items issued, and optionally check holds
771 # If not all items are issued and there are no holds: charge no fee
772 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
773 my ( $notissued, $reserved );
774 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
776 if( $notissued == 0 ) {
777 # all items are issued
778 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
779 ( $biblionumber, $borrowernumber ) );
780 $fee = 0 if $reserved == 0;
788 =head2 GetReserveStatus
790 $reservestatus = GetReserveStatus($itemnumber);
792 Takes an itemnumber and returns the status of the reserve placed on it.
793 If several reserves exist, the reserve with the lower priority is given.
797 ## FIXME: I don't think this does what it thinks it does.
798 ## It only ever checks the first reserve result, even though
799 ## multiple reserves for that bib can have the itemnumber set
800 ## the sub is only used once in the codebase.
801 sub GetReserveStatus {
802 my ($itemnumber) = @_;
804 my $dbh = C4::Context->dbh;
806 my ($sth, $found, $priority);
808 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
809 $sth->execute($itemnumber);
810 ($found, $priority) = $sth->fetchrow_array;
814 return 'Waiting' if $found eq 'W' and $priority == 0;
815 return 'Processing' if $found eq 'P';
816 return 'Finished' if $found eq 'F';
819 return 'Reserved' if defined $priority && $priority > 0;
821 return ''; # empty string here will remove need for checking undef, or less log lines
826 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($item);
827 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($item, $lookahead);
829 Find a book in the reserves.
831 C<$item> is the book's item.
832 C<$lookahead> is the number of days to look in advance for future reserves.
834 As I understand it, C<&CheckReserves> looks for the given item in the
835 reserves. If it is found, that's a match, and C<$status> is set to
838 Otherwise, it finds the most important item in the reserves with the
839 same biblio number as this book (I'm not clear on this) and returns it
840 with C<$status> set to C<Reserved>.
842 C<&CheckReserves> returns a two-element list:
844 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
846 C<$reserve> is the reserve item that matched. It is a
847 reference-to-hash whose keys are mostly the fields of the reserves
848 table in the Koha database.
853 my ( $item, $lookahead_days, $ignore_borrowers ) = @_;
854 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
856 return unless $item; # bail if we got nothing.
858 return if ( $item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
860 # if item is not for loan it cannot be reserved either.....
861 # except where items.notforloan < 0 : This indicates the item is holdable.
863 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
864 return if grep { $_ eq $item->notforloan } @SkipHoldTrapOnNotForLoanValue;
866 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? $item->notforloan > 0 : $item->notforloan;
868 my $item_type = $item->effective_itemtype;
870 return if Koha::ItemTypes->find( $item_type )->notforloan;
877 # Find this item in the reserves
878 my @reserves = _Findgroupreserve( $item->biblionumber, $item->itemnumber, $lookahead_days, $ignore_borrowers);
880 # $priority and $highest are used to find the most important item
881 # in the list returned by &_Findgroupreserve. (The lower $priority,
882 # the more important the item.)
883 # $highest is the most important item we've seen so far.
886 if (scalar @reserves) {
887 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
888 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
889 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
890 my $priority = 10000000;
892 foreach my $res (@reserves) {
893 if ($res->{'found'} && $res->{'found'} eq 'W') {
894 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
895 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
896 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
897 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
898 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
901 my $local_hold_match;
903 if ($LocalHoldsPriority) {
904 $patron = Koha::Patrons->find( $res->{borrowernumber} );
906 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
907 my $local_holds_priority_item_branchcode =
908 $item->$LocalHoldsPriorityItemControl;
909 my $local_holds_priority_patron_branchcode =
910 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
912 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
913 ? $patron->branchcode
916 $local_holds_priority_item_branchcode eq
917 $local_holds_priority_patron_branchcode;
921 # See if this item is more important than what we've got so far
922 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
923 next if $res->{item_group_id} && ( !$item->item_group || $item->item_group->id != $res->{item_group_id} );
924 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
925 $patron //= Koha::Patrons->find( $res->{borrowernumber} );
926 my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron );
927 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
928 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
929 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
930 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
931 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
932 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
933 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
934 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
935 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
936 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
937 $priority = $res->{'priority'};
939 last if $local_hold_match;
945 # If we get this far, then no exact match was found.
946 # We return the most important (i.e. next) reservation.
948 $highest->{'itemnumber'} = $item->itemnumber;
949 return ( "Reserved", $highest, \@reserves );
955 =head2 CancelExpiredReserves
957 CancelExpiredReserves();
959 Cancels all reserves with an expiration date from before today.
963 sub CancelExpiredReserves {
964 my $cancellation_reason = shift;
965 my $today = dt_from_string();
966 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
967 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
969 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
972 { expirationdate => { '<', $dtf->format_date($today) } },
973 { patron_expiration_date => { '<' => $dtf->format_date($today) } }
977 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
979 # FIXME To move to Koha::Holds->search_expired (?)
980 my $holds = Koha::Holds->search( $params );
982 while ( my $hold = $holds->next ) {
983 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
985 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
987 my $cancel_params = {};
988 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
989 if ( defined($hold->found) && $hold->found eq 'W' ) {
990 $cancel_params->{charge_cancel_fee} = 1;
992 $cancel_params->{autofill} = C4::Context->preference('ExpireReservesAutoFill');
993 $hold->cancel( $cancel_params );
997 =head2 AutoUnsuspendReserves
999 AutoUnsuspendReserves();
1001 Unsuspends all suspended reserves with a suspend_until date from before today.
1005 sub AutoUnsuspendReserves {
1006 my $today = dt_from_string();
1008 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
1010 map { $_->resume() } @holds;
1015 ModReserve({ rank => $rank,
1016 reserve_id => $reserve_id,
1017 branchcode => $branchcode
1018 [, itemnumber => $itemnumber ]
1019 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1022 Change a hold request's priority or cancel it.
1024 C<$rank> specifies the effect of the change. If C<$rank>
1025 is 'n', nothing happens. This corresponds to leaving a
1026 request alone when changing its priority in the holds queue
1029 If C<$rank> is 'del', the hold request is cancelled.
1031 If C<$rank> is an integer greater than zero, the priority of
1032 the request is set to that value. Since priority != 0 means
1033 that the item is not waiting on the hold shelf, setting the
1034 priority to a non-zero value also sets the request's found
1035 status and waiting date to NULL.
1037 If the hold is 'found' (waiting, in-transit, processing) the
1038 only field that can be updated is the expiration date.
1040 The optional C<$itemnumber> parameter is used only when
1041 C<$rank> is a non-zero integer; if supplied, the itemnumber
1042 of the hold request is set accordingly; if omitted, the itemnumber
1045 B<FIXME:> Note that the forgoing can have the effect of causing
1046 item-level hold requests to turn into title-level requests. This
1047 will be fixed once reserves has separate columns for requested
1048 itemnumber and supplying itemnumber.
1053 my ( $params ) = @_;
1055 my $rank = $params->{'rank'};
1056 my $reserve_id = $params->{'reserve_id'};
1057 my $branchcode = $params->{'branchcode'};
1058 my $itemnumber = $params->{'itemnumber'};
1059 my $suspend_until = $params->{'suspend_until'};
1060 my $borrowernumber = $params->{'borrowernumber'};
1061 my $biblionumber = $params->{'biblionumber'};
1062 my $cancellation_reason = $params->{'cancellation_reason'};
1063 my $date = $params->{expirationdate};
1065 return if defined $rank && $rank eq "n";
1067 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1070 unless ( $reserve_id ) {
1071 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1072 return unless $holds->count; # FIXME Should raise an exception
1073 $hold = $holds->next;
1074 $reserve_id = $hold->reserve_id;
1077 $hold ||= Koha::Holds->find($reserve_id);
1079 # FIXME Other calls may fail
1080 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1082 my $original = C4::Context->preference('HoldsLog') ? $hold->unblessed : undef;
1084 if ( $rank eq "del" ) {
1085 $hold->cancel({ cancellation_reason => $cancellation_reason });
1087 elsif ($hold->found && $hold->priority eq '0' && $date) {
1089 # The only column that can be updated for a found hold is the expiration date
1090 $hold->expirationdate($date)->store();
1092 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold, undef, $original )
1093 if C4::Context->preference('HoldsLog');
1095 elsif ($rank =~ /^\d+/ and $rank > 0) {
1098 branchcode => $branchcode,
1099 itemnumber => $itemnumber,
1101 waitingdate => undef
1103 if (exists $params->{reservedate}) {
1104 $properties->{reservedate} = $params->{reservedate} || undef;
1106 if (exists $params->{expirationdate}) {
1107 $properties->{expirationdate} = $params->{expirationdate} || undef;
1110 $hold->set($properties)->store();
1112 if ( defined( $suspend_until ) ) {
1113 if ( $suspend_until ) {
1114 $hold->suspend_hold( $suspend_until );
1116 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1117 # If the hold is not suspended, this does nothing.
1118 $hold->set( { suspend_until => undef } )->store();
1122 _FixPriority( { reserve_id => $reserve_id, rank => $rank } );
1124 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold, undef, $original )
1125 if C4::Context->preference('HoldsLog');
1129 =head2 ModReserveStatus
1131 &ModReserveStatus($itemnumber, $newstatus);
1133 Update the reserve status for the active (priority=0) reserve.
1135 $itemnumber is the itemnumber the reserve is on
1137 $newstatus is the new status.
1141 sub ModReserveStatus {
1143 #first : check if we have a reservation for this item .
1144 my ($itemnumber, $newstatus) = @_;
1145 my $dbh = C4::Context->dbh;
1147 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1148 my $sth_set = $dbh->prepare($query);
1149 $sth_set->execute( $newstatus, $itemnumber );
1151 my $item = Koha::Items->find($itemnumber);
1152 if ( $item->location && $item->location eq 'CART'
1153 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1155 CartToShelf( $itemnumber );
1159 =head2 ModReserveAffect
1161 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id, $notify_library);
1163 This function affect an item and a status for a given reserve, either fetched directly
1164 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1165 is given, only first reserve returned is affected, which is ok for anything but
1168 if $transferToDo is not set, then the status is set to "Waiting" as well.
1169 otherwise, a transfer is on the way, and the end of the transfer will
1170 take care of the waiting status
1172 This function also removes any entry of the hold in holds queue table.
1176 sub ModReserveAffect {
1177 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id, $notify_library ) = @_;
1178 my $dbh = C4::Context->dbh;
1180 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1181 # attached to $itemnumber
1182 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1183 $sth->execute($itemnumber);
1184 my ($biblionumber) = $sth->fetchrow;
1186 # get request - need to find out if item is already
1187 # waiting in order to not send duplicate hold filled notifications
1190 # Find hold by id if we have it
1191 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1192 # Find item level hold for this item if there is one
1193 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1194 # Find record level hold if there is no item level hold
1195 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1197 return unless $hold;
1199 my $original = $hold->unblessed;
1201 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1203 $hold->itemnumber($itemnumber);
1205 if ($transferToDo) {
1206 $hold->set_transfer();
1207 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1208 && C4::Context->interface eq 'sip'
1209 && !$already_on_shelf) {
1210 $hold->set_processing();
1212 $hold->set_waiting($desk_id);
1213 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1214 # Complete transfer if one exists
1215 my $transfer = $hold->item->get_transfer;
1216 $transfer->receive if $transfer;
1219 _koha_notify_hold_changed( $hold ) if $notify_library;
1221 _FixPriority( { biblionumber => $biblionumber } );
1222 my $item = Koha::Items->find($itemnumber);
1223 if ( $item->location && $item->location eq 'CART'
1224 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1225 CartToShelf( $itemnumber );
1228 my $std = $dbh->prepare(q{
1230 FROM tmp_holdsqueue q
1231 INNER JOIN hold_fill_targets t
1232 ON q.borrowernumber = t.borrowernumber
1233 AND q.biblionumber = t.biblionumber
1234 AND q.itemnumber = t.itemnumber
1235 AND q.item_level_request = t.item_level_request
1236 AND q.holdingbranch = t.source_branchcode
1237 WHERE t.reserve_id = ?
1239 $std->execute($hold->reserve_id);
1241 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold, undef, $original )
1242 if C4::Context->preference('HoldsLog');
1247 =head2 ModReserveCancelAll
1249 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1251 function to cancel reserve and check other reserves
1255 sub ModReserveCancelAll {
1258 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1259 my $item = Koha::Items->find($itemnumber);
1261 #step 1 : cancel the reservation
1262 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1263 return unless $holds->count;
1264 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1266 #step 2 check for other reserves on this item
1267 ( undef, $nextreservinfo, undef ) = CheckReserves($item);
1269 if ($nextreservinfo) {
1270 if( $item->holdingbranch ne $nextreservinfo->{'branchcode'} ) {
1271 $messages->{'transfert'} = $nextreservinfo->{'branchcode'};
1274 $messages->{'waiting'} = 1;
1278 return ( $messages, $nextreservinfo->{borrowernumber} );
1281 =head2 ModReserveMinusPriority
1283 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1285 Reduce the values of queued list
1289 sub ModReserveMinusPriority {
1290 my ( $itemnumber, $reserve_id ) = @_;
1292 #first step update the value of the first person on reserv
1293 my $dbh = C4::Context->dbh;
1296 SET priority = 0 , itemnumber = ?
1297 WHERE reserve_id = ?
1299 my $sth_upd = $dbh->prepare($query);
1300 $sth_upd->execute( $itemnumber, $reserve_id );
1301 # second step update all others reserves
1302 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1305 =head2 IsAvailableForItemLevelRequest
1307 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1309 Checks whether a given item record is available for an
1310 item-level hold request. An item is available if
1312 * it is not lost AND
1313 * it is not damaged AND
1314 * it is not withdrawn AND
1315 * a waiting or in transit reserve is placed on
1316 * does not have a not for loan value > 0
1318 Need to check the issuingrules onshelfholds column,
1319 if this is set items on the shelf can be placed on hold
1321 Note that IsAvailableForItemLevelRequest() does not
1322 check if the staff operator is authorized to place
1323 a request on the item - in particular,
1324 this routine does not check IndependentBranches
1325 and canreservefromotherbranches.
1327 Note also that this subroutine does not checks smart
1328 rules limits for item by reservesallowed/holds_per_record
1329 values, this complemented in calling code with calls and
1330 checks with CanItemBeReserved or CanBookBeReserved.
1334 sub IsAvailableForItemLevelRequest {
1337 my $pickup_branchcode = shift;
1339 my $dbh = C4::Context->dbh;
1340 # must check the notforloan setting of the itemtype
1341 # FIXME - a lot of places in the code do this
1342 # or something similar - need to be
1344 my $itemtype = $item->effective_itemtype;
1346 unless defined $itemtype;
1347 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1350 $notforloan_per_itemtype ||
1352 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1354 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1356 if ($pickup_branchcode) {
1357 my $destination = Koha::Libraries->find($pickup_branchcode);
1358 return 0 unless $destination;
1359 return 0 unless $destination->pickup_location;
1360 return 0 unless $item->can_be_transferred( { to => $destination } );
1361 my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $item, $patron );
1362 my $branchitemrule =
1363 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1364 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1365 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1368 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1370 if ( $on_shelf_holds == 1 ) {
1372 } elsif ( $on_shelf_holds == 2 ) {
1374 # These calculations work at the biblio level, and can be expensive
1375 # we use the in-memory cache to avoid calling once per item when looping items on a biblio
1377 my $memory_cache = Koha::Cache::Memory::Lite->get_instance();
1378 my $cache_key = sprintf "ItemsAnyAvailableAndNotRestricted:%s:%s", $patron->id, $item->biblionumber;
1380 my $any_available = $memory_cache->get_from_cache($cache_key);
1381 return $any_available ? 0 : 1 if defined($any_available);
1384 ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron } );
1385 $memory_cache->set_in_cache( $cache_key, $any_available );
1386 return $any_available ? 0 : 1;
1388 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1389 return $item->notforloan < 0 || $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1393 =head2 ItemsAnyAvailableAndNotRestricted
1395 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1397 This function checks all items for specified biblionumber (numeric) against patron (object)
1398 and returns true (1) if at least one item available for loan/check out/present/not held
1399 and also checks other parameters logic which not restricts item for hold at all (for ex.
1400 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1404 sub ItemsAnyAvailableAndNotRestricted {
1407 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1409 foreach my $i (@items) {
1410 my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $i, $param->{patron} );
1411 my $branchitemrule =
1412 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1413 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1415 # we can return (end the loop) when first one found:
1418 || $i->notforloan # items with non-zero notforloan cannot be checked out
1421 || IsItemOnHoldAndFound( $i->id )
1423 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1424 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1425 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1426 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1427 || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1433 =head2 AlterPriority
1435 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1437 This function changes a reserve's priority up, down, to the top, or to the bottom.
1438 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1443 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1445 my $hold = Koha::Holds->find( $reserve_id );
1446 return unless $hold;
1448 if ( $hold->cancellationdate ) {
1449 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1453 if ( $where eq 'up' ) {
1454 return unless $prev_priority;
1455 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1456 } elsif ( $where eq 'down' ) {
1457 return unless $next_priority;
1458 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1459 } elsif ( $where eq 'top' ) {
1460 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1461 } elsif ( $where eq 'bottom' ) {
1462 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1465 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
1467 biblio_ids => [ $hold->biblionumber ]
1469 ) if C4::Context->preference('RealTimeHoldsQueue');
1470 # FIXME Should return the new priority
1473 =head2 ToggleLowestPriority
1475 ToggleLowestPriority( $borrowernumber, $biblionumber );
1477 This function sets the lowestPriority field to true if is false, and false if it is true.
1481 sub ToggleLowestPriority {
1482 my ( $reserve_id ) = @_;
1484 my $dbh = C4::Context->dbh;
1486 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1487 $sth->execute( $reserve_id );
1489 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1492 =head2 ToggleSuspend
1494 ToggleSuspend( $reserve_id );
1496 This function sets the suspend field to true if is false, and false if it is true.
1497 If the reserve is currently suspended with a suspend_until date, that date will
1498 be cleared when it is unsuspended.
1503 my ( $reserve_id, $suspend_until ) = @_;
1505 my $hold = Koha::Holds->find( $reserve_id );
1507 if ( $hold->is_suspended ) {
1510 $hold->suspend_hold( $suspend_until );
1517 borrowernumber => $borrowernumber,
1518 [ biblionumber => $biblionumber, ]
1519 [ suspend_until => $suspend_until, ]
1520 [ suspend => $suspend ]
1523 This function accepts a set of hash keys as its parameters.
1524 It requires either borrowernumber or biblionumber, or both.
1526 suspend_until is wholly optional.
1533 my $borrowernumber = $params{'borrowernumber'} || undef;
1534 my $biblionumber = $params{'biblionumber'} || undef;
1535 my $suspend_until = $params{'suspend_until'} || undef;
1536 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1538 return unless ( $borrowernumber || $biblionumber );
1541 $params->{found} = undef;
1542 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1543 $params->{biblionumber} = $biblionumber if $biblionumber;
1545 my @holds = Koha::Holds->search($params)->as_list;
1548 map { $_->suspend_hold($suspend_until) } @holds;
1551 map { $_->resume() } @holds;
1559 reserve_id => $reserve_id,
1561 [ignoreSetLowestRank => $ignoreSetLowestRank]
1566 _FixPriority({ biblionumber => $biblionumber});
1568 This routine adjusts the priority of a hold request and holds
1571 In the first form, where a reserve_id is passed, the priority of the
1572 hold is set to supplied rank, and other holds for that bib are adjusted
1573 accordingly. If the rank is "del", the hold is cancelled. If no rank
1574 is supplied, all of the holds on that bib have their priority adjusted
1575 as if the second form had been used.
1577 In the second form, where a biblionumber is passed, the holds on that
1578 bib (that are not captured) are sorted in order of increasing priority,
1579 then have reserves.priority set so that the first non-captured hold
1580 has its priority set to 1, the second non-captured hold has its priority
1581 set to 2, and so forth.
1583 In both cases, holds that have the lowestPriority flag on are have their
1584 priority adjusted to ensure that they remain at the end of the line.
1586 Note that the ignoreSetLowestRank parameter is meant to be used only
1587 when _FixPriority calls itself.
1592 my ( $params ) = @_;
1593 my $reserve_id = $params->{reserve_id};
1594 my $rank = $params->{rank} // '';
1595 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1596 my $biblionumber = $params->{biblionumber};
1598 my $dbh = C4::Context->dbh;
1601 if ( $reserve_id ) {
1602 $hold = Koha::Holds->find( $reserve_id );
1603 if (!defined $hold){
1604 # may have already been checked out and hold fulfilled
1605 $hold = Koha::Old::Holds->find( $reserve_id );
1607 return unless $hold;
1610 unless ( $biblionumber ) { # FIXME This is a very weird API
1611 $biblionumber = $hold->biblionumber;
1614 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1617 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1619 # make sure priority for waiting or in-transit items is 0
1623 WHERE reserve_id = ?
1624 AND found IN ('W', 'T', 'P')
1626 my $sth = $dbh->prepare($query);
1627 $sth->execute( $reserve_id );
1633 SELECT reserve_id, borrowernumber, reservedate
1635 WHERE biblionumber = ?
1636 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1637 ORDER BY priority ASC
1639 my $sth = $dbh->prepare($query);
1640 $sth->execute( $biblionumber );
1641 while ( my $line = $sth->fetchrow_hashref ) {
1642 push( @priority, $line );
1645 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1646 # To find the matching index
1648 my $key = -1; # to allow for 0 to be a valid result
1649 for ( $i = 0 ; $i < @priority ; $i++ ) {
1650 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1651 $key = $i; # save the index
1656 # if index exists in array then move it to new position
1657 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1658 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1659 my $moving_item = splice( @priority, $key, 1 );
1660 $new_rank = scalar @priority if $new_rank > scalar @priority;
1661 splice( @priority, $new_rank, 0, $moving_item );
1664 # now fix the priority on those that are left....
1668 WHERE reserve_id = ?
1670 $sth = $dbh->prepare($query);
1671 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1674 $priority[$j]->{'reserve_id'}
1678 unless ( $ignoreSetLowestRank ) {
1679 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1680 $sth->execute($biblionumber);
1681 while ( my $res = $sth->fetchrow_hashref() ) {
1683 reserve_id => $res->{'reserve_id'},
1685 ignoreSetLowestRank => 1
1691 =head2 _Findgroupreserve
1693 @results = &_Findgroupreserve($biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1695 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1696 first match found. If neither, then we look for non-holds-queue based holds.
1697 Lookahead is the number of days to look in advance.
1699 C<&_Findgroupreserve> returns :
1700 C<@results> is an array of references-to-hash whose keys are mostly
1701 fields from the reserves table of the Koha database, plus
1702 C<biblioitemnumber>.
1704 This routine with either return:
1705 1 - Item specific holds from the holds queue
1706 2 - Title level holds from the holds queue
1707 3 - All holds for this biblionumber
1709 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1713 sub _Findgroupreserve {
1714 my ( $biblionumber, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1715 my $dbh = C4::Context->dbh;
1717 # check for targeted match form the holds queue
1718 my $hold_target_query = qq{
1719 SELECT reserves.biblionumber AS biblionumber,
1720 reserves.borrowernumber AS borrowernumber,
1721 reserves.reservedate AS reservedate,
1722 reserves.branchcode AS branchcode,
1723 reserves.cancellationdate AS cancellationdate,
1724 reserves.found AS found,
1725 reserves.reservenotes AS reservenotes,
1726 reserves.priority AS priority,
1727 reserves.timestamp AS timestamp,
1728 biblioitems.biblioitemnumber AS biblioitemnumber,
1729 reserves.itemnumber AS itemnumber,
1730 reserves.reserve_id AS reserve_id,
1731 reserves.itemtype AS itemtype,
1732 reserves.non_priority AS non_priority,
1733 reserves.item_group_id AS item_group_id
1735 JOIN biblioitems USING (biblionumber)
1736 JOIN hold_fill_targets USING (reserve_id)
1739 AND hold_fill_targets.itemnumber = ?
1740 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1744 my $sth = $dbh->prepare($hold_target_query);
1745 $sth->execute($itemnumber, $lookahead||0);
1747 if ( my $data = $sth->fetchrow_hashref ) {
1748 push( @results, $data )
1749 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1751 return @results if @results;
1754 SELECT reserves.biblionumber AS biblionumber,
1755 reserves.borrowernumber AS borrowernumber,
1756 reserves.reservedate AS reservedate,
1757 reserves.waitingdate AS waitingdate,
1758 reserves.branchcode AS branchcode,
1759 reserves.cancellationdate AS cancellationdate,
1760 reserves.found AS found,
1761 reserves.reservenotes AS reservenotes,
1762 reserves.priority AS priority,
1763 reserves.timestamp AS timestamp,
1764 reserves.itemnumber AS itemnumber,
1765 reserves.reserve_id AS reserve_id,
1766 reserves.itemtype AS itemtype,
1767 reserves.non_priority AS non_priority,
1768 reserves.item_group_id AS item_group_id
1770 WHERE reserves.biblionumber = ?
1771 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1772 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1776 $sth = $dbh->prepare($query);
1777 $sth->execute( $biblionumber, $itemnumber, $lookahead||0);
1779 while ( my $data = $sth->fetchrow_hashref ) {
1780 push( @results, $data )
1781 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1786 =head2 _koha_notify_reserve
1788 _koha_notify_reserve( $hold->reserve_id );
1790 Sends a notification to the patron that their hold has been filled (through
1793 The letter code for this notice may be found using the following query:
1795 select distinct letter_code
1796 from message_transports
1797 inner join message_attributes using (message_attribute_id)
1798 where message_name = 'Hold_Filled'
1800 This will probably sipmly be 'HOLD', but because it is defined in the database,
1801 it is subject to addition or change.
1803 The following tables are availalbe witin the notice:
1814 sub _koha_notify_reserve {
1815 my $reserve_id = shift;
1817 my $hold = Koha::Holds->find($reserve_id);
1818 my $borrowernumber = $hold->borrowernumber;
1820 my $patron = Koha::Patrons->find( $borrowernumber );
1822 # Try to get the borrower's email address
1823 my $to_address = $patron->notice_email_address;
1825 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1826 borrowernumber => $borrowernumber,
1827 message_name => 'Hold_Filled'
1830 my $library = Koha::Libraries->find( $hold->branchcode );
1831 my $from_email_address = $library->from_email_address;
1833 my %letter_params = (
1834 module => 'reserves',
1835 branchcode => $hold->branchcode,
1836 lang => $patron->lang,
1838 'branches' => $library->unblessed,
1839 'borrowers' => $patron->unblessed,
1840 'biblio' => $hold->biblionumber,
1841 'biblioitems' => $hold->biblionumber,
1842 'reserves' => $hold->unblessed,
1843 'items' => $hold->itemnumber,
1847 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.
1848 my $do_not_lock = ( exists $ENV{_} && $ENV{_} =~ m|prove| ) || $ENV{KOHA_TESTING};
1849 my $send_notification = sub {
1850 my ( $mtt, $letter_code, $wants_digest ) = (@_);
1851 return unless defined $letter_code;
1852 $letter_params{letter_code} = $letter_code;
1853 $letter_params{message_transport_type} = $mtt;
1854 my $letter = C4::Letters::GetPreparedLetter(%letter_params);
1856 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1860 unless ($wants_digest) {
1861 C4::Letters::EnqueueLetter(
1864 borrowernumber => $borrowernumber,
1865 from_address => $from_email_address,
1866 message_transport_type => $mtt,
1870 C4::Context->dbh->do(q|LOCK TABLE message_queue READ|) unless $do_not_lock;
1871 C4::Context->dbh->do(q|LOCK TABLE message_queue WRITE|) unless $do_not_lock;
1872 my $message = C4::Message->find_last_message( $patron->unblessed, $letter_code, $mtt );
1874 C4::Context->dbh->do(q|UNLOCK TABLES|) unless $do_not_lock;
1875 C4::Message->enqueue( $letter, $patron, $mtt );
1877 $message->append($letter);
1880 C4::Context->dbh->do(q|UNLOCK TABLES|) unless $do_not_lock;
1884 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1886 ( $mtt eq 'email' and not $to_address ) # No email address
1887 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1888 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1889 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1892 &$send_notification($mtt, $letter_code, $messagingprefs->{wants_digest});
1893 $notification_sent++;
1895 #Making sure that a print notification is sent if no other transport types can be utilized.
1896 if (! $notification_sent) {
1897 &$send_notification('print', 'HOLD');
1902 =head2 _koha_notify_hold_changed
1904 _koha_notify_hold_changed( $hold_object );
1908 sub _koha_notify_hold_changed {
1911 my $patron = $hold->patron;
1912 my $library = $hold->branch;
1914 my $letter = C4::Letters::GetPreparedLetter(
1915 module => 'reserves',
1916 letter_code => 'HOLD_CHANGED',
1917 branchcode => $hold->branchcode,
1918 substitute => { today => output_pref( dt_from_string ) },
1920 'branches' => $library->unblessed,
1921 'borrowers' => $patron->unblessed,
1922 'biblio' => $hold->biblionumber,
1923 'biblioitems' => $hold->biblionumber,
1924 'reserves' => $hold->unblessed,
1925 'items' => $hold->itemnumber,
1929 return unless $letter;
1932 C4::Context->preference('ExpireReservesAutoFillEmail')
1933 || $library->inbound_email_address;
1935 C4::Letters::EnqueueLetter(
1938 borrowernumber => $patron->id,
1939 message_transport_type => 'email',
1940 from_address => $library->from_email_address,
1941 to_address => $email,
1946 =head2 _ShiftPriority
1948 $new_priority = _ShiftPriority( $biblionumber, $priority );
1950 This increments the priority of all reserves after the one
1951 with either the lowest date after C<$reservedate>
1952 or the lowest priority after C<$priority>.
1954 It effectively makes room for a new reserve to be inserted with a certain
1955 priority, which is returned.
1957 This is most useful when the reservedate can be set by the user. It allows
1958 the new reserve to be placed before other reserves that have a later
1959 reservedate. Since priority also is set by the form in reserves/request.pl
1960 the sub accounts for that too.
1964 sub _ShiftPriority {
1965 my ( $biblio, $new_priority ) = @_;
1967 my $dbh = C4::Context->dbh;
1968 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND priority > ? ORDER BY priority ASC LIMIT 1";
1969 my $sth = $dbh->prepare( $query );
1970 $sth->execute( $biblio, $new_priority );
1971 my $min_priority = $sth->fetchrow;
1972 # if no such matches are found, $new_priority remains as original value
1973 $new_priority = $min_priority if ( $min_priority );
1975 # Shift the priority up by one; works in conjunction with the next SQL statement
1976 $query = "UPDATE reserves
1977 SET priority = priority+1
1978 WHERE biblionumber = ?
1979 AND borrowernumber = ?
1982 my $sth_update = $dbh->prepare( $query );
1984 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1985 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1986 $sth = $dbh->prepare( $query );
1987 $sth->execute( $new_priority, $biblio );
1988 while ( my $row = $sth->fetchrow_hashref ) {
1989 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1992 return $new_priority; # so the caller knows what priority they wind up receiving
1997 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1999 Use when checking out an item to handle reserves
2000 If $cancelreserve boolean is set to true, it will remove existing reserve
2005 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2007 $cancelreserve //= 0;
2009 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2010 my $item = Koha::Items->find($itemnumber);
2011 my ( $restype, $res, undef ) = CheckReserves( $item, $lookahead );
2014 my $biblionumber = $res->{biblionumber};
2016 if ($res->{borrowernumber} == $borrowernumber) {
2017 my $hold = Koha::Holds->find( $res->{reserve_id} );
2018 $hold->fill({ item_id => $itemnumber });
2022 # The item is reserved by someone else.
2023 # Find this item in the reserves
2025 my $borr_res = Koha::Holds->search({
2026 borrowernumber => $borrowernumber,
2027 biblionumber => $biblionumber,
2029 order_by => 'priority'
2033 # The item is reserved by the current patron
2034 $borr_res->fill({ item_id => $itemnumber });
2037 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2038 RevertWaitingStatus({ itemnumber => $itemnumber });
2040 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2041 my $hold = Koha::Holds->find( $res->{reserve_id} );
2049 MergeHolds($dbh,$to_biblio, $from_biblio);
2051 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2056 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2057 my $sth = $dbh->prepare(
2058 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2060 $sth->execute($from_biblio);
2061 if ( my $data = $sth->fetchrow_hashref() ) {
2063 # holds exist on old record, if not we don't need to do anything
2064 $sth = $dbh->prepare(
2065 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2066 $sth->execute( $to_biblio, $from_biblio );
2069 # don't reorder those already waiting
2071 $sth = $dbh->prepare(
2072 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2074 my $upd_sth = $dbh->prepare(
2075 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2076 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2078 $sth->execute( $to_biblio );
2080 while ( my $reserve = $sth->fetchrow_hashref() ) {
2082 $priority, $to_biblio,
2083 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2084 $reserve->{'itemnumber'}
2091 =head2 RevertWaitingStatus
2093 RevertWaitingStatus({ itemnumber => $itemnumber });
2095 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2097 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2098 item level hold, even if it was only a bibliolevel hold to
2099 begin with. This is because we can no longer know if a hold
2100 was item-level or bib-level after a hold has been set to
2105 sub RevertWaitingStatus {
2106 my ( $params ) = @_;
2107 my $itemnumber = $params->{'itemnumber'};
2109 return unless ( $itemnumber );
2111 my $dbh = C4::Context->dbh;
2113 ## Get the waiting reserve we want to revert
2114 my $hold = Koha::Holds->search(
2116 itemnumber => $itemnumber,
2117 found => { not => undef },
2121 ## Increment the priority of all other non-waiting
2122 ## reserves for this bib record
2123 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2124 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2126 ## Fix up the currently waiting reserve
2131 waitingdate => undef,
2132 expirationdate => $hold->patron_expiration_date,
2133 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2135 )->store( { hold_reverted => 1 } );
2137 logaction( 'HOLDS', 'MODIFY', $hold->id, $hold )
2138 if C4::Context->preference('HoldsLog');
2140 _FixPriority( { biblionumber => $hold->biblionumber } );
2142 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
2144 biblio_ids => [ $hold->biblionumber ]
2146 ) if C4::Context->preference('RealTimeHoldsQueue');
2156 branchcode => $branchcode,
2157 borrowernumber => $borrowernumber,
2158 biblionumber => $biblionumber,
2159 [ itemnumber => $itemnumber, ]
2160 [ barcode => $barcode, ]
2164 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2166 The letter code will be HOLD_SLIP, and the following tables are
2167 available within the slip:
2180 my $branchcode = $args->{branchcode};
2181 my $reserve_id = $args->{reserve_id};
2182 my $itemnumber = $args->{itemnumber};
2184 my $hold = Koha::Holds->find($reserve_id);
2185 return unless $hold;
2187 my $patron = $hold->borrower;
2188 my $reserve = $hold->unblessed;
2190 return C4::Letters::GetPreparedLetter (
2191 module => 'circulation',
2192 letter_code => 'HOLD_SLIP',
2193 branchcode => $branchcode,
2194 lang => $patron->lang,
2196 'reserves' => $reserve,
2197 'branches' => $reserve->{branchcode},
2198 'borrowers' => $reserve->{borrowernumber},
2199 'biblio' => $reserve->{biblionumber},
2200 'biblioitems' => $reserve->{biblionumber},
2201 'items' => $reserve->{itemnumber} || $itemnumber,
2206 =head2 CalculatePriority
2208 my $p = CalculatePriority($biblionumber, $resdate);
2210 Calculate priority for a new reserve on biblionumber, placing it at
2211 the end of the line of all holds whose start date falls before
2212 the current system time and that are neither on the hold shelf
2215 The reserve date parameter is optional; if it is supplied, the
2216 priority is based on the set of holds whose start date falls before
2217 the parameter value.
2219 After calculation of this priority, it is recommended to call
2220 _ShiftPriority. Note that this is currently done in
2225 sub CalculatePriority {
2226 my ( $biblionumber, $resdate ) = @_;
2229 SELECT COUNT(*) FROM reserves
2230 WHERE biblionumber = ?
2232 AND (found IS NULL OR found = '')
2234 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2236 $sql.= ' AND ( reservedate <= ? )';
2239 $sql.= ' AND ( reservedate < NOW() )';
2241 my $dbh = C4::Context->dbh();
2242 my @row = $dbh->selectrow_array(
2245 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2248 return @row ? $row[0]+1 : 1;
2251 =head2 IsItemOnHoldAndFound
2253 my $bool = IsItemFoundHold( $itemnumber );
2255 Returns true if the item is currently on hold
2256 and that hold has a non-null found status ( W, T, etc. )
2260 sub IsItemOnHoldAndFound {
2261 my ($itemnumber) = @_;
2263 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2265 my $found = $rs->count(
2267 itemnumber => $itemnumber,
2268 found => { '!=' => undef }
2275 =head2 GetMaxPatronHoldsForRecord
2277 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2279 For multiple holds on a given record for a given patron, the max
2280 number of record level holds that a patron can be placed is the highest
2281 value of the holds_per_record rule for each item if the record for that
2282 patron. This subroutine finds and returns the highest holds_per_record
2283 rule value for a given patron id and record id.
2287 sub GetMaxPatronHoldsForRecord {
2288 my ( $borrowernumber, $biblionumber ) = @_;
2290 my $patron = Koha::Patrons->find($borrowernumber);
2291 my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2293 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2295 my $categorycode = $patron->categorycode;
2297 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2300 foreach my $item (@items) {
2301 my $itemtype = $item->effective_itemtype();
2303 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2305 my $rule = Koha::CirculationRules->get_effective_rule({
2306 categorycode => $categorycode,
2307 itemtype => $itemtype,
2308 branchcode => $branchcode,
2309 rule_name => 'holds_per_record'
2311 my $holds_per_record = $rule ? $rule->rule_value : 0;
2312 $max = $holds_per_record if $holds_per_record > $max;
2320 Koha Development Team <http://koha-community.org/>