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