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