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