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