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