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