Bug 7607: (follow-up) Address OPAC and limits
[koha.git] / C4 / Reserves.pm
blobc5a8d4ab532fcece39d0c1d325ec14373fc5a01e
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};
188 my $non_priority = $params->{non_priority};
190 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
191 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
193 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
195 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
196 # of the document, we force the value $priority and $found .
197 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
198 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
200 if (
201 # If item is already checked out, it cannot be set waiting
202 !$item->onloan
204 # The item can't be waiting if it needs a transfer
205 && $item->holdingbranch eq $branch
207 # Similarly, if in transit it can't be waiting
208 && !$item->get_transfer
210 # If we can't hold damaged items, and it is damaged, it can't be waiting
211 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
213 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
214 && !$item->current_holds->count )
216 $priority = 0;
217 $found = 'W';
221 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
223 # Make room in reserves for this before those of a later reserve date
224 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
227 my $waitingdate;
229 # If the reserv had the waiting status, we had the value of the resdate
230 if ( $found && $found eq 'W' ) {
231 $waitingdate = $resdate;
234 # Don't add itemtype limit if specific item is selected
235 $itemtype = undef if $checkitem;
237 # updates take place here
238 my $hold = Koha::Hold->new(
240 borrowernumber => $borrowernumber,
241 biblionumber => $biblionumber,
242 reservedate => $resdate,
243 branchcode => $branch,
244 priority => $priority,
245 reservenotes => $notes,
246 itemnumber => $checkitem,
247 found => $found,
248 waitingdate => $waitingdate,
249 expirationdate => $expdate,
250 itemtype => $itemtype,
251 item_level_hold => $checkitem ? 1 : 0,
252 non_priority => $non_priority ? 1 : 0,
254 )->store();
255 $hold->set_waiting() if $found && $found eq 'W';
257 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
258 if C4::Context->preference('HoldsLog');
260 my $reserve_id = $hold->id();
262 # add a reserve fee if needed
263 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
264 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
265 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
268 _FixPriority({ biblionumber => $biblionumber});
270 # Send e-mail to librarian if syspref is active
271 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
272 my $patron = Koha::Patrons->find( $borrowernumber );
273 my $library = $patron->library;
274 if ( my $letter = C4::Letters::GetPreparedLetter (
275 module => 'reserves',
276 letter_code => 'HOLDPLACED',
277 branchcode => $branch,
278 lang => $patron->lang,
279 tables => {
280 'branches' => $library->unblessed,
281 'borrowers' => $patron->unblessed,
282 'biblio' => $biblionumber,
283 'biblioitems' => $biblionumber,
284 'items' => $checkitem,
285 'reserves' => $hold->unblessed,
287 ) ) {
289 my $branch_email_address = $library->inbound_email_address;
291 C4::Letters::EnqueueLetter(
293 letter => $letter,
294 borrowernumber => $borrowernumber,
295 message_transport_type => 'email',
296 to_address => $branch_email_address,
302 Koha::Plugins->call('after_hold_create', $hold);
304 return $reserve_id;
307 =head2 CanBookBeReserved
309 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
310 if ($canReserve eq 'OK') { #We can reserve this Item! }
312 $params are passed directly through to CanItemBeReserved
314 See CanItemBeReserved() for possible return values.
316 =cut
318 sub CanBookBeReserved{
319 my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
321 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
322 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
323 && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
324 return { status =>'alreadypossession' };
327 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
328 #get items linked via host records
329 my @hostitems = get_hostitemnumbers_of($biblionumber);
330 if (@hostitems){
331 push (@itemnumbers, @hostitems);
334 my $canReserve = { status => '' };
335 foreach my $itemnumber (@itemnumbers) {
336 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode, $params );
337 return { status => 'OK' } if $canReserve->{status} eq 'OK';
339 return $canReserve;
342 =head2 CanItemBeReserved
344 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
345 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
347 current params are 'ignore_found_holds' - if true holds that have been trapped are not counted
348 toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
349 current checkout against the high holds threshold
351 @RETURNS { status => OK }, if the Item can be reserved.
352 { status => ageRestricted }, if the Item is age restricted for this borrower.
353 { status => damaged }, if the Item is damaged.
354 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
355 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
356 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
357 { status => notReservable }, if holds on this item are not allowed
358 { status => libraryNotFound }, if given branchcode is not an existing library
359 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
360 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
361 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
363 =cut
365 sub CanItemBeReserved {
366 my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
368 my $dbh = C4::Context->dbh;
369 my $ruleitemtype; # itemtype of the matching issuing rule
370 my $allowedreserves = 0; # Total number of holds allowed across all records
371 my $holds_per_record = 1; # Total number of holds allowed for this one given record
372 my $holds_per_day; # Default to unlimited
374 # we retrieve borrowers and items informations #
375 # item->{itype} will come for biblioitems if necessery
376 my $item = Koha::Items->find($itemnumber);
377 my $biblio = $item->biblio;
378 my $patron = Koha::Patrons->find( $borrowernumber );
379 my $borrower = $patron->unblessed;
381 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
382 return { status =>'damaged' }
383 if ( $item->damaged
384 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
386 # Check for the age restriction
387 my ( $ageRestriction, $daysToAgeRestriction ) =
388 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
389 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
391 # Check that the patron doesn't have an item level hold on this item already
392 return { status =>'itemAlreadyOnHold' }
393 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
395 # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
396 if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
397 && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
398 return { status =>'alreadypossession' };
401 my $controlbranch = C4::Context->preference('ReservesControlBranch');
403 my $querycount = q{
404 SELECT count(*) AS count
405 FROM reserves
406 LEFT JOIN items USING (itemnumber)
407 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
408 LEFT JOIN borrowers USING (borrowernumber)
409 WHERE borrowernumber = ?
412 my $branchcode = "";
413 my $branchfield = "reserves.branchcode";
415 if ( $controlbranch eq "ItemHomeLibrary" ) {
416 $branchfield = "items.homebranch";
417 $branchcode = $item->homebranch;
419 elsif ( $controlbranch eq "PatronLibrary" ) {
420 $branchfield = "borrowers.branchcode";
421 $branchcode = $borrower->{branchcode};
424 # we retrieve rights
425 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
426 $ruleitemtype = $rights->{itemtype};
427 $allowedreserves = $rights->{reservesallowed} // $allowedreserves;
428 $holds_per_record = $rights->{holds_per_record} // $holds_per_record;
429 $holds_per_day = $rights->{holds_per_day};
431 else {
432 $ruleitemtype = undef;
435 my $search_params = {
436 borrowernumber => $borrowernumber,
437 biblionumber => $item->biblionumber,
439 $search_params->{found} = undef if $params->{ignore_found_holds};
441 my $holds = Koha::Holds->search($search_params);
442 if ( defined $holds_per_record && $holds_per_record ne ''
443 && $holds->count() >= $holds_per_record ) {
444 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
447 my $today_holds = Koha::Holds->search({
448 borrowernumber => $borrowernumber,
449 reservedate => dt_from_string->date
452 if ( defined $holds_per_day && $holds_per_day ne ''
453 && $today_holds->count() >= $holds_per_day )
455 return { status => 'tooManyReservesToday', limit => $holds_per_day };
458 # we retrieve count
460 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
462 # If using item-level itypes, fall back to the record
463 # level itemtype if the hold has no associated item
464 $querycount .=
465 C4::Context->preference('item-level_itypes')
466 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
467 : " AND biblioitems.itemtype = ?"
468 if defined $ruleitemtype;
470 my $sthcount = $dbh->prepare($querycount);
472 if ( defined $ruleitemtype ) {
473 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
475 else {
476 $sthcount->execute( $borrowernumber, $branchcode );
479 my $reservecount = "0";
480 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
481 $reservecount = $rowcount->{count};
484 # we check if it's ok or not
485 if ( defined $allowedreserves && $allowedreserves ne ''
486 && $reservecount >= $allowedreserves ) {
487 return { status => 'tooManyReserves', limit => $allowedreserves };
490 # Now we need to check hold limits by patron category
491 my $rule = Koha::CirculationRules->get_effective_rule(
493 categorycode => $borrower->{categorycode},
494 branchcode => $branchcode,
495 rule_name => 'max_holds',
498 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
499 my $total_holds_count = Koha::Holds->search(
501 borrowernumber => $borrower->{borrowernumber}
503 )->count();
505 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
508 my $reserves_control_branch =
509 GetReservesControlBranch( $item->unblessed(), $borrower );
510 my $branchitemrule =
511 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
513 if ( $branchitemrule->{holdallowed} == 0 ) {
514 return { status => 'notReservable' };
517 if ( $branchitemrule->{holdallowed} == 1
518 && $borrower->{branchcode} ne $item->homebranch )
520 return { status => 'cannotReserveFromOtherBranches' };
523 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
524 if ( $branchitemrule->{holdallowed} == 3) {
525 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
526 return { status => 'branchNotInHoldGroup' };
530 # If reservecount is ok, we check item branch if IndependentBranches is ON
531 # and canreservefromotherbranches is OFF
532 if ( C4::Context->preference('IndependentBranches')
533 and !C4::Context->preference('canreservefromotherbranches') )
535 if ( $item->homebranch ne $borrower->{branchcode} ) {
536 return { status => 'cannotReserveFromOtherBranches' };
540 if ($pickup_branchcode) {
541 my $destination = Koha::Libraries->find({
542 branchcode => $pickup_branchcode,
545 unless ($destination) {
546 return { status => 'libraryNotFound' };
548 unless ($destination->pickup_location) {
549 return { status => 'libraryNotPickupLocation' };
551 unless ($item->can_be_transferred({ to => $destination })) {
552 return { status => 'cannotBeTransferred' };
554 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
555 return { status => 'pickupNotInHoldGroup' };
557 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
558 return { status => 'pickupNotInHoldGroup' };
562 return { status => 'OK' };
565 =head2 CanReserveBeCanceledFromOpac
567 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
569 returns 1 if reserve can be cancelled by user from OPAC.
570 First check if reserve belongs to user, next checks if reserve is not in
571 transfer or waiting status
573 =cut
575 sub CanReserveBeCanceledFromOpac {
576 my ($reserve_id, $borrowernumber) = @_;
578 return unless $reserve_id and $borrowernumber;
579 my $reserve = Koha::Holds->find($reserve_id);
581 return 0 unless $reserve->borrowernumber == $borrowernumber;
582 return $reserve->is_cancelable_from_opac;
585 =head2 GetOtherReserves
587 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
589 Check queued list of this document and check if this document must be transferred
591 =cut
593 sub GetOtherReserves {
594 my ($itemnumber) = @_;
595 my $messages;
596 my $nextreservinfo;
597 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
598 if ($checkreserves) {
599 my $item = Koha::Items->find($itemnumber);
600 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
601 $messages->{'transfert'} = $checkreserves->{'branchcode'};
602 #minus priorities of others reservs
603 ModReserveMinusPriority(
604 $itemnumber,
605 $checkreserves->{'reserve_id'},
608 #launch the subroutine dotransfer
609 C4::Items::ModItemTransfer(
610 $itemnumber,
611 $item->holdingbranch,
612 $checkreserves->{'branchcode'},
613 'Reserve'
618 #step 2b : case of a reservation on the same branch, set the waiting status
619 else {
620 $messages->{'waiting'} = 1;
621 ModReserveMinusPriority(
622 $itemnumber,
623 $checkreserves->{'reserve_id'},
625 ModReserveStatus($itemnumber,'W');
628 $nextreservinfo = $checkreserves;
631 return ( $messages, $nextreservinfo );
634 =head2 ChargeReserveFee
636 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
638 Charge the fee for a reserve (if $fee > 0)
640 =cut
642 sub ChargeReserveFee {
643 my ( $borrowernumber, $fee, $title ) = @_;
644 return if !$fee || $fee == 0; # the last test is needed to include 0.00
645 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
647 amount => $fee,
648 description => $title,
649 note => undef,
650 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
651 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
652 interface => C4::Context->interface,
653 invoice_type => undef,
654 type => 'RESERVE',
655 item_id => undef
660 =head2 GetReserveFee
662 $fee = GetReserveFee( $borrowernumber, $biblionumber );
664 Calculate the fee for a reserve (if applicable).
666 =cut
668 sub GetReserveFee {
669 my ( $borrowernumber, $biblionumber ) = @_;
670 my $borquery = qq{
671 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
673 my $issue_qry = qq{
674 SELECT COUNT(*) FROM items
675 LEFT JOIN issues USING (itemnumber)
676 WHERE items.biblionumber=? AND issues.issue_id IS NULL
678 my $holds_qry = qq{
679 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
682 my $dbh = C4::Context->dbh;
683 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
684 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
685 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
686 # This is a reconstruction of the old code:
687 # Compare number of items with items issued, and optionally check holds
688 # If not all items are issued and there are no holds: charge no fee
689 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
690 my ( $notissued, $reserved );
691 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
692 ( $biblionumber ) );
693 if( $notissued ) {
694 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
695 ( $biblionumber, $borrowernumber ) );
696 $fee = 0 if $reserved == 0;
699 return $fee;
702 =head2 GetReserveStatus
704 $reservestatus = GetReserveStatus($itemnumber);
706 Takes an itemnumber and returns the status of the reserve placed on it.
707 If several reserves exist, the reserve with the lower priority is given.
709 =cut
711 ## FIXME: I don't think this does what it thinks it does.
712 ## It only ever checks the first reserve result, even though
713 ## multiple reserves for that bib can have the itemnumber set
714 ## the sub is only used once in the codebase.
715 sub GetReserveStatus {
716 my ($itemnumber) = @_;
718 my $dbh = C4::Context->dbh;
720 my ($sth, $found, $priority);
721 if ( $itemnumber ) {
722 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
723 $sth->execute($itemnumber);
724 ($found, $priority) = $sth->fetchrow_array;
727 if(defined $found) {
728 return 'Waiting' if $found eq 'W' and $priority == 0;
729 return 'Processing' if $found eq 'P';
730 return 'Finished' if $found eq 'F';
733 return 'Reserved' if defined $priority && $priority > 0;
735 return ''; # empty string here will remove need for checking undef, or less log lines
738 =head2 CheckReserves
740 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
741 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
742 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
744 Find a book in the reserves.
746 C<$itemnumber> is the book's item number.
747 C<$lookahead> is the number of days to look in advance for future reserves.
749 As I understand it, C<&CheckReserves> looks for the given item in the
750 reserves. If it is found, that's a match, and C<$status> is set to
751 C<Waiting>.
753 Otherwise, it finds the most important item in the reserves with the
754 same biblio number as this book (I'm not clear on this) and returns it
755 with C<$status> set to C<Reserved>.
757 C<&CheckReserves> returns a two-element list:
759 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
761 C<$reserve> is the reserve item that matched. It is a
762 reference-to-hash whose keys are mostly the fields of the reserves
763 table in the Koha database.
765 =cut
767 sub CheckReserves {
768 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
769 my $dbh = C4::Context->dbh;
770 my $sth;
771 my $select;
772 if (C4::Context->preference('item-level_itypes')){
773 $select = "
774 SELECT items.biblionumber,
775 items.biblioitemnumber,
776 itemtypes.notforloan,
777 items.notforloan AS itemnotforloan,
778 items.itemnumber,
779 items.damaged,
780 items.homebranch,
781 items.holdingbranch
782 FROM items
783 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
784 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
787 else {
788 $select = "
789 SELECT items.biblionumber,
790 items.biblioitemnumber,
791 itemtypes.notforloan,
792 items.notforloan AS itemnotforloan,
793 items.itemnumber,
794 items.damaged,
795 items.homebranch,
796 items.holdingbranch
797 FROM items
798 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
799 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
803 if ($item) {
804 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
805 $sth->execute($item);
807 else {
808 $sth = $dbh->prepare("$select WHERE barcode = ?");
809 $sth->execute($barcode);
811 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
812 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
813 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
815 return unless $itemnumber; # bail if we got nothing.
816 # if item is not for loan it cannot be reserved either.....
817 # except where items.notforloan < 0 : This indicates the item is holdable.
819 my @SkipHoldTrapOnNotForLoanValue = split( '|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
820 return if @SkipHoldTrapOnNotForLoanValue && grep( $notforloan_per_item, @SkipHoldTrapOnNotForLoanValue );
822 my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
823 return if $dont_trap or $notforloan_per_itemtype;
825 # Find this item in the reserves
826 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
828 # $priority and $highest are used to find the most important item
829 # in the list returned by &_Findgroupreserve. (The lower $priority,
830 # the more important the item.)
831 # $highest is the most important item we've seen so far.
832 my $highest;
834 if (scalar @reserves) {
835 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
836 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
837 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
839 my $priority = 10000000;
840 foreach my $res (@reserves) {
841 if ( $res->{'itemnumber'} && $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
842 if ($res->{'found'} eq 'W') {
843 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
844 } elsif ($res->{'found'} eq 'P') {
845 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
846 } else {
847 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
849 } else {
850 my $patron;
851 my $item;
852 my $local_hold_match;
854 if ($LocalHoldsPriority) {
855 $patron = Koha::Patrons->find( $res->{borrowernumber} );
856 $item = Koha::Items->find($itemnumber);
858 unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
859 my $local_holds_priority_item_branchcode =
860 $item->$LocalHoldsPriorityItemControl;
861 my $local_holds_priority_patron_branchcode =
862 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
863 ? $res->{branchcode}
864 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
865 ? $patron->branchcode
866 : undef;
867 $local_hold_match =
868 $local_holds_priority_item_branchcode eq
869 $local_holds_priority_patron_branchcode;
873 # See if this item is more important than what we've got so far
874 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
875 $item ||= Koha::Items->find($itemnumber);
876 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
877 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
878 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
879 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
880 next if ($branchitemrule->{'holdallowed'} == 0);
881 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
882 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
883 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
884 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
885 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
886 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
887 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
888 next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
889 $priority = $res->{'priority'};
890 $highest = $res;
891 last if $local_hold_match;
897 # If we get this far, then no exact match was found.
898 # We return the most important (i.e. next) reservation.
899 if ($highest) {
900 $highest->{'itemnumber'} = $item;
901 return ( "Reserved", $highest, \@reserves );
904 return ( '' );
907 =head2 CancelExpiredReserves
909 CancelExpiredReserves();
911 Cancels all reserves with an expiration date from before today.
913 =cut
915 sub CancelExpiredReserves {
916 my $cancellation_reason = shift;
917 my $today = dt_from_string();
918 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
919 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
921 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
922 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
923 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
925 # FIXME To move to Koha::Holds->search_expired (?)
926 my $holds = Koha::Holds->search( $params );
928 while ( my $hold = $holds->next ) {
929 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
931 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
933 my $cancel_params = {};
934 $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
935 if ( defined($hold->found) && $hold->found eq 'W' ) {
936 $cancel_params->{charge_cancel_fee} = 1;
938 $hold->cancel( $cancel_params );
942 =head2 AutoUnsuspendReserves
944 AutoUnsuspendReserves();
946 Unsuspends all suspended reserves with a suspend_until date from before today.
948 =cut
950 sub AutoUnsuspendReserves {
951 my $today = dt_from_string();
953 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
955 map { $_->resume() } @holds;
958 =head2 ModReserve
960 ModReserve({ rank => $rank,
961 reserve_id => $reserve_id,
962 branchcode => $branchcode
963 [, itemnumber => $itemnumber ]
964 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
967 Change a hold request's priority or cancel it.
969 C<$rank> specifies the effect of the change. If C<$rank>
970 is 'W' or 'n', nothing happens. This corresponds to leaving a
971 request alone when changing its priority in the holds queue
972 for a bib.
974 If C<$rank> is 'del', the hold request is cancelled.
976 If C<$rank> is an integer greater than zero, the priority of
977 the request is set to that value. Since priority != 0 means
978 that the item is not waiting on the hold shelf, setting the
979 priority to a non-zero value also sets the request's found
980 status and waiting date to NULL.
982 The optional C<$itemnumber> parameter is used only when
983 C<$rank> is a non-zero integer; if supplied, the itemnumber
984 of the hold request is set accordingly; if omitted, the itemnumber
985 is cleared.
987 B<FIXME:> Note that the forgoing can have the effect of causing
988 item-level hold requests to turn into title-level requests. This
989 will be fixed once reserves has separate columns for requested
990 itemnumber and supplying itemnumber.
992 =cut
994 sub ModReserve {
995 my ( $params ) = @_;
997 my $rank = $params->{'rank'};
998 my $reserve_id = $params->{'reserve_id'};
999 my $branchcode = $params->{'branchcode'};
1000 my $itemnumber = $params->{'itemnumber'};
1001 my $suspend_until = $params->{'suspend_until'};
1002 my $borrowernumber = $params->{'borrowernumber'};
1003 my $biblionumber = $params->{'biblionumber'};
1004 my $cancellation_reason = $params->{'cancellation_reason'};
1006 return if $rank eq "W";
1007 return if $rank eq "n";
1009 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1011 my $hold;
1012 unless ( $reserve_id ) {
1013 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1014 return unless $holds->count; # FIXME Should raise an exception
1015 $hold = $holds->next;
1016 $reserve_id = $hold->reserve_id;
1019 $hold ||= Koha::Holds->find($reserve_id);
1021 if ( $rank eq "del" ) {
1022 $hold->cancel({ cancellation_reason => $cancellation_reason });
1024 elsif ($rank =~ /^\d+/ and $rank > 0) {
1025 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1026 if C4::Context->preference('HoldsLog');
1028 my $properties = {
1029 priority => $rank,
1030 branchcode => $branchcode,
1031 itemnumber => $itemnumber,
1032 found => undef,
1033 waitingdate => undef
1035 if (exists $params->{reservedate}) {
1036 $properties->{reservedate} = $params->{reservedate} || undef;
1038 if (exists $params->{expirationdate}) {
1039 $properties->{expirationdate} = $params->{expirationdate} || undef;
1042 $hold->set($properties)->store();
1044 if ( defined( $suspend_until ) ) {
1045 if ( $suspend_until ) {
1046 $suspend_until = eval { dt_from_string( $suspend_until ) };
1047 $hold->suspend_hold( $suspend_until );
1048 } else {
1049 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1050 # If the hold is not suspended, this does nothing.
1051 $hold->set( { suspend_until => undef } )->store();
1055 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1059 =head2 ModReserveFill
1061 &ModReserveFill($reserve);
1063 Fill a reserve. If I understand this correctly, this means that the
1064 reserved book has been found and given to the patron who reserved it.
1066 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1067 whose keys are fields from the reserves table in the Koha database.
1069 =cut
1071 sub ModReserveFill {
1072 my ($res) = @_;
1073 my $reserve_id = $res->{'reserve_id'};
1075 my $hold = Koha::Holds->find($reserve_id);
1076 # get the priority on this record....
1077 my $priority = $hold->priority;
1079 # update the hold statuses, no need to store it though, we will be deleting it anyway
1080 $hold->set(
1082 found => 'F',
1083 priority => 0,
1087 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1088 if C4::Context->preference('HoldsLog');
1090 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1091 Koha::Old::Hold->new( $hold->unblessed() )->store();
1093 $hold->delete();
1095 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1096 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1097 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1100 # now fix the priority on the others (if the priority wasn't
1101 # already sorted!)....
1102 unless ( $priority == 0 ) {
1103 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1107 =head2 ModReserveStatus
1109 &ModReserveStatus($itemnumber, $newstatus);
1111 Update the reserve status for the active (priority=0) reserve.
1113 $itemnumber is the itemnumber the reserve is on
1115 $newstatus is the new status.
1117 =cut
1119 sub ModReserveStatus {
1121 #first : check if we have a reservation for this item .
1122 my ($itemnumber, $newstatus) = @_;
1123 my $dbh = C4::Context->dbh;
1125 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1126 my $sth_set = $dbh->prepare($query);
1127 $sth_set->execute( $newstatus, $itemnumber );
1129 my $item = Koha::Items->find($itemnumber);
1130 if ( $item->location && $item->location eq 'CART'
1131 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1132 && $newstatus ) {
1133 CartToShelf( $itemnumber );
1137 =head2 ModReserveAffect
1139 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1141 This function affect an item and a status for a given reserve, either fetched directly
1142 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1143 is given, only first reserve returned is affected, which is ok for anything but
1144 multi-item holds.
1146 if $transferToDo is not set, then the status is set to "Waiting" as well.
1147 otherwise, a transfer is on the way, and the end of the transfer will
1148 take care of the waiting status
1150 =cut
1152 sub ModReserveAffect {
1153 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1154 my $dbh = C4::Context->dbh;
1156 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1157 # attached to $itemnumber
1158 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1159 $sth->execute($itemnumber);
1160 my ($biblionumber) = $sth->fetchrow;
1162 # get request - need to find out if item is already
1163 # waiting in order to not send duplicate hold filled notifications
1165 my $hold;
1166 # Find hold by id if we have it
1167 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1168 # Find item level hold for this item if there is one
1169 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1170 # Find record level hold if there is no item level hold
1171 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1173 return unless $hold;
1175 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1177 $hold->itemnumber($itemnumber);
1179 if ($transferToDo) {
1180 $hold->set_transfer();
1181 } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1182 && C4::Context->interface eq 'sip'
1183 && !$already_on_shelf) {
1184 $hold->set_processing();
1185 } else {
1186 $hold->set_waiting($desk_id);
1187 _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1188 my $transfers = Koha::Item::Transfers->search({
1189 itemnumber => $itemnumber,
1190 datearrived => undef
1192 while( my $transfer = $transfers->next ){
1193 $transfer->datearrived( dt_from_string() )->store;
1198 _FixPriority( { biblionumber => $biblionumber } );
1199 my $item = Koha::Items->find($itemnumber);
1200 if ( $item->location && $item->location eq 'CART'
1201 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1202 CartToShelf( $itemnumber );
1205 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1206 if C4::Context->preference('HoldsLog');
1208 return;
1211 =head2 ModReserveCancelAll
1213 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1215 function to cancel reserv,check other reserves, and transfer document if it's necessary
1217 =cut
1219 sub ModReserveCancelAll {
1220 my $messages;
1221 my $nextreservinfo;
1222 my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1224 #step 1 : cancel the reservation
1225 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1226 return unless $holds->count;
1227 $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1229 #step 2 launch the subroutine of the others reserves
1230 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1232 return ( $messages, $nextreservinfo->{borrowernumber} );
1235 =head2 ModReserveMinusPriority
1237 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1239 Reduce the values of queued list
1241 =cut
1243 sub ModReserveMinusPriority {
1244 my ( $itemnumber, $reserve_id ) = @_;
1246 #first step update the value of the first person on reserv
1247 my $dbh = C4::Context->dbh;
1248 my $query = "
1249 UPDATE reserves
1250 SET priority = 0 , itemnumber = ?
1251 WHERE reserve_id = ?
1253 my $sth_upd = $dbh->prepare($query);
1254 $sth_upd->execute( $itemnumber, $reserve_id );
1255 # second step update all others reserves
1256 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1259 =head2 IsAvailableForItemLevelRequest
1261 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1263 Checks whether a given item record is available for an
1264 item-level hold request. An item is available if
1266 * it is not lost AND
1267 * it is not damaged AND
1268 * it is not withdrawn AND
1269 * a waiting or in transit reserve is placed on
1270 * does not have a not for loan value > 0
1272 Need to check the issuingrules onshelfholds column,
1273 if this is set items on the shelf can be placed on hold
1275 Note that IsAvailableForItemLevelRequest() does not
1276 check if the staff operator is authorized to place
1277 a request on the item - in particular,
1278 this routine does not check IndependentBranches
1279 and canreservefromotherbranches.
1281 Note also that this subroutine does not checks smart
1282 rules limits for item by reservesallowed/holds_per_record
1283 values, this complemented in calling code with calls and
1284 checks with CanItemBeReserved or CanBookBeReserved.
1286 =cut
1288 sub IsAvailableForItemLevelRequest {
1289 my $item = shift;
1290 my $patron = shift;
1291 my $pickup_branchcode = shift;
1292 # items_any_available is precalculated status passed from request.pl when set of items
1293 # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1294 my $items_any_available = shift;
1296 my $dbh = C4::Context->dbh;
1297 # must check the notforloan setting of the itemtype
1298 # FIXME - a lot of places in the code do this
1299 # or something similar - need to be
1300 # consolidated
1301 my $itemtype = $item->effective_itemtype;
1302 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1304 return 0 if
1305 $notforloan_per_itemtype ||
1306 $item->itemlost ||
1307 $item->notforloan > 0 ||
1308 $item->withdrawn ||
1309 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1311 if ($pickup_branchcode) {
1312 my $destination = Koha::Libraries->find($pickup_branchcode);
1313 return 0 unless $destination;
1314 return 0 unless $destination->pickup_location;
1315 return 0 unless $item->can_be_transferred( { to => $destination } );
1316 my $reserves_control_branch =
1317 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1318 my $branchitemrule =
1319 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1320 my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1321 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1324 my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1326 if ( $on_shelf_holds == 1 ) {
1327 return 1;
1328 } elsif ( $on_shelf_holds == 2 ) {
1330 # if we have this param predefined from outer caller sub, we just need
1331 # to return it, so we saving from having loop inside other loop:
1332 return $items_any_available ? 0 : 1
1333 if defined $items_any_available;
1335 my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1336 return $any_available ? 0 : 1;
1337 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1338 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1342 =head2 ItemsAnyAvailableAndNotRestricted
1344 ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1346 This function checks all items for specified biblionumber (numeric) against patron (object)
1347 and returns true (1) if at least one item available for loan/check out/present/not held
1348 and also checks other parameters logic which not restricts item for hold at all (for ex.
1349 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1351 =cut
1353 sub ItemsAnyAvailableAndNotRestricted {
1354 my $param = shift;
1356 my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1358 foreach my $i (@items) {
1359 my $reserves_control_branch =
1360 GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1361 my $branchitemrule =
1362 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1363 my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1365 # we can return (end the loop) when first one found:
1366 return 1
1367 unless $i->itemlost
1368 || $i->notforloan > 0
1369 || $i->withdrawn
1370 || $i->onloan
1371 || IsItemOnHoldAndFound( $i->id )
1372 || ( $i->damaged
1373 && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1374 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1375 || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1376 || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1377 || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1380 return 0;
1383 =head2 AlterPriority
1385 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1387 This function changes a reserve's priority up, down, to the top, or to the bottom.
1388 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1390 =cut
1392 sub AlterPriority {
1393 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1395 my $hold = Koha::Holds->find( $reserve_id );
1396 return unless $hold;
1398 if ( $hold->cancellationdate ) {
1399 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1400 return;
1403 if ( $where eq 'up' ) {
1404 return unless $prev_priority;
1405 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1406 } elsif ( $where eq 'down' ) {
1407 return unless $next_priority;
1408 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1409 } elsif ( $where eq 'top' ) {
1410 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1411 } elsif ( $where eq 'bottom' ) {
1412 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1415 # FIXME Should return the new priority
1418 =head2 ToggleLowestPriority
1420 ToggleLowestPriority( $borrowernumber, $biblionumber );
1422 This function sets the lowestPriority field to true if is false, and false if it is true.
1424 =cut
1426 sub ToggleLowestPriority {
1427 my ( $reserve_id ) = @_;
1429 my $dbh = C4::Context->dbh;
1431 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1432 $sth->execute( $reserve_id );
1434 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1437 =head2 ToggleSuspend
1439 ToggleSuspend( $reserve_id );
1441 This function sets the suspend field to true if is false, and false if it is true.
1442 If the reserve is currently suspended with a suspend_until date, that date will
1443 be cleared when it is unsuspended.
1445 =cut
1447 sub ToggleSuspend {
1448 my ( $reserve_id, $suspend_until ) = @_;
1450 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1452 my $hold = Koha::Holds->find( $reserve_id );
1454 if ( $hold->is_suspended ) {
1455 $hold->resume()
1456 } else {
1457 $hold->suspend_hold( $suspend_until );
1461 =head2 SuspendAll
1463 SuspendAll(
1464 borrowernumber => $borrowernumber,
1465 [ biblionumber => $biblionumber, ]
1466 [ suspend_until => $suspend_until, ]
1467 [ suspend => $suspend ]
1470 This function accepts a set of hash keys as its parameters.
1471 It requires either borrowernumber or biblionumber, or both.
1473 suspend_until is wholly optional.
1475 =cut
1477 sub SuspendAll {
1478 my %params = @_;
1480 my $borrowernumber = $params{'borrowernumber'} || undef;
1481 my $biblionumber = $params{'biblionumber'} || undef;
1482 my $suspend_until = $params{'suspend_until'} || undef;
1483 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1485 $suspend_until = eval { dt_from_string($suspend_until) }
1486 if ( defined($suspend_until) );
1488 return unless ( $borrowernumber || $biblionumber );
1490 my $params;
1491 $params->{found} = undef;
1492 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1493 $params->{biblionumber} = $biblionumber if $biblionumber;
1495 my @holds = Koha::Holds->search($params);
1497 if ($suspend) {
1498 map { $_->suspend_hold($suspend_until) } @holds;
1500 else {
1501 map { $_->resume() } @holds;
1506 =head2 _FixPriority
1508 _FixPriority({
1509 reserve_id => $reserve_id,
1510 [rank => $rank,]
1511 [ignoreSetLowestRank => $ignoreSetLowestRank]
1516 _FixPriority({ biblionumber => $biblionumber});
1518 This routine adjusts the priority of a hold request and holds
1519 on the same bib.
1521 In the first form, where a reserve_id is passed, the priority of the
1522 hold is set to supplied rank, and other holds for that bib are adjusted
1523 accordingly. If the rank is "del", the hold is cancelled. If no rank
1524 is supplied, all of the holds on that bib have their priority adjusted
1525 as if the second form had been used.
1527 In the second form, where a biblionumber is passed, the holds on that
1528 bib (that are not captured) are sorted in order of increasing priority,
1529 then have reserves.priority set so that the first non-captured hold
1530 has its priority set to 1, the second non-captured hold has its priority
1531 set to 2, and so forth.
1533 In both cases, holds that have the lowestPriority flag on are have their
1534 priority adjusted to ensure that they remain at the end of the line.
1536 Note that the ignoreSetLowestRank parameter is meant to be used only
1537 when _FixPriority calls itself.
1539 =cut
1541 sub _FixPriority {
1542 my ( $params ) = @_;
1543 my $reserve_id = $params->{reserve_id};
1544 my $rank = $params->{rank} // '';
1545 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1546 my $biblionumber = $params->{biblionumber};
1548 my $dbh = C4::Context->dbh;
1550 my $hold;
1551 if ( $reserve_id ) {
1552 $hold = Koha::Holds->find( $reserve_id );
1553 if (!defined $hold){
1554 # may have already been checked out and hold fulfilled
1555 $hold = Koha::Old::Holds->find( $reserve_id );
1557 return unless $hold;
1560 unless ( $biblionumber ) { # FIXME This is a very weird API
1561 $biblionumber = $hold->biblionumber;
1564 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1565 $hold->cancel;
1567 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1569 # make sure priority for waiting or in-transit items is 0
1570 my $query = "
1571 UPDATE reserves
1572 SET priority = 0
1573 WHERE reserve_id = ?
1574 AND found IN ('W', 'T', 'P')
1576 my $sth = $dbh->prepare($query);
1577 $sth->execute( $reserve_id );
1579 my @priority;
1581 # get whats left
1582 my $query = "
1583 SELECT reserve_id, borrowernumber, reservedate
1584 FROM reserves
1585 WHERE biblionumber = ?
1586 AND ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1587 ORDER BY priority ASC
1589 my $sth = $dbh->prepare($query);
1590 $sth->execute( $biblionumber );
1591 while ( my $line = $sth->fetchrow_hashref ) {
1592 push( @priority, $line );
1595 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1596 # To find the matching index
1597 my $i;
1598 my $key = -1; # to allow for 0 to be a valid result
1599 for ( $i = 0 ; $i < @priority ; $i++ ) {
1600 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1601 $key = $i; # save the index
1602 last;
1606 # if index exists in array then move it to new position
1607 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1608 my $new_rank = $rank -
1609 1; # $new_rank is what you want the new index to be in the array
1610 my $moving_item = splice( @priority, $key, 1 );
1611 splice( @priority, $new_rank, 0, $moving_item );
1614 # now fix the priority on those that are left....
1615 $query = "
1616 UPDATE reserves
1617 SET priority = ?
1618 WHERE reserve_id = ?
1620 $sth = $dbh->prepare($query);
1621 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1622 $sth->execute(
1623 $j + 1,
1624 $priority[$j]->{'reserve_id'}
1628 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1629 $sth->execute();
1631 unless ( $ignoreSetLowestRank ) {
1632 while ( my $res = $sth->fetchrow_hashref() ) {
1633 _FixPriority({
1634 reserve_id => $res->{'reserve_id'},
1635 rank => '999999',
1636 ignoreSetLowestRank => 1
1642 =head2 _Findgroupreserve
1644 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1646 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1647 first match found. If neither, then we look for non-holds-queue based holds.
1648 Lookahead is the number of days to look in advance.
1650 C<&_Findgroupreserve> returns :
1651 C<@results> is an array of references-to-hash whose keys are mostly
1652 fields from the reserves table of the Koha database, plus
1653 C<biblioitemnumber>.
1655 This routine with either return:
1656 1 - Item specific holds from the holds queue
1657 2 - Title level holds from the holds queue
1658 3 - All holds for this biblionumber
1660 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1662 =cut
1664 sub _Findgroupreserve {
1665 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1666 my $dbh = C4::Context->dbh;
1668 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1669 # check for exact targeted match
1670 my $item_level_target_query = qq{
1671 SELECT reserves.biblionumber AS biblionumber,
1672 reserves.borrowernumber AS borrowernumber,
1673 reserves.reservedate AS reservedate,
1674 reserves.branchcode AS branchcode,
1675 reserves.cancellationdate AS cancellationdate,
1676 reserves.found AS found,
1677 reserves.reservenotes AS reservenotes,
1678 reserves.priority AS priority,
1679 reserves.timestamp AS timestamp,
1680 biblioitems.biblioitemnumber AS biblioitemnumber,
1681 reserves.itemnumber AS itemnumber,
1682 reserves.reserve_id AS reserve_id,
1683 reserves.itemtype AS itemtype,
1684 reserves.non_priority AS non_priority
1685 FROM reserves
1686 JOIN biblioitems USING (biblionumber)
1687 JOIN hold_fill_targets USING (reserve_id)
1688 WHERE found IS NULL
1689 AND priority > 0
1690 AND item_level_request = 1
1691 AND hold_fill_targets.itemnumber = ?
1692 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1693 AND suspend = 0
1694 ORDER BY priority
1696 my $sth = $dbh->prepare($item_level_target_query);
1697 $sth->execute($itemnumber, $lookahead||0);
1698 my @results;
1699 if ( my $data = $sth->fetchrow_hashref ) {
1700 push( @results, $data )
1701 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1703 return @results if @results;
1705 # check for title-level targeted match
1706 my $title_level_target_query = qq{
1707 SELECT reserves.biblionumber AS biblionumber,
1708 reserves.borrowernumber AS borrowernumber,
1709 reserves.reservedate AS reservedate,
1710 reserves.branchcode AS branchcode,
1711 reserves.cancellationdate AS cancellationdate,
1712 reserves.found AS found,
1713 reserves.reservenotes AS reservenotes,
1714 reserves.priority AS priority,
1715 reserves.timestamp AS timestamp,
1716 biblioitems.biblioitemnumber AS biblioitemnumber,
1717 reserves.itemnumber AS itemnumber,
1718 reserves.reserve_id AS reserve_id,
1719 reserves.itemtype AS itemtype,
1720 reserves.non_priority AS non_priority
1721 FROM reserves
1722 JOIN biblioitems USING (biblionumber)
1723 JOIN hold_fill_targets USING (reserve_id)
1724 WHERE found IS NULL
1725 AND priority > 0
1726 AND item_level_request = 0
1727 AND hold_fill_targets.itemnumber = ?
1728 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1729 AND suspend = 0
1730 ORDER BY priority
1732 $sth = $dbh->prepare($title_level_target_query);
1733 $sth->execute($itemnumber, $lookahead||0);
1734 @results = ();
1735 if ( my $data = $sth->fetchrow_hashref ) {
1736 push( @results, $data )
1737 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1739 return @results if @results;
1741 my $query = qq{
1742 SELECT reserves.biblionumber AS biblionumber,
1743 reserves.borrowernumber AS borrowernumber,
1744 reserves.reservedate AS reservedate,
1745 reserves.waitingdate AS waitingdate,
1746 reserves.branchcode AS branchcode,
1747 reserves.cancellationdate AS cancellationdate,
1748 reserves.found AS found,
1749 reserves.reservenotes AS reservenotes,
1750 reserves.priority AS priority,
1751 reserves.timestamp AS timestamp,
1752 reserves.itemnumber AS itemnumber,
1753 reserves.reserve_id AS reserve_id,
1754 reserves.itemtype AS itemtype,
1755 reserves.non_priority AS non_priority
1756 FROM reserves
1757 WHERE reserves.biblionumber = ?
1758 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1759 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1760 AND suspend = 0
1761 ORDER BY priority
1763 $sth = $dbh->prepare($query);
1764 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1765 @results = ();
1766 while ( my $data = $sth->fetchrow_hashref ) {
1767 push( @results, $data )
1768 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1770 return @results;
1773 =head2 _koha_notify_reserve
1775 _koha_notify_reserve( $hold->reserve_id );
1777 Sends a notification to the patron that their hold has been filled (through
1778 ModReserveAffect, _not_ ModReserveFill)
1780 The letter code for this notice may be found using the following query:
1782 select distinct letter_code
1783 from message_transports
1784 inner join message_attributes using (message_attribute_id)
1785 where message_name = 'Hold_Filled'
1787 This will probably sipmly be 'HOLD', but because it is defined in the database,
1788 it is subject to addition or change.
1790 The following tables are availalbe witin the notice:
1792 branches
1793 borrowers
1794 biblio
1795 biblioitems
1796 reserves
1797 items
1799 =cut
1801 sub _koha_notify_reserve {
1802 my $reserve_id = shift;
1803 my $hold = Koha::Holds->find($reserve_id);
1804 my $borrowernumber = $hold->borrowernumber;
1806 my $patron = Koha::Patrons->find( $borrowernumber );
1808 # Try to get the borrower's email address
1809 my $to_address = $patron->notice_email_address;
1811 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1812 borrowernumber => $borrowernumber,
1813 message_name => 'Hold_Filled'
1814 } );
1816 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1818 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1820 my %letter_params = (
1821 module => 'reserves',
1822 branchcode => $hold->branchcode,
1823 lang => $patron->lang,
1824 tables => {
1825 'branches' => $library,
1826 'borrowers' => $patron->unblessed,
1827 'biblio' => $hold->biblionumber,
1828 'biblioitems' => $hold->biblionumber,
1829 'reserves' => $hold->unblessed,
1830 'items' => $hold->itemnumber,
1834 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.
1835 my $send_notification = sub {
1836 my ( $mtt, $letter_code ) = (@_);
1837 return unless defined $letter_code;
1838 $letter_params{letter_code} = $letter_code;
1839 $letter_params{message_transport_type} = $mtt;
1840 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1841 unless ($letter) {
1842 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1843 return;
1846 C4::Letters::EnqueueLetter( {
1847 letter => $letter,
1848 borrowernumber => $borrowernumber,
1849 from_address => $admin_email_address,
1850 message_transport_type => $mtt,
1851 } );
1854 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1855 next if (
1856 ( $mtt eq 'email' and not $to_address ) # No email address
1857 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1858 or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1859 or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1862 &$send_notification($mtt, $letter_code);
1863 $notification_sent++;
1865 #Making sure that a print notification is sent if no other transport types can be utilized.
1866 if (! $notification_sent) {
1867 &$send_notification('print', 'HOLD');
1872 =head2 _ShiftPriorityByDateAndPriority
1874 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1876 This increments the priority of all reserves after the one
1877 with either the lowest date after C<$reservedate>
1878 or the lowest priority after C<$priority>.
1880 It effectively makes room for a new reserve to be inserted with a certain
1881 priority, which is returned.
1883 This is most useful when the reservedate can be set by the user. It allows
1884 the new reserve to be placed before other reserves that have a later
1885 reservedate. Since priority also is set by the form in reserves/request.pl
1886 the sub accounts for that too.
1888 =cut
1890 sub _ShiftPriorityByDateAndPriority {
1891 my ( $biblio, $resdate, $new_priority ) = @_;
1893 my $dbh = C4::Context->dbh;
1894 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1895 my $sth = $dbh->prepare( $query );
1896 $sth->execute( $biblio, $resdate, $new_priority );
1897 my $min_priority = $sth->fetchrow;
1898 # if no such matches are found, $new_priority remains as original value
1899 $new_priority = $min_priority if ( $min_priority );
1901 # Shift the priority up by one; works in conjunction with the next SQL statement
1902 $query = "UPDATE reserves
1903 SET priority = priority+1
1904 WHERE biblionumber = ?
1905 AND borrowernumber = ?
1906 AND reservedate = ?
1907 AND found IS NULL";
1908 my $sth_update = $dbh->prepare( $query );
1910 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1911 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1912 $sth = $dbh->prepare( $query );
1913 $sth->execute( $new_priority, $biblio );
1914 while ( my $row = $sth->fetchrow_hashref ) {
1915 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1918 return $new_priority; # so the caller knows what priority they wind up receiving
1921 =head2 MoveReserve
1923 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1925 Use when checking out an item to handle reserves
1926 If $cancelreserve boolean is set to true, it will remove existing reserve
1928 =cut
1930 sub MoveReserve {
1931 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1933 $cancelreserve //= 0;
1935 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1936 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1937 return unless $res;
1939 my $biblionumber = $res->{biblionumber};
1941 if ($res->{borrowernumber} == $borrowernumber) {
1942 ModReserveFill($res);
1944 else {
1945 # warn "Reserved";
1946 # The item is reserved by someone else.
1947 # Find this item in the reserves
1949 my $borr_res = Koha::Holds->search({
1950 borrowernumber => $borrowernumber,
1951 biblionumber => $biblionumber,
1953 order_by => 'priority'
1954 })->next();
1956 if ( $borr_res ) {
1957 # The item is reserved by the current patron
1958 ModReserveFill($borr_res->unblessed);
1961 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1962 RevertWaitingStatus({ itemnumber => $itemnumber });
1964 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1965 my $hold = Koha::Holds->find( $res->{reserve_id} );
1966 $hold->cancel;
1971 =head2 MergeHolds
1973 MergeHolds($dbh,$to_biblio, $from_biblio);
1975 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1977 =cut
1979 sub MergeHolds {
1980 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1981 my $sth = $dbh->prepare(
1982 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1984 $sth->execute($from_biblio);
1985 if ( my $data = $sth->fetchrow_hashref() ) {
1987 # holds exist on old record, if not we don't need to do anything
1988 $sth = $dbh->prepare(
1989 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1990 $sth->execute( $to_biblio, $from_biblio );
1992 # Reorder by date
1993 # don't reorder those already waiting
1995 $sth = $dbh->prepare(
1996 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
1998 my $upd_sth = $dbh->prepare(
1999 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2000 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2002 $sth->execute( $to_biblio );
2003 my $priority = 1;
2004 while ( my $reserve = $sth->fetchrow_hashref() ) {
2005 $upd_sth->execute(
2006 $priority, $to_biblio,
2007 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2008 $reserve->{'itemnumber'}
2010 $priority++;
2015 =head2 RevertWaitingStatus
2017 RevertWaitingStatus({ itemnumber => $itemnumber });
2019 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2021 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2022 item level hold, even if it was only a bibliolevel hold to
2023 begin with. This is because we can no longer know if a hold
2024 was item-level or bib-level after a hold has been set to
2025 waiting status.
2027 =cut
2029 sub RevertWaitingStatus {
2030 my ( $params ) = @_;
2031 my $itemnumber = $params->{'itemnumber'};
2033 return unless ( $itemnumber );
2035 my $dbh = C4::Context->dbh;
2037 ## Get the waiting reserve we want to revert
2038 my $hold = Koha::Holds->search(
2040 itemnumber => $itemnumber,
2041 found => { not => undef },
2043 )->next;
2045 ## Increment the priority of all other non-waiting
2046 ## reserves for this bib record
2047 my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2048 ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2050 ## Fix up the currently waiting reserve
2051 $hold->set(
2053 priority => 1,
2054 found => undef,
2055 waitingdate => undef,
2056 itemnumber => $hold->item_level_hold ? $hold->itemnumber : undef,
2058 )->store();
2060 _FixPriority( { biblionumber => $hold->biblionumber } );
2062 return $hold;
2065 =head2 ReserveSlip
2067 ReserveSlip(
2069 branchcode => $branchcode,
2070 borrowernumber => $borrowernumber,
2071 biblionumber => $biblionumber,
2072 [ itemnumber => $itemnumber, ]
2073 [ barcode => $barcode, ]
2077 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2079 The letter code will be HOLD_SLIP, and the following tables are
2080 available within the slip:
2082 reserves
2083 branches
2084 borrowers
2085 biblio
2086 biblioitems
2087 items
2089 =cut
2091 sub ReserveSlip {
2092 my ($args) = @_;
2093 my $branchcode = $args->{branchcode};
2094 my $reserve_id = $args->{reserve_id};
2096 my $hold = Koha::Holds->find($reserve_id);
2097 return unless $hold;
2099 my $patron = $hold->borrower;
2100 my $reserve = $hold->unblessed;
2102 return C4::Letters::GetPreparedLetter (
2103 module => 'circulation',
2104 letter_code => 'HOLD_SLIP',
2105 branchcode => $branchcode,
2106 lang => $patron->lang,
2107 tables => {
2108 'reserves' => $reserve,
2109 'branches' => $reserve->{branchcode},
2110 'borrowers' => $reserve->{borrowernumber},
2111 'biblio' => $reserve->{biblionumber},
2112 'biblioitems' => $reserve->{biblionumber},
2113 'items' => $reserve->{itemnumber},
2118 =head2 GetReservesControlBranch
2120 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2122 Return the branchcode to be used to determine which reserves
2123 policy applies to a transaction.
2125 C<$item> is a hashref for an item. Only 'homebranch' is used.
2127 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2129 =cut
2131 sub GetReservesControlBranch {
2132 my ( $item, $borrower ) = @_;
2134 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2136 my $branchcode =
2137 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2138 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2139 : undef;
2141 return $branchcode;
2144 =head2 CalculatePriority
2146 my $p = CalculatePriority($biblionumber, $resdate);
2148 Calculate priority for a new reserve on biblionumber, placing it at
2149 the end of the line of all holds whose start date falls before
2150 the current system time and that are neither on the hold shelf
2151 or in transit.
2153 The reserve date parameter is optional; if it is supplied, the
2154 priority is based on the set of holds whose start date falls before
2155 the parameter value.
2157 After calculation of this priority, it is recommended to call
2158 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2159 AddReserves.
2161 =cut
2163 sub CalculatePriority {
2164 my ( $biblionumber, $resdate ) = @_;
2166 my $sql = q{
2167 SELECT COUNT(*) FROM reserves
2168 WHERE biblionumber = ?
2169 AND priority > 0
2170 AND (found IS NULL OR found = '')
2172 #skip found==W or found==T or found==P (waiting, transit or processing holds)
2173 if( $resdate ) {
2174 $sql.= ' AND ( reservedate <= ? )';
2176 else {
2177 $sql.= ' AND ( reservedate < NOW() )';
2179 my $dbh = C4::Context->dbh();
2180 my @row = $dbh->selectrow_array(
2181 $sql,
2182 undef,
2183 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2186 return @row ? $row[0]+1 : 1;
2189 =head2 IsItemOnHoldAndFound
2191 my $bool = IsItemFoundHold( $itemnumber );
2193 Returns true if the item is currently on hold
2194 and that hold has a non-null found status ( W, T, etc. )
2196 =cut
2198 sub IsItemOnHoldAndFound {
2199 my ($itemnumber) = @_;
2201 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2203 my $found = $rs->count(
2205 itemnumber => $itemnumber,
2206 found => { '!=' => undef }
2210 return $found;
2213 =head2 GetMaxPatronHoldsForRecord
2215 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2217 For multiple holds on a given record for a given patron, the max
2218 number of record level holds that a patron can be placed is the highest
2219 value of the holds_per_record rule for each item if the record for that
2220 patron. This subroutine finds and returns the highest holds_per_record
2221 rule value for a given patron id and record id.
2223 =cut
2225 sub GetMaxPatronHoldsForRecord {
2226 my ( $borrowernumber, $biblionumber ) = @_;
2228 my $patron = Koha::Patrons->find($borrowernumber);
2229 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2231 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2233 my $categorycode = $patron->categorycode;
2234 my $branchcode;
2235 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2237 my $max = 0;
2238 foreach my $item (@items) {
2239 my $itemtype = $item->effective_itemtype();
2241 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2243 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2244 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2245 $max = $holds_per_record if $holds_per_record > $max;
2248 return $max;
2251 =head2 GetHoldRule
2253 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2255 Returns the matching hold related issuingrule fields for a given
2256 patron category, itemtype, and library.
2258 =cut
2260 sub GetHoldRule {
2261 my ( $categorycode, $itemtype, $branchcode ) = @_;
2263 my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2265 itemtype => $itemtype,
2266 categorycode => $categorycode,
2267 branchcode => $branchcode,
2268 rule_name => 'reservesallowed',
2269 order_by => {
2270 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2275 my $rules;
2276 if ( $reservesallowed ) {
2277 $rules->{reservesallowed} = $reservesallowed->rule_value;
2278 $rules->{itemtype} = $reservesallowed->itemtype;
2279 $rules->{categorycode} = $reservesallowed->categorycode;
2280 $rules->{branchcode} = $reservesallowed->branchcode;
2283 my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2285 itemtype => $itemtype,
2286 categorycode => $categorycode,
2287 branchcode => $branchcode,
2288 rules => ['holds_per_record', 'holds_per_day'],
2289 order_by => {
2290 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2294 $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2295 $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2297 return $rules;
2300 =head1 AUTHOR
2302 Koha Development Team <http://koha-community.org/>
2304 =cut