Bug 25410: Sync liblibrarian and libopac descriptions
[koha.git] / C4 / Reserves.pm
blob9f8d31637af80a2039e8c98cf3ba83038db2d2f3
1 package C4::Reserves;
3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
6 # 2011 Catalyst IT
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24 use Modern::Perl;
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Items;
31 use C4::Letters;
32 use C4::Log;
33 use C4::Members::Messaging;
34 use C4::Members;
35 use Koha::Account::Lines;
36 use Koha::Biblios;
37 use Koha::Calendar;
38 use Koha::CirculationRules;
39 use Koha::Database;
40 use Koha::DateUtils;
41 use Koha::Hold;
42 use Koha::Holds;
43 use Koha::ItemTypes;
44 use Koha::Items;
45 use Koha::Libraries;
46 use Koha::Old::Hold;
47 use Koha::Patrons;
49 use Carp;
50 use Data::Dumper;
51 use List::MoreUtils qw( firstidx any );
53 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
55 =head1 NAME
57 C4::Reserves - Koha functions for dealing with reservation.
59 =head1 SYNOPSIS
61 use C4::Reserves;
63 =head1 DESCRIPTION
65 This modules provides somes functions to deal with reservations.
67 Reserves are stored in reserves table.
68 The following columns contains important values :
69 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
70 =0 : then the reserve is being dealed
71 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
72 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
73 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
74 F(inished) : the reserve has been completed, and is done
75 - itemnumber : empty : the reserve is still unaffected to an item
76 filled: the reserve is attached to an item
77 The complete workflow is :
78 ==== 1st use case ====
79 patron request a document, 1st available : P >0, F=NULL, I=NULL
80 a library having it run "transfertodo", and clic on the list
81 if there is no transfer to do, the reserve waiting
82 patron can pick it up P =0, F=W, I=filled
83 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
84 The pickup library receive the book, it check in P =0, F=W, I=filled
85 The patron borrow the book P =0, F=F, I=filled
87 ==== 2nd use case ====
88 patron requests a document, a given item,
89 If pickup is holding branch P =0, F=W, I=filled
90 If transfer needed, write in branchtransfer P =0, F=T, I=filled
91 The pickup library receive the book, it checks it in P =0, F=W, I=filled
92 The patron borrow the book P =0, F=F, I=filled
94 =head1 FUNCTIONS
96 =cut
98 BEGIN {
99 require Exporter;
100 @ISA = qw(Exporter);
101 @EXPORT = qw(
102 &AddReserve
104 &GetReserveStatus
106 &GetOtherReserves
108 &ModReserveFill
109 &ModReserveAffect
110 &ModReserve
111 &ModReserveStatus
112 &ModReserveCancelAll
113 &ModReserveMinusPriority
114 &MoveReserve
116 &CheckReserves
117 &CanBookBeReserved
118 &CanItemBeReserved
119 &CanReserveBeCanceledFromOpac
120 &CancelExpiredReserves
122 &AutoUnsuspendReserves
124 &IsAvailableForItemLevelRequest
125 ItemsAnyAvailableForHold
127 &AlterPriority
128 &ToggleLowestPriority
130 &ReserveSlip
131 &ToggleSuspend
132 &SuspendAll
134 &GetReservesControlBranch
136 IsItemOnHoldAndFound
138 GetMaxPatronHoldsForRecord
140 @EXPORT_OK = qw( MergeHolds );
143 =head2 AddReserve
145 AddReserve(
147 branchcode => $branchcode,
148 borrowernumber => $borrowernumber,
149 biblionumber => $biblionumber,
150 priority => $priority,
151 reservation_date => $reservation_date,
152 expiration_date => $expiration_date,
153 notes => $notes,
154 title => $title,
155 itemnumber => $itemnumber,
156 found => $found,
157 itemtype => $itemtype,
161 Adds reserve and generates HOLDPLACED message.
163 The following tables are available witin the HOLDPLACED message:
165 branches
166 borrowers
167 biblio
168 biblioitems
169 items
170 reserves
172 =cut
174 sub AddReserve {
175 my ($params) = @_;
176 my $branch = $params->{branchcode};
177 my $borrowernumber = $params->{borrowernumber};
178 my $biblionumber = $params->{biblionumber};
179 my $priority = $params->{priority};
180 my $resdate = $params->{reservation_date};
181 my $expdate = $params->{expiration_date};
182 my $notes = $params->{notes};
183 my $title = $params->{title};
184 my $checkitem = $params->{itemnumber};
185 my $found = $params->{found};
186 my $itemtype = $params->{itemtype};
188 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
189 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
191 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
193 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
194 # of the document, we force the value $priority and $found .
195 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
196 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
198 if (
199 # If item is already checked out, it cannot be set waiting
200 !$item->onloan
202 # The item can't be waiting if it needs a transfer
203 && $item->holdingbranch eq $branch
205 # Similarly, if in transit it can't be waiting
206 && !$item->get_transfer
208 # If we can't hold damaged items, and it is damaged, it can't be waiting
209 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
211 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
212 && !$item->current_holds->count )
214 $priority = 0;
215 $found = 'W';
219 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
221 # Make room in reserves for this before those of a later reserve date
222 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
225 my $waitingdate;
227 # If the reserv had the waiting status, we had the value of the resdate
228 if ( $found && $found eq 'W' ) {
229 $waitingdate = $resdate;
232 # Don't add itemtype limit if specific item is selected
233 $itemtype = undef if $checkitem;
235 # updates take place here
236 my $hold = Koha::Hold->new(
238 borrowernumber => $borrowernumber,
239 biblionumber => $biblionumber,
240 reservedate => $resdate,
241 branchcode => $branch,
242 priority => $priority,
243 reservenotes => $notes,
244 itemnumber => $checkitem,
245 found => $found,
246 waitingdate => $waitingdate,
247 expirationdate => $expdate,
248 itemtype => $itemtype,
249 item_level_hold => $checkitem ? 1 : 0,
251 )->store();
252 $hold->set_waiting() if $found && $found eq 'W';
254 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
255 if C4::Context->preference('HoldsLog');
257 my $reserve_id = $hold->id();
259 # add a reserve fee if needed
260 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
261 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
262 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
265 _FixPriority({ biblionumber => $biblionumber});
267 # Send e-mail to librarian if syspref is active
268 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
269 my $patron = Koha::Patrons->find( $borrowernumber );
270 my $library = $patron->library;
271 if ( my $letter = C4::Letters::GetPreparedLetter (
272 module => 'reserves',
273 letter_code => 'HOLDPLACED',
274 branchcode => $branch,
275 lang => $patron->lang,
276 tables => {
277 'branches' => $library->unblessed,
278 'borrowers' => $patron->unblessed,
279 'biblio' => $biblionumber,
280 'biblioitems' => $biblionumber,
281 'items' => $checkitem,
282 'reserves' => $hold->unblessed,
284 ) ) {
286 my $branch_email_address = $library->inbound_email_address;
288 C4::Letters::EnqueueLetter(
290 letter => $letter,
291 borrowernumber => $borrowernumber,
292 message_transport_type => 'email',
293 to_address => $branch_email_address,
299 return $reserve_id;
302 =head2 CanBookBeReserved
304 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
305 if ($canReserve eq 'OK') { #We can reserve this Item! }
307 See CanItemBeReserved() for possible return values.
309 =cut
311 sub CanBookBeReserved{
312 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
314 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
315 #get items linked via host records
316 my @hostitems = get_hostitemnumbers_of($biblionumber);
317 if (@hostitems){
318 push (@itemnumbers, @hostitems);
321 my $canReserve = { status => '' };
322 foreach my $itemnumber (@itemnumbers) {
323 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
324 return { status => 'OK' } if $canReserve->{status} eq 'OK';
326 return $canReserve;
329 =head2 CanItemBeReserved
331 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
332 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
334 @RETURNS { status => OK }, if the Item can be reserved.
335 { status => ageRestricted }, if the Item is age restricted for this borrower.
336 { status => damaged }, if the Item is damaged.
337 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
338 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
339 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
340 { status => notReservable }, if holds on this item are not allowed
341 { status => libraryNotFound }, if given branchcode is not an existing library
342 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
343 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
344 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
346 =cut
348 sub CanItemBeReserved {
349 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
351 my $dbh = C4::Context->dbh;
352 my $ruleitemtype; # itemtype of the matching issuing rule
353 my $allowedreserves = 0; # Total number of holds allowed across all records
354 my $holds_per_record = 1; # Total number of holds allowed for this one given record
355 my $holds_per_day; # Default to unlimited
357 # we retrieve borrowers and items informations #
358 # item->{itype} will come for biblioitems if necessery
359 my $item = Koha::Items->find($itemnumber);
360 my $biblio = $item->biblio;
361 my $patron = Koha::Patrons->find( $borrowernumber );
362 my $borrower = $patron->unblessed;
364 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
365 return { status =>'damaged' }
366 if ( $item->damaged
367 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
369 # Check for the age restriction
370 my ( $ageRestriction, $daysToAgeRestriction ) =
371 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
372 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
374 # Check that the patron doesn't have an item level hold on this item already
375 return { status =>'itemAlreadyOnHold' }
376 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
378 my $controlbranch = C4::Context->preference('ReservesControlBranch');
380 my $querycount = q{
381 SELECT count(*) AS count
382 FROM reserves
383 LEFT JOIN items USING (itemnumber)
384 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
385 LEFT JOIN borrowers USING (borrowernumber)
386 WHERE borrowernumber = ?
389 my $branchcode = "";
390 my $branchfield = "reserves.branchcode";
392 if ( $controlbranch eq "ItemHomeLibrary" ) {
393 $branchfield = "items.homebranch";
394 $branchcode = $item->homebranch;
396 elsif ( $controlbranch eq "PatronLibrary" ) {
397 $branchfield = "borrowers.branchcode";
398 $branchcode = $borrower->{branchcode};
401 # we retrieve rights
402 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
403 $ruleitemtype = $rights->{itemtype};
404 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
405 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
406 $holds_per_day = $rights->{holds_per_day};
408 else {
409 $ruleitemtype = undef;
412 my $holds = Koha::Holds->search(
414 borrowernumber => $borrowernumber,
415 biblionumber => $item->biblionumber,
418 if ( defined $holds_per_record && $holds_per_record ne ''
419 && $holds->count() >= $holds_per_record ) {
420 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
423 my $today_holds = Koha::Holds->search({
424 borrowernumber => $borrowernumber,
425 reservedate => dt_from_string->date
428 if ( defined $holds_per_day && $holds_per_day ne ''
429 && $today_holds->count() >= $holds_per_day )
431 return { status => 'tooManyReservesToday', limit => $holds_per_day };
434 # we retrieve count
436 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
438 # If using item-level itypes, fall back to the record
439 # level itemtype if the hold has no associated item
440 $querycount .=
441 C4::Context->preference('item-level_itypes')
442 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
443 : " AND biblioitems.itemtype = ?"
444 if defined $ruleitemtype;
446 my $sthcount = $dbh->prepare($querycount);
448 if ( defined $ruleitemtype ) {
449 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
451 else {
452 $sthcount->execute( $borrowernumber, $branchcode );
455 my $reservecount = "0";
456 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
457 $reservecount = $rowcount->{count};
460 # we check if it's ok or not
461 if ( defined $allowedreserves && $allowedreserves ne ''
462 && $reservecount >= $allowedreserves ) {
463 return { status => 'tooManyReserves', limit => $allowedreserves };
466 # Now we need to check hold limits by patron category
467 my $rule = Koha::CirculationRules->get_effective_rule(
469 categorycode => $borrower->{categorycode},
470 branchcode => $branchcode,
471 rule_name => 'max_holds',
474 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
475 my $total_holds_count = Koha::Holds->search(
477 borrowernumber => $borrower->{borrowernumber}
479 )->count();
481 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
484 my $reserves_control_branch =
485 GetReservesControlBranch( $item->unblessed(), $borrower );
486 my $branchitemrule =
487 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
489 if ( $branchitemrule->{holdallowed} == 0 ) {
490 return { status => 'notReservable' };
493 if ( $branchitemrule->{holdallowed} == 1
494 && $borrower->{branchcode} ne $item->homebranch )
496 return { status => 'cannotReserveFromOtherBranches' };
499 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
500 if ( $branchitemrule->{holdallowed} == 3) {
501 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
502 return { status => 'branchNotInHoldGroup' };
506 # If reservecount is ok, we check item branch if IndependentBranches is ON
507 # and canreservefromotherbranches is OFF
508 if ( C4::Context->preference('IndependentBranches')
509 and !C4::Context->preference('canreservefromotherbranches') )
511 if ( $item->homebranch ne $borrower->{branchcode} ) {
512 return { status => 'cannotReserveFromOtherBranches' };
516 if ($pickup_branchcode) {
517 my $destination = Koha::Libraries->find({
518 branchcode => $pickup_branchcode,
521 unless ($destination) {
522 return { status => 'libraryNotFound' };
524 unless ($destination->pickup_location) {
525 return { status => 'libraryNotPickupLocation' };
527 unless ($item->can_be_transferred({ to => $destination })) {
528 return { status => 'cannotBeTransferred' };
530 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
531 return { status => 'pickupNotInHoldGroup' };
533 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
534 return { status => 'pickupNotInHoldGroup' };
538 return { status => 'OK' };
541 =head2 CanReserveBeCanceledFromOpac
543 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
545 returns 1 if reserve can be cancelled by user from OPAC.
546 First check if reserve belongs to user, next checks if reserve is not in
547 transfer or waiting status
549 =cut
551 sub CanReserveBeCanceledFromOpac {
552 my ($reserve_id, $borrowernumber) = @_;
554 return unless $reserve_id and $borrowernumber;
555 my $reserve = Koha::Holds->find($reserve_id);
557 return 0 unless $reserve->borrowernumber == $borrowernumber;
558 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
560 return 1;
564 =head2 GetOtherReserves
566 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
568 Check queued list of this document and check if this document must be transferred
570 =cut
572 sub GetOtherReserves {
573 my ($itemnumber) = @_;
574 my $messages;
575 my $nextreservinfo;
576 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
577 if ($checkreserves) {
578 my $item = Koha::Items->find($itemnumber);
579 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
580 $messages->{'transfert'} = $checkreserves->{'branchcode'};
581 #minus priorities of others reservs
582 ModReserveMinusPriority(
583 $itemnumber,
584 $checkreserves->{'reserve_id'},
587 #launch the subroutine dotransfer
588 C4::Items::ModItemTransfer(
589 $itemnumber,
590 $item->holdingbranch,
591 $checkreserves->{'branchcode'},
592 'Reserve'
597 #step 2b : case of a reservation on the same branch, set the waiting status
598 else {
599 $messages->{'waiting'} = 1;
600 ModReserveMinusPriority(
601 $itemnumber,
602 $checkreserves->{'reserve_id'},
604 ModReserveStatus($itemnumber,'W');
607 $nextreservinfo = $checkreserves->{'borrowernumber'};
610 return ( $messages, $nextreservinfo );
613 =head2 ChargeReserveFee
615 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
617 Charge the fee for a reserve (if $fee > 0)
619 =cut
621 sub ChargeReserveFee {
622 my ( $borrowernumber, $fee, $title ) = @_;
623 return if !$fee || $fee == 0; # the last test is needed to include 0.00
624 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
626 amount => $fee,
627 description => $title,
628 note => undef,
629 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
630 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
631 interface => C4::Context->interface,
632 invoice_type => undef,
633 type => 'RESERVE',
634 item_id => undef
639 =head2 GetReserveFee
641 $fee = GetReserveFee( $borrowernumber, $biblionumber );
643 Calculate the fee for a reserve (if applicable).
645 =cut
647 sub GetReserveFee {
648 my ( $borrowernumber, $biblionumber ) = @_;
649 my $borquery = qq{
650 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
652 my $issue_qry = qq{
653 SELECT COUNT(*) FROM items
654 LEFT JOIN issues USING (itemnumber)
655 WHERE items.biblionumber=? AND issues.issue_id IS NULL
657 my $holds_qry = qq{
658 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
661 my $dbh = C4::Context->dbh;
662 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
663 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
664 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
665 # This is a reconstruction of the old code:
666 # Compare number of items with items issued, and optionally check holds
667 # If not all items are issued and there are no holds: charge no fee
668 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
669 my ( $notissued, $reserved );
670 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
671 ( $biblionumber ) );
672 if( $notissued ) {
673 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
674 ( $biblionumber, $borrowernumber ) );
675 $fee = 0 if $reserved == 0;
678 return $fee;
681 =head2 GetReserveStatus
683 $reservestatus = GetReserveStatus($itemnumber);
685 Takes an itemnumber and returns the status of the reserve placed on it.
686 If several reserves exist, the reserve with the lower priority is given.
688 =cut
690 ## FIXME: I don't think this does what it thinks it does.
691 ## It only ever checks the first reserve result, even though
692 ## multiple reserves for that bib can have the itemnumber set
693 ## the sub is only used once in the codebase.
694 sub GetReserveStatus {
695 my ($itemnumber) = @_;
697 my $dbh = C4::Context->dbh;
699 my ($sth, $found, $priority);
700 if ( $itemnumber ) {
701 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
702 $sth->execute($itemnumber);
703 ($found, $priority) = $sth->fetchrow_array;
706 if(defined $found) {
707 return 'Waiting' if $found eq 'W' and $priority == 0;
708 return 'Finished' if $found eq 'F';
711 return 'Reserved' if defined $priority && $priority > 0;
713 return ''; # empty string here will remove need for checking undef, or less log lines
716 =head2 CheckReserves
718 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
719 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
720 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
722 Find a book in the reserves.
724 C<$itemnumber> is the book's item number.
725 C<$lookahead> is the number of days to look in advance for future reserves.
727 As I understand it, C<&CheckReserves> looks for the given item in the
728 reserves. If it is found, that's a match, and C<$status> is set to
729 C<Waiting>.
731 Otherwise, it finds the most important item in the reserves with the
732 same biblio number as this book (I'm not clear on this) and returns it
733 with C<$status> set to C<Reserved>.
735 C<&CheckReserves> returns a two-element list:
737 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
739 C<$reserve> is the reserve item that matched. It is a
740 reference-to-hash whose keys are mostly the fields of the reserves
741 table in the Koha database.
743 =cut
745 sub CheckReserves {
746 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
747 my $dbh = C4::Context->dbh;
748 my $sth;
749 my $select;
750 if (C4::Context->preference('item-level_itypes')){
751 $select = "
752 SELECT items.biblionumber,
753 items.biblioitemnumber,
754 itemtypes.notforloan,
755 items.notforloan AS itemnotforloan,
756 items.itemnumber,
757 items.damaged,
758 items.homebranch,
759 items.holdingbranch
760 FROM items
761 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
762 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
765 else {
766 $select = "
767 SELECT items.biblionumber,
768 items.biblioitemnumber,
769 itemtypes.notforloan,
770 items.notforloan AS itemnotforloan,
771 items.itemnumber,
772 items.damaged,
773 items.homebranch,
774 items.holdingbranch
775 FROM items
776 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
777 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
781 if ($item) {
782 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
783 $sth->execute($item);
785 else {
786 $sth = $dbh->prepare("$select WHERE barcode = ?");
787 $sth->execute($barcode);
789 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
790 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
791 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
793 return unless $itemnumber; # bail if we got nothing.
794 # if item is not for loan it cannot be reserved either.....
795 # except where items.notforloan < 0 : This indicates the item is holdable.
797 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
798 return if $dont_trap or $notforloan_per_itemtype;
800 # Find this item in the reserves
801 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
803 # $priority and $highest are used to find the most important item
804 # in the list returned by &_Findgroupreserve. (The lower $priority,
805 # the more important the item.)
806 # $highest is the most important item we've seen so far.
807 my $highest;
809 if (scalar @reserves) {
810 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
811 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
812 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
814 my $priority = 10000000;
815 foreach my $res (@reserves) {
816 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
817 if ($res->{'found'} eq 'W') {
818 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
819 } else {
820 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
822 } else {
823 my $patron;
824 my $item;
825 my $local_hold_match;
827 if ($LocalHoldsPriority) {
828 $patron = Koha::Patrons->find( $res->{borrowernumber} );
829 $item = Koha::Items->find($itemnumber);
831 my $local_holds_priority_item_branchcode =
832 $item->$LocalHoldsPriorityItemControl;
833 my $local_holds_priority_patron_branchcode =
834 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
835 ? $res->{branchcode}
836 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
837 ? $patron->branchcode
838 : undef;
839 $local_hold_match =
840 $local_holds_priority_item_branchcode eq
841 $local_holds_priority_patron_branchcode;
844 # See if this item is more important than what we've got so far
845 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
846 $item ||= Koha::Items->find($itemnumber);
847 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
848 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
849 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
850 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
851 next if ($branchitemrule->{'holdallowed'} == 0);
852 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
853 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
854 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
855 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
856 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
857 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
858 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
859 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
860 $priority = $res->{'priority'};
861 $highest = $res;
862 last if $local_hold_match;
868 # If we get this far, then no exact match was found.
869 # We return the most important (i.e. next) reservation.
870 if ($highest) {
871 $highest->{'itemnumber'} = $item;
872 return ( "Reserved", $highest, \@reserves );
875 return ( '' );
878 =head2 CancelExpiredReserves
880 CancelExpiredReserves();
882 Cancels all reserves with an expiration date from before today.
884 =cut
886 sub CancelExpiredReserves {
887 my $today = dt_from_string();
888 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
889 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
891 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
892 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
893 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
895 # FIXME To move to Koha::Holds->search_expired (?)
896 my $holds = Koha::Holds->search( $params );
898 while ( my $hold = $holds->next ) {
899 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
901 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
903 my $cancel_params = {};
904 if ( $hold->found eq 'W' ) {
905 $cancel_params->{charge_cancel_fee} = 1;
907 $hold->cancel( $cancel_params );
911 =head2 AutoUnsuspendReserves
913 AutoUnsuspendReserves();
915 Unsuspends all suspended reserves with a suspend_until date from before today.
917 =cut
919 sub AutoUnsuspendReserves {
920 my $today = dt_from_string();
922 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
924 map { $_->resume() } @holds;
927 =head2 ModReserve
929 ModReserve({ rank => $rank,
930 reserve_id => $reserve_id,
931 branchcode => $branchcode
932 [, itemnumber => $itemnumber ]
933 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
936 Change a hold request's priority or cancel it.
938 C<$rank> specifies the effect of the change. If C<$rank>
939 is 'W' or 'n', nothing happens. This corresponds to leaving a
940 request alone when changing its priority in the holds queue
941 for a bib.
943 If C<$rank> is 'del', the hold request is cancelled.
945 If C<$rank> is an integer greater than zero, the priority of
946 the request is set to that value. Since priority != 0 means
947 that the item is not waiting on the hold shelf, setting the
948 priority to a non-zero value also sets the request's found
949 status and waiting date to NULL.
951 The optional C<$itemnumber> parameter is used only when
952 C<$rank> is a non-zero integer; if supplied, the itemnumber
953 of the hold request is set accordingly; if omitted, the itemnumber
954 is cleared.
956 B<FIXME:> Note that the forgoing can have the effect of causing
957 item-level hold requests to turn into title-level requests. This
958 will be fixed once reserves has separate columns for requested
959 itemnumber and supplying itemnumber.
961 =cut
963 sub ModReserve {
964 my ( $params ) = @_;
966 my $rank = $params->{'rank'};
967 my $reserve_id = $params->{'reserve_id'};
968 my $branchcode = $params->{'branchcode'};
969 my $itemnumber = $params->{'itemnumber'};
970 my $suspend_until = $params->{'suspend_until'};
971 my $borrowernumber = $params->{'borrowernumber'};
972 my $biblionumber = $params->{'biblionumber'};
974 return if $rank eq "W";
975 return if $rank eq "n";
977 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
979 my $hold;
980 unless ( $reserve_id ) {
981 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
982 return unless $holds->count; # FIXME Should raise an exception
983 $hold = $holds->next;
984 $reserve_id = $hold->reserve_id;
987 $hold ||= Koha::Holds->find($reserve_id);
989 if ( $rank eq "del" ) {
990 $hold->cancel;
992 elsif ($rank =~ /^\d+/ and $rank > 0) {
993 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
994 if C4::Context->preference('HoldsLog');
996 my $properties = {
997 priority => $rank,
998 branchcode => $branchcode,
999 itemnumber => $itemnumber,
1000 found => undef,
1001 waitingdate => undef
1003 if (exists $params->{reservedate}) {
1004 $properties->{reservedate} = $params->{reservedate} || undef;
1006 if (exists $params->{expirationdate}) {
1007 $properties->{expirationdate} = $params->{expirationdate} || undef;
1010 $hold->set($properties)->store();
1012 if ( defined( $suspend_until ) ) {
1013 if ( $suspend_until ) {
1014 $suspend_until = eval { dt_from_string( $suspend_until ) };
1015 $hold->suspend_hold( $suspend_until );
1016 } else {
1017 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1018 # If the hold is not suspended, this does nothing.
1019 $hold->set( { suspend_until => undef } )->store();
1023 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1027 =head2 ModReserveFill
1029 &ModReserveFill($reserve);
1031 Fill a reserve. If I understand this correctly, this means that the
1032 reserved book has been found and given to the patron who reserved it.
1034 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1035 whose keys are fields from the reserves table in the Koha database.
1037 =cut
1039 sub ModReserveFill {
1040 my ($res) = @_;
1041 my $reserve_id = $res->{'reserve_id'};
1043 my $hold = Koha::Holds->find($reserve_id);
1044 # get the priority on this record....
1045 my $priority = $hold->priority;
1047 # update the hold statuses, no need to store it though, we will be deleting it anyway
1048 $hold->set(
1050 found => 'F',
1051 priority => 0,
1055 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1056 if C4::Context->preference('HoldsLog');
1058 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1059 Koha::Old::Hold->new( $hold->unblessed() )->store();
1061 $hold->delete();
1063 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1064 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1065 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1068 # now fix the priority on the others (if the priority wasn't
1069 # already sorted!)....
1070 unless ( $priority == 0 ) {
1071 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1075 =head2 ModReserveStatus
1077 &ModReserveStatus($itemnumber, $newstatus);
1079 Update the reserve status for the active (priority=0) reserve.
1081 $itemnumber is the itemnumber the reserve is on
1083 $newstatus is the new status.
1085 =cut
1087 sub ModReserveStatus {
1089 #first : check if we have a reservation for this item .
1090 my ($itemnumber, $newstatus) = @_;
1091 my $dbh = C4::Context->dbh;
1093 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1094 my $sth_set = $dbh->prepare($query);
1095 $sth_set->execute( $newstatus, $itemnumber );
1097 my $item = Koha::Items->find($itemnumber);
1098 if ( $item->location && $item->location eq 'CART'
1099 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1100 && $newstatus ) {
1101 CartToShelf( $itemnumber );
1105 =head2 ModReserveAffect
1107 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1109 This function affect an item and a status for a given reserve, either fetched directly
1110 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1111 is given, only first reserve returned is affected, which is ok for anything but
1112 multi-item holds.
1114 if $transferToDo is not set, then the status is set to "Waiting" as well.
1115 otherwise, a transfer is on the way, and the end of the transfer will
1116 take care of the waiting status
1118 =cut
1120 sub ModReserveAffect {
1121 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1122 my $dbh = C4::Context->dbh;
1124 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1125 # attached to $itemnumber
1126 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1127 $sth->execute($itemnumber);
1128 my ($biblionumber) = $sth->fetchrow;
1130 # get request - need to find out if item is already
1131 # waiting in order to not send duplicate hold filled notifications
1133 my $hold;
1134 # Find hold by id if we have it
1135 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1136 # Find item level hold for this item if there is one
1137 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1138 # Find record level hold if there is no item level hold
1139 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1141 return unless $hold;
1143 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1145 $hold->itemnumber($itemnumber);
1146 $hold->set_waiting($transferToDo);
1148 if( !$transferToDo ){
1149 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1150 my $transfers = Koha::Item::Transfers->search({
1151 itemnumber => $itemnumber,
1152 datearrived => undef
1154 while( my $transfer = $transfers->next ){
1155 $transfer->datearrived( dt_from_string() )->store;
1160 _FixPriority( { biblionumber => $biblionumber } );
1161 my $item = Koha::Items->find($itemnumber);
1162 if ( $item->location && $item->location eq 'CART'
1163 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1164 CartToShelf( $itemnumber );
1167 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1168 if C4::Context->preference('HoldsLog');
1170 return;
1173 =head2 ModReserveCancelAll
1175 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1177 function to cancel reserv,check other reserves, and transfer document if it's necessary
1179 =cut
1181 sub ModReserveCancelAll {
1182 my $messages;
1183 my $nextreservinfo;
1184 my ( $itemnumber, $borrowernumber ) = @_;
1186 #step 1 : cancel the reservation
1187 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1188 return unless $holds->count;
1189 $holds->next->cancel;
1191 #step 2 launch the subroutine of the others reserves
1192 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1194 return ( $messages, $nextreservinfo );
1197 =head2 ModReserveMinusPriority
1199 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1201 Reduce the values of queued list
1203 =cut
1205 sub ModReserveMinusPriority {
1206 my ( $itemnumber, $reserve_id ) = @_;
1208 #first step update the value of the first person on reserv
1209 my $dbh = C4::Context->dbh;
1210 my $query = "
1211 UPDATE reserves
1212 SET priority = 0 , itemnumber = ?
1213 WHERE reserve_id = ?
1215 my $sth_upd = $dbh->prepare($query);
1216 $sth_upd->execute( $itemnumber, $reserve_id );
1217 # second step update all others reserves
1218 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1221 =head2 IsAvailableForItemLevelRequest
1223 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1225 Checks whether a given item record is available for an
1226 item-level hold request. An item is available if
1228 * it is not lost AND
1229 * it is not damaged AND
1230 * it is not withdrawn AND
1231 * a waiting or in transit reserve is placed on
1232 * does not have a not for loan value > 0
1234 Need to check the issuingrules onshelfholds column,
1235 if this is set items on the shelf can be placed on hold
1237 Note that IsAvailableForItemLevelRequest() does not
1238 check if the staff operator is authorized to place
1239 a request on the item - in particular,
1240 this routine does not check IndependentBranches
1241 and canreservefromotherbranches.
1243 =cut
1245 sub IsAvailableForItemLevelRequest {
1246 my $item = shift;
1247 my $patron = shift;
1248 my $pickup_branchcode = shift;
1249 # items_any_available is precalculated status passed from request.pl when set of items
1250 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1251 my $items_any_available = shift;
1253 my $dbh = C4::Context->dbh;
1254 # must check the notforloan setting of the itemtype
1255 # FIXME - a lot of places in the code do this
1256 # or something similar - need to be
1257 # consolidated
1258 my $itemtype = $item->effective_itemtype;
1259 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1261 return 0 if
1262 $notforloan_per_itemtype ||
1263 $item->itemlost ||
1264 $item->notforloan > 0 ||
1265 $item->withdrawn ||
1266 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1268 if ($pickup_branchcode) {
1269 my $destination = Koha::Libraries->find($pickup_branchcode);
1270 return 0 unless $destination;
1271 return 0 unless $destination->pickup_location;
1272 return 0 unless $item->can_be_transferred( { to => $destination } );
1273 my $reserves_control_branch =
1274 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1275 my $branchitemrule =
1276 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1277 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1278 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1281 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1283 if ( $on_shelf_holds == 1 ) {
1284 return 1;
1285 } elsif ( $on_shelf_holds == 2 ) {
1287 # if we have this param predefined from outer caller sub, we just need
1288 # to return it, so we saving from having loop inside other loop:
1289 return $items_any_available ? 0 : 1
1290 if defined $items_any_available;
1292 my $any_available = ItemsAnyAvailableForHold( { biblionumber => $item->biblionumber, patron => $patron });
1293 return $any_available ? 0 : 1;
1294 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1295 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1299 =head2 ItemsAnyAvailableForHold
1301 ItemsAnyAvailableForHold( { biblionumber => $biblionumber, patron => $patron });
1303 This function checks all items for specified biblionumber (num) / patron (object)
1304 and returns true (1) or false (0) depending if any of rules allows at least of
1305 one item to be available for hold including lots of parameters/logic
1307 =cut
1309 sub ItemsAnyAvailableForHold {
1310 my $param = shift;
1312 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1314 my $any_available = 0;
1316 foreach my $i (@items) {
1317 my $reserves_control_branch =
1318 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1319 my $branchitemrule =
1320 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1321 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1323 $any_available = 1
1324 unless $i->itemlost
1325 || $i->notforloan > 0
1326 || $i->withdrawn
1327 || $i->onloan
1328 || IsItemOnHoldAndFound( $i->id )
1329 || ( $i->damaged
1330 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1331 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1332 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1333 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } );
1336 return $any_available;
1339 =head2 AlterPriority
1341 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1343 This function changes a reserve's priority up, down, to the top, or to the bottom.
1344 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1346 =cut
1348 sub AlterPriority {
1349 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1351 my $hold = Koha::Holds->find( $reserve_id );
1352 return unless $hold;
1354 if ( $hold->cancellationdate ) {
1355 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1356 return;
1359 if ( $where eq 'up' ) {
1360 return unless $prev_priority;
1361 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1362 } elsif ( $where eq 'down' ) {
1363 return unless $next_priority;
1364 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1365 } elsif ( $where eq 'top' ) {
1366 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1367 } elsif ( $where eq 'bottom' ) {
1368 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1371 # FIXME Should return the new priority
1374 =head2 ToggleLowestPriority
1376 ToggleLowestPriority( $borrowernumber, $biblionumber );
1378 This function sets the lowestPriority field to true if is false, and false if it is true.
1380 =cut
1382 sub ToggleLowestPriority {
1383 my ( $reserve_id ) = @_;
1385 my $dbh = C4::Context->dbh;
1387 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1388 $sth->execute( $reserve_id );
1390 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1393 =head2 ToggleSuspend
1395 ToggleSuspend( $reserve_id );
1397 This function sets the suspend field to true if is false, and false if it is true.
1398 If the reserve is currently suspended with a suspend_until date, that date will
1399 be cleared when it is unsuspended.
1401 =cut
1403 sub ToggleSuspend {
1404 my ( $reserve_id, $suspend_until ) = @_;
1406 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1408 my $hold = Koha::Holds->find( $reserve_id );
1410 if ( $hold->is_suspended ) {
1411 $hold->resume()
1412 } else {
1413 $hold->suspend_hold( $suspend_until );
1417 =head2 SuspendAll
1419 SuspendAll(
1420 borrowernumber => $borrowernumber,
1421 [ biblionumber => $biblionumber, ]
1422 [ suspend_until => $suspend_until, ]
1423 [ suspend => $suspend ]
1426 This function accepts a set of hash keys as its parameters.
1427 It requires either borrowernumber or biblionumber, or both.
1429 suspend_until is wholly optional.
1431 =cut
1433 sub SuspendAll {
1434 my %params = @_;
1436 my $borrowernumber = $params{'borrowernumber'} || undef;
1437 my $biblionumber = $params{'biblionumber'} || undef;
1438 my $suspend_until = $params{'suspend_until'} || undef;
1439 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1441 $suspend_until = eval { dt_from_string($suspend_until) }
1442 if ( defined($suspend_until) );
1444 return unless ( $borrowernumber || $biblionumber );
1446 my $params;
1447 $params->{found} = undef;
1448 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1449 $params->{biblionumber} = $biblionumber if $biblionumber;
1451 my @holds = Koha::Holds->search($params);
1453 if ($suspend) {
1454 map { $_->suspend_hold($suspend_until) } @holds;
1456 else {
1457 map { $_->resume() } @holds;
1462 =head2 _FixPriority
1464 _FixPriority({
1465 reserve_id => $reserve_id,
1466 [rank => $rank,]
1467 [ignoreSetLowestRank => $ignoreSetLowestRank]
1472 _FixPriority({ biblionumber => $biblionumber});
1474 This routine adjusts the priority of a hold request and holds
1475 on the same bib.
1477 In the first form, where a reserve_id is passed, the priority of the
1478 hold is set to supplied rank, and other holds for that bib are adjusted
1479 accordingly. If the rank is "del", the hold is cancelled. If no rank
1480 is supplied, all of the holds on that bib have their priority adjusted
1481 as if the second form had been used.
1483 In the second form, where a biblionumber is passed, the holds on that
1484 bib (that are not captured) are sorted in order of increasing priority,
1485 then have reserves.priority set so that the first non-captured hold
1486 has its priority set to 1, the second non-captured hold has its priority
1487 set to 2, and so forth.
1489 In both cases, holds that have the lowestPriority flag on are have their
1490 priority adjusted to ensure that they remain at the end of the line.
1492 Note that the ignoreSetLowestRank parameter is meant to be used only
1493 when _FixPriority calls itself.
1495 =cut
1497 sub _FixPriority {
1498 my ( $params ) = @_;
1499 my $reserve_id = $params->{reserve_id};
1500 my $rank = $params->{rank} // '';
1501 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1502 my $biblionumber = $params->{biblionumber};
1504 my $dbh = C4::Context->dbh;
1506 my $hold;
1507 if ( $reserve_id ) {
1508 $hold = Koha::Holds->find( $reserve_id );
1509 if (!defined $hold){
1510 # may have already been checked out and hold fulfilled
1511 $hold = Koha::Old::Holds->find( $reserve_id );
1513 return unless $hold;
1516 unless ( $biblionumber ) { # FIXME This is a very weird API
1517 $biblionumber = $hold->biblionumber;
1520 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1521 $hold->cancel;
1523 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1525 # make sure priority for waiting or in-transit items is 0
1526 my $query = "
1527 UPDATE reserves
1528 SET priority = 0
1529 WHERE reserve_id = ?
1530 AND found IN ('W', 'T')
1532 my $sth = $dbh->prepare($query);
1533 $sth->execute( $reserve_id );
1535 my @priority;
1537 # get whats left
1538 my $query = "
1539 SELECT reserve_id, borrowernumber, reservedate
1540 FROM reserves
1541 WHERE biblionumber = ?
1542 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1543 ORDER BY priority ASC
1545 my $sth = $dbh->prepare($query);
1546 $sth->execute( $biblionumber );
1547 while ( my $line = $sth->fetchrow_hashref ) {
1548 push( @priority, $line );
1551 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1552 # To find the matching index
1553 my $i;
1554 my $key = -1; # to allow for 0 to be a valid result
1555 for ( $i = 0 ; $i < @priority ; $i++ ) {
1556 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1557 $key = $i; # save the index
1558 last;
1562 # if index exists in array then move it to new position
1563 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1564 my $new_rank = $rank -
1565 1; # $new_rank is what you want the new index to be in the array
1566 my $moving_item = splice( @priority, $key, 1 );
1567 splice( @priority, $new_rank, 0, $moving_item );
1570 # now fix the priority on those that are left....
1571 $query = "
1572 UPDATE reserves
1573 SET priority = ?
1574 WHERE reserve_id = ?
1576 $sth = $dbh->prepare($query);
1577 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1578 $sth->execute(
1579 $j + 1,
1580 $priority[$j]->{'reserve_id'}
1584 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1585 $sth->execute();
1587 unless ( $ignoreSetLowestRank ) {
1588 while ( my $res = $sth->fetchrow_hashref() ) {
1589 _FixPriority({
1590 reserve_id => $res->{'reserve_id'},
1591 rank => '999999',
1592 ignoreSetLowestRank => 1
1598 =head2 _Findgroupreserve
1600 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1602 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1603 first match found. If neither, then we look for non-holds-queue based holds.
1604 Lookahead is the number of days to look in advance.
1606 C<&_Findgroupreserve> returns :
1607 C<@results> is an array of references-to-hash whose keys are mostly
1608 fields from the reserves table of the Koha database, plus
1609 C<biblioitemnumber>.
1611 This routine with either return:
1612 1 - Item specific holds from the holds queue
1613 2 - Title level holds from the holds queue
1614 3 - All holds for this biblionumber
1616 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1618 =cut
1620 sub _Findgroupreserve {
1621 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1622 my $dbh = C4::Context->dbh;
1624 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1625 # check for exact targeted match
1626 my $item_level_target_query = qq{
1627 SELECT reserves.biblionumber AS biblionumber,
1628 reserves.borrowernumber AS borrowernumber,
1629 reserves.reservedate AS reservedate,
1630 reserves.branchcode AS branchcode,
1631 reserves.cancellationdate AS cancellationdate,
1632 reserves.found AS found,
1633 reserves.reservenotes AS reservenotes,
1634 reserves.priority AS priority,
1635 reserves.timestamp AS timestamp,
1636 biblioitems.biblioitemnumber AS biblioitemnumber,
1637 reserves.itemnumber AS itemnumber,
1638 reserves.reserve_id AS reserve_id,
1639 reserves.itemtype AS itemtype
1640 FROM reserves
1641 JOIN biblioitems USING (biblionumber)
1642 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1643 WHERE found IS NULL
1644 AND priority > 0
1645 AND item_level_request = 1
1646 AND itemnumber = ?
1647 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1648 AND suspend = 0
1649 ORDER BY priority
1651 my $sth = $dbh->prepare($item_level_target_query);
1652 $sth->execute($itemnumber, $lookahead||0);
1653 my @results;
1654 if ( my $data = $sth->fetchrow_hashref ) {
1655 push( @results, $data )
1656 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1658 return @results if @results;
1660 # check for title-level targeted match
1661 my $title_level_target_query = qq{
1662 SELECT reserves.biblionumber AS biblionumber,
1663 reserves.borrowernumber AS borrowernumber,
1664 reserves.reservedate AS reservedate,
1665 reserves.branchcode AS branchcode,
1666 reserves.cancellationdate AS cancellationdate,
1667 reserves.found AS found,
1668 reserves.reservenotes AS reservenotes,
1669 reserves.priority AS priority,
1670 reserves.timestamp AS timestamp,
1671 biblioitems.biblioitemnumber AS biblioitemnumber,
1672 reserves.itemnumber AS itemnumber,
1673 reserves.reserve_id AS reserve_id,
1674 reserves.itemtype AS itemtype
1675 FROM reserves
1676 JOIN biblioitems USING (biblionumber)
1677 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1678 WHERE found IS NULL
1679 AND priority > 0
1680 AND item_level_request = 0
1681 AND hold_fill_targets.itemnumber = ?
1682 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1683 AND suspend = 0
1684 ORDER BY priority
1686 $sth = $dbh->prepare($title_level_target_query);
1687 $sth->execute($itemnumber, $lookahead||0);
1688 @results = ();
1689 if ( my $data = $sth->fetchrow_hashref ) {
1690 push( @results, $data )
1691 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1693 return @results if @results;
1695 my $query = qq{
1696 SELECT reserves.biblionumber AS biblionumber,
1697 reserves.borrowernumber AS borrowernumber,
1698 reserves.reservedate AS reservedate,
1699 reserves.waitingdate AS waitingdate,
1700 reserves.branchcode AS branchcode,
1701 reserves.cancellationdate AS cancellationdate,
1702 reserves.found AS found,
1703 reserves.reservenotes AS reservenotes,
1704 reserves.priority AS priority,
1705 reserves.timestamp AS timestamp,
1706 reserves.itemnumber AS itemnumber,
1707 reserves.reserve_id AS reserve_id,
1708 reserves.itemtype AS itemtype
1709 FROM reserves
1710 WHERE reserves.biblionumber = ?
1711 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1712 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1713 AND suspend = 0
1714 ORDER BY priority
1716 $sth = $dbh->prepare($query);
1717 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1718 @results = ();
1719 while ( my $data = $sth->fetchrow_hashref ) {
1720 push( @results, $data )
1721 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1723 return @results;
1726 =head2 _koha_notify_reserve
1728 _koha_notify_reserve( $hold->reserve_id );
1730 Sends a notification to the patron that their hold has been filled (through
1731 ModReserveAffect, _not_ ModReserveFill)
1733 The letter code for this notice may be found using the following query:
1735 select distinct letter_code
1736 from message_transports
1737 inner join message_attributes using (message_attribute_id)
1738 where message_name = 'Hold_Filled'
1740 This will probably sipmly be 'HOLD', but because it is defined in the database,
1741 it is subject to addition or change.
1743 The following tables are availalbe witin the notice:
1745 branches
1746 borrowers
1747 biblio
1748 biblioitems
1749 reserves
1750 items
1752 =cut
1754 sub _koha_notify_reserve {
1755 my $reserve_id = shift;
1756 my $hold = Koha::Holds->find($reserve_id);
1757 my $borrowernumber = $hold->borrowernumber;
1759 my $patron = Koha::Patrons->find( $borrowernumber );
1761 # Try to get the borrower's email address
1762 my $to_address = $patron->notice_email_address;
1764 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1765 borrowernumber => $borrowernumber,
1766 message_name => 'Hold_Filled'
1767 } );
1769 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1771 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1773 my %letter_params = (
1774 module => 'reserves',
1775 branchcode => $hold->branchcode,
1776 lang => $patron->lang,
1777 tables => {
1778 'branches' => $library,
1779 'borrowers' => $patron->unblessed,
1780 'biblio' => $hold->biblionumber,
1781 'biblioitems' => $hold->biblionumber,
1782 'reserves' => $hold->unblessed,
1783 'items' => $hold->itemnumber,
1787 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.
1788 my $send_notification = sub {
1789 my ( $mtt, $letter_code ) = (@_);
1790 return unless defined $letter_code;
1791 $letter_params{letter_code} = $letter_code;
1792 $letter_params{message_transport_type} = $mtt;
1793 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1794 unless ($letter) {
1795 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1796 return;
1799 C4::Letters::EnqueueLetter( {
1800 letter => $letter,
1801 borrowernumber => $borrowernumber,
1802 from_address => $admin_email_address,
1803 message_transport_type => $mtt,
1804 } );
1807 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1808 next if (
1809 ( $mtt eq 'email' and not $to_address ) # No email address
1810 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1811 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1814 &$send_notification($mtt, $letter_code);
1815 $notification_sent++;
1817 #Making sure that a print notification is sent if no other transport types can be utilized.
1818 if (! $notification_sent) {
1819 &$send_notification('print', 'HOLD');
1824 =head2 _ShiftPriorityByDateAndPriority
1826 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1828 This increments the priority of all reserves after the one
1829 with either the lowest date after C<$reservedate>
1830 or the lowest priority after C<$priority>.
1832 It effectively makes room for a new reserve to be inserted with a certain
1833 priority, which is returned.
1835 This is most useful when the reservedate can be set by the user. It allows
1836 the new reserve to be placed before other reserves that have a later
1837 reservedate. Since priority also is set by the form in reserves/request.pl
1838 the sub accounts for that too.
1840 =cut
1842 sub _ShiftPriorityByDateAndPriority {
1843 my ( $biblio, $resdate, $new_priority ) = @_;
1845 my $dbh = C4::Context->dbh;
1846 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1847 my $sth = $dbh->prepare( $query );
1848 $sth->execute( $biblio, $resdate, $new_priority );
1849 my $min_priority = $sth->fetchrow;
1850 # if no such matches are found, $new_priority remains as original value
1851 $new_priority = $min_priority if ( $min_priority );
1853 # Shift the priority up by one; works in conjunction with the next SQL statement
1854 $query = "UPDATE reserves
1855 SET priority = priority+1
1856 WHERE biblionumber = ?
1857 AND borrowernumber = ?
1858 AND reservedate = ?
1859 AND found IS NULL";
1860 my $sth_update = $dbh->prepare( $query );
1862 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1863 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1864 $sth = $dbh->prepare( $query );
1865 $sth->execute( $new_priority, $biblio );
1866 while ( my $row = $sth->fetchrow_hashref ) {
1867 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1870 return $new_priority; # so the caller knows what priority they wind up receiving
1873 =head2 MoveReserve
1875 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1877 Use when checking out an item to handle reserves
1878 If $cancelreserve boolean is set to true, it will remove existing reserve
1880 =cut
1882 sub MoveReserve {
1883 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1885 $cancelreserve //= 0;
1887 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1888 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1889 return unless $res;
1891 my $biblionumber = $res->{biblionumber};
1893 if ($res->{borrowernumber} == $borrowernumber) {
1894 ModReserveFill($res);
1896 else {
1897 # warn "Reserved";
1898 # The item is reserved by someone else.
1899 # Find this item in the reserves
1901 my $borr_res = Koha::Holds->search({
1902 borrowernumber => $borrowernumber,
1903 biblionumber => $biblionumber,
1905 order_by => 'priority'
1906 })->next();
1908 if ( $borr_res ) {
1909 # The item is reserved by the current patron
1910 ModReserveFill($borr_res->unblessed);
1913 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1914 RevertWaitingStatus({ itemnumber => $itemnumber });
1916 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1917 my $hold = Koha::Holds->find( $res->{reserve_id} );
1918 $hold->cancel;
1923 =head2 MergeHolds
1925 MergeHolds($dbh,$to_biblio, $from_biblio);
1927 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1929 =cut
1931 sub MergeHolds {
1932 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1933 my $sth = $dbh->prepare(
1934 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1936 $sth->execute($from_biblio);
1937 if ( my $data = $sth->fetchrow_hashref() ) {
1939 # holds exist on old record, if not we don't need to do anything
1940 $sth = $dbh->prepare(
1941 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1942 $sth->execute( $to_biblio, $from_biblio );
1944 # Reorder by date
1945 # don't reorder those already waiting
1947 $sth = $dbh->prepare(
1948 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1950 my $upd_sth = $dbh->prepare(
1951 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1952 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1954 $sth->execute( $to_biblio, 'W', 'T' );
1955 my $priority = 1;
1956 while ( my $reserve = $sth->fetchrow_hashref() ) {
1957 $upd_sth->execute(
1958 $priority, $to_biblio,
1959 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1960 $reserve->{'itemnumber'}
1962 $priority++;
1967 =head2 RevertWaitingStatus
1969 RevertWaitingStatus({ itemnumber => $itemnumber });
1971 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1973 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1974 item level hold, even if it was only a bibliolevel hold to
1975 begin with. This is because we can no longer know if a hold
1976 was item-level or bib-level after a hold has been set to
1977 waiting status.
1979 =cut
1981 sub RevertWaitingStatus {
1982 my ( $params ) = @_;
1983 my $itemnumber = $params->{'itemnumber'};
1985 return unless ( $itemnumber );
1987 my $dbh = C4::Context->dbh;
1989 ## Get the waiting reserve we want to revert
1990 my $query = "
1991 SELECT * FROM reserves
1992 WHERE itemnumber = ?
1993 AND found IS NOT NULL
1995 my $sth = $dbh->prepare( $query );
1996 $sth->execute( $itemnumber );
1997 my $reserve = $sth->fetchrow_hashref();
1999 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
2001 ## Increment the priority of all other non-waiting
2002 ## reserves for this bib record
2003 $query = "
2004 UPDATE reserves
2006 priority = priority + 1
2007 WHERE
2008 biblionumber = ?
2010 priority > 0
2012 $sth = $dbh->prepare( $query );
2013 $sth->execute( $reserve->{'biblionumber'} );
2015 $hold->set(
2017 priority => 1,
2018 found => undef,
2019 waitingdate => undef,
2020 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2022 )->store();
2024 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2026 return $hold;
2029 =head2 ReserveSlip
2031 ReserveSlip(
2033 branchcode => $branchcode,
2034 borrowernumber => $borrowernumber,
2035 biblionumber => $biblionumber,
2036 [ itemnumber => $itemnumber, ]
2037 [ barcode => $barcode, ]
2041 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2043 The letter code will be HOLD_SLIP, and the following tables are
2044 available within the slip:
2046 reserves
2047 branches
2048 borrowers
2049 biblio
2050 biblioitems
2051 items
2053 =cut
2055 sub ReserveSlip {
2056 my ($args) = @_;
2057 my $branchcode = $args->{branchcode};
2058 my $borrowernumber = $args->{borrowernumber};
2059 my $biblionumber = $args->{biblionumber};
2060 my $itemnumber = $args->{itemnumber};
2061 my $barcode = $args->{barcode};
2064 my $patron = Koha::Patrons->find($borrowernumber);
2066 my $hold;
2067 if ($itemnumber || $barcode ) {
2068 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2070 $hold = Koha::Holds->search(
2072 biblionumber => $biblionumber,
2073 borrowernumber => $borrowernumber,
2074 itemnumber => $itemnumber
2076 )->next;
2078 else {
2079 $hold = Koha::Holds->search(
2081 biblionumber => $biblionumber,
2082 borrowernumber => $borrowernumber
2084 )->next;
2087 return unless $hold;
2088 my $reserve = $hold->unblessed;
2090 return C4::Letters::GetPreparedLetter (
2091 module => 'circulation',
2092 letter_code => 'HOLD_SLIP',
2093 branchcode => $branchcode,
2094 lang => $patron->lang,
2095 tables => {
2096 'reserves' => $reserve,
2097 'branches' => $reserve->{branchcode},
2098 'borrowers' => $reserve->{borrowernumber},
2099 'biblio' => $reserve->{biblionumber},
2100 'biblioitems' => $reserve->{biblionumber},
2101 'items' => $reserve->{itemnumber},
2106 =head2 GetReservesControlBranch
2108 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2110 Return the branchcode to be used to determine which reserves
2111 policy applies to a transaction.
2113 C<$item> is a hashref for an item. Only 'homebranch' is used.
2115 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2117 =cut
2119 sub GetReservesControlBranch {
2120 my ( $item, $borrower ) = @_;
2122 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2124 my $branchcode =
2125 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2126 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2127 : undef;
2129 return $branchcode;
2132 =head2 CalculatePriority
2134 my $p = CalculatePriority($biblionumber, $resdate);
2136 Calculate priority for a new reserve on biblionumber, placing it at
2137 the end of the line of all holds whose start date falls before
2138 the current system time and that are neither on the hold shelf
2139 or in transit.
2141 The reserve date parameter is optional; if it is supplied, the
2142 priority is based on the set of holds whose start date falls before
2143 the parameter value.
2145 After calculation of this priority, it is recommended to call
2146 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2147 AddReserves.
2149 =cut
2151 sub CalculatePriority {
2152 my ( $biblionumber, $resdate ) = @_;
2154 my $sql = q{
2155 SELECT COUNT(*) FROM reserves
2156 WHERE biblionumber = ?
2157 AND priority > 0
2158 AND (found IS NULL OR found = '')
2160 #skip found==W or found==T (waiting or transit holds)
2161 if( $resdate ) {
2162 $sql.= ' AND ( reservedate <= ? )';
2164 else {
2165 $sql.= ' AND ( reservedate < NOW() )';
2167 my $dbh = C4::Context->dbh();
2168 my @row = $dbh->selectrow_array(
2169 $sql,
2170 undef,
2171 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2174 return @row ? $row[0]+1 : 1;
2177 =head2 IsItemOnHoldAndFound
2179 my $bool = IsItemFoundHold( $itemnumber );
2181 Returns true if the item is currently on hold
2182 and that hold has a non-null found status ( W, T, etc. )
2184 =cut
2186 sub IsItemOnHoldAndFound {
2187 my ($itemnumber) = @_;
2189 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2191 my $found = $rs->count(
2193 itemnumber => $itemnumber,
2194 found => { '!=' => undef }
2198 return $found;
2201 =head2 GetMaxPatronHoldsForRecord
2203 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2205 For multiple holds on a given record for a given patron, the max
2206 number of record level holds that a patron can be placed is the highest
2207 value of the holds_per_record rule for each item if the record for that
2208 patron. This subroutine finds and returns the highest holds_per_record
2209 rule value for a given patron id and record id.
2211 =cut
2213 sub GetMaxPatronHoldsForRecord {
2214 my ( $borrowernumber, $biblionumber ) = @_;
2216 my $patron = Koha::Patrons->find($borrowernumber);
2217 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2219 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2221 my $categorycode = $patron->categorycode;
2222 my $branchcode;
2223 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2225 my $max = 0;
2226 foreach my $item (@items) {
2227 my $itemtype = $item->effective_itemtype();
2229 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2231 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2232 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2233 $max = $holds_per_record if $holds_per_record > $max;
2236 return $max;
2239 =head2 GetHoldRule
2241 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2243 Returns the matching hold related issuingrule fields for a given
2244 patron category, itemtype, and library.
2246 =cut
2248 sub GetHoldRule {
2249 my ( $categorycode, $itemtype, $branchcode ) = @_;
2251 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2253 itemtype => $itemtype,
2254 categorycode => $categorycode,
2255 branchcode => $branchcode,
2256 rule_name => 'reservesallowed',
2257 order_by => {
2258 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2263 my $rules;
2264 if ( $reservesallowed ) {
2265 $rules->{reservesallowed} = $reservesallowed->rule_value;
2266 $rules->{itemtype} = $reservesallowed->itemtype;
2267 $rules->{categorycode} = $reservesallowed->categorycode;
2268 $rules->{branchcode} = $reservesallowed->branchcode;
2271 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2273 itemtype => $itemtype,
2274 categorycode => $categorycode,
2275 branchcode => $branchcode,
2276 rules => ['holds_per_record', 'holds_per_day'],
2277 order_by => {
2278 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2282 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2283 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2285 return $rules;
2288 =head1 AUTHOR
2290 Koha Development Team <http://koha-community.org/>
2292 =cut