Bug 30129: remove the third required date that was causing 500 error
[koha.git] / C4 / Reserves.pm
1 package C4::Reserves;
2
3 # Copyright 2000-2002 Katipo Communications
4 #           2006 SAN Ouest Provence
5 #           2007-2010 BibLibre Paul POULAIN
6 #           2011 Catalyst IT
7 #
8 # This file is part of Koha.
9 #
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.
14 #
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.
19 #
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>.
22
23
24 use Modern::Perl;
25
26 use C4::Accounts;
27 use C4::Circulation qw( CheckIfIssuedToPatron GetAgeRestriction GetBranchItemRule );
28 use C4::Context;
29 use C4::Items qw( CartToShelf get_hostitemnumbers_of );
30 use C4::Letters;
31 use C4::Log qw( logaction );
32 use C4::Members::Messaging;
33 use C4::Members;
34 use Koha::Account::Lines;
35 use Koha::Biblios;
36 use Koha::Calendar;
37 use Koha::CirculationRules;
38 use Koha::Database;
39 use Koha::DateUtils qw( dt_from_string output_pref );
40 use Koha::Hold;
41 use Koha::Holds;
42 use Koha::ItemTypes;
43 use Koha::Items;
44 use Koha::Libraries;
45 use Koha::Old::Hold;
46 use Koha::Patrons;
47 use Koha::Plugins;
48
49 use List::MoreUtils qw( any );
50
51 =head1 NAME
52
53 C4::Reserves - Koha functions for dealing with reservation.
54
55 =head1 SYNOPSIS
56
57   use C4::Reserves;
58
59 =head1 DESCRIPTION
60
61 This modules provides somes functions to deal with reservations.
62
63   Reserves are stored in reserves table.
64   The following columns contains important values :
65   - priority >0      : then the reserve is at 1st stage, and not yet affected to any item.
66              =0      : then the reserve is being dealed
67   - found : NULL         : means the patron requested the 1st available, and we haven't chosen the item
68             T(ransit)    : the reserve is linked to an item but is in transit to the pickup branch
69             W(aiting)    : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
70             F(inished)   : the reserve has been completed, and is done
71             P(rocessing) : reserved item has been returned using self-check machine and reserve needs to be confirmed
72                            by librarian before notice is send and status changed to waiting.
73                            Applicable only if HoldsNeedProcessingSIP system preference is set.
74   - itemnumber : empty : the reserve is still unaffected to an item
75                  filled: the reserve is attached to an item
76   The complete workflow is :
77   ==== 1st use case ====
78   patron request a document, 1st available :                      P >0, F=NULL, I=NULL
79   a library having it run "transfertodo", and clic on the list
80          if there is no transfer to do, the reserve waiting
81          patron can pick it up                                    P =0, F=W,    I=filled
82          if there is a transfer to do, write in branchtransfer    P =0, F=T,    I=filled
83            The pickup library receive the book, it check in       P =0, F=W,    I=filled
84   The patron borrow the book                                      P =0, F=F,    I=filled
85
86   ==== 2nd use case ====
87   patron requests a document, a given item,
88     If pickup is holding branch                                   P =0, F=W,   I=filled
89     If transfer needed, write in branchtransfer                   P =0, F=T,    I=filled
90         The pickup library receive the book, it checks it in      P =0, F=W,    I=filled
91   The patron borrow the book                                      P =0, F=F,    I=filled
92
93 =head1 FUNCTIONS
94
95 =cut
96
97 our (@ISA, @EXPORT_OK);
98 BEGIN {
99     require Exporter;
100     @ISA = qw(Exporter);
101     @EXPORT_OK = qw(
102       AddReserve
103
104       GetReserveStatus
105
106       GetOtherReserves
107       ChargeReserveFee
108       GetReserveFee
109
110       ModReserveAffect
111       ModReserve
112       ModReserveStatus
113       ModReserveCancelAll
114       ModReserveMinusPriority
115       MoveReserve
116
117       CheckReserves
118       CanBookBeReserved
119       CanItemBeReserved
120       CanReserveBeCanceledFromOpac
121       CancelExpiredReserves
122
123       AutoUnsuspendReserves
124
125       IsAvailableForItemLevelRequest
126       ItemsAnyAvailableAndNotRestricted
127
128       AlterPriority
129       ToggleLowestPriority
130
131       ReserveSlip
132       ToggleSuspend
133       SuspendAll
134
135       GetReservesControlBranch
136
137       CalculatePriority
138
139       IsItemOnHoldAndFound
140
141       GetMaxPatronHoldsForRecord
142
143       MergeHolds
144
145       RevertWaitingStatus
146     );
147 }
148
149 =head2 AddReserve
150
151     AddReserve(
152         {
153             branchcode       => $branchcode,
154             borrowernumber   => $borrowernumber,
155             biblionumber     => $biblionumber,
156             priority         => $priority,
157             reservation_date => $reservation_date,
158             expiration_date  => $expiration_date,
159             notes            => $notes,
160             title            => $title,
161             itemnumber       => $itemnumber,
162             found            => $found,
163             itemtype         => $itemtype,
164         }
165     );
166
167 Adds reserve and generates HOLDPLACED message.
168
169 The following tables are available witin the HOLDPLACED message:
170
171     branches
172     borrowers
173     biblio
174     biblioitems
175     items
176     reserves
177
178 =cut
179
180 sub AddReserve {
181     my ($params)       = @_;
182     my $branch         = $params->{branchcode};
183     my $borrowernumber = $params->{borrowernumber};
184     my $biblionumber   = $params->{biblionumber};
185     my $priority       = $params->{priority};
186     my $resdate        = $params->{reservation_date};
187     my $patron_expiration_date = $params->{expiration_date};
188     my $notes          = $params->{notes};
189     my $title          = $params->{title};
190     my $checkitem      = $params->{itemnumber};
191     my $found          = $params->{found};
192     my $itemtype       = $params->{itemtype};
193     my $non_priority   = $params->{non_priority};
194
195     $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
196         or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
197
198     $patron_expiration_date = output_pref({ str => $patron_expiration_date, dateonly => 1, dateformat => 'iso' });
199
200     # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
201     # of the document, we force the value $priority and $found .
202     if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
203         my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
204
205         if (
206             # If item is already checked out, it cannot be set waiting
207             !$item->onloan
208
209             # The item can't be waiting if it needs a transfer
210             && $item->holdingbranch eq $branch
211
212             # Similarly, if in transit it can't be waiting
213             && !$item->get_transfer
214
215             # If we can't hold damaged items, and it is damaged, it can't be waiting
216             && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
217
218             # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
219             && !$item->current_holds->count )
220         {
221             $priority = 0;
222             $found = 'W';
223         }
224     }
225
226     if ( C4::Context->preference('AllowHoldDateInFuture') ) {
227
228         # Make room in reserves for this before those of a later reserve date
229         $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
230     }
231
232     my $waitingdate;
233
234     # If the reserv had the waiting status, we had the value of the resdate
235     if ( $found && $found eq 'W' ) {
236         $waitingdate = $resdate;
237     }
238
239     # Don't add itemtype limit if specific item is selected
240     $itemtype = undef if $checkitem;
241
242     # updates take place here
243     my $hold = Koha::Hold->new(
244         {
245             borrowernumber => $borrowernumber,
246             biblionumber   => $biblionumber,
247             reservedate    => $resdate,
248             branchcode     => $branch,
249             priority       => $priority,
250             reservenotes   => $notes,
251             itemnumber     => $checkitem,
252             found          => $found,
253             waitingdate    => $waitingdate,
254             patron_expiration_date => $patron_expiration_date,
255             itemtype       => $itemtype,
256             item_level_hold => $checkitem ? 1 : 0,
257             non_priority   => $non_priority ? 1 : 0,
258         }
259     )->store();
260     $hold->set_waiting() if $found && $found eq 'W';
261
262     logaction( 'HOLDS', 'CREATE', $hold->id, $hold )
263         if C4::Context->preference('HoldsLog');
264
265     my $reserve_id = $hold->id();
266
267     # add a reserve fee if needed
268     if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
269         my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
270         ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
271     }
272
273     _FixPriority({ biblionumber => $biblionumber});
274
275     # Send e-mail to librarian if syspref is active
276     if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
277         my $patron = Koha::Patrons->find( $borrowernumber );
278         my $library = $patron->library;
279         if ( my $letter =  C4::Letters::GetPreparedLetter (
280             module => 'reserves',
281             letter_code => 'HOLDPLACED',
282             branchcode => $branch,
283             lang => $patron->lang,
284             tables => {
285                 'branches'    => $library->unblessed,
286                 'borrowers'   => $patron->unblessed,
287                 'biblio'      => $biblionumber,
288                 'biblioitems' => $biblionumber,
289                 'items'       => $checkitem,
290                 'reserves'    => $hold->unblessed,
291             },
292         ) ) {
293
294             my $branch_email_address = $library->inbound_email_address;
295
296             C4::Letters::EnqueueLetter(
297                 {
298                     letter                 => $letter,
299                     borrowernumber         => $borrowernumber,
300                     message_transport_type => 'email',
301                     to_address             => $branch_email_address,
302                 }
303             );
304         }
305     }
306
307     Koha::Plugins->call('after_hold_create', $hold);
308
309     return $reserve_id;
310 }
311
312 =head2 CanBookBeReserved
313
314   $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
315   if ($canReserve eq 'OK') { #We can reserve this Item! }
316
317   $params are passed directly through to CanItemBeReserved
318
319 See CanItemBeReserved() for possible return values.
320
321 =cut
322
323 sub CanBookBeReserved{
324     my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
325
326     # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
327     if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
328         && C4::Circulation::CheckIfIssuedToPatron( $borrowernumber, $biblionumber ) ) {
329         return { status =>'alreadypossession' };
330     }
331
332     my $items;
333     #get items linked via host records
334     my @hostitemnumbers = get_hostitemnumbers_of($biblionumber);
335     if (@hostitemnumbers){
336         $items = Koha::Items->search({
337             -or => [
338                 biblionumber => $biblionumber,
339                 itemnumber => { -in => @hostitemnumbers }
340             ]
341         });
342     } else {
343         $items = Koha::Items->search({ biblionumber => $biblionumber});
344     }
345
346     my $canReserve = { status => '' };
347     my $patron = Koha::Patrons->find( $borrowernumber );
348     while ( my $item = $items->next ) {
349         $canReserve = CanItemBeReserved( $patron, $item, $pickup_branchcode, $params );
350         return { status => 'OK' } if $canReserve->{status} eq 'OK';
351     }
352     return $canReserve;
353 }
354
355 =head2 CanItemBeReserved
356
357   $canReserve = &CanItemBeReserved($patron, $item, $branchcode, $params)
358   if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
359
360   current params are:
361   'ignore_found_holds' - if true holds that have been trapped are not counted
362   toward the patron limit, used by checkHighHolds to avoid counting the hold we will fill with the
363   current checkout against the high holds threshold
364   'ignore_hold_counts' - we use this routine to check if an item can fill a hold - on this case we
365   should not check if there are too many holds as we only csre about reservability
366
367 @RETURNS { status => OK },              if the Item can be reserved.
368          { status => ageRestricted },   if the Item is age restricted for this borrower.
369          { status => damaged },         if the Item is damaged.
370          { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
371          { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
372          { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
373          { status => notReservable },   if holds on this item are not allowed
374          { status => libraryNotFound },   if given branchcode is not an existing library
375          { status => libraryNotPickupLocation },   if given branchcode is not configured to be a pickup location
376          { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
377          { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
378
379 =cut
380
381 sub CanItemBeReserved {
382     my ( $patron, $item, $pickup_branchcode, $params ) = @_;
383
384     my $dbh = C4::Context->dbh;
385     my $ruleitemtype;    # itemtype of the matching issuing rule
386     my $allowedreserves  = 0; # Total number of holds allowed across all records, default to none
387
388     # we retrieve borrowers and items informations #
389     # item->{itype} will come for biblioitems if necessery
390     my $biblio   = $item->biblio;
391     my $borrower = $patron->unblessed;
392
393     # If an item is damaged and we don't allow holds on damaged items, we can stop right here
394     return { status =>'damaged' }
395       if ( $item->damaged
396         && !C4::Context->preference('AllowHoldsOnDamagedItems') );
397
398     # Check for the age restriction
399     my ( $ageRestriction, $daysToAgeRestriction ) =
400       C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
401     return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
402
403     # Check that the patron doesn't have an item level hold on this item already
404     return { status =>'itemAlreadyOnHold' }
405       if ( !$params->{ignore_hold_counts} && Koha::Holds->search( { borrowernumber => $patron->borrowernumber, itemnumber => $item->itemnumber } )->count() );
406
407     # Check that patron have not checked out this biblio (if AllowHoldsOnPatronsPossessions set)
408     if ( !C4::Context->preference('AllowHoldsOnPatronsPossessions')
409         && C4::Circulation::CheckIfIssuedToPatron( $patron->borrowernumber, $biblio->biblionumber ) ) {
410         return { status =>'alreadypossession' };
411     }
412
413     my $controlbranch = C4::Context->preference('ReservesControlBranch');
414
415     my $querycount = q{
416         SELECT count(*) AS count
417           FROM reserves
418      LEFT JOIN items USING (itemnumber)
419      LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
420      LEFT JOIN borrowers USING (borrowernumber)
421          WHERE borrowernumber = ?
422     };
423
424     my $branchcode  = "";
425     my $branchfield = "reserves.branchcode";
426
427     if ( $controlbranch eq "ItemHomeLibrary" ) {
428         $branchfield = "items.homebranch";
429         $branchcode  = $item->homebranch;
430     }
431     elsif ( $controlbranch eq "PatronLibrary" ) {
432         $branchfield = "borrowers.branchcode";
433         $branchcode  = $borrower->{branchcode};
434     }
435
436     # we retrieve rights
437     if (
438         my $reservesallowed = Koha::CirculationRules->get_effective_rule({
439                 itemtype     => $item->effective_itemtype,
440                 categorycode => $borrower->{categorycode},
441                 branchcode   => $branchcode,
442                 rule_name    => 'reservesallowed',
443         })
444     ) {
445         $ruleitemtype     = $reservesallowed->itemtype;
446         $allowedreserves  = $reservesallowed->rule_value // 0; #undefined is 0, blank is unlimited
447     }
448     else {
449         $ruleitemtype = undef;
450     }
451
452     my $rights = Koha::CirculationRules->get_effective_rules({
453         categorycode => $borrower->{'categorycode'},
454         itemtype     => $item->effective_itemtype,
455         branchcode   => $branchcode,
456         rules        => ['holds_per_record','holds_per_day']
457     });
458     my $holds_per_record = $rights->{holds_per_record} // 1;
459     my $holds_per_day    = $rights->{holds_per_day};
460
461     my $search_params = {
462         borrowernumber => $patron->borrowernumber,
463         biblionumber   => $item->biblionumber,
464     };
465     $search_params->{found} = undef if $params->{ignore_found_holds};
466
467     my $holds = Koha::Holds->search($search_params);
468     if (   defined $holds_per_record && $holds_per_record ne '' ){
469         if ( $holds_per_record == 0 ) {
470             return { status => "noReservesAllowed" };
471         }
472         if ( !$params->{ignore_hold_counts} && $holds->count() >= $holds_per_record ) {
473             return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
474         }
475     }
476
477     my $today_holds = Koha::Holds->search({
478         borrowernumber => $patron->borrowernumber,
479         reservedate    => dt_from_string->date
480     });
481
482     if (!$params->{ignore_hold_counts} && defined $holds_per_day && $holds_per_day ne ''
483         && $today_holds->count() >= $holds_per_day )
484     {
485         return { status => 'tooManyReservesToday', limit => $holds_per_day };
486     }
487
488     # we retrieve count
489
490     $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
491
492     # If using item-level itypes, fall back to the record
493     # level itemtype if the hold has no associated item
494     $querycount .=
495       C4::Context->preference('item-level_itypes')
496       ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
497       : " AND biblioitems.itemtype = ?"
498       if defined $ruleitemtype;
499
500     my $sthcount = $dbh->prepare($querycount);
501
502     if ( defined $ruleitemtype ) {
503         $sthcount->execute( $patron->borrowernumber, $branchcode, $ruleitemtype );
504     }
505     else {
506         $sthcount->execute( $patron->borrowernumber, $branchcode );
507     }
508
509     my $reservecount = "0";
510     if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
511         $reservecount = $rowcount->{count};
512     }
513
514     # we check if it's ok or not
515     if ( defined $allowedreserves && $allowedreserves ne '' ){
516         if( $allowedreserves == 0 ){
517             return { status => 'noReservesAllowed' };
518         }
519         if ( !$params->{ignore_hold_counts} && $reservecount >= $allowedreserves ) {
520             return { status => 'tooManyReserves', limit => $allowedreserves };
521         }
522     }
523
524     # Now we need to check hold limits by patron category
525     my $rule = Koha::CirculationRules->get_effective_rule(
526         {
527             categorycode => $patron->categorycode,
528             branchcode   => $branchcode,
529             rule_name    => 'max_holds',
530         }
531     );
532     if (!$params->{ignore_hold_counts} && $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
533         my $total_holds_count = Koha::Holds->search(
534             {
535                 borrowernumber => $patron->borrowernumber
536             }
537         )->count();
538
539         return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
540     }
541
542     my $reserves_control_branch =
543       GetReservesControlBranch( $item->unblessed(), $patron->unblessed );
544     my $branchitemrule =
545       C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->effective_itemtype );
546
547     if ( $branchitemrule->{holdallowed} eq 'not_allowed' ) {
548         return { status => 'notReservable' };
549     }
550
551     if (   $branchitemrule->{holdallowed} eq 'from_home_library'
552         && $borrower->{branchcode} ne $item->homebranch )
553     {
554         return { status => 'cannotReserveFromOtherBranches' };
555     }
556
557     my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
558     if ( $branchitemrule->{holdallowed} eq 'from_local_hold_group') {
559         if($patron->branchcode ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} )) {
560             return { status => 'branchNotInHoldGroup' };
561         }
562     }
563
564     # If reservecount is ok, we check item branch if IndependentBranches is ON
565     # and canreservefromotherbranches is OFF
566     if ( C4::Context->preference('IndependentBranches')
567         and !C4::Context->preference('canreservefromotherbranches') )
568     {
569         if ( $item->homebranch ne $patron->branchcode ) {
570             return { status => 'cannotReserveFromOtherBranches' };
571         }
572     }
573
574     if ($pickup_branchcode) {
575         my $destination = Koha::Libraries->find({
576             branchcode => $pickup_branchcode,
577         });
578
579         unless ($destination) {
580             return { status => 'libraryNotFound' };
581         }
582         unless ($destination->pickup_location) {
583             return { status => 'libraryNotPickupLocation' };
584         }
585         unless ($item->can_be_transferred({ to => $destination })) {
586             return { status => 'cannotBeTransferred' };
587         }
588         if ($branchitemrule->{hold_fulfillment_policy} eq 'holdgroup' && !$item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
589             return { status => 'pickupNotInHoldGroup' };
590         }
591         if ($branchitemrule->{hold_fulfillment_policy} eq 'patrongroup' && !Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
592             return { status => 'pickupNotInHoldGroup' };
593         }
594     }
595
596     return { status => 'OK' };
597 }
598
599 =head2 CanReserveBeCanceledFromOpac
600
601     $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
602
603     returns 1 if reserve can be cancelled by user from OPAC.
604     First check if reserve belongs to user, next checks if reserve is not in
605     transfer or waiting status
606
607 =cut
608
609 sub CanReserveBeCanceledFromOpac {
610     my ($reserve_id, $borrowernumber) = @_;
611
612     return unless $reserve_id and $borrowernumber;
613     my $reserve = Koha::Holds->find($reserve_id) or return;
614
615     return 0 unless $reserve->borrowernumber == $borrowernumber;
616     return $reserve->is_cancelable_from_opac;
617 }
618
619 =head2 GetOtherReserves
620
621   ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
622
623 Check queued list of this document and check if this document must be transferred
624
625 =cut
626
627 sub GetOtherReserves {
628     my ($itemnumber) = @_;
629     my $messages;
630     my $nextreservinfo;
631     my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
632     if ($checkreserves) {
633         my $item = Koha::Items->find($itemnumber);
634         if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
635             $messages->{'transfert'} = $checkreserves->{'branchcode'};
636             #minus priorities of others reservs
637             ModReserveMinusPriority(
638                 $itemnumber,
639                 $checkreserves->{'reserve_id'},
640             );
641
642             #launch the subroutine dotransfer
643             C4::Items::ModItemTransfer(
644                 $itemnumber,
645                 $item->holdingbranch,
646                 $checkreserves->{'branchcode'},
647                 'Reserve'
648               ),
649               ;
650         }
651
652      #step 2b : case of a reservation on the same branch, set the waiting status
653         else {
654             $messages->{'waiting'} = 1;
655             ModReserveMinusPriority(
656                 $itemnumber,
657                 $checkreserves->{'reserve_id'},
658             );
659             ModReserveStatus($itemnumber,'W');
660         }
661
662         $nextreservinfo = $checkreserves;
663     }
664
665     return ( $messages, $nextreservinfo );
666 }
667
668 =head2 ChargeReserveFee
669
670     $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
671
672     Charge the fee for a reserve (if $fee > 0)
673
674 =cut
675
676 sub ChargeReserveFee {
677     my ( $borrowernumber, $fee, $title ) = @_;
678     return if !$fee || $fee == 0;    # the last test is needed to include 0.00
679     Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
680         {
681             amount       => $fee,
682             description  => $title,
683             note         => undef,
684             user_id      => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
685             library_id   => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
686             interface    => C4::Context->interface,
687             invoice_type => undef,
688             type         => 'RESERVE',
689             item_id      => undef
690         }
691     );
692 }
693
694 =head2 GetReserveFee
695
696     $fee = GetReserveFee( $borrowernumber, $biblionumber );
697
698     Calculate the fee for a reserve (if applicable).
699
700 =cut
701
702 sub GetReserveFee {
703     my ( $borrowernumber, $biblionumber ) = @_;
704     my $borquery = qq{
705 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
706     };
707     my $issue_qry = qq{
708 SELECT COUNT(*) FROM items
709 LEFT JOIN issues USING (itemnumber)
710 WHERE items.biblionumber=? AND issues.issue_id IS NULL
711     };
712     my $holds_qry = qq{
713 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
714     };
715
716     my $dbh = C4::Context->dbh;
717     my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
718     my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
719     if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
720         # This is a reconstruction of the old code:
721         # Compare number of items with items issued, and optionally check holds
722         # If not all items are issued and there are no holds: charge no fee
723         # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
724         my ( $notissued, $reserved );
725         ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
726             ( $biblionumber ) );
727         if( $notissued ) {
728             ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
729                 ( $biblionumber, $borrowernumber ) );
730             $fee = 0 if $reserved == 0;
731         }
732     }
733     return $fee;
734 }
735
736 =head2 GetReserveStatus
737
738   $reservestatus = GetReserveStatus($itemnumber);
739
740 Takes an itemnumber and returns the status of the reserve placed on it.
741 If several reserves exist, the reserve with the lower priority is given.
742
743 =cut
744
745 ## FIXME: I don't think this does what it thinks it does.
746 ## It only ever checks the first reserve result, even though
747 ## multiple reserves for that bib can have the itemnumber set
748 ## the sub is only used once in the codebase.
749 sub GetReserveStatus {
750     my ($itemnumber) = @_;
751
752     my $dbh = C4::Context->dbh;
753
754     my ($sth, $found, $priority);
755     if ( $itemnumber ) {
756         $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
757         $sth->execute($itemnumber);
758         ($found, $priority) = $sth->fetchrow_array;
759     }
760
761     if(defined $found) {
762         return 'Waiting'  if $found eq 'W' and $priority == 0;
763         return 'Processing'  if $found eq 'P';
764         return 'Finished' if $found eq 'F';
765     }
766
767     return 'Reserved' if defined $priority && $priority > 0;
768
769     return ''; # empty string here will remove need for checking undef, or less log lines
770 }
771
772 =head2 CheckReserves
773
774   ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
775   ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
776   ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
777
778 Find a book in the reserves.
779
780 C<$itemnumber> is the book's item number.
781 C<$lookahead> is the number of days to look in advance for future reserves.
782
783 As I understand it, C<&CheckReserves> looks for the given item in the
784 reserves. If it is found, that's a match, and C<$status> is set to
785 C<Waiting>.
786
787 Otherwise, it finds the most important item in the reserves with the
788 same biblio number as this book (I'm not clear on this) and returns it
789 with C<$status> set to C<Reserved>.
790
791 C<&CheckReserves> returns a two-element list:
792
793 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
794
795 C<$reserve> is the reserve item that matched. It is a
796 reference-to-hash whose keys are mostly the fields of the reserves
797 table in the Koha database.
798
799 =cut
800
801 sub CheckReserves {
802     my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
803     my $dbh = C4::Context->dbh;
804     my $sth;
805     my $select;
806     if (C4::Context->preference('item-level_itypes')){
807         $select = "
808            SELECT items.biblionumber,
809            items.biblioitemnumber,
810            itemtypes.notforloan,
811            items.notforloan AS itemnotforloan,
812            items.itemnumber,
813            items.damaged,
814            items.homebranch,
815            items.holdingbranch
816            FROM   items
817            LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
818            LEFT JOIN itemtypes   ON items.itype   = itemtypes.itemtype
819         ";
820     }
821     else {
822         $select = "
823            SELECT items.biblionumber,
824            items.biblioitemnumber,
825            itemtypes.notforloan,
826            items.notforloan AS itemnotforloan,
827            items.itemnumber,
828            items.damaged,
829            items.homebranch,
830            items.holdingbranch
831            FROM   items
832            LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
833            LEFT JOIN itemtypes   ON biblioitems.itemtype   = itemtypes.itemtype
834         ";
835     }
836
837     if ($item) {
838         $sth = $dbh->prepare("$select WHERE itemnumber = ?");
839         $sth->execute($item);
840     }
841     else {
842         $sth = $dbh->prepare("$select WHERE barcode = ?");
843         $sth->execute($barcode);
844     }
845     # note: we get the itemnumber because we might have started w/ just the barcode.  Now we know for sure we have it.
846     my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
847     return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
848
849     return unless $itemnumber; # bail if we got nothing.
850     # if item is not for loan it cannot be reserved either.....
851     # except where items.notforloan < 0 :  This indicates the item is holdable.
852
853     my @SkipHoldTrapOnNotForLoanValue = split( '\|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
854     return if grep { $_ eq $notforloan_per_item } @SkipHoldTrapOnNotForLoanValue;
855
856     my $dont_trap = C4::Context->preference('TrapHoldsOnOrder') ? ($notforloan_per_item > 0) : ($notforloan_per_item && 1 );
857     return if $dont_trap or $notforloan_per_itemtype;
858
859     # Find this item in the reserves
860     my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
861
862     # $priority and $highest are used to find the most important item
863     # in the list returned by &_Findgroupreserve. (The lower $priority,
864     # the more important the item.)
865     # $highest is the most important item we've seen so far.
866     my $highest;
867
868     if (scalar @reserves) {
869         my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
870         my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
871         my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
872
873         my $priority = 10000000;
874         foreach my $res (@reserves) {
875             if ($res->{'found'} && $res->{'found'} eq 'W') {
876                 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
877             } elsif ($res->{'found'} && $res->{'found'} eq 'P') {
878                 return ( "Processing", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
879             } elsif ($res->{'found'} && $res->{'found'} eq 'T') {
880                 return ( "Transferred", $res, \@reserves ); # Found determinated hold, e. g. the transferred one
881             } else {
882                 my $patron;
883                 my $item;
884                 my $local_hold_match;
885
886                 if ($LocalHoldsPriority) {
887                     $patron = Koha::Patrons->find( $res->{borrowernumber} );
888                     $item = Koha::Items->find($itemnumber);
889
890                     unless ($item->exclude_from_local_holds_priority || $patron->category->exclude_from_local_holds_priority) {
891                         my $local_holds_priority_item_branchcode =
892                             $item->$LocalHoldsPriorityItemControl;
893                         my $local_holds_priority_patron_branchcode =
894                             ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
895                             ? $res->{branchcode}
896                             : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
897                             ? $patron->branchcode
898                             : undef;
899                         $local_hold_match =
900                             $local_holds_priority_item_branchcode eq
901                             $local_holds_priority_patron_branchcode;
902                     }
903                 }
904
905                 # See if this item is more important than what we've got so far
906                 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
907                     $item ||= Koha::Items->find($itemnumber);
908                     next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
909                     $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
910                     my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
911                     my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
912                     next if ($branchitemrule->{'holdallowed'} eq 'not_allowed');
913                     next if (($branchitemrule->{'holdallowed'} eq 'from_home_library') && ($item->homebranch ne $patron->branchcode));
914                     my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
915                     next if (($branchitemrule->{'holdallowed'} eq 'from_local_hold_group') && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
916                     my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
917                     next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
918                     next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
919                     next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
920                     next unless $item->can_be_transferred( { to => Koha::Libraries->find( $res->{branchcode} ) } );
921                     $priority = $res->{'priority'};
922                     $highest  = $res;
923                     last if $local_hold_match;
924                 }
925             }
926         }
927     }
928
929     # If we get this far, then no exact match was found.
930     # We return the most important (i.e. next) reservation.
931     if ($highest) {
932         $highest->{'itemnumber'} = $item;
933         return ( "Reserved", $highest, \@reserves );
934     }
935
936     return ( '' );
937 }
938
939 =head2 CancelExpiredReserves
940
941   CancelExpiredReserves();
942
943 Cancels all reserves with an expiration date from before today.
944
945 =cut
946
947 sub CancelExpiredReserves {
948     my $cancellation_reason = shift;
949     my $today = dt_from_string();
950     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
951     my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
952
953     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
954     my $params = {
955         -or => [
956             { expirationdate => { '<', $dtf->format_date($today) } },
957             { patron_expiration_date => { '<' => $dtf->format_date($today) } }
958         ]
959     };
960
961     $params->{found} = [ { '!=', 'W' }, undef ]  unless $expireWaiting;
962
963     # FIXME To move to Koha::Holds->search_expired (?)
964     my $holds = Koha::Holds->search( $params );
965
966     while ( my $hold = $holds->next ) {
967         my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
968
969         next if !$cancel_on_holidays && $calendar->is_holiday( $today );
970
971         my $cancel_params = {};
972         $cancel_params->{cancellation_reason} = $cancellation_reason if defined($cancellation_reason);
973         if ( defined($hold->found) && $hold->found eq 'W' ) {
974             $cancel_params->{charge_cancel_fee} = 1;
975         }
976         $hold->cancel( $cancel_params );
977     }
978 }
979
980 =head2 AutoUnsuspendReserves
981
982   AutoUnsuspendReserves();
983
984 Unsuspends all suspended reserves with a suspend_until date from before today.
985
986 =cut
987
988 sub AutoUnsuspendReserves {
989     my $today = dt_from_string();
990
991     my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } )->as_list;
992
993     map { $_->resume() } @holds;
994 }
995
996 =head2 ModReserve
997
998   ModReserve({ rank => $rank,
999                reserve_id => $reserve_id,
1000                branchcode => $branchcode
1001                [, itemnumber => $itemnumber ]
1002                [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1003               });
1004
1005 Change a hold request's priority or cancel it.
1006
1007 C<$rank> specifies the effect of the change.  If C<$rank>
1008 is 'n', nothing happens.  This corresponds to leaving a
1009 request alone when changing its priority in the holds queue
1010 for a bib.
1011
1012 If C<$rank> is 'del', the hold request is cancelled.
1013
1014 If C<$rank> is an integer greater than zero, the priority of
1015 the request is set to that value.  Since priority != 0 means
1016 that the item is not waiting on the hold shelf, setting the
1017 priority to a non-zero value also sets the request's found
1018 status and waiting date to NULL.
1019
1020 If the hold is 'found' (waiting, in-transit, processing) the
1021 only field that can be updated is the expiration date.
1022
1023 The optional C<$itemnumber> parameter is used only when
1024 C<$rank> is a non-zero integer; if supplied, the itemnumber
1025 of the hold request is set accordingly; if omitted, the itemnumber
1026 is cleared.
1027
1028 B<FIXME:> Note that the forgoing can have the effect of causing
1029 item-level hold requests to turn into title-level requests.  This
1030 will be fixed once reserves has separate columns for requested
1031 itemnumber and supplying itemnumber.
1032
1033 =cut
1034
1035 sub ModReserve {
1036     my ( $params ) = @_;
1037
1038     my $rank = $params->{'rank'};
1039     my $reserve_id = $params->{'reserve_id'};
1040     my $branchcode = $params->{'branchcode'};
1041     my $itemnumber = $params->{'itemnumber'};
1042     my $suspend_until = $params->{'suspend_until'};
1043     my $borrowernumber = $params->{'borrowernumber'};
1044     my $biblionumber = $params->{'biblionumber'};
1045     my $cancellation_reason = $params->{'cancellation_reason'};
1046     my $date = $params->{expirationdate};
1047
1048     return if defined $rank && $rank eq "n";
1049
1050     return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1051
1052     my $hold;
1053     unless ( $reserve_id ) {
1054         my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1055         return unless $holds->count; # FIXME Should raise an exception
1056         $hold = $holds->next;
1057         $reserve_id = $hold->reserve_id;
1058     }
1059
1060     $hold ||= Koha::Holds->find($reserve_id);
1061
1062     # FIXME Other calls may fail
1063     Koha::Exceptions::ObjectNotFound->throw( 'No hold with id ' . $reserve_id ) unless $hold;
1064
1065     if ( $rank eq "del" ) {
1066         $hold->cancel({ cancellation_reason => $cancellation_reason });
1067     }
1068     elsif ($hold->found && $hold->priority eq '0' && $date) {
1069         logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1070             if C4::Context->preference('HoldsLog');
1071
1072         # The only column that can be updated for a found hold is the expiration date
1073         $hold->expirationdate(dt_from_string($date))->store();
1074     }
1075     elsif ($rank =~ /^\d+/ and $rank > 0) {
1076         logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1077             if C4::Context->preference('HoldsLog');
1078
1079         my $properties = {
1080             priority    => $rank,
1081             branchcode  => $branchcode,
1082             itemnumber  => $itemnumber,
1083             found       => undef,
1084             waitingdate => undef
1085         };
1086         if (exists $params->{reservedate}) {
1087             $properties->{reservedate} = $params->{reservedate} || undef;
1088         }
1089         if (exists $params->{expirationdate}) {
1090             $properties->{expirationdate} = $params->{expirationdate} || undef;
1091         }
1092
1093         $hold->set($properties)->store();
1094
1095         if ( defined( $suspend_until ) ) {
1096             if ( $suspend_until ) {
1097                 $suspend_until = eval { dt_from_string( $suspend_until ) };
1098                 $hold->suspend_hold( $suspend_until );
1099             } else {
1100                 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1101                 # If the hold is not suspended, this does nothing.
1102                 $hold->set( { suspend_until => undef } )->store();
1103             }
1104         }
1105
1106         _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1107     }
1108 }
1109
1110 =head2 ModReserveStatus
1111
1112   &ModReserveStatus($itemnumber, $newstatus);
1113
1114 Update the reserve status for the active (priority=0) reserve.
1115
1116 $itemnumber is the itemnumber the reserve is on
1117
1118 $newstatus is the new status.
1119
1120 =cut
1121
1122 sub ModReserveStatus {
1123
1124     #first : check if we have a reservation for this item .
1125     my ($itemnumber, $newstatus) = @_;
1126     my $dbh = C4::Context->dbh;
1127
1128     my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1129     my $sth_set = $dbh->prepare($query);
1130     $sth_set->execute( $newstatus, $itemnumber );
1131
1132     my $item = Koha::Items->find($itemnumber);
1133     if ( $item->location && $item->location eq 'CART'
1134         && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1135         && $newstatus ) {
1136       CartToShelf( $itemnumber );
1137     }
1138 }
1139
1140 =head2 ModReserveAffect
1141
1142   &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1143
1144 This function affect an item and a status for a given reserve, either fetched directly
1145 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1146 is given, only first reserve returned is affected, which is ok for anything but
1147 multi-item holds.
1148
1149 if $transferToDo is not set, then the status is set to "Waiting" as well.
1150 otherwise, a transfer is on the way, and the end of the transfer will
1151 take care of the waiting status
1152
1153 This function also removes any entry of the hold in holds queue table.
1154
1155 =cut
1156
1157 sub ModReserveAffect {
1158     my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1159     my $dbh = C4::Context->dbh;
1160
1161     # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1162     # attached to $itemnumber
1163     my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1164     $sth->execute($itemnumber);
1165     my ($biblionumber) = $sth->fetchrow;
1166
1167     # get request - need to find out if item is already
1168     # waiting in order to not send duplicate hold filled notifications
1169
1170     my $hold;
1171     # Find hold by id if we have it
1172     $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1173     # Find item level hold for this item if there is one
1174     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1175     # Find record level hold if there is no item level hold
1176     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1177
1178     return unless $hold;
1179
1180     my $already_on_shelf = $hold->found && $hold->found eq 'W';
1181
1182     $hold->itemnumber($itemnumber);
1183
1184     if ($transferToDo) {
1185         $hold->set_transfer();
1186     } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1187              && C4::Context->interface eq 'sip'
1188              && !$already_on_shelf) {
1189         $hold->set_processing();
1190     } else {
1191         $hold->set_waiting($desk_id);
1192         _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1193         # Complete transfer if one exists
1194         my $transfer = $hold->item->get_transfer;
1195         $transfer->receive if $transfer;
1196     }
1197
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 );
1203     }
1204
1205     my $std = $dbh->prepare(q{
1206         DELETE  q, t
1207         FROM    tmp_holdsqueue q
1208         INNER JOIN hold_fill_targets t
1209         ON  q.borrowernumber = t.borrowernumber
1210             AND q.biblionumber = t.biblionumber
1211             AND q.itemnumber = t.itemnumber
1212             AND q.item_level_request = t.item_level_request
1213             AND q.holdingbranch = t.source_branchcode
1214         WHERE t.reserve_id = ?
1215     });
1216     $std->execute($hold->reserve_id);
1217
1218     logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, $hold )
1219         if C4::Context->preference('HoldsLog');
1220
1221     return;
1222 }
1223
1224 =head2 ModReserveCancelAll
1225
1226   ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1227
1228 function to cancel reserv,check other reserves, and transfer document if it's necessary
1229
1230 =cut
1231
1232 sub ModReserveCancelAll {
1233     my $messages;
1234     my $nextreservinfo;
1235     my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1236
1237     #step 1 : cancel the reservation
1238     my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1239     return unless $holds->count;
1240     $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1241
1242     #step 2 launch the subroutine of the others reserves
1243     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1244
1245     return ( $messages, $nextreservinfo->{borrowernumber} );
1246 }
1247
1248 =head2 ModReserveMinusPriority
1249
1250   &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1251
1252 Reduce the values of queued list
1253
1254 =cut
1255
1256 sub ModReserveMinusPriority {
1257     my ( $itemnumber, $reserve_id ) = @_;
1258
1259     #first step update the value of the first person on reserv
1260     my $dbh   = C4::Context->dbh;
1261     my $query = "
1262         UPDATE reserves
1263         SET    priority = 0 , itemnumber = ?
1264         WHERE  reserve_id = ?
1265     ";
1266     my $sth_upd = $dbh->prepare($query);
1267     $sth_upd->execute( $itemnumber, $reserve_id );
1268     # second step update all others reserves
1269     _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1270 }
1271
1272 =head2 IsAvailableForItemLevelRequest
1273
1274   my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1275
1276 Checks whether a given item record is available for an
1277 item-level hold request.  An item is available if
1278
1279 * it is not lost AND
1280 * it is not damaged AND
1281 * it is not withdrawn AND
1282 * a waiting or in transit reserve is placed on
1283 * does not have a not for loan value > 0
1284
1285 Need to check the issuingrules onshelfholds column,
1286 if this is set items on the shelf can be placed on hold
1287
1288 Note that IsAvailableForItemLevelRequest() does not
1289 check if the staff operator is authorized to place
1290 a request on the item - in particular,
1291 this routine does not check IndependentBranches
1292 and canreservefromotherbranches.
1293
1294 Note also that this subroutine does not checks smart
1295 rules limits for item by reservesallowed/holds_per_record
1296 values, this complemented in calling code with calls and
1297 checks with CanItemBeReserved or CanBookBeReserved.
1298
1299 =cut
1300
1301 sub IsAvailableForItemLevelRequest {
1302     my $item                = shift;
1303     my $patron              = shift;
1304     my $pickup_branchcode   = shift;
1305     # items_any_available is precalculated status passed from request.pl when set of items
1306     # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1307     my $items_any_available = shift;
1308
1309     my $dbh = C4::Context->dbh;
1310     # must check the notforloan setting of the itemtype
1311     # FIXME - a lot of places in the code do this
1312     #         or something similar - need to be
1313     #         consolidated
1314     my $itemtype = $item->effective_itemtype;
1315     return 0
1316       unless defined $itemtype;
1317     my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1318
1319     return 0 if
1320         $notforloan_per_itemtype ||
1321         $item->itemlost        ||
1322         $item->notforloan > 0  || # item with negative or zero notforloan value is holdable
1323         $item->withdrawn        ||
1324         ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1325
1326     if ($pickup_branchcode) {
1327         my $destination = Koha::Libraries->find($pickup_branchcode);
1328         return 0 unless $destination;
1329         return 0 unless $destination->pickup_location;
1330         return 0 unless $item->can_be_transferred( { to => $destination } );
1331         my $reserves_control_branch =
1332             GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1333         my $branchitemrule =
1334             C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1335         my $home_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
1336         return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1337     }
1338
1339     my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1340
1341     if ( $on_shelf_holds == 1 ) {
1342         return 1;
1343     } elsif ( $on_shelf_holds == 2 ) {
1344
1345         # if we have this param predefined from outer caller sub, we just need
1346         # to return it, so we saving from having loop inside other loop:
1347         return  $items_any_available ? 0 : 1
1348             if defined $items_any_available;
1349
1350         my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1351         return $any_available ? 0 : 1;
1352     } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1353         return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1354     }
1355 }
1356
1357 =head2 ItemsAnyAvailableAndNotRestricted
1358
1359   ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1360
1361 This function checks all items for specified biblionumber (numeric) against patron (object)
1362 and returns true (1) if at least one item available for loan/check out/present/not held
1363 and also checks other parameters logic which not restricts item for hold at all (for ex.
1364 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1365
1366 =cut
1367
1368 sub ItemsAnyAvailableAndNotRestricted {
1369     my $param = shift;
1370
1371     my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } )->as_list;
1372
1373     foreach my $i (@items) {
1374         my $reserves_control_branch =
1375             GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1376         my $branchitemrule =
1377             C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1378         my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1379
1380         # we can return (end the loop) when first one found:
1381         return 1
1382             unless $i->itemlost
1383             || $i->notforloan # items with non-zero notforloan cannot be checked out
1384             || $i->withdrawn
1385             || $i->onloan
1386             || IsItemOnHoldAndFound( $i->id )
1387             || ( $i->damaged
1388                  && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1389             || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1390             || $branchitemrule->{holdallowed} eq 'from_home_library' && $param->{patron}->branchcode ne $i->homebranch
1391             || $branchitemrule->{holdallowed} eq 'from_local_hold_group' && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1392             || CanItemBeReserved( $param->{patron}, $i )->{status} ne 'OK';
1393     }
1394
1395     return 0;
1396 }
1397
1398 =head2 AlterPriority
1399
1400   AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1401
1402 This function changes a reserve's priority up, down, to the top, or to the bottom.
1403 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1404
1405 =cut
1406
1407 sub AlterPriority {
1408     my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1409
1410     my $hold = Koha::Holds->find( $reserve_id );
1411     return unless $hold;
1412
1413     if ( $hold->cancellationdate ) {
1414         warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1415         return;
1416     }
1417
1418     if ( $where eq 'up' ) {
1419       return unless $prev_priority;
1420       _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1421     } elsif ( $where eq 'down' ) {
1422       return unless $next_priority;
1423       _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1424     } elsif ( $where eq 'top' ) {
1425       _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1426     } elsif ( $where eq 'bottom' ) {
1427       _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1428     }
1429
1430     # FIXME Should return the new priority
1431 }
1432
1433 =head2 ToggleLowestPriority
1434
1435   ToggleLowestPriority( $borrowernumber, $biblionumber );
1436
1437 This function sets the lowestPriority field to true if is false, and false if it is true.
1438
1439 =cut
1440
1441 sub ToggleLowestPriority {
1442     my ( $reserve_id ) = @_;
1443
1444     my $dbh = C4::Context->dbh;
1445
1446     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1447     $sth->execute( $reserve_id );
1448
1449     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1450 }
1451
1452 =head2 ToggleSuspend
1453
1454   ToggleSuspend( $reserve_id );
1455
1456 This function sets the suspend field to true if is false, and false if it is true.
1457 If the reserve is currently suspended with a suspend_until date, that date will
1458 be cleared when it is unsuspended.
1459
1460 =cut
1461
1462 sub ToggleSuspend {
1463     my ( $reserve_id, $suspend_until ) = @_;
1464
1465     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1466
1467     my $hold = Koha::Holds->find( $reserve_id );
1468
1469     if ( $hold->is_suspended ) {
1470         $hold->resume()
1471     } else {
1472         $hold->suspend_hold( $suspend_until );
1473     }
1474 }
1475
1476 =head2 SuspendAll
1477
1478   SuspendAll(
1479       borrowernumber   => $borrowernumber,
1480       [ biblionumber   => $biblionumber, ]
1481       [ suspend_until  => $suspend_until, ]
1482       [ suspend        => $suspend ]
1483   );
1484
1485   This function accepts a set of hash keys as its parameters.
1486   It requires either borrowernumber or biblionumber, or both.
1487
1488   suspend_until is wholly optional.
1489
1490 =cut
1491
1492 sub SuspendAll {
1493     my %params = @_;
1494
1495     my $borrowernumber = $params{'borrowernumber'} || undef;
1496     my $biblionumber   = $params{'biblionumber'}   || undef;
1497     my $suspend_until  = $params{'suspend_until'}  || undef;
1498     my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1499
1500     $suspend_until = eval { dt_from_string($suspend_until) }
1501       if ( defined($suspend_until) );
1502
1503     return unless ( $borrowernumber || $biblionumber );
1504
1505     my $params;
1506     $params->{found}          = undef;
1507     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1508     $params->{biblionumber}   = $biblionumber if $biblionumber;
1509
1510     my @holds = Koha::Holds->search($params)->as_list;
1511
1512     if ($suspend) {
1513         map { $_->suspend_hold($suspend_until) } @holds;
1514     }
1515     else {
1516         map { $_->resume() } @holds;
1517     }
1518 }
1519
1520
1521 =head2 _FixPriority
1522
1523   _FixPriority({
1524     reserve_id => $reserve_id,
1525     [rank => $rank,]
1526     [ignoreSetLowestRank => $ignoreSetLowestRank]
1527   });
1528
1529   or
1530
1531   _FixPriority({ biblionumber => $biblionumber});
1532
1533 This routine adjusts the priority of a hold request and holds
1534 on the same bib.
1535
1536 In the first form, where a reserve_id is passed, the priority of the
1537 hold is set to supplied rank, and other holds for that bib are adjusted
1538 accordingly.  If the rank is "del", the hold is cancelled.  If no rank
1539 is supplied, all of the holds on that bib have their priority adjusted
1540 as if the second form had been used.
1541
1542 In the second form, where a biblionumber is passed, the holds on that
1543 bib (that are not captured) are sorted in order of increasing priority,
1544 then have reserves.priority set so that the first non-captured hold
1545 has its priority set to 1, the second non-captured hold has its priority
1546 set to 2, and so forth.
1547
1548 In both cases, holds that have the lowestPriority flag on are have their
1549 priority adjusted to ensure that they remain at the end of the line.
1550
1551 Note that the ignoreSetLowestRank parameter is meant to be used only
1552 when _FixPriority calls itself.
1553
1554 =cut
1555
1556 sub _FixPriority {
1557     my ( $params ) = @_;
1558     my $reserve_id = $params->{reserve_id};
1559     my $rank = $params->{rank} // '';
1560     my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1561     my $biblionumber = $params->{biblionumber};
1562
1563     my $dbh = C4::Context->dbh;
1564
1565     my $hold;
1566     if ( $reserve_id ) {
1567         $hold = Koha::Holds->find( $reserve_id );
1568         if (!defined $hold){
1569             # may have already been checked out and hold fulfilled
1570             $hold = Koha::Old::Holds->find( $reserve_id );
1571         }
1572         return unless $hold;
1573     }
1574
1575     unless ( $biblionumber ) { # FIXME This is a very weird API
1576         $biblionumber = $hold->biblionumber;
1577     }
1578
1579     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1580         $hold->cancel;
1581     }
1582     elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1583
1584         # make sure priority for waiting or in-transit items is 0
1585         my $query = "
1586             UPDATE reserves
1587             SET    priority = 0
1588             WHERE reserve_id = ?
1589             AND found IN ('W', 'T', 'P')
1590         ";
1591         my $sth = $dbh->prepare($query);
1592         $sth->execute( $reserve_id );
1593     }
1594     my @priority;
1595
1596     # get whats left
1597     my $query = "
1598         SELECT reserve_id, borrowernumber, reservedate
1599         FROM   reserves
1600         WHERE  biblionumber   = ?
1601           AND  ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1602         ORDER BY priority ASC
1603     ";
1604     my $sth = $dbh->prepare($query);
1605     $sth->execute( $biblionumber );
1606     while ( my $line = $sth->fetchrow_hashref ) {
1607         push( @priority,     $line );
1608     }
1609
1610     # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1611     # To find the matching index
1612     my $i;
1613     my $key = -1;    # to allow for 0 to be a valid result
1614     for ( $i = 0 ; $i < @priority ; $i++ ) {
1615         if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1616             $key = $i;    # save the index
1617             last;
1618         }
1619     }
1620
1621     # if index exists in array then move it to new position
1622     if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1623         my $new_rank = $rank - 1; # $new_rank is what you want the new index to be in the array
1624         my $moving_item = splice( @priority, $key, 1 );
1625         $new_rank = scalar @priority if $new_rank > scalar @priority;
1626         splice( @priority, $new_rank, 0, $moving_item );
1627     }
1628
1629     # now fix the priority on those that are left....
1630     $query = "
1631         UPDATE reserves
1632         SET    priority = ?
1633         WHERE  reserve_id = ?
1634     ";
1635     $sth = $dbh->prepare($query);
1636     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1637         $sth->execute(
1638             $j + 1,
1639             $priority[$j]->{'reserve_id'}
1640         );
1641     }
1642
1643     unless ( $ignoreSetLowestRank ) {
1644         $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 AND biblionumber = ? ORDER BY priority" );
1645         $sth->execute($biblionumber);
1646       while ( my $res = $sth->fetchrow_hashref() ) {
1647         _FixPriority({
1648             reserve_id => $res->{'reserve_id'},
1649             rank => '999999',
1650             ignoreSetLowestRank => 1
1651         });
1652       }
1653     }
1654 }
1655
1656 =head2 _Findgroupreserve
1657
1658   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1659
1660 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1661 first match found.  If neither, then we look for non-holds-queue based holds.
1662 Lookahead is the number of days to look in advance.
1663
1664 C<&_Findgroupreserve> returns :
1665 C<@results> is an array of references-to-hash whose keys are mostly
1666 fields from the reserves table of the Koha database, plus
1667 C<biblioitemnumber>.
1668
1669 This routine with either return:
1670 1 - Item specific holds from the holds queue
1671 2 - Title level holds from the holds queue
1672 3 - All holds for this biblionumber
1673
1674 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1675
1676 =cut
1677
1678 sub _Findgroupreserve {
1679     my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1680     my $dbh   = C4::Context->dbh;
1681
1682     # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1683     # check for exact targeted match
1684     my $item_level_target_query = qq{
1685         SELECT reserves.biblionumber        AS biblionumber,
1686                reserves.borrowernumber      AS borrowernumber,
1687                reserves.reservedate         AS reservedate,
1688                reserves.branchcode          AS branchcode,
1689                reserves.cancellationdate    AS cancellationdate,
1690                reserves.found               AS found,
1691                reserves.reservenotes        AS reservenotes,
1692                reserves.priority            AS priority,
1693                reserves.timestamp           AS timestamp,
1694                biblioitems.biblioitemnumber AS biblioitemnumber,
1695                reserves.itemnumber          AS itemnumber,
1696                reserves.reserve_id          AS reserve_id,
1697                reserves.itemtype            AS itemtype,
1698                reserves.non_priority        AS non_priority
1699         FROM reserves
1700         JOIN biblioitems USING (biblionumber)
1701         JOIN hold_fill_targets USING (reserve_id)
1702         WHERE found IS NULL
1703         AND priority > 0
1704         AND item_level_request = 1
1705         AND hold_fill_targets.itemnumber = ?
1706         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1707         AND suspend = 0
1708         ORDER BY priority
1709     };
1710     my $sth = $dbh->prepare($item_level_target_query);
1711     $sth->execute($itemnumber, $lookahead||0);
1712     my @results;
1713     if ( my $data = $sth->fetchrow_hashref ) {
1714         push( @results, $data )
1715           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1716     }
1717     return @results if @results;
1718
1719     # check for title-level targeted match
1720     my $title_level_target_query = qq{
1721         SELECT reserves.biblionumber        AS biblionumber,
1722                reserves.borrowernumber      AS borrowernumber,
1723                reserves.reservedate         AS reservedate,
1724                reserves.branchcode          AS branchcode,
1725                reserves.cancellationdate    AS cancellationdate,
1726                reserves.found               AS found,
1727                reserves.reservenotes        AS reservenotes,
1728                reserves.priority            AS priority,
1729                reserves.timestamp           AS timestamp,
1730                biblioitems.biblioitemnumber AS biblioitemnumber,
1731                reserves.itemnumber          AS itemnumber,
1732                reserves.reserve_id          AS reserve_id,
1733                reserves.itemtype            AS itemtype,
1734                reserves.non_priority        AS non_priority
1735         FROM reserves
1736         JOIN biblioitems USING (biblionumber)
1737         JOIN hold_fill_targets USING (reserve_id)
1738         WHERE found IS NULL
1739         AND priority > 0
1740         AND item_level_request = 0
1741         AND hold_fill_targets.itemnumber = ?
1742         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1743         AND suspend = 0
1744         ORDER BY priority
1745     };
1746     $sth = $dbh->prepare($title_level_target_query);
1747     $sth->execute($itemnumber, $lookahead||0);
1748     @results = ();
1749     if ( my $data = $sth->fetchrow_hashref ) {
1750         push( @results, $data )
1751           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1752     }
1753     return @results if @results;
1754
1755     my $query = qq{
1756         SELECT reserves.biblionumber               AS biblionumber,
1757                reserves.borrowernumber             AS borrowernumber,
1758                reserves.reservedate                AS reservedate,
1759                reserves.waitingdate                AS waitingdate,
1760                reserves.branchcode                 AS branchcode,
1761                reserves.cancellationdate           AS cancellationdate,
1762                reserves.found                      AS found,
1763                reserves.reservenotes               AS reservenotes,
1764                reserves.priority                   AS priority,
1765                reserves.timestamp                  AS timestamp,
1766                reserves.itemnumber                 AS itemnumber,
1767                reserves.reserve_id                 AS reserve_id,
1768                reserves.itemtype                   AS itemtype,
1769                reserves.non_priority        AS non_priority
1770         FROM reserves
1771         WHERE reserves.biblionumber = ?
1772           AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1773           AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1774           AND suspend = 0
1775           ORDER BY priority
1776     };
1777     $sth = $dbh->prepare($query);
1778     $sth->execute( $biblio, $itemnumber, $lookahead||0);
1779     @results = ();
1780     while ( my $data = $sth->fetchrow_hashref ) {
1781         push( @results, $data )
1782           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1783     }
1784     return @results;
1785 }
1786
1787 =head2 _koha_notify_reserve
1788
1789   _koha_notify_reserve( $hold->reserve_id );
1790
1791 Sends a notification to the patron that their hold has been filled (through
1792 ModReserveAffect)
1793
1794 The letter code for this notice may be found using the following query:
1795
1796     select distinct letter_code
1797     from message_transports
1798     inner join message_attributes using (message_attribute_id)
1799     where message_name = 'Hold_Filled'
1800
1801 This will probably sipmly be 'HOLD', but because it is defined in the database,
1802 it is subject to addition or change.
1803
1804 The following tables are availalbe witin the notice:
1805
1806     branches
1807     borrowers
1808     biblio
1809     biblioitems
1810     reserves
1811     items
1812
1813 =cut
1814
1815 sub _koha_notify_reserve {
1816     my $reserve_id = shift;
1817     my $hold = Koha::Holds->find($reserve_id);
1818     my $borrowernumber = $hold->borrowernumber;
1819
1820     my $patron = Koha::Patrons->find( $borrowernumber );
1821
1822     # Try to get the borrower's email address
1823     my $to_address = $patron->notice_email_address;
1824
1825     my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1826             borrowernumber => $borrowernumber,
1827             message_name => 'Hold_Filled'
1828     } );
1829
1830     my $library = Koha::Libraries->find( $hold->branchcode );
1831     my $admin_email_address = $library->from_email_address;
1832     $library = $library->unblessed;
1833
1834     my %letter_params = (
1835         module => 'reserves',
1836         branchcode => $hold->branchcode,
1837         lang => $patron->lang,
1838         tables => {
1839             'branches'       => $library,
1840             'borrowers'      => $patron->unblessed,
1841             'biblio'         => $hold->biblionumber,
1842             'biblioitems'    => $hold->biblionumber,
1843             'reserves'       => $hold->unblessed,
1844             'items'          => $hold->itemnumber,
1845         },
1846     );
1847
1848     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.
1849     my $send_notification = sub {
1850         my ( $mtt, $letter_code ) = (@_);
1851         return unless defined $letter_code;
1852         $letter_params{letter_code} = $letter_code;
1853         $letter_params{message_transport_type} = $mtt;
1854         my $letter =  C4::Letters::GetPreparedLetter ( %letter_params );
1855         unless ($letter) {
1856             warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1857             return;
1858         }
1859
1860         C4::Letters::EnqueueLetter( {
1861             letter => $letter,
1862             borrowernumber => $borrowernumber,
1863             from_address => $admin_email_address,
1864             message_transport_type => $mtt,
1865         } );
1866     };
1867
1868     while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1869         next if (
1870                ( $mtt eq 'email' and not $to_address ) # No email address
1871             or ( $mtt eq 'sms'   and not $patron->smsalertnumber ) # No SMS number
1872             or ( $mtt eq 'itiva' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1873             or ( $mtt eq 'phone' and not $patron->phone ) # No phone number to call
1874         );
1875
1876         &$send_notification($mtt, $letter_code);
1877         $notification_sent++;
1878     }
1879     #Making sure that a print notification is sent if no other transport types can be utilized.
1880     if (! $notification_sent) {
1881         &$send_notification('print', 'HOLD');
1882     }
1883
1884 }
1885
1886 =head2 _ShiftPriorityByDateAndPriority
1887
1888   $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1889
1890 This increments the priority of all reserves after the one
1891 with either the lowest date after C<$reservedate>
1892 or the lowest priority after C<$priority>.
1893
1894 It effectively makes room for a new reserve to be inserted with a certain
1895 priority, which is returned.
1896
1897 This is most useful when the reservedate can be set by the user.  It allows
1898 the new reserve to be placed before other reserves that have a later
1899 reservedate.  Since priority also is set by the form in reserves/request.pl
1900 the sub accounts for that too.
1901
1902 =cut
1903
1904 sub _ShiftPriorityByDateAndPriority {
1905     my ( $biblio, $resdate, $new_priority ) = @_;
1906
1907     my $dbh = C4::Context->dbh;
1908     my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1909     my $sth = $dbh->prepare( $query );
1910     $sth->execute( $biblio, $resdate, $new_priority );
1911     my $min_priority = $sth->fetchrow;
1912     # if no such matches are found, $new_priority remains as original value
1913     $new_priority = $min_priority if ( $min_priority );
1914
1915     # Shift the priority up by one; works in conjunction with the next SQL statement
1916     $query = "UPDATE reserves
1917               SET priority = priority+1
1918               WHERE biblionumber = ?
1919               AND borrowernumber = ?
1920               AND reservedate = ?
1921               AND found IS NULL";
1922     my $sth_update = $dbh->prepare( $query );
1923
1924     # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1925     $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1926     $sth = $dbh->prepare( $query );
1927     $sth->execute( $new_priority, $biblio );
1928     while ( my $row = $sth->fetchrow_hashref ) {
1929         $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1930     }
1931
1932     return $new_priority;  # so the caller knows what priority they wind up receiving
1933 }
1934
1935 =head2 MoveReserve
1936
1937   MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1938
1939 Use when checking out an item to handle reserves
1940 If $cancelreserve boolean is set to true, it will remove existing reserve
1941
1942 =cut
1943
1944 sub MoveReserve {
1945     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1946
1947     $cancelreserve //= 0;
1948
1949     my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1950     my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1951     return unless $res;
1952
1953     my $biblionumber = $res->{biblionumber};
1954
1955     if ($res->{borrowernumber} == $borrowernumber) {
1956         my $hold = Koha::Holds->find( $res->{reserve_id} );
1957         $hold->fill;
1958     }
1959     else {
1960         # warn "Reserved";
1961         # The item is reserved by someone else.
1962         # Find this item in the reserves
1963
1964         my $borr_res  = Koha::Holds->search({
1965             borrowernumber => $borrowernumber,
1966             biblionumber   => $biblionumber,
1967         },{
1968             order_by       => 'priority'
1969         })->next();
1970
1971         if ( $borr_res ) {
1972             # The item is reserved by the current patron
1973             $borr_res->fill;
1974         }
1975
1976         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1977             RevertWaitingStatus({ itemnumber => $itemnumber });
1978         }
1979         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1980             my $hold = Koha::Holds->find( $res->{reserve_id} );
1981             $hold->cancel;
1982         }
1983     }
1984 }
1985
1986 =head2 MergeHolds
1987
1988   MergeHolds($dbh,$to_biblio, $from_biblio);
1989
1990 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1991
1992 =cut
1993
1994 sub MergeHolds {
1995     my ( $dbh, $to_biblio, $from_biblio ) = @_;
1996     my $sth = $dbh->prepare(
1997         "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1998     );
1999     $sth->execute($from_biblio);
2000     if ( my $data = $sth->fetchrow_hashref() ) {
2001
2002         # holds exist on old record, if not we don't need to do anything
2003         $sth = $dbh->prepare(
2004             "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2005         $sth->execute( $to_biblio, $from_biblio );
2006
2007         # Reorder by date
2008         # don't reorder those already waiting
2009
2010         $sth = $dbh->prepare(
2011 "SELECT * FROM reserves WHERE biblionumber = ? AND (found NOT IN ('W', 'T', 'P') OR found is NULL) ORDER BY reservedate ASC"
2012         );
2013         my $upd_sth = $dbh->prepare(
2014 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2015         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2016         );
2017         $sth->execute( $to_biblio );
2018         my $priority = 1;
2019         while ( my $reserve = $sth->fetchrow_hashref() ) {
2020             $upd_sth->execute(
2021                 $priority,                    $to_biblio,
2022                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2023                 $reserve->{'itemnumber'}
2024             );
2025             $priority++;
2026         }
2027     }
2028 }
2029
2030 =head2 RevertWaitingStatus
2031
2032   RevertWaitingStatus({ itemnumber => $itemnumber });
2033
2034   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2035
2036   Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2037           item level hold, even if it was only a bibliolevel hold to
2038           begin with. This is because we can no longer know if a hold
2039           was item-level or bib-level after a hold has been set to
2040           waiting status.
2041
2042 =cut
2043
2044 sub RevertWaitingStatus {
2045     my ( $params ) = @_;
2046     my $itemnumber = $params->{'itemnumber'};
2047
2048     return unless ( $itemnumber );
2049
2050     my $dbh = C4::Context->dbh;
2051
2052     ## Get the waiting reserve we want to revert
2053     my $hold = Koha::Holds->search(
2054         {
2055             itemnumber => $itemnumber,
2056             found => { not => undef },
2057         }
2058     )->next;
2059
2060     ## Increment the priority of all other non-waiting
2061     ## reserves for this bib record
2062     my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2063                            ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2064
2065     ## Fix up the currently waiting reserve
2066     $hold->set(
2067         {
2068             priority    => 1,
2069             found       => undef,
2070             waitingdate => undef,
2071             expirationdate => $hold->patron_expiration_date,
2072             itemnumber  => $hold->item_level_hold ? $hold->itemnumber : undef,
2073         }
2074     )->store();
2075
2076     _FixPriority( { biblionumber => $hold->biblionumber } );
2077
2078     return $hold;
2079 }
2080
2081 =head2 ReserveSlip
2082
2083 ReserveSlip(
2084     {
2085         branchcode     => $branchcode,
2086         borrowernumber => $borrowernumber,
2087         biblionumber   => $biblionumber,
2088         [ itemnumber   => $itemnumber, ]
2089         [ barcode      => $barcode, ]
2090     }
2091   )
2092
2093 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2094
2095 The letter code will be HOLD_SLIP, and the following tables are
2096 available within the slip:
2097
2098     reserves
2099     branches
2100     borrowers
2101     biblio
2102     biblioitems
2103     items
2104
2105 =cut
2106
2107 sub ReserveSlip {
2108     my ($args) = @_;
2109     my $branchcode     = $args->{branchcode};
2110     my $reserve_id = $args->{reserve_id};
2111
2112     my $hold = Koha::Holds->find($reserve_id);
2113     return unless $hold;
2114
2115     my $patron = $hold->borrower;
2116     my $reserve = $hold->unblessed;
2117
2118     return  C4::Letters::GetPreparedLetter (
2119         module => 'circulation',
2120         letter_code => 'HOLD_SLIP',
2121         branchcode => $branchcode,
2122         lang => $patron->lang,
2123         tables => {
2124             'reserves'    => $reserve,
2125             'branches'    => $reserve->{branchcode},
2126             'borrowers'   => $reserve->{borrowernumber},
2127             'biblio'      => $reserve->{biblionumber},
2128             'biblioitems' => $reserve->{biblionumber},
2129             'items'       => $reserve->{itemnumber},
2130         },
2131     );
2132 }
2133
2134 =head2 GetReservesControlBranch
2135
2136   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2137
2138   Return the branchcode to be used to determine which reserves
2139   policy applies to a transaction.
2140
2141   C<$item> is a hashref for an item. Only 'homebranch' is used.
2142
2143   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2144
2145 =cut
2146
2147 sub GetReservesControlBranch {
2148     my ( $item, $borrower ) = @_;
2149
2150     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2151
2152     my $branchcode =
2153         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2154       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2155       :                                              undef;
2156
2157     return $branchcode;
2158 }
2159
2160 =head2 CalculatePriority
2161
2162     my $p = CalculatePriority($biblionumber, $resdate);
2163
2164 Calculate priority for a new reserve on biblionumber, placing it at
2165 the end of the line of all holds whose start date falls before
2166 the current system time and that are neither on the hold shelf
2167 or in transit.
2168
2169 The reserve date parameter is optional; if it is supplied, the
2170 priority is based on the set of holds whose start date falls before
2171 the parameter value.
2172
2173 After calculation of this priority, it is recommended to call
2174 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2175 AddReserves.
2176
2177 =cut
2178
2179 sub CalculatePriority {
2180     my ( $biblionumber, $resdate ) = @_;
2181
2182     my $sql = q{
2183         SELECT COUNT(*) FROM reserves
2184         WHERE biblionumber = ?
2185         AND   priority > 0
2186         AND   (found IS NULL OR found = '')
2187     };
2188     #skip found==W or found==T or found==P (waiting, transit or processing holds)
2189     if( $resdate ) {
2190         $sql.= ' AND ( reservedate <= ? )';
2191     }
2192     else {
2193         $sql.= ' AND ( reservedate < NOW() )';
2194     }
2195     my $dbh = C4::Context->dbh();
2196     my @row = $dbh->selectrow_array(
2197         $sql,
2198         undef,
2199         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2200     );
2201
2202     return @row ? $row[0]+1 : 1;
2203 }
2204
2205 =head2 IsItemOnHoldAndFound
2206
2207     my $bool = IsItemFoundHold( $itemnumber );
2208
2209     Returns true if the item is currently on hold
2210     and that hold has a non-null found status ( W, T, etc. )
2211
2212 =cut
2213
2214 sub IsItemOnHoldAndFound {
2215     my ($itemnumber) = @_;
2216
2217     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2218
2219     my $found = $rs->count(
2220         {
2221             itemnumber => $itemnumber,
2222             found      => { '!=' => undef }
2223         }
2224     );
2225
2226     return $found;
2227 }
2228
2229 =head2 GetMaxPatronHoldsForRecord
2230
2231 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2232
2233 For multiple holds on a given record for a given patron, the max
2234 number of record level holds that a patron can be placed is the highest
2235 value of the holds_per_record rule for each item if the record for that
2236 patron. This subroutine finds and returns the highest holds_per_record
2237 rule value for a given patron id and record id.
2238
2239 =cut
2240
2241 sub GetMaxPatronHoldsForRecord {
2242     my ( $borrowernumber, $biblionumber ) = @_;
2243
2244     my $patron = Koha::Patrons->find($borrowernumber);
2245     my @items = Koha::Items->search( { biblionumber => $biblionumber } )->as_list;
2246
2247     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2248
2249     my $categorycode = $patron->categorycode;
2250     my $branchcode;
2251     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2252
2253     my $max = 0;
2254     foreach my $item (@items) {
2255         my $itemtype = $item->effective_itemtype();
2256
2257         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2258
2259         my $rule = Koha::CirculationRules->get_effective_rule({
2260             categorycode => $categorycode,
2261             itemtype     => $itemtype,
2262             branchcode   => $branchcode,
2263             rule_name    => 'holds_per_record'
2264         });
2265         my $holds_per_record = $rule ? $rule->rule_value : 0;
2266         $max = $holds_per_record if $holds_per_record > $max;
2267     }
2268
2269     return $max;
2270 }
2271
2272 =head1 AUTHOR
2273
2274 Koha Development Team <http://koha-community.org/>
2275
2276 =cut
2277
2278 1;