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