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