Bug 23091: Move _Restore to Koha::Item store trigger
[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::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;
49
50 use Carp;
51 use Data::Dumper;
52 use List::MoreUtils qw( firstidx any );
53
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
55
56 =head1 NAME
57
58 C4::Reserves - Koha functions for dealing with reservation.
59
60 =head1 SYNOPSIS
61
62   use C4::Reserves;
63
64 =head1 DESCRIPTION
65
66 This modules provides somes functions to deal with reservations.
67
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
87
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
94
95 =head1 FUNCTIONS
96
97 =cut
98
99 BEGIN {
100     require Exporter;
101     @ISA = qw(Exporter);
102     @EXPORT = qw(
103         &AddReserve
104
105         &GetReserveStatus
106
107         &GetOtherReserves
108
109         &ModReserveFill
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         IsItemOnHoldAndFound
138
139         GetMaxPatronHoldsForRecord
140     );
141     @EXPORT_OK = qw( MergeHolds );
142 }
143
144 =head2 AddReserve
145
146     AddReserve(
147         {
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,
159         }
160     );
161
162 Adds reserve and generates HOLDPLACED message.
163
164 The following tables are available witin the HOLDPLACED message:
165
166     branches
167     borrowers
168     biblio
169     biblioitems
170     items
171     reserves
172
173 =cut
174
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};
189
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' });
192
193     $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
194
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
199
200         if (
201             # If item is already checked out, it cannot be set waiting
202             !$item->onloan
203
204             # The item can't be waiting if it needs a transfer
205             && $item->holdingbranch eq $branch
206
207             # Similarly, if in transit it can't be waiting
208             && !$item->get_transfer
209
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 )
212
213             # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
214             && !$item->current_holds->count )
215         {
216             $priority = 0;
217             $found = 'W';
218         }
219     }
220
221     if ( C4::Context->preference('AllowHoldDateInFuture') ) {
222
223         # Make room in reserves for this before those of a later reserve date
224         $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
225     }
226
227     my $waitingdate;
228
229     # If the reserv had the waiting status, we had the value of the resdate
230     if ( $found && $found eq 'W' ) {
231         $waitingdate = $resdate;
232     }
233
234     # Don't add itemtype limit if specific item is selected
235     $itemtype = undef if $checkitem;
236
237     # updates take place here
238     my $hold = Koha::Hold->new(
239         {
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,
253         }
254     )->store();
255     $hold->set_waiting() if $found && $found eq 'W';
256
257     logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
258         if C4::Context->preference('HoldsLog');
259
260     my $reserve_id = $hold->id();
261
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 );
266     }
267
268     _FixPriority({ biblionumber => $biblionumber});
269
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,
286             },
287         ) ) {
288
289             my $branch_email_address = $library->inbound_email_address;
290
291             C4::Letters::EnqueueLetter(
292                 {
293                     letter                 => $letter,
294                     borrowernumber         => $borrowernumber,
295                     message_transport_type => 'email',
296                     to_address             => $branch_email_address,
297                 }
298             );
299         }
300     }
301
302     Koha::Plugins->call('after_hold_create', $hold);
303
304     return $reserve_id;
305 }
306
307 =head2 CanBookBeReserved
308
309   $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode, $params)
310   if ($canReserve eq 'OK') { #We can reserve this Item! }
311
312   $params are passed directly through to CanItemBeReserved
313
314 See CanItemBeReserved() for possible return values.
315
316 =cut
317
318 sub CanBookBeReserved{
319     my ($borrowernumber, $biblionumber, $pickup_branchcode, $params) = @_;
320
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' };
325     }
326
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);
332     }
333
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';
338     }
339     return $canReserve;
340 }
341
342 =head2 CanItemBeReserved
343
344   $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode, $params)
345   if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
346
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
350
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.
362
363 =cut
364
365 sub CanItemBeReserved {
366     my ( $borrowernumber, $itemnumber, $pickup_branchcode, $params ) = @_;
367
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
373
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;
380
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') );
385
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;
390
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();
394
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' };
399     }
400
401     my $controlbranch = C4::Context->preference('ReservesControlBranch');
402
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 = ?
410     };
411
412     my $branchcode  = "";
413     my $branchfield = "reserves.branchcode";
414
415     if ( $controlbranch eq "ItemHomeLibrary" ) {
416         $branchfield = "items.homebranch";
417         $branchcode  = $item->homebranch;
418     }
419     elsif ( $controlbranch eq "PatronLibrary" ) {
420         $branchfield = "borrowers.branchcode";
421         $branchcode  = $borrower->{branchcode};
422     }
423
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};
430     }
431     else {
432         $ruleitemtype = undef;
433     }
434
435     my $search_params = {
436         borrowernumber => $borrowernumber,
437         biblionumber   => $item->biblionumber,
438     };
439     $search_params->{found} = undef if $params->{ignore_found_holds};
440
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 };
445     }
446
447     my $today_holds = Koha::Holds->search({
448         borrowernumber => $borrowernumber,
449         reservedate    => dt_from_string->date
450     });
451
452     if (   defined $holds_per_day && $holds_per_day ne ''
453         && $today_holds->count() >= $holds_per_day )
454     {
455         return { status => 'tooManyReservesToday', limit => $holds_per_day };
456     }
457
458     # we retrieve count
459
460     $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
461
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;
469
470     my $sthcount = $dbh->prepare($querycount);
471
472     if ( defined $ruleitemtype ) {
473         $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
474     }
475     else {
476         $sthcount->execute( $borrowernumber, $branchcode );
477     }
478
479     my $reservecount = "0";
480     if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
481         $reservecount = $rowcount->{count};
482     }
483
484     # we check if it's ok or not
485     if (   defined  $allowedreserves && $allowedreserves ne ''
486         && $reservecount >= $allowedreserves ) {
487         return { status => 'tooManyReserves', limit => $allowedreserves };
488     }
489
490     # Now we need to check hold limits by patron category
491     my $rule = Koha::CirculationRules->get_effective_rule(
492         {
493             categorycode => $borrower->{categorycode},
494             branchcode   => $branchcode,
495             rule_name    => 'max_holds',
496         }
497     );
498     if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
499         my $total_holds_count = Koha::Holds->search(
500             {
501                 borrowernumber => $borrower->{borrowernumber}
502             }
503         )->count();
504
505         return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
506     }
507
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?
512
513     if ( $branchitemrule->{holdallowed} == 0 ) {
514         return { status => 'notReservable' };
515     }
516
517     if (   $branchitemrule->{holdallowed} == 1
518         && $borrower->{branchcode} ne $item->homebranch )
519     {
520         return { status => 'cannotReserveFromOtherBranches' };
521     }
522
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' };
527         }
528     }
529
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') )
534     {
535         if ( $item->homebranch ne $borrower->{branchcode} ) {
536             return { status => 'cannotReserveFromOtherBranches' };
537         }
538     }
539
540     if ($pickup_branchcode) {
541         my $destination = Koha::Libraries->find({
542             branchcode => $pickup_branchcode,
543         });
544
545         unless ($destination) {
546             return { status => 'libraryNotFound' };
547         }
548         unless ($destination->pickup_location) {
549             return { status => 'libraryNotPickupLocation' };
550         }
551         unless ($item->can_be_transferred({ to => $destination })) {
552             return { status => 'cannotBeTransferred' };
553         }
554         unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
555             return { status => 'pickupNotInHoldGroup' };
556         }
557         unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
558             return { status => 'pickupNotInHoldGroup' };
559         }
560     }
561
562     return { status => 'OK' };
563 }
564
565 =head2 CanReserveBeCanceledFromOpac
566
567     $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
568
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
572
573 =cut
574
575 sub CanReserveBeCanceledFromOpac {
576     my ($reserve_id, $borrowernumber) = @_;
577
578     return unless $reserve_id and $borrowernumber;
579     my $reserve = Koha::Holds->find($reserve_id);
580
581     return 0 unless $reserve->borrowernumber == $borrowernumber;
582     return $reserve->is_cancelable_from_opac;
583 }
584
585 =head2 GetOtherReserves
586
587   ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
588
589 Check queued list of this document and check if this document must be transferred
590
591 =cut
592
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'},
606             );
607
608             #launch the subroutine dotransfer
609             C4::Items::ModItemTransfer(
610                 $itemnumber,
611                 $item->holdingbranch,
612                 $checkreserves->{'branchcode'},
613                 'Reserve'
614               ),
615               ;
616         }
617
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'},
624             );
625             ModReserveStatus($itemnumber,'W');
626         }
627
628         $nextreservinfo = $checkreserves;
629     }
630
631     return ( $messages, $nextreservinfo );
632 }
633
634 =head2 ChargeReserveFee
635
636     $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
637
638     Charge the fee for a reserve (if $fee > 0)
639
640 =cut
641
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(
646         {
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
656         }
657     );
658 }
659
660 =head2 GetReserveFee
661
662     $fee = GetReserveFee( $borrowernumber, $biblionumber );
663
664     Calculate the fee for a reserve (if applicable).
665
666 =cut
667
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 = ?
672     };
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
677     };
678     my $holds_qry = qq{
679 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
680     };
681
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;
697         }
698     }
699     return $fee;
700 }
701
702 =head2 GetReserveStatus
703
704   $reservestatus = GetReserveStatus($itemnumber);
705
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.
708
709 =cut
710
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) = @_;
717
718     my $dbh = C4::Context->dbh;
719
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;
725     }
726
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';
731     }
732
733     return 'Reserved' if defined $priority && $priority > 0;
734
735     return ''; # empty string here will remove need for checking undef, or less log lines
736 }
737
738 =head2 CheckReserves
739
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);
743
744 Find a book in the reserves.
745
746 C<$itemnumber> is the book's item number.
747 C<$lookahead> is the number of days to look in advance for future reserves.
748
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>.
752
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>.
756
757 C<&CheckReserves> returns a two-element list:
758
759 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
760
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.
764
765 =cut
766
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
785         ";
786     }
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
800         ";
801     }
802
803     if ($item) {
804         $sth = $dbh->prepare("$select WHERE itemnumber = ?");
805         $sth->execute($item);
806     }
807     else {
808         $sth = $dbh->prepare("$select WHERE barcode = ?");
809         $sth->execute($barcode);
810     }
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') );
814
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.
818
819     my @SkipHoldTrapOnNotForLoanValue = split( '|', C4::Context->preference('SkipHoldTrapOnNotForLoanValue') );
820     return if @SkipHoldTrapOnNotForLoanValue && grep( $notforloan_per_item, @SkipHoldTrapOnNotForLoanValue );
821
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;
824
825     # Find this item in the reserves
826     my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
827
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;
833
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');
838
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
848                 }
849             } else {
850                 my $patron;
851                 my $item;
852                 my $local_hold_match;
853
854                 if ($LocalHoldsPriority) {
855                     $patron = Koha::Patrons->find( $res->{borrowernumber} );
856                     $item = Koha::Items->find($itemnumber);
857
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;
870                     }
871                 }
872
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;
892                 }
893             }
894         }
895     }
896
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 );
902     }
903
904     return ( '' );
905 }
906
907 =head2 CancelExpiredReserves
908
909   CancelExpiredReserves();
910
911 Cancels all reserves with an expiration date from before today.
912
913 =cut
914
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');
920
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;
924
925     # FIXME To move to Koha::Holds->search_expired (?)
926     my $holds = Koha::Holds->search( $params );
927
928     while ( my $hold = $holds->next ) {
929         my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
930
931         next if !$cancel_on_holidays && $calendar->is_holiday( $today );
932
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;
937         }
938         $hold->cancel( $cancel_params );
939     }
940 }
941
942 =head2 AutoUnsuspendReserves
943
944   AutoUnsuspendReserves();
945
946 Unsuspends all suspended reserves with a suspend_until date from before today.
947
948 =cut
949
950 sub AutoUnsuspendReserves {
951     my $today = dt_from_string();
952
953     my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
954
955     map { $_->resume() } @holds;
956 }
957
958 =head2 ModReserve
959
960   ModReserve({ rank => $rank,
961                reserve_id => $reserve_id,
962                branchcode => $branchcode
963                [, itemnumber => $itemnumber ]
964                [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
965               });
966
967 Change a hold request's priority or cancel it.
968
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.
973
974 If C<$rank> is 'del', the hold request is cancelled.
975
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.
981
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.
986
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.
991
992 =cut
993
994 sub ModReserve {
995     my ( $params ) = @_;
996
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'};
1005
1006     return if $rank eq "W";
1007     return if $rank eq "n";
1008
1009     return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1010
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;
1017     }
1018
1019     $hold ||= Koha::Holds->find($reserve_id);
1020
1021     if ( $rank eq "del" ) {
1022         $hold->cancel({ cancellation_reason => $cancellation_reason });
1023     }
1024     elsif ($rank =~ /^\d+/ and $rank > 0) {
1025         logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1026             if C4::Context->preference('HoldsLog');
1027
1028         my $properties = {
1029             priority    => $rank,
1030             branchcode  => $branchcode,
1031             itemnumber  => $itemnumber,
1032             found       => undef,
1033             waitingdate => undef
1034         };
1035         if (exists $params->{reservedate}) {
1036             $properties->{reservedate} = $params->{reservedate} || undef;
1037         }
1038         if (exists $params->{expirationdate}) {
1039             $properties->{expirationdate} = $params->{expirationdate} || undef;
1040         }
1041
1042         $hold->set($properties)->store();
1043
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();
1052             }
1053         }
1054
1055         _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1056     }
1057 }
1058
1059 =head2 ModReserveFill
1060
1061   &ModReserveFill($reserve);
1062
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.
1065
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.
1068
1069 =cut
1070
1071 sub ModReserveFill {
1072     my ($res) = @_;
1073     my $reserve_id = $res->{'reserve_id'};
1074
1075     my $hold = Koha::Holds->find($reserve_id);
1076     # get the priority on this record....
1077     my $priority = $hold->priority;
1078
1079     # update the hold statuses, no need to store it though, we will be deleting it anyway
1080     $hold->set(
1081         {
1082             found    => 'F',
1083             priority => 0,
1084         }
1085     );
1086
1087     logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1088         if C4::Context->preference('HoldsLog');
1089
1090     # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1091     Koha::Old::Hold->new( $hold->unblessed() )->store();
1092
1093     $hold->delete();
1094
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 );
1098     }
1099
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 } );
1104     }
1105 }
1106
1107 =head2 ModReserveStatus
1108
1109   &ModReserveStatus($itemnumber, $newstatus);
1110
1111 Update the reserve status for the active (priority=0) reserve.
1112
1113 $itemnumber is the itemnumber the reserve is on
1114
1115 $newstatus is the new status.
1116
1117 =cut
1118
1119 sub ModReserveStatus {
1120
1121     #first : check if we have a reservation for this item .
1122     my ($itemnumber, $newstatus) = @_;
1123     my $dbh = C4::Context->dbh;
1124
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 );
1128
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 );
1134     }
1135 }
1136
1137 =head2 ModReserveAffect
1138
1139   &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id, $desk_id);
1140
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.
1145
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
1149
1150 =cut
1151
1152 sub ModReserveAffect {
1153     my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id, $desk_id ) = @_;
1154     my $dbh = C4::Context->dbh;
1155
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;
1161
1162     # get request - need to find out if item is already
1163     # waiting in order to not send duplicate hold filled notifications
1164
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();
1172
1173     return unless $hold;
1174
1175     my $already_on_shelf = $hold->found && $hold->found eq 'W';
1176
1177     $hold->itemnumber($itemnumber);
1178
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
1191         });
1192         while( my $transfer = $transfers->next ){
1193             $transfer->datearrived( dt_from_string() )->store;
1194         };
1195     }
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     logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1206         if C4::Context->preference('HoldsLog');
1207
1208     return;
1209 }
1210
1211 =head2 ModReserveCancelAll
1212
1213   ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1214
1215 function to cancel reserv,check other reserves, and transfer document if it's necessary
1216
1217 =cut
1218
1219 sub ModReserveCancelAll {
1220     my $messages;
1221     my $nextreservinfo;
1222     my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1223
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 });
1228
1229     #step 2 launch the subroutine of the others reserves
1230     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1231
1232     return ( $messages, $nextreservinfo->{borrowernumber} );
1233 }
1234
1235 =head2 ModReserveMinusPriority
1236
1237   &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1238
1239 Reduce the values of queued list
1240
1241 =cut
1242
1243 sub ModReserveMinusPriority {
1244     my ( $itemnumber, $reserve_id ) = @_;
1245
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 = ?
1252     ";
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' });
1257 }
1258
1259 =head2 IsAvailableForItemLevelRequest
1260
1261   my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1262
1263 Checks whether a given item record is available for an
1264 item-level hold request.  An item is available if
1265
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
1271
1272 Need to check the issuingrules onshelfholds column,
1273 if this is set items on the shelf can be placed on hold
1274
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.
1280
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.
1285
1286 =cut
1287
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;
1295
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;
1303
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'));
1310
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} );
1322     }
1323
1324     my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1325
1326     if ( $on_shelf_holds == 1 ) {
1327         return 1;
1328     } elsif ( $on_shelf_holds == 2 ) {
1329
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;
1334
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 );
1339     }
1340 }
1341
1342 =head2 ItemsAnyAvailableAndNotRestricted
1343
1344   ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1345
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)
1350
1351 =cut
1352
1353 sub ItemsAnyAvailableAndNotRestricted {
1354     my $param = shift;
1355
1356     my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1357
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 } );
1364
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';
1378     }
1379
1380     return 0;
1381 }
1382
1383 =head2 AlterPriority
1384
1385   AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1386
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
1389
1390 =cut
1391
1392 sub AlterPriority {
1393     my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1394
1395     my $hold = Koha::Holds->find( $reserve_id );
1396     return unless $hold;
1397
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;
1401     }
1402
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 });
1413     }
1414
1415     # FIXME Should return the new priority
1416 }
1417
1418 =head2 ToggleLowestPriority
1419
1420   ToggleLowestPriority( $borrowernumber, $biblionumber );
1421
1422 This function sets the lowestPriority field to true if is false, and false if it is true.
1423
1424 =cut
1425
1426 sub ToggleLowestPriority {
1427     my ( $reserve_id ) = @_;
1428
1429     my $dbh = C4::Context->dbh;
1430
1431     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1432     $sth->execute( $reserve_id );
1433
1434     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1435 }
1436
1437 =head2 ToggleSuspend
1438
1439   ToggleSuspend( $reserve_id );
1440
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.
1444
1445 =cut
1446
1447 sub ToggleSuspend {
1448     my ( $reserve_id, $suspend_until ) = @_;
1449
1450     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1451
1452     my $hold = Koha::Holds->find( $reserve_id );
1453
1454     if ( $hold->is_suspended ) {
1455         $hold->resume()
1456     } else {
1457         $hold->suspend_hold( $suspend_until );
1458     }
1459 }
1460
1461 =head2 SuspendAll
1462
1463   SuspendAll(
1464       borrowernumber   => $borrowernumber,
1465       [ biblionumber   => $biblionumber, ]
1466       [ suspend_until  => $suspend_until, ]
1467       [ suspend        => $suspend ]
1468   );
1469
1470   This function accepts a set of hash keys as its parameters.
1471   It requires either borrowernumber or biblionumber, or both.
1472
1473   suspend_until is wholly optional.
1474
1475 =cut
1476
1477 sub SuspendAll {
1478     my %params = @_;
1479
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;
1484
1485     $suspend_until = eval { dt_from_string($suspend_until) }
1486       if ( defined($suspend_until) );
1487
1488     return unless ( $borrowernumber || $biblionumber );
1489
1490     my $params;
1491     $params->{found}          = undef;
1492     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1493     $params->{biblionumber}   = $biblionumber if $biblionumber;
1494
1495     my @holds = Koha::Holds->search($params);
1496
1497     if ($suspend) {
1498         map { $_->suspend_hold($suspend_until) } @holds;
1499     }
1500     else {
1501         map { $_->resume() } @holds;
1502     }
1503 }
1504
1505
1506 =head2 _FixPriority
1507
1508   _FixPriority({
1509     reserve_id => $reserve_id,
1510     [rank => $rank,]
1511     [ignoreSetLowestRank => $ignoreSetLowestRank]
1512   });
1513
1514   or
1515
1516   _FixPriority({ biblionumber => $biblionumber});
1517
1518 This routine adjusts the priority of a hold request and holds
1519 on the same bib.
1520
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.
1526
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.
1532
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.
1535
1536 Note that the ignoreSetLowestRank parameter is meant to be used only
1537 when _FixPriority calls itself.
1538
1539 =cut
1540
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};
1547
1548     my $dbh = C4::Context->dbh;
1549
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 );
1556         }
1557         return unless $hold;
1558     }
1559
1560     unless ( $biblionumber ) { # FIXME This is a very weird API
1561         $biblionumber = $hold->biblionumber;
1562     }
1563
1564     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1565         $hold->cancel;
1566     }
1567     elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1568
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')
1575         ";
1576         my $sth = $dbh->prepare($query);
1577         $sth->execute( $reserve_id );
1578     }
1579     my @priority;
1580
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
1588     ";
1589     my $sth = $dbh->prepare($query);
1590     $sth->execute( $biblionumber );
1591     while ( my $line = $sth->fetchrow_hashref ) {
1592         push( @priority,     $line );
1593     }
1594
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;
1603         }
1604     }
1605
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 );
1612     }
1613
1614     # now fix the priority on those that are left....
1615     $query = "
1616         UPDATE reserves
1617         SET    priority = ?
1618         WHERE  reserve_id = ?
1619     ";
1620     $sth = $dbh->prepare($query);
1621     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1622         $sth->execute(
1623             $j + 1,
1624             $priority[$j]->{'reserve_id'}
1625         );
1626     }
1627
1628     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1629     $sth->execute();
1630
1631     unless ( $ignoreSetLowestRank ) {
1632       while ( my $res = $sth->fetchrow_hashref() ) {
1633         _FixPriority({
1634             reserve_id => $res->{'reserve_id'},
1635             rank => '999999',
1636             ignoreSetLowestRank => 1
1637         });
1638       }
1639     }
1640 }
1641
1642 =head2 _Findgroupreserve
1643
1644   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1645
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.
1649
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>.
1654
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
1659
1660 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1661
1662 =cut
1663
1664 sub _Findgroupreserve {
1665     my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1666     my $dbh   = C4::Context->dbh;
1667
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
1695     };
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 ;
1702     }
1703     return @results if @results;
1704
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
1731     };
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 ;
1738     }
1739     return @results if @results;
1740
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
1762     };
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 ;
1769     }
1770     return @results;
1771 }
1772
1773 =head2 _koha_notify_reserve
1774
1775   _koha_notify_reserve( $hold->reserve_id );
1776
1777 Sends a notification to the patron that their hold has been filled (through
1778 ModReserveAffect, _not_ ModReserveFill)
1779
1780 The letter code for this notice may be found using the following query:
1781
1782     select distinct letter_code
1783     from message_transports
1784     inner join message_attributes using (message_attribute_id)
1785     where message_name = 'Hold_Filled'
1786
1787 This will probably sipmly be 'HOLD', but because it is defined in the database,
1788 it is subject to addition or change.
1789
1790 The following tables are availalbe witin the notice:
1791
1792     branches
1793     borrowers
1794     biblio
1795     biblioitems
1796     reserves
1797     items
1798
1799 =cut
1800
1801 sub _koha_notify_reserve {
1802     my $reserve_id = shift;
1803     my $hold = Koha::Holds->find($reserve_id);
1804     my $borrowernumber = $hold->borrowernumber;
1805
1806     my $patron = Koha::Patrons->find( $borrowernumber );
1807
1808     # Try to get the borrower's email address
1809     my $to_address = $patron->notice_email_address;
1810
1811     my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1812             borrowernumber => $borrowernumber,
1813             message_name => 'Hold_Filled'
1814     } );
1815
1816     my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1817
1818     my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1819
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,
1831         },
1832     );
1833
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;
1844         }
1845
1846         C4::Letters::EnqueueLetter( {
1847             letter => $letter,
1848             borrowernumber => $borrowernumber,
1849             from_address => $admin_email_address,
1850             message_transport_type => $mtt,
1851         } );
1852     };
1853
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
1860         );
1861
1862         &$send_notification($mtt, $letter_code);
1863         $notification_sent++;
1864     }
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');
1868     }
1869
1870 }
1871
1872 =head2 _ShiftPriorityByDateAndPriority
1873
1874   $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1875
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>.
1879
1880 It effectively makes room for a new reserve to be inserted with a certain
1881 priority, which is returned.
1882
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.
1887
1888 =cut
1889
1890 sub _ShiftPriorityByDateAndPriority {
1891     my ( $biblio, $resdate, $new_priority ) = @_;
1892
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 );
1900
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 );
1909
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} );
1916     }
1917
1918     return $new_priority;  # so the caller knows what priority they wind up receiving
1919 }
1920
1921 =head2 MoveReserve
1922
1923   MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1924
1925 Use when checking out an item to handle reserves
1926 If $cancelreserve boolean is set to true, it will remove existing reserve
1927
1928 =cut
1929
1930 sub MoveReserve {
1931     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1932
1933     $cancelreserve //= 0;
1934
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;
1938
1939     my $biblionumber     =  $res->{biblionumber};
1940
1941     if ($res->{borrowernumber} == $borrowernumber) {
1942         ModReserveFill($res);
1943     }
1944     else {
1945         # warn "Reserved";
1946         # The item is reserved by someone else.
1947         # Find this item in the reserves
1948
1949         my $borr_res  = Koha::Holds->search({
1950             borrowernumber => $borrowernumber,
1951             biblionumber   => $biblionumber,
1952         },{
1953             order_by       => 'priority'
1954         })->next();
1955
1956         if ( $borr_res ) {
1957             # The item is reserved by the current patron
1958             ModReserveFill($borr_res->unblessed);
1959         }
1960
1961         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1962             RevertWaitingStatus({ itemnumber => $itemnumber });
1963         }
1964         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1965             my $hold = Koha::Holds->find( $res->{reserve_id} );
1966             $hold->cancel;
1967         }
1968     }
1969 }
1970
1971 =head2 MergeHolds
1972
1973   MergeHolds($dbh,$to_biblio, $from_biblio);
1974
1975 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1976
1977 =cut
1978
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 = ?"
1983     );
1984     $sth->execute($from_biblio);
1985     if ( my $data = $sth->fetchrow_hashref() ) {
1986
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 );
1991
1992         # Reorder by date
1993         # don't reorder those already waiting
1994
1995         $sth = $dbh->prepare(
1996 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1997         );
1998         my $upd_sth = $dbh->prepare(
1999 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2000         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2001         );
2002         $sth->execute( $to_biblio, 'W', 'T', 'P' );
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'}
2009             );
2010             $priority++;
2011         }
2012     }
2013 }
2014
2015 =head2 RevertWaitingStatus
2016
2017   RevertWaitingStatus({ itemnumber => $itemnumber });
2018
2019   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2020
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.
2026
2027 =cut
2028
2029 sub RevertWaitingStatus {
2030     my ( $params ) = @_;
2031     my $itemnumber = $params->{'itemnumber'};
2032
2033     return unless ( $itemnumber );
2034
2035     my $dbh = C4::Context->dbh;
2036
2037     ## Get the waiting reserve we want to revert
2038     my $hold = Koha::Holds->search(
2039         {
2040             itemnumber => $itemnumber,
2041             found => { not => undef },
2042         }
2043     )->next;
2044
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 });
2049
2050     ## Fix up the currently waiting reserve
2051     $hold->set(
2052         {
2053             priority    => 1,
2054             found       => undef,
2055             waitingdate => undef,
2056             itemnumber  => $hold->item_level_hold ? $hold->itemnumber : undef,
2057         }
2058     )->store();
2059
2060     _FixPriority( { biblionumber => $hold->biblionumber } );
2061
2062     return $hold;
2063 }
2064
2065 =head2 ReserveSlip
2066
2067 ReserveSlip(
2068     {
2069         branchcode     => $branchcode,
2070         borrowernumber => $borrowernumber,
2071         biblionumber   => $biblionumber,
2072         [ itemnumber   => $itemnumber, ]
2073         [ barcode      => $barcode, ]
2074     }
2075   )
2076
2077 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2078
2079 The letter code will be HOLD_SLIP, and the following tables are
2080 available within the slip:
2081
2082     reserves
2083     branches
2084     borrowers
2085     biblio
2086     biblioitems
2087     items
2088
2089 =cut
2090
2091 sub ReserveSlip {
2092     my ($args) = @_;
2093     my $branchcode     = $args->{branchcode};
2094     my $reserve_id = $args->{reserve_id};
2095
2096     my $hold = Koha::Holds->find($reserve_id);
2097     return unless $hold;
2098
2099     my $patron = $hold->borrower;
2100     my $reserve = $hold->unblessed;
2101
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},
2114         },
2115     );
2116 }
2117
2118 =head2 GetReservesControlBranch
2119
2120   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2121
2122   Return the branchcode to be used to determine which reserves
2123   policy applies to a transaction.
2124
2125   C<$item> is a hashref for an item. Only 'homebranch' is used.
2126
2127   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2128
2129 =cut
2130
2131 sub GetReservesControlBranch {
2132     my ( $item, $borrower ) = @_;
2133
2134     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2135
2136     my $branchcode =
2137         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2138       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2139       :                                              undef;
2140
2141     return $branchcode;
2142 }
2143
2144 =head2 CalculatePriority
2145
2146     my $p = CalculatePriority($biblionumber, $resdate);
2147
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.
2152
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.
2156
2157 After calculation of this priority, it is recommended to call
2158 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2159 AddReserves.
2160
2161 =cut
2162
2163 sub CalculatePriority {
2164     my ( $biblionumber, $resdate ) = @_;
2165
2166     my $sql = q{
2167         SELECT COUNT(*) FROM reserves
2168         WHERE biblionumber = ?
2169         AND   priority > 0
2170         AND   (found IS NULL OR found = '')
2171     };
2172     #skip found==W or found==T or found==P (waiting, transit or processing holds)
2173     if( $resdate ) {
2174         $sql.= ' AND ( reservedate <= ? )';
2175     }
2176     else {
2177         $sql.= ' AND ( reservedate < NOW() )';
2178     }
2179     my $dbh = C4::Context->dbh();
2180     my @row = $dbh->selectrow_array(
2181         $sql,
2182         undef,
2183         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2184     );
2185
2186     return @row ? $row[0]+1 : 1;
2187 }
2188
2189 =head2 IsItemOnHoldAndFound
2190
2191     my $bool = IsItemFoundHold( $itemnumber );
2192
2193     Returns true if the item is currently on hold
2194     and that hold has a non-null found status ( W, T, etc. )
2195
2196 =cut
2197
2198 sub IsItemOnHoldAndFound {
2199     my ($itemnumber) = @_;
2200
2201     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2202
2203     my $found = $rs->count(
2204         {
2205             itemnumber => $itemnumber,
2206             found      => { '!=' => undef }
2207         }
2208     );
2209
2210     return $found;
2211 }
2212
2213 =head2 GetMaxPatronHoldsForRecord
2214
2215 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2216
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.
2222
2223 =cut
2224
2225 sub GetMaxPatronHoldsForRecord {
2226     my ( $borrowernumber, $biblionumber ) = @_;
2227
2228     my $patron = Koha::Patrons->find($borrowernumber);
2229     my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2230
2231     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2232
2233     my $categorycode = $patron->categorycode;
2234     my $branchcode;
2235     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2236
2237     my $max = 0;
2238     foreach my $item (@items) {
2239         my $itemtype = $item->effective_itemtype();
2240
2241         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2242
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;
2246     }
2247
2248     return $max;
2249 }
2250
2251 =head2 GetHoldRule
2252
2253 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2254
2255 Returns the matching hold related issuingrule fields for a given
2256 patron category, itemtype, and library.
2257
2258 =cut
2259
2260 sub GetHoldRule {
2261     my ( $categorycode, $itemtype, $branchcode ) = @_;
2262
2263     my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2264         {
2265             itemtype     => $itemtype,
2266             categorycode => $categorycode,
2267             branchcode   => $branchcode,
2268             rule_name    => 'reservesallowed',
2269             order_by     => {
2270                 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2271             }
2272         }
2273     );
2274
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;
2281     }
2282
2283     my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2284         {
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' ]
2291             }
2292         }
2293     );
2294     $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2295     $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2296
2297     return $rules;
2298 }
2299
2300 =head1 AUTHOR
2301
2302 Koha Development Team <http://koha-community.org/>
2303
2304 =cut
2305
2306 1;