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