Bug 18927: Use fully qualified subroutine names in C4::Items
[koha.git] / C4 / Reserves.pm
blob3be9df9f5904ee9330b150ffde6bf5de8f1a3a4b
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 strict;
25 #use warnings; FIXME - Bug 2505
26 use C4::Context;
27 use C4::Biblio;
28 use C4::Members;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Accounts;
33 # for _koha_notify_reserve
34 use C4::Members::Messaging;
35 use C4::Members qw();
36 use C4::Letters;
37 use C4::Log;
39 use Koha::Biblios;
40 use Koha::DateUtils;
41 use Koha::Calendar;
42 use Koha::Database;
43 use Koha::Hold;
44 use Koha::Old::Hold;
45 use Koha::Holds;
46 use Koha::Libraries;
47 use Koha::IssuingRules;
48 use Koha::Items;
49 use Koha::ItemTypes;
50 use Koha::Patrons;
52 use List::MoreUtils qw( firstidx any );
53 use Carp;
54 use Data::Dumper;
56 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
58 =head1 NAME
60 C4::Reserves - Koha functions for dealing with reservation.
62 =head1 SYNOPSIS
64 use C4::Reserves;
66 =head1 DESCRIPTION
68 This modules provides somes functions to deal with reservations.
70 Reserves are stored in reserves table.
71 The following columns contains important values :
72 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
73 =0 : then the reserve is being dealed
74 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
75 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
76 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
77 F(inished) : the reserve has been completed, and is done
78 - itemnumber : empty : the reserve is still unaffected to an item
79 filled: the reserve is attached to an item
80 The complete workflow is :
81 ==== 1st use case ====
82 patron request a document, 1st available : P >0, F=NULL, I=NULL
83 a library having it run "transfertodo", and clic on the list
84 if there is no transfer to do, the reserve waiting
85 patron can pick it up P =0, F=W, I=filled
86 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
87 The pickup library receive the book, it check in P =0, F=W, I=filled
88 The patron borrow the book P =0, F=F, I=filled
90 ==== 2nd use case ====
91 patron requests a document, a given item,
92 If pickup is holding branch P =0, F=W, I=filled
93 If transfer needed, write in branchtransfer P =0, F=T, I=filled
94 The pickup library receive the book, it checks it in P =0, F=W, I=filled
95 The patron borrow the book P =0, F=F, I=filled
97 =head1 FUNCTIONS
99 =cut
101 BEGIN {
102 require Exporter;
103 @ISA = qw(Exporter);
104 @EXPORT = qw(
105 &AddReserve
107 &GetReservesForBranch
108 &GetReserveStatus
110 &GetOtherReserves
112 &ModReserveFill
113 &ModReserveAffect
114 &ModReserve
115 &ModReserveStatus
116 &ModReserveCancelAll
117 &ModReserveMinusPriority
118 &MoveReserve
120 &CheckReserves
121 &CanBookBeReserved
122 &CanItemBeReserved
123 &CanReserveBeCanceledFromOpac
124 &CancelReserve
125 &CancelExpiredReserves
127 &AutoUnsuspendReserves
129 &IsAvailableForItemLevelRequest
131 &OPACItemHoldsAllowed
133 &AlterPriority
134 &ToggleLowestPriority
136 &ReserveSlip
137 &ToggleSuspend
138 &SuspendAll
140 &GetReservesControlBranch
142 IsItemOnHoldAndFound
144 GetMaxPatronHoldsForRecord
146 @EXPORT_OK = qw( MergeHolds );
149 =head2 AddReserve
151 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
153 Adds reserve and generates HOLDPLACED message.
155 The following tables are available witin the HOLDPLACED message:
157 branches
158 borrowers
159 biblio
160 biblioitems
161 items
162 reserves
164 =cut
166 sub AddReserve {
167 my (
168 $branch, $borrowernumber, $biblionumber, $bibitems,
169 $priority, $resdate, $expdate, $notes,
170 $title, $checkitem, $found, $itemtype
171 ) = @_;
173 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
174 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
176 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
178 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
180 # Make room in reserves for this before those of a later reserve date
181 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
184 my $waitingdate;
186 # If the reserv had the waiting status, we had the value of the resdate
187 if ( $found eq 'W' ) {
188 $waitingdate = $resdate;
191 # Don't add itemtype limit if specific item is selected
192 $itemtype = undef if $checkitem;
194 # updates take place here
195 my $hold = Koha::Hold->new(
197 borrowernumber => $borrowernumber,
198 biblionumber => $biblionumber,
199 reservedate => $resdate,
200 branchcode => $branch,
201 priority => $priority,
202 reservenotes => $notes,
203 itemnumber => $checkitem,
204 found => $found,
205 waitingdate => $waitingdate,
206 expirationdate => $expdate,
207 itemtype => $itemtype,
209 )->store();
211 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
212 if C4::Context->preference('HoldsLog');
214 my $reserve_id = $hold->id();
216 # add a reserve fee if needed
217 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
218 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
219 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
222 _FixPriority({ biblionumber => $biblionumber});
224 # Send e-mail to librarian if syspref is active
225 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
226 my $patron = Koha::Patrons->find( $borrowernumber );
227 my $library = $patron->library;
228 if ( my $letter = C4::Letters::GetPreparedLetter (
229 module => 'reserves',
230 letter_code => 'HOLDPLACED',
231 branchcode => $branch,
232 lang => $patron->lang,
233 tables => {
234 'branches' => $library->unblessed,
235 'borrowers' => $patron->unblessed,
236 'biblio' => $biblionumber,
237 'biblioitems' => $biblionumber,
238 'items' => $checkitem,
239 'reserves' => $hold->unblessed,
241 ) ) {
243 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
245 C4::Letters::EnqueueLetter(
246 { letter => $letter,
247 borrowernumber => $borrowernumber,
248 message_transport_type => 'email',
249 from_address => $admin_email_address,
250 to_address => $admin_email_address,
256 return $reserve_id;
259 =head2 CanBookBeReserved
261 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
262 if ($canReserve eq 'OK') { #We can reserve this Item! }
264 See CanItemBeReserved() for possible return values.
266 =cut
268 sub CanBookBeReserved{
269 my ($borrowernumber, $biblionumber) = @_;
271 my $items = GetItemnumbersForBiblio($biblionumber);
272 #get items linked via host records
273 my @hostitems = get_hostitemnumbers_of($biblionumber);
274 if (@hostitems){
275 push (@$items,@hostitems);
278 my $canReserve;
279 foreach my $item (@$items) {
280 $canReserve = CanItemBeReserved( $borrowernumber, $item );
281 return 'OK' if $canReserve eq 'OK';
283 return $canReserve;
286 =head2 CanItemBeReserved
288 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
289 if ($canReserve eq 'OK') { #We can reserve this Item! }
291 @RETURNS OK, if the Item can be reserved.
292 ageRestricted, if the Item is age restricted for this borrower.
293 damaged, if the Item is damaged.
294 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
295 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
296 notReservable, if holds on this item are not allowed
298 =cut
300 sub CanItemBeReserved {
301 my ( $borrowernumber, $itemnumber ) = @_;
303 my $dbh = C4::Context->dbh;
304 my $ruleitemtype; # itemtype of the matching issuing rule
305 my $allowedreserves = 0; # Total number of holds allowed across all records
306 my $holds_per_record = 1; # Total number of holds allowed for this one given record
308 # we retrieve borrowers and items informations #
309 # item->{itype} will come for biblioitems if necessery
310 my $item = GetItem($itemnumber);
311 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
312 my $patron = Koha::Patrons->find( $borrowernumber );
313 my $borrower = $patron->unblessed;
315 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
316 return 'damaged'
317 if ( $item->{damaged}
318 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
320 # Check for the age restriction
321 my ( $ageRestriction, $daysToAgeRestriction ) =
322 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
323 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
325 # Check that the patron doesn't have an item level hold on this item already
326 return 'itemAlreadyOnHold'
327 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
329 my $controlbranch = C4::Context->preference('ReservesControlBranch');
331 my $querycount = q{
332 SELECT count(*) AS count
333 FROM reserves
334 LEFT JOIN items USING (itemnumber)
335 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
336 LEFT JOIN borrowers USING (borrowernumber)
337 WHERE borrowernumber = ?
340 my $branchcode = "";
341 my $branchfield = "reserves.branchcode";
343 if ( $controlbranch eq "ItemHomeLibrary" ) {
344 $branchfield = "items.homebranch";
345 $branchcode = $item->{homebranch};
347 elsif ( $controlbranch eq "PatronLibrary" ) {
348 $branchfield = "borrowers.branchcode";
349 $branchcode = $borrower->{branchcode};
352 # we retrieve rights
353 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
354 $ruleitemtype = $rights->{itemtype};
355 $allowedreserves = $rights->{reservesallowed};
356 $holds_per_record = $rights->{holds_per_record};
358 else {
359 $ruleitemtype = '*';
362 $item = Koha::Items->find( $itemnumber );
363 my $holds = Koha::Holds->search(
365 borrowernumber => $borrowernumber,
366 biblionumber => $item->biblionumber,
367 found => undef, # Found holds don't count against a patron's holds limit
370 if ( $holds->count() >= $holds_per_record ) {
371 return "tooManyHoldsForThisRecord";
374 # we retrieve count
376 $querycount .= "AND $branchfield = ?";
378 # If using item-level itypes, fall back to the record
379 # level itemtype if the hold has no associated item
380 $querycount .=
381 C4::Context->preference('item-level_itypes')
382 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
383 : " AND biblioitems.itemtype = ?"
384 if ( $ruleitemtype ne "*" );
386 my $sthcount = $dbh->prepare($querycount);
388 if ( $ruleitemtype eq "*" ) {
389 $sthcount->execute( $borrowernumber, $branchcode );
391 else {
392 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
395 my $reservecount = "0";
396 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
397 $reservecount = $rowcount->{count};
400 # we check if it's ok or not
401 if ( $reservecount >= $allowedreserves ) {
402 return 'tooManyReserves';
405 my $circ_control_branch =
406 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
407 my $branchitemrule =
408 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
410 if ( $branchitemrule->{holdallowed} == 0 ) {
411 return 'notReservable';
414 if ( $branchitemrule->{holdallowed} == 1
415 && $borrower->{branchcode} ne $item->homebranch )
417 return 'cannotReserveFromOtherBranches';
420 # If reservecount is ok, we check item branch if IndependentBranches is ON
421 # and canreservefromotherbranches is OFF
422 if ( C4::Context->preference('IndependentBranches')
423 and !C4::Context->preference('canreservefromotherbranches') )
425 my $itembranch = $item->homebranch;
426 if ( $itembranch ne $borrower->{branchcode} ) {
427 return 'cannotReserveFromOtherBranches';
431 return 'OK';
434 =head2 CanReserveBeCanceledFromOpac
436 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
438 returns 1 if reserve can be cancelled by user from OPAC.
439 First check if reserve belongs to user, next checks if reserve is not in
440 transfer or waiting status
442 =cut
444 sub CanReserveBeCanceledFromOpac {
445 my ($reserve_id, $borrowernumber) = @_;
447 return unless $reserve_id and $borrowernumber;
448 my $reserve = Koha::Holds->find($reserve_id);
450 return 0 unless $reserve->borrowernumber == $borrowernumber;
451 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
453 return 1;
457 =head2 GetOtherReserves
459 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
461 Check queued list of this document and check if this document must be transferred
463 =cut
465 sub GetOtherReserves {
466 my ($itemnumber) = @_;
467 my $messages;
468 my $nextreservinfo;
469 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
470 if ($checkreserves) {
471 my $iteminfo = GetItem($itemnumber);
472 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
473 $messages->{'transfert'} = $checkreserves->{'branchcode'};
474 #minus priorities of others reservs
475 ModReserveMinusPriority(
476 $itemnumber,
477 $checkreserves->{'reserve_id'},
480 #launch the subroutine dotransfer
481 C4::Items::ModItemTransfer(
482 $itemnumber,
483 $iteminfo->{'holdingbranch'},
484 $checkreserves->{'branchcode'}
489 #step 2b : case of a reservation on the same branch, set the waiting status
490 else {
491 $messages->{'waiting'} = 1;
492 ModReserveMinusPriority(
493 $itemnumber,
494 $checkreserves->{'reserve_id'},
496 ModReserveStatus($itemnumber,'W');
499 $nextreservinfo = $checkreserves->{'borrowernumber'};
502 return ( $messages, $nextreservinfo );
505 =head2 ChargeReserveFee
507 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
509 Charge the fee for a reserve (if $fee > 0)
511 =cut
513 sub ChargeReserveFee {
514 my ( $borrowernumber, $fee, $title ) = @_;
515 return if !$fee || $fee==0; # the last test is needed to include 0.00
516 my $accquery = qq{
517 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
519 my $dbh = C4::Context->dbh;
520 my $nextacctno = &getnextacctno( $borrowernumber );
521 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
524 =head2 GetReserveFee
526 $fee = GetReserveFee( $borrowernumber, $biblionumber );
528 Calculate the fee for a reserve (if applicable).
530 =cut
532 sub GetReserveFee {
533 my ( $borrowernumber, $biblionumber ) = @_;
534 my $borquery = qq{
535 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
537 my $issue_qry = qq{
538 SELECT COUNT(*) FROM items
539 LEFT JOIN issues USING (itemnumber)
540 WHERE items.biblionumber=? AND issues.issue_id IS NULL
542 my $holds_qry = qq{
543 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
546 my $dbh = C4::Context->dbh;
547 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
548 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
549 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
550 # This is a reconstruction of the old code:
551 # Compare number of items with items issued, and optionally check holds
552 # If not all items are issued and there are no holds: charge no fee
553 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
554 my ( $notissued, $reserved );
555 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
556 ( $biblionumber ) );
557 if( $notissued ) {
558 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
559 ( $biblionumber, $borrowernumber ) );
560 $fee = 0 if $reserved == 0;
563 return $fee;
566 =head2 GetReservesForBranch
568 @transreserv = GetReservesForBranch($frombranch);
570 =cut
572 sub GetReservesForBranch {
573 my ($frombranch) = @_;
574 my $dbh = C4::Context->dbh;
576 my $query = "
577 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
578 FROM reserves
579 WHERE priority='0'
580 AND found='W'
582 $query .= " AND branchcode=? " if ( $frombranch );
583 $query .= "ORDER BY waitingdate" ;
585 my $sth = $dbh->prepare($query);
586 if ($frombranch){
587 $sth->execute($frombranch);
588 } else {
589 $sth->execute();
592 my @transreserv;
593 my $i = 0;
594 while ( my $data = $sth->fetchrow_hashref ) {
595 $transreserv[$i] = $data;
596 $i++;
598 return (@transreserv);
601 =head2 GetReserveStatus
603 $reservestatus = GetReserveStatus($itemnumber);
605 Takes an itemnumber and returns the status of the reserve placed on it.
606 If several reserves exist, the reserve with the lower priority is given.
608 =cut
610 ## FIXME: I don't think this does what it thinks it does.
611 ## It only ever checks the first reserve result, even though
612 ## multiple reserves for that bib can have the itemnumber set
613 ## the sub is only used once in the codebase.
614 sub GetReserveStatus {
615 my ($itemnumber) = @_;
617 my $dbh = C4::Context->dbh;
619 my ($sth, $found, $priority);
620 if ( $itemnumber ) {
621 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
622 $sth->execute($itemnumber);
623 ($found, $priority) = $sth->fetchrow_array;
626 if(defined $found) {
627 return 'Waiting' if $found eq 'W' and $priority == 0;
628 return 'Finished' if $found eq 'F';
631 return 'Reserved' if $priority > 0;
633 return ''; # empty string here will remove need for checking undef, or less log lines
636 =head2 CheckReserves
638 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
639 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
640 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
642 Find a book in the reserves.
644 C<$itemnumber> is the book's item number.
645 C<$lookahead> is the number of days to look in advance for future reserves.
647 As I understand it, C<&CheckReserves> looks for the given item in the
648 reserves. If it is found, that's a match, and C<$status> is set to
649 C<Waiting>.
651 Otherwise, it finds the most important item in the reserves with the
652 same biblio number as this book (I'm not clear on this) and returns it
653 with C<$status> set to C<Reserved>.
655 C<&CheckReserves> returns a two-element list:
657 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
659 C<$reserve> is the reserve item that matched. It is a
660 reference-to-hash whose keys are mostly the fields of the reserves
661 table in the Koha database.
663 =cut
665 sub CheckReserves {
666 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
667 my $dbh = C4::Context->dbh;
668 my $sth;
669 my $select;
670 if (C4::Context->preference('item-level_itypes')){
671 $select = "
672 SELECT items.biblionumber,
673 items.biblioitemnumber,
674 itemtypes.notforloan,
675 items.notforloan AS itemnotforloan,
676 items.itemnumber,
677 items.damaged,
678 items.homebranch,
679 items.holdingbranch
680 FROM items
681 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
682 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
685 else {
686 $select = "
687 SELECT items.biblionumber,
688 items.biblioitemnumber,
689 itemtypes.notforloan,
690 items.notforloan AS itemnotforloan,
691 items.itemnumber,
692 items.damaged,
693 items.homebranch,
694 items.holdingbranch
695 FROM items
696 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
697 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
701 if ($item) {
702 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
703 $sth->execute($item);
705 else {
706 $sth = $dbh->prepare("$select WHERE barcode = ?");
707 $sth->execute($barcode);
709 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
710 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
712 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
714 return unless $itemnumber; # bail if we got nothing.
716 # if item is not for loan it cannot be reserved either.....
717 # except where items.notforloan < 0 : This indicates the item is holdable.
718 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
720 # Find this item in the reserves
721 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
723 # $priority and $highest are used to find the most important item
724 # in the list returned by &_Findgroupreserve. (The lower $priority,
725 # the more important the item.)
726 # $highest is the most important item we've seen so far.
727 my $highest;
728 if (scalar @reserves) {
729 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
730 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
731 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
733 my $priority = 10000000;
734 foreach my $res (@reserves) {
735 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
736 return ( "Waiting", $res, \@reserves ); # Found it
737 } else {
738 my $patron;
739 my $iteminfo;
740 my $local_hold_match;
742 if ($LocalHoldsPriority) {
743 $patron = Koha::Patrons->find( $res->{borrowernumber} );
744 $iteminfo = C4::Items::GetItem($itemnumber);
746 my $local_holds_priority_item_branchcode =
747 $iteminfo->{$LocalHoldsPriorityItemControl};
748 my $local_holds_priority_patron_branchcode =
749 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
750 ? $res->{branchcode}
751 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
752 ? $patron->branchcode
753 : undef;
754 $local_hold_match =
755 $local_holds_priority_item_branchcode eq
756 $local_holds_priority_patron_branchcode;
759 # See if this item is more important than what we've got so far
760 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
761 $iteminfo ||= C4::Items::GetItem($itemnumber);
762 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
763 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
764 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
765 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
766 next if ($branchitemrule->{'holdallowed'} == 0);
767 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
768 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
769 $priority = $res->{'priority'};
770 $highest = $res;
771 last if $local_hold_match;
777 # If we get this far, then no exact match was found.
778 # We return the most important (i.e. next) reservation.
779 if ($highest) {
780 $highest->{'itemnumber'} = $item;
781 return ( "Reserved", $highest, \@reserves );
784 return ( '' );
787 =head2 CancelExpiredReserves
789 CancelExpiredReserves();
791 Cancels all reserves with an expiration date from before today.
793 =cut
795 sub CancelExpiredReserves {
797 my $today = dt_from_string();
798 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
800 my $dbh = C4::Context->dbh;
801 my $sth = $dbh->prepare( "
802 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
803 AND expirationdate IS NOT NULL
804 " );
805 $sth->execute();
807 while ( my $res = $sth->fetchrow_hashref() ) {
808 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
809 my $cancel_params = { reserve_id => $res->{'reserve_id'} };
811 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
813 if ( $res->{found} eq 'W' ) {
814 $cancel_params->{charge_cancel_fee} = 1;
817 CancelReserve($cancel_params);
821 =head2 AutoUnsuspendReserves
823 AutoUnsuspendReserves();
825 Unsuspends all suspended reserves with a suspend_until date from before today.
827 =cut
829 sub AutoUnsuspendReserves {
830 my $today = dt_from_string();
832 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
834 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
837 =head2 CancelReserve
839 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
841 Cancels a reserve. If C<charge_cancel_fee> is passed and the C<ExpireReservesMaxPickUpDelayCharge> syspref is set, charge that fee to the patron's account.
843 =cut
845 sub CancelReserve {
846 my ( $params ) = @_;
848 my $reserve_id = $params->{'reserve_id'};
849 my $hold;
850 if ( $reserve_id ) {
851 $hold = Koha::Holds->find( $reserve_id );
852 } else {
853 $hold = Koha::Holds->search( $params ); # biblionumber, borrowernumber, itemnumber
856 return unless $hold;
858 logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
859 if C4::Context->preference('HoldsLog');
861 my $query = "
862 UPDATE reserves
863 SET cancellationdate = now(),
864 priority = 0
865 WHERE reserve_id = ?
867 my $dbh = C4::Context->dbh;
868 my $sth = $dbh->prepare($query);
869 $sth->execute( $reserve_id );
871 $query = "
872 INSERT INTO old_reserves
873 SELECT * FROM reserves
874 WHERE reserve_id = ?
876 $sth = $dbh->prepare($query);
877 $sth->execute( $reserve_id );
879 $query = "
880 DELETE FROM reserves
881 WHERE reserve_id = ?
883 $sth = $dbh->prepare($query);
884 $sth->execute( $reserve_id );
886 # now fix the priority on the others....
887 _FixPriority({ biblionumber => $hold->biblionumber });
889 # and, if desired, charge a cancel fee
890 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
891 if ( $charge && $params->{'charge_cancel_fee'} ) {
892 manualinvoice($hold->borrowernumber, $hold->itemnumber, '', 'HE', $charge);
895 return $hold->unblessed;
898 =head2 ModReserve
900 ModReserve({ rank => $rank,
901 reserve_id => $reserve_id,
902 branchcode => $branchcode
903 [, itemnumber => $itemnumber ]
904 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
907 Change a hold request's priority or cancel it.
909 C<$rank> specifies the effect of the change. If C<$rank>
910 is 'W' or 'n', nothing happens. This corresponds to leaving a
911 request alone when changing its priority in the holds queue
912 for a bib.
914 If C<$rank> is 'del', the hold request is cancelled.
916 If C<$rank> is an integer greater than zero, the priority of
917 the request is set to that value. Since priority != 0 means
918 that the item is not waiting on the hold shelf, setting the
919 priority to a non-zero value also sets the request's found
920 status and waiting date to NULL.
922 The optional C<$itemnumber> parameter is used only when
923 C<$rank> is a non-zero integer; if supplied, the itemnumber
924 of the hold request is set accordingly; if omitted, the itemnumber
925 is cleared.
927 B<FIXME:> Note that the forgoing can have the effect of causing
928 item-level hold requests to turn into title-level requests. This
929 will be fixed once reserves has separate columns for requested
930 itemnumber and supplying itemnumber.
932 =cut
934 sub ModReserve {
935 my ( $params ) = @_;
937 my $rank = $params->{'rank'};
938 my $reserve_id = $params->{'reserve_id'};
939 my $branchcode = $params->{'branchcode'};
940 my $itemnumber = $params->{'itemnumber'};
941 my $suspend_until = $params->{'suspend_until'};
942 my $borrowernumber = $params->{'borrowernumber'};
943 my $biblionumber = $params->{'biblionumber'};
945 return if $rank eq "W";
946 return if $rank eq "n";
948 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
950 my $hold;
951 unless ( $reserve_id ) {
952 $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
953 return unless $hold; # FIXME Should raise an exception
954 $reserve_id = $hold->reserve_id;
957 if ( $rank eq "del" ) {
958 CancelReserve({ reserve_id => $reserve_id });
960 elsif ($rank =~ /^\d+/ and $rank > 0) {
961 $hold ||= Koha::Holds->find($reserve_id);
962 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
963 if C4::Context->preference('HoldsLog');
965 $hold->set(
967 priority => $rank,
968 branchcode => $branchcode,
969 itemnumber => $itemnumber,
970 found => undef,
971 waitingdate => undef
973 )->store();
975 if ( defined( $suspend_until ) ) {
976 if ( $suspend_until ) {
977 $suspend_until = eval { dt_from_string( $suspend_until ) };
978 $hold->suspend_hold( $suspend_until );
979 } else {
980 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
981 # If the hold is not suspended, this does nothing.
982 $hold->set( { suspend_until => undef } )->store();
986 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
990 =head2 ModReserveFill
992 &ModReserveFill($reserve);
994 Fill a reserve. If I understand this correctly, this means that the
995 reserved book has been found and given to the patron who reserved it.
997 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
998 whose keys are fields from the reserves table in the Koha database.
1000 =cut
1002 sub ModReserveFill {
1003 my ($res) = @_;
1004 my $reserve_id = $res->{'reserve_id'};
1006 my $hold = Koha::Holds->find($reserve_id);
1008 # get the priority on this record....
1009 my $priority = $hold->priority;
1011 # update the hold statuses, no need to store it though, we will be deleting it anyway
1012 $hold->set(
1014 found => 'F',
1015 priority => 0,
1019 Koha::Old::Hold->new( $hold->unblessed() )->store();
1021 $hold->delete();
1023 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1024 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1025 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1028 # now fix the priority on the others (if the priority wasn't
1029 # already sorted!)....
1030 unless ( $priority == 0 ) {
1031 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1035 =head2 ModReserveStatus
1037 &ModReserveStatus($itemnumber, $newstatus);
1039 Update the reserve status for the active (priority=0) reserve.
1041 $itemnumber is the itemnumber the reserve is on
1043 $newstatus is the new status.
1045 =cut
1047 sub ModReserveStatus {
1049 #first : check if we have a reservation for this item .
1050 my ($itemnumber, $newstatus) = @_;
1051 my $dbh = C4::Context->dbh;
1053 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1054 my $sth_set = $dbh->prepare($query);
1055 $sth_set->execute( $newstatus, $itemnumber );
1057 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1058 CartToShelf( $itemnumber );
1062 =head2 ModReserveAffect
1064 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1066 This function affect an item and a status for a given reserve, either fetched directly
1067 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1068 is given, only first reserve returned is affected, which is ok for anything but
1069 multi-item holds.
1071 if $transferToDo is not set, then the status is set to "Waiting" as well.
1072 otherwise, a transfer is on the way, and the end of the transfer will
1073 take care of the waiting status
1075 =cut
1077 sub ModReserveAffect {
1078 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1079 my $dbh = C4::Context->dbh;
1081 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1082 # attached to $itemnumber
1083 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1084 $sth->execute($itemnumber);
1085 my ($biblionumber) = $sth->fetchrow;
1087 # get request - need to find out if item is already
1088 # waiting in order to not send duplicate hold filled notifications
1090 my $hold;
1091 # Find hold by id if we have it
1092 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1093 # Find item level hold for this item if there is one
1094 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1095 # Find record level hold if there is no item level hold
1096 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1098 return unless $hold;
1100 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1102 $hold->itemnumber($itemnumber);
1103 $hold->set_waiting($transferToDo);
1105 _koha_notify_reserve( $hold->reserve_id )
1106 if ( !$transferToDo && !$already_on_shelf );
1108 _FixPriority( { biblionumber => $biblionumber } );
1110 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1111 CartToShelf($itemnumber);
1114 return;
1117 =head2 ModReserveCancelAll
1119 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1121 function to cancel reserv,check other reserves, and transfer document if it's necessary
1123 =cut
1125 sub ModReserveCancelAll {
1126 my $messages;
1127 my $nextreservinfo;
1128 my ( $itemnumber, $borrowernumber ) = @_;
1130 #step 1 : cancel the reservation
1131 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1133 #step 2 launch the subroutine of the others reserves
1134 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1136 return ( $messages, $nextreservinfo );
1139 =head2 ModReserveMinusPriority
1141 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1143 Reduce the values of queued list
1145 =cut
1147 sub ModReserveMinusPriority {
1148 my ( $itemnumber, $reserve_id ) = @_;
1150 #first step update the value of the first person on reserv
1151 my $dbh = C4::Context->dbh;
1152 my $query = "
1153 UPDATE reserves
1154 SET priority = 0 , itemnumber = ?
1155 WHERE reserve_id = ?
1157 my $sth_upd = $dbh->prepare($query);
1158 $sth_upd->execute( $itemnumber, $reserve_id );
1159 # second step update all others reserves
1160 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1163 =head2 IsAvailableForItemLevelRequest
1165 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1167 Checks whether a given item record is available for an
1168 item-level hold request. An item is available if
1170 * it is not lost AND
1171 * it is not damaged AND
1172 * it is not withdrawn AND
1173 * does not have a not for loan value > 0
1175 Need to check the issuingrules onshelfholds column,
1176 if this is set items on the shelf can be placed on hold
1178 Note that IsAvailableForItemLevelRequest() does not
1179 check if the staff operator is authorized to place
1180 a request on the item - in particular,
1181 this routine does not check IndependentBranches
1182 and canreservefromotherbranches.
1184 =cut
1186 sub IsAvailableForItemLevelRequest {
1187 my $item = shift;
1188 my $borrower = shift;
1190 my $dbh = C4::Context->dbh;
1191 # must check the notforloan setting of the itemtype
1192 # FIXME - a lot of places in the code do this
1193 # or something similar - need to be
1194 # consolidated
1195 my $itype = _get_itype($item);
1196 my $notforloan_per_itemtype
1197 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1198 undef, $itype);
1200 return 0 if
1201 $notforloan_per_itemtype ||
1202 $item->{itemlost} ||
1203 $item->{notforloan} > 0 ||
1204 $item->{withdrawn} ||
1205 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1207 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1209 if ( $on_shelf_holds == 1 ) {
1210 return 1;
1211 } elsif ( $on_shelf_holds == 2 ) {
1212 my @items =
1213 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1215 my $any_available = 0;
1217 foreach my $i (@items) {
1218 $any_available = 1
1219 unless $i->itemlost
1220 || $i->notforloan > 0
1221 || $i->withdrawn
1222 || $i->onloan
1223 || IsItemOnHoldAndFound( $i->id )
1224 || ( $i->damaged
1225 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1226 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1229 return $any_available ? 0 : 1;
1232 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1235 =head2 OnShelfHoldsAllowed
1237 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1239 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1240 holds are allowed, returns true if so.
1242 =cut
1244 sub OnShelfHoldsAllowed {
1245 my ($item, $borrower) = @_;
1247 my $itype = _get_itype($item);
1248 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1251 sub _get_itype {
1252 my $item = shift;
1254 my $itype;
1255 if (C4::Context->preference('item-level_itypes')) {
1256 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1257 # When GetItem is fixed, we can remove this
1258 $itype = $item->{itype};
1260 else {
1261 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1262 # So if we already have a biblioitems join when calling this function,
1263 # we don't need to access the database again
1264 $itype = $item->{itemtype};
1266 unless ($itype) {
1267 my $dbh = C4::Context->dbh;
1268 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1269 my $sth = $dbh->prepare($query);
1270 $sth->execute($item->{biblioitemnumber});
1271 if (my $data = $sth->fetchrow_hashref()){
1272 $itype = $data->{itemtype};
1275 return $itype;
1278 sub _OnShelfHoldsAllowed {
1279 my ($itype,$borrowercategory,$branchcode) = @_;
1281 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1282 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1285 =head2 AlterPriority
1287 AlterPriority( $where, $reserve_id );
1289 This function changes a reserve's priority up, down, to the top, or to the bottom.
1290 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1292 =cut
1294 sub AlterPriority {
1295 my ( $where, $reserve_id ) = @_;
1297 my $hold = Koha::Holds->find( $reserve_id );
1298 return unless $hold;
1300 if ( $hold->cancellationdate ) {
1301 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1302 return;
1305 if ( $where eq 'up' || $where eq 'down' ) {
1307 my $priority = $hold->priority;
1308 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1309 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1311 } elsif ( $where eq 'top' ) {
1313 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1315 } elsif ( $where eq 'bottom' ) {
1317 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1320 # FIXME Should return the new priority
1323 =head2 ToggleLowestPriority
1325 ToggleLowestPriority( $borrowernumber, $biblionumber );
1327 This function sets the lowestPriority field to true if is false, and false if it is true.
1329 =cut
1331 sub ToggleLowestPriority {
1332 my ( $reserve_id ) = @_;
1334 my $dbh = C4::Context->dbh;
1336 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1337 $sth->execute( $reserve_id );
1339 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1342 =head2 ToggleSuspend
1344 ToggleSuspend( $reserve_id );
1346 This function sets the suspend field to true if is false, and false if it is true.
1347 If the reserve is currently suspended with a suspend_until date, that date will
1348 be cleared when it is unsuspended.
1350 =cut
1352 sub ToggleSuspend {
1353 my ( $reserve_id, $suspend_until ) = @_;
1355 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1357 my $hold = Koha::Holds->find( $reserve_id );
1359 if ( $hold->is_suspended ) {
1360 $hold->resume()
1361 } else {
1362 $hold->suspend_hold( $suspend_until );
1366 =head2 SuspendAll
1368 SuspendAll(
1369 borrowernumber => $borrowernumber,
1370 [ biblionumber => $biblionumber, ]
1371 [ suspend_until => $suspend_until, ]
1372 [ suspend => $suspend ]
1375 This function accepts a set of hash keys as its parameters.
1376 It requires either borrowernumber or biblionumber, or both.
1378 suspend_until is wholly optional.
1380 =cut
1382 sub SuspendAll {
1383 my %params = @_;
1385 my $borrowernumber = $params{'borrowernumber'} || undef;
1386 my $biblionumber = $params{'biblionumber'} || undef;
1387 my $suspend_until = $params{'suspend_until'} || undef;
1388 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1390 $suspend_until = eval { dt_from_string($suspend_until) }
1391 if ( defined($suspend_until) );
1393 return unless ( $borrowernumber || $biblionumber );
1395 my $params;
1396 $params->{found} = undef;
1397 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1398 $params->{biblionumber} = $biblionumber if $biblionumber;
1400 my @holds = Koha::Holds->search($params);
1402 if ($suspend) {
1403 map { $_->suspend_hold($suspend_until) } @holds;
1405 else {
1406 map { $_->resume() } @holds;
1411 =head2 _FixPriority
1413 _FixPriority({
1414 reserve_id => $reserve_id,
1415 [rank => $rank,]
1416 [ignoreSetLowestRank => $ignoreSetLowestRank]
1421 _FixPriority({ biblionumber => $biblionumber});
1423 This routine adjusts the priority of a hold request and holds
1424 on the same bib.
1426 In the first form, where a reserve_id is passed, the priority of the
1427 hold is set to supplied rank, and other holds for that bib are adjusted
1428 accordingly. If the rank is "del", the hold is cancelled. If no rank
1429 is supplied, all of the holds on that bib have their priority adjusted
1430 as if the second form had been used.
1432 In the second form, where a biblionumber is passed, the holds on that
1433 bib (that are not captured) are sorted in order of increasing priority,
1434 then have reserves.priority set so that the first non-captured hold
1435 has its priority set to 1, the second non-captured hold has its priority
1436 set to 2, and so forth.
1438 In both cases, holds that have the lowestPriority flag on are have their
1439 priority adjusted to ensure that they remain at the end of the line.
1441 Note that the ignoreSetLowestRank parameter is meant to be used only
1442 when _FixPriority calls itself.
1444 =cut
1446 sub _FixPriority {
1447 my ( $params ) = @_;
1448 my $reserve_id = $params->{reserve_id};
1449 my $rank = $params->{rank} // '';
1450 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1451 my $biblionumber = $params->{biblionumber};
1453 my $dbh = C4::Context->dbh;
1455 unless ( $biblionumber ) {
1456 my $hold = Koha::Holds->find( $reserve_id );
1457 $biblionumber = $hold->biblionumber;
1460 if ( $rank eq "del" ) {
1461 CancelReserve({ reserve_id => $reserve_id });
1463 elsif ( $rank eq "W" || $rank eq "0" ) {
1465 # make sure priority for waiting or in-transit items is 0
1466 my $query = "
1467 UPDATE reserves
1468 SET priority = 0
1469 WHERE reserve_id = ?
1470 AND found IN ('W', 'T')
1472 my $sth = $dbh->prepare($query);
1473 $sth->execute( $reserve_id );
1475 my @priority;
1477 # get whats left
1478 my $query = "
1479 SELECT reserve_id, borrowernumber, reservedate
1480 FROM reserves
1481 WHERE biblionumber = ?
1482 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1483 ORDER BY priority ASC
1485 my $sth = $dbh->prepare($query);
1486 $sth->execute( $biblionumber );
1487 while ( my $line = $sth->fetchrow_hashref ) {
1488 push( @priority, $line );
1491 # To find the matching index
1492 my $i;
1493 my $key = -1; # to allow for 0 to be a valid result
1494 for ( $i = 0 ; $i < @priority ; $i++ ) {
1495 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1496 $key = $i; # save the index
1497 last;
1501 # if index exists in array then move it to new position
1502 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1503 my $new_rank = $rank -
1504 1; # $new_rank is what you want the new index to be in the array
1505 my $moving_item = splice( @priority, $key, 1 );
1506 splice( @priority, $new_rank, 0, $moving_item );
1509 # now fix the priority on those that are left....
1510 $query = "
1511 UPDATE reserves
1512 SET priority = ?
1513 WHERE reserve_id = ?
1515 $sth = $dbh->prepare($query);
1516 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1517 $sth->execute(
1518 $j + 1,
1519 $priority[$j]->{'reserve_id'}
1523 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1524 $sth->execute();
1526 unless ( $ignoreSetLowestRank ) {
1527 while ( my $res = $sth->fetchrow_hashref() ) {
1528 _FixPriority({
1529 reserve_id => $res->{'reserve_id'},
1530 rank => '999999',
1531 ignoreSetLowestRank => 1
1537 =head2 _Findgroupreserve
1539 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1541 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1542 first match found. If neither, then we look for non-holds-queue based holds.
1543 Lookahead is the number of days to look in advance.
1545 C<&_Findgroupreserve> returns :
1546 C<@results> is an array of references-to-hash whose keys are mostly
1547 fields from the reserves table of the Koha database, plus
1548 C<biblioitemnumber>.
1550 =cut
1552 sub _Findgroupreserve {
1553 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1554 my $dbh = C4::Context->dbh;
1556 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1557 # check for exact targeted match
1558 my $item_level_target_query = qq{
1559 SELECT reserves.biblionumber AS biblionumber,
1560 reserves.borrowernumber AS borrowernumber,
1561 reserves.reservedate AS reservedate,
1562 reserves.branchcode AS branchcode,
1563 reserves.cancellationdate AS cancellationdate,
1564 reserves.found AS found,
1565 reserves.reservenotes AS reservenotes,
1566 reserves.priority AS priority,
1567 reserves.timestamp AS timestamp,
1568 biblioitems.biblioitemnumber AS biblioitemnumber,
1569 reserves.itemnumber AS itemnumber,
1570 reserves.reserve_id AS reserve_id,
1571 reserves.itemtype AS itemtype
1572 FROM reserves
1573 JOIN biblioitems USING (biblionumber)
1574 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1575 WHERE found IS NULL
1576 AND priority > 0
1577 AND item_level_request = 1
1578 AND itemnumber = ?
1579 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1580 AND suspend = 0
1581 ORDER BY priority
1583 my $sth = $dbh->prepare($item_level_target_query);
1584 $sth->execute($itemnumber, $lookahead||0);
1585 my @results;
1586 if ( my $data = $sth->fetchrow_hashref ) {
1587 push( @results, $data )
1588 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1590 return @results if @results;
1592 # check for title-level targeted match
1593 my $title_level_target_query = qq{
1594 SELECT reserves.biblionumber AS biblionumber,
1595 reserves.borrowernumber AS borrowernumber,
1596 reserves.reservedate AS reservedate,
1597 reserves.branchcode AS branchcode,
1598 reserves.cancellationdate AS cancellationdate,
1599 reserves.found AS found,
1600 reserves.reservenotes AS reservenotes,
1601 reserves.priority AS priority,
1602 reserves.timestamp AS timestamp,
1603 biblioitems.biblioitemnumber AS biblioitemnumber,
1604 reserves.itemnumber AS itemnumber,
1605 reserves.reserve_id AS reserve_id,
1606 reserves.itemtype AS itemtype
1607 FROM reserves
1608 JOIN biblioitems USING (biblionumber)
1609 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1610 WHERE found IS NULL
1611 AND priority > 0
1612 AND item_level_request = 0
1613 AND hold_fill_targets.itemnumber = ?
1614 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1615 AND suspend = 0
1616 ORDER BY priority
1618 $sth = $dbh->prepare($title_level_target_query);
1619 $sth->execute($itemnumber, $lookahead||0);
1620 @results = ();
1621 if ( my $data = $sth->fetchrow_hashref ) {
1622 push( @results, $data )
1623 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1625 return @results if @results;
1627 my $query = qq{
1628 SELECT reserves.biblionumber AS biblionumber,
1629 reserves.borrowernumber AS borrowernumber,
1630 reserves.reservedate AS reservedate,
1631 reserves.waitingdate AS waitingdate,
1632 reserves.branchcode AS branchcode,
1633 reserves.cancellationdate AS cancellationdate,
1634 reserves.found AS found,
1635 reserves.reservenotes AS reservenotes,
1636 reserves.priority AS priority,
1637 reserves.timestamp AS timestamp,
1638 reserves.itemnumber AS itemnumber,
1639 reserves.reserve_id AS reserve_id,
1640 reserves.itemtype AS itemtype
1641 FROM reserves
1642 WHERE reserves.biblionumber = ?
1643 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1644 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1645 AND suspend = 0
1646 ORDER BY priority
1648 $sth = $dbh->prepare($query);
1649 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1650 @results = ();
1651 while ( my $data = $sth->fetchrow_hashref ) {
1652 push( @results, $data )
1653 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1655 return @results;
1658 =head2 _koha_notify_reserve
1660 _koha_notify_reserve( $hold->reserve_id );
1662 Sends a notification to the patron that their hold has been filled (through
1663 ModReserveAffect, _not_ ModReserveFill)
1665 The letter code for this notice may be found using the following query:
1667 select distinct letter_code
1668 from message_transports
1669 inner join message_attributes using (message_attribute_id)
1670 where message_name = 'Hold_Filled'
1672 This will probably sipmly be 'HOLD', but because it is defined in the database,
1673 it is subject to addition or change.
1675 The following tables are availalbe witin the notice:
1677 branches
1678 borrowers
1679 biblio
1680 biblioitems
1681 reserves
1682 items
1684 =cut
1686 sub _koha_notify_reserve {
1687 my $reserve_id = shift;
1688 my $hold = Koha::Holds->find($reserve_id);
1689 my $borrowernumber = $hold->borrowernumber;
1691 my $patron = Koha::Patrons->find( $borrowernumber );
1693 # Try to get the borrower's email address
1694 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1696 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1697 borrowernumber => $borrowernumber,
1698 message_name => 'Hold_Filled'
1699 } );
1701 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1703 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1705 my %letter_params = (
1706 module => 'reserves',
1707 branchcode => $hold->branchcode,
1708 lang => $patron->lang,
1709 tables => {
1710 'branches' => $library,
1711 'borrowers' => $patron->unblessed,
1712 'biblio' => $hold->biblionumber,
1713 'biblioitems' => $hold->biblionumber,
1714 'reserves' => $hold->unblessed,
1715 'items' => $hold->itemnumber,
1719 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.
1720 my $send_notification = sub {
1721 my ( $mtt, $letter_code ) = (@_);
1722 return unless defined $letter_code;
1723 $letter_params{letter_code} = $letter_code;
1724 $letter_params{message_transport_type} = $mtt;
1725 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1726 unless ($letter) {
1727 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1728 return;
1731 C4::Letters::EnqueueLetter( {
1732 letter => $letter,
1733 borrowernumber => $borrowernumber,
1734 from_address => $admin_email_address,
1735 message_transport_type => $mtt,
1736 } );
1739 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1740 next if (
1741 ( $mtt eq 'email' and not $to_address ) # No email address
1742 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1743 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1746 &$send_notification($mtt, $letter_code);
1747 $notification_sent++;
1749 #Making sure that a print notification is sent if no other transport types can be utilized.
1750 if (! $notification_sent) {
1751 &$send_notification('print', 'HOLD');
1756 =head2 _ShiftPriorityByDateAndPriority
1758 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1760 This increments the priority of all reserves after the one
1761 with either the lowest date after C<$reservedate>
1762 or the lowest priority after C<$priority>.
1764 It effectively makes room for a new reserve to be inserted with a certain
1765 priority, which is returned.
1767 This is most useful when the reservedate can be set by the user. It allows
1768 the new reserve to be placed before other reserves that have a later
1769 reservedate. Since priority also is set by the form in reserves/request.pl
1770 the sub accounts for that too.
1772 =cut
1774 sub _ShiftPriorityByDateAndPriority {
1775 my ( $biblio, $resdate, $new_priority ) = @_;
1777 my $dbh = C4::Context->dbh;
1778 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1779 my $sth = $dbh->prepare( $query );
1780 $sth->execute( $biblio, $resdate, $new_priority );
1781 my $min_priority = $sth->fetchrow;
1782 # if no such matches are found, $new_priority remains as original value
1783 $new_priority = $min_priority if ( $min_priority );
1785 # Shift the priority up by one; works in conjunction with the next SQL statement
1786 $query = "UPDATE reserves
1787 SET priority = priority+1
1788 WHERE biblionumber = ?
1789 AND borrowernumber = ?
1790 AND reservedate = ?
1791 AND found IS NULL";
1792 my $sth_update = $dbh->prepare( $query );
1794 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1795 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1796 $sth = $dbh->prepare( $query );
1797 $sth->execute( $new_priority, $biblio );
1798 while ( my $row = $sth->fetchrow_hashref ) {
1799 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1802 return $new_priority; # so the caller knows what priority they wind up receiving
1805 =head2 OPACItemHoldsAllowed
1807 OPACItemHoldsAllowed($item_record,$borrower_record);
1809 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1810 if specific item holds are allowed, returns true if so.
1812 =cut
1814 sub OPACItemHoldsAllowed {
1815 my ($item,$borrower) = @_;
1817 my $branchcode = $item->{homebranch} or die "No homebranch";
1818 my $itype;
1819 my $dbh = C4::Context->dbh;
1820 if (C4::Context->preference('item-level_itypes')) {
1821 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1822 # When GetItem is fixed, we can remove this
1823 $itype = $item->{itype};
1825 else {
1826 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1827 my $sth = $dbh->prepare($query);
1828 $sth->execute($item->{biblioitemnumber});
1829 if (my $data = $sth->fetchrow_hashref()){
1830 $itype = $data->{itemtype};
1834 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1835 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1837 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1839 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1840 ORDER BY
1841 issuingrules.categorycode desc,
1842 issuingrules.itemtype desc,
1843 issuingrules.branchcode desc
1844 LIMIT 1";
1845 my $sth = $dbh->prepare($query);
1846 $sth->execute($borrower->{categorycode},$itype,$branchcode);
1847 my $data = $sth->fetchrow_hashref;
1848 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1849 return '' if $opacitemholds eq 'N';
1850 return $opacitemholds;
1853 =head2 MoveReserve
1855 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1857 Use when checking out an item to handle reserves
1858 If $cancelreserve boolean is set to true, it will remove existing reserve
1860 =cut
1862 sub MoveReserve {
1863 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1865 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1866 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1867 return unless $res;
1869 my $biblionumber = $res->{biblionumber};
1871 if ($res->{borrowernumber} == $borrowernumber) {
1872 ModReserveFill($res);
1874 else {
1875 # warn "Reserved";
1876 # The item is reserved by someone else.
1877 # Find this item in the reserves
1879 my $borr_res;
1880 foreach (@$all_reserves) {
1881 $_->{'borrowernumber'} == $borrowernumber or next;
1882 $_->{'biblionumber'} == $biblionumber or next;
1884 $borr_res = $_;
1885 last;
1888 if ( $borr_res ) {
1889 # The item is reserved by the current patron
1890 ModReserveFill($borr_res);
1893 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1894 RevertWaitingStatus({ itemnumber => $itemnumber });
1896 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1897 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
1902 =head2 MergeHolds
1904 MergeHolds($dbh,$to_biblio, $from_biblio);
1906 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1908 =cut
1910 sub MergeHolds {
1911 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1912 my $sth = $dbh->prepare(
1913 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1915 $sth->execute($from_biblio);
1916 if ( my $data = $sth->fetchrow_hashref() ) {
1918 # holds exist on old record, if not we don't need to do anything
1919 $sth = $dbh->prepare(
1920 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1921 $sth->execute( $to_biblio, $from_biblio );
1923 # Reorder by date
1924 # don't reorder those already waiting
1926 $sth = $dbh->prepare(
1927 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1929 my $upd_sth = $dbh->prepare(
1930 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1931 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1933 $sth->execute( $to_biblio, 'W', 'T' );
1934 my $priority = 1;
1935 while ( my $reserve = $sth->fetchrow_hashref() ) {
1936 $upd_sth->execute(
1937 $priority, $to_biblio,
1938 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1939 $reserve->{'itemnumber'}
1941 $priority++;
1946 =head2 RevertWaitingStatus
1948 RevertWaitingStatus({ itemnumber => $itemnumber });
1950 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1952 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1953 item level hold, even if it was only a bibliolevel hold to
1954 begin with. This is because we can no longer know if a hold
1955 was item-level or bib-level after a hold has been set to
1956 waiting status.
1958 =cut
1960 sub RevertWaitingStatus {
1961 my ( $params ) = @_;
1962 my $itemnumber = $params->{'itemnumber'};
1964 return unless ( $itemnumber );
1966 my $dbh = C4::Context->dbh;
1968 ## Get the waiting reserve we want to revert
1969 my $query = "
1970 SELECT * FROM reserves
1971 WHERE itemnumber = ?
1972 AND found IS NOT NULL
1974 my $sth = $dbh->prepare( $query );
1975 $sth->execute( $itemnumber );
1976 my $reserve = $sth->fetchrow_hashref();
1978 ## Increment the priority of all other non-waiting
1979 ## reserves for this bib record
1980 $query = "
1981 UPDATE reserves
1983 priority = priority + 1
1984 WHERE
1985 biblionumber = ?
1987 priority > 0
1989 $sth = $dbh->prepare( $query );
1990 $sth->execute( $reserve->{'biblionumber'} );
1992 ## Fix up the currently waiting reserve
1993 $query = "
1994 UPDATE reserves
1996 priority = 1,
1997 found = NULL,
1998 waitingdate = NULL
1999 WHERE
2000 reserve_id = ?
2002 $sth = $dbh->prepare( $query );
2003 $sth->execute( $reserve->{'reserve_id'} );
2004 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2007 =head2 ReserveSlip
2009 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2011 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2013 The letter code will be HOLD_SLIP, and the following tables are
2014 available within the slip:
2016 reserves
2017 branches
2018 borrowers
2019 biblio
2020 biblioitems
2021 items
2023 =cut
2025 sub ReserveSlip {
2026 my ($branch, $borrowernumber, $biblionumber) = @_;
2028 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2029 my $patron = Koha::Patrons->find( $borrowernumber );
2031 my $hold = Koha::Holds->search({biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next;
2032 return unless $hold;
2033 my $reserve = $hold->unblessed;
2035 return C4::Letters::GetPreparedLetter (
2036 module => 'circulation',
2037 letter_code => 'HOLD_SLIP',
2038 branchcode => $branch,
2039 lang => $patron->lang,
2040 tables => {
2041 'reserves' => $reserve,
2042 'branches' => $reserve->{branchcode},
2043 'borrowers' => $reserve->{borrowernumber},
2044 'biblio' => $reserve->{biblionumber},
2045 'biblioitems' => $reserve->{biblionumber},
2046 'items' => $reserve->{itemnumber},
2051 =head2 GetReservesControlBranch
2053 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2055 Return the branchcode to be used to determine which reserves
2056 policy applies to a transaction.
2058 C<$item> is a hashref for an item. Only 'homebranch' is used.
2060 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2062 =cut
2064 sub GetReservesControlBranch {
2065 my ( $item, $borrower ) = @_;
2067 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2069 my $branchcode =
2070 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2071 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2072 : undef;
2074 return $branchcode;
2077 =head2 CalculatePriority
2079 my $p = CalculatePriority($biblionumber, $resdate);
2081 Calculate priority for a new reserve on biblionumber, placing it at
2082 the end of the line of all holds whose start date falls before
2083 the current system time and that are neither on the hold shelf
2084 or in transit.
2086 The reserve date parameter is optional; if it is supplied, the
2087 priority is based on the set of holds whose start date falls before
2088 the parameter value.
2090 After calculation of this priority, it is recommended to call
2091 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2092 AddReserves.
2094 =cut
2096 sub CalculatePriority {
2097 my ( $biblionumber, $resdate ) = @_;
2099 my $sql = q{
2100 SELECT COUNT(*) FROM reserves
2101 WHERE biblionumber = ?
2102 AND priority > 0
2103 AND (found IS NULL OR found = '')
2105 #skip found==W or found==T (waiting or transit holds)
2106 if( $resdate ) {
2107 $sql.= ' AND ( reservedate <= ? )';
2109 else {
2110 $sql.= ' AND ( reservedate < NOW() )';
2112 my $dbh = C4::Context->dbh();
2113 my @row = $dbh->selectrow_array(
2114 $sql,
2115 undef,
2116 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2119 return @row ? $row[0]+1 : 1;
2122 =head2 IsItemOnHoldAndFound
2124 my $bool = IsItemFoundHold( $itemnumber );
2126 Returns true if the item is currently on hold
2127 and that hold has a non-null found status ( W, T, etc. )
2129 =cut
2131 sub IsItemOnHoldAndFound {
2132 my ($itemnumber) = @_;
2134 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2136 my $found = $rs->count(
2138 itemnumber => $itemnumber,
2139 found => { '!=' => undef }
2143 return $found;
2146 =head2 GetMaxPatronHoldsForRecord
2148 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2150 For multiple holds on a given record for a given patron, the max
2151 number of record level holds that a patron can be placed is the highest
2152 value of the holds_per_record rule for each item if the record for that
2153 patron. This subroutine finds and returns the highest holds_per_record
2154 rule value for a given patron id and record id.
2156 =cut
2158 sub GetMaxPatronHoldsForRecord {
2159 my ( $borrowernumber, $biblionumber ) = @_;
2161 my $patron = Koha::Patrons->find($borrowernumber);
2162 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2164 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2166 my $categorycode = $patron->categorycode;
2167 my $branchcode;
2168 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2170 my $max = 0;
2171 foreach my $item (@items) {
2172 my $itemtype = $item->effective_itemtype();
2174 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2176 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2177 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2178 $max = $holds_per_record if $holds_per_record > $max;
2181 return $max;
2184 =head2 GetHoldRule
2186 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2188 Returns the matching hold related issuingrule fields for a given
2189 patron category, itemtype, and library.
2191 =cut
2193 sub GetHoldRule {
2194 my ( $categorycode, $itemtype, $branchcode ) = @_;
2196 my $dbh = C4::Context->dbh;
2198 my $sth = $dbh->prepare(
2200 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2201 FROM issuingrules
2202 WHERE (categorycode in (?,'*') )
2203 AND (itemtype IN (?,'*'))
2204 AND (branchcode IN (?,'*'))
2205 ORDER BY categorycode DESC,
2206 itemtype DESC,
2207 branchcode DESC
2211 $sth->execute( $categorycode, $itemtype, $branchcode );
2213 return $sth->fetchrow_hashref();
2216 =head1 AUTHOR
2218 Koha Development Team <http://koha-community.org/>
2220 =cut