Bug 19059: Remove CancelReserve - do not log DELETE
[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                 return ( "Waiting", $res, \@reserves ); # Found it
736             } else {
737                 my $patron;
738                 my $iteminfo;
739                 my $local_hold_match;
740
741                 if ($LocalHoldsPriority) {
742                     $patron = Koha::Patrons->find( $res->{borrowernumber} );
743                     $iteminfo = C4::Items::GetItem($itemnumber);
744
745                     my $local_holds_priority_item_branchcode =
746                       $iteminfo->{$LocalHoldsPriorityItemControl};
747                     my $local_holds_priority_patron_branchcode =
748                       ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
749                       ? $res->{branchcode}
750                       : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
751                       ? $patron->branchcode
752                       : undef;
753                     $local_hold_match =
754                       $local_holds_priority_item_branchcode eq
755                       $local_holds_priority_patron_branchcode;
756                 }
757
758                 # See if this item is more important than what we've got so far
759                 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
760                     $iteminfo ||= C4::Items::GetItem($itemnumber);
761                     next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
762                     $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
763                     my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
764                     my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
765                     next if ($branchitemrule->{'holdallowed'} == 0);
766                     next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
767                     next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
768                     $priority = $res->{'priority'};
769                     $highest  = $res;
770                     last if $local_hold_match;
771                 }
772             }
773         }
774     }
775
776     # If we get this far, then no exact match was found.
777     # We return the most important (i.e. next) reservation.
778     if ($highest) {
779         $highest->{'itemnumber'} = $item;
780         return ( "Reserved", $highest, \@reserves );
781     }
782
783     return ( '' );
784 }
785
786 =head2 CancelExpiredReserves
787
788   CancelExpiredReserves();
789
790 Cancels all reserves with an expiration date from before today.
791
792 =cut
793
794 sub CancelExpiredReserves {
795
796     my $today = dt_from_string();
797     my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
798
799     my $dbh = C4::Context->dbh;
800
801     my $dtf = Koha::Database->new->schema->storage->datetime_parser;
802     my $today = dt_from_string;
803     # FIXME To move to Koha::Holds->search_expired (?)
804     my $holds = Koha::Holds->search(
805         {
806             expirationdate => { '<', $dtf->format_date($today) }
807         }
808     );
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 ( $holds->found eq 'W' ) {
817             $cancel_params->{charge_cancel_fee} = 1;
818         }
819         $hold->cancel( $cancel_params );
820
821     }
822 }
823
824 =head2 AutoUnsuspendReserves
825
826   AutoUnsuspendReserves();
827
828 Unsuspends all suspended reserves with a suspend_until date from before today.
829
830 =cut
831
832 sub AutoUnsuspendReserves {
833     my $today = dt_from_string();
834
835     my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
836
837     map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
838 }
839
840 =head2 CancelReserve
841
842   CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
843
844 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.
845
846 =cut
847
848 sub CancelReserve {
849     my ( $params ) = @_;
850
851     my $reserve_id = $params->{'reserve_id'};
852     my $hold;
853     if ( $reserve_id ) {
854         $hold = Koha::Holds->find( $reserve_id );
855     } else {
856         $hold = Koha::Holds->search( $params ); # biblionumber, borrowernumber, itemnumber
857     }
858
859     return unless $hold;
860
861     logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
862         if C4::Context->preference('HoldsLog');
863
864     my $query = "
865         UPDATE reserves
866         SET    cancellationdate = now(),
867                priority         = 0
868         WHERE  reserve_id = ?
869     ";
870     my $dbh = C4::Context->dbh;
871     my $sth = $dbh->prepare($query);
872     $sth->execute( $reserve_id );
873
874     $query = "
875         INSERT INTO old_reserves
876         SELECT * FROM reserves
877         WHERE  reserve_id = ?
878     ";
879     $sth = $dbh->prepare($query);
880     $sth->execute( $reserve_id );
881
882     $query = "
883         DELETE FROM reserves
884         WHERE  reserve_id = ?
885     ";
886     $sth = $dbh->prepare($query);
887     $sth->execute( $reserve_id );
888
889     # now fix the priority on the others....
890     _FixPriority({ biblionumber => $hold->biblionumber });
891
892     # and, if desired, charge a cancel fee
893     my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
894     if ( $charge && $params->{'charge_cancel_fee'} ) {
895         manualinvoice($hold->borrowernumber, $hold->itemnumber, '', 'HE', $charge);
896     }
897
898     return $hold->unblessed;
899 }
900
901 =head2 ModReserve
902
903   ModReserve({ rank => $rank,
904                reserve_id => $reserve_id,
905                branchcode => $branchcode
906                [, itemnumber => $itemnumber ]
907                [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
908               });
909
910 Change a hold request's priority or cancel it.
911
912 C<$rank> specifies the effect of the change.  If C<$rank>
913 is 'W' or 'n', nothing happens.  This corresponds to leaving a
914 request alone when changing its priority in the holds queue
915 for a bib.
916
917 If C<$rank> is 'del', the hold request is cancelled.
918
919 If C<$rank> is an integer greater than zero, the priority of
920 the request is set to that value.  Since priority != 0 means
921 that the item is not waiting on the hold shelf, setting the
922 priority to a non-zero value also sets the request's found
923 status and waiting date to NULL.
924
925 The optional C<$itemnumber> parameter is used only when
926 C<$rank> is a non-zero integer; if supplied, the itemnumber
927 of the hold request is set accordingly; if omitted, the itemnumber
928 is cleared.
929
930 B<FIXME:> Note that the forgoing can have the effect of causing
931 item-level hold requests to turn into title-level requests.  This
932 will be fixed once reserves has separate columns for requested
933 itemnumber and supplying itemnumber.
934
935 =cut
936
937 sub ModReserve {
938     my ( $params ) = @_;
939
940     my $rank = $params->{'rank'};
941     my $reserve_id = $params->{'reserve_id'};
942     my $branchcode = $params->{'branchcode'};
943     my $itemnumber = $params->{'itemnumber'};
944     my $suspend_until = $params->{'suspend_until'};
945     my $borrowernumber = $params->{'borrowernumber'};
946     my $biblionumber = $params->{'biblionumber'};
947
948     return if $rank eq "W";
949     return if $rank eq "n";
950
951     return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
952
953     my $hold;
954     unless ( $reserve_id ) {
955         $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
956         return unless $hold; # FIXME Should raise an exception
957         $reserve_id = $hold->reserve_id;
958     }
959
960     $hold ||= Koha::Holds->find($reserve_id);
961
962     if ( $rank eq "del" ) {
963         $hold->cancel;
964     }
965     elsif ($rank =~ /^\d+/ and $rank > 0) {
966         logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
967             if C4::Context->preference('HoldsLog');
968
969         $hold->set(
970             {
971                 priority    => $rank,
972                 branchcode  => $branchcode,
973                 itemnumber  => $itemnumber,
974                 found       => undef,
975                 waitingdate => undef
976             }
977         )->store();
978
979         if ( defined( $suspend_until ) ) {
980             if ( $suspend_until ) {
981                 $suspend_until = eval { dt_from_string( $suspend_until ) };
982                 $hold->suspend_hold( $suspend_until );
983             } else {
984                 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
985                 # If the hold is not suspended, this does nothing.
986                 $hold->set( { suspend_until => undef } )->store();
987             }
988         }
989
990         _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
991     }
992 }
993
994 =head2 ModReserveFill
995
996   &ModReserveFill($reserve);
997
998 Fill a reserve. If I understand this correctly, this means that the
999 reserved book has been found and given to the patron who reserved it.
1000
1001 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1002 whose keys are fields from the reserves table in the Koha database.
1003
1004 =cut
1005
1006 sub ModReserveFill {
1007     my ($res) = @_;
1008     my $reserve_id = $res->{'reserve_id'};
1009
1010     my $hold = Koha::Holds->find($reserve_id);
1011
1012     # get the priority on this record....
1013     my $priority = $hold->priority;
1014
1015     # update the hold statuses, no need to store it though, we will be deleting it anyway
1016     $hold->set(
1017         {
1018             found    => 'F',
1019             priority => 0,
1020         }
1021     );
1022
1023     # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1024     Koha::Old::Hold->new( $hold->unblessed() )->store();
1025
1026     $hold->delete();
1027
1028     if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1029         my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1030         ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1031     }
1032
1033     # now fix the priority on the others (if the priority wasn't
1034     # already sorted!)....
1035     unless ( $priority == 0 ) {
1036         _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1037     }
1038 }
1039
1040 =head2 ModReserveStatus
1041
1042   &ModReserveStatus($itemnumber, $newstatus);
1043
1044 Update the reserve status for the active (priority=0) reserve.
1045
1046 $itemnumber is the itemnumber the reserve is on
1047
1048 $newstatus is the new status.
1049
1050 =cut
1051
1052 sub ModReserveStatus {
1053
1054     #first : check if we have a reservation for this item .
1055     my ($itemnumber, $newstatus) = @_;
1056     my $dbh = C4::Context->dbh;
1057
1058     my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1059     my $sth_set = $dbh->prepare($query);
1060     $sth_set->execute( $newstatus, $itemnumber );
1061
1062     if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1063       CartToShelf( $itemnumber );
1064     }
1065 }
1066
1067 =head2 ModReserveAffect
1068
1069   &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1070
1071 This function affect an item and a status for a given reserve, either fetched directly
1072 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1073 is given, only first reserve returned is affected, which is ok for anything but
1074 multi-item holds.
1075
1076 if $transferToDo is not set, then the status is set to "Waiting" as well.
1077 otherwise, a transfer is on the way, and the end of the transfer will
1078 take care of the waiting status
1079
1080 =cut
1081
1082 sub ModReserveAffect {
1083     my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1084     my $dbh = C4::Context->dbh;
1085
1086     # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1087     # attached to $itemnumber
1088     my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1089     $sth->execute($itemnumber);
1090     my ($biblionumber) = $sth->fetchrow;
1091
1092     # get request - need to find out if item is already
1093     # waiting in order to not send duplicate hold filled notifications
1094
1095     my $hold;
1096     # Find hold by id if we have it
1097     $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1098     # Find item level hold for this item if there is one
1099     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1100     # Find record level hold if there is no item level hold
1101     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1102
1103     return unless $hold;
1104
1105     my $already_on_shelf = $hold->found && $hold->found eq 'W';
1106
1107     $hold->itemnumber($itemnumber);
1108     $hold->set_waiting($transferToDo);
1109
1110     _koha_notify_reserve( $hold->reserve_id )
1111       if ( !$transferToDo && !$already_on_shelf );
1112
1113     _FixPriority( { biblionumber => $biblionumber } );
1114
1115     if ( C4::Context->preference("ReturnToShelvingCart") ) {
1116         CartToShelf($itemnumber);
1117     }
1118
1119     return;
1120 }
1121
1122 =head2 ModReserveCancelAll
1123
1124   ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1125
1126 function to cancel reserv,check other reserves, and transfer document if it's necessary
1127
1128 =cut
1129
1130 sub ModReserveCancelAll {
1131     my $messages;
1132     my $nextreservinfo;
1133     my ( $itemnumber, $borrowernumber ) = @_;
1134
1135     #step 1 : cancel the reservation
1136     my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1137     return unless $holds->count;
1138     $holds->next->cancel;
1139
1140     #step 2 launch the subroutine of the others reserves
1141     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1142
1143     return ( $messages, $nextreservinfo );
1144 }
1145
1146 =head2 ModReserveMinusPriority
1147
1148   &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1149
1150 Reduce the values of queued list
1151
1152 =cut
1153
1154 sub ModReserveMinusPriority {
1155     my ( $itemnumber, $reserve_id ) = @_;
1156
1157     #first step update the value of the first person on reserv
1158     my $dbh   = C4::Context->dbh;
1159     my $query = "
1160         UPDATE reserves
1161         SET    priority = 0 , itemnumber = ?
1162         WHERE  reserve_id = ?
1163     ";
1164     my $sth_upd = $dbh->prepare($query);
1165     $sth_upd->execute( $itemnumber, $reserve_id );
1166     # second step update all others reserves
1167     _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1168 }
1169
1170 =head2 IsAvailableForItemLevelRequest
1171
1172   my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1173
1174 Checks whether a given item record is available for an
1175 item-level hold request.  An item is available if
1176
1177 * it is not lost AND
1178 * it is not damaged AND
1179 * it is not withdrawn AND
1180 * does not have a not for loan value > 0
1181
1182 Need to check the issuingrules onshelfholds column,
1183 if this is set items on the shelf can be placed on hold
1184
1185 Note that IsAvailableForItemLevelRequest() does not
1186 check if the staff operator is authorized to place
1187 a request on the item - in particular,
1188 this routine does not check IndependentBranches
1189 and canreservefromotherbranches.
1190
1191 =cut
1192
1193 sub IsAvailableForItemLevelRequest {
1194     my $item = shift;
1195     my $borrower = shift;
1196
1197     my $dbh = C4::Context->dbh;
1198     # must check the notforloan setting of the itemtype
1199     # FIXME - a lot of places in the code do this
1200     #         or something similar - need to be
1201     #         consolidated
1202     my $itype = _get_itype($item);
1203     my $notforloan_per_itemtype
1204       = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1205                               undef, $itype);
1206
1207     return 0 if
1208         $notforloan_per_itemtype ||
1209         $item->{itemlost}        ||
1210         $item->{notforloan} > 0  ||
1211         $item->{withdrawn}        ||
1212         ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1213
1214     my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1215
1216     if ( $on_shelf_holds == 1 ) {
1217         return 1;
1218     } elsif ( $on_shelf_holds == 2 ) {
1219         my @items =
1220           Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1221
1222         my $any_available = 0;
1223
1224         foreach my $i (@items) {
1225             $any_available = 1
1226               unless $i->itemlost
1227               || $i->notforloan > 0
1228               || $i->withdrawn
1229               || $i->onloan
1230               || IsItemOnHoldAndFound( $i->id )
1231               || ( $i->damaged
1232                 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1233               || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1234         }
1235
1236         return $any_available ? 0 : 1;
1237     }
1238
1239     return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1240 }
1241
1242 =head2 OnShelfHoldsAllowed
1243
1244   OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1245
1246 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1247 holds are allowed, returns true if so.
1248
1249 =cut
1250
1251 sub OnShelfHoldsAllowed {
1252     my ($item, $borrower) = @_;
1253
1254     my $itype = _get_itype($item);
1255     return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1256 }
1257
1258 sub _get_itype {
1259     my $item = shift;
1260
1261     my $itype;
1262     if (C4::Context->preference('item-level_itypes')) {
1263         # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1264         # When GetItem is fixed, we can remove this
1265         $itype = $item->{itype};
1266     }
1267     else {
1268         # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1269         # So if we already have a biblioitems join when calling this function,
1270         # we don't need to access the database again
1271         $itype = $item->{itemtype};
1272     }
1273     unless ($itype) {
1274         my $dbh = C4::Context->dbh;
1275         my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1276         my $sth = $dbh->prepare($query);
1277         $sth->execute($item->{biblioitemnumber});
1278         if (my $data = $sth->fetchrow_hashref()){
1279             $itype = $data->{itemtype};
1280         }
1281     }
1282     return $itype;
1283 }
1284
1285 sub _OnShelfHoldsAllowed {
1286     my ($itype,$borrowercategory,$branchcode) = @_;
1287
1288     my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1289     return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1290 }
1291
1292 =head2 AlterPriority
1293
1294   AlterPriority( $where, $reserve_id );
1295
1296 This function changes a reserve's priority up, down, to the top, or to the bottom.
1297 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1298
1299 =cut
1300
1301 sub AlterPriority {
1302     my ( $where, $reserve_id ) = @_;
1303
1304     my $hold = Koha::Holds->find( $reserve_id );
1305     return unless $hold;
1306
1307     if ( $hold->cancellationdate ) {
1308         warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1309         return;
1310     }
1311
1312     if ( $where eq 'up' || $where eq 'down' ) {
1313
1314       my $priority = $hold->priority;
1315       $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1316       _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1317
1318     } elsif ( $where eq 'top' ) {
1319
1320       _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1321
1322     } elsif ( $where eq 'bottom' ) {
1323
1324       _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1325
1326     }
1327     # FIXME Should return the new priority
1328 }
1329
1330 =head2 ToggleLowestPriority
1331
1332   ToggleLowestPriority( $borrowernumber, $biblionumber );
1333
1334 This function sets the lowestPriority field to true if is false, and false if it is true.
1335
1336 =cut
1337
1338 sub ToggleLowestPriority {
1339     my ( $reserve_id ) = @_;
1340
1341     my $dbh = C4::Context->dbh;
1342
1343     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1344     $sth->execute( $reserve_id );
1345
1346     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1347 }
1348
1349 =head2 ToggleSuspend
1350
1351   ToggleSuspend( $reserve_id );
1352
1353 This function sets the suspend field to true if is false, and false if it is true.
1354 If the reserve is currently suspended with a suspend_until date, that date will
1355 be cleared when it is unsuspended.
1356
1357 =cut
1358
1359 sub ToggleSuspend {
1360     my ( $reserve_id, $suspend_until ) = @_;
1361
1362     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1363
1364     my $hold = Koha::Holds->find( $reserve_id );
1365
1366     if ( $hold->is_suspended ) {
1367         $hold->resume()
1368     } else {
1369         $hold->suspend_hold( $suspend_until );
1370     }
1371 }
1372
1373 =head2 SuspendAll
1374
1375   SuspendAll(
1376       borrowernumber   => $borrowernumber,
1377       [ biblionumber   => $biblionumber, ]
1378       [ suspend_until  => $suspend_until, ]
1379       [ suspend        => $suspend ]
1380   );
1381
1382   This function accepts a set of hash keys as its parameters.
1383   It requires either borrowernumber or biblionumber, or both.
1384
1385   suspend_until is wholly optional.
1386
1387 =cut
1388
1389 sub SuspendAll {
1390     my %params = @_;
1391
1392     my $borrowernumber = $params{'borrowernumber'} || undef;
1393     my $biblionumber   = $params{'biblionumber'}   || undef;
1394     my $suspend_until  = $params{'suspend_until'}  || undef;
1395     my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1396
1397     $suspend_until = eval { dt_from_string($suspend_until) }
1398       if ( defined($suspend_until) );
1399
1400     return unless ( $borrowernumber || $biblionumber );
1401
1402     my $params;
1403     $params->{found}          = undef;
1404     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1405     $params->{biblionumber}   = $biblionumber if $biblionumber;
1406
1407     my @holds = Koha::Holds->search($params);
1408
1409     if ($suspend) {
1410         map { $_->suspend_hold($suspend_until) } @holds;
1411     }
1412     else {
1413         map { $_->resume() } @holds;
1414     }
1415 }
1416
1417
1418 =head2 _FixPriority
1419
1420   _FixPriority({
1421     reserve_id => $reserve_id,
1422     [rank => $rank,]
1423     [ignoreSetLowestRank => $ignoreSetLowestRank]
1424   });
1425
1426   or
1427
1428   _FixPriority({ biblionumber => $biblionumber});
1429
1430 This routine adjusts the priority of a hold request and holds
1431 on the same bib.
1432
1433 In the first form, where a reserve_id is passed, the priority of the
1434 hold is set to supplied rank, and other holds for that bib are adjusted
1435 accordingly.  If the rank is "del", the hold is cancelled.  If no rank
1436 is supplied, all of the holds on that bib have their priority adjusted
1437 as if the second form had been used.
1438
1439 In the second form, where a biblionumber is passed, the holds on that
1440 bib (that are not captured) are sorted in order of increasing priority,
1441 then have reserves.priority set so that the first non-captured hold
1442 has its priority set to 1, the second non-captured hold has its priority
1443 set to 2, and so forth.
1444
1445 In both cases, holds that have the lowestPriority flag on are have their
1446 priority adjusted to ensure that they remain at the end of the line.
1447
1448 Note that the ignoreSetLowestRank parameter is meant to be used only
1449 when _FixPriority calls itself.
1450
1451 =cut
1452
1453 sub _FixPriority {
1454     my ( $params ) = @_;
1455     my $reserve_id = $params->{reserve_id};
1456     my $rank = $params->{rank} // '';
1457     my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1458     my $biblionumber = $params->{biblionumber};
1459
1460     my $dbh = C4::Context->dbh;
1461
1462     my $hold;
1463     if ( $reserve_id ) {
1464         $hold = Koha::Holds->find( $reserve_id );
1465         return unless $hold;
1466     }
1467
1468     unless ( $biblionumber ) { # FIXME This is a very weird API
1469         $biblionumber = $hold->biblionumber;
1470     }
1471
1472     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1473         $hold->cancel;
1474     }
1475     elsif ( $rank eq "W" || $rank eq "0" ) {
1476
1477         # make sure priority for waiting or in-transit items is 0
1478         my $query = "
1479             UPDATE reserves
1480             SET    priority = 0
1481             WHERE reserve_id = ?
1482             AND found IN ('W', 'T')
1483         ";
1484         my $sth = $dbh->prepare($query);
1485         $sth->execute( $reserve_id );
1486     }
1487     my @priority;
1488
1489     # get whats left
1490     my $query = "
1491         SELECT reserve_id, borrowernumber, reservedate
1492         FROM   reserves
1493         WHERE  biblionumber   = ?
1494           AND  ((found <> 'W' AND found <> 'T') OR found IS NULL)
1495         ORDER BY priority ASC
1496     ";
1497     my $sth = $dbh->prepare($query);
1498     $sth->execute( $biblionumber );
1499     while ( my $line = $sth->fetchrow_hashref ) {
1500         push( @priority,     $line );
1501     }
1502
1503     # To find the matching index
1504     my $i;
1505     my $key = -1;    # to allow for 0 to be a valid result
1506     for ( $i = 0 ; $i < @priority ; $i++ ) {
1507         if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1508             $key = $i;    # save the index
1509             last;
1510         }
1511     }
1512
1513     # if index exists in array then move it to new position
1514     if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1515         my $new_rank = $rank -
1516           1;    # $new_rank is what you want the new index to be in the array
1517         my $moving_item = splice( @priority, $key, 1 );
1518         splice( @priority, $new_rank, 0, $moving_item );
1519     }
1520
1521     # now fix the priority on those that are left....
1522     $query = "
1523         UPDATE reserves
1524         SET    priority = ?
1525         WHERE  reserve_id = ?
1526     ";
1527     $sth = $dbh->prepare($query);
1528     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1529         $sth->execute(
1530             $j + 1,
1531             $priority[$j]->{'reserve_id'}
1532         );
1533     }
1534
1535     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1536     $sth->execute();
1537
1538     unless ( $ignoreSetLowestRank ) {
1539       while ( my $res = $sth->fetchrow_hashref() ) {
1540         _FixPriority({
1541             reserve_id => $res->{'reserve_id'},
1542             rank => '999999',
1543             ignoreSetLowestRank => 1
1544         });
1545       }
1546     }
1547 }
1548
1549 =head2 _Findgroupreserve
1550
1551   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1552
1553 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1554 first match found.  If neither, then we look for non-holds-queue based holds.
1555 Lookahead is the number of days to look in advance.
1556
1557 C<&_Findgroupreserve> returns :
1558 C<@results> is an array of references-to-hash whose keys are mostly
1559 fields from the reserves table of the Koha database, plus
1560 C<biblioitemnumber>.
1561
1562 =cut
1563
1564 sub _Findgroupreserve {
1565     my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1566     my $dbh   = C4::Context->dbh;
1567
1568     # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1569     # check for exact targeted match
1570     my $item_level_target_query = qq{
1571         SELECT reserves.biblionumber        AS biblionumber,
1572                reserves.borrowernumber      AS borrowernumber,
1573                reserves.reservedate         AS reservedate,
1574                reserves.branchcode          AS branchcode,
1575                reserves.cancellationdate    AS cancellationdate,
1576                reserves.found               AS found,
1577                reserves.reservenotes        AS reservenotes,
1578                reserves.priority            AS priority,
1579                reserves.timestamp           AS timestamp,
1580                biblioitems.biblioitemnumber AS biblioitemnumber,
1581                reserves.itemnumber          AS itemnumber,
1582                reserves.reserve_id          AS reserve_id,
1583                reserves.itemtype            AS itemtype
1584         FROM reserves
1585         JOIN biblioitems USING (biblionumber)
1586         JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1587         WHERE found IS NULL
1588         AND priority > 0
1589         AND item_level_request = 1
1590         AND itemnumber = ?
1591         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1592         AND suspend = 0
1593         ORDER BY priority
1594     };
1595     my $sth = $dbh->prepare($item_level_target_query);
1596     $sth->execute($itemnumber, $lookahead||0);
1597     my @results;
1598     if ( my $data = $sth->fetchrow_hashref ) {
1599         push( @results, $data )
1600           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1601     }
1602     return @results if @results;
1603
1604     # check for title-level targeted match
1605     my $title_level_target_query = qq{
1606         SELECT reserves.biblionumber        AS biblionumber,
1607                reserves.borrowernumber      AS borrowernumber,
1608                reserves.reservedate         AS reservedate,
1609                reserves.branchcode          AS branchcode,
1610                reserves.cancellationdate    AS cancellationdate,
1611                reserves.found               AS found,
1612                reserves.reservenotes        AS reservenotes,
1613                reserves.priority            AS priority,
1614                reserves.timestamp           AS timestamp,
1615                biblioitems.biblioitemnumber AS biblioitemnumber,
1616                reserves.itemnumber          AS itemnumber,
1617                reserves.reserve_id          AS reserve_id,
1618                reserves.itemtype            AS itemtype
1619         FROM reserves
1620         JOIN biblioitems USING (biblionumber)
1621         JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1622         WHERE found IS NULL
1623         AND priority > 0
1624         AND item_level_request = 0
1625         AND hold_fill_targets.itemnumber = ?
1626         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1627         AND suspend = 0
1628         ORDER BY priority
1629     };
1630     $sth = $dbh->prepare($title_level_target_query);
1631     $sth->execute($itemnumber, $lookahead||0);
1632     @results = ();
1633     if ( my $data = $sth->fetchrow_hashref ) {
1634         push( @results, $data )
1635           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1636     }
1637     return @results if @results;
1638
1639     my $query = qq{
1640         SELECT reserves.biblionumber               AS biblionumber,
1641                reserves.borrowernumber             AS borrowernumber,
1642                reserves.reservedate                AS reservedate,
1643                reserves.waitingdate                AS waitingdate,
1644                reserves.branchcode                 AS branchcode,
1645                reserves.cancellationdate           AS cancellationdate,
1646                reserves.found                      AS found,
1647                reserves.reservenotes               AS reservenotes,
1648                reserves.priority                   AS priority,
1649                reserves.timestamp                  AS timestamp,
1650                reserves.itemnumber                 AS itemnumber,
1651                reserves.reserve_id                 AS reserve_id,
1652                reserves.itemtype                   AS itemtype
1653         FROM reserves
1654         WHERE reserves.biblionumber = ?
1655           AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1656           AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1657           AND suspend = 0
1658           ORDER BY priority
1659     };
1660     $sth = $dbh->prepare($query);
1661     $sth->execute( $biblio, $itemnumber, $lookahead||0);
1662     @results = ();
1663     while ( my $data = $sth->fetchrow_hashref ) {
1664         push( @results, $data )
1665           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1666     }
1667     return @results;
1668 }
1669
1670 =head2 _koha_notify_reserve
1671
1672   _koha_notify_reserve( $hold->reserve_id );
1673
1674 Sends a notification to the patron that their hold has been filled (through
1675 ModReserveAffect, _not_ ModReserveFill)
1676
1677 The letter code for this notice may be found using the following query:
1678
1679     select distinct letter_code
1680     from message_transports
1681     inner join message_attributes using (message_attribute_id)
1682     where message_name = 'Hold_Filled'
1683
1684 This will probably sipmly be 'HOLD', but because it is defined in the database,
1685 it is subject to addition or change.
1686
1687 The following tables are availalbe witin the notice:
1688
1689     branches
1690     borrowers
1691     biblio
1692     biblioitems
1693     reserves
1694     items
1695
1696 =cut
1697
1698 sub _koha_notify_reserve {
1699     my $reserve_id = shift;
1700     my $hold = Koha::Holds->find($reserve_id);
1701     my $borrowernumber = $hold->borrowernumber;
1702
1703     my $patron = Koha::Patrons->find( $borrowernumber );
1704
1705     # Try to get the borrower's email address
1706     my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1707
1708     my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1709             borrowernumber => $borrowernumber,
1710             message_name => 'Hold_Filled'
1711     } );
1712
1713     my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1714
1715     my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1716
1717     my %letter_params = (
1718         module => 'reserves',
1719         branchcode => $hold->branchcode,
1720         lang => $patron->lang,
1721         tables => {
1722             'branches'       => $library,
1723             'borrowers'      => $patron->unblessed,
1724             'biblio'         => $hold->biblionumber,
1725             'biblioitems'    => $hold->biblionumber,
1726             'reserves'       => $hold->unblessed,
1727             'items'          => $hold->itemnumber,
1728         },
1729     );
1730
1731     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.
1732     my $send_notification = sub {
1733         my ( $mtt, $letter_code ) = (@_);
1734         return unless defined $letter_code;
1735         $letter_params{letter_code} = $letter_code;
1736         $letter_params{message_transport_type} = $mtt;
1737         my $letter =  C4::Letters::GetPreparedLetter ( %letter_params );
1738         unless ($letter) {
1739             warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1740             return;
1741         }
1742
1743         C4::Letters::EnqueueLetter( {
1744             letter => $letter,
1745             borrowernumber => $borrowernumber,
1746             from_address => $admin_email_address,
1747             message_transport_type => $mtt,
1748         } );
1749     };
1750
1751     while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1752         next if (
1753                ( $mtt eq 'email' and not $to_address ) # No email address
1754             or ( $mtt eq 'sms'   and not $patron->smsalertnumber ) # No SMS number
1755             or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1756         );
1757
1758         &$send_notification($mtt, $letter_code);
1759         $notification_sent++;
1760     }
1761     #Making sure that a print notification is sent if no other transport types can be utilized.
1762     if (! $notification_sent) {
1763         &$send_notification('print', 'HOLD');
1764     }
1765
1766 }
1767
1768 =head2 _ShiftPriorityByDateAndPriority
1769
1770   $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1771
1772 This increments the priority of all reserves after the one
1773 with either the lowest date after C<$reservedate>
1774 or the lowest priority after C<$priority>.
1775
1776 It effectively makes room for a new reserve to be inserted with a certain
1777 priority, which is returned.
1778
1779 This is most useful when the reservedate can be set by the user.  It allows
1780 the new reserve to be placed before other reserves that have a later
1781 reservedate.  Since priority also is set by the form in reserves/request.pl
1782 the sub accounts for that too.
1783
1784 =cut
1785
1786 sub _ShiftPriorityByDateAndPriority {
1787     my ( $biblio, $resdate, $new_priority ) = @_;
1788
1789     my $dbh = C4::Context->dbh;
1790     my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1791     my $sth = $dbh->prepare( $query );
1792     $sth->execute( $biblio, $resdate, $new_priority );
1793     my $min_priority = $sth->fetchrow;
1794     # if no such matches are found, $new_priority remains as original value
1795     $new_priority = $min_priority if ( $min_priority );
1796
1797     # Shift the priority up by one; works in conjunction with the next SQL statement
1798     $query = "UPDATE reserves
1799               SET priority = priority+1
1800               WHERE biblionumber = ?
1801               AND borrowernumber = ?
1802               AND reservedate = ?
1803               AND found IS NULL";
1804     my $sth_update = $dbh->prepare( $query );
1805
1806     # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1807     $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1808     $sth = $dbh->prepare( $query );
1809     $sth->execute( $new_priority, $biblio );
1810     while ( my $row = $sth->fetchrow_hashref ) {
1811         $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1812     }
1813
1814     return $new_priority;  # so the caller knows what priority they wind up receiving
1815 }
1816
1817 =head2 OPACItemHoldsAllowed
1818
1819   OPACItemHoldsAllowed($item_record,$borrower_record);
1820
1821 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1822 if specific item holds are allowed, returns true if so.
1823
1824 =cut
1825
1826 sub OPACItemHoldsAllowed {
1827     my ($item,$borrower) = @_;
1828
1829     my $branchcode = $item->{homebranch} or die "No homebranch";
1830     my $itype;
1831     my $dbh = C4::Context->dbh;
1832     if (C4::Context->preference('item-level_itypes')) {
1833        # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1834        # When GetItem is fixed, we can remove this
1835        $itype = $item->{itype};
1836     }
1837     else {
1838        my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1839        my $sth = $dbh->prepare($query);
1840        $sth->execute($item->{biblioitemnumber});
1841        if (my $data = $sth->fetchrow_hashref()){
1842            $itype = $data->{itemtype};
1843        }
1844     }
1845
1846     my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1847           (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1848         AND
1849           (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1850         AND
1851           (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1852         ORDER BY
1853           issuingrules.categorycode desc,
1854           issuingrules.itemtype desc,
1855           issuingrules.branchcode desc
1856        LIMIT 1";
1857     my $sth = $dbh->prepare($query);
1858     $sth->execute($borrower->{categorycode},$itype,$branchcode);
1859     my $data = $sth->fetchrow_hashref;
1860     my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1861     return '' if $opacitemholds eq 'N';
1862     return $opacitemholds;
1863 }
1864
1865 =head2 MoveReserve
1866
1867   MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1868
1869 Use when checking out an item to handle reserves
1870 If $cancelreserve boolean is set to true, it will remove existing reserve
1871
1872 =cut
1873
1874 sub MoveReserve {
1875     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1876
1877     my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1878     my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1879     return unless $res;
1880
1881     my $biblionumber     =  $res->{biblionumber};
1882
1883     if ($res->{borrowernumber} == $borrowernumber) {
1884         ModReserveFill($res);
1885     }
1886     else {
1887         # warn "Reserved";
1888         # The item is reserved by someone else.
1889         # Find this item in the reserves
1890
1891         my $borr_res;
1892         foreach (@$all_reserves) {
1893             $_->{'borrowernumber'} == $borrowernumber or next;
1894             $_->{'biblionumber'}   == $biblionumber   or next;
1895
1896             $borr_res = $_;
1897             last;
1898         }
1899
1900         if ( $borr_res ) {
1901             # The item is reserved by the current patron
1902             ModReserveFill($borr_res);
1903         }
1904
1905         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1906             RevertWaitingStatus({ itemnumber => $itemnumber });
1907         }
1908         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1909             my $hold = Koha::Holds->find( $res->{reserve_id} );
1910             $hold->cancel;
1911         }
1912     }
1913 }
1914
1915 =head2 MergeHolds
1916
1917   MergeHolds($dbh,$to_biblio, $from_biblio);
1918
1919 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1920
1921 =cut
1922
1923 sub MergeHolds {
1924     my ( $dbh, $to_biblio, $from_biblio ) = @_;
1925     my $sth = $dbh->prepare(
1926         "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1927     );
1928     $sth->execute($from_biblio);
1929     if ( my $data = $sth->fetchrow_hashref() ) {
1930
1931         # holds exist on old record, if not we don't need to do anything
1932         $sth = $dbh->prepare(
1933             "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1934         $sth->execute( $to_biblio, $from_biblio );
1935
1936         # Reorder by date
1937         # don't reorder those already waiting
1938
1939         $sth = $dbh->prepare(
1940 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1941         );
1942         my $upd_sth = $dbh->prepare(
1943 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1944         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1945         );
1946         $sth->execute( $to_biblio, 'W', 'T' );
1947         my $priority = 1;
1948         while ( my $reserve = $sth->fetchrow_hashref() ) {
1949             $upd_sth->execute(
1950                 $priority,                    $to_biblio,
1951                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1952                 $reserve->{'itemnumber'}
1953             );
1954             $priority++;
1955         }
1956     }
1957 }
1958
1959 =head2 RevertWaitingStatus
1960
1961   RevertWaitingStatus({ itemnumber => $itemnumber });
1962
1963   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1964
1965   Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1966           item level hold, even if it was only a bibliolevel hold to
1967           begin with. This is because we can no longer know if a hold
1968           was item-level or bib-level after a hold has been set to
1969           waiting status.
1970
1971 =cut
1972
1973 sub RevertWaitingStatus {
1974     my ( $params ) = @_;
1975     my $itemnumber = $params->{'itemnumber'};
1976
1977     return unless ( $itemnumber );
1978
1979     my $dbh = C4::Context->dbh;
1980
1981     ## Get the waiting reserve we want to revert
1982     my $query = "
1983         SELECT * FROM reserves
1984         WHERE itemnumber = ?
1985         AND found IS NOT NULL
1986     ";
1987     my $sth = $dbh->prepare( $query );
1988     $sth->execute( $itemnumber );
1989     my $reserve = $sth->fetchrow_hashref();
1990
1991     ## Increment the priority of all other non-waiting
1992     ## reserves for this bib record
1993     $query = "
1994         UPDATE reserves
1995         SET
1996           priority = priority + 1
1997         WHERE
1998           biblionumber =  ?
1999         AND
2000           priority > 0
2001     ";
2002     $sth = $dbh->prepare( $query );
2003     $sth->execute( $reserve->{'biblionumber'} );
2004
2005     ## Fix up the currently waiting reserve
2006     $query = "
2007     UPDATE reserves
2008     SET
2009       priority = 1,
2010       found = NULL,
2011       waitingdate = NULL
2012     WHERE
2013       reserve_id = ?
2014     ";
2015     $sth = $dbh->prepare( $query );
2016     $sth->execute( $reserve->{'reserve_id'} );
2017     _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2018 }
2019
2020 =head2 ReserveSlip
2021
2022   ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2023
2024 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2025
2026 The letter code will be HOLD_SLIP, and the following tables are
2027 available within the slip:
2028
2029     reserves
2030     branches
2031     borrowers
2032     biblio
2033     biblioitems
2034     items
2035
2036 =cut
2037
2038 sub ReserveSlip {
2039     my ($branch, $borrowernumber, $biblionumber) = @_;
2040
2041 #   return unless ( C4::Context->boolean_preference('printreserveslips') );
2042     my $patron = Koha::Patrons->find( $borrowernumber );
2043
2044     my $hold = Koha::Holds->search({biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next;
2045     return unless $hold;
2046     my $reserve = $hold->unblessed;
2047
2048     return  C4::Letters::GetPreparedLetter (
2049         module => 'circulation',
2050         letter_code => 'HOLD_SLIP',
2051         branchcode => $branch,
2052         lang => $patron->lang,
2053         tables => {
2054             'reserves'    => $reserve,
2055             'branches'    => $reserve->{branchcode},
2056             'borrowers'   => $reserve->{borrowernumber},
2057             'biblio'      => $reserve->{biblionumber},
2058             'biblioitems' => $reserve->{biblionumber},
2059             'items'       => $reserve->{itemnumber},
2060         },
2061     );
2062 }
2063
2064 =head2 GetReservesControlBranch
2065
2066   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2067
2068   Return the branchcode to be used to determine which reserves
2069   policy applies to a transaction.
2070
2071   C<$item> is a hashref for an item. Only 'homebranch' is used.
2072
2073   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2074
2075 =cut
2076
2077 sub GetReservesControlBranch {
2078     my ( $item, $borrower ) = @_;
2079
2080     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2081
2082     my $branchcode =
2083         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2084       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2085       :                                              undef;
2086
2087     return $branchcode;
2088 }
2089
2090 =head2 CalculatePriority
2091
2092     my $p = CalculatePriority($biblionumber, $resdate);
2093
2094 Calculate priority for a new reserve on biblionumber, placing it at
2095 the end of the line of all holds whose start date falls before
2096 the current system time and that are neither on the hold shelf
2097 or in transit.
2098
2099 The reserve date parameter is optional; if it is supplied, the
2100 priority is based on the set of holds whose start date falls before
2101 the parameter value.
2102
2103 After calculation of this priority, it is recommended to call
2104 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2105 AddReserves.
2106
2107 =cut
2108
2109 sub CalculatePriority {
2110     my ( $biblionumber, $resdate ) = @_;
2111
2112     my $sql = q{
2113         SELECT COUNT(*) FROM reserves
2114         WHERE biblionumber = ?
2115         AND   priority > 0
2116         AND   (found IS NULL OR found = '')
2117     };
2118     #skip found==W or found==T (waiting or transit holds)
2119     if( $resdate ) {
2120         $sql.= ' AND ( reservedate <= ? )';
2121     }
2122     else {
2123         $sql.= ' AND ( reservedate < NOW() )';
2124     }
2125     my $dbh = C4::Context->dbh();
2126     my @row = $dbh->selectrow_array(
2127         $sql,
2128         undef,
2129         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2130     );
2131
2132     return @row ? $row[0]+1 : 1;
2133 }
2134
2135 =head2 IsItemOnHoldAndFound
2136
2137     my $bool = IsItemFoundHold( $itemnumber );
2138
2139     Returns true if the item is currently on hold
2140     and that hold has a non-null found status ( W, T, etc. )
2141
2142 =cut
2143
2144 sub IsItemOnHoldAndFound {
2145     my ($itemnumber) = @_;
2146
2147     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2148
2149     my $found = $rs->count(
2150         {
2151             itemnumber => $itemnumber,
2152             found      => { '!=' => undef }
2153         }
2154     );
2155
2156     return $found;
2157 }
2158
2159 =head2 GetMaxPatronHoldsForRecord
2160
2161 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2162
2163 For multiple holds on a given record for a given patron, the max
2164 number of record level holds that a patron can be placed is the highest
2165 value of the holds_per_record rule for each item if the record for that
2166 patron. This subroutine finds and returns the highest holds_per_record
2167 rule value for a given patron id and record id.
2168
2169 =cut
2170
2171 sub GetMaxPatronHoldsForRecord {
2172     my ( $borrowernumber, $biblionumber ) = @_;
2173
2174     my $patron = Koha::Patrons->find($borrowernumber);
2175     my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2176
2177     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2178
2179     my $categorycode = $patron->categorycode;
2180     my $branchcode;
2181     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2182
2183     my $max = 0;
2184     foreach my $item (@items) {
2185         my $itemtype = $item->effective_itemtype();
2186
2187         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2188
2189         my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2190         my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2191         $max = $holds_per_record if $holds_per_record > $max;
2192     }
2193
2194     return $max;
2195 }
2196
2197 =head2 GetHoldRule
2198
2199 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2200
2201 Returns the matching hold related issuingrule fields for a given
2202 patron category, itemtype, and library.
2203
2204 =cut
2205
2206 sub GetHoldRule {
2207     my ( $categorycode, $itemtype, $branchcode ) = @_;
2208
2209     my $dbh = C4::Context->dbh;
2210
2211     my $sth = $dbh->prepare(
2212         q{
2213          SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2214            FROM issuingrules
2215           WHERE (categorycode in (?,'*') )
2216             AND (itemtype IN (?,'*'))
2217             AND (branchcode IN (?,'*'))
2218        ORDER BY categorycode DESC,
2219                 itemtype     DESC,
2220                 branchcode   DESC
2221         }
2222     );
2223
2224     $sth->execute( $categorycode, $itemtype, $branchcode );
2225
2226     return $sth->fetchrow_hashref();
2227 }
2228
2229 =head1 AUTHOR
2230
2231 Koha Development Team <http://koha-community.org/>
2232
2233 =cut
2234
2235 1;