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