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