Bug 25534: (QA follow-up) Add sample notice
[koha.git] / C4 / Reserves.pm
blobeb1a6f88f783eb577ead2dfbf7a8187b4fcf12aa
1 package C4::Reserves;
3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
6 # 2011 Catalyst IT
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24 use Modern::Perl;
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Items;
31 use C4::Letters;
32 use C4::Log;
33 use C4::Members::Messaging;
34 use C4::Members;
35 use Koha::Account::Lines;
36 use Koha::Biblios;
37 use Koha::Calendar;
38 use Koha::CirculationRules;
39 use Koha::Database;
40 use Koha::DateUtils;
41 use Koha::Hold;
42 use Koha::Holds;
43 use Koha::ItemTypes;
44 use Koha::Items;
45 use Koha::Libraries;
46 use Koha::Old::Hold;
47 use Koha::Patrons;
48 use Koha::Plugins;
50 use Carp;
51 use Data::Dumper;
52 use List::MoreUtils qw( firstidx any );
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
56 =head1 NAME
58 C4::Reserves - Koha functions for dealing with reservation.
60 =head1 SYNOPSIS
62 use C4::Reserves;
64 =head1 DESCRIPTION
66 This modules provides somes functions to deal with reservations.
68 Reserves are stored in reserves table.
69 The following columns contains important values :
70 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
71 =0 : then the reserve is being dealed
72 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
73 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
74 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
75 F(inished) : the reserve has been completed, and is done
76 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
95 =head1 FUNCTIONS
97 =cut
99 BEGIN {
100 require Exporter;
101 @ISA = qw(Exporter);
102 @EXPORT = qw(
103 &AddReserve
105 &GetReserveStatus
107 &GetOtherReserves
109 &ModReserveFill
110 &ModReserveAffect
111 &ModReserve
112 &ModReserveStatus
113 &ModReserveCancelAll
114 &ModReserveMinusPriority
115 &MoveReserve
117 &CheckReserves
118 &CanBookBeReserved
119 &CanItemBeReserved
120 &CanReserveBeCanceledFromOpac
121 &CancelExpiredReserves
123 &AutoUnsuspendReserves
125 &IsAvailableForItemLevelRequest
126 ItemsAnyAvailableAndNotRestricted
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(
148 branchcode => $branchcode,
149 borrowernumber => $borrowernumber,
150 biblionumber => $biblionumber,
151 priority => $priority,
152 reservation_date => $reservation_date,
153 expiration_date => $expiration_date,
154 notes => $notes,
155 title => $title,
156 itemnumber => $itemnumber,
157 found => $found,
158 itemtype => $itemtype,
162 Adds reserve and generates HOLDPLACED message.
164 The following tables are available witin the HOLDPLACED message:
166 branches
167 borrowers
168 biblio
169 biblioitems
170 items
171 reserves
173 =cut
175 sub AddReserve {
176 my ($params) = @_;
177 my $branch = $params->{branchcode};
178 my $borrowernumber = $params->{borrowernumber};
179 my $biblionumber = $params->{biblionumber};
180 my $priority = $params->{priority};
181 my $resdate = $params->{reservation_date};
182 my $expdate = $params->{expiration_date};
183 my $notes = $params->{notes};
184 my $title = $params->{title};
185 my $checkitem = $params->{itemnumber};
186 my $found = $params->{found};
187 my $itemtype = $params->{itemtype};
189 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
190 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
192 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
194 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
195 # of the document, we force the value $priority and $found .
196 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
197 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
199 if (
200 # If item is already checked out, it cannot be set waiting
201 !$item->onloan
203 # The item can't be waiting if it needs a transfer
204 && $item->holdingbranch eq $branch
206 # Similarly, if in transit it can't be waiting
207 && !$item->get_transfer
209 # If we can't hold damaged items, and it is damaged, it can't be waiting
210 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
212 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
213 && !$item->current_holds->count )
215 $priority = 0;
216 $found = 'W';
220 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
222 # Make room in reserves for this before those of a later reserve date
223 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
226 my $waitingdate;
228 # If the reserv had the waiting status, we had the value of the resdate
229 if ( $found && $found eq 'W' ) {
230 $waitingdate = $resdate;
233 # Don't add itemtype limit if specific item is selected
234 $itemtype = undef if $checkitem;
236 # updates take place here
237 my $hold = Koha::Hold->new(
239 borrowernumber => $borrowernumber,
240 biblionumber => $biblionumber,
241 reservedate => $resdate,
242 branchcode => $branch,
243 priority => $priority,
244 reservenotes => $notes,
245 itemnumber => $checkitem,
246 found => $found,
247 waitingdate => $waitingdate,
248 expirationdate => $expdate,
249 itemtype => $itemtype,
250 item_level_hold => $checkitem ? 1 : 0,
252 )->store();
253 $hold->set_waiting() if $found && $found eq 'W';
255 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
256 if C4::Context->preference('HoldsLog');
258 my $reserve_id = $hold->id();
260 # add a reserve fee if needed
261 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
262 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
263 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
266 _FixPriority({ biblionumber => $biblionumber});
268 # Send e-mail to librarian if syspref is active
269 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
270 my $patron = Koha::Patrons->find( $borrowernumber );
271 my $library = $patron->library;
272 if ( my $letter = C4::Letters::GetPreparedLetter (
273 module => 'reserves',
274 letter_code => 'HOLDPLACED',
275 branchcode => $branch,
276 lang => $patron->lang,
277 tables => {
278 'branches' => $library->unblessed,
279 'borrowers' => $patron->unblessed,
280 'biblio' => $biblionumber,
281 'biblioitems' => $biblionumber,
282 'items' => $checkitem,
283 'reserves' => $hold->unblessed,
285 ) ) {
287 my $branch_email_address = $library->inbound_email_address;
289 C4::Letters::EnqueueLetter(
291 letter => $letter,
292 borrowernumber => $borrowernumber,
293 message_transport_type => 'email',
294 to_address => $branch_email_address,
300 Koha::Plugins->call('after_hold_create', $hold);
302 return $reserve_id;
305 =head2 CanBookBeReserved
307 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
308 if ($canReserve eq 'OK') { #We can reserve this Item! }
310 $params are passed directly through to CanItemBeReserved
312 See CanItemBeReserved() for possible return values.
314 =cut
316 sub CanBookBeReserved{
317 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
319 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
320 #get items linked via host records
321 my @hostitems = get_hostitemnumbers_of($biblionumber);
322 if (@hostitems){
323 push (@itemnumbers, @hostitems);
326 my $canReserve = { status => '' };
327 foreach my $itemnumber (@itemnumbers) {
328 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
329 return { status => 'OK' } if $canReserve->{status} eq 'OK';
331 return $canReserve;
334 =head2 CanItemBeReserved
336 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
337 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
339 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
340 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
341 current checkout against the high holds threshold
343 @RETURNS { status => OK }, if the Item can be reserved.
344 { status => ageRestricted }, if the Item is age restricted for this borrower.
345 { status => damaged }, if the Item is damaged.
346 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
347 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
348 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
349 { status => notReservable }, if holds on this item are not allowed
350 { status => libraryNotFound }, if given branchcode is not an existing library
351 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
352 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
353 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
355 =cut
357 sub CanItemBeReserved {
358 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
360 my $dbh = C4::Context->dbh;
361 my $ruleitemtype; # itemtype of the matching issuing rule
362 my $allowedreserves = 0; # Total number of holds allowed across all records
363 my $holds_per_record = 1; # Total number of holds allowed for this one given record
364 my $holds_per_day; # Default to unlimited
366 # we retrieve borrowers and items informations #
367 # item->{itype} will come for biblioitems if necessery
368 my $item = Koha::Items->find($itemnumber);
369 my $biblio = $item->biblio;
370 my $patron = Koha::Patrons->find( $borrowernumber );
371 my $borrower = $patron->unblessed;
373 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
374 return { status =>'damaged' }
375 if ( $item->damaged
376 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
378 # Check for the age restriction
379 my ( $ageRestriction, $daysToAgeRestriction ) =
380 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
381 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
383 # Check that the patron doesn't have an item level hold on this item already
384 return { status =>'itemAlreadyOnHold' }
385 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
387 my $controlbranch = C4::Context->preference('ReservesControlBranch');
389 my $querycount = q{
390 SELECT count(*) AS count
391 FROM reserves
392 LEFT JOIN items USING (itemnumber)
393 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
394 LEFT JOIN borrowers USING (borrowernumber)
395 WHERE borrowernumber = ?
398 my $branchcode = "";
399 my $branchfield = "reserves.branchcode";
401 if ( $controlbranch eq "ItemHomeLibrary" ) {
402 $branchfield = "items.homebranch";
403 $branchcode = $item->homebranch;
405 elsif ( $controlbranch eq "PatronLibrary" ) {
406 $branchfield = "borrowers.branchcode";
407 $branchcode = $borrower->{branchcode};
410 # we retrieve rights
411 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
412 $ruleitemtype = $rights->{itemtype};
413 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
414 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
415 $holds_per_day = $rights->{holds_per_day};
417 else {
418 $ruleitemtype = undef;
421 my $search_params = {
422 borrowernumber => $borrowernumber,
423 biblionumber => $item->biblionumber,
425 $search_params->{found} = undef if $params->{ignore_found_holds};
427 my $holds = Koha::Holds->search($search_params);
428 if ( defined $holds_per_record && $holds_per_record ne ''
429 && $holds->count() >= $holds_per_record ) {
430 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
433 my $today_holds = Koha::Holds->search({
434 borrowernumber => $borrowernumber,
435 reservedate => dt_from_string->date
438 if ( defined $holds_per_day && $holds_per_day ne ''
439 && $today_holds->count() >= $holds_per_day )
441 return { status => 'tooManyReservesToday', limit => $holds_per_day };
444 # we retrieve count
446 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
448 # If using item-level itypes, fall back to the record
449 # level itemtype if the hold has no associated item
450 $querycount .=
451 C4::Context->preference('item-level_itypes')
452 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
453 : " AND biblioitems.itemtype = ?"
454 if defined $ruleitemtype;
456 my $sthcount = $dbh->prepare($querycount);
458 if ( defined $ruleitemtype ) {
459 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
461 else {
462 $sthcount->execute( $borrowernumber, $branchcode );
465 my $reservecount = "0";
466 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
467 $reservecount = $rowcount->{count};
470 # we check if it's ok or not
471 if ( defined $allowedreserves && $allowedreserves ne ''
472 && $reservecount >= $allowedreserves ) {
473 return { status => 'tooManyReserves', limit => $allowedreserves };
476 # Now we need to check hold limits by patron category
477 my $rule = Koha::CirculationRules->get_effective_rule(
479 categorycode => $borrower->{categorycode},
480 branchcode => $branchcode,
481 rule_name => 'max_holds',
484 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
485 my $total_holds_count = Koha::Holds->search(
487 borrowernumber => $borrower->{borrowernumber}
489 )->count();
491 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
494 my $reserves_control_branch =
495 GetReservesControlBranch( $item->unblessed(), $borrower );
496 my $branchitemrule =
497 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
499 if ( $branchitemrule->{holdallowed} == 0 ) {
500 return { status => 'notReservable' };
503 if ( $branchitemrule->{holdallowed} == 1
504 && $borrower->{branchcode} ne $item->homebranch )
506 return { status => 'cannotReserveFromOtherBranches' };
509 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
510 if ( $branchitemrule->{holdallowed} == 3) {
511 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
512 return { status => 'branchNotInHoldGroup' };
516 # If reservecount is ok, we check item branch if IndependentBranches is ON
517 # and canreservefromotherbranches is OFF
518 if ( C4::Context->preference('IndependentBranches')
519 and !C4::Context->preference('canreservefromotherbranches') )
521 if ( $item->homebranch ne $borrower->{branchcode} ) {
522 return { status => 'cannotReserveFromOtherBranches' };
526 if ($pickup_branchcode) {
527 my $destination = Koha::Libraries->find({
528 branchcode => $pickup_branchcode,
531 unless ($destination) {
532 return { status => 'libraryNotFound' };
534 unless ($destination->pickup_location) {
535 return { status => 'libraryNotPickupLocation' };
537 unless ($item->can_be_transferred({ to => $destination })) {
538 return { status => 'cannotBeTransferred' };
540 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
541 return { status => 'pickupNotInHoldGroup' };
543 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
544 return { status => 'pickupNotInHoldGroup' };
548 return { status => 'OK' };
551 =head2 CanReserveBeCanceledFromOpac
553 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
555 returns 1 if reserve can be cancelled by user from OPAC.
556 First check if reserve belongs to user, next checks if reserve is not in
557 transfer or waiting status
559 =cut
561 sub CanReserveBeCanceledFromOpac {
562 my ($reserve_id, $borrowernumber) = @_;
564 return unless $reserve_id and $borrowernumber;
565 my $reserve = Koha::Holds->find($reserve_id);
567 return 0 unless $reserve->borrowernumber == $borrowernumber;
568 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
570 return 1;
574 =head2 GetOtherReserves
576 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
578 Check queued list of this document and check if this document must be transferred
580 =cut
582 sub GetOtherReserves {
583 my ($itemnumber) = @_;
584 my $messages;
585 my $nextreservinfo;
586 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
587 if ($checkreserves) {
588 my $item = Koha::Items->find($itemnumber);
589 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
590 $messages->{'transfert'} = $checkreserves->{'branchcode'};
591 #minus priorities of others reservs
592 ModReserveMinusPriority(
593 $itemnumber,
594 $checkreserves->{'reserve_id'},
597 #launch the subroutine dotransfer
598 C4::Items::ModItemTransfer(
599 $itemnumber,
600 $item->holdingbranch,
601 $checkreserves->{'branchcode'},
602 'Reserve'
607 #step 2b : case of a reservation on the same branch, set the waiting status
608 else {
609 $messages->{'waiting'} = 1;
610 ModReserveMinusPriority(
611 $itemnumber,
612 $checkreserves->{'reserve_id'},
614 ModReserveStatus($itemnumber,'W');
617 $nextreservinfo = $checkreserves;
620 return ( $messages, $nextreservinfo );
623 =head2 ChargeReserveFee
625 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
627 Charge the fee for a reserve (if $fee > 0)
629 =cut
631 sub ChargeReserveFee {
632 my ( $borrowernumber, $fee, $title ) = @_;
633 return if !$fee || $fee == 0; # the last test is needed to include 0.00
634 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
636 amount => $fee,
637 description => $title,
638 note => undef,
639 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
640 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
641 interface => C4::Context->interface,
642 invoice_type => undef,
643 type => 'RESERVE',
644 item_id => undef
649 =head2 GetReserveFee
651 $fee = GetReserveFee( $borrowernumber, $biblionumber );
653 Calculate the fee for a reserve (if applicable).
655 =cut
657 sub GetReserveFee {
658 my ( $borrowernumber, $biblionumber ) = @_;
659 my $borquery = qq{
660 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
662 my $issue_qry = qq{
663 SELECT COUNT(*) FROM items
664 LEFT JOIN issues USING (itemnumber)
665 WHERE items.biblionumber=? AND issues.issue_id IS NULL
667 my $holds_qry = qq{
668 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
671 my $dbh = C4::Context->dbh;
672 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
673 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
674 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
675 # This is a reconstruction of the old code:
676 # Compare number of items with items issued, and optionally check holds
677 # If not all items are issued and there are no holds: charge no fee
678 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
679 my ( $notissued, $reserved );
680 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
681 ( $biblionumber ) );
682 if( $notissued ) {
683 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
684 ( $biblionumber, $borrowernumber ) );
685 $fee = 0 if $reserved == 0;
688 return $fee;
691 =head2 GetReserveStatus
693 $reservestatus = GetReserveStatus($itemnumber);
695 Takes an itemnumber and returns the status of the reserve placed on it.
696 If several reserves exist, the reserve with the lower priority is given.
698 =cut
700 ## FIXME: I don't think this does what it thinks it does.
701 ## It only ever checks the first reserve result, even though
702 ## multiple reserves for that bib can have the itemnumber set
703 ## the sub is only used once in the codebase.
704 sub GetReserveStatus {
705 my ($itemnumber) = @_;
707 my $dbh = C4::Context->dbh;
709 my ($sth, $found, $priority);
710 if ( $itemnumber ) {
711 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
712 $sth->execute($itemnumber);
713 ($found, $priority) = $sth->fetchrow_array;
716 if(defined $found) {
717 return 'Waiting' if $found eq 'W' and $priority == 0;
718 return 'Finished' if $found eq 'F';
721 return 'Reserved' if defined $priority && $priority > 0;
723 return ''; # empty string here will remove need for checking undef, or less log lines
726 =head2 CheckReserves
728 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
729 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
730 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
732 Find a book in the reserves.
734 C<$itemnumber> is the book's item number.
735 C<$lookahead> is the number of days to look in advance for future reserves.
737 As I understand it, C<&CheckReserves> looks for the given item in the
738 reserves. If it is found, that's a match, and C<$status> is set to
739 C<Waiting>.
741 Otherwise, it finds the most important item in the reserves with the
742 same biblio number as this book (I'm not clear on this) and returns it
743 with C<$status> set to C<Reserved>.
745 C<&CheckReserves> returns a two-element list:
747 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
749 C<$reserve> is the reserve item that matched. It is a
750 reference-to-hash whose keys are mostly the fields of the reserves
751 table in the Koha database.
753 =cut
755 sub CheckReserves {
756 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
757 my $dbh = C4::Context->dbh;
758 my $sth;
759 my $select;
760 if (C4::Context->preference('item-level_itypes')){
761 $select = "
762 SELECT items.biblionumber,
763 items.biblioitemnumber,
764 itemtypes.notforloan,
765 items.notforloan AS itemnotforloan,
766 items.itemnumber,
767 items.damaged,
768 items.homebranch,
769 items.holdingbranch
770 FROM items
771 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
772 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
775 else {
776 $select = "
777 SELECT items.biblionumber,
778 items.biblioitemnumber,
779 itemtypes.notforloan,
780 items.notforloan AS itemnotforloan,
781 items.itemnumber,
782 items.damaged,
783 items.homebranch,
784 items.holdingbranch
785 FROM items
786 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
787 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
791 if ($item) {
792 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
793 $sth->execute($item);
795 else {
796 $sth = $dbh->prepare("$select WHERE barcode = ?");
797 $sth->execute($barcode);
799 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
800 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
801 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
803 return unless $itemnumber; # bail if we got nothing.
804 # if item is not for loan it cannot be reserved either.....
805 # except where items.notforloan < 0 : This indicates the item is holdable.
807 my @SkipHoldTrapOnNotForLoanValue = split( '|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
808 return if @SkipHoldTrapOnNotForLoanValue && grep( $notforloan_per_item, @SkipHoldTrapOnNotForLoanValue );
810 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
811 return if $dont_trap or $notforloan_per_itemtype;
813 # Find this item in the reserves
814 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
816 # $priority and $highest are used to find the most important item
817 # in the list returned by &_Findgroupreserve. (The lower $priority,
818 # the more important the item.)
819 # $highest is the most important item we've seen so far.
820 my $highest;
822 if (scalar @reserves) {
823 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
824 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
825 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
827 my $priority = 10000000;
828 foreach my $res (@reserves) {
829 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
830 if ($res->{'found'} eq 'W') {
831 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
832 } else {
833 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
835 } else {
836 my $patron;
837 my $item;
838 my $local_hold_match;
840 if ($LocalHoldsPriority) {
841 $patron = Koha::Patrons->find( $res->{borrowernumber} );
842 $item = Koha::Items->find($itemnumber);
844 my $local_holds_priority_item_branchcode =
845 $item->$LocalHoldsPriorityItemControl;
846 my $local_holds_priority_patron_branchcode =
847 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
848 ? $res->{branchcode}
849 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
850 ? $patron->branchcode
851 : undef;
852 $local_hold_match =
853 $local_holds_priority_item_branchcode eq
854 $local_holds_priority_patron_branchcode;
857 # See if this item is more important than what we've got so far
858 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
859 $item ||= Koha::Items->find($itemnumber);
860 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
861 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
862 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
863 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
864 next if ($branchitemrule->{'holdallowed'} == 0);
865 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
866 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
867 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
868 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
869 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
870 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
871 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
872 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
873 $priority = $res->{'priority'};
874 $highest = $res;
875 last if $local_hold_match;
881 # If we get this far, then no exact match was found.
882 # We return the most important (i.e. next) reservation.
883 if ($highest) {
884 $highest->{'itemnumber'} = $item;
885 return ( "Reserved", $highest, \@reserves );
888 return ( '' );
891 =head2 CancelExpiredReserves
893 CancelExpiredReserves();
895 Cancels all reserves with an expiration date from before today.
897 =cut
899 sub CancelExpiredReserves {
900 my $today = dt_from_string();
901 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
902 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
904 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
905 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
906 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
908 # FIXME To move to Koha::Holds->search_expired (?)
909 my $holds = Koha::Holds->search( $params );
911 while ( my $hold = $holds->next ) {
912 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
914 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
916 my $cancel_params = {};
917 if ( $hold->found eq 'W' ) {
918 $cancel_params->{charge_cancel_fee} = 1;
920 $hold->cancel( $cancel_params );
924 =head2 AutoUnsuspendReserves
926 AutoUnsuspendReserves();
928 Unsuspends all suspended reserves with a suspend_until date from before today.
930 =cut
932 sub AutoUnsuspendReserves {
933 my $today = dt_from_string();
935 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
937 map { $_->resume() } @holds;
940 =head2 ModReserve
942 ModReserve({ rank => $rank,
943 reserve_id => $reserve_id,
944 branchcode => $branchcode
945 [, itemnumber => $itemnumber ]
946 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
949 Change a hold request's priority or cancel it.
951 C<$rank> specifies the effect of the change. If C<$rank>
952 is 'W' or 'n', nothing happens. This corresponds to leaving a
953 request alone when changing its priority in the holds queue
954 for a bib.
956 If C<$rank> is 'del', the hold request is cancelled.
958 If C<$rank> is an integer greater than zero, the priority of
959 the request is set to that value. Since priority != 0 means
960 that the item is not waiting on the hold shelf, setting the
961 priority to a non-zero value also sets the request's found
962 status and waiting date to NULL.
964 The optional C<$itemnumber> parameter is used only when
965 C<$rank> is a non-zero integer; if supplied, the itemnumber
966 of the hold request is set accordingly; if omitted, the itemnumber
967 is cleared.
969 B<FIXME:> Note that the forgoing can have the effect of causing
970 item-level hold requests to turn into title-level requests. This
971 will be fixed once reserves has separate columns for requested
972 itemnumber and supplying itemnumber.
974 =cut
976 sub ModReserve {
977 my ( $params ) = @_;
979 my $rank = $params->{'rank'};
980 my $reserve_id = $params->{'reserve_id'};
981 my $branchcode = $params->{'branchcode'};
982 my $itemnumber = $params->{'itemnumber'};
983 my $suspend_until = $params->{'suspend_until'};
984 my $borrowernumber = $params->{'borrowernumber'};
985 my $biblionumber = $params->{'biblionumber'};
986 my $cancellation_reason = $params->{'cancellation_reason'};
988 return if $rank eq "W";
989 return if $rank eq "n";
991 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
993 my $hold;
994 unless ( $reserve_id ) {
995 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
996 return unless $holds->count; # FIXME Should raise an exception
997 $hold = $holds->next;
998 $reserve_id = $hold->reserve_id;
1001 $hold ||= Koha::Holds->find($reserve_id);
1003 if ( $rank eq "del" ) {
1004 $hold->cancel({ cancellation_reason => $cancellation_reason });
1006 elsif ($rank =~ /^\d+/ and $rank > 0) {
1007 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1008 if C4::Context->preference('HoldsLog');
1010 my $properties = {
1011 priority => $rank,
1012 branchcode => $branchcode,
1013 itemnumber => $itemnumber,
1014 found => undef,
1015 waitingdate => undef
1017 if (exists $params->{reservedate}) {
1018 $properties->{reservedate} = $params->{reservedate} || undef;
1020 if (exists $params->{expirationdate}) {
1021 $properties->{expirationdate} = $params->{expirationdate} || undef;
1024 $hold->set($properties)->store();
1026 if ( defined( $suspend_until ) ) {
1027 if ( $suspend_until ) {
1028 $suspend_until = eval { dt_from_string( $suspend_until ) };
1029 $hold->suspend_hold( $suspend_until );
1030 } else {
1031 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1032 # If the hold is not suspended, this does nothing.
1033 $hold->set( { suspend_until => undef } )->store();
1037 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1041 =head2 ModReserveFill
1043 &ModReserveFill($reserve);
1045 Fill a reserve. If I understand this correctly, this means that the
1046 reserved book has been found and given to the patron who reserved it.
1048 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1049 whose keys are fields from the reserves table in the Koha database.
1051 =cut
1053 sub ModReserveFill {
1054 my ($res) = @_;
1055 my $reserve_id = $res->{'reserve_id'};
1057 my $hold = Koha::Holds->find($reserve_id);
1058 # get the priority on this record....
1059 my $priority = $hold->priority;
1061 # update the hold statuses, no need to store it though, we will be deleting it anyway
1062 $hold->set(
1064 found => 'F',
1065 priority => 0,
1069 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1070 if C4::Context->preference('HoldsLog');
1072 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1073 Koha::Old::Hold->new( $hold->unblessed() )->store();
1075 $hold->delete();
1077 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1078 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1079 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1082 # now fix the priority on the others (if the priority wasn't
1083 # already sorted!)....
1084 unless ( $priority == 0 ) {
1085 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1089 =head2 ModReserveStatus
1091 &ModReserveStatus($itemnumber, $newstatus);
1093 Update the reserve status for the active (priority=0) reserve.
1095 $itemnumber is the itemnumber the reserve is on
1097 $newstatus is the new status.
1099 =cut
1101 sub ModReserveStatus {
1103 #first : check if we have a reservation for this item .
1104 my ($itemnumber, $newstatus) = @_;
1105 my $dbh = C4::Context->dbh;
1107 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1108 my $sth_set = $dbh->prepare($query);
1109 $sth_set->execute( $newstatus, $itemnumber );
1111 my $item = Koha::Items->find($itemnumber);
1112 if ( $item->location && $item->location eq 'CART'
1113 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1114 && $newstatus ) {
1115 CartToShelf( $itemnumber );
1119 =head2 ModReserveAffect
1121 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1123 This function affect an item and a status for a given reserve, either fetched directly
1124 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1125 is given, only first reserve returned is affected, which is ok for anything but
1126 multi-item holds.
1128 if $transferToDo is not set, then the status is set to "Waiting" as well.
1129 otherwise, a transfer is on the way, and the end of the transfer will
1130 take care of the waiting status
1132 =cut
1134 sub ModReserveAffect {
1135 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1136 my $dbh = C4::Context->dbh;
1138 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1139 # attached to $itemnumber
1140 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1141 $sth->execute($itemnumber);
1142 my ($biblionumber) = $sth->fetchrow;
1144 # get request - need to find out if item is already
1145 # waiting in order to not send duplicate hold filled notifications
1147 my $hold;
1148 # Find hold by id if we have it
1149 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1150 # Find item level hold for this item if there is one
1151 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1152 # Find record level hold if there is no item level hold
1153 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1155 return unless $hold;
1157 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1159 $hold->itemnumber($itemnumber);
1160 $hold->set_waiting($transferToDo);
1162 if( !$transferToDo ){
1163 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1164 my $transfers = Koha::Item::Transfers->search({
1165 itemnumber => $itemnumber,
1166 datearrived => undef
1168 while( my $transfer = $transfers->next ){
1169 $transfer->datearrived( dt_from_string() )->store;
1174 _FixPriority( { biblionumber => $biblionumber } );
1175 my $item = Koha::Items->find($itemnumber);
1176 if ( $item->location && $item->location eq 'CART'
1177 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1178 CartToShelf( $itemnumber );
1181 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1182 if C4::Context->preference('HoldsLog');
1184 return;
1187 =head2 ModReserveCancelAll
1189 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1191 function to cancel reserv,check other reserves, and transfer document if it's necessary
1193 =cut
1195 sub ModReserveCancelAll {
1196 my $messages;
1197 my $nextreservinfo;
1198 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1200 #step 1 : cancel the reservation
1201 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1202 return unless $holds->count;
1203 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1205 #step 2 launch the subroutine of the others reserves
1206 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1208 return ( $messages, $nextreservinfo->{borrowernumber} );
1211 =head2 ModReserveMinusPriority
1213 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1215 Reduce the values of queued list
1217 =cut
1219 sub ModReserveMinusPriority {
1220 my ( $itemnumber, $reserve_id ) = @_;
1222 #first step update the value of the first person on reserv
1223 my $dbh = C4::Context->dbh;
1224 my $query = "
1225 UPDATE reserves
1226 SET priority = 0 , itemnumber = ?
1227 WHERE reserve_id = ?
1229 my $sth_upd = $dbh->prepare($query);
1230 $sth_upd->execute( $itemnumber, $reserve_id );
1231 # second step update all others reserves
1232 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1235 =head2 IsAvailableForItemLevelRequest
1237 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1239 Checks whether a given item record is available for an
1240 item-level hold request. An item is available if
1242 * it is not lost AND
1243 * it is not damaged AND
1244 * it is not withdrawn AND
1245 * a waiting or in transit reserve is placed on
1246 * does not have a not for loan value > 0
1248 Need to check the issuingrules onshelfholds column,
1249 if this is set items on the shelf can be placed on hold
1251 Note that IsAvailableForItemLevelRequest() does not
1252 check if the staff operator is authorized to place
1253 a request on the item - in particular,
1254 this routine does not check IndependentBranches
1255 and canreservefromotherbranches.
1257 Note also that this subroutine does not checks smart
1258 rules limits for item by reservesallowed/holds_per_record
1259 values, this complemented in calling code with calls and
1260 checks with CanItemBeReserved or CanBookBeReserved.
1262 =cut
1264 sub IsAvailableForItemLevelRequest {
1265 my $item = shift;
1266 my $patron = shift;
1267 my $pickup_branchcode = shift;
1268 # items_any_available is precalculated status passed from request.pl when set of items
1269 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1270 my $items_any_available = shift;
1272 my $dbh = C4::Context->dbh;
1273 # must check the notforloan setting of the itemtype
1274 # FIXME - a lot of places in the code do this
1275 # or something similar - need to be
1276 # consolidated
1277 my $itemtype = $item->effective_itemtype;
1278 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1280 return 0 if
1281 $notforloan_per_itemtype ||
1282 $item->itemlost ||
1283 $item->notforloan > 0 ||
1284 $item->withdrawn ||
1285 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1287 if ($pickup_branchcode) {
1288 my $destination = Koha::Libraries->find($pickup_branchcode);
1289 return 0 unless $destination;
1290 return 0 unless $destination->pickup_location;
1291 return 0 unless $item->can_be_transferred( { to => $destination } );
1292 my $reserves_control_branch =
1293 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1294 my $branchitemrule =
1295 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1296 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1297 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1300 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1302 if ( $on_shelf_holds == 1 ) {
1303 return 1;
1304 } elsif ( $on_shelf_holds == 2 ) {
1306 # if we have this param predefined from outer caller sub, we just need
1307 # to return it, so we saving from having loop inside other loop:
1308 return $items_any_available ? 0 : 1
1309 if defined $items_any_available;
1311 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1312 return $any_available ? 0 : 1;
1313 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1314 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1318 =head2 ItemsAnyAvailableAndNotRestricted
1320 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1322 This function checks all items for specified biblionumber (numeric) against patron (object)
1323 and returns true (1) if at least one item available for loan/check out/present/not held
1324 and also checks other parameters logic which not restricts item for hold at all (for ex.
1325 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1327 =cut
1329 sub ItemsAnyAvailableAndNotRestricted {
1330 my $param = shift;
1332 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1334 foreach my $i (@items) {
1335 my $reserves_control_branch =
1336 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1337 my $branchitemrule =
1338 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1339 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1341 # we can return (end the loop) when first one found:
1342 return 1
1343 unless $i->itemlost
1344 || $i->notforloan > 0
1345 || $i->withdrawn
1346 || $i->onloan
1347 || IsItemOnHoldAndFound( $i->id )
1348 || ( $i->damaged
1349 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1350 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1351 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1352 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1353 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1356 return 0;
1359 =head2 AlterPriority
1361 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1363 This function changes a reserve's priority up, down, to the top, or to the bottom.
1364 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1366 =cut
1368 sub AlterPriority {
1369 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1371 my $hold = Koha::Holds->find( $reserve_id );
1372 return unless $hold;
1374 if ( $hold->cancellationdate ) {
1375 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1376 return;
1379 if ( $where eq 'up' ) {
1380 return unless $prev_priority;
1381 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1382 } elsif ( $where eq 'down' ) {
1383 return unless $next_priority;
1384 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1385 } elsif ( $where eq 'top' ) {
1386 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1387 } elsif ( $where eq 'bottom' ) {
1388 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1391 # FIXME Should return the new priority
1394 =head2 ToggleLowestPriority
1396 ToggleLowestPriority( $borrowernumber, $biblionumber );
1398 This function sets the lowestPriority field to true if is false, and false if it is true.
1400 =cut
1402 sub ToggleLowestPriority {
1403 my ( $reserve_id ) = @_;
1405 my $dbh = C4::Context->dbh;
1407 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1408 $sth->execute( $reserve_id );
1410 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1413 =head2 ToggleSuspend
1415 ToggleSuspend( $reserve_id );
1417 This function sets the suspend field to true if is false, and false if it is true.
1418 If the reserve is currently suspended with a suspend_until date, that date will
1419 be cleared when it is unsuspended.
1421 =cut
1423 sub ToggleSuspend {
1424 my ( $reserve_id, $suspend_until ) = @_;
1426 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1428 my $hold = Koha::Holds->find( $reserve_id );
1430 if ( $hold->is_suspended ) {
1431 $hold->resume()
1432 } else {
1433 $hold->suspend_hold( $suspend_until );
1437 =head2 SuspendAll
1439 SuspendAll(
1440 borrowernumber => $borrowernumber,
1441 [ biblionumber => $biblionumber, ]
1442 [ suspend_until => $suspend_until, ]
1443 [ suspend => $suspend ]
1446 This function accepts a set of hash keys as its parameters.
1447 It requires either borrowernumber or biblionumber, or both.
1449 suspend_until is wholly optional.
1451 =cut
1453 sub SuspendAll {
1454 my %params = @_;
1456 my $borrowernumber = $params{'borrowernumber'} || undef;
1457 my $biblionumber = $params{'biblionumber'} || undef;
1458 my $suspend_until = $params{'suspend_until'} || undef;
1459 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1461 $suspend_until = eval { dt_from_string($suspend_until) }
1462 if ( defined($suspend_until) );
1464 return unless ( $borrowernumber || $biblionumber );
1466 my $params;
1467 $params->{found} = undef;
1468 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1469 $params->{biblionumber} = $biblionumber if $biblionumber;
1471 my @holds = Koha::Holds->search($params);
1473 if ($suspend) {
1474 map { $_->suspend_hold($suspend_until) } @holds;
1476 else {
1477 map { $_->resume() } @holds;
1482 =head2 _FixPriority
1484 _FixPriority({
1485 reserve_id => $reserve_id,
1486 [rank => $rank,]
1487 [ignoreSetLowestRank => $ignoreSetLowestRank]
1492 _FixPriority({ biblionumber => $biblionumber});
1494 This routine adjusts the priority of a hold request and holds
1495 on the same bib.
1497 In the first form, where a reserve_id is passed, the priority of the
1498 hold is set to supplied rank, and other holds for that bib are adjusted
1499 accordingly. If the rank is "del", the hold is cancelled. If no rank
1500 is supplied, all of the holds on that bib have their priority adjusted
1501 as if the second form had been used.
1503 In the second form, where a biblionumber is passed, the holds on that
1504 bib (that are not captured) are sorted in order of increasing priority,
1505 then have reserves.priority set so that the first non-captured hold
1506 has its priority set to 1, the second non-captured hold has its priority
1507 set to 2, and so forth.
1509 In both cases, holds that have the lowestPriority flag on are have their
1510 priority adjusted to ensure that they remain at the end of the line.
1512 Note that the ignoreSetLowestRank parameter is meant to be used only
1513 when _FixPriority calls itself.
1515 =cut
1517 sub _FixPriority {
1518 my ( $params ) = @_;
1519 my $reserve_id = $params->{reserve_id};
1520 my $rank = $params->{rank} // '';
1521 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1522 my $biblionumber = $params->{biblionumber};
1524 my $dbh = C4::Context->dbh;
1526 my $hold;
1527 if ( $reserve_id ) {
1528 $hold = Koha::Holds->find( $reserve_id );
1529 if (!defined $hold){
1530 # may have already been checked out and hold fulfilled
1531 $hold = Koha::Old::Holds->find( $reserve_id );
1533 return unless $hold;
1536 unless ( $biblionumber ) { # FIXME This is a very weird API
1537 $biblionumber = $hold->biblionumber;
1540 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1541 $hold->cancel;
1543 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1545 # make sure priority for waiting or in-transit items is 0
1546 my $query = "
1547 UPDATE reserves
1548 SET priority = 0
1549 WHERE reserve_id = ?
1550 AND found IN ('W', 'T')
1552 my $sth = $dbh->prepare($query);
1553 $sth->execute( $reserve_id );
1555 my @priority;
1557 # get whats left
1558 my $query = "
1559 SELECT reserve_id, borrowernumber, reservedate
1560 FROM reserves
1561 WHERE biblionumber = ?
1562 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1563 ORDER BY priority ASC
1565 my $sth = $dbh->prepare($query);
1566 $sth->execute( $biblionumber );
1567 while ( my $line = $sth->fetchrow_hashref ) {
1568 push( @priority, $line );
1571 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1572 # To find the matching index
1573 my $i;
1574 my $key = -1; # to allow for 0 to be a valid result
1575 for ( $i = 0 ; $i < @priority ; $i++ ) {
1576 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1577 $key = $i; # save the index
1578 last;
1582 # if index exists in array then move it to new position
1583 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1584 my $new_rank = $rank -
1585 1; # $new_rank is what you want the new index to be in the array
1586 my $moving_item = splice( @priority, $key, 1 );
1587 splice( @priority, $new_rank, 0, $moving_item );
1590 # now fix the priority on those that are left....
1591 $query = "
1592 UPDATE reserves
1593 SET priority = ?
1594 WHERE reserve_id = ?
1596 $sth = $dbh->prepare($query);
1597 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1598 $sth->execute(
1599 $j + 1,
1600 $priority[$j]->{'reserve_id'}
1604 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1605 $sth->execute();
1607 unless ( $ignoreSetLowestRank ) {
1608 while ( my $res = $sth->fetchrow_hashref() ) {
1609 _FixPriority({
1610 reserve_id => $res->{'reserve_id'},
1611 rank => '999999',
1612 ignoreSetLowestRank => 1
1618 =head2 _Findgroupreserve
1620 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1622 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1623 first match found. If neither, then we look for non-holds-queue based holds.
1624 Lookahead is the number of days to look in advance.
1626 C<&_Findgroupreserve> returns :
1627 C<@results> is an array of references-to-hash whose keys are mostly
1628 fields from the reserves table of the Koha database, plus
1629 C<biblioitemnumber>.
1631 This routine with either return:
1632 1 - Item specific holds from the holds queue
1633 2 - Title level holds from the holds queue
1634 3 - All holds for this biblionumber
1636 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1638 =cut
1640 sub _Findgroupreserve {
1641 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1642 my $dbh = C4::Context->dbh;
1644 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1645 # check for exact targeted match
1646 my $item_level_target_query = qq{
1647 SELECT reserves.biblionumber AS biblionumber,
1648 reserves.borrowernumber AS borrowernumber,
1649 reserves.reservedate AS reservedate,
1650 reserves.branchcode AS branchcode,
1651 reserves.cancellationdate AS cancellationdate,
1652 reserves.found AS found,
1653 reserves.reservenotes AS reservenotes,
1654 reserves.priority AS priority,
1655 reserves.timestamp AS timestamp,
1656 biblioitems.biblioitemnumber AS biblioitemnumber,
1657 reserves.itemnumber AS itemnumber,
1658 reserves.reserve_id AS reserve_id,
1659 reserves.itemtype AS itemtype
1660 FROM reserves
1661 JOIN biblioitems USING (biblionumber)
1662 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1663 WHERE found IS NULL
1664 AND priority > 0
1665 AND item_level_request = 1
1666 AND itemnumber = ?
1667 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1668 AND suspend = 0
1669 ORDER BY priority
1671 my $sth = $dbh->prepare($item_level_target_query);
1672 $sth->execute($itemnumber, $lookahead||0);
1673 my @results;
1674 if ( my $data = $sth->fetchrow_hashref ) {
1675 push( @results, $data )
1676 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1678 return @results if @results;
1680 # check for title-level targeted match
1681 my $title_level_target_query = qq{
1682 SELECT reserves.biblionumber AS biblionumber,
1683 reserves.borrowernumber AS borrowernumber,
1684 reserves.reservedate AS reservedate,
1685 reserves.branchcode AS branchcode,
1686 reserves.cancellationdate AS cancellationdate,
1687 reserves.found AS found,
1688 reserves.reservenotes AS reservenotes,
1689 reserves.priority AS priority,
1690 reserves.timestamp AS timestamp,
1691 biblioitems.biblioitemnumber AS biblioitemnumber,
1692 reserves.itemnumber AS itemnumber,
1693 reserves.reserve_id AS reserve_id,
1694 reserves.itemtype AS itemtype
1695 FROM reserves
1696 JOIN biblioitems USING (biblionumber)
1697 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1698 WHERE found IS NULL
1699 AND priority > 0
1700 AND item_level_request = 0
1701 AND hold_fill_targets.itemnumber = ?
1702 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1703 AND suspend = 0
1704 ORDER BY priority
1706 $sth = $dbh->prepare($title_level_target_query);
1707 $sth->execute($itemnumber, $lookahead||0);
1708 @results = ();
1709 if ( my $data = $sth->fetchrow_hashref ) {
1710 push( @results, $data )
1711 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1713 return @results if @results;
1715 my $query = qq{
1716 SELECT reserves.biblionumber AS biblionumber,
1717 reserves.borrowernumber AS borrowernumber,
1718 reserves.reservedate AS reservedate,
1719 reserves.waitingdate AS waitingdate,
1720 reserves.branchcode AS branchcode,
1721 reserves.cancellationdate AS cancellationdate,
1722 reserves.found AS found,
1723 reserves.reservenotes AS reservenotes,
1724 reserves.priority AS priority,
1725 reserves.timestamp AS timestamp,
1726 reserves.itemnumber AS itemnumber,
1727 reserves.reserve_id AS reserve_id,
1728 reserves.itemtype AS itemtype
1729 FROM reserves
1730 WHERE reserves.biblionumber = ?
1731 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1732 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1733 AND suspend = 0
1734 ORDER BY priority
1736 $sth = $dbh->prepare($query);
1737 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1738 @results = ();
1739 while ( my $data = $sth->fetchrow_hashref ) {
1740 push( @results, $data )
1741 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1743 return @results;
1746 =head2 _koha_notify_reserve
1748 _koha_notify_reserve( $hold->reserve_id );
1750 Sends a notification to the patron that their hold has been filled (through
1751 ModReserveAffect, _not_ ModReserveFill)
1753 The letter code for this notice may be found using the following query:
1755 select distinct letter_code
1756 from message_transports
1757 inner join message_attributes using (message_attribute_id)
1758 where message_name = 'Hold_Filled'
1760 This will probably sipmly be 'HOLD', but because it is defined in the database,
1761 it is subject to addition or change.
1763 The following tables are availalbe witin the notice:
1765 branches
1766 borrowers
1767 biblio
1768 biblioitems
1769 reserves
1770 items
1772 =cut
1774 sub _koha_notify_reserve {
1775 my $reserve_id = shift;
1776 my $hold = Koha::Holds->find($reserve_id);
1777 my $borrowernumber = $hold->borrowernumber;
1779 my $patron = Koha::Patrons->find( $borrowernumber );
1781 # Try to get the borrower's email address
1782 my $to_address = $patron->notice_email_address;
1784 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1785 borrowernumber => $borrowernumber,
1786 message_name => 'Hold_Filled'
1787 } );
1789 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1791 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1793 my %letter_params = (
1794 module => 'reserves',
1795 branchcode => $hold->branchcode,
1796 lang => $patron->lang,
1797 tables => {
1798 'branches' => $library,
1799 'borrowers' => $patron->unblessed,
1800 'biblio' => $hold->biblionumber,
1801 'biblioitems' => $hold->biblionumber,
1802 'reserves' => $hold->unblessed,
1803 'items' => $hold->itemnumber,
1807 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.
1808 my $send_notification = sub {
1809 my ( $mtt, $letter_code ) = (@_);
1810 return unless defined $letter_code;
1811 $letter_params{letter_code} = $letter_code;
1812 $letter_params{message_transport_type} = $mtt;
1813 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1814 unless ($letter) {
1815 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1816 return;
1819 C4::Letters::EnqueueLetter( {
1820 letter => $letter,
1821 borrowernumber => $borrowernumber,
1822 from_address => $admin_email_address,
1823 message_transport_type => $mtt,
1824 } );
1827 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1828 next if (
1829 ( $mtt eq 'email' and not $to_address ) # No email address
1830 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1831 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1834 &$send_notification($mtt, $letter_code);
1835 $notification_sent++;
1837 #Making sure that a print notification is sent if no other transport types can be utilized.
1838 if (! $notification_sent) {
1839 &$send_notification('print', 'HOLD');
1844 =head2 _ShiftPriorityByDateAndPriority
1846 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1848 This increments the priority of all reserves after the one
1849 with either the lowest date after C<$reservedate>
1850 or the lowest priority after C<$priority>.
1852 It effectively makes room for a new reserve to be inserted with a certain
1853 priority, which is returned.
1855 This is most useful when the reservedate can be set by the user. It allows
1856 the new reserve to be placed before other reserves that have a later
1857 reservedate. Since priority also is set by the form in reserves/request.pl
1858 the sub accounts for that too.
1860 =cut
1862 sub _ShiftPriorityByDateAndPriority {
1863 my ( $biblio, $resdate, $new_priority ) = @_;
1865 my $dbh = C4::Context->dbh;
1866 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1867 my $sth = $dbh->prepare( $query );
1868 $sth->execute( $biblio, $resdate, $new_priority );
1869 my $min_priority = $sth->fetchrow;
1870 # if no such matches are found, $new_priority remains as original value
1871 $new_priority = $min_priority if ( $min_priority );
1873 # Shift the priority up by one; works in conjunction with the next SQL statement
1874 $query = "UPDATE reserves
1875 SET priority = priority+1
1876 WHERE biblionumber = ?
1877 AND borrowernumber = ?
1878 AND reservedate = ?
1879 AND found IS NULL";
1880 my $sth_update = $dbh->prepare( $query );
1882 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1883 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1884 $sth = $dbh->prepare( $query );
1885 $sth->execute( $new_priority, $biblio );
1886 while ( my $row = $sth->fetchrow_hashref ) {
1887 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1890 return $new_priority; # so the caller knows what priority they wind up receiving
1893 =head2 MoveReserve
1895 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1897 Use when checking out an item to handle reserves
1898 If $cancelreserve boolean is set to true, it will remove existing reserve
1900 =cut
1902 sub MoveReserve {
1903 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1905 $cancelreserve //= 0;
1907 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1908 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1909 return unless $res;
1911 my $biblionumber = $res->{biblionumber};
1913 if ($res->{borrowernumber} == $borrowernumber) {
1914 ModReserveFill($res);
1916 else {
1917 # warn "Reserved";
1918 # The item is reserved by someone else.
1919 # Find this item in the reserves
1921 my $borr_res = Koha::Holds->search({
1922 borrowernumber => $borrowernumber,
1923 biblionumber => $biblionumber,
1925 order_by => 'priority'
1926 })->next();
1928 if ( $borr_res ) {
1929 # The item is reserved by the current patron
1930 ModReserveFill($borr_res->unblessed);
1933 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1934 RevertWaitingStatus({ itemnumber => $itemnumber });
1936 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1937 my $hold = Koha::Holds->find( $res->{reserve_id} );
1938 $hold->cancel;
1943 =head2 MergeHolds
1945 MergeHolds($dbh,$to_biblio, $from_biblio);
1947 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1949 =cut
1951 sub MergeHolds {
1952 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1953 my $sth = $dbh->prepare(
1954 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1956 $sth->execute($from_biblio);
1957 if ( my $data = $sth->fetchrow_hashref() ) {
1959 # holds exist on old record, if not we don't need to do anything
1960 $sth = $dbh->prepare(
1961 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1962 $sth->execute( $to_biblio, $from_biblio );
1964 # Reorder by date
1965 # don't reorder those already waiting
1967 $sth = $dbh->prepare(
1968 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1970 my $upd_sth = $dbh->prepare(
1971 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1972 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1974 $sth->execute( $to_biblio, 'W', 'T' );
1975 my $priority = 1;
1976 while ( my $reserve = $sth->fetchrow_hashref() ) {
1977 $upd_sth->execute(
1978 $priority, $to_biblio,
1979 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1980 $reserve->{'itemnumber'}
1982 $priority++;
1987 =head2 RevertWaitingStatus
1989 RevertWaitingStatus({ itemnumber => $itemnumber });
1991 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1993 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1994 item level hold, even if it was only a bibliolevel hold to
1995 begin with. This is because we can no longer know if a hold
1996 was item-level or bib-level after a hold has been set to
1997 waiting status.
1999 =cut
2001 sub RevertWaitingStatus {
2002 my ( $params ) = @_;
2003 my $itemnumber = $params->{'itemnumber'};
2005 return unless ( $itemnumber );
2007 my $dbh = C4::Context->dbh;
2009 ## Get the waiting reserve we want to revert
2010 my $hold = Koha::Holds->search(
2012 itemnumber => $itemnumber,
2013 found => { not => undef },
2015 )->next;
2017 ## Increment the priority of all other non-waiting
2018 ## reserves for this bib record
2019 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2020 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2022 ## Fix up the currently waiting reserve
2023 $hold->set(
2025 priority => 1,
2026 found => undef,
2027 waitingdate => undef,
2028 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2030 )->store();
2032 _FixPriority( { biblionumber => $hold->biblionumber } );
2034 return $hold;
2037 =head2 ReserveSlip
2039 ReserveSlip(
2041 branchcode => $branchcode,
2042 borrowernumber => $borrowernumber,
2043 biblionumber => $biblionumber,
2044 [ itemnumber => $itemnumber, ]
2045 [ barcode => $barcode, ]
2049 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2051 The letter code will be HOLD_SLIP, and the following tables are
2052 available within the slip:
2054 reserves
2055 branches
2056 borrowers
2057 biblio
2058 biblioitems
2059 items
2061 =cut
2063 sub ReserveSlip {
2064 my ($args) = @_;
2065 my $branchcode = $args->{branchcode};
2066 my $reserve_id = $args->{reserve_id};
2068 my $hold = Koha::Holds->find($reserve_id);
2069 return unless $hold;
2071 my $patron = $hold->borrower;
2072 my $reserve = $hold->unblessed;
2074 return C4::Letters::GetPreparedLetter (
2075 module => 'circulation',
2076 letter_code => 'HOLD_SLIP',
2077 branchcode => $branchcode,
2078 lang => $patron->lang,
2079 tables => {
2080 'reserves' => $reserve,
2081 'branches' => $reserve->{branchcode},
2082 'borrowers' => $reserve->{borrowernumber},
2083 'biblio' => $reserve->{biblionumber},
2084 'biblioitems' => $reserve->{biblionumber},
2085 'items' => $reserve->{itemnumber},
2090 =head2 GetReservesControlBranch
2092 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2094 Return the branchcode to be used to determine which reserves
2095 policy applies to a transaction.
2097 C<$item> is a hashref for an item. Only 'homebranch' is used.
2099 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2101 =cut
2103 sub GetReservesControlBranch {
2104 my ( $item, $borrower ) = @_;
2106 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2108 my $branchcode =
2109 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2110 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2111 : undef;
2113 return $branchcode;
2116 =head2 CalculatePriority
2118 my $p = CalculatePriority($biblionumber, $resdate);
2120 Calculate priority for a new reserve on biblionumber, placing it at
2121 the end of the line of all holds whose start date falls before
2122 the current system time and that are neither on the hold shelf
2123 or in transit.
2125 The reserve date parameter is optional; if it is supplied, the
2126 priority is based on the set of holds whose start date falls before
2127 the parameter value.
2129 After calculation of this priority, it is recommended to call
2130 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2131 AddReserves.
2133 =cut
2135 sub CalculatePriority {
2136 my ( $biblionumber, $resdate ) = @_;
2138 my $sql = q{
2139 SELECT COUNT(*) FROM reserves
2140 WHERE biblionumber = ?
2141 AND priority > 0
2142 AND (found IS NULL OR found = '')
2144 #skip found==W or found==T (waiting or transit holds)
2145 if( $resdate ) {
2146 $sql.= ' AND ( reservedate <= ? )';
2148 else {
2149 $sql.= ' AND ( reservedate < NOW() )';
2151 my $dbh = C4::Context->dbh();
2152 my @row = $dbh->selectrow_array(
2153 $sql,
2154 undef,
2155 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2158 return @row ? $row[0]+1 : 1;
2161 =head2 IsItemOnHoldAndFound
2163 my $bool = IsItemFoundHold( $itemnumber );
2165 Returns true if the item is currently on hold
2166 and that hold has a non-null found status ( W, T, etc. )
2168 =cut
2170 sub IsItemOnHoldAndFound {
2171 my ($itemnumber) = @_;
2173 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2175 my $found = $rs->count(
2177 itemnumber => $itemnumber,
2178 found => { '!=' => undef }
2182 return $found;
2185 =head2 GetMaxPatronHoldsForRecord
2187 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2189 For multiple holds on a given record for a given patron, the max
2190 number of record level holds that a patron can be placed is the highest
2191 value of the holds_per_record rule for each item if the record for that
2192 patron. This subroutine finds and returns the highest holds_per_record
2193 rule value for a given patron id and record id.
2195 =cut
2197 sub GetMaxPatronHoldsForRecord {
2198 my ( $borrowernumber, $biblionumber ) = @_;
2200 my $patron = Koha::Patrons->find($borrowernumber);
2201 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2203 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2205 my $categorycode = $patron->categorycode;
2206 my $branchcode;
2207 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2209 my $max = 0;
2210 foreach my $item (@items) {
2211 my $itemtype = $item->effective_itemtype();
2213 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2215 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2216 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2217 $max = $holds_per_record if $holds_per_record > $max;
2220 return $max;
2223 =head2 GetHoldRule
2225 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2227 Returns the matching hold related issuingrule fields for a given
2228 patron category, itemtype, and library.
2230 =cut
2232 sub GetHoldRule {
2233 my ( $categorycode, $itemtype, $branchcode ) = @_;
2235 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2237 itemtype => $itemtype,
2238 categorycode => $categorycode,
2239 branchcode => $branchcode,
2240 rule_name => 'reservesallowed',
2241 order_by => {
2242 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2247 my $rules;
2248 if ( $reservesallowed ) {
2249 $rules->{reservesallowed} = $reservesallowed->rule_value;
2250 $rules->{itemtype} = $reservesallowed->itemtype;
2251 $rules->{categorycode} = $reservesallowed->categorycode;
2252 $rules->{branchcode} = $reservesallowed->branchcode;
2255 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2257 itemtype => $itemtype,
2258 categorycode => $categorycode,
2259 branchcode => $branchcode,
2260 rules => ['holds_per_record', 'holds_per_day'],
2261 order_by => {
2262 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2266 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2267 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2269 return $rules;
2272 =head1 AUTHOR
2274 Koha Development Team <http://koha-community.org/>
2276 =cut