Bug 22806: (follow-up) CanBookBeReserved and CanItemBeReserved must check AllowHoldsO...
[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 =>'itemAlreadyOnLoan' };
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 =>'itemAlreadyOnLoan' };
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 $today = dt_from_string();
917     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
918     my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
919
920     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
921     my $params = { expirationdate => { '<', $dtf->format_date($today) } };
922     $params->{found} = [ { '!=', 'W' }, undef ]  unless $expireWaiting;
923
924     # FIXME To move to Koha::Holds->search_expired (?)
925     my $holds = Koha::Holds->search( $params );
926
927     while ( my $hold = $holds->next ) {
928         my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
929
930         next if !$cancel_on_holidays && $calendar->is_holiday( $today );
931
932         my $cancel_params = {};
933         if ( $hold->found eq 'W' ) {
934             $cancel_params->{charge_cancel_fee} = 1;
935         }
936         $hold->cancel( $cancel_params );
937     }
938 }
939
940 =head2 AutoUnsuspendReserves
941
942   AutoUnsuspendReserves();
943
944 Unsuspends all suspended reserves with a suspend_until date from before today.
945
946 =cut
947
948 sub AutoUnsuspendReserves {
949     my $today = dt_from_string();
950
951     my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
952
953     map { $_->resume() } @holds;
954 }
955
956 =head2 ModReserve
957
958   ModReserve({ rank => $rank,
959                reserve_id => $reserve_id,
960                branchcode => $branchcode
961                [, itemnumber => $itemnumber ]
962                [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
963               });
964
965 Change a hold request's priority or cancel it.
966
967 C<$rank> specifies the effect of the change.  If C<$rank>
968 is 'W' or 'n', nothing happens.  This corresponds to leaving a
969 request alone when changing its priority in the holds queue
970 for a bib.
971
972 If C<$rank> is 'del', the hold request is cancelled.
973
974 If C<$rank> is an integer greater than zero, the priority of
975 the request is set to that value.  Since priority != 0 means
976 that the item is not waiting on the hold shelf, setting the
977 priority to a non-zero value also sets the request's found
978 status and waiting date to NULL.
979
980 The optional C<$itemnumber> parameter is used only when
981 C<$rank> is a non-zero integer; if supplied, the itemnumber
982 of the hold request is set accordingly; if omitted, the itemnumber
983 is cleared.
984
985 B<FIXME:> Note that the forgoing can have the effect of causing
986 item-level hold requests to turn into title-level requests.  This
987 will be fixed once reserves has separate columns for requested
988 itemnumber and supplying itemnumber.
989
990 =cut
991
992 sub ModReserve {
993     my ( $params ) = @_;
994
995     my $rank = $params->{'rank'};
996     my $reserve_id = $params->{'reserve_id'};
997     my $branchcode = $params->{'branchcode'};
998     my $itemnumber = $params->{'itemnumber'};
999     my $suspend_until = $params->{'suspend_until'};
1000     my $borrowernumber = $params->{'borrowernumber'};
1001     my $biblionumber = $params->{'biblionumber'};
1002     my $cancellation_reason = $params->{'cancellation_reason'};
1003
1004     return if $rank eq "W";
1005     return if $rank eq "n";
1006
1007     return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1008
1009     my $hold;
1010     unless ( $reserve_id ) {
1011         my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
1012         return unless $holds->count; # FIXME Should raise an exception
1013         $hold = $holds->next;
1014         $reserve_id = $hold->reserve_id;
1015     }
1016
1017     $hold ||= Koha::Holds->find($reserve_id);
1018
1019     if ( $rank eq "del" ) {
1020         $hold->cancel({ cancellation_reason => $cancellation_reason });
1021     }
1022     elsif ($rank =~ /^\d+/ and $rank > 0) {
1023         logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1024             if C4::Context->preference('HoldsLog');
1025
1026         my $properties = {
1027             priority    => $rank,
1028             branchcode  => $branchcode,
1029             itemnumber  => $itemnumber,
1030             found       => undef,
1031             waitingdate => undef
1032         };
1033         if (exists $params->{reservedate}) {
1034             $properties->{reservedate} = $params->{reservedate} || undef;
1035         }
1036         if (exists $params->{expirationdate}) {
1037             $properties->{expirationdate} = $params->{expirationdate} || undef;
1038         }
1039
1040         $hold->set($properties)->store();
1041
1042         if ( defined( $suspend_until ) ) {
1043             if ( $suspend_until ) {
1044                 $suspend_until = eval { dt_from_string( $suspend_until ) };
1045                 $hold->suspend_hold( $suspend_until );
1046             } else {
1047                 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1048                 # If the hold is not suspended, this does nothing.
1049                 $hold->set( { suspend_until => undef } )->store();
1050             }
1051         }
1052
1053         _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1054     }
1055 }
1056
1057 =head2 ModReserveFill
1058
1059   &ModReserveFill($reserve);
1060
1061 Fill a reserve. If I understand this correctly, this means that the
1062 reserved book has been found and given to the patron who reserved it.
1063
1064 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1065 whose keys are fields from the reserves table in the Koha database.
1066
1067 =cut
1068
1069 sub ModReserveFill {
1070     my ($res) = @_;
1071     my $reserve_id = $res->{'reserve_id'};
1072
1073     my $hold = Koha::Holds->find($reserve_id);
1074     # get the priority on this record....
1075     my $priority = $hold->priority;
1076
1077     # update the hold statuses, no need to store it though, we will be deleting it anyway
1078     $hold->set(
1079         {
1080             found    => 'F',
1081             priority => 0,
1082         }
1083     );
1084
1085     logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1086         if C4::Context->preference('HoldsLog');
1087
1088     # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1089     Koha::Old::Hold->new( $hold->unblessed() )->store();
1090
1091     $hold->delete();
1092
1093     if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1094         my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1095         ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1096     }
1097
1098     # now fix the priority on the others (if the priority wasn't
1099     # already sorted!)....
1100     unless ( $priority == 0 ) {
1101         _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1102     }
1103 }
1104
1105 =head2 ModReserveStatus
1106
1107   &ModReserveStatus($itemnumber, $newstatus);
1108
1109 Update the reserve status for the active (priority=0) reserve.
1110
1111 $itemnumber is the itemnumber the reserve is on
1112
1113 $newstatus is the new status.
1114
1115 =cut
1116
1117 sub ModReserveStatus {
1118
1119     #first : check if we have a reservation for this item .
1120     my ($itemnumber, $newstatus) = @_;
1121     my $dbh = C4::Context->dbh;
1122
1123     my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1124     my $sth_set = $dbh->prepare($query);
1125     $sth_set->execute( $newstatus, $itemnumber );
1126
1127     my $item = Koha::Items->find($itemnumber);
1128     if ( $item->location && $item->location eq 'CART'
1129         && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1130         && $newstatus ) {
1131       CartToShelf( $itemnumber );
1132     }
1133 }
1134
1135 =head2 ModReserveAffect
1136
1137   &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1138
1139 This function affect an item and a status for a given reserve, either fetched directly
1140 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1141 is given, only first reserve returned is affected, which is ok for anything but
1142 multi-item holds.
1143
1144 if $transferToDo is not set, then the status is set to "Waiting" as well.
1145 otherwise, a transfer is on the way, and the end of the transfer will
1146 take care of the waiting status
1147
1148 =cut
1149
1150 sub ModReserveAffect {
1151     my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1152     my $dbh = C4::Context->dbh;
1153
1154     # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1155     # attached to $itemnumber
1156     my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1157     $sth->execute($itemnumber);
1158     my ($biblionumber) = $sth->fetchrow;
1159
1160     # get request - need to find out if item is already
1161     # waiting in order to not send duplicate hold filled notifications
1162
1163     my $hold;
1164     # Find hold by id if we have it
1165     $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1166     # Find item level hold for this item if there is one
1167     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1168     # Find record level hold if there is no item level hold
1169     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1170
1171     return unless $hold;
1172
1173     my $already_on_shelf = $hold->found && $hold->found eq 'W';
1174
1175     $hold->itemnumber($itemnumber);
1176
1177     if ($transferToDo) {
1178         $hold->set_transfer();
1179     } elsif (C4::Context->preference('HoldsNeedProcessingSIP')
1180              && C4::Context->interface eq 'sip'
1181              && !$already_on_shelf) {
1182         $hold->set_processing();
1183     } else {
1184         $hold->set_waiting();
1185         _koha_notify_reserve( $hold->reserve_id ) unless $already_on_shelf;
1186         my $transfers = Koha::Item::Transfers->search({
1187             itemnumber => $itemnumber,
1188             datearrived => undef
1189         });
1190         while( my $transfer = $transfers->next ){
1191             $transfer->datearrived( dt_from_string() )->store;
1192         };
1193     }
1194
1195
1196     _FixPriority( { biblionumber => $biblionumber } );
1197     my $item = Koha::Items->find($itemnumber);
1198     if ( $item->location && $item->location eq 'CART'
1199         && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1200       CartToShelf( $itemnumber );
1201     }
1202
1203     logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1204         if C4::Context->preference('HoldsLog');
1205
1206     return;
1207 }
1208
1209 =head2 ModReserveCancelAll
1210
1211   ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber,$reason);
1212
1213 function to cancel reserv,check other reserves, and transfer document if it's necessary
1214
1215 =cut
1216
1217 sub ModReserveCancelAll {
1218     my $messages;
1219     my $nextreservinfo;
1220     my ( $itemnumber, $borrowernumber, $cancellation_reason ) = @_;
1221
1222     #step 1 : cancel the reservation
1223     my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1224     return unless $holds->count;
1225     $holds->next->cancel({ cancellation_reason => $cancellation_reason });
1226
1227     #step 2 launch the subroutine of the others reserves
1228     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1229
1230     return ( $messages, $nextreservinfo->{borrowernumber} );
1231 }
1232
1233 =head2 ModReserveMinusPriority
1234
1235   &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1236
1237 Reduce the values of queued list
1238
1239 =cut
1240
1241 sub ModReserveMinusPriority {
1242     my ( $itemnumber, $reserve_id ) = @_;
1243
1244     #first step update the value of the first person on reserv
1245     my $dbh   = C4::Context->dbh;
1246     my $query = "
1247         UPDATE reserves
1248         SET    priority = 0 , itemnumber = ?
1249         WHERE  reserve_id = ?
1250     ";
1251     my $sth_upd = $dbh->prepare($query);
1252     $sth_upd->execute( $itemnumber, $reserve_id );
1253     # second step update all others reserves
1254     _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1255 }
1256
1257 =head2 IsAvailableForItemLevelRequest
1258
1259   my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1260
1261 Checks whether a given item record is available for an
1262 item-level hold request.  An item is available if
1263
1264 * it is not lost AND
1265 * it is not damaged AND
1266 * it is not withdrawn AND
1267 * a waiting or in transit reserve is placed on
1268 * does not have a not for loan value > 0
1269
1270 Need to check the issuingrules onshelfholds column,
1271 if this is set items on the shelf can be placed on hold
1272
1273 Note that IsAvailableForItemLevelRequest() does not
1274 check if the staff operator is authorized to place
1275 a request on the item - in particular,
1276 this routine does not check IndependentBranches
1277 and canreservefromotherbranches.
1278
1279 Note also that this subroutine does not checks smart
1280 rules limits for item by reservesallowed/holds_per_record
1281 values, this complemented in calling code with calls and
1282 checks with CanItemBeReserved or CanBookBeReserved.
1283
1284 =cut
1285
1286 sub IsAvailableForItemLevelRequest {
1287     my $item                = shift;
1288     my $patron              = shift;
1289     my $pickup_branchcode   = shift;
1290     # items_any_available is precalculated status passed from request.pl when set of items
1291     # looped outside of IsAvailableForItemLevelRequest to avoid nested loops:
1292     my $items_any_available = shift;
1293
1294     my $dbh = C4::Context->dbh;
1295     # must check the notforloan setting of the itemtype
1296     # FIXME - a lot of places in the code do this
1297     #         or something similar - need to be
1298     #         consolidated
1299     my $itemtype = $item->effective_itemtype;
1300     my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1301
1302     return 0 if
1303         $notforloan_per_itemtype ||
1304         $item->itemlost        ||
1305         $item->notforloan > 0  ||
1306         $item->withdrawn        ||
1307         ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1308
1309     if ($pickup_branchcode) {
1310         my $destination = Koha::Libraries->find($pickup_branchcode);
1311         return 0 unless $destination;
1312         return 0 unless $destination->pickup_location;
1313         return 0 unless $item->can_be_transferred( { to => $destination } );
1314         my $reserves_control_branch =
1315             GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1316         my $branchitemrule =
1317             C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1318         my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1319         return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1320     }
1321
1322     my $on_shelf_holds = Koha::CirculationRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1323
1324     if ( $on_shelf_holds == 1 ) {
1325         return 1;
1326     } elsif ( $on_shelf_holds == 2 ) {
1327
1328         # if we have this param predefined from outer caller sub, we just need
1329         # to return it, so we saving from having loop inside other loop:
1330         return  $items_any_available ? 0 : 1
1331             if defined $items_any_available;
1332
1333         my $any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $item->biblionumber, patron => $patron });
1334         return $any_available ? 0 : 1;
1335     } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1336         return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1337     }
1338 }
1339
1340 =head2 ItemsAnyAvailableAndNotRestricted
1341
1342   ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblionumber, patron => $patron });
1343
1344 This function checks all items for specified biblionumber (numeric) against patron (object)
1345 and returns true (1) if at least one item available for loan/check out/present/not held
1346 and also checks other parameters logic which not restricts item for hold at all (for ex.
1347 AllowHoldsOnDamagedItems or 'holdallowed' own/sibling library)
1348
1349 =cut
1350
1351 sub ItemsAnyAvailableAndNotRestricted {
1352     my $param = shift;
1353
1354     my @items = Koha::Items->search( { biblionumber => $param->{biblionumber} } );
1355
1356     foreach my $i (@items) {
1357         my $reserves_control_branch =
1358             GetReservesControlBranch( $i->unblessed(), $param->{patron}->unblessed );
1359         my $branchitemrule =
1360             C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1361         my $item_library = Koha::Libraries->find( { branchcode => $i->homebranch } );
1362
1363         # we can return (end the loop) when first one found:
1364         return 1
1365             unless $i->itemlost
1366             || $i->notforloan > 0
1367             || $i->withdrawn
1368             || $i->onloan
1369             || IsItemOnHoldAndFound( $i->id )
1370             || ( $i->damaged
1371                  && ! C4::Context->preference('AllowHoldsOnDamagedItems') )
1372             || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1373             || $branchitemrule->{holdallowed} == 1 && $param->{patron}->branchcode ne $i->homebranch
1374             || $branchitemrule->{holdallowed} == 3 && ! $item_library->validate_hold_sibling( { branchcode => $param->{patron}->branchcode } )
1375             || CanItemBeReserved( $param->{patron}->borrowernumber, $i->id )->{status} ne 'OK';
1376     }
1377
1378     return 0;
1379 }
1380
1381 =head2 AlterPriority
1382
1383   AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1384
1385 This function changes a reserve's priority up, down, to the top, or to the bottom.
1386 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1387
1388 =cut
1389
1390 sub AlterPriority {
1391     my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1392
1393     my $hold = Koha::Holds->find( $reserve_id );
1394     return unless $hold;
1395
1396     if ( $hold->cancellationdate ) {
1397         warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1398         return;
1399     }
1400
1401     if ( $where eq 'up' ) {
1402       return unless $prev_priority;
1403       _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1404     } elsif ( $where eq 'down' ) {
1405       return unless $next_priority;
1406       _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1407     } elsif ( $where eq 'top' ) {
1408       _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1409     } elsif ( $where eq 'bottom' ) {
1410       _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1411     }
1412
1413     # FIXME Should return the new priority
1414 }
1415
1416 =head2 ToggleLowestPriority
1417
1418   ToggleLowestPriority( $borrowernumber, $biblionumber );
1419
1420 This function sets the lowestPriority field to true if is false, and false if it is true.
1421
1422 =cut
1423
1424 sub ToggleLowestPriority {
1425     my ( $reserve_id ) = @_;
1426
1427     my $dbh = C4::Context->dbh;
1428
1429     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1430     $sth->execute( $reserve_id );
1431
1432     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1433 }
1434
1435 =head2 ToggleSuspend
1436
1437   ToggleSuspend( $reserve_id );
1438
1439 This function sets the suspend field to true if is false, and false if it is true.
1440 If the reserve is currently suspended with a suspend_until date, that date will
1441 be cleared when it is unsuspended.
1442
1443 =cut
1444
1445 sub ToggleSuspend {
1446     my ( $reserve_id, $suspend_until ) = @_;
1447
1448     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1449
1450     my $hold = Koha::Holds->find( $reserve_id );
1451
1452     if ( $hold->is_suspended ) {
1453         $hold->resume()
1454     } else {
1455         $hold->suspend_hold( $suspend_until );
1456     }
1457 }
1458
1459 =head2 SuspendAll
1460
1461   SuspendAll(
1462       borrowernumber   => $borrowernumber,
1463       [ biblionumber   => $biblionumber, ]
1464       [ suspend_until  => $suspend_until, ]
1465       [ suspend        => $suspend ]
1466   );
1467
1468   This function accepts a set of hash keys as its parameters.
1469   It requires either borrowernumber or biblionumber, or both.
1470
1471   suspend_until is wholly optional.
1472
1473 =cut
1474
1475 sub SuspendAll {
1476     my %params = @_;
1477
1478     my $borrowernumber = $params{'borrowernumber'} || undef;
1479     my $biblionumber   = $params{'biblionumber'}   || undef;
1480     my $suspend_until  = $params{'suspend_until'}  || undef;
1481     my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1482
1483     $suspend_until = eval { dt_from_string($suspend_until) }
1484       if ( defined($suspend_until) );
1485
1486     return unless ( $borrowernumber || $biblionumber );
1487
1488     my $params;
1489     $params->{found}          = undef;
1490     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1491     $params->{biblionumber}   = $biblionumber if $biblionumber;
1492
1493     my @holds = Koha::Holds->search($params);
1494
1495     if ($suspend) {
1496         map { $_->suspend_hold($suspend_until) } @holds;
1497     }
1498     else {
1499         map { $_->resume() } @holds;
1500     }
1501 }
1502
1503
1504 =head2 _FixPriority
1505
1506   _FixPriority({
1507     reserve_id => $reserve_id,
1508     [rank => $rank,]
1509     [ignoreSetLowestRank => $ignoreSetLowestRank]
1510   });
1511
1512   or
1513
1514   _FixPriority({ biblionumber => $biblionumber});
1515
1516 This routine adjusts the priority of a hold request and holds
1517 on the same bib.
1518
1519 In the first form, where a reserve_id is passed, the priority of the
1520 hold is set to supplied rank, and other holds for that bib are adjusted
1521 accordingly.  If the rank is "del", the hold is cancelled.  If no rank
1522 is supplied, all of the holds on that bib have their priority adjusted
1523 as if the second form had been used.
1524
1525 In the second form, where a biblionumber is passed, the holds on that
1526 bib (that are not captured) are sorted in order of increasing priority,
1527 then have reserves.priority set so that the first non-captured hold
1528 has its priority set to 1, the second non-captured hold has its priority
1529 set to 2, and so forth.
1530
1531 In both cases, holds that have the lowestPriority flag on are have their
1532 priority adjusted to ensure that they remain at the end of the line.
1533
1534 Note that the ignoreSetLowestRank parameter is meant to be used only
1535 when _FixPriority calls itself.
1536
1537 =cut
1538
1539 sub _FixPriority {
1540     my ( $params ) = @_;
1541     my $reserve_id = $params->{reserve_id};
1542     my $rank = $params->{rank} // '';
1543     my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1544     my $biblionumber = $params->{biblionumber};
1545
1546     my $dbh = C4::Context->dbh;
1547
1548     my $hold;
1549     if ( $reserve_id ) {
1550         $hold = Koha::Holds->find( $reserve_id );
1551         if (!defined $hold){
1552             # may have already been checked out and hold fulfilled
1553             $hold = Koha::Old::Holds->find( $reserve_id );
1554         }
1555         return unless $hold;
1556     }
1557
1558     unless ( $biblionumber ) { # FIXME This is a very weird API
1559         $biblionumber = $hold->biblionumber;
1560     }
1561
1562     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1563         $hold->cancel;
1564     }
1565     elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1566
1567         # make sure priority for waiting or in-transit items is 0
1568         my $query = "
1569             UPDATE reserves
1570             SET    priority = 0
1571             WHERE reserve_id = ?
1572             AND found IN ('W', 'T', 'P')
1573         ";
1574         my $sth = $dbh->prepare($query);
1575         $sth->execute( $reserve_id );
1576     }
1577     my @priority;
1578
1579     # get whats left
1580     my $query = "
1581         SELECT reserve_id, borrowernumber, reservedate
1582         FROM   reserves
1583         WHERE  biblionumber   = ?
1584           AND  ((found <> 'W' AND found <> 'T' AND found <> 'P') OR found IS NULL)
1585         ORDER BY priority ASC
1586     ";
1587     my $sth = $dbh->prepare($query);
1588     $sth->execute( $biblionumber );
1589     while ( my $line = $sth->fetchrow_hashref ) {
1590         push( @priority,     $line );
1591     }
1592
1593     # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1594     # To find the matching index
1595     my $i;
1596     my $key = -1;    # to allow for 0 to be a valid result
1597     for ( $i = 0 ; $i < @priority ; $i++ ) {
1598         if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1599             $key = $i;    # save the index
1600             last;
1601         }
1602     }
1603
1604     # if index exists in array then move it to new position
1605     if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1606         my $new_rank = $rank -
1607           1;    # $new_rank is what you want the new index to be in the array
1608         my $moving_item = splice( @priority, $key, 1 );
1609         splice( @priority, $new_rank, 0, $moving_item );
1610     }
1611
1612     # now fix the priority on those that are left....
1613     $query = "
1614         UPDATE reserves
1615         SET    priority = ?
1616         WHERE  reserve_id = ?
1617     ";
1618     $sth = $dbh->prepare($query);
1619     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1620         $sth->execute(
1621             $j + 1,
1622             $priority[$j]->{'reserve_id'}
1623         );
1624     }
1625
1626     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1627     $sth->execute();
1628
1629     unless ( $ignoreSetLowestRank ) {
1630       while ( my $res = $sth->fetchrow_hashref() ) {
1631         _FixPriority({
1632             reserve_id => $res->{'reserve_id'},
1633             rank => '999999',
1634             ignoreSetLowestRank => 1
1635         });
1636       }
1637     }
1638 }
1639
1640 =head2 _Findgroupreserve
1641
1642   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1643
1644 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1645 first match found.  If neither, then we look for non-holds-queue based holds.
1646 Lookahead is the number of days to look in advance.
1647
1648 C<&_Findgroupreserve> returns :
1649 C<@results> is an array of references-to-hash whose keys are mostly
1650 fields from the reserves table of the Koha database, plus
1651 C<biblioitemnumber>.
1652
1653 This routine with either return:
1654 1 - Item specific holds from the holds queue
1655 2 - Title level holds from the holds queue
1656 3 - All holds for this biblionumber
1657
1658 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1659
1660 =cut
1661
1662 sub _Findgroupreserve {
1663     my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1664     my $dbh   = C4::Context->dbh;
1665
1666     # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1667     # check for exact targeted match
1668     my $item_level_target_query = qq{
1669         SELECT reserves.biblionumber        AS biblionumber,
1670                reserves.borrowernumber      AS borrowernumber,
1671                reserves.reservedate         AS reservedate,
1672                reserves.branchcode          AS branchcode,
1673                reserves.cancellationdate    AS cancellationdate,
1674                reserves.found               AS found,
1675                reserves.reservenotes        AS reservenotes,
1676                reserves.priority            AS priority,
1677                reserves.timestamp           AS timestamp,
1678                biblioitems.biblioitemnumber AS biblioitemnumber,
1679                reserves.itemnumber          AS itemnumber,
1680                reserves.reserve_id          AS reserve_id,
1681                reserves.itemtype            AS itemtype,
1682                reserves.non_priority        AS non_priority
1683         FROM reserves
1684         JOIN biblioitems USING (biblionumber)
1685         JOIN hold_fill_targets USING (reserve_id)
1686         WHERE found IS NULL
1687         AND priority > 0
1688         AND item_level_request = 1
1689         AND hold_fill_targets.itemnumber = ?
1690         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1691         AND suspend = 0
1692         ORDER BY priority
1693     };
1694     my $sth = $dbh->prepare($item_level_target_query);
1695     $sth->execute($itemnumber, $lookahead||0);
1696     my @results;
1697     if ( my $data = $sth->fetchrow_hashref ) {
1698         push( @results, $data )
1699           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1700     }
1701     return @results if @results;
1702
1703     # check for title-level targeted match
1704     my $title_level_target_query = qq{
1705         SELECT reserves.biblionumber        AS biblionumber,
1706                reserves.borrowernumber      AS borrowernumber,
1707                reserves.reservedate         AS reservedate,
1708                reserves.branchcode          AS branchcode,
1709                reserves.cancellationdate    AS cancellationdate,
1710                reserves.found               AS found,
1711                reserves.reservenotes        AS reservenotes,
1712                reserves.priority            AS priority,
1713                reserves.timestamp           AS timestamp,
1714                biblioitems.biblioitemnumber AS biblioitemnumber,
1715                reserves.itemnumber          AS itemnumber,
1716                reserves.reserve_id          AS reserve_id,
1717                reserves.itemtype            AS itemtype,
1718                reserves.non_priority        AS non_priority
1719         FROM reserves
1720         JOIN biblioitems USING (biblionumber)
1721         JOIN hold_fill_targets USING (reserve_id)
1722         WHERE found IS NULL
1723         AND priority > 0
1724         AND item_level_request = 0
1725         AND hold_fill_targets.itemnumber = ?
1726         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1727         AND suspend = 0
1728         ORDER BY priority
1729     };
1730     $sth = $dbh->prepare($title_level_target_query);
1731     $sth->execute($itemnumber, $lookahead||0);
1732     @results = ();
1733     if ( my $data = $sth->fetchrow_hashref ) {
1734         push( @results, $data )
1735           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1736     }
1737     return @results if @results;
1738
1739     my $query = qq{
1740         SELECT reserves.biblionumber               AS biblionumber,
1741                reserves.borrowernumber             AS borrowernumber,
1742                reserves.reservedate                AS reservedate,
1743                reserves.waitingdate                AS waitingdate,
1744                reserves.branchcode                 AS branchcode,
1745                reserves.cancellationdate           AS cancellationdate,
1746                reserves.found                      AS found,
1747                reserves.reservenotes               AS reservenotes,
1748                reserves.priority                   AS priority,
1749                reserves.timestamp                  AS timestamp,
1750                reserves.itemnumber                 AS itemnumber,
1751                reserves.reserve_id                 AS reserve_id,
1752                reserves.itemtype                   AS itemtype,
1753                reserves.non_priority        AS non_priority
1754         FROM reserves
1755         WHERE reserves.biblionumber = ?
1756           AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1757           AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1758           AND suspend = 0
1759           ORDER BY priority
1760     };
1761     $sth = $dbh->prepare($query);
1762     $sth->execute( $biblio, $itemnumber, $lookahead||0);
1763     @results = ();
1764     while ( my $data = $sth->fetchrow_hashref ) {
1765         push( @results, $data )
1766           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1767     }
1768     return @results;
1769 }
1770
1771 =head2 _koha_notify_reserve
1772
1773   _koha_notify_reserve( $hold->reserve_id );
1774
1775 Sends a notification to the patron that their hold has been filled (through
1776 ModReserveAffect, _not_ ModReserveFill)
1777
1778 The letter code for this notice may be found using the following query:
1779
1780     select distinct letter_code
1781     from message_transports
1782     inner join message_attributes using (message_attribute_id)
1783     where message_name = 'Hold_Filled'
1784
1785 This will probably sipmly be 'HOLD', but because it is defined in the database,
1786 it is subject to addition or change.
1787
1788 The following tables are availalbe witin the notice:
1789
1790     branches
1791     borrowers
1792     biblio
1793     biblioitems
1794     reserves
1795     items
1796
1797 =cut
1798
1799 sub _koha_notify_reserve {
1800     my $reserve_id = shift;
1801     my $hold = Koha::Holds->find($reserve_id);
1802     my $borrowernumber = $hold->borrowernumber;
1803
1804     my $patron = Koha::Patrons->find( $borrowernumber );
1805
1806     # Try to get the borrower's email address
1807     my $to_address = $patron->notice_email_address;
1808
1809     my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1810             borrowernumber => $borrowernumber,
1811             message_name => 'Hold_Filled'
1812     } );
1813
1814     my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1815
1816     my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1817
1818     my %letter_params = (
1819         module => 'reserves',
1820         branchcode => $hold->branchcode,
1821         lang => $patron->lang,
1822         tables => {
1823             'branches'       => $library,
1824             'borrowers'      => $patron->unblessed,
1825             'biblio'         => $hold->biblionumber,
1826             'biblioitems'    => $hold->biblionumber,
1827             'reserves'       => $hold->unblessed,
1828             'items'          => $hold->itemnumber,
1829         },
1830     );
1831
1832     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.
1833     my $send_notification = sub {
1834         my ( $mtt, $letter_code ) = (@_);
1835         return unless defined $letter_code;
1836         $letter_params{letter_code} = $letter_code;
1837         $letter_params{message_transport_type} = $mtt;
1838         my $letter =  C4::Letters::GetPreparedLetter ( %letter_params );
1839         unless ($letter) {
1840             warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1841             return;
1842         }
1843
1844         C4::Letters::EnqueueLetter( {
1845             letter => $letter,
1846             borrowernumber => $borrowernumber,
1847             from_address => $admin_email_address,
1848             message_transport_type => $mtt,
1849         } );
1850     };
1851
1852     while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1853         next if (
1854                ( $mtt eq 'email' and not $to_address ) # No email address
1855             or ( $mtt eq 'sms'   and not $patron->smsalertnumber ) # No SMS number
1856             or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1857         );
1858
1859         &$send_notification($mtt, $letter_code);
1860         $notification_sent++;
1861     }
1862     #Making sure that a print notification is sent if no other transport types can be utilized.
1863     if (! $notification_sent) {
1864         &$send_notification('print', 'HOLD');
1865     }
1866
1867 }
1868
1869 =head2 _ShiftPriorityByDateAndPriority
1870
1871   $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1872
1873 This increments the priority of all reserves after the one
1874 with either the lowest date after C<$reservedate>
1875 or the lowest priority after C<$priority>.
1876
1877 It effectively makes room for a new reserve to be inserted with a certain
1878 priority, which is returned.
1879
1880 This is most useful when the reservedate can be set by the user.  It allows
1881 the new reserve to be placed before other reserves that have a later
1882 reservedate.  Since priority also is set by the form in reserves/request.pl
1883 the sub accounts for that too.
1884
1885 =cut
1886
1887 sub _ShiftPriorityByDateAndPriority {
1888     my ( $biblio, $resdate, $new_priority ) = @_;
1889
1890     my $dbh = C4::Context->dbh;
1891     my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1892     my $sth = $dbh->prepare( $query );
1893     $sth->execute( $biblio, $resdate, $new_priority );
1894     my $min_priority = $sth->fetchrow;
1895     # if no such matches are found, $new_priority remains as original value
1896     $new_priority = $min_priority if ( $min_priority );
1897
1898     # Shift the priority up by one; works in conjunction with the next SQL statement
1899     $query = "UPDATE reserves
1900               SET priority = priority+1
1901               WHERE biblionumber = ?
1902               AND borrowernumber = ?
1903               AND reservedate = ?
1904               AND found IS NULL";
1905     my $sth_update = $dbh->prepare( $query );
1906
1907     # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1908     $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1909     $sth = $dbh->prepare( $query );
1910     $sth->execute( $new_priority, $biblio );
1911     while ( my $row = $sth->fetchrow_hashref ) {
1912         $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1913     }
1914
1915     return $new_priority;  # so the caller knows what priority they wind up receiving
1916 }
1917
1918 =head2 MoveReserve
1919
1920   MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1921
1922 Use when checking out an item to handle reserves
1923 If $cancelreserve boolean is set to true, it will remove existing reserve
1924
1925 =cut
1926
1927 sub MoveReserve {
1928     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1929
1930     $cancelreserve //= 0;
1931
1932     my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1933     my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1934     return unless $res;
1935
1936     my $biblionumber     =  $res->{biblionumber};
1937
1938     if ($res->{borrowernumber} == $borrowernumber) {
1939         ModReserveFill($res);
1940     }
1941     else {
1942         # warn "Reserved";
1943         # The item is reserved by someone else.
1944         # Find this item in the reserves
1945
1946         my $borr_res  = Koha::Holds->search({
1947             borrowernumber => $borrowernumber,
1948             biblionumber   => $biblionumber,
1949         },{
1950             order_by       => 'priority'
1951         })->next();
1952
1953         if ( $borr_res ) {
1954             # The item is reserved by the current patron
1955             ModReserveFill($borr_res->unblessed);
1956         }
1957
1958         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1959             RevertWaitingStatus({ itemnumber => $itemnumber });
1960         }
1961         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1962             my $hold = Koha::Holds->find( $res->{reserve_id} );
1963             $hold->cancel;
1964         }
1965     }
1966 }
1967
1968 =head2 MergeHolds
1969
1970   MergeHolds($dbh,$to_biblio, $from_biblio);
1971
1972 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1973
1974 =cut
1975
1976 sub MergeHolds {
1977     my ( $dbh, $to_biblio, $from_biblio ) = @_;
1978     my $sth = $dbh->prepare(
1979         "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1980     );
1981     $sth->execute($from_biblio);
1982     if ( my $data = $sth->fetchrow_hashref() ) {
1983
1984         # holds exist on old record, if not we don't need to do anything
1985         $sth = $dbh->prepare(
1986             "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1987         $sth->execute( $to_biblio, $from_biblio );
1988
1989         # Reorder by date
1990         # don't reorder those already waiting
1991
1992         $sth = $dbh->prepare(
1993 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1994         );
1995         my $upd_sth = $dbh->prepare(
1996 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1997         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1998         );
1999         $sth->execute( $to_biblio, 'W', 'T', 'P' );
2000         my $priority = 1;
2001         while ( my $reserve = $sth->fetchrow_hashref() ) {
2002             $upd_sth->execute(
2003                 $priority,                    $to_biblio,
2004                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2005                 $reserve->{'itemnumber'}
2006             );
2007             $priority++;
2008         }
2009     }
2010 }
2011
2012 =head2 RevertWaitingStatus
2013
2014   RevertWaitingStatus({ itemnumber => $itemnumber });
2015
2016   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2017
2018   Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2019           item level hold, even if it was only a bibliolevel hold to
2020           begin with. This is because we can no longer know if a hold
2021           was item-level or bib-level after a hold has been set to
2022           waiting status.
2023
2024 =cut
2025
2026 sub RevertWaitingStatus {
2027     my ( $params ) = @_;
2028     my $itemnumber = $params->{'itemnumber'};
2029
2030     return unless ( $itemnumber );
2031
2032     my $dbh = C4::Context->dbh;
2033
2034     ## Get the waiting reserve we want to revert
2035     my $hold = Koha::Holds->search(
2036         {
2037             itemnumber => $itemnumber,
2038             found => { not => undef },
2039         }
2040     )->next;
2041
2042     ## Increment the priority of all other non-waiting
2043     ## reserves for this bib record
2044     my $holds = Koha::Holds->search({ biblionumber => $hold->biblionumber, priority => { '>' => 0 } })
2045                            ->update({ priority => \'priority + 1' }, { no_triggers => 1 });
2046
2047     ## Fix up the currently waiting reserve
2048     $hold->set(
2049         {
2050             priority    => 1,
2051             found       => undef,
2052             waitingdate => undef,
2053             itemnumber  => $hold->item_level_hold ? $hold->itemnumber : undef,
2054         }
2055     )->store();
2056
2057     _FixPriority( { biblionumber => $hold->biblionumber } );
2058
2059     return $hold;
2060 }
2061
2062 =head2 ReserveSlip
2063
2064 ReserveSlip(
2065     {
2066         branchcode     => $branchcode,
2067         borrowernumber => $borrowernumber,
2068         biblionumber   => $biblionumber,
2069         [ itemnumber   => $itemnumber, ]
2070         [ barcode      => $barcode, ]
2071     }
2072   )
2073
2074 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2075
2076 The letter code will be HOLD_SLIP, and the following tables are
2077 available within the slip:
2078
2079     reserves
2080     branches
2081     borrowers
2082     biblio
2083     biblioitems
2084     items
2085
2086 =cut
2087
2088 sub ReserveSlip {
2089     my ($args) = @_;
2090     my $branchcode     = $args->{branchcode};
2091     my $reserve_id = $args->{reserve_id};
2092
2093     my $hold = Koha::Holds->find($reserve_id);
2094     return unless $hold;
2095
2096     my $patron = $hold->borrower;
2097     my $reserve = $hold->unblessed;
2098
2099     return  C4::Letters::GetPreparedLetter (
2100         module => 'circulation',
2101         letter_code => 'HOLD_SLIP',
2102         branchcode => $branchcode,
2103         lang => $patron->lang,
2104         tables => {
2105             'reserves'    => $reserve,
2106             'branches'    => $reserve->{branchcode},
2107             'borrowers'   => $reserve->{borrowernumber},
2108             'biblio'      => $reserve->{biblionumber},
2109             'biblioitems' => $reserve->{biblionumber},
2110             'items'       => $reserve->{itemnumber},
2111         },
2112     );
2113 }
2114
2115 =head2 GetReservesControlBranch
2116
2117   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2118
2119   Return the branchcode to be used to determine which reserves
2120   policy applies to a transaction.
2121
2122   C<$item> is a hashref for an item. Only 'homebranch' is used.
2123
2124   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2125
2126 =cut
2127
2128 sub GetReservesControlBranch {
2129     my ( $item, $borrower ) = @_;
2130
2131     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2132
2133     my $branchcode =
2134         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2135       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2136       :                                              undef;
2137
2138     return $branchcode;
2139 }
2140
2141 =head2 CalculatePriority
2142
2143     my $p = CalculatePriority($biblionumber, $resdate);
2144
2145 Calculate priority for a new reserve on biblionumber, placing it at
2146 the end of the line of all holds whose start date falls before
2147 the current system time and that are neither on the hold shelf
2148 or in transit.
2149
2150 The reserve date parameter is optional; if it is supplied, the
2151 priority is based on the set of holds whose start date falls before
2152 the parameter value.
2153
2154 After calculation of this priority, it is recommended to call
2155 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2156 AddReserves.
2157
2158 =cut
2159
2160 sub CalculatePriority {
2161     my ( $biblionumber, $resdate ) = @_;
2162
2163     my $sql = q{
2164         SELECT COUNT(*) FROM reserves
2165         WHERE biblionumber = ?
2166         AND   priority > 0
2167         AND   (found IS NULL OR found = '')
2168     };
2169     #skip found==W or found==T or found==P (waiting, transit or processing holds)
2170     if( $resdate ) {
2171         $sql.= ' AND ( reservedate <= ? )';
2172     }
2173     else {
2174         $sql.= ' AND ( reservedate < NOW() )';
2175     }
2176     my $dbh = C4::Context->dbh();
2177     my @row = $dbh->selectrow_array(
2178         $sql,
2179         undef,
2180         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2181     );
2182
2183     return @row ? $row[0]+1 : 1;
2184 }
2185
2186 =head2 IsItemOnHoldAndFound
2187
2188     my $bool = IsItemFoundHold( $itemnumber );
2189
2190     Returns true if the item is currently on hold
2191     and that hold has a non-null found status ( W, T, etc. )
2192
2193 =cut
2194
2195 sub IsItemOnHoldAndFound {
2196     my ($itemnumber) = @_;
2197
2198     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2199
2200     my $found = $rs->count(
2201         {
2202             itemnumber => $itemnumber,
2203             found      => { '!=' => undef }
2204         }
2205     );
2206
2207     return $found;
2208 }
2209
2210 =head2 GetMaxPatronHoldsForRecord
2211
2212 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2213
2214 For multiple holds on a given record for a given patron, the max
2215 number of record level holds that a patron can be placed is the highest
2216 value of the holds_per_record rule for each item if the record for that
2217 patron. This subroutine finds and returns the highest holds_per_record
2218 rule value for a given patron id and record id.
2219
2220 =cut
2221
2222 sub GetMaxPatronHoldsForRecord {
2223     my ( $borrowernumber, $biblionumber ) = @_;
2224
2225     my $patron = Koha::Patrons->find($borrowernumber);
2226     my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2227
2228     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2229
2230     my $categorycode = $patron->categorycode;
2231     my $branchcode;
2232     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2233
2234     my $max = 0;
2235     foreach my $item (@items) {
2236         my $itemtype = $item->effective_itemtype();
2237
2238         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2239
2240         my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2241         my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2242         $max = $holds_per_record if $holds_per_record > $max;
2243     }
2244
2245     return $max;
2246 }
2247
2248 =head2 GetHoldRule
2249
2250 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2251
2252 Returns the matching hold related issuingrule fields for a given
2253 patron category, itemtype, and library.
2254
2255 =cut
2256
2257 sub GetHoldRule {
2258     my ( $categorycode, $itemtype, $branchcode ) = @_;
2259
2260     my $reservesallowed = Koha::CirculationRules->get_effective_rule(
2261         {
2262             itemtype     => $itemtype,
2263             categorycode => $categorycode,
2264             branchcode   => $branchcode,
2265             rule_name    => 'reservesallowed',
2266             order_by     => {
2267                 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2268             }
2269         }
2270     );
2271
2272     my $rules;
2273     if ( $reservesallowed ) {
2274         $rules->{reservesallowed} = $reservesallowed->rule_value;
2275         $rules->{itemtype}        = $reservesallowed->itemtype;
2276         $rules->{categorycode}    = $reservesallowed->categorycode;
2277         $rules->{branchcode}      = $reservesallowed->branchcode;
2278     }
2279
2280     my $holds_per_x_rules = Koha::CirculationRules->get_effective_rules(
2281         {
2282             itemtype     => $itemtype,
2283             categorycode => $categorycode,
2284             branchcode   => $branchcode,
2285             rules        => ['holds_per_record', 'holds_per_day'],
2286             order_by     => {
2287                 -desc => [ 'categorycode', 'itemtype', 'branchcode' ]
2288             }
2289         }
2290     );
2291     $rules->{holds_per_record} = $holds_per_x_rules->{holds_per_record};
2292     $rules->{holds_per_day} = $holds_per_x_rules->{holds_per_day};
2293
2294     return $rules;
2295 }
2296
2297 =head1 AUTHOR
2298
2299 Koha Development Team <http://koha-community.org/>
2300
2301 =cut
2302
2303 1;