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