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