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