Bug 23049: Capitalise type passed to add_debit for `account`
[koha.git] / C4 / Reserves.pm
blobcf6ee50169dceef386dbea5cdc72198604fa8ad8
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
27 use C4::Accounts;
28 use C4::Biblio;
29 use C4::Circulation;
30 use C4::Context;
31 use C4::Items;
32 use C4::Letters;
33 use C4::Log;
34 use C4::Members::Messaging;
35 use C4::Members;
36 use Koha::Account::Lines;
37 use Koha::Biblios;
38 use Koha::Calendar;
39 use Koha::CirculationRules;
40 use Koha::Database;
41 use Koha::DateUtils;
42 use Koha::Hold;
43 use Koha::Holds;
44 use Koha::IssuingRules;
45 use Koha::ItemTypes;
46 use Koha::Items;
47 use Koha::Libraries;
48 use Koha::Old::Hold;
49 use Koha::Patrons;
51 use Carp;
52 use Data::Dumper;
53 use List::MoreUtils qw( firstidx any );
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
57 =head1 NAME
59 C4::Reserves - Koha functions for dealing with reservation.
61 =head1 SYNOPSIS
63 use C4::Reserves;
65 =head1 DESCRIPTION
67 This modules provides somes functions to deal with reservations.
69 Reserves are stored in reserves table.
70 The following columns contains important values :
71 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
72 =0 : then the reserve is being dealed
73 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
74 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
75 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
76 F(inished) : the reserve has been completed, and is done
77 - itemnumber : empty : the reserve is still unaffected to an item
78 filled: the reserve is attached to an item
79 The complete workflow is :
80 ==== 1st use case ====
81 patron request a document, 1st available : P >0, F=NULL, I=NULL
82 a library having it run "transfertodo", and clic on the list
83 if there is no transfer to do, the reserve waiting
84 patron can pick it up P =0, F=W, I=filled
85 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
86 The pickup library receive the book, it check in P =0, F=W, I=filled
87 The patron borrow the book P =0, F=F, I=filled
89 ==== 2nd use case ====
90 patron requests a document, a given item,
91 If pickup is holding branch P =0, F=W, I=filled
92 If transfer needed, write in branchtransfer P =0, F=T, I=filled
93 The pickup library receive the book, it checks it in P =0, F=W, I=filled
94 The patron borrow the book P =0, F=F, I=filled
96 =head1 FUNCTIONS
98 =cut
100 BEGIN {
101 require Exporter;
102 @ISA = qw(Exporter);
103 @EXPORT = qw(
104 &AddReserve
106 &GetReserveStatus
108 &GetOtherReserves
110 &ModReserveFill
111 &ModReserveAffect
112 &ModReserve
113 &ModReserveStatus
114 &ModReserveCancelAll
115 &ModReserveMinusPriority
116 &MoveReserve
118 &CheckReserves
119 &CanBookBeReserved
120 &CanItemBeReserved
121 &CanReserveBeCanceledFromOpac
122 &CancelExpiredReserves
124 &AutoUnsuspendReserves
126 &IsAvailableForItemLevelRequest
128 &AlterPriority
129 &ToggleLowestPriority
131 &ReserveSlip
132 &ToggleSuspend
133 &SuspendAll
135 &GetReservesControlBranch
137 IsItemOnHoldAndFound
139 GetMaxPatronHoldsForRecord
141 @EXPORT_OK = qw( MergeHolds );
144 =head2 AddReserve
146 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
148 Adds reserve and generates HOLDPLACED message.
150 The following tables are available witin the HOLDPLACED message:
152 branches
153 borrowers
154 biblio
155 biblioitems
156 items
157 reserves
159 =cut
161 sub AddReserve {
162 my (
163 $branch, $borrowernumber, $biblionumber, $bibitems,
164 $priority, $resdate, $expdate, $notes,
165 $title, $checkitem, $found, $itemtype
166 ) = @_;
168 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
169 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
171 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
173 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
174 # of the document, we force the value $priority and $found .
175 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
176 $priority = 0;
177 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
178 if ( $item->holdingbranch eq $branch ) {
179 $found = 'W';
183 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
185 # Make room in reserves for this before those of a later reserve date
186 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
189 my $waitingdate;
191 # If the reserv had the waiting status, we had the value of the resdate
192 if ( $found eq 'W' ) {
193 $waitingdate = $resdate;
196 # Don't add itemtype limit if specific item is selected
197 $itemtype = undef if $checkitem;
199 # updates take place here
200 my $hold = Koha::Hold->new(
202 borrowernumber => $borrowernumber,
203 biblionumber => $biblionumber,
204 reservedate => $resdate,
205 branchcode => $branch,
206 priority => $priority,
207 reservenotes => $notes,
208 itemnumber => $checkitem,
209 found => $found,
210 waitingdate => $waitingdate,
211 expirationdate => $expdate,
212 itemtype => $itemtype,
213 item_level_hold => $checkitem ? 1 : 0,
215 )->store();
216 $hold->set_waiting() if $found eq 'W';
218 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
219 if C4::Context->preference('HoldsLog');
221 my $reserve_id = $hold->id();
223 # add a reserve fee if needed
224 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
225 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
226 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
229 _FixPriority({ biblionumber => $biblionumber});
231 # Send e-mail to librarian if syspref is active
232 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
233 my $patron = Koha::Patrons->find( $borrowernumber );
234 my $library = $patron->library;
235 if ( my $letter = C4::Letters::GetPreparedLetter (
236 module => 'reserves',
237 letter_code => 'HOLDPLACED',
238 branchcode => $branch,
239 lang => $patron->lang,
240 tables => {
241 'branches' => $library->unblessed,
242 'borrowers' => $patron->unblessed,
243 'biblio' => $biblionumber,
244 'biblioitems' => $biblionumber,
245 'items' => $checkitem,
246 'reserves' => $hold->unblessed,
248 ) ) {
250 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
252 C4::Letters::EnqueueLetter(
253 { letter => $letter,
254 borrowernumber => $borrowernumber,
255 message_transport_type => 'email',
256 from_address => $admin_email_address,
257 to_address => $admin_email_address,
263 return $reserve_id;
266 =head2 CanBookBeReserved
268 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
269 if ($canReserve eq 'OK') { #We can reserve this Item! }
271 See CanItemBeReserved() for possible return values.
273 =cut
275 sub CanBookBeReserved{
276 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
278 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
279 #get items linked via host records
280 my @hostitems = get_hostitemnumbers_of($biblionumber);
281 if (@hostitems){
282 push (@itemnumbers, @hostitems);
285 my $canReserve = { status => '' };
286 foreach my $itemnumber (@itemnumbers) {
287 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
288 return { status => 'OK' } if $canReserve->{status} eq 'OK';
290 return $canReserve;
293 =head2 CanItemBeReserved
295 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
296 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
298 @RETURNS { status => OK }, if the Item can be reserved.
299 { status => ageRestricted }, if the Item is age restricted for this borrower.
300 { status => damaged }, if the Item is damaged.
301 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
302 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
303 { status => notReservable }, if holds on this item are not allowed
304 { status => libraryNotFound }, if given branchcode is not an existing library
305 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
306 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
308 =cut
310 sub CanItemBeReserved {
311 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
313 my $dbh = C4::Context->dbh;
314 my $ruleitemtype; # itemtype of the matching issuing rule
315 my $allowedreserves = 0; # Total number of holds allowed across all records
316 my $holds_per_record = 1; # Total number of holds allowed for this one given record
317 my $holds_per_day; # Default to unlimited
319 # we retrieve borrowers and items informations #
320 # item->{itype} will come for biblioitems if necessery
321 my $item = Koha::Items->find($itemnumber);
322 my $biblio = $item->biblio;
323 my $patron = Koha::Patrons->find( $borrowernumber );
324 my $borrower = $patron->unblessed;
326 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
327 return { status =>'damaged' }
328 if ( $item->damaged
329 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
331 # Check for the age restriction
332 my ( $ageRestriction, $daysToAgeRestriction ) =
333 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
334 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
336 # Check that the patron doesn't have an item level hold on this item already
337 return { status =>'itemAlreadyOnHold' }
338 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
340 my $controlbranch = C4::Context->preference('ReservesControlBranch');
342 my $querycount = q{
343 SELECT count(*) AS count
344 FROM reserves
345 LEFT JOIN items USING (itemnumber)
346 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
347 LEFT JOIN borrowers USING (borrowernumber)
348 WHERE borrowernumber = ?
351 my $branchcode = "";
352 my $branchfield = "reserves.branchcode";
354 if ( $controlbranch eq "ItemHomeLibrary" ) {
355 $branchfield = "items.homebranch";
356 $branchcode = $item->homebranch;
358 elsif ( $controlbranch eq "PatronLibrary" ) {
359 $branchfield = "borrowers.branchcode";
360 $branchcode = $borrower->{branchcode};
363 # we retrieve rights
364 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
365 $ruleitemtype = $rights->{itemtype};
366 $allowedreserves = $rights->{reservesallowed};
367 $holds_per_record = $rights->{holds_per_record};
368 $holds_per_day = $rights->{holds_per_day};
370 else {
371 $ruleitemtype = '*';
374 my $holds = Koha::Holds->search(
376 borrowernumber => $borrowernumber,
377 biblionumber => $item->biblionumber,
378 found => undef, # Found holds don't count against a patron's holds limit
381 if ( $holds->count() >= $holds_per_record ) {
382 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
385 my $today_holds = Koha::Holds->search({
386 borrowernumber => $borrowernumber,
387 reservedate => dt_from_string->date
390 if ( defined $holds_per_day &&
391 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
392 or ( $holds_per_day == 0 ) )
394 return { status => 'tooManyReservesToday', limit => $holds_per_day };
397 # we retrieve count
399 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
401 # If using item-level itypes, fall back to the record
402 # level itemtype if the hold has no associated item
403 $querycount .=
404 C4::Context->preference('item-level_itypes')
405 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
406 : " AND biblioitems.itemtype = ?"
407 if ( $ruleitemtype ne "*" );
409 my $sthcount = $dbh->prepare($querycount);
411 if ( $ruleitemtype eq "*" ) {
412 $sthcount->execute( $borrowernumber, $branchcode );
414 else {
415 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
418 my $reservecount = "0";
419 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
420 $reservecount = $rowcount->{count};
423 # we check if it's ok or not
424 if ( $reservecount >= $allowedreserves ) {
425 return { status => 'tooManyReserves', limit => $allowedreserves };
428 # Now we need to check hold limits by patron category
429 my $rule = Koha::CirculationRules->get_effective_rule(
431 categorycode => $borrower->{categorycode},
432 branchcode => $branchcode,
433 rule_name => 'max_holds',
436 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
437 my $total_holds_count = Koha::Holds->search(
439 borrowernumber => $borrower->{borrowernumber}
441 )->count();
443 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
446 my $reserves_control_branch =
447 GetReservesControlBranch( $item->unblessed(), $borrower );
448 my $branchitemrule =
449 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
451 if ( $branchitemrule->{holdallowed} == 0 ) {
452 return { status => 'notReservable' };
455 if ( $branchitemrule->{holdallowed} == 1
456 && $borrower->{branchcode} ne $item->homebranch )
458 return { status => 'cannotReserveFromOtherBranches' };
461 # If reservecount is ok, we check item branch if IndependentBranches is ON
462 # and canreservefromotherbranches is OFF
463 if ( C4::Context->preference('IndependentBranches')
464 and !C4::Context->preference('canreservefromotherbranches') )
466 if ( $item->homebranch ne $borrower->{branchcode} ) {
467 return { status => 'cannotReserveFromOtherBranches' };
471 if ($pickup_branchcode) {
472 my $destination = Koha::Libraries->find({
473 branchcode => $pickup_branchcode,
476 unless ($destination) {
477 return { status => 'libraryNotFound' };
479 unless ($destination->pickup_location) {
480 return { status => 'libraryNotPickupLocation' };
482 unless ($item->can_be_transferred({ to => $destination })) {
483 return { status => 'cannotBeTransferred' };
487 return { status => 'OK' };
490 =head2 CanReserveBeCanceledFromOpac
492 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
494 returns 1 if reserve can be cancelled by user from OPAC.
495 First check if reserve belongs to user, next checks if reserve is not in
496 transfer or waiting status
498 =cut
500 sub CanReserveBeCanceledFromOpac {
501 my ($reserve_id, $borrowernumber) = @_;
503 return unless $reserve_id and $borrowernumber;
504 my $reserve = Koha::Holds->find($reserve_id);
506 return 0 unless $reserve->borrowernumber == $borrowernumber;
507 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
509 return 1;
513 =head2 GetOtherReserves
515 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
517 Check queued list of this document and check if this document must be transferred
519 =cut
521 sub GetOtherReserves {
522 my ($itemnumber) = @_;
523 my $messages;
524 my $nextreservinfo;
525 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
526 if ($checkreserves) {
527 my $item = Koha::Items->find($itemnumber);
528 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
529 $messages->{'transfert'} = $checkreserves->{'branchcode'};
530 #minus priorities of others reservs
531 ModReserveMinusPriority(
532 $itemnumber,
533 $checkreserves->{'reserve_id'},
536 #launch the subroutine dotransfer
537 C4::Items::ModItemTransfer(
538 $itemnumber,
539 $item->holdingbranch,
540 $checkreserves->{'branchcode'}
545 #step 2b : case of a reservation on the same branch, set the waiting status
546 else {
547 $messages->{'waiting'} = 1;
548 ModReserveMinusPriority(
549 $itemnumber,
550 $checkreserves->{'reserve_id'},
552 ModReserveStatus($itemnumber,'W');
555 $nextreservinfo = $checkreserves->{'borrowernumber'};
558 return ( $messages, $nextreservinfo );
561 =head2 ChargeReserveFee
563 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
565 Charge the fee for a reserve (if $fee > 0)
567 =cut
569 sub ChargeReserveFee {
570 my ( $borrowernumber, $fee, $title ) = @_;
571 return if !$fee || $fee == 0; # the last test is needed to include 0.00
572 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
574 amount => $fee,
575 description => $title,
576 note => undef,
577 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
578 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
579 interface => C4::Context->interface,
580 invoice_type => undef,
581 type => 'RESERVE',
582 item_id => undef
587 =head2 GetReserveFee
589 $fee = GetReserveFee( $borrowernumber, $biblionumber );
591 Calculate the fee for a reserve (if applicable).
593 =cut
595 sub GetReserveFee {
596 my ( $borrowernumber, $biblionumber ) = @_;
597 my $borquery = qq{
598 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
600 my $issue_qry = qq{
601 SELECT COUNT(*) FROM items
602 LEFT JOIN issues USING (itemnumber)
603 WHERE items.biblionumber=? AND issues.issue_id IS NULL
605 my $holds_qry = qq{
606 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
609 my $dbh = C4::Context->dbh;
610 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
611 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
612 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
613 # This is a reconstruction of the old code:
614 # Compare number of items with items issued, and optionally check holds
615 # If not all items are issued and there are no holds: charge no fee
616 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
617 my ( $notissued, $reserved );
618 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
619 ( $biblionumber ) );
620 if( $notissued ) {
621 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
622 ( $biblionumber, $borrowernumber ) );
623 $fee = 0 if $reserved == 0;
626 return $fee;
629 =head2 GetReserveStatus
631 $reservestatus = GetReserveStatus($itemnumber);
633 Takes an itemnumber and returns the status of the reserve placed on it.
634 If several reserves exist, the reserve with the lower priority is given.
636 =cut
638 ## FIXME: I don't think this does what it thinks it does.
639 ## It only ever checks the first reserve result, even though
640 ## multiple reserves for that bib can have the itemnumber set
641 ## the sub is only used once in the codebase.
642 sub GetReserveStatus {
643 my ($itemnumber) = @_;
645 my $dbh = C4::Context->dbh;
647 my ($sth, $found, $priority);
648 if ( $itemnumber ) {
649 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
650 $sth->execute($itemnumber);
651 ($found, $priority) = $sth->fetchrow_array;
654 if(defined $found) {
655 return 'Waiting' if $found eq 'W' and $priority == 0;
656 return 'Finished' if $found eq 'F';
659 return 'Reserved' if $priority > 0;
661 return ''; # empty string here will remove need for checking undef, or less log lines
664 =head2 CheckReserves
666 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
667 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
668 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
670 Find a book in the reserves.
672 C<$itemnumber> is the book's item number.
673 C<$lookahead> is the number of days to look in advance for future reserves.
675 As I understand it, C<&CheckReserves> looks for the given item in the
676 reserves. If it is found, that's a match, and C<$status> is set to
677 C<Waiting>.
679 Otherwise, it finds the most important item in the reserves with the
680 same biblio number as this book (I'm not clear on this) and returns it
681 with C<$status> set to C<Reserved>.
683 C<&CheckReserves> returns a two-element list:
685 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
687 C<$reserve> is the reserve item that matched. It is a
688 reference-to-hash whose keys are mostly the fields of the reserves
689 table in the Koha database.
691 =cut
693 sub CheckReserves {
694 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
695 my $dbh = C4::Context->dbh;
696 my $sth;
697 my $select;
698 if (C4::Context->preference('item-level_itypes')){
699 $select = "
700 SELECT items.biblionumber,
701 items.biblioitemnumber,
702 itemtypes.notforloan,
703 items.notforloan AS itemnotforloan,
704 items.itemnumber,
705 items.damaged,
706 items.homebranch,
707 items.holdingbranch
708 FROM items
709 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
710 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
713 else {
714 $select = "
715 SELECT items.biblionumber,
716 items.biblioitemnumber,
717 itemtypes.notforloan,
718 items.notforloan AS itemnotforloan,
719 items.itemnumber,
720 items.damaged,
721 items.homebranch,
722 items.holdingbranch
723 FROM items
724 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
725 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
729 if ($item) {
730 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
731 $sth->execute($item);
733 else {
734 $sth = $dbh->prepare("$select WHERE barcode = ?");
735 $sth->execute($barcode);
737 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
738 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
739 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
741 return unless $itemnumber; # bail if we got nothing.
742 # if item is not for loan it cannot be reserved either.....
743 # except where items.notforloan < 0 : This indicates the item is holdable.
744 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
746 # Find this item in the reserves
747 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
749 # $priority and $highest are used to find the most important item
750 # in the list returned by &_Findgroupreserve. (The lower $priority,
751 # the more important the item.)
752 # $highest is the most important item we've seen so far.
753 my $highest;
754 if (scalar @reserves) {
755 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
756 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
757 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
759 my $priority = 10000000;
760 foreach my $res (@reserves) {
761 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
762 if ($res->{'found'} eq 'W') {
763 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
764 } else {
765 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
767 } else {
768 my $patron;
769 my $item;
770 my $local_hold_match;
772 if ($LocalHoldsPriority) {
773 $patron = Koha::Patrons->find( $res->{borrowernumber} );
774 $item = Koha::Items->find($itemnumber);
776 my $local_holds_priority_item_branchcode =
777 $item->$LocalHoldsPriorityItemControl;
778 my $local_holds_priority_patron_branchcode =
779 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
780 ? $res->{branchcode}
781 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
782 ? $patron->branchcode
783 : undef;
784 $local_hold_match =
785 $local_holds_priority_item_branchcode eq
786 $local_holds_priority_patron_branchcode;
789 # See if this item is more important than what we've got so far
790 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
791 $item ||= Koha::Items->find($itemnumber);
792 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
793 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
794 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
795 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
796 next if ($branchitemrule->{'holdallowed'} == 0);
797 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
798 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
799 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
800 next unless $item->can_be_transferred( { to => scalar Koha::Libraries->find( $res->{branchcode} ) } );
801 $priority = $res->{'priority'};
802 $highest = $res;
803 last if $local_hold_match;
809 # If we get this far, then no exact match was found.
810 # We return the most important (i.e. next) reservation.
811 if ($highest) {
812 $highest->{'itemnumber'} = $item;
813 return ( "Reserved", $highest, \@reserves );
816 return ( '' );
819 =head2 CancelExpiredReserves
821 CancelExpiredReserves();
823 Cancels all reserves with an expiration date from before today.
825 =cut
827 sub CancelExpiredReserves {
828 my $today = dt_from_string();
829 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
830 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
832 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
833 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
834 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
836 # FIXME To move to Koha::Holds->search_expired (?)
837 my $holds = Koha::Holds->search( $params );
839 while ( my $hold = $holds->next ) {
840 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
842 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
844 my $cancel_params = {};
845 if ( $hold->found eq 'W' ) {
846 $cancel_params->{charge_cancel_fee} = 1;
848 $hold->cancel( $cancel_params );
852 =head2 AutoUnsuspendReserves
854 AutoUnsuspendReserves();
856 Unsuspends all suspended reserves with a suspend_until date from before today.
858 =cut
860 sub AutoUnsuspendReserves {
861 my $today = dt_from_string();
863 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
865 map { $_->resume() } @holds;
868 =head2 ModReserve
870 ModReserve({ rank => $rank,
871 reserve_id => $reserve_id,
872 branchcode => $branchcode
873 [, itemnumber => $itemnumber ]
874 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
877 Change a hold request's priority or cancel it.
879 C<$rank> specifies the effect of the change. If C<$rank>
880 is 'W' or 'n', nothing happens. This corresponds to leaving a
881 request alone when changing its priority in the holds queue
882 for a bib.
884 If C<$rank> is 'del', the hold request is cancelled.
886 If C<$rank> is an integer greater than zero, the priority of
887 the request is set to that value. Since priority != 0 means
888 that the item is not waiting on the hold shelf, setting the
889 priority to a non-zero value also sets the request's found
890 status and waiting date to NULL.
892 The optional C<$itemnumber> parameter is used only when
893 C<$rank> is a non-zero integer; if supplied, the itemnumber
894 of the hold request is set accordingly; if omitted, the itemnumber
895 is cleared.
897 B<FIXME:> Note that the forgoing can have the effect of causing
898 item-level hold requests to turn into title-level requests. This
899 will be fixed once reserves has separate columns for requested
900 itemnumber and supplying itemnumber.
902 =cut
904 sub ModReserve {
905 my ( $params ) = @_;
907 my $rank = $params->{'rank'};
908 my $reserve_id = $params->{'reserve_id'};
909 my $branchcode = $params->{'branchcode'};
910 my $itemnumber = $params->{'itemnumber'};
911 my $suspend_until = $params->{'suspend_until'};
912 my $borrowernumber = $params->{'borrowernumber'};
913 my $biblionumber = $params->{'biblionumber'};
915 return if $rank eq "W";
916 return if $rank eq "n";
918 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
920 my $hold;
921 unless ( $reserve_id ) {
922 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
923 return unless $holds->count; # FIXME Should raise an exception
924 $hold = $holds->next;
925 $reserve_id = $hold->reserve_id;
928 $hold ||= Koha::Holds->find($reserve_id);
930 if ( $rank eq "del" ) {
931 $hold->cancel;
933 elsif ($rank =~ /^\d+/ and $rank > 0) {
934 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
935 if C4::Context->preference('HoldsLog');
937 my $properties = {
938 priority => $rank,
939 branchcode => $branchcode,
940 itemnumber => $itemnumber,
941 found => undef,
942 waitingdate => undef
944 if (exists $params->{reservedate}) {
945 $properties->{reservedate} = $params->{reservedate} || undef;
947 if (exists $params->{expirationdate}) {
948 $properties->{expirationdate} = $params->{expirationdate} || undef;
951 $hold->set($properties)->store();
953 if ( defined( $suspend_until ) ) {
954 if ( $suspend_until ) {
955 $suspend_until = eval { dt_from_string( $suspend_until ) };
956 $hold->suspend_hold( $suspend_until );
957 } else {
958 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
959 # If the hold is not suspended, this does nothing.
960 $hold->set( { suspend_until => undef } )->store();
964 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
968 =head2 ModReserveFill
970 &ModReserveFill($reserve);
972 Fill a reserve. If I understand this correctly, this means that the
973 reserved book has been found and given to the patron who reserved it.
975 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
976 whose keys are fields from the reserves table in the Koha database.
978 =cut
980 sub ModReserveFill {
981 my ($res) = @_;
982 my $reserve_id = $res->{'reserve_id'};
984 my $hold = Koha::Holds->find($reserve_id);
985 # get the priority on this record....
986 my $priority = $hold->priority;
988 # update the hold statuses, no need to store it though, we will be deleting it anyway
989 $hold->set(
991 found => 'F',
992 priority => 0,
996 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
997 Koha::Old::Hold->new( $hold->unblessed() )->store();
999 $hold->delete();
1001 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1002 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1003 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1006 # now fix the priority on the others (if the priority wasn't
1007 # already sorted!)....
1008 unless ( $priority == 0 ) {
1009 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1013 =head2 ModReserveStatus
1015 &ModReserveStatus($itemnumber, $newstatus);
1017 Update the reserve status for the active (priority=0) reserve.
1019 $itemnumber is the itemnumber the reserve is on
1021 $newstatus is the new status.
1023 =cut
1025 sub ModReserveStatus {
1027 #first : check if we have a reservation for this item .
1028 my ($itemnumber, $newstatus) = @_;
1029 my $dbh = C4::Context->dbh;
1031 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1032 my $sth_set = $dbh->prepare($query);
1033 $sth_set->execute( $newstatus, $itemnumber );
1035 my $item = Koha::Items->find($itemnumber);
1036 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) && $newstatus ) {
1037 CartToShelf( $itemnumber );
1041 =head2 ModReserveAffect
1043 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1045 This function affect an item and a status for a given reserve, either fetched directly
1046 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1047 is given, only first reserve returned is affected, which is ok for anything but
1048 multi-item holds.
1050 if $transferToDo is not set, then the status is set to "Waiting" as well.
1051 otherwise, a transfer is on the way, and the end of the transfer will
1052 take care of the waiting status
1054 =cut
1056 sub ModReserveAffect {
1057 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1058 my $dbh = C4::Context->dbh;
1060 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1061 # attached to $itemnumber
1062 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1063 $sth->execute($itemnumber);
1064 my ($biblionumber) = $sth->fetchrow;
1066 # get request - need to find out if item is already
1067 # waiting in order to not send duplicate hold filled notifications
1069 my $hold;
1070 # Find hold by id if we have it
1071 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1072 # Find item level hold for this item if there is one
1073 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1074 # Find record level hold if there is no item level hold
1075 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1077 return unless $hold;
1079 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1081 $hold->itemnumber($itemnumber);
1082 $hold->set_waiting($transferToDo);
1084 _koha_notify_reserve( $hold->reserve_id )
1085 if ( !$transferToDo && !$already_on_shelf );
1087 _FixPriority( { biblionumber => $biblionumber } );
1088 my $item = Koha::Items->find($itemnumber);
1089 if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART' ) ) {
1090 CartToShelf( $itemnumber );
1093 return;
1096 =head2 ModReserveCancelAll
1098 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1100 function to cancel reserv,check other reserves, and transfer document if it's necessary
1102 =cut
1104 sub ModReserveCancelAll {
1105 my $messages;
1106 my $nextreservinfo;
1107 my ( $itemnumber, $borrowernumber ) = @_;
1109 #step 1 : cancel the reservation
1110 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1111 return unless $holds->count;
1112 $holds->next->cancel;
1114 #step 2 launch the subroutine of the others reserves
1115 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1117 return ( $messages, $nextreservinfo );
1120 =head2 ModReserveMinusPriority
1122 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1124 Reduce the values of queued list
1126 =cut
1128 sub ModReserveMinusPriority {
1129 my ( $itemnumber, $reserve_id ) = @_;
1131 #first step update the value of the first person on reserv
1132 my $dbh = C4::Context->dbh;
1133 my $query = "
1134 UPDATE reserves
1135 SET priority = 0 , itemnumber = ?
1136 WHERE reserve_id = ?
1138 my $sth_upd = $dbh->prepare($query);
1139 $sth_upd->execute( $itemnumber, $reserve_id );
1140 # second step update all others reserves
1141 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1144 =head2 IsAvailableForItemLevelRequest
1146 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1148 Checks whether a given item record is available for an
1149 item-level hold request. An item is available if
1151 * it is not lost AND
1152 * it is not damaged AND
1153 * it is not withdrawn AND
1154 * a waiting or in transit reserve is placed on
1155 * does not have a not for loan value > 0
1157 Need to check the issuingrules onshelfholds column,
1158 if this is set items on the shelf can be placed on hold
1160 Note that IsAvailableForItemLevelRequest() does not
1161 check if the staff operator is authorized to place
1162 a request on the item - in particular,
1163 this routine does not check IndependentBranches
1164 and canreservefromotherbranches.
1166 =cut
1168 sub IsAvailableForItemLevelRequest {
1169 my ( $item, $patron, $pickup_branchcode ) = @_;
1171 my $dbh = C4::Context->dbh;
1172 # must check the notforloan setting of the itemtype
1173 # FIXME - a lot of places in the code do this
1174 # or something similar - need to be
1175 # consolidated
1176 my $itemtype = $item->effective_itemtype;
1177 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1179 return 0 if
1180 $notforloan_per_itemtype ||
1181 $item->itemlost ||
1182 $item->notforloan > 0 ||
1183 $item->withdrawn ||
1184 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1186 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1188 if ($pickup_branchcode) {
1189 my $destination = Koha::Libraries->find($pickup_branchcode);
1190 return 0 unless $destination;
1191 return 0 unless $destination->pickup_location;
1192 return 0 unless $item->can_be_transferred( { to => $destination } );
1195 if ( $on_shelf_holds == 1 ) {
1196 return 1;
1197 } elsif ( $on_shelf_holds == 2 ) {
1198 my @items =
1199 Koha::Items->search( { biblionumber => $item->biblionumber } );
1201 my $any_available = 0;
1203 foreach my $i (@items) {
1204 my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1205 my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1207 $any_available = 1
1208 unless $i->itemlost
1209 || $i->notforloan > 0
1210 || $i->withdrawn
1211 || $i->onloan
1212 || IsItemOnHoldAndFound( $i->id )
1213 || ( $i->damaged
1214 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1215 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1216 || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch;
1219 return $any_available ? 0 : 1;
1220 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1221 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1225 sub _get_itype {
1226 my $item = shift;
1228 my $itype;
1229 if (C4::Context->preference('item-level_itypes')) {
1230 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1231 # When GetItem is fixed, we can remove this
1232 $itype = $item->{itype};
1234 else {
1235 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1236 # So if we already have a biblioitems join when calling this function,
1237 # we don't need to access the database again
1238 $itype = $item->{itemtype};
1240 unless ($itype) {
1241 my $dbh = C4::Context->dbh;
1242 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1243 my $sth = $dbh->prepare($query);
1244 $sth->execute($item->{biblioitemnumber});
1245 if (my $data = $sth->fetchrow_hashref()){
1246 $itype = $data->{itemtype};
1249 return $itype;
1252 =head2 AlterPriority
1254 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1256 This function changes a reserve's priority up, down, to the top, or to the bottom.
1257 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1259 =cut
1261 sub AlterPriority {
1262 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1264 my $hold = Koha::Holds->find( $reserve_id );
1265 return unless $hold;
1267 if ( $hold->cancellationdate ) {
1268 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1269 return;
1272 if ( $where eq 'up' ) {
1273 return unless $prev_priority;
1274 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1275 } elsif ( $where eq 'down' ) {
1276 return unless $next_priority;
1277 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1278 } elsif ( $where eq 'top' ) {
1279 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1280 } elsif ( $where eq 'bottom' ) {
1281 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1284 # FIXME Should return the new priority
1287 =head2 ToggleLowestPriority
1289 ToggleLowestPriority( $borrowernumber, $biblionumber );
1291 This function sets the lowestPriority field to true if is false, and false if it is true.
1293 =cut
1295 sub ToggleLowestPriority {
1296 my ( $reserve_id ) = @_;
1298 my $dbh = C4::Context->dbh;
1300 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1301 $sth->execute( $reserve_id );
1303 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1306 =head2 ToggleSuspend
1308 ToggleSuspend( $reserve_id );
1310 This function sets the suspend field to true if is false, and false if it is true.
1311 If the reserve is currently suspended with a suspend_until date, that date will
1312 be cleared when it is unsuspended.
1314 =cut
1316 sub ToggleSuspend {
1317 my ( $reserve_id, $suspend_until ) = @_;
1319 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1321 my $hold = Koha::Holds->find( $reserve_id );
1323 if ( $hold->is_suspended ) {
1324 $hold->resume()
1325 } else {
1326 $hold->suspend_hold( $suspend_until );
1330 =head2 SuspendAll
1332 SuspendAll(
1333 borrowernumber => $borrowernumber,
1334 [ biblionumber => $biblionumber, ]
1335 [ suspend_until => $suspend_until, ]
1336 [ suspend => $suspend ]
1339 This function accepts a set of hash keys as its parameters.
1340 It requires either borrowernumber or biblionumber, or both.
1342 suspend_until is wholly optional.
1344 =cut
1346 sub SuspendAll {
1347 my %params = @_;
1349 my $borrowernumber = $params{'borrowernumber'} || undef;
1350 my $biblionumber = $params{'biblionumber'} || undef;
1351 my $suspend_until = $params{'suspend_until'} || undef;
1352 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1354 $suspend_until = eval { dt_from_string($suspend_until) }
1355 if ( defined($suspend_until) );
1357 return unless ( $borrowernumber || $biblionumber );
1359 my $params;
1360 $params->{found} = undef;
1361 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1362 $params->{biblionumber} = $biblionumber if $biblionumber;
1364 my @holds = Koha::Holds->search($params);
1366 if ($suspend) {
1367 map { $_->suspend_hold($suspend_until) } @holds;
1369 else {
1370 map { $_->resume() } @holds;
1375 =head2 _FixPriority
1377 _FixPriority({
1378 reserve_id => $reserve_id,
1379 [rank => $rank,]
1380 [ignoreSetLowestRank => $ignoreSetLowestRank]
1385 _FixPriority({ biblionumber => $biblionumber});
1387 This routine adjusts the priority of a hold request and holds
1388 on the same bib.
1390 In the first form, where a reserve_id is passed, the priority of the
1391 hold is set to supplied rank, and other holds for that bib are adjusted
1392 accordingly. If the rank is "del", the hold is cancelled. If no rank
1393 is supplied, all of the holds on that bib have their priority adjusted
1394 as if the second form had been used.
1396 In the second form, where a biblionumber is passed, the holds on that
1397 bib (that are not captured) are sorted in order of increasing priority,
1398 then have reserves.priority set so that the first non-captured hold
1399 has its priority set to 1, the second non-captured hold has its priority
1400 set to 2, and so forth.
1402 In both cases, holds that have the lowestPriority flag on are have their
1403 priority adjusted to ensure that they remain at the end of the line.
1405 Note that the ignoreSetLowestRank parameter is meant to be used only
1406 when _FixPriority calls itself.
1408 =cut
1410 sub _FixPriority {
1411 my ( $params ) = @_;
1412 my $reserve_id = $params->{reserve_id};
1413 my $rank = $params->{rank} // '';
1414 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1415 my $biblionumber = $params->{biblionumber};
1417 my $dbh = C4::Context->dbh;
1419 my $hold;
1420 if ( $reserve_id ) {
1421 $hold = Koha::Holds->find( $reserve_id );
1422 return unless $hold;
1425 unless ( $biblionumber ) { # FIXME This is a very weird API
1426 $biblionumber = $hold->biblionumber;
1429 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1430 $hold->cancel;
1432 elsif ( $rank eq "W" || $rank eq "0" ) {
1434 # make sure priority for waiting or in-transit items is 0
1435 my $query = "
1436 UPDATE reserves
1437 SET priority = 0
1438 WHERE reserve_id = ?
1439 AND found IN ('W', 'T')
1441 my $sth = $dbh->prepare($query);
1442 $sth->execute( $reserve_id );
1444 my @priority;
1446 # get whats left
1447 my $query = "
1448 SELECT reserve_id, borrowernumber, reservedate
1449 FROM reserves
1450 WHERE biblionumber = ?
1451 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1452 ORDER BY priority ASC
1454 my $sth = $dbh->prepare($query);
1455 $sth->execute( $biblionumber );
1456 while ( my $line = $sth->fetchrow_hashref ) {
1457 push( @priority, $line );
1460 # To find the matching index
1461 my $i;
1462 my $key = -1; # to allow for 0 to be a valid result
1463 for ( $i = 0 ; $i < @priority ; $i++ ) {
1464 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1465 $key = $i; # save the index
1466 last;
1470 # if index exists in array then move it to new position
1471 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1472 my $new_rank = $rank -
1473 1; # $new_rank is what you want the new index to be in the array
1474 my $moving_item = splice( @priority, $key, 1 );
1475 splice( @priority, $new_rank, 0, $moving_item );
1478 # now fix the priority on those that are left....
1479 $query = "
1480 UPDATE reserves
1481 SET priority = ?
1482 WHERE reserve_id = ?
1484 $sth = $dbh->prepare($query);
1485 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1486 $sth->execute(
1487 $j + 1,
1488 $priority[$j]->{'reserve_id'}
1492 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1493 $sth->execute();
1495 unless ( $ignoreSetLowestRank ) {
1496 while ( my $res = $sth->fetchrow_hashref() ) {
1497 _FixPriority({
1498 reserve_id => $res->{'reserve_id'},
1499 rank => '999999',
1500 ignoreSetLowestRank => 1
1506 =head2 _Findgroupreserve
1508 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1510 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1511 first match found. If neither, then we look for non-holds-queue based holds.
1512 Lookahead is the number of days to look in advance.
1514 C<&_Findgroupreserve> returns :
1515 C<@results> is an array of references-to-hash whose keys are mostly
1516 fields from the reserves table of the Koha database, plus
1517 C<biblioitemnumber>.
1519 This routine with either return:
1520 1 - Item specific holds from the holds queue
1521 2 - Title level holds from the holds queue
1522 3 - All holds for this biblionumber
1524 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1526 =cut
1528 sub _Findgroupreserve {
1529 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1530 my $dbh = C4::Context->dbh;
1532 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1533 # check for exact targeted match
1534 my $item_level_target_query = qq{
1535 SELECT reserves.biblionumber AS biblionumber,
1536 reserves.borrowernumber AS borrowernumber,
1537 reserves.reservedate AS reservedate,
1538 reserves.branchcode AS branchcode,
1539 reserves.cancellationdate AS cancellationdate,
1540 reserves.found AS found,
1541 reserves.reservenotes AS reservenotes,
1542 reserves.priority AS priority,
1543 reserves.timestamp AS timestamp,
1544 biblioitems.biblioitemnumber AS biblioitemnumber,
1545 reserves.itemnumber AS itemnumber,
1546 reserves.reserve_id AS reserve_id,
1547 reserves.itemtype AS itemtype
1548 FROM reserves
1549 JOIN biblioitems USING (biblionumber)
1550 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1551 WHERE found IS NULL
1552 AND priority > 0
1553 AND item_level_request = 1
1554 AND itemnumber = ?
1555 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1556 AND suspend = 0
1557 ORDER BY priority
1559 my $sth = $dbh->prepare($item_level_target_query);
1560 $sth->execute($itemnumber, $lookahead||0);
1561 my @results;
1562 if ( my $data = $sth->fetchrow_hashref ) {
1563 push( @results, $data )
1564 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1566 return @results if @results;
1568 # check for title-level targeted match
1569 my $title_level_target_query = qq{
1570 SELECT reserves.biblionumber AS biblionumber,
1571 reserves.borrowernumber AS borrowernumber,
1572 reserves.reservedate AS reservedate,
1573 reserves.branchcode AS branchcode,
1574 reserves.cancellationdate AS cancellationdate,
1575 reserves.found AS found,
1576 reserves.reservenotes AS reservenotes,
1577 reserves.priority AS priority,
1578 reserves.timestamp AS timestamp,
1579 biblioitems.biblioitemnumber AS biblioitemnumber,
1580 reserves.itemnumber AS itemnumber,
1581 reserves.reserve_id AS reserve_id,
1582 reserves.itemtype AS itemtype
1583 FROM reserves
1584 JOIN biblioitems USING (biblionumber)
1585 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1586 WHERE found IS NULL
1587 AND priority > 0
1588 AND item_level_request = 0
1589 AND hold_fill_targets.itemnumber = ?
1590 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1591 AND suspend = 0
1592 ORDER BY priority
1594 $sth = $dbh->prepare($title_level_target_query);
1595 $sth->execute($itemnumber, $lookahead||0);
1596 @results = ();
1597 if ( my $data = $sth->fetchrow_hashref ) {
1598 push( @results, $data )
1599 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1601 return @results if @results;
1603 my $query = qq{
1604 SELECT reserves.biblionumber AS biblionumber,
1605 reserves.borrowernumber AS borrowernumber,
1606 reserves.reservedate AS reservedate,
1607 reserves.waitingdate AS waitingdate,
1608 reserves.branchcode AS branchcode,
1609 reserves.cancellationdate AS cancellationdate,
1610 reserves.found AS found,
1611 reserves.reservenotes AS reservenotes,
1612 reserves.priority AS priority,
1613 reserves.timestamp AS timestamp,
1614 reserves.itemnumber AS itemnumber,
1615 reserves.reserve_id AS reserve_id,
1616 reserves.itemtype AS itemtype
1617 FROM reserves
1618 WHERE reserves.biblionumber = ?
1619 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1620 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1621 AND suspend = 0
1622 ORDER BY priority
1624 $sth = $dbh->prepare($query);
1625 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1626 @results = ();
1627 while ( my $data = $sth->fetchrow_hashref ) {
1628 push( @results, $data )
1629 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1631 return @results;
1634 =head2 _koha_notify_reserve
1636 _koha_notify_reserve( $hold->reserve_id );
1638 Sends a notification to the patron that their hold has been filled (through
1639 ModReserveAffect, _not_ ModReserveFill)
1641 The letter code for this notice may be found using the following query:
1643 select distinct letter_code
1644 from message_transports
1645 inner join message_attributes using (message_attribute_id)
1646 where message_name = 'Hold_Filled'
1648 This will probably sipmly be 'HOLD', but because it is defined in the database,
1649 it is subject to addition or change.
1651 The following tables are availalbe witin the notice:
1653 branches
1654 borrowers
1655 biblio
1656 biblioitems
1657 reserves
1658 items
1660 =cut
1662 sub _koha_notify_reserve {
1663 my $reserve_id = shift;
1664 my $hold = Koha::Holds->find($reserve_id);
1665 my $borrowernumber = $hold->borrowernumber;
1667 my $patron = Koha::Patrons->find( $borrowernumber );
1669 # Try to get the borrower's email address
1670 my $to_address = $patron->notice_email_address;
1672 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1673 borrowernumber => $borrowernumber,
1674 message_name => 'Hold_Filled'
1675 } );
1677 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1679 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1681 my %letter_params = (
1682 module => 'reserves',
1683 branchcode => $hold->branchcode,
1684 lang => $patron->lang,
1685 tables => {
1686 'branches' => $library,
1687 'borrowers' => $patron->unblessed,
1688 'biblio' => $hold->biblionumber,
1689 'biblioitems' => $hold->biblionumber,
1690 'reserves' => $hold->unblessed,
1691 'items' => $hold->itemnumber,
1695 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.
1696 my $send_notification = sub {
1697 my ( $mtt, $letter_code ) = (@_);
1698 return unless defined $letter_code;
1699 $letter_params{letter_code} = $letter_code;
1700 $letter_params{message_transport_type} = $mtt;
1701 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1702 unless ($letter) {
1703 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1704 return;
1707 C4::Letters::EnqueueLetter( {
1708 letter => $letter,
1709 borrowernumber => $borrowernumber,
1710 from_address => $admin_email_address,
1711 message_transport_type => $mtt,
1712 } );
1715 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1716 next if (
1717 ( $mtt eq 'email' and not $to_address ) # No email address
1718 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1719 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1722 &$send_notification($mtt, $letter_code);
1723 $notification_sent++;
1725 #Making sure that a print notification is sent if no other transport types can be utilized.
1726 if (! $notification_sent) {
1727 &$send_notification('print', 'HOLD');
1732 =head2 _ShiftPriorityByDateAndPriority
1734 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1736 This increments the priority of all reserves after the one
1737 with either the lowest date after C<$reservedate>
1738 or the lowest priority after C<$priority>.
1740 It effectively makes room for a new reserve to be inserted with a certain
1741 priority, which is returned.
1743 This is most useful when the reservedate can be set by the user. It allows
1744 the new reserve to be placed before other reserves that have a later
1745 reservedate. Since priority also is set by the form in reserves/request.pl
1746 the sub accounts for that too.
1748 =cut
1750 sub _ShiftPriorityByDateAndPriority {
1751 my ( $biblio, $resdate, $new_priority ) = @_;
1753 my $dbh = C4::Context->dbh;
1754 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1755 my $sth = $dbh->prepare( $query );
1756 $sth->execute( $biblio, $resdate, $new_priority );
1757 my $min_priority = $sth->fetchrow;
1758 # if no such matches are found, $new_priority remains as original value
1759 $new_priority = $min_priority if ( $min_priority );
1761 # Shift the priority up by one; works in conjunction with the next SQL statement
1762 $query = "UPDATE reserves
1763 SET priority = priority+1
1764 WHERE biblionumber = ?
1765 AND borrowernumber = ?
1766 AND reservedate = ?
1767 AND found IS NULL";
1768 my $sth_update = $dbh->prepare( $query );
1770 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1771 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1772 $sth = $dbh->prepare( $query );
1773 $sth->execute( $new_priority, $biblio );
1774 while ( my $row = $sth->fetchrow_hashref ) {
1775 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1778 return $new_priority; # so the caller knows what priority they wind up receiving
1781 =head2 MoveReserve
1783 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1785 Use when checking out an item to handle reserves
1786 If $cancelreserve boolean is set to true, it will remove existing reserve
1788 =cut
1790 sub MoveReserve {
1791 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1793 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1794 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1795 return unless $res;
1797 my $biblionumber = $res->{biblionumber};
1799 if ($res->{borrowernumber} == $borrowernumber) {
1800 ModReserveFill($res);
1802 else {
1803 # warn "Reserved";
1804 # The item is reserved by someone else.
1805 # Find this item in the reserves
1807 my $borr_res = Koha::Holds->search({
1808 borrowernumber => $borrowernumber,
1809 biblionumber => $biblionumber,
1811 order_by => 'priority'
1812 })->next();
1814 if ( $borr_res ) {
1815 # The item is reserved by the current patron
1816 ModReserveFill($borr_res->unblessed);
1819 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1820 RevertWaitingStatus({ itemnumber => $itemnumber });
1822 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1823 my $hold = Koha::Holds->find( $res->{reserve_id} );
1824 $hold->cancel;
1829 =head2 MergeHolds
1831 MergeHolds($dbh,$to_biblio, $from_biblio);
1833 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1835 =cut
1837 sub MergeHolds {
1838 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1839 my $sth = $dbh->prepare(
1840 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1842 $sth->execute($from_biblio);
1843 if ( my $data = $sth->fetchrow_hashref() ) {
1845 # holds exist on old record, if not we don't need to do anything
1846 $sth = $dbh->prepare(
1847 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1848 $sth->execute( $to_biblio, $from_biblio );
1850 # Reorder by date
1851 # don't reorder those already waiting
1853 $sth = $dbh->prepare(
1854 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1856 my $upd_sth = $dbh->prepare(
1857 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1858 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1860 $sth->execute( $to_biblio, 'W', 'T' );
1861 my $priority = 1;
1862 while ( my $reserve = $sth->fetchrow_hashref() ) {
1863 $upd_sth->execute(
1864 $priority, $to_biblio,
1865 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1866 $reserve->{'itemnumber'}
1868 $priority++;
1873 =head2 RevertWaitingStatus
1875 RevertWaitingStatus({ itemnumber => $itemnumber });
1877 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1879 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1880 item level hold, even if it was only a bibliolevel hold to
1881 begin with. This is because we can no longer know if a hold
1882 was item-level or bib-level after a hold has been set to
1883 waiting status.
1885 =cut
1887 sub RevertWaitingStatus {
1888 my ( $params ) = @_;
1889 my $itemnumber = $params->{'itemnumber'};
1891 return unless ( $itemnumber );
1893 my $dbh = C4::Context->dbh;
1895 ## Get the waiting reserve we want to revert
1896 my $query = "
1897 SELECT * FROM reserves
1898 WHERE itemnumber = ?
1899 AND found IS NOT NULL
1901 my $sth = $dbh->prepare( $query );
1902 $sth->execute( $itemnumber );
1903 my $reserve = $sth->fetchrow_hashref();
1905 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1907 ## Increment the priority of all other non-waiting
1908 ## reserves for this bib record
1909 $query = "
1910 UPDATE reserves
1912 priority = priority + 1
1913 WHERE
1914 biblionumber = ?
1916 priority > 0
1918 $sth = $dbh->prepare( $query );
1919 $sth->execute( $reserve->{'biblionumber'} );
1921 ## Fix up the currently waiting reserve
1922 $query = "
1923 UPDATE reserves
1925 priority = 1,
1926 found = NULL,
1927 waitingdate = NULL
1928 WHERE
1929 reserve_id = ?
1931 $sth = $dbh->prepare( $query );
1932 $sth->execute( $reserve->{'reserve_id'} );
1934 unless ( $hold->item_level_hold ) {
1935 $hold->itemnumber(undef)->store;
1938 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1941 =head2 ReserveSlip
1943 ReserveSlip(
1945 branchcode => $branchcode,
1946 borrowernumber => $borrowernumber,
1947 biblionumber => $biblionumber,
1948 [ itemnumber => $itemnumber, ]
1949 [ barcode => $barcode, ]
1953 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1955 The letter code will be HOLD_SLIP, and the following tables are
1956 available within the slip:
1958 reserves
1959 branches
1960 borrowers
1961 biblio
1962 biblioitems
1963 items
1965 =cut
1967 sub ReserveSlip {
1968 my ($args) = @_;
1969 my $branchcode = $args->{branchcode};
1970 my $borrowernumber = $args->{borrowernumber};
1971 my $biblionumber = $args->{biblionumber};
1972 my $itemnumber = $args->{itemnumber};
1973 my $barcode = $args->{barcode};
1976 my $patron = Koha::Patrons->find($borrowernumber);
1978 my $hold;
1979 if ($itemnumber || $barcode ) {
1980 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
1982 $hold = Koha::Holds->search(
1984 biblionumber => $biblionumber,
1985 borrowernumber => $borrowernumber,
1986 itemnumber => $itemnumber
1988 )->next;
1990 else {
1991 $hold = Koha::Holds->search(
1993 biblionumber => $biblionumber,
1994 borrowernumber => $borrowernumber
1996 )->next;
1999 return unless $hold;
2000 my $reserve = $hold->unblessed;
2002 return C4::Letters::GetPreparedLetter (
2003 module => 'circulation',
2004 letter_code => 'HOLD_SLIP',
2005 branchcode => $branchcode,
2006 lang => $patron->lang,
2007 tables => {
2008 'reserves' => $reserve,
2009 'branches' => $reserve->{branchcode},
2010 'borrowers' => $reserve->{borrowernumber},
2011 'biblio' => $reserve->{biblionumber},
2012 'biblioitems' => $reserve->{biblionumber},
2013 'items' => $reserve->{itemnumber},
2018 =head2 GetReservesControlBranch
2020 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2022 Return the branchcode to be used to determine which reserves
2023 policy applies to a transaction.
2025 C<$item> is a hashref for an item. Only 'homebranch' is used.
2027 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2029 =cut
2031 sub GetReservesControlBranch {
2032 my ( $item, $borrower ) = @_;
2034 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2036 my $branchcode =
2037 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2038 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2039 : undef;
2041 return $branchcode;
2044 =head2 CalculatePriority
2046 my $p = CalculatePriority($biblionumber, $resdate);
2048 Calculate priority for a new reserve on biblionumber, placing it at
2049 the end of the line of all holds whose start date falls before
2050 the current system time and that are neither on the hold shelf
2051 or in transit.
2053 The reserve date parameter is optional; if it is supplied, the
2054 priority is based on the set of holds whose start date falls before
2055 the parameter value.
2057 After calculation of this priority, it is recommended to call
2058 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2059 AddReserves.
2061 =cut
2063 sub CalculatePriority {
2064 my ( $biblionumber, $resdate ) = @_;
2066 my $sql = q{
2067 SELECT COUNT(*) FROM reserves
2068 WHERE biblionumber = ?
2069 AND priority > 0
2070 AND (found IS NULL OR found = '')
2072 #skip found==W or found==T (waiting or transit holds)
2073 if( $resdate ) {
2074 $sql.= ' AND ( reservedate <= ? )';
2076 else {
2077 $sql.= ' AND ( reservedate < NOW() )';
2079 my $dbh = C4::Context->dbh();
2080 my @row = $dbh->selectrow_array(
2081 $sql,
2082 undef,
2083 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2086 return @row ? $row[0]+1 : 1;
2089 =head2 IsItemOnHoldAndFound
2091 my $bool = IsItemFoundHold( $itemnumber );
2093 Returns true if the item is currently on hold
2094 and that hold has a non-null found status ( W, T, etc. )
2096 =cut
2098 sub IsItemOnHoldAndFound {
2099 my ($itemnumber) = @_;
2101 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2103 my $found = $rs->count(
2105 itemnumber => $itemnumber,
2106 found => { '!=' => undef }
2110 return $found;
2113 =head2 GetMaxPatronHoldsForRecord
2115 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2117 For multiple holds on a given record for a given patron, the max
2118 number of record level holds that a patron can be placed is the highest
2119 value of the holds_per_record rule for each item if the record for that
2120 patron. This subroutine finds and returns the highest holds_per_record
2121 rule value for a given patron id and record id.
2123 =cut
2125 sub GetMaxPatronHoldsForRecord {
2126 my ( $borrowernumber, $biblionumber ) = @_;
2128 my $patron = Koha::Patrons->find($borrowernumber);
2129 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2131 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2133 my $categorycode = $patron->categorycode;
2134 my $branchcode;
2135 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2137 my $max = 0;
2138 foreach my $item (@items) {
2139 my $itemtype = $item->effective_itemtype();
2141 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2143 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2144 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2145 $max = $holds_per_record if $holds_per_record > $max;
2148 return $max;
2151 =head2 GetHoldRule
2153 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2155 Returns the matching hold related issuingrule fields for a given
2156 patron category, itemtype, and library.
2158 =cut
2160 sub GetHoldRule {
2161 my ( $categorycode, $itemtype, $branchcode ) = @_;
2163 my $dbh = C4::Context->dbh;
2165 my $sth = $dbh->prepare(
2167 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2168 FROM issuingrules
2169 WHERE (categorycode in (?,'*') )
2170 AND (itemtype IN (?,'*'))
2171 AND (branchcode IN (?,'*'))
2172 ORDER BY categorycode DESC,
2173 itemtype DESC,
2174 branchcode DESC
2178 $sth->execute( $categorycode, $itemtype, $branchcode );
2180 return $sth->fetchrow_hashref();
2183 =head1 AUTHOR
2185 Koha Development Team <http://koha-community.org/>
2187 =cut