Bug 23591: Hide archived suggestions
[koha.git] / C4 / Reserves.pm
blobb4cc6c470d111a2e8da78291ed36b8e708df0f38
1 package C4::Reserves;
3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
6 # 2011 Catalyst IT
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>.
24 use Modern::Perl;
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Items;
31 use C4::Letters;
32 use C4::Log;
33 use C4::Members::Messaging;
34 use C4::Members;
35 use Koha::Account::Lines;
36 use Koha::Biblios;
37 use Koha::Calendar;
38 use Koha::CirculationRules;
39 use Koha::Database;
40 use Koha::DateUtils;
41 use Koha::Hold;
42 use Koha::Holds;
43 use Koha::ItemTypes;
44 use Koha::Items;
45 use Koha::Libraries;
46 use Koha::Old::Hold;
47 use Koha::Patrons;
49 use Carp;
50 use Data::Dumper;
51 use List::MoreUtils qw( firstidx any );
53 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
55 =head1 NAME
57 C4::Reserves - Koha functions for dealing with reservation.
59 =head1 SYNOPSIS
61 use C4::Reserves;
63 =head1 DESCRIPTION
65 This modules provides somes functions to deal with reservations.
67 Reserves are stored in reserves table.
68 The following columns contains important values :
69 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
70 =0 : then the reserve is being dealed
71 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
72 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
73 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
74 F(inished) : the reserve has been completed, and is done
75 - itemnumber : empty : the reserve is still unaffected to an item
76 filled: the reserve is attached to an item
77 The complete workflow is :
78 ==== 1st use case ====
79 patron request a document, 1st available : P >0, F=NULL, I=NULL
80 a library having it run "transfertodo", and clic on the list
81 if there is no transfer to do, the reserve waiting
82 patron can pick it up P =0, F=W, I=filled
83 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it check in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
87 ==== 2nd use case ====
88 patron requests a document, a given item,
89 If pickup is holding branch P =0, F=W, I=filled
90 If transfer needed, write in branchtransfer P =0, F=T, I=filled
91 The pickup library receive the book, it checks it in P =0, F=W, I=filled
92 The patron borrow the book P =0, F=F, I=filled
94 =head1 FUNCTIONS
96 =cut
98 BEGIN {
99 require Exporter;
100 @ISA = qw(Exporter);
101 @EXPORT = qw(
102 &AddReserve
104 &GetReserveStatus
106 &GetOtherReserves
108 &ModReserveFill
109 &ModReserveAffect
110 &ModReserve
111 &ModReserveStatus
112 &ModReserveCancelAll
113 &ModReserveMinusPriority
114 &MoveReserve
116 &CheckReserves
117 &CanBookBeReserved
118 &CanItemBeReserved
119 &CanReserveBeCanceledFromOpac
120 &CancelExpiredReserves
122 &AutoUnsuspendReserves
124 &IsAvailableForItemLevelRequest
125 ItemsAnyAvailableForHold
127 &AlterPriority
128 &ToggleLowestPriority
130 &ReserveSlip
131 &ToggleSuspend
132 &SuspendAll
134 &GetReservesControlBranch
136 IsItemOnHoldAndFound
138 GetMaxPatronHoldsForRecord
140 @EXPORT_OK = qw( MergeHolds );
143 =head2 AddReserve
145 AddReserve(
147 branch => $branchcode,
148 borrowernumber => $borrowernumber,
149 biblionumber => $biblionumber,
150 priority => $priority,
151 reservation_date => $reservation_date,
152 expiration_date => $expiration_date,
153 notes => $notes,
154 title => $title,
155 itemnumber => $itemnumber,
156 found => $found,
157 itemtype => $itemtype,
161 Adds reserve and generates HOLDPLACED message.
163 The following tables are available witin the HOLDPLACED message:
165 branches
166 borrowers
167 biblio
168 biblioitems
169 items
170 reserves
172 =cut
174 sub AddReserve {
175 my ($params) = @_;
176 my $branch = $params->{branchcode};
177 my $borrowernumber = $params->{borrowernumber};
178 my $biblionumber = $params->{biblionumber};
179 my $priority = $params->{priority};
180 my $resdate = $params->{reservation_date};
181 my $expdate = $params->{expiration_date};
182 my $notes = $params->{notes};
183 my $title = $params->{title};
184 my $checkitem = $params->{itemnumber};
185 my $found = $params->{found};
186 my $itemtype = $params->{itemtype};
188 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
189 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
191 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
193 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
194 # of the document, we force the value $priority and $found .
195 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
196 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
198 if (
199 # If item is already checked out, it cannot be set waiting
200 !$item->onloan
202 # The item can't be waiting if it needs a transfer
203 && $item->holdingbranch eq $branch
205 # Similarly, if in transit it can't be waiting
206 && !$item->get_transfer
208 # If we can't hold damaged items, and it is damaged, it can't be waiting
209 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
211 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
212 && !$item->current_holds->count )
214 $priority = 0;
215 $found = 'W';
219 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
221 # Make room in reserves for this before those of a later reserve date
222 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
225 my $waitingdate;
227 # If the reserv had the waiting status, we had the value of the resdate
228 if ( $found && $found eq 'W' ) {
229 $waitingdate = $resdate;
232 # Don't add itemtype limit if specific item is selected
233 $itemtype = undef if $checkitem;
235 # updates take place here
236 my $hold = Koha::Hold->new(
238 borrowernumber => $borrowernumber,
239 biblionumber => $biblionumber,
240 reservedate => $resdate,
241 branchcode => $branch,
242 priority => $priority,
243 reservenotes => $notes,
244 itemnumber => $checkitem,
245 found => $found,
246 waitingdate => $waitingdate,
247 expirationdate => $expdate,
248 itemtype => $itemtype,
249 item_level_hold => $checkitem ? 1 : 0,
251 )->store();
252 $hold->set_waiting() if $found && $found eq 'W';
254 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
255 if C4::Context->preference('HoldsLog');
257 my $reserve_id = $hold->id();
259 # add a reserve fee if needed
260 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
261 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
262 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
265 _FixPriority({ biblionumber => $biblionumber});
267 # Send e-mail to librarian if syspref is active
268 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
269 my $patron = Koha::Patrons->find( $borrowernumber );
270 my $library = $patron->library;
271 if ( my $letter = C4::Letters::GetPreparedLetter (
272 module => 'reserves',
273 letter_code => 'HOLDPLACED',
274 branchcode => $branch,
275 lang => $patron->lang,
276 tables => {
277 'branches' => $library->unblessed,
278 'borrowers' => $patron->unblessed,
279 'biblio' => $biblionumber,
280 'biblioitems' => $biblionumber,
281 'items' => $checkitem,
282 'reserves' => $hold->unblessed,
284 ) ) {
286 my $branch_email_address = $library->inbound_email_address;
288 C4::Letters::EnqueueLetter(
290 letter => $letter,
291 borrowernumber => $borrowernumber,
292 message_transport_type => 'email',
293 to_address => $branch_email_address,
299 return $reserve_id;
302 =head2 CanBookBeReserved
304 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
305 if ($canReserve eq 'OK') { #We can reserve this Item! }
307 See CanItemBeReserved() for possible return values.
309 =cut
311 sub CanBookBeReserved{
312 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
314 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
315 #get items linked via host records
316 my @hostitems = get_hostitemnumbers_of($biblionumber);
317 if (@hostitems){
318 push (@itemnumbers, @hostitems);
321 my $canReserve = { status => '' };
322 foreach my $itemnumber (@itemnumbers) {
323 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
324 return { status => 'OK' } if $canReserve->{status} eq 'OK';
326 return $canReserve;
329 =head2 CanItemBeReserved
331 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
332 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
334 @RETURNS { status => OK }, if the Item can be reserved.
335 { status => ageRestricted }, if the Item is age restricted for this borrower.
336 { status => damaged }, if the Item is damaged.
337 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
338 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
339 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
340 { status => notReservable }, if holds on this item are not allowed
341 { status => libraryNotFound }, if given branchcode is not an existing library
342 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
343 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
344 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
346 =cut
348 sub CanItemBeReserved {
349 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
351 my $dbh = C4::Context->dbh;
352 my $ruleitemtype; # itemtype of the matching issuing rule
353 my $allowedreserves = 0; # Total number of holds allowed across all records
354 my $holds_per_record = 1; # Total number of holds allowed for this one given record
355 my $holds_per_day; # Default to unlimited
357 # we retrieve borrowers and items informations #
358 # item->{itype} will come for biblioitems if necessery
359 my $item = Koha::Items->find($itemnumber);
360 my $biblio = $item->biblio;
361 my $patron = Koha::Patrons->find( $borrowernumber );
362 my $borrower = $patron->unblessed;
364 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
365 return { status =>'damaged' }
366 if ( $item->damaged
367 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
369 # Check for the age restriction
370 my ( $ageRestriction, $daysToAgeRestriction ) =
371 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
372 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
374 # Check that the patron doesn't have an item level hold on this item already
375 return { status =>'itemAlreadyOnHold' }
376 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
378 my $controlbranch = C4::Context->preference('ReservesControlBranch');
380 my $querycount = q{
381 SELECT count(*) AS count
382 FROM reserves
383 LEFT JOIN items USING (itemnumber)
384 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
385 LEFT JOIN borrowers USING (borrowernumber)
386 WHERE borrowernumber = ?
389 my $branchcode = "";
390 my $branchfield = "reserves.branchcode";
392 if ( $controlbranch eq "ItemHomeLibrary" ) {
393 $branchfield = "items.homebranch";
394 $branchcode = $item->homebranch;
396 elsif ( $controlbranch eq "PatronLibrary" ) {
397 $branchfield = "borrowers.branchcode";
398 $branchcode = $borrower->{branchcode};
401 # we retrieve rights
402 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
403 $ruleitemtype = $rights->{itemtype};
404 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
405 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
406 $holds_per_day = $rights->{holds_per_day};
408 else {
409 $ruleitemtype = undef;
412 my $holds = Koha::Holds->search(
414 borrowernumber => $borrowernumber,
415 biblionumber => $item->biblionumber,
418 if ( defined $holds_per_record && $holds_per_record ne ''
419 && $holds->count() >= $holds_per_record ) {
420 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
423 my $today_holds = Koha::Holds->search({
424 borrowernumber => $borrowernumber,
425 reservedate => dt_from_string->date
428 if ( defined $holds_per_day && $holds_per_day ne ''
429 && $today_holds->count() >= $holds_per_day )
431 return { status => 'tooManyReservesToday', limit => $holds_per_day };
434 # we retrieve count
436 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
438 # If using item-level itypes, fall back to the record
439 # level itemtype if the hold has no associated item
440 $querycount .=
441 C4::Context->preference('item-level_itypes')
442 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
443 : " AND biblioitems.itemtype = ?"
444 if defined $ruleitemtype;
446 my $sthcount = $dbh->prepare($querycount);
448 if ( defined $ruleitemtype ) {
449 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
451 else {
452 $sthcount->execute( $borrowernumber, $branchcode );
455 my $reservecount = "0";
456 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
457 $reservecount = $rowcount->{count};
460 # we check if it's ok or not
461 if ( defined $allowedreserves && $allowedreserves ne ''
462 && $reservecount >= $allowedreserves ) {
463 return { status => 'tooManyReserves', limit => $allowedreserves };
466 # Now we need to check hold limits by patron category
467 my $rule = Koha::CirculationRules->get_effective_rule(
469 categorycode => $borrower->{categorycode},
470 branchcode => $branchcode,
471 rule_name => 'max_holds',
474 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
475 my $total_holds_count = Koha::Holds->search(
477 borrowernumber => $borrower->{borrowernumber}
479 )->count();
481 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
484 my $reserves_control_branch =
485 GetReservesControlBranch( $item->unblessed(), $borrower );
486 my $branchitemrule =
487 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
489 if ( $branchitemrule->{holdallowed} == 0 ) {
490 return { status => 'notReservable' };
493 if ( $branchitemrule->{holdallowed} == 1
494 && $borrower->{branchcode} ne $item->homebranch )
496 return { status => 'cannotReserveFromOtherBranches' };
499 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
500 if ( $branchitemrule->{holdallowed} == 3) {
501 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
502 return { status => 'branchNotInHoldGroup' };
506 # If reservecount is ok, we check item branch if IndependentBranches is ON
507 # and canreservefromotherbranches is OFF
508 if ( C4::Context->preference('IndependentBranches')
509 and !C4::Context->preference('canreservefromotherbranches') )
511 if ( $item->homebranch ne $borrower->{branchcode} ) {
512 return { status => 'cannotReserveFromOtherBranches' };
516 if ($pickup_branchcode) {
517 my $destination = Koha::Libraries->find({
518 branchcode => $pickup_branchcode,
521 unless ($destination) {
522 return { status => 'libraryNotFound' };
524 unless ($destination->pickup_location) {
525 return { status => 'libraryNotPickupLocation' };
527 unless ($item->can_be_transferred({ to => $destination })) {
528 return { status => 'cannotBeTransferred' };
530 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
531 return { status => 'pickupNotInHoldGroup' };
533 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
534 return { status => 'pickupNotInHoldGroup' };
538 return { status => 'OK' };
541 =head2 CanReserveBeCanceledFromOpac
543 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
545 returns 1 if reserve can be cancelled by user from OPAC.
546 First check if reserve belongs to user, next checks if reserve is not in
547 transfer or waiting status
549 =cut
551 sub CanReserveBeCanceledFromOpac {
552 my ($reserve_id, $borrowernumber) = @_;
554 return unless $reserve_id and $borrowernumber;
555 my $reserve = Koha::Holds->find($reserve_id);
557 return 0 unless $reserve->borrowernumber == $borrowernumber;
558 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
560 return 1;
564 =head2 GetOtherReserves
566 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
568 Check queued list of this document and check if this document must be transferred
570 =cut
572 sub GetOtherReserves {
573 my ($itemnumber) = @_;
574 my $messages;
575 my $nextreservinfo;
576 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
577 if ($checkreserves) {
578 my $item = Koha::Items->find($itemnumber);
579 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
580 $messages->{'transfert'} = $checkreserves->{'branchcode'};
581 #minus priorities of others reservs
582 ModReserveMinusPriority(
583 $itemnumber,
584 $checkreserves->{'reserve_id'},
587 #launch the subroutine dotransfer
588 C4::Items::ModItemTransfer(
589 $itemnumber,
590 $item->holdingbranch,
591 $checkreserves->{'branchcode'},
592 'Reserve'
597 #step 2b : case of a reservation on the same branch, set the waiting status
598 else {
599 $messages->{'waiting'} = 1;
600 ModReserveMinusPriority(
601 $itemnumber,
602 $checkreserves->{'reserve_id'},
604 ModReserveStatus($itemnumber,'W');
607 $nextreservinfo = $checkreserves->{'borrowernumber'};
610 return ( $messages, $nextreservinfo );
613 =head2 ChargeReserveFee
615 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
617 Charge the fee for a reserve (if $fee > 0)
619 =cut
621 sub ChargeReserveFee {
622 my ( $borrowernumber, $fee, $title ) = @_;
623 return if !$fee || $fee == 0; # the last test is needed to include 0.00
624 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
626 amount => $fee,
627 description => $title,
628 note => undef,
629 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
630 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
631 interface => C4::Context->interface,
632 invoice_type => undef,
633 type => 'RESERVE',
634 item_id => undef
639 =head2 GetReserveFee
641 $fee = GetReserveFee( $borrowernumber, $biblionumber );
643 Calculate the fee for a reserve (if applicable).
645 =cut
647 sub GetReserveFee {
648 my ( $borrowernumber, $biblionumber ) = @_;
649 my $borquery = qq{
650 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
652 my $issue_qry = qq{
653 SELECT COUNT(*) FROM items
654 LEFT JOIN issues USING (itemnumber)
655 WHERE items.biblionumber=? AND issues.issue_id IS NULL
657 my $holds_qry = qq{
658 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
661 my $dbh = C4::Context->dbh;
662 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
663 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
664 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
665 # This is a reconstruction of the old code:
666 # Compare number of items with items issued, and optionally check holds
667 # If not all items are issued and there are no holds: charge no fee
668 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
669 my ( $notissued, $reserved );
670 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
671 ( $biblionumber ) );
672 if( $notissued ) {
673 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
674 ( $biblionumber, $borrowernumber ) );
675 $fee = 0 if $reserved == 0;
678 return $fee;
681 =head2 GetReserveStatus
683 $reservestatus = GetReserveStatus($itemnumber);
685 Takes an itemnumber and returns the status of the reserve placed on it.
686 If several reserves exist, the reserve with the lower priority is given.
688 =cut
690 ## FIXME: I don't think this does what it thinks it does.
691 ## It only ever checks the first reserve result, even though
692 ## multiple reserves for that bib can have the itemnumber set
693 ## the sub is only used once in the codebase.
694 sub GetReserveStatus {
695 my ($itemnumber) = @_;
697 my $dbh = C4::Context->dbh;
699 my ($sth, $found, $priority);
700 if ( $itemnumber ) {
701 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
702 $sth->execute($itemnumber);
703 ($found, $priority) = $sth->fetchrow_array;
706 if(defined $found) {
707 return 'Waiting' if $found eq 'W' and $priority == 0;
708 return 'Finished' if $found eq 'F';
711 return 'Reserved' if defined $priority && $priority > 0;
713 return ''; # empty string here will remove need for checking undef, or less log lines
716 =head2 CheckReserves
718 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
719 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
720 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
722 Find a book in the reserves.
724 C<$itemnumber> is the book's item number.
725 C<$lookahead> is the number of days to look in advance for future reserves.
727 As I understand it, C<&CheckReserves> looks for the given item in the
728 reserves. If it is found, that's a match, and C<$status> is set to
729 C<Waiting>.
731 Otherwise, it finds the most important item in the reserves with the
732 same biblio number as this book (I'm not clear on this) and returns it
733 with C<$status> set to C<Reserved>.
735 C<&CheckReserves> returns a two-element list:
737 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
739 C<$reserve> is the reserve item that matched. It is a
740 reference-to-hash whose keys are mostly the fields of the reserves
741 table in the Koha database.
743 =cut
745 sub CheckReserves {
746 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
747 my $dbh = C4::Context->dbh;
748 my $sth;
749 my $select;
750 if (C4::Context->preference('item-level_itypes')){
751 $select = "
752 SELECT items.biblionumber,
753 items.biblioitemnumber,
754 itemtypes.notforloan,
755 items.notforloan AS itemnotforloan,
756 items.itemnumber,
757 items.damaged,
758 items.homebranch,
759 items.holdingbranch
760 FROM items
761 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
762 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
765 else {
766 $select = "
767 SELECT items.biblionumber,
768 items.biblioitemnumber,
769 itemtypes.notforloan,
770 items.notforloan AS itemnotforloan,
771 items.itemnumber,
772 items.damaged,
773 items.homebranch,
774 items.holdingbranch
775 FROM items
776 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
777 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
781 if ($item) {
782 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
783 $sth->execute($item);
785 else {
786 $sth = $dbh->prepare("$select WHERE barcode = ?");
787 $sth->execute($barcode);
789 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
790 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
791 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
793 return unless $itemnumber; # bail if we got nothing.
794 # if item is not for loan it cannot be reserved either.....
795 # except where items.notforloan < 0 : This indicates the item is holdable.
796 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
798 # Find this item in the reserves
799 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
801 # $priority and $highest are used to find the most important item
802 # in the list returned by &_Findgroupreserve. (The lower $priority,
803 # the more important the item.)
804 # $highest is the most important item we've seen so far.
805 my $highest;
806 if (scalar @reserves) {
807 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
808 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
809 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
811 my $priority = 10000000;
812 foreach my $res (@reserves) {
813 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
814 if ($res->{'found'} eq 'W') {
815 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
816 } else {
817 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
819 } else {
820 my $patron;
821 my $item;
822 my $local_hold_match;
824 if ($LocalHoldsPriority) {
825 $patron = Koha::Patrons->find( $res->{borrowernumber} );
826 $item = Koha::Items->find($itemnumber);
828 my $local_holds_priority_item_branchcode =
829 $item->$LocalHoldsPriorityItemControl;
830 my $local_holds_priority_patron_branchcode =
831 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
832 ? $res->{branchcode}
833 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
834 ? $patron->branchcode
835 : undef;
836 $local_hold_match =
837 $local_holds_priority_item_branchcode eq
838 $local_holds_priority_patron_branchcode;
841 # See if this item is more important than what we've got so far
842 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
843 $item ||= Koha::Items->find($itemnumber);
844 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
845 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
846 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
847 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
848 next if ($branchitemrule->{'holdallowed'} == 0);
849 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
850 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
851 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
852 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
853 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
854 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
855 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
856 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
857 $priority = $res->{'priority'};
858 $highest = $res;
859 last if $local_hold_match;
865 # If we get this far, then no exact match was found.
866 # We return the most important (i.e. next) reservation.
867 if ($highest) {
868 $highest->{'itemnumber'} = $item;
869 return ( "Reserved", $highest, \@reserves );
872 return ( '' );
875 =head2 CancelExpiredReserves
877 CancelExpiredReserves();
879 Cancels all reserves with an expiration date from before today.
881 =cut
883 sub CancelExpiredReserves {
884 my $today = dt_from_string();
885 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
886 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
888 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
889 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
890 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
892 # FIXME To move to Koha::Holds->search_expired (?)
893 my $holds = Koha::Holds->search( $params );
895 while ( my $hold = $holds->next ) {
896 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
898 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
900 my $cancel_params = {};
901 if ( $hold->found eq 'W' ) {
902 $cancel_params->{charge_cancel_fee} = 1;
904 $hold->cancel( $cancel_params );
908 =head2 AutoUnsuspendReserves
910 AutoUnsuspendReserves();
912 Unsuspends all suspended reserves with a suspend_until date from before today.
914 =cut
916 sub AutoUnsuspendReserves {
917 my $today = dt_from_string();
919 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
921 map { $_->resume() } @holds;
924 =head2 ModReserve
926 ModReserve({ rank => $rank,
927 reserve_id => $reserve_id,
928 branchcode => $branchcode
929 [, itemnumber => $itemnumber ]
930 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
933 Change a hold request's priority or cancel it.
935 C<$rank> specifies the effect of the change. If C<$rank>
936 is 'W' or 'n', nothing happens. This corresponds to leaving a
937 request alone when changing its priority in the holds queue
938 for a bib.
940 If C<$rank> is 'del', the hold request is cancelled.
942 If C<$rank> is an integer greater than zero, the priority of
943 the request is set to that value. Since priority != 0 means
944 that the item is not waiting on the hold shelf, setting the
945 priority to a non-zero value also sets the request's found
946 status and waiting date to NULL.
948 The optional C<$itemnumber> parameter is used only when
949 C<$rank> is a non-zero integer; if supplied, the itemnumber
950 of the hold request is set accordingly; if omitted, the itemnumber
951 is cleared.
953 B<FIXME:> Note that the forgoing can have the effect of causing
954 item-level hold requests to turn into title-level requests. This
955 will be fixed once reserves has separate columns for requested
956 itemnumber and supplying itemnumber.
958 =cut
960 sub ModReserve {
961 my ( $params ) = @_;
963 my $rank = $params->{'rank'};
964 my $reserve_id = $params->{'reserve_id'};
965 my $branchcode = $params->{'branchcode'};
966 my $itemnumber = $params->{'itemnumber'};
967 my $suspend_until = $params->{'suspend_until'};
968 my $borrowernumber = $params->{'borrowernumber'};
969 my $biblionumber = $params->{'biblionumber'};
971 return if $rank eq "W";
972 return if $rank eq "n";
974 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
976 my $hold;
977 unless ( $reserve_id ) {
978 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
979 return unless $holds->count; # FIXME Should raise an exception
980 $hold = $holds->next;
981 $reserve_id = $hold->reserve_id;
984 $hold ||= Koha::Holds->find($reserve_id);
986 if ( $rank eq "del" ) {
987 $hold->cancel;
989 elsif ($rank =~ /^\d+/ and $rank > 0) {
990 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
991 if C4::Context->preference('HoldsLog');
993 my $properties = {
994 priority => $rank,
995 branchcode => $branchcode,
996 itemnumber => $itemnumber,
997 found => undef,
998 waitingdate => undef
1000 if (exists $params->{reservedate}) {
1001 $properties->{reservedate} = $params->{reservedate} || undef;
1003 if (exists $params->{expirationdate}) {
1004 $properties->{expirationdate} = $params->{expirationdate} || undef;
1007 $hold->set($properties)->store();
1009 if ( defined( $suspend_until ) ) {
1010 if ( $suspend_until ) {
1011 $suspend_until = eval { dt_from_string( $suspend_until ) };
1012 $hold->suspend_hold( $suspend_until );
1013 } else {
1014 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1015 # If the hold is not suspended, this does nothing.
1016 $hold->set( { suspend_until => undef } )->store();
1020 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1024 =head2 ModReserveFill
1026 &ModReserveFill($reserve);
1028 Fill a reserve. If I understand this correctly, this means that the
1029 reserved book has been found and given to the patron who reserved it.
1031 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1032 whose keys are fields from the reserves table in the Koha database.
1034 =cut
1036 sub ModReserveFill {
1037 my ($res) = @_;
1038 my $reserve_id = $res->{'reserve_id'};
1040 my $hold = Koha::Holds->find($reserve_id);
1041 # get the priority on this record....
1042 my $priority = $hold->priority;
1044 # update the hold statuses, no need to store it though, we will be deleting it anyway
1045 $hold->set(
1047 found => 'F',
1048 priority => 0,
1052 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1053 if C4::Context->preference('HoldsLog');
1055 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1056 Koha::Old::Hold->new( $hold->unblessed() )->store();
1058 $hold->delete();
1060 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1061 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1062 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1065 # now fix the priority on the others (if the priority wasn't
1066 # already sorted!)....
1067 unless ( $priority == 0 ) {
1068 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1072 =head2 ModReserveStatus
1074 &ModReserveStatus($itemnumber, $newstatus);
1076 Update the reserve status for the active (priority=0) reserve.
1078 $itemnumber is the itemnumber the reserve is on
1080 $newstatus is the new status.
1082 =cut
1084 sub ModReserveStatus {
1086 #first : check if we have a reservation for this item .
1087 my ($itemnumber, $newstatus) = @_;
1088 my $dbh = C4::Context->dbh;
1090 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1091 my $sth_set = $dbh->prepare($query);
1092 $sth_set->execute( $newstatus, $itemnumber );
1094 my $item = Koha::Items->find($itemnumber);
1095 if ( $item->location && $item->location eq 'CART'
1096 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1097 && $newstatus ) {
1098 CartToShelf( $itemnumber );
1102 =head2 ModReserveAffect
1104 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1106 This function affect an item and a status for a given reserve, either fetched directly
1107 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1108 is given, only first reserve returned is affected, which is ok for anything but
1109 multi-item holds.
1111 if $transferToDo is not set, then the status is set to "Waiting" as well.
1112 otherwise, a transfer is on the way, and the end of the transfer will
1113 take care of the waiting status
1115 =cut
1117 sub ModReserveAffect {
1118 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1119 my $dbh = C4::Context->dbh;
1121 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1122 # attached to $itemnumber
1123 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1124 $sth->execute($itemnumber);
1125 my ($biblionumber) = $sth->fetchrow;
1127 # get request - need to find out if item is already
1128 # waiting in order to not send duplicate hold filled notifications
1130 my $hold;
1131 # Find hold by id if we have it
1132 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1133 # Find item level hold for this item if there is one
1134 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1135 # Find record level hold if there is no item level hold
1136 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1138 return unless $hold;
1140 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1142 $hold->itemnumber($itemnumber);
1143 $hold->set_waiting($transferToDo);
1145 _koha_notify_reserve( $hold->reserve_id )
1146 if ( !$transferToDo && !$already_on_shelf );
1148 _FixPriority( { biblionumber => $biblionumber } );
1149 my $item = Koha::Items->find($itemnumber);
1150 if ( $item->location && $item->location eq 'CART'
1151 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1152 CartToShelf( $itemnumber );
1155 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1156 if C4::Context->preference('HoldsLog');
1158 return;
1161 =head2 ModReserveCancelAll
1163 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1165 function to cancel reserv,check other reserves, and transfer document if it's necessary
1167 =cut
1169 sub ModReserveCancelAll {
1170 my $messages;
1171 my $nextreservinfo;
1172 my ( $itemnumber, $borrowernumber ) = @_;
1174 #step 1 : cancel the reservation
1175 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1176 return unless $holds->count;
1177 $holds->next->cancel;
1179 #step 2 launch the subroutine of the others reserves
1180 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1182 return ( $messages, $nextreservinfo );
1185 =head2 ModReserveMinusPriority
1187 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1189 Reduce the values of queued list
1191 =cut
1193 sub ModReserveMinusPriority {
1194 my ( $itemnumber, $reserve_id ) = @_;
1196 #first step update the value of the first person on reserv
1197 my $dbh = C4::Context->dbh;
1198 my $query = "
1199 UPDATE reserves
1200 SET priority = 0 , itemnumber = ?
1201 WHERE reserve_id = ?
1203 my $sth_upd = $dbh->prepare($query);
1204 $sth_upd->execute( $itemnumber, $reserve_id );
1205 # second step update all others reserves
1206 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1209 =head2 IsAvailableForItemLevelRequest
1211 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1213 Checks whether a given item record is available for an
1214 item-level hold request. An item is available if
1216 * it is not lost AND
1217 * it is not damaged AND
1218 * it is not withdrawn AND
1219 * a waiting or in transit reserve is placed on
1220 * does not have a not for loan value > 0
1222 Need to check the issuingrules onshelfholds column,
1223 if this is set items on the shelf can be placed on hold
1225 Note that IsAvailableForItemLevelRequest() does not
1226 check if the staff operator is authorized to place
1227 a request on the item - in particular,
1228 this routine does not check IndependentBranches
1229 and canreservefromotherbranches.
1231 =cut
1233 sub IsAvailableForItemLevelRequest {
1234 my $item = shift;
1235 my $patron = shift;
1236 my $pickup_branchcode = shift;
1237 # items_any_available is precalculated status passed from request.pl when set of items
1238 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1239 my $items_any_available = shift;
1241 my $dbh = C4::Context->dbh;
1242 # must check the notforloan setting of the itemtype
1243 # FIXME - a lot of places in the code do this
1244 # or something similar - need to be
1245 # consolidated
1246 my $itemtype = $item->effective_itemtype;
1247 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1249 return 0 if
1250 $notforloan_per_itemtype ||
1251 $item->itemlost ||
1252 $item->notforloan > 0 ||
1253 $item->withdrawn ||
1254 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1256 if ($pickup_branchcode) {
1257 my $destination = Koha::Libraries->find($pickup_branchcode);
1258 return 0 unless $destination;
1259 return 0 unless $destination->pickup_location;
1260 return 0 unless $item->can_be_transferred( { to => $destination } );
1261 my $reserves_control_branch =
1262 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1263 my $branchitemrule =
1264 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1265 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1266 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1269 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1271 if ( $on_shelf_holds == 1 ) {
1272 return 1;
1273 } elsif ( $on_shelf_holds == 2 ) {
1275 # if we have this param predefined from outer caller sub, we just need
1276 # to return it, so we saving from having loop inside other loop:
1277 return $items_any_available ? 0 : 1
1278 if defined $items_any_available;
1280 my $any_available = ItemsAnyAvailableForHold( { biblionumber => $item->biblionumber, patron => $patron });
1281 return $any_available ? 0 : 1;
1282 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1283 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1287 =head2 ItemsAnyAvailableForHold
1289 ItemsAnyAvailableForHold( { biblionumber => $biblionumber, patron => $patron });
1291 This function checks all items for specified biblionumber (num) / patron (object)
1292 and returns true (1) or false (0) depending if any of rules allows at least of
1293 one item to be available for hold including lots of parameters/logic
1295 =cut
1297 sub ItemsAnyAvailableForHold {
1298 my $param = shift;
1300 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1302 my $any_available = 0;
1304 foreach my $i (@items) {
1305 my $reserves_control_branch =
1306 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1307 my $branchitemrule =
1308 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1309 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1311 $any_available = 1
1312 unless $i->itemlost
1313 || $i->notforloan > 0
1314 || $i->withdrawn
1315 || $i->onloan
1316 || IsItemOnHoldAndFound( $i->id )
1317 || ( $i->damaged
1318 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1319 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1320 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1321 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } );
1324 return $any_available;
1327 =head2 AlterPriority
1329 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1331 This function changes a reserve's priority up, down, to the top, or to the bottom.
1332 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1334 =cut
1336 sub AlterPriority {
1337 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1339 my $hold = Koha::Holds->find( $reserve_id );
1340 return unless $hold;
1342 if ( $hold->cancellationdate ) {
1343 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1344 return;
1347 if ( $where eq 'up' ) {
1348 return unless $prev_priority;
1349 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1350 } elsif ( $where eq 'down' ) {
1351 return unless $next_priority;
1352 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1353 } elsif ( $where eq 'top' ) {
1354 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1355 } elsif ( $where eq 'bottom' ) {
1356 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1359 # FIXME Should return the new priority
1362 =head2 ToggleLowestPriority
1364 ToggleLowestPriority( $borrowernumber, $biblionumber );
1366 This function sets the lowestPriority field to true if is false, and false if it is true.
1368 =cut
1370 sub ToggleLowestPriority {
1371 my ( $reserve_id ) = @_;
1373 my $dbh = C4::Context->dbh;
1375 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1376 $sth->execute( $reserve_id );
1378 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1381 =head2 ToggleSuspend
1383 ToggleSuspend( $reserve_id );
1385 This function sets the suspend field to true if is false, and false if it is true.
1386 If the reserve is currently suspended with a suspend_until date, that date will
1387 be cleared when it is unsuspended.
1389 =cut
1391 sub ToggleSuspend {
1392 my ( $reserve_id, $suspend_until ) = @_;
1394 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1396 my $hold = Koha::Holds->find( $reserve_id );
1398 if ( $hold->is_suspended ) {
1399 $hold->resume()
1400 } else {
1401 $hold->suspend_hold( $suspend_until );
1405 =head2 SuspendAll
1407 SuspendAll(
1408 borrowernumber => $borrowernumber,
1409 [ biblionumber => $biblionumber, ]
1410 [ suspend_until => $suspend_until, ]
1411 [ suspend => $suspend ]
1414 This function accepts a set of hash keys as its parameters.
1415 It requires either borrowernumber or biblionumber, or both.
1417 suspend_until is wholly optional.
1419 =cut
1421 sub SuspendAll {
1422 my %params = @_;
1424 my $borrowernumber = $params{'borrowernumber'} || undef;
1425 my $biblionumber = $params{'biblionumber'} || undef;
1426 my $suspend_until = $params{'suspend_until'} || undef;
1427 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1429 $suspend_until = eval { dt_from_string($suspend_until) }
1430 if ( defined($suspend_until) );
1432 return unless ( $borrowernumber || $biblionumber );
1434 my $params;
1435 $params->{found} = undef;
1436 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1437 $params->{biblionumber} = $biblionumber if $biblionumber;
1439 my @holds = Koha::Holds->search($params);
1441 if ($suspend) {
1442 map { $_->suspend_hold($suspend_until) } @holds;
1444 else {
1445 map { $_->resume() } @holds;
1450 =head2 _FixPriority
1452 _FixPriority({
1453 reserve_id => $reserve_id,
1454 [rank => $rank,]
1455 [ignoreSetLowestRank => $ignoreSetLowestRank]
1460 _FixPriority({ biblionumber => $biblionumber});
1462 This routine adjusts the priority of a hold request and holds
1463 on the same bib.
1465 In the first form, where a reserve_id is passed, the priority of the
1466 hold is set to supplied rank, and other holds for that bib are adjusted
1467 accordingly. If the rank is "del", the hold is cancelled. If no rank
1468 is supplied, all of the holds on that bib have their priority adjusted
1469 as if the second form had been used.
1471 In the second form, where a biblionumber is passed, the holds on that
1472 bib (that are not captured) are sorted in order of increasing priority,
1473 then have reserves.priority set so that the first non-captured hold
1474 has its priority set to 1, the second non-captured hold has its priority
1475 set to 2, and so forth.
1477 In both cases, holds that have the lowestPriority flag on are have their
1478 priority adjusted to ensure that they remain at the end of the line.
1480 Note that the ignoreSetLowestRank parameter is meant to be used only
1481 when _FixPriority calls itself.
1483 =cut
1485 sub _FixPriority {
1486 my ( $params ) = @_;
1487 my $reserve_id = $params->{reserve_id};
1488 my $rank = $params->{rank} // '';
1489 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1490 my $biblionumber = $params->{biblionumber};
1492 my $dbh = C4::Context->dbh;
1494 my $hold;
1495 if ( $reserve_id ) {
1496 $hold = Koha::Holds->find( $reserve_id );
1497 if (!defined $hold){
1498 # may have already been checked out and hold fulfilled
1499 $hold = Koha::Old::Holds->find( $reserve_id );
1501 return unless $hold;
1504 unless ( $biblionumber ) { # FIXME This is a very weird API
1505 $biblionumber = $hold->biblionumber;
1508 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1509 $hold->cancel;
1511 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1513 # make sure priority for waiting or in-transit items is 0
1514 my $query = "
1515 UPDATE reserves
1516 SET priority = 0
1517 WHERE reserve_id = ?
1518 AND found IN ('W', 'T')
1520 my $sth = $dbh->prepare($query);
1521 $sth->execute( $reserve_id );
1523 my @priority;
1525 # get whats left
1526 my $query = "
1527 SELECT reserve_id, borrowernumber, reservedate
1528 FROM reserves
1529 WHERE biblionumber = ?
1530 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1531 ORDER BY priority ASC
1533 my $sth = $dbh->prepare($query);
1534 $sth->execute( $biblionumber );
1535 while ( my $line = $sth->fetchrow_hashref ) {
1536 push( @priority, $line );
1539 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1540 # To find the matching index
1541 my $i;
1542 my $key = -1; # to allow for 0 to be a valid result
1543 for ( $i = 0 ; $i < @priority ; $i++ ) {
1544 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1545 $key = $i; # save the index
1546 last;
1550 # if index exists in array then move it to new position
1551 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1552 my $new_rank = $rank -
1553 1; # $new_rank is what you want the new index to be in the array
1554 my $moving_item = splice( @priority, $key, 1 );
1555 splice( @priority, $new_rank, 0, $moving_item );
1558 # now fix the priority on those that are left....
1559 $query = "
1560 UPDATE reserves
1561 SET priority = ?
1562 WHERE reserve_id = ?
1564 $sth = $dbh->prepare($query);
1565 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1566 $sth->execute(
1567 $j + 1,
1568 $priority[$j]->{'reserve_id'}
1572 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1573 $sth->execute();
1575 unless ( $ignoreSetLowestRank ) {
1576 while ( my $res = $sth->fetchrow_hashref() ) {
1577 _FixPriority({
1578 reserve_id => $res->{'reserve_id'},
1579 rank => '999999',
1580 ignoreSetLowestRank => 1
1586 =head2 _Findgroupreserve
1588 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1590 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1591 first match found. If neither, then we look for non-holds-queue based holds.
1592 Lookahead is the number of days to look in advance.
1594 C<&_Findgroupreserve> returns :
1595 C<@results> is an array of references-to-hash whose keys are mostly
1596 fields from the reserves table of the Koha database, plus
1597 C<biblioitemnumber>.
1599 This routine with either return:
1600 1 - Item specific holds from the holds queue
1601 2 - Title level holds from the holds queue
1602 3 - All holds for this biblionumber
1604 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1606 =cut
1608 sub _Findgroupreserve {
1609 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1610 my $dbh = C4::Context->dbh;
1612 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1613 # check for exact targeted match
1614 my $item_level_target_query = qq{
1615 SELECT reserves.biblionumber AS biblionumber,
1616 reserves.borrowernumber AS borrowernumber,
1617 reserves.reservedate AS reservedate,
1618 reserves.branchcode AS branchcode,
1619 reserves.cancellationdate AS cancellationdate,
1620 reserves.found AS found,
1621 reserves.reservenotes AS reservenotes,
1622 reserves.priority AS priority,
1623 reserves.timestamp AS timestamp,
1624 biblioitems.biblioitemnumber AS biblioitemnumber,
1625 reserves.itemnumber AS itemnumber,
1626 reserves.reserve_id AS reserve_id,
1627 reserves.itemtype AS itemtype
1628 FROM reserves
1629 JOIN biblioitems USING (biblionumber)
1630 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1631 WHERE found IS NULL
1632 AND priority > 0
1633 AND item_level_request = 1
1634 AND itemnumber = ?
1635 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1636 AND suspend = 0
1637 ORDER BY priority
1639 my $sth = $dbh->prepare($item_level_target_query);
1640 $sth->execute($itemnumber, $lookahead||0);
1641 my @results;
1642 if ( my $data = $sth->fetchrow_hashref ) {
1643 push( @results, $data )
1644 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1646 return @results if @results;
1648 # check for title-level targeted match
1649 my $title_level_target_query = qq{
1650 SELECT reserves.biblionumber AS biblionumber,
1651 reserves.borrowernumber AS borrowernumber,
1652 reserves.reservedate AS reservedate,
1653 reserves.branchcode AS branchcode,
1654 reserves.cancellationdate AS cancellationdate,
1655 reserves.found AS found,
1656 reserves.reservenotes AS reservenotes,
1657 reserves.priority AS priority,
1658 reserves.timestamp AS timestamp,
1659 biblioitems.biblioitemnumber AS biblioitemnumber,
1660 reserves.itemnumber AS itemnumber,
1661 reserves.reserve_id AS reserve_id,
1662 reserves.itemtype AS itemtype
1663 FROM reserves
1664 JOIN biblioitems USING (biblionumber)
1665 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1666 WHERE found IS NULL
1667 AND priority > 0
1668 AND item_level_request = 0
1669 AND hold_fill_targets.itemnumber = ?
1670 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1671 AND suspend = 0
1672 ORDER BY priority
1674 $sth = $dbh->prepare($title_level_target_query);
1675 $sth->execute($itemnumber, $lookahead||0);
1676 @results = ();
1677 if ( my $data = $sth->fetchrow_hashref ) {
1678 push( @results, $data )
1679 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1681 return @results if @results;
1683 my $query = qq{
1684 SELECT reserves.biblionumber AS biblionumber,
1685 reserves.borrowernumber AS borrowernumber,
1686 reserves.reservedate AS reservedate,
1687 reserves.waitingdate AS waitingdate,
1688 reserves.branchcode AS branchcode,
1689 reserves.cancellationdate AS cancellationdate,
1690 reserves.found AS found,
1691 reserves.reservenotes AS reservenotes,
1692 reserves.priority AS priority,
1693 reserves.timestamp AS timestamp,
1694 reserves.itemnumber AS itemnumber,
1695 reserves.reserve_id AS reserve_id,
1696 reserves.itemtype AS itemtype
1697 FROM reserves
1698 WHERE reserves.biblionumber = ?
1699 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1700 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1701 AND suspend = 0
1702 ORDER BY priority
1704 $sth = $dbh->prepare($query);
1705 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1706 @results = ();
1707 while ( my $data = $sth->fetchrow_hashref ) {
1708 push( @results, $data )
1709 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1711 return @results;
1714 =head2 _koha_notify_reserve
1716 _koha_notify_reserve( $hold->reserve_id );
1718 Sends a notification to the patron that their hold has been filled (through
1719 ModReserveAffect, _not_ ModReserveFill)
1721 The letter code for this notice may be found using the following query:
1723 select distinct letter_code
1724 from message_transports
1725 inner join message_attributes using (message_attribute_id)
1726 where message_name = 'Hold_Filled'
1728 This will probably sipmly be 'HOLD', but because it is defined in the database,
1729 it is subject to addition or change.
1731 The following tables are availalbe witin the notice:
1733 branches
1734 borrowers
1735 biblio
1736 biblioitems
1737 reserves
1738 items
1740 =cut
1742 sub _koha_notify_reserve {
1743 my $reserve_id = shift;
1744 my $hold = Koha::Holds->find($reserve_id);
1745 my $borrowernumber = $hold->borrowernumber;
1747 my $patron = Koha::Patrons->find( $borrowernumber );
1749 # Try to get the borrower's email address
1750 my $to_address = $patron->notice_email_address;
1752 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1753 borrowernumber => $borrowernumber,
1754 message_name => 'Hold_Filled'
1755 } );
1757 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1759 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1761 my %letter_params = (
1762 module => 'reserves',
1763 branchcode => $hold->branchcode,
1764 lang => $patron->lang,
1765 tables => {
1766 'branches' => $library,
1767 'borrowers' => $patron->unblessed,
1768 'biblio' => $hold->biblionumber,
1769 'biblioitems' => $hold->biblionumber,
1770 'reserves' => $hold->unblessed,
1771 'items' => $hold->itemnumber,
1775 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.
1776 my $send_notification = sub {
1777 my ( $mtt, $letter_code ) = (@_);
1778 return unless defined $letter_code;
1779 $letter_params{letter_code} = $letter_code;
1780 $letter_params{message_transport_type} = $mtt;
1781 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1782 unless ($letter) {
1783 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1784 return;
1787 C4::Letters::EnqueueLetter( {
1788 letter => $letter,
1789 borrowernumber => $borrowernumber,
1790 from_address => $admin_email_address,
1791 message_transport_type => $mtt,
1792 } );
1795 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1796 next if (
1797 ( $mtt eq 'email' and not $to_address ) # No email address
1798 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1799 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1802 &$send_notification($mtt, $letter_code);
1803 $notification_sent++;
1805 #Making sure that a print notification is sent if no other transport types can be utilized.
1806 if (! $notification_sent) {
1807 &$send_notification('print', 'HOLD');
1812 =head2 _ShiftPriorityByDateAndPriority
1814 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1816 This increments the priority of all reserves after the one
1817 with either the lowest date after C<$reservedate>
1818 or the lowest priority after C<$priority>.
1820 It effectively makes room for a new reserve to be inserted with a certain
1821 priority, which is returned.
1823 This is most useful when the reservedate can be set by the user. It allows
1824 the new reserve to be placed before other reserves that have a later
1825 reservedate. Since priority also is set by the form in reserves/request.pl
1826 the sub accounts for that too.
1828 =cut
1830 sub _ShiftPriorityByDateAndPriority {
1831 my ( $biblio, $resdate, $new_priority ) = @_;
1833 my $dbh = C4::Context->dbh;
1834 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1835 my $sth = $dbh->prepare( $query );
1836 $sth->execute( $biblio, $resdate, $new_priority );
1837 my $min_priority = $sth->fetchrow;
1838 # if no such matches are found, $new_priority remains as original value
1839 $new_priority = $min_priority if ( $min_priority );
1841 # Shift the priority up by one; works in conjunction with the next SQL statement
1842 $query = "UPDATE reserves
1843 SET priority = priority+1
1844 WHERE biblionumber = ?
1845 AND borrowernumber = ?
1846 AND reservedate = ?
1847 AND found IS NULL";
1848 my $sth_update = $dbh->prepare( $query );
1850 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1851 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1852 $sth = $dbh->prepare( $query );
1853 $sth->execute( $new_priority, $biblio );
1854 while ( my $row = $sth->fetchrow_hashref ) {
1855 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1858 return $new_priority; # so the caller knows what priority they wind up receiving
1861 =head2 MoveReserve
1863 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1865 Use when checking out an item to handle reserves
1866 If $cancelreserve boolean is set to true, it will remove existing reserve
1868 =cut
1870 sub MoveReserve {
1871 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1873 $cancelreserve //= 0;
1875 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1876 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1877 return unless $res;
1879 my $biblionumber = $res->{biblionumber};
1881 if ($res->{borrowernumber} == $borrowernumber) {
1882 ModReserveFill($res);
1884 else {
1885 # warn "Reserved";
1886 # The item is reserved by someone else.
1887 # Find this item in the reserves
1889 my $borr_res = Koha::Holds->search({
1890 borrowernumber => $borrowernumber,
1891 biblionumber => $biblionumber,
1893 order_by => 'priority'
1894 })->next();
1896 if ( $borr_res ) {
1897 # The item is reserved by the current patron
1898 ModReserveFill($borr_res->unblessed);
1901 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1902 RevertWaitingStatus({ itemnumber => $itemnumber });
1904 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1905 my $hold = Koha::Holds->find( $res->{reserve_id} );
1906 $hold->cancel;
1911 =head2 MergeHolds
1913 MergeHolds($dbh,$to_biblio, $from_biblio);
1915 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1917 =cut
1919 sub MergeHolds {
1920 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1921 my $sth = $dbh->prepare(
1922 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1924 $sth->execute($from_biblio);
1925 if ( my $data = $sth->fetchrow_hashref() ) {
1927 # holds exist on old record, if not we don't need to do anything
1928 $sth = $dbh->prepare(
1929 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1930 $sth->execute( $to_biblio, $from_biblio );
1932 # Reorder by date
1933 # don't reorder those already waiting
1935 $sth = $dbh->prepare(
1936 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1938 my $upd_sth = $dbh->prepare(
1939 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1940 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1942 $sth->execute( $to_biblio, 'W', 'T' );
1943 my $priority = 1;
1944 while ( my $reserve = $sth->fetchrow_hashref() ) {
1945 $upd_sth->execute(
1946 $priority, $to_biblio,
1947 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1948 $reserve->{'itemnumber'}
1950 $priority++;
1955 =head2 RevertWaitingStatus
1957 RevertWaitingStatus({ itemnumber => $itemnumber });
1959 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1961 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1962 item level hold, even if it was only a bibliolevel hold to
1963 begin with. This is because we can no longer know if a hold
1964 was item-level or bib-level after a hold has been set to
1965 waiting status.
1967 =cut
1969 sub RevertWaitingStatus {
1970 my ( $params ) = @_;
1971 my $itemnumber = $params->{'itemnumber'};
1973 return unless ( $itemnumber );
1975 my $dbh = C4::Context->dbh;
1977 ## Get the waiting reserve we want to revert
1978 my $query = "
1979 SELECT * FROM reserves
1980 WHERE itemnumber = ?
1981 AND found IS NOT NULL
1983 my $sth = $dbh->prepare( $query );
1984 $sth->execute( $itemnumber );
1985 my $reserve = $sth->fetchrow_hashref();
1987 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1989 ## Increment the priority of all other non-waiting
1990 ## reserves for this bib record
1991 $query = "
1992 UPDATE reserves
1994 priority = priority + 1
1995 WHERE
1996 biblionumber = ?
1998 priority > 0
2000 $sth = $dbh->prepare( $query );
2001 $sth->execute( $reserve->{'biblionumber'} );
2003 $hold->set(
2005 priority => 1,
2006 found => undef,
2007 waitingdate => undef,
2008 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2010 )->store();
2012 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2014 return $hold;
2017 =head2 ReserveSlip
2019 ReserveSlip(
2021 branchcode => $branchcode,
2022 borrowernumber => $borrowernumber,
2023 biblionumber => $biblionumber,
2024 [ itemnumber => $itemnumber, ]
2025 [ barcode => $barcode, ]
2029 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2031 The letter code will be HOLD_SLIP, and the following tables are
2032 available within the slip:
2034 reserves
2035 branches
2036 borrowers
2037 biblio
2038 biblioitems
2039 items
2041 =cut
2043 sub ReserveSlip {
2044 my ($args) = @_;
2045 my $branchcode = $args->{branchcode};
2046 my $borrowernumber = $args->{borrowernumber};
2047 my $biblionumber = $args->{biblionumber};
2048 my $itemnumber = $args->{itemnumber};
2049 my $barcode = $args->{barcode};
2052 my $patron = Koha::Patrons->find($borrowernumber);
2054 my $hold;
2055 if ($itemnumber || $barcode ) {
2056 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2058 $hold = Koha::Holds->search(
2060 biblionumber => $biblionumber,
2061 borrowernumber => $borrowernumber,
2062 itemnumber => $itemnumber
2064 )->next;
2066 else {
2067 $hold = Koha::Holds->search(
2069 biblionumber => $biblionumber,
2070 borrowernumber => $borrowernumber
2072 )->next;
2075 return unless $hold;
2076 my $reserve = $hold->unblessed;
2078 return C4::Letters::GetPreparedLetter (
2079 module => 'circulation',
2080 letter_code => 'HOLD_SLIP',
2081 branchcode => $branchcode,
2082 lang => $patron->lang,
2083 tables => {
2084 'reserves' => $reserve,
2085 'branches' => $reserve->{branchcode},
2086 'borrowers' => $reserve->{borrowernumber},
2087 'biblio' => $reserve->{biblionumber},
2088 'biblioitems' => $reserve->{biblionumber},
2089 'items' => $reserve->{itemnumber},
2094 =head2 GetReservesControlBranch
2096 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2098 Return the branchcode to be used to determine which reserves
2099 policy applies to a transaction.
2101 C<$item> is a hashref for an item. Only 'homebranch' is used.
2103 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2105 =cut
2107 sub GetReservesControlBranch {
2108 my ( $item, $borrower ) = @_;
2110 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2112 my $branchcode =
2113 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2114 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2115 : undef;
2117 return $branchcode;
2120 =head2 CalculatePriority
2122 my $p = CalculatePriority($biblionumber, $resdate);
2124 Calculate priority for a new reserve on biblionumber, placing it at
2125 the end of the line of all holds whose start date falls before
2126 the current system time and that are neither on the hold shelf
2127 or in transit.
2129 The reserve date parameter is optional; if it is supplied, the
2130 priority is based on the set of holds whose start date falls before
2131 the parameter value.
2133 After calculation of this priority, it is recommended to call
2134 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2135 AddReserves.
2137 =cut
2139 sub CalculatePriority {
2140 my ( $biblionumber, $resdate ) = @_;
2142 my $sql = q{
2143 SELECT COUNT(*) FROM reserves
2144 WHERE biblionumber = ?
2145 AND priority > 0
2146 AND (found IS NULL OR found = '')
2148 #skip found==W or found==T (waiting or transit holds)
2149 if( $resdate ) {
2150 $sql.= ' AND ( reservedate <= ? )';
2152 else {
2153 $sql.= ' AND ( reservedate < NOW() )';
2155 my $dbh = C4::Context->dbh();
2156 my @row = $dbh->selectrow_array(
2157 $sql,
2158 undef,
2159 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2162 return @row ? $row[0]+1 : 1;
2165 =head2 IsItemOnHoldAndFound
2167 my $bool = IsItemFoundHold( $itemnumber );
2169 Returns true if the item is currently on hold
2170 and that hold has a non-null found status ( W, T, etc. )
2172 =cut
2174 sub IsItemOnHoldAndFound {
2175 my ($itemnumber) = @_;
2177 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2179 my $found = $rs->count(
2181 itemnumber => $itemnumber,
2182 found => { '!=' => undef }
2186 return $found;
2189 =head2 GetMaxPatronHoldsForRecord
2191 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2193 For multiple holds on a given record for a given patron, the max
2194 number of record level holds that a patron can be placed is the highest
2195 value of the holds_per_record rule for each item if the record for that
2196 patron. This subroutine finds and returns the highest holds_per_record
2197 rule value for a given patron id and record id.
2199 =cut
2201 sub GetMaxPatronHoldsForRecord {
2202 my ( $borrowernumber, $biblionumber ) = @_;
2204 my $patron = Koha::Patrons->find($borrowernumber);
2205 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2207 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2209 my $categorycode = $patron->categorycode;
2210 my $branchcode;
2211 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2213 my $max = 0;
2214 foreach my $item (@items) {
2215 my $itemtype = $item->effective_itemtype();
2217 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2219 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2220 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2221 $max = $holds_per_record if $holds_per_record > $max;
2224 return $max;
2227 =head2 GetHoldRule
2229 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2231 Returns the matching hold related issuingrule fields for a given
2232 patron category, itemtype, and library.
2234 =cut
2236 sub GetHoldRule {
2237 my ( $categorycode, $itemtype, $branchcode ) = @_;
2239 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2241 itemtype => $itemtype,
2242 categorycode => $categorycode,
2243 branchcode => $branchcode,
2244 rule_name => 'reservesallowed',
2245 order_by => {
2246 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2251 my $rules;
2252 if ( $reservesallowed ) {
2253 $rules->{reservesallowed} = $reservesallowed->rule_value;
2254 $rules->{itemtype} = $reservesallowed->itemtype;
2255 $rules->{categorycode} = $reservesallowed->categorycode;
2256 $rules->{branchcode} = $reservesallowed->branchcode;
2259 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2261 itemtype => $itemtype,
2262 categorycode => $categorycode,
2263 branchcode => $branchcode,
2264 rules => ['holds_per_record', 'holds_per_day'],
2265 order_by => {
2266 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2270 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2271 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2273 return $rules;
2276 =head1 AUTHOR
2278 Koha Development Team <http://koha-community.org/>
2280 =cut