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::CirculationRules;
41 use Koha::DateUtils qw( dt_from_string output_pref );
51 use List::MoreUtils qw( any );
55 C4::Reserves - Koha functions for dealing with reservation.
63 This modules provides somes functions to deal with reservations.
65 Reserves are stored in reserves table.
66 The following columns contains important values :
67 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
68 =0 : then the reserve is being dealed
69 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
70 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
71 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
72 F(inished) : the reserve has been completed, and is done
73 P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
74 by librarian before notice is send and status changed to waiting.
75 Applicable only if HoldsNeedProcessingSIP system preference is set.
76 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
99 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 $patron_expiration_date = $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 $patron_expiration_date = output_pref({ str => $patron_expiration_date, 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 )
227 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
228 # Make room in reserves for this if passed a priority
229 $priority = _ShiftPriority( $biblionumber, $priority );
234 # If the reserv had the waiting status, we had the value of the resdate
235 if ( $found && $found eq 'W' ) {
236 $waitingdate = $resdate;
239 # Don't add itemtype limit if specific item is selected
240 $itemtype = undef if $checkitem;
242 # updates take place here
243 my $hold = Koha::Hold->new(
245 borrowernumber => $borrowernumber,
246 biblionumber => $biblionumber,
247 reservedate => $resdate,
248 branchcode => $branch,
249 priority => $priority,
250 reservenotes => $notes,
251 itemnumber => $checkitem,
253 waitingdate => $waitingdate,
254 patron_expiration_date => $patron_expiration_date,
255 itemtype => $itemtype,
256 item_level_hold => $checkitem ? 1 : 0,
257 non_priority => $non_priority ? 1 : 0,
260 $hold->set_waiting() if $found && $found eq 'W';
262 logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
263 if C4::Context->preference('HoldsLog');
265 my $reserve_id = $hold->id();
267 # add a reserve fee if needed
268 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
269 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
270 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
273 _FixPriority({ biblionumber => $biblionumber});
275 # Send e-mail to librarian if syspref is active
276 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
277 my $patron = Koha::Patrons->find( $borrowernumber );
278 my $library = $patron->library;
279 if ( my $letter = C4::Letters::GetPreparedLetter (
280 module => 'reserves',
281 letter_code => 'HOLDPLACED',
282 branchcode => $branch,
283 lang => $patron->lang,
285 'branches' => $library->unblessed,
286 'borrowers' => $patron->unblessed,
287 'biblio' => $biblionumber,
288 'biblioitems' => $biblionumber,
289 'items' => $checkitem,
290 'reserves' => $hold->unblessed,
294 my $branch_email_address = $library->inbound_email_address;
296 C4::Letters::EnqueueLetter(
299 borrowernumber => $borrowernumber,
300 message_transport_type => 'email',
301 to_address => $branch_email_address,
307 Koha::Plugins->call('after_hold_create', $hold);
312 payload => { hold => $hold->get_from_storage }
316 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
318 biblio_ids => [ $biblionumber ]
320 ) if C4::Context->preference('RealTimeHoldsQueue');
325 =head2 CanBookBeReserved
327 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
328 if ($canReserve eq 'OK') { #We can reserve this Item! }
330 $params are passed directly through to CanItemBeReserved
332 See CanItemBeReserved() for possible return values.
336 sub CanBookBeReserved{
337 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
339 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
340 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
341 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
342 return { status =>'alreadypossession' };
345 if ( $params->{itemtype} ) {
347 # biblio-level, item type-contrained
348 my $patron = Koha::Patrons->find($borrowernumber);
349 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
351 itemtype => $params->{itemtype},
352 categorycode => $patron->categorycode,
353 branchcode => $pickup_branchcode,
354 rule_name => 'reservesallowed',
358 $reservesallowed = ( $reservesallowed eq '' ) ? undef : $reservesallowed;
360 my $count = $patron->holds->search(
363 { 'me.itemtype' => $params->{itemtype} },
364 { 'item.itype' => $params->{itemtype} }
372 return { status => '' }
373 if defined $reservesallowed and $reservesallowed < $count + 1;
377 #get items linked via host records
378 my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
379 if (@hostitemnumbers){
380 $items = Koha::Items->search({
382 biblionumber => $biblionumber,
383 itemnumber => { -in => @hostitemnumbers }
387 $items = Koha::Items->search({ biblionumber => $biblionumber});
390 my $canReserve = { status => '' };
391 my $patron = Koha::Patrons->find( $borrowernumber );
392 while ( my $item = $items->next ) {
393 $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
394 return { status => 'OK' } if $canReserve->{status} eq 'OK';
399 =head2 CanItemBeReserved
401 $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
402 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
405 'ignore_found_holds' - if true holds that have been trapped are not counted
406 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
407 current checkout against the high holds threshold
408 'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
409 should not check if there are too many holds as we only csre about reservability
411 @RETURNS { status => OK }, if the Item can be reserved.
412 { status => ageRestricted }, if the Item is age restricted for this borrower.
413 { status => damaged }, if the Item is damaged.
414 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
415 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
416 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
417 { status => notReservable }, if holds on this item are not allowed
418 { status => libraryNotFound }, if given branchcode is not an existing library
419 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
420 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
421 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
422 { status => recall }, if the borrower has already placed a recall on this item
426 sub CanItemBeReserved {
427 my ( $patron, $item, $pickup_branchcode, $params ) = @_;
429 my $dbh = C4::Context->dbh;
430 my $ruleitemtype; # itemtype of the matching issuing rule
431 my $allowedreserves = 0; # Total number of holds allowed across all records, default to none
433 # We check item branch if IndependentBranches is ON
434 # and canreservefromotherbranches is OFF
435 if ( C4::Context->preference('IndependentBranches')
436 and !C4::Context->preference('canreservefromotherbranches') )
438 if ( $item->homebranch ne $patron->branchcode ) {
439 return { status => 'cannotReserveFromOtherBranches' };
443 # we retrieve borrowers and items informations #
444 # item->{itype} will come for biblioitems if necessery
445 my $borrower = $patron->unblessed;
447 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
448 return { status =>'damaged' }
450 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
452 if( GetMarcFromKohaField('biblioitems.agerestriction') ){
453 my $biblio = $item->biblio;
454 # Check for the age restriction
455 my ( $ageRestriction, $daysToAgeRestriction ) =
456 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
457 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
460 # Check that the patron doesn't have an item level hold on this item already
461 return { status =>'itemAlreadyOnHold' }
462 if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
464 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
465 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
466 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $item->biblionumber ) ) {
467 return { status =>'alreadypossession' };
470 # check if a recall exists on this item from this borrower
471 return { status => 'recall' }
472 if $patron->recalls->filter_by_current->search({ item_id => $item->itemnumber })->count;
474 my $controlbranch = C4::Context->preference('ReservesControlBranch');
476 my $reserves_control_branch;
477 my $branchfield = "reserves.branchcode";
479 if ( $controlbranch eq "ItemHomeLibrary" ) {
480 $branchfield = "items.homebranch";
481 $reserves_control_branch = $item->homebranch;
483 elsif ( $controlbranch eq "PatronLibrary" ) {
484 $branchfield = "borrowers.branchcode";
485 $reserves_control_branch = $borrower->{branchcode};
490 my $reservesallowed = Koha::CirculationRules->get_effective_rule({
491 itemtype => $item->effective_itemtype,
492 categorycode => $borrower->{categorycode},
493 branchcode => $reserves_control_branch,
494 rule_name => 'reservesallowed',
497 $ruleitemtype = $reservesallowed->itemtype;
498 $allowedreserves = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
501 $ruleitemtype = undef;
504 my $rights = Koha::CirculationRules->get_effective_rules({
505 categorycode => $borrower->{'categorycode'},
506 itemtype => $item->effective_itemtype,
507 branchcode => $reserves_control_branch,
508 rules => ['holds_per_record','holds_per_day']
510 my $holds_per_record = $rights->{holds_per_record} // 1;
511 my $holds_per_day = $rights->{holds_per_day};
513 if ( defined $holds_per_record && $holds_per_record ne '' ){
514 if ( $holds_per_record == 0 ) {
515 return { status => "noReservesAllowed" };
517 if ( !$params->{ignore_hold_counts} ) {
518 my $search_params = {
519 borrowernumber => $patron->borrowernumber,
520 biblionumber => $item->biblionumber,
522 $search_params->{found} = undef if $params->{ignore_found_holds};
523 my $holds = Koha::Holds->search($search_params);
524 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record } if $holds->count() >= $holds_per_record;
528 if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne '')
530 my $today_holds = Koha::Holds->search({
531 borrowernumber => $patron->borrowernumber,
532 reservedate => dt_from_string->date
534 return { status => 'tooManyReservesToday', limit => $holds_per_day } if $today_holds->count() >= $holds_per_day;
537 # we check if it's ok or not
538 if ( defined $allowedreserves && $allowedreserves ne '' ){
539 if( $allowedreserves == 0 ){
540 return { status => 'noReservesAllowed' };
542 if ( !$params->{ignore_hold_counts} ) {
545 SELECT count(*) AS count
547 LEFT JOIN items USING (itemnumber)
548 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
549 LEFT JOIN borrowers USING (borrowernumber)
550 WHERE borrowernumber = ?
552 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
554 # If using item-level itypes, fall back to the record
555 # level itemtype if the hold has no associated item
556 if ( defined $ruleitemtype ) {
557 if ( C4::Context->preference('item-level_itypes') ) {
559 AND ( COALESCE( items.itype, biblioitems.itemtype ) = ?
560 OR reserves.itemtype = ? )
565 AND ( biblioitems.itemtype = ?
566 OR reserves.itemtype = ? )
571 my $sthcount = $dbh->prepare($querycount);
573 if ( defined $ruleitemtype ) {
574 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch, $ruleitemtype, $ruleitemtype );
577 $sthcount->execute( $patron->borrowernumber, $reserves_control_branch );
580 my $reservecount = "0";
581 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
582 $reservecount = $rowcount->{count};
585 return { status => 'tooManyReserves', limit => $allowedreserves } if $reservecount >= $allowedreserves;
589 # Now we need to check hold limits by patron category
590 my $rule = Koha::CirculationRules->get_effective_rule(
592 categorycode => $patron->categorycode,
593 branchcode => $reserves_control_branch,
594 rule_name => 'max_holds',
597 if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
598 my $total_holds_count = Koha::Holds->search(
600 borrowernumber => $patron->borrowernumber
604 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
608 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
610 if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
611 return { status => 'notReservable' };
614 if ( $branchitemrule->{holdallowed} eq 'from_home_library'
615 && $borrower->{branchcode} ne $item->homebranch )
617 return { status => 'cannotReserveFromOtherBranches' };
620 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
621 if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
622 if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
623 return { status => 'branchNotInHoldGroup' };
627 if ($pickup_branchcode) {
628 my $destination = Koha::Libraries->find({
629 branchcode => $pickup_branchcode,
632 unless ($destination) {
633 return { status => 'libraryNotFound' };
635 unless ($destination->pickup_location) {
636 return { status => 'libraryNotPickupLocation' };
638 unless ($item->can_be_transferred({ to => $destination })) {
639 return { status => 'cannotBeTransferred' };
641 if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
642 return { status => 'pickupNotInHoldGroup' };
644 if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
645 return { status => 'pickupNotInHoldGroup' };
649 return { status => 'OK' };
652 =head2 CanReserveBeCanceledFromOpac
654 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
656 returns 1 if reserve can be cancelled by user from OPAC.
657 First check if reserve belongs to user, next checks if reserve is not in
658 transfer or waiting status
662 sub CanReserveBeCanceledFromOpac {
663 my ($reserve_id, $borrowernumber) = @_;
665 return unless $reserve_id and $borrowernumber;
666 my $reserve = Koha::Holds->find($reserve_id) or return;
668 return 0 unless $reserve->borrowernumber == $borrowernumber;
669 return $reserve->is_cancelable_from_opac;
672 =head2 GetOtherReserves
674 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
676 Check queued list of this document and check if this document must be transferred
680 sub GetOtherReserves {
681 my ($itemnumber) = @_;
684 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
685 if ($checkreserves) {
686 my $item = Koha::Items->find($itemnumber);
687 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
688 $messages->{'transfert'} = $checkreserves->{'branchcode'};
689 #minus priorities of others reservs
690 ModReserveMinusPriority(
692 $checkreserves->{'reserve_id'},
695 #launch the subroutine dotransfer
696 C4::Items::ModItemTransfer(
698 $item->holdingbranch,
699 $checkreserves->{'branchcode'},
705 #step 2b : case of a reservation on the same branch, set the waiting status
707 $messages->{'waiting'} = 1;
708 ModReserveMinusPriority(
710 $checkreserves->{'reserve_id'},
712 ModReserveStatus($itemnumber,'W');
715 $nextreservinfo = $checkreserves;
718 return ( $messages, $nextreservinfo );
721 =head2 ChargeReserveFee
723 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
725 Charge the fee for a reserve (if $fee > 0)
729 sub ChargeReserveFee {
730 my ( $borrowernumber, $fee, $title ) = @_;
731 return if !$fee || $fee == 0; # the last test is needed to include 0.00
732 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
735 description => $title,
737 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
738 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
739 interface => C4::Context->interface,
740 invoice_type => undef,
749 $fee = GetReserveFee( $borrowernumber, $biblionumber );
751 Calculate the fee for a reserve (if applicable).
756 my ( $borrowernumber, $biblionumber ) = @_;
758 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
761 SELECT COUNT(*) FROM items
762 LEFT JOIN issues USING (itemnumber)
763 WHERE items.biblionumber=? AND issues.issue_id IS NULL
766 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
769 my $dbh = C4::Context->dbh;
770 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
771 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
772 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
773 # This is a reconstruction of the old code:
774 # Compare number of items with items issued, and optionally check holds
775 # If not all items are issued and there are no holds: charge no fee
776 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
777 my ( $notissued, $reserved );
778 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
781 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
782 ( $biblionumber, $borrowernumber ) );
783 $fee = 0 if $reserved == 0;
789 =head2 GetReserveStatus
791 $reservestatus = GetReserveStatus($itemnumber);
793 Takes an itemnumber and returns the status of the reserve placed on it.
794 If several reserves exist, the reserve with the lower priority is given.
798 ## FIXME: I don't think this does what it thinks it does.
799 ## It only ever checks the first reserve result, even though
800 ## multiple reserves for that bib can have the itemnumber set
801 ## the sub is only used once in the codebase.
802 sub GetReserveStatus {
803 my ($itemnumber) = @_;
805 my $dbh = C4::Context->dbh;
807 my ($sth, $found, $priority);
809 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
810 $sth->execute($itemnumber);
811 ($found, $priority) = $sth->fetchrow_array;
815 return 'Waiting' if $found eq 'W' and $priority == 0;
816 return 'Processing' if $found eq 'P';
817 return 'Finished' if $found eq 'F';
820 return 'Reserved' if defined $priority && $priority > 0;
822 return ''; # empty string here will remove need for checking undef, or less log lines
827 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
828 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
829 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
831 Find a book in the reserves.
833 C<$itemnumber> is the book's item number.
834 C<$lookahead> is the number of days to look in advance for future reserves.
836 As I understand it, C<&CheckReserves> looks for the given item in the
837 reserves. If it is found, that's a match, and C<$status> is set to
840 Otherwise, it finds the most important item in the reserves with the
841 same biblio number as this book (I'm not clear on this) and returns it
842 with C<$status> set to C<Reserved>.
844 C<&CheckReserves> returns a two-element list:
846 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
848 C<$reserve> is the reserve item that matched. It is a
849 reference-to-hash whose keys are mostly the fields of the reserves
850 table in the Koha database.
855 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
856 my $dbh = C4::Context->dbh;
859 if (C4::Context->preference('item-level_itypes')){
861 SELECT items.biblionumber,
862 items.biblioitemnumber,
863 itemtypes.notforloan,
864 items.notforloan AS itemnotforloan,
870 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
871 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
876 SELECT items.biblionumber,
877 items.biblioitemnumber,
878 itemtypes.notforloan,
879 items.notforloan AS itemnotforloan,
885 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
886 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
891 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
892 $sth->execute($item);
895 $sth = $dbh->prepare("$select WHERE barcode = ?");
896 $sth->execute($barcode);
898 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
899 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
900 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
902 return unless $itemnumber; # bail if we got nothing.
903 # if item is not for loan it cannot be reserved either.....
904 # except where items.notforloan < 0 : This indicates the item is holdable.
906 my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
907 return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
909 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
910 return if $dont_trap or $notforloan_per_itemtype;
912 # Find this item in the reserves
913 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
915 # $priority and $highest are used to find the most important item
916 # in the list returned by &_Findgroupreserve. (The lower $priority,
917 # the more important the item.)
918 # $highest is the most important item we've seen so far.
921 if (scalar @reserves) {
922 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
923 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
924 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
926 my $priority = 10000000;
927 foreach my $res (@reserves) {
928 if ($res->{'found'} && $res->{'found'} eq 'W') {
929 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
930 } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
931 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
932 } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
933 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
937 my $local_hold_match;
939 if ($LocalHoldsPriority) {
940 $patron = Koha::Patrons->find( $res->{borrowernumber} );
941 $item = Koha::Items->find($itemnumber);
943 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
944 my $local_holds_priority_item_branchcode =
945 $item->$LocalHoldsPriorityItemControl;
946 my $local_holds_priority_patron_branchcode =
947 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
949 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
950 ? $patron->branchcode
953 $local_holds_priority_item_branchcode eq
954 $local_holds_priority_patron_branchcode;
958 # See if this item is more important than what we've got so far
959 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
960 $item ||= Koha::Items->find($itemnumber);
961 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
962 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
963 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
964 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
965 next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
966 next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
967 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
968 next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
969 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
970 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
971 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
972 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
973 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
974 $priority = $res->{'priority'};
976 last if $local_hold_match;
982 # If we get this far, then no exact match was found.
983 # We return the most important (i.e. next) reservation.
985 $highest->{'itemnumber'} = $item;
986 return ( "Reserved", $highest, \@reserves );
992 =head2 CancelExpiredReserves
994 CancelExpiredReserves();
996 Cancels all reserves with an expiration date from before today.
1000 sub CancelExpiredReserves {
1001 my $cancellation_reason = shift;
1002 my $today = dt_from_string();
1003 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
1004 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
1006 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
1009 { expirationdate => { '<', $dtf->format_date($today) } },
1010 { patron_expiration_date => { '<' => $dtf->format_date($today) } }
1014 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
1016 # FIXME To move to Koha::Holds->search_expired (?)
1017 my $holds = Koha::Holds->search( $params );
1019 while ( my $hold = $holds->next ) {
1020 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
1022 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
1024 my $cancel_params = {};
1025 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
1026 if ( defined($hold->found) && $hold->found eq 'W' ) {
1027 $cancel_params->{charge_cancel_fee} = 1;
1029 $cancel_params->{autofill} = C4::Context->preference('ExpireReservesAutoFill');
1030 $hold->cancel( $cancel_params );
1034 =head2 AutoUnsuspendReserves
1036 AutoUnsuspendReserves();
1038 Unsuspends all suspended reserves with a suspend_until date from before today.
1042 sub AutoUnsuspendReserves {
1043 my $today = dt_from_string();
1045 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
1047 map { $_->resume() } @holds;
1052 ModReserve({ rank => $rank,
1053 reserve_id => $reserve_id,
1054 branchcode => $branchcode
1055 [, itemnumber => $itemnumber ]
1056 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1059 Change a hold request's priority or cancel it.
1061 C<$rank> specifies the effect of the change. If C<$rank>
1062 is 'n', nothing happens. This corresponds to leaving a
1063 request alone when changing its priority in the holds queue
1066 If C<$rank> is 'del', the hold request is cancelled.
1068 If C<$rank> is an integer greater than zero, the priority of
1069 the request is set to that value. Since priority != 0 means
1070 that the item is not waiting on the hold shelf, setting the
1071 priority to a non-zero value also sets the request's found
1072 status and waiting date to NULL.
1074 If the hold is 'found' (waiting, in-transit, processing) the
1075 only field that can be updated is the expiration date.
1077 The optional C<$itemnumber> parameter is used only when
1078 C<$rank> is a non-zero integer; if supplied, the itemnumber
1079 of the hold request is set accordingly; if omitted, the itemnumber
1082 B<FIXME:> Note that the forgoing can have the effect of causing
1083 item-level hold requests to turn into title-level requests. This
1084 will be fixed once reserves has separate columns for requested
1085 itemnumber and supplying itemnumber.
1090 my ( $params ) = @_;
1092 my $rank = $params->{'rank'};
1093 my $reserve_id = $params->{'reserve_id'};
1094 my $branchcode = $params->{'branchcode'};
1095 my $itemnumber = $params->{'itemnumber'};
1096 my $suspend_until = $params->{'suspend_until'};
1097 my $borrowernumber = $params->{'borrowernumber'};
1098 my $biblionumber = $params->{'biblionumber'};
1099 my $cancellation_reason = $params->{'cancellation_reason'};
1100 my $date = $params->{expirationdate};
1102 return if defined $rank && $rank eq "n";
1104 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1107 unless ( $reserve_id ) {
1108 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1109 return unless $holds->count; # FIXME Should raise an exception
1110 $hold = $holds->next;
1111 $reserve_id = $hold->reserve_id;
1114 $hold ||= Koha::Holds->find($reserve_id);
1116 # FIXME Other calls may fail
1117 Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1119 if ( $rank eq "del" ) {
1120 $hold->cancel({ cancellation_reason => $cancellation_reason });
1122 elsif ($hold->found && $hold->priority eq '0' && $date) {
1123 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1124 if C4::Context->preference('HoldsLog');
1126 # The only column that can be updated for a found hold is the expiration date
1127 $hold->expirationdate(dt_from_string($date))->store();
1129 elsif ($rank =~ /^\d+/ and $rank > 0) {
1130 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1131 if C4::Context->preference('HoldsLog');
1135 branchcode => $branchcode,
1136 itemnumber => $itemnumber,
1138 waitingdate => undef
1140 if (exists $params->{reservedate}) {
1141 $properties->{reservedate} = $params->{reservedate} || undef;
1143 if (exists $params->{expirationdate}) {
1144 $properties->{expirationdate} = $params->{expirationdate} || undef;
1147 $hold->set($properties)->store();
1149 if ( defined( $suspend_until ) ) {
1150 if ( $suspend_until ) {
1151 $suspend_until = eval { dt_from_string( $suspend_until ) };
1152 $hold->suspend_hold( $suspend_until );
1154 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1155 # If the hold is not suspended, this does nothing.
1156 $hold->set( { suspend_until => undef } )->store();
1160 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1164 =head2 ModReserveStatus
1166 &ModReserveStatus($itemnumber, $newstatus);
1168 Update the reserve status for the active (priority=0) reserve.
1170 $itemnumber is the itemnumber the reserve is on
1172 $newstatus is the new status.
1176 sub ModReserveStatus {
1178 #first : check if we have a reservation for this item .
1179 my ($itemnumber, $newstatus) = @_;
1180 my $dbh = C4::Context->dbh;
1182 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1183 my $sth_set = $dbh->prepare($query);
1184 $sth_set->execute( $newstatus, $itemnumber );
1186 my $item = Koha::Items->find($itemnumber);
1187 if ( $item->location && $item->location eq 'CART'
1188 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1190 CartToShelf( $itemnumber );
1194 =head2 ModReserveAffect
1196 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id, $notify_library);
1198 This function affect an item and a status for a given reserve, either fetched directly
1199 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1200 is given, only first reserve returned is affected, which is ok for anything but
1203 if $transferToDo is not set, then the status is set to "Waiting" as well.
1204 otherwise, a transfer is on the way, and the end of the transfer will
1205 take care of the waiting status
1207 This function also removes any entry of the hold in holds queue table.
1211 sub ModReserveAffect {
1212 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id, $notify_library ) = @_;
1213 my $dbh = C4::Context->dbh;
1215 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1216 # attached to $itemnumber
1217 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1218 $sth->execute($itemnumber);
1219 my ($biblionumber) = $sth->fetchrow;
1221 # get request - need to find out if item is already
1222 # waiting in order to not send duplicate hold filled notifications
1225 # Find hold by id if we have it
1226 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1227 # Find item level hold for this item if there is one
1228 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1229 # Find record level hold if there is no item level hold
1230 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1232 return unless $hold;
1234 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1236 $hold->itemnumber($itemnumber);
1238 if ($transferToDo) {
1239 $hold->set_transfer();
1240 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1241 && C4::Context->interface eq 'sip'
1242 && !$already_on_shelf) {
1243 $hold->set_processing();
1245 $hold->set_waiting($desk_id);
1246 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1247 # Complete transfer if one exists
1248 my $transfer = $hold->item->get_transfer;
1249 $transfer->receive if $transfer;
1252 _koha_notify_hold_changed( $hold ) if $notify_library;
1254 _FixPriority( { biblionumber => $biblionumber } );
1255 my $item = Koha::Items->find($itemnumber);
1256 if ( $item->location && $item->location eq 'CART'
1257 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1258 CartToShelf( $itemnumber );
1261 my $std = $dbh->prepare(q{
1263 FROM tmp_holdsqueue q
1264 INNER JOIN hold_fill_targets t
1265 ON q.borrowernumber = t.borrowernumber
1266 AND q.biblionumber = t.biblionumber
1267 AND q.itemnumber = t.itemnumber
1268 AND q.item_level_request = t.item_level_request
1269 AND q.holdingbranch = t.source_branchcode
1270 WHERE t.reserve_id = ?
1272 $std->execute($hold->reserve_id);
1274 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1275 if C4::Context->preference('HoldsLog');
1280 =head2 ModReserveCancelAll
1282 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1284 function to cancel reserv,check other reserves, and transfer document if it's necessary
1288 sub ModReserveCancelAll {
1291 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1293 #step 1 : cancel the reservation
1294 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1295 return unless $holds->count;
1296 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1298 #step 2 launch the subroutine of the others reserves
1299 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1301 return ( $messages, $nextreservinfo->{borrowernumber} );
1304 =head2 ModReserveMinusPriority
1306 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1308 Reduce the values of queued list
1312 sub ModReserveMinusPriority {
1313 my ( $itemnumber, $reserve_id ) = @_;
1315 #first step update the value of the first person on reserv
1316 my $dbh = C4::Context->dbh;
1319 SET priority = 0 , itemnumber = ?
1320 WHERE reserve_id = ?
1322 my $sth_upd = $dbh->prepare($query);
1323 $sth_upd->execute( $itemnumber, $reserve_id );
1324 # second step update all others reserves
1325 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1328 =head2 IsAvailableForItemLevelRequest
1330 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1332 Checks whether a given item record is available for an
1333 item-level hold request. An item is available if
1335 * it is not lost AND
1336 * it is not damaged AND
1337 * it is not withdrawn AND
1338 * a waiting or in transit reserve is placed on
1339 * does not have a not for loan value > 0
1341 Need to check the issuingrules onshelfholds column,
1342 if this is set items on the shelf can be placed on hold
1344 Note that IsAvailableForItemLevelRequest() does not
1345 check if the staff operator is authorized to place
1346 a request on the item - in particular,
1347 this routine does not check IndependentBranches
1348 and canreservefromotherbranches.
1350 Note also that this subroutine does not checks smart
1351 rules limits for item by reservesallowed/holds_per_record
1352 values, this complemented in calling code with calls and
1353 checks with CanItemBeReserved or CanBookBeReserved.
1357 sub IsAvailableForItemLevelRequest {
1360 my $pickup_branchcode = shift;
1361 # items_any_available is precalculated status passed from request.pl when set of items
1362 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1363 my $items_any_available = shift;
1365 my $dbh = C4::Context->dbh;
1366 # must check the notforloan setting of the itemtype
1367 # FIXME - a lot of places in the code do this
1368 # or something similar - need to be
1370 my $itemtype = $item->effective_itemtype;
1372 unless defined $itemtype;
1373 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1376 $notforloan_per_itemtype ||
1378 $item->notforloan > 0 || # item with negative or zero notforloan value is holdable
1380 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1382 if ($pickup_branchcode) {
1383 my $destination = Koha::Libraries->find($pickup_branchcode);
1384 return 0 unless $destination;
1385 return 0 unless $destination->pickup_location;
1386 return 0 unless $item->can_be_transferred( { to => $destination } );
1387 my $reserves_control_branch =
1388 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1389 my $branchitemrule =
1390 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1391 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1392 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1395 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1397 if ( $on_shelf_holds == 1 ) {
1399 } elsif ( $on_shelf_holds == 2 ) {
1401 # if we have this param predefined from outer caller sub, we just need
1402 # to return it, so we saving from having loop inside other loop:
1403 return $items_any_available ? 0 : 1
1404 if defined $items_any_available;
1406 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1407 return $any_available ? 0 : 1;
1408 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1409 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1413 =head2 ItemsAnyAvailableAndNotRestricted
1415 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1417 This function checks all items for specified biblionumber (numeric) against patron (object)
1418 and returns true (1) if at least one item available for loan/check out/present/not held
1419 and also checks other parameters logic which not restricts item for hold at all (for ex.
1420 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1424 sub ItemsAnyAvailableAndNotRestricted {
1427 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1429 foreach my $i (@items) {
1430 my $reserves_control_branch =
1431 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1432 my $branchitemrule =
1433 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1434 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1436 # we can return (end the loop) when first one found:
1439 || $i->notforloan # items with non-zero notforloan cannot be checked out
1442 || IsItemOnHoldAndFound( $i->id )
1444 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1445 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1446 || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1447 || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1448 || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1454 =head2 AlterPriority
1456 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1458 This function changes a reserve's priority up, down, to the top, or to the bottom.
1459 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1464 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1466 my $hold = Koha::Holds->find( $reserve_id );
1467 return unless $hold;
1469 if ( $hold->cancellationdate ) {
1470 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1474 if ( $where eq 'up' ) {
1475 return unless $prev_priority;
1476 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1477 } elsif ( $where eq 'down' ) {
1478 return unless $next_priority;
1479 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1480 } elsif ( $where eq 'top' ) {
1481 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1482 } elsif ( $where eq 'bottom' ) {
1483 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1486 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
1488 biblio_ids => [ $hold->biblionumber ]
1490 ) if C4::Context->preference('RealTimeHoldsQueue');
1491 # FIXME Should return the new priority
1494 =head2 ToggleLowestPriority
1496 ToggleLowestPriority( $borrowernumber, $biblionumber );
1498 This function sets the lowestPriority field to true if is false, and false if it is true.
1502 sub ToggleLowestPriority {
1503 my ( $reserve_id ) = @_;
1505 my $dbh = C4::Context->dbh;
1507 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1508 $sth->execute( $reserve_id );
1510 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1513 =head2 ToggleSuspend
1515 ToggleSuspend( $reserve_id );
1517 This function sets the suspend field to true if is false, and false if it is true.
1518 If the reserve is currently suspended with a suspend_until date, that date will
1519 be cleared when it is unsuspended.
1524 my ( $reserve_id, $suspend_until ) = @_;
1526 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1528 my $hold = Koha::Holds->find( $reserve_id );
1530 if ( $hold->is_suspended ) {
1533 $hold->suspend_hold( $suspend_until );
1540 borrowernumber => $borrowernumber,
1541 [ biblionumber => $biblionumber, ]
1542 [ suspend_until => $suspend_until, ]
1543 [ suspend => $suspend ]
1546 This function accepts a set of hash keys as its parameters.
1547 It requires either borrowernumber or biblionumber, or both.
1549 suspend_until is wholly optional.
1556 my $borrowernumber = $params{'borrowernumber'} || undef;
1557 my $biblionumber = $params{'biblionumber'} || undef;
1558 my $suspend_until = $params{'suspend_until'} || undef;
1559 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1561 $suspend_until = eval { dt_from_string($suspend_until) }
1562 if ( defined($suspend_until) );
1564 return unless ( $borrowernumber || $biblionumber );
1567 $params->{found} = undef;
1568 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1569 $params->{biblionumber} = $biblionumber if $biblionumber;
1571 my @holds = Koha::Holds->search($params)->as_list;
1574 map { $_->suspend_hold($suspend_until) } @holds;
1577 map { $_->resume() } @holds;
1585 reserve_id => $reserve_id,
1587 [ignoreSetLowestRank => $ignoreSetLowestRank]
1592 _FixPriority({ biblionumber => $biblionumber});
1594 This routine adjusts the priority of a hold request and holds
1597 In the first form, where a reserve_id is passed, the priority of the
1598 hold is set to supplied rank, and other holds for that bib are adjusted
1599 accordingly. If the rank is "del", the hold is cancelled. If no rank
1600 is supplied, all of the holds on that bib have their priority adjusted
1601 as if the second form had been used.
1603 In the second form, where a biblionumber is passed, the holds on that
1604 bib (that are not captured) are sorted in order of increasing priority,
1605 then have reserves.priority set so that the first non-captured hold
1606 has its priority set to 1, the second non-captured hold has its priority
1607 set to 2, and so forth.
1609 In both cases, holds that have the lowestPriority flag on are have their
1610 priority adjusted to ensure that they remain at the end of the line.
1612 Note that the ignoreSetLowestRank parameter is meant to be used only
1613 when _FixPriority calls itself.
1618 my ( $params ) = @_;
1619 my $reserve_id = $params->{reserve_id};
1620 my $rank = $params->{rank} // '';
1621 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1622 my $biblionumber = $params->{biblionumber};
1624 my $dbh = C4::Context->dbh;
1627 if ( $reserve_id ) {
1628 $hold = Koha::Holds->find( $reserve_id );
1629 if (!defined $hold){
1630 # may have already been checked out and hold fulfilled
1631 $hold = Koha::Old::Holds->find( $reserve_id );
1633 return unless $hold;
1636 unless ( $biblionumber ) { # FIXME This is a very weird API
1637 $biblionumber = $hold->biblionumber;
1640 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1643 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1645 # make sure priority for waiting or in-transit items is 0
1649 WHERE reserve_id = ?
1650 AND found IN ('W', 'T', 'P')
1652 my $sth = $dbh->prepare($query);
1653 $sth->execute( $reserve_id );
1659 SELECT reserve_id, borrowernumber, reservedate
1661 WHERE biblionumber = ?
1662 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1663 ORDER BY priority ASC
1665 my $sth = $dbh->prepare($query);
1666 $sth->execute( $biblionumber );
1667 while ( my $line = $sth->fetchrow_hashref ) {
1668 push( @priority, $line );
1671 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1672 # To find the matching index
1674 my $key = -1; # to allow for 0 to be a valid result
1675 for ( $i = 0 ; $i < @priority ; $i++ ) {
1676 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1677 $key = $i; # save the index
1682 # if index exists in array then move it to new position
1683 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1684 my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1685 my $moving_item = splice( @priority, $key, 1 );
1686 $new_rank = scalar @priority if $new_rank > scalar @priority;
1687 splice( @priority, $new_rank, 0, $moving_item );
1690 # now fix the priority on those that are left....
1694 WHERE reserve_id = ?
1696 $sth = $dbh->prepare($query);
1697 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1700 $priority[$j]->{'reserve_id'}
1704 unless ( $ignoreSetLowestRank ) {
1705 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1706 $sth->execute($biblionumber);
1707 while ( my $res = $sth->fetchrow_hashref() ) {
1709 reserve_id => $res->{'reserve_id'},
1711 ignoreSetLowestRank => 1
1717 =head2 _Findgroupreserve
1719 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1721 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1722 first match found. If neither, then we look for non-holds-queue based holds.
1723 Lookahead is the number of days to look in advance.
1725 C<&_Findgroupreserve> returns :
1726 C<@results> is an array of references-to-hash whose keys are mostly
1727 fields from the reserves table of the Koha database, plus
1728 C<biblioitemnumber>.
1730 This routine with either return:
1731 1 - Item specific holds from the holds queue
1732 2 - Title level holds from the holds queue
1733 3 - All holds for this biblionumber
1735 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1739 sub _Findgroupreserve {
1740 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1741 my $dbh = C4::Context->dbh;
1743 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1744 # check for exact targeted match
1745 my $item_level_target_query = qq{
1746 SELECT reserves.biblionumber AS biblionumber,
1747 reserves.borrowernumber AS borrowernumber,
1748 reserves.reservedate AS reservedate,
1749 reserves.branchcode AS branchcode,
1750 reserves.cancellationdate AS cancellationdate,
1751 reserves.found AS found,
1752 reserves.reservenotes AS reservenotes,
1753 reserves.priority AS priority,
1754 reserves.timestamp AS timestamp,
1755 biblioitems.biblioitemnumber AS biblioitemnumber,
1756 reserves.itemnumber AS itemnumber,
1757 reserves.reserve_id AS reserve_id,
1758 reserves.itemtype AS itemtype,
1759 reserves.non_priority AS non_priority
1761 JOIN biblioitems USING (biblionumber)
1762 JOIN hold_fill_targets USING (reserve_id)
1765 AND item_level_request = 1
1766 AND hold_fill_targets.itemnumber = ?
1767 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1771 my $sth = $dbh->prepare($item_level_target_query);
1772 $sth->execute($itemnumber, $lookahead||0);
1774 if ( my $data = $sth->fetchrow_hashref ) {
1775 push( @results, $data )
1776 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1778 return @results if @results;
1780 # check for title-level targeted match
1781 my $title_level_target_query = qq{
1782 SELECT reserves.biblionumber AS biblionumber,
1783 reserves.borrowernumber AS borrowernumber,
1784 reserves.reservedate AS reservedate,
1785 reserves.branchcode AS branchcode,
1786 reserves.cancellationdate AS cancellationdate,
1787 reserves.found AS found,
1788 reserves.reservenotes AS reservenotes,
1789 reserves.priority AS priority,
1790 reserves.timestamp AS timestamp,
1791 biblioitems.biblioitemnumber AS biblioitemnumber,
1792 reserves.itemnumber AS itemnumber,
1793 reserves.reserve_id AS reserve_id,
1794 reserves.itemtype AS itemtype,
1795 reserves.non_priority AS non_priority
1797 JOIN biblioitems USING (biblionumber)
1798 JOIN hold_fill_targets USING (reserve_id)
1801 AND item_level_request = 0
1802 AND hold_fill_targets.itemnumber = ?
1803 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1807 $sth = $dbh->prepare($title_level_target_query);
1808 $sth->execute($itemnumber, $lookahead||0);
1810 if ( my $data = $sth->fetchrow_hashref ) {
1811 push( @results, $data )
1812 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1814 return @results if @results;
1817 SELECT reserves.biblionumber AS biblionumber,
1818 reserves.borrowernumber AS borrowernumber,
1819 reserves.reservedate AS reservedate,
1820 reserves.waitingdate AS waitingdate,
1821 reserves.branchcode AS branchcode,
1822 reserves.cancellationdate AS cancellationdate,
1823 reserves.found AS found,
1824 reserves.reservenotes AS reservenotes,
1825 reserves.priority AS priority,
1826 reserves.timestamp AS timestamp,
1827 reserves.itemnumber AS itemnumber,
1828 reserves.reserve_id AS reserve_id,
1829 reserves.itemtype AS itemtype,
1830 reserves.non_priority AS non_priority
1832 WHERE reserves.biblionumber = ?
1833 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1834 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1838 $sth = $dbh->prepare($query);
1839 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1841 while ( my $data = $sth->fetchrow_hashref ) {
1842 push( @results, $data )
1843 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1848 =head2 _koha_notify_reserve
1850 _koha_notify_reserve( $hold->reserve_id );
1852 Sends a notification to the patron that their hold has been filled (through
1855 The letter code for this notice may be found using the following query:
1857 select distinct letter_code
1858 from message_transports
1859 inner join message_attributes using (message_attribute_id)
1860 where message_name = 'Hold_Filled'
1862 This will probably sipmly be 'HOLD', but because it is defined in the database,
1863 it is subject to addition or change.
1865 The following tables are availalbe witin the notice:
1876 sub _koha_notify_reserve {
1877 my $reserve_id = shift;
1878 my $notify_library = shift;
1880 my $hold = Koha::Holds->find($reserve_id);
1881 my $borrowernumber = $hold->borrowernumber;
1883 my $patron = Koha::Patrons->find( $borrowernumber );
1885 # Try to get the borrower's email address
1886 my $to_address = $patron->notice_email_address;
1888 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1889 borrowernumber => $borrowernumber,
1890 message_name => 'Hold_Filled'
1893 my $library = Koha::Libraries->find( $hold->branchcode );
1894 my $admin_email_address = $library->from_email_address;
1895 $library = $library->unblessed;
1897 my %letter_params = (
1898 module => 'reserves',
1899 branchcode => $hold->branchcode,
1900 lang => $patron->lang,
1902 'branches' => $library,
1903 'borrowers' => $patron->unblessed,
1904 'biblio' => $hold->biblionumber,
1905 'biblioitems' => $hold->biblionumber,
1906 'reserves' => $hold->unblessed,
1907 'items' => $hold->itemnumber,
1911 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.
1912 my $send_notification = sub {
1913 my ( $mtt, $letter_code ) = (@_);
1914 return unless defined $letter_code;
1915 $letter_params{letter_code} = $letter_code;
1916 $letter_params{message_transport_type} = $mtt;
1917 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1919 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1923 C4::Letters::EnqueueLetter( {
1925 borrowernumber => $borrowernumber,
1926 from_address => $admin_email_address,
1927 message_transport_type => $mtt,
1931 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1933 ( $mtt eq 'email' and not $to_address ) # No email address
1934 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1935 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1936 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1939 &$send_notification($mtt, $letter_code);
1940 $notification_sent++;
1942 #Making sure that a print notification is sent if no other transport types can be utilized.
1943 if (! $notification_sent) {
1944 &$send_notification('print', 'HOLD');
1947 if ($notify_library) {
1948 my $letter = C4::Letters::GetPreparedLetter(
1949 module => 'reserves',
1950 letter_code => 'HOLD_CHANGED',
1951 branchcode => $hold->branchcode,
1952 substitute => { today => output_pref( dt_from_string ) },
1954 'branches' => $library,
1955 'borrowers' => $patron->unblessed,
1956 'biblio' => $hold->biblionumber,
1957 'biblioitems' => $hold->biblionumber,
1958 'reserves' => $hold->unblessed,
1959 'items' => $hold->itemnumber,
1964 C4::Context->preference('ExpireReservesAutoFillEmail')
1965 || $library->{branchemail}
1966 || C4::Context->preference('KohaAdminEmailAddress');
1968 C4::Letters::EnqueueLetter(
1971 borrowernumber => $borrowernumber,
1972 message_transport_type => 'email',
1973 from_address => $email,
1974 to_address => $email,
1980 =head2 _koha_notify_hold_changed
1982 _koha_notify_hold_changed( $hold_object );
1986 sub _koha_notify_hold_changed {
1989 my $patron = $hold->patron;
1990 my $library = $hold->branch;
1992 my $letter = C4::Letters::GetPreparedLetter(
1993 module => 'reserves',
1994 letter_code => 'HOLD_CHANGED',
1995 branchcode => $hold->branchcode,
1996 substitute => { today => output_pref( dt_from_string ) },
1998 'branches' => $library->unblessed,
1999 'borrowers' => $patron->unblessed,
2000 'biblio' => $hold->biblionumber,
2001 'biblioitems' => $hold->biblionumber,
2002 'reserves' => $hold->unblessed,
2003 'items' => $hold->itemnumber,
2007 return unless $letter;
2010 C4::Context->preference('ExpireReservesAutoFillEmail')
2011 || $library->branchemail
2012 || C4::Context->preference('KohaAdminEmailAddress');
2014 C4::Letters::EnqueueLetter(
2017 borrowernumber => $patron->id,
2018 message_transport_type => 'email',
2019 from_address => $email,
2020 to_address => $email,
2025 =head2 _ShiftPriority
2027 $new_priority = _ShiftPriority( $biblionumber, $priority );
2029 This increments the priority of all reserves after the one
2030 with either the lowest date after C<$reservedate>
2031 or the lowest priority after C<$priority>.
2033 It effectively makes room for a new reserve to be inserted with a certain
2034 priority, which is returned.
2036 This is most useful when the reservedate can be set by the user. It allows
2037 the new reserve to be placed before other reserves that have a later
2038 reservedate. Since priority also is set by the form in reserves/request.pl
2039 the sub accounts for that too.
2043 sub _ShiftPriority {
2044 my ( $biblio, $new_priority ) = @_;
2046 my $dbh = C4::Context->dbh;
2047 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND priority > ? ORDER BY priority ASC LIMIT 1";
2048 my $sth = $dbh->prepare( $query );
2049 $sth->execute( $biblio, $new_priority );
2050 my $min_priority = $sth->fetchrow;
2051 # if no such matches are found, $new_priority remains as original value
2052 $new_priority = $min_priority if ( $min_priority );
2054 # Shift the priority up by one; works in conjunction with the next SQL statement
2055 $query = "UPDATE reserves
2056 SET priority = priority+1
2057 WHERE biblionumber = ?
2058 AND borrowernumber = ?
2061 my $sth_update = $dbh->prepare( $query );
2063 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2064 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2065 $sth = $dbh->prepare( $query );
2066 $sth->execute( $new_priority, $biblio );
2067 while ( my $row = $sth->fetchrow_hashref ) {
2068 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2071 return $new_priority; # so the caller knows what priority they wind up receiving
2076 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2078 Use when checking out an item to handle reserves
2079 If $cancelreserve boolean is set to true, it will remove existing reserve
2084 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2086 $cancelreserve //= 0;
2088 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2089 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
2092 my $biblionumber = $res->{biblionumber};
2094 if ($res->{borrowernumber} == $borrowernumber) {
2095 my $hold = Koha::Holds->find( $res->{reserve_id} );
2100 # The item is reserved by someone else.
2101 # Find this item in the reserves
2103 my $borr_res = Koha::Holds->search({
2104 borrowernumber => $borrowernumber,
2105 biblionumber => $biblionumber,
2107 order_by => 'priority'
2111 # The item is reserved by the current patron
2115 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2116 RevertWaitingStatus({ itemnumber => $itemnumber });
2118 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2119 my $hold = Koha::Holds->find( $res->{reserve_id} );
2127 MergeHolds($dbh,$to_biblio, $from_biblio);
2129 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2134 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2135 my $sth = $dbh->prepare(
2136 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2138 $sth->execute($from_biblio);
2139 if ( my $data = $sth->fetchrow_hashref() ) {
2141 # holds exist on old record, if not we don't need to do anything
2142 $sth = $dbh->prepare(
2143 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2144 $sth->execute( $to_biblio, $from_biblio );
2147 # don't reorder those already waiting
2149 $sth = $dbh->prepare(
2150 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2152 my $upd_sth = $dbh->prepare(
2153 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2154 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2156 $sth->execute( $to_biblio );
2158 while ( my $reserve = $sth->fetchrow_hashref() ) {
2160 $priority, $to_biblio,
2161 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2162 $reserve->{'itemnumber'}
2169 =head2 RevertWaitingStatus
2171 RevertWaitingStatus({ itemnumber => $itemnumber });
2173 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2175 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2176 item level hold, even if it was only a bibliolevel hold to
2177 begin with. This is because we can no longer know if a hold
2178 was item-level or bib-level after a hold has been set to
2183 sub RevertWaitingStatus {
2184 my ( $params ) = @_;
2185 my $itemnumber = $params->{'itemnumber'};
2187 return unless ( $itemnumber );
2189 my $dbh = C4::Context->dbh;
2191 ## Get the waiting reserve we want to revert
2192 my $hold = Koha::Holds->search(
2194 itemnumber => $itemnumber,
2195 found => { not => undef },
2199 ## Increment the priority of all other non-waiting
2200 ## reserves for this bib record
2201 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2202 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2204 ## Fix up the currently waiting reserve
2209 waitingdate => undef,
2210 expirationdate => $hold->patron_expiration_date,
2211 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2215 _FixPriority( { biblionumber => $hold->biblionumber } );
2217 Koha::BackgroundJob::BatchUpdateBiblioHoldsQueue->new->enqueue(
2219 biblio_ids => [ $hold->biblionumber ]
2221 ) if C4::Context->preference('RealTimeHoldsQueue');
2231 branchcode => $branchcode,
2232 borrowernumber => $borrowernumber,
2233 biblionumber => $biblionumber,
2234 [ itemnumber => $itemnumber, ]
2235 [ barcode => $barcode, ]
2239 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2241 The letter code will be HOLD_SLIP, and the following tables are
2242 available within the slip:
2255 my $branchcode = $args->{branchcode};
2256 my $reserve_id = $args->{reserve_id};
2258 my $hold = Koha::Holds->find($reserve_id);
2259 return unless $hold;
2261 my $patron = $hold->borrower;
2262 my $reserve = $hold->unblessed;
2264 return C4::Letters::GetPreparedLetter (
2265 module => 'circulation',
2266 letter_code => 'HOLD_SLIP',
2267 branchcode => $branchcode,
2268 lang => $patron->lang,
2270 'reserves' => $reserve,
2271 'branches' => $reserve->{branchcode},
2272 'borrowers' => $reserve->{borrowernumber},
2273 'biblio' => $reserve->{biblionumber},
2274 'biblioitems' => $reserve->{biblionumber},
2275 'items' => $reserve->{itemnumber},
2280 =head2 GetReservesControlBranch
2282 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2284 Return the branchcode to be used to determine which reserves
2285 policy applies to a transaction.
2287 C<$item> is a hashref for an item. Only 'homebranch' is used.
2289 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2293 sub GetReservesControlBranch {
2294 my ( $item, $borrower ) = @_;
2296 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2299 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2300 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2306 =head2 CalculatePriority
2308 my $p = CalculatePriority($biblionumber, $resdate);
2310 Calculate priority for a new reserve on biblionumber, placing it at
2311 the end of the line of all holds whose start date falls before
2312 the current system time and that are neither on the hold shelf
2315 The reserve date parameter is optional; if it is supplied, the
2316 priority is based on the set of holds whose start date falls before
2317 the parameter value.
2319 After calculation of this priority, it is recommended to call
2320 _ShiftPriority. Note that this is currently done in
2325 sub CalculatePriority {
2326 my ( $biblionumber, $resdate ) = @_;
2329 SELECT COUNT(*) FROM reserves
2330 WHERE biblionumber = ?
2332 AND (found IS NULL OR found = '')
2334 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2336 $sql.= ' AND ( reservedate <= ? )';
2339 $sql.= ' AND ( reservedate < NOW() )';
2341 my $dbh = C4::Context->dbh();
2342 my @row = $dbh->selectrow_array(
2345 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2348 return @row ? $row[0]+1 : 1;
2351 =head2 IsItemOnHoldAndFound
2353 my $bool = IsItemFoundHold( $itemnumber );
2355 Returns true if the item is currently on hold
2356 and that hold has a non-null found status ( W, T, etc. )
2360 sub IsItemOnHoldAndFound {
2361 my ($itemnumber) = @_;
2363 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2365 my $found = $rs->count(
2367 itemnumber => $itemnumber,
2368 found => { '!=' => undef }
2375 =head2 GetMaxPatronHoldsForRecord
2377 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2379 For multiple holds on a given record for a given patron, the max
2380 number of record level holds that a patron can be placed is the highest
2381 value of the holds_per_record rule for each item if the record for that
2382 patron. This subroutine finds and returns the highest holds_per_record
2383 rule value for a given patron id and record id.
2387 sub GetMaxPatronHoldsForRecord {
2388 my ( $borrowernumber, $biblionumber ) = @_;
2390 my $patron = Koha::Patrons->find($borrowernumber);
2391 my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2393 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2395 my $categorycode = $patron->categorycode;
2397 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2400 foreach my $item (@items) {
2401 my $itemtype = $item->effective_itemtype();
2403 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2405 my $rule = Koha::CirculationRules->get_effective_rule({
2406 categorycode => $categorycode,
2407 itemtype => $itemtype,
2408 branchcode => $branchcode,
2409 rule_name => 'holds_per_record'
2411 my $holds_per_record = $rule ? $rule->rule_value : 0;
2412 $max = $holds_per_record if $holds_per_record > $max;
2420 Koha Development Team <http://koha-community.org/>