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