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