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