Bug 22330: Transfer limits should be respected for placing holds in staff interface...
[koha.git] / C4 / Reserves.pm
1 package C4::Reserves;
2
3 # Copyright 2000-2002 Katipo Communications
4 #           2006 SAN Ouest Provence
5 #           2007-2010 BibLibre Paul POULAIN
6 #           2011 Catalyst IT
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23
24 use strict;
25 #use warnings; FIXME - Bug 2505
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Items;
31 use C4::Members;
32
33 # for _koha_notify_reserve
34 use C4::Letters;
35 use C4::Log;
36 use C4::Members qw();
37 use C4::Members::Messaging;
38
39 use Koha::Account::Lines;
40 use Koha::Biblios;
41 use Koha::Calendar;
42 use Koha::CirculationRules;
43 use Koha::Database;
44 use Koha::DateUtils;
45 use Koha::Hold;
46 use Koha::Holds;
47 use Koha::IssuingRules;
48 use Koha::ItemTypes;
49 use Koha::Items;
50 use Koha::Libraries;
51 use Koha::Libraries;
52 use Koha::Old::Hold;
53 use Koha::Patrons;
54
55 use Carp;
56 use Data::Dumper;
57 use List::MoreUtils qw( firstidx any );
58
59 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
60
61 =head1 NAME
62
63 C4::Reserves - Koha functions for dealing with reservation.
64
65 =head1 SYNOPSIS
66
67   use C4::Reserves;
68
69 =head1 DESCRIPTION
70
71 This modules provides somes functions to deal with reservations.
72
73   Reserves are stored in reserves table.
74   The following columns contains important values :
75   - priority >0      : then the reserve is at 1st stage, and not yet affected to any item.
76              =0      : then the reserve is being dealed
77   - found : NULL       : means the patron requested the 1st available, and we haven't chosen the item
78             T(ransit)  : the reserve is linked to an item but is in transit to the pickup branch
79             W(aiting)  : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
80             F(inished) : the reserve has been completed, and is done
81   - itemnumber : empty : the reserve is still unaffected to an item
82                  filled: the reserve is attached to an item
83   The complete workflow is :
84   ==== 1st use case ====
85   patron request a document, 1st available :                      P >0, F=NULL, I=NULL
86   a library having it run "transfertodo", and clic on the list
87          if there is no transfer to do, the reserve waiting
88          patron can pick it up                                    P =0, F=W,    I=filled
89          if there is a transfer to do, write in branchtransfer    P =0, F=T,    I=filled
90            The pickup library receive the book, it check in       P =0, F=W,    I=filled
91   The patron borrow the book                                      P =0, F=F,    I=filled
92
93   ==== 2nd use case ====
94   patron requests a document, a given item,
95     If pickup is holding branch                                   P =0, F=W,   I=filled
96     If transfer needed, write in branchtransfer                   P =0, F=T,    I=filled
97         The pickup library receive the book, it checks it in      P =0, F=W,    I=filled
98   The patron borrow the book                                      P =0, F=F,    I=filled
99
100 =head1 FUNCTIONS
101
102 =cut
103
104 BEGIN {
105     require Exporter;
106     @ISA = qw(Exporter);
107     @EXPORT = qw(
108         &AddReserve
109
110         &GetReserveStatus
111
112         &GetOtherReserves
113
114         &ModReserveFill
115         &ModReserveAffect
116         &ModReserve
117         &ModReserveStatus
118         &ModReserveCancelAll
119         &ModReserveMinusPriority
120         &MoveReserve
121
122         &CheckReserves
123         &CanBookBeReserved
124         &CanItemBeReserved
125         &CanReserveBeCanceledFromOpac
126         &CancelExpiredReserves
127
128         &AutoUnsuspendReserves
129
130         &IsAvailableForItemLevelRequest
131
132         &AlterPriority
133         &ToggleLowestPriority
134
135         &ReserveSlip
136         &ToggleSuspend
137         &SuspendAll
138
139         &GetReservesControlBranch
140
141         IsItemOnHoldAndFound
142
143         GetMaxPatronHoldsForRecord
144     );
145     @EXPORT_OK = qw( MergeHolds );
146 }
147
148 =head2 AddReserve
149
150     AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
151
152 Adds reserve and generates HOLDPLACED message.
153
154 The following tables are available witin the HOLDPLACED message:
155
156     branches
157     borrowers
158     biblio
159     biblioitems
160     items
161     reserves
162
163 =cut
164
165 sub AddReserve {
166     my (
167         $branch,   $borrowernumber, $biblionumber, $bibitems,
168         $priority, $resdate,        $expdate,      $notes,
169         $title,    $checkitem,      $found,        $itemtype
170     ) = @_;
171
172     $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
173         or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
174
175     $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
176
177     # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
178     # of the document, we force the value $priority and $found .
179     if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
180         $priority = 0;
181         my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
182         if ( $item->holdingbranch eq $branch ) {
183             $found = 'W';
184         }
185     }
186
187     if ( C4::Context->preference('AllowHoldDateInFuture') ) {
188
189         # Make room in reserves for this before those of a later reserve date
190         $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
191     }
192
193     my $waitingdate;
194
195     # If the reserv had the waiting status, we had the value of the resdate
196     if ( $found eq 'W' ) {
197         $waitingdate = $resdate;
198     }
199
200     # Don't add itemtype limit if specific item is selected
201     $itemtype = undef if $checkitem;
202
203     # updates take place here
204     my $hold = Koha::Hold->new(
205         {
206             borrowernumber => $borrowernumber,
207             biblionumber   => $biblionumber,
208             reservedate    => $resdate,
209             branchcode     => $branch,
210             priority       => $priority,
211             reservenotes   => $notes,
212             itemnumber     => $checkitem,
213             found          => $found,
214             waitingdate    => $waitingdate,
215             expirationdate => $expdate,
216             itemtype       => $itemtype,
217         }
218     )->store();
219     $hold->set_waiting() if $found eq 'W';
220
221     logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
222         if C4::Context->preference('HoldsLog');
223
224     my $reserve_id = $hold->id();
225
226     # add a reserve fee if needed
227     if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
228         my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
229         ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
230     }
231
232     _FixPriority({ biblionumber => $biblionumber});
233
234     # Send e-mail to librarian if syspref is active
235     if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
236         my $patron = Koha::Patrons->find( $borrowernumber );
237         my $library = $patron->library;
238         if ( my $letter =  C4::Letters::GetPreparedLetter (
239             module => 'reserves',
240             letter_code => 'HOLDPLACED',
241             branchcode => $branch,
242             lang => $patron->lang,
243             tables => {
244                 'branches'    => $library->unblessed,
245                 'borrowers'   => $patron->unblessed,
246                 'biblio'      => $biblionumber,
247                 'biblioitems' => $biblionumber,
248                 'items'       => $checkitem,
249                 'reserves'    => $hold->unblessed,
250             },
251         ) ) {
252
253             my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
254
255             C4::Letters::EnqueueLetter(
256                 {   letter                 => $letter,
257                     borrowernumber         => $borrowernumber,
258                     message_transport_type => 'email',
259                     from_address           => $admin_email_address,
260                     to_address           => $admin_email_address,
261                 }
262             );
263         }
264     }
265
266     return $reserve_id;
267 }
268
269 =head2 CanBookBeReserved
270
271   $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
272   if ($canReserve eq 'OK') { #We can reserve this Item! }
273
274 See CanItemBeReserved() for possible return values.
275
276 =cut
277
278 sub CanBookBeReserved{
279     my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
280
281     my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
282     #get items linked via host records
283     my @hostitems = get_hostitemnumbers_of($biblionumber);
284     if (@hostitems){
285         push (@itemnumbers, @hostitems);
286     }
287
288     my $canReserve = { status => '' };
289     foreach my $itemnumber (@itemnumbers) {
290         $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
291         return { status => 'OK' } if $canReserve->{status} eq 'OK';
292     }
293     return $canReserve;
294 }
295
296 =head2 CanItemBeReserved
297
298   $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
299   if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
300
301 @RETURNS { status => OK },              if the Item can be reserved.
302          { status => ageRestricted },   if the Item is age restricted for this borrower.
303          { status => damaged },         if the Item is damaged.
304          { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
305          { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
306          { status => notReservable },   if holds on this item are not allowed
307          { status => libraryNotFound },   if given branchcode is not an existing library
308          { status => libraryNotPickupLocation },   if given branchcode is not configured to be a pickup location
309          { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
310
311 =cut
312
313 sub CanItemBeReserved {
314     my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
315
316     my $dbh = C4::Context->dbh;
317     my $ruleitemtype;    # itemtype of the matching issuing rule
318     my $allowedreserves  = 0; # Total number of holds allowed across all records
319     my $holds_per_record = 1; # Total number of holds allowed for this one given record
320     my $holds_per_day;        # Default to unlimited
321
322     # we retrieve borrowers and items informations #
323     # item->{itype} will come for biblioitems if necessery
324     my $item       = Koha::Items->find($itemnumber);
325     my $biblio     = $item->biblio;
326     my $patron = Koha::Patrons->find( $borrowernumber );
327     my $borrower = $patron->unblessed;
328
329     # If an item is damaged and we don't allow holds on damaged items, we can stop right here
330     return { status =>'damaged' }
331       if ( $item->damaged
332         && !C4::Context->preference('AllowHoldsOnDamagedItems') );
333
334     # Check for the age restriction
335     my ( $ageRestriction, $daysToAgeRestriction ) =
336       C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
337     return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
338
339     # Check that the patron doesn't have an item level hold on this item already
340     return { status =>'itemAlreadyOnHold' }
341       if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
342
343     my $controlbranch = C4::Context->preference('ReservesControlBranch');
344
345     my $querycount = q{
346         SELECT count(*) AS count
347           FROM reserves
348      LEFT JOIN items USING (itemnumber)
349      LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
350      LEFT JOIN borrowers USING (borrowernumber)
351          WHERE borrowernumber = ?
352     };
353
354     my $branchcode  = "";
355     my $branchfield = "reserves.branchcode";
356
357     if ( $controlbranch eq "ItemHomeLibrary" ) {
358         $branchfield = "items.homebranch";
359         $branchcode  = $item->homebranch;
360     }
361     elsif ( $controlbranch eq "PatronLibrary" ) {
362         $branchfield = "borrowers.branchcode";
363         $branchcode  = $borrower->{branchcode};
364     }
365
366     # we retrieve rights
367     if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
368         $ruleitemtype     = $rights->{itemtype};
369         $allowedreserves  = $rights->{reservesallowed};
370         $holds_per_record = $rights->{holds_per_record};
371         $holds_per_day    = $rights->{holds_per_day};
372     }
373     else {
374         $ruleitemtype = '*';
375     }
376
377     my $holds = Koha::Holds->search(
378         {
379             borrowernumber => $borrowernumber,
380             biblionumber   => $item->biblionumber,
381             found          => undef, # Found holds don't count against a patron's holds limit
382         }
383     );
384     if ( $holds->count() >= $holds_per_record ) {
385         return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
386     }
387
388     my $today_holds = Koha::Holds->search({
389         borrowernumber => $borrowernumber,
390         reservedate    => dt_from_string->date
391     });
392
393     if ( defined $holds_per_day &&
394           (   ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
395            or ( $holds_per_day == 0 ) )
396         )  {
397         return { status => 'tooManyReservesToday', limit => $holds_per_day };
398     }
399
400     # we retrieve count
401
402     $querycount .= "AND $branchfield = ?";
403
404     # If using item-level itypes, fall back to the record
405     # level itemtype if the hold has no associated item
406     $querycount .=
407       C4::Context->preference('item-level_itypes')
408       ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
409       : " AND biblioitems.itemtype = ?"
410       if ( $ruleitemtype ne "*" );
411
412     my $sthcount = $dbh->prepare($querycount);
413
414     if ( $ruleitemtype eq "*" ) {
415         $sthcount->execute( $borrowernumber, $branchcode );
416     }
417     else {
418         $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
419     }
420
421     my $reservecount = "0";
422     if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
423         $reservecount = $rowcount->{count};
424     }
425
426     # we check if it's ok or not
427     if ( $reservecount >= $allowedreserves ) {
428         return { status => 'tooManyReserves', limit => $allowedreserves };
429     }
430
431     # Now we need to check hold limits by patron category
432     my $rule = Koha::CirculationRules->get_effective_rule(
433         {
434             categorycode => $borrower->{categorycode},
435             branchcode   => $branchcode,
436             rule_name    => 'max_holds',
437         }
438     );
439     if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
440         my $total_holds_count = Koha::Holds->search(
441             {
442                 borrowernumber => $borrower->{borrowernumber}
443             }
444         )->count();
445
446         return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
447     }
448
449     my $circ_control_branch =
450       C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
451     my $branchitemrule =
452       C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
453
454     if ( $branchitemrule->{holdallowed} == 0 ) {
455         return { status => 'notReservable' };
456     }
457
458     if (   $branchitemrule->{holdallowed} == 1
459         && $borrower->{branchcode} ne $item->homebranch )
460     {
461         return { status => 'cannotReserveFromOtherBranches' };
462     }
463
464     # If reservecount is ok, we check item branch if IndependentBranches is ON
465     # and canreservefromotherbranches is OFF
466     if ( C4::Context->preference('IndependentBranches')
467         and !C4::Context->preference('canreservefromotherbranches') )
468     {
469         if ( $item->homebranch ne $borrower->{branchcode} ) {
470             return { status => 'cannotReserveFromOtherBranches' };
471         }
472     }
473
474     if ($pickup_branchcode) {
475         my $destination = Koha::Libraries->find({
476             branchcode => $pickup_branchcode,
477         });
478
479         unless ($destination) {
480             return { status => 'libraryNotFound' };
481         }
482         unless ($destination->pickup_location) {
483             return { status => 'libraryNotPickupLocation' };
484         }
485         unless ($item->can_be_transferred({ to => $destination })) {
486             return { status => 'cannotBeTransferred' };
487         }
488     }
489
490     return { status => 'OK' };
491 }
492
493 =head2 CanReserveBeCanceledFromOpac
494
495     $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
496
497     returns 1 if reserve can be cancelled by user from OPAC.
498     First check if reserve belongs to user, next checks if reserve is not in
499     transfer or waiting status
500
501 =cut
502
503 sub CanReserveBeCanceledFromOpac {
504     my ($reserve_id, $borrowernumber) = @_;
505
506     return unless $reserve_id and $borrowernumber;
507     my $reserve = Koha::Holds->find($reserve_id);
508
509     return 0 unless $reserve->borrowernumber == $borrowernumber;
510     return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
511
512     return 1;
513
514 }
515
516 =head2 GetOtherReserves
517
518   ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
519
520 Check queued list of this document and check if this document must be transferred
521
522 =cut
523
524 sub GetOtherReserves {
525     my ($itemnumber) = @_;
526     my $messages;
527     my $nextreservinfo;
528     my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
529     if ($checkreserves) {
530         my $item = Koha::Items->find($itemnumber);
531         if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
532             $messages->{'transfert'} = $checkreserves->{'branchcode'};
533             #minus priorities of others reservs
534             ModReserveMinusPriority(
535                 $itemnumber,
536                 $checkreserves->{'reserve_id'},
537             );
538
539             #launch the subroutine dotransfer
540             C4::Items::ModItemTransfer(
541                 $itemnumber,
542                 $item->holdingbranch,
543                 $checkreserves->{'branchcode'}
544               ),
545               ;
546         }
547
548      #step 2b : case of a reservation on the same branch, set the waiting status
549         else {
550             $messages->{'waiting'} = 1;
551             ModReserveMinusPriority(
552                 $itemnumber,
553                 $checkreserves->{'reserve_id'},
554             );
555             ModReserveStatus($itemnumber,'W');
556         }
557
558         $nextreservinfo = $checkreserves->{'borrowernumber'};
559     }
560
561     return ( $messages, $nextreservinfo );
562 }
563
564 =head2 ChargeReserveFee
565
566     $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
567
568     Charge the fee for a reserve (if $fee > 0)
569
570 =cut
571
572 sub ChargeReserveFee {
573     my ( $borrowernumber, $fee, $title ) = @_;
574     return if !$fee || $fee == 0;    # the last test is needed to include 0.00
575     Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
576         {
577             amount       => $fee,
578             description  => "Reserve Charge - " . $title,
579             note         => undef,
580             user_id      => C4::Context->userenv ? C4::Context->userenv->{'number'} : 0,
581             library_id   => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
582             sip          => undef,
583             invoice_type => undef,
584             type         => 'reserve',
585             item_id      => undef
586         }
587     );
588 }
589
590 =head2 GetReserveFee
591
592     $fee = GetReserveFee( $borrowernumber, $biblionumber );
593
594     Calculate the fee for a reserve (if applicable).
595
596 =cut
597
598 sub GetReserveFee {
599     my ( $borrowernumber, $biblionumber ) = @_;
600     my $borquery = qq{
601 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
602     };
603     my $issue_qry = qq{
604 SELECT COUNT(*) FROM items
605 LEFT JOIN issues USING (itemnumber)
606 WHERE items.biblionumber=? AND issues.issue_id IS NULL
607     };
608     my $holds_qry = qq{
609 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
610     };
611
612     my $dbh = C4::Context->dbh;
613     my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
614     my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
615     if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
616         # This is a reconstruction of the old code:
617         # Compare number of items with items issued, and optionally check holds
618         # If not all items are issued and there are no holds: charge no fee
619         # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
620         my ( $notissued, $reserved );
621         ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
622             ( $biblionumber ) );
623         if( $notissued ) {
624             ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
625                 ( $biblionumber, $borrowernumber ) );
626             $fee = 0 if $reserved == 0;
627         }
628     }
629     return $fee;
630 }
631
632 =head2 GetReserveStatus
633
634   $reservestatus = GetReserveStatus($itemnumber);
635
636 Takes an itemnumber and returns the status of the reserve placed on it.
637 If several reserves exist, the reserve with the lower priority is given.
638
639 =cut
640
641 ## FIXME: I don't think this does what it thinks it does.
642 ## It only ever checks the first reserve result, even though
643 ## multiple reserves for that bib can have the itemnumber set
644 ## the sub is only used once in the codebase.
645 sub GetReserveStatus {
646     my ($itemnumber) = @_;
647
648     my $dbh = C4::Context->dbh;
649
650     my ($sth, $found, $priority);
651     if ( $itemnumber ) {
652         $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
653         $sth->execute($itemnumber);
654         ($found, $priority) = $sth->fetchrow_array;
655     }
656
657     if(defined $found) {
658         return 'Waiting'  if $found eq 'W' and $priority == 0;
659         return 'Finished' if $found eq 'F';
660     }
661
662     return 'Reserved' if $priority > 0;
663
664     return ''; # empty string here will remove need for checking undef, or less log lines
665 }
666
667 =head2 CheckReserves
668
669   ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
670   ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
671   ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
672
673 Find a book in the reserves.
674
675 C<$itemnumber> is the book's item number.
676 C<$lookahead> is the number of days to look in advance for future reserves.
677
678 As I understand it, C<&CheckReserves> looks for the given item in the
679 reserves. If it is found, that's a match, and C<$status> is set to
680 C<Waiting>.
681
682 Otherwise, it finds the most important item in the reserves with the
683 same biblio number as this book (I'm not clear on this) and returns it
684 with C<$status> set to C<Reserved>.
685
686 C<&CheckReserves> returns a two-element list:
687
688 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
689
690 C<$reserve> is the reserve item that matched. It is a
691 reference-to-hash whose keys are mostly the fields of the reserves
692 table in the Koha database.
693
694 =cut
695
696 sub CheckReserves {
697     my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
698     my $dbh = C4::Context->dbh;
699     my $sth;
700     my $select;
701     if (C4::Context->preference('item-level_itypes')){
702         $select = "
703            SELECT items.biblionumber,
704            items.biblioitemnumber,
705            itemtypes.notforloan,
706            items.notforloan AS itemnotforloan,
707            items.itemnumber,
708            items.damaged,
709            items.homebranch,
710            items.holdingbranch
711            FROM   items
712            LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
713            LEFT JOIN itemtypes   ON items.itype   = itemtypes.itemtype
714         ";
715     }
716     else {
717         $select = "
718            SELECT items.biblionumber,
719            items.biblioitemnumber,
720            itemtypes.notforloan,
721            items.notforloan AS itemnotforloan,
722            items.itemnumber,
723            items.damaged,
724            items.homebranch,
725            items.holdingbranch
726            FROM   items
727            LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
728            LEFT JOIN itemtypes   ON biblioitems.itemtype   = itemtypes.itemtype
729         ";
730     }
731
732     if ($item) {
733         $sth = $dbh->prepare("$select WHERE itemnumber = ?");
734         $sth->execute($item);
735     }
736     else {
737         $sth = $dbh->prepare("$select WHERE barcode = ?");
738         $sth->execute($barcode);
739     }
740     # note: we get the itemnumber because we might have started w/ just the barcode.  Now we know for sure we have it.
741     my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
742
743     return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
744
745     return unless $itemnumber; # bail if we got nothing.
746
747     # if item is not for loan it cannot be reserved either.....
748     # except where items.notforloan < 0 :  This indicates the item is holdable.
749     return if  ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
750
751     # Find this item in the reserves
752     my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
753
754     # $priority and $highest are used to find the most important item
755     # in the list returned by &_Findgroupreserve. (The lower $priority,
756     # the more important the item.)
757     # $highest is the most important item we've seen so far.
758     my $highest;
759     if (scalar @reserves) {
760         my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
761         my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
762         my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
763
764         my $priority = 10000000;
765         foreach my $res (@reserves) {
766             if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
767                 if ($res->{'found'} eq 'W') {
768                     return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
769                 } else {
770                     return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
771                 }
772             } else {
773                 my $patron;
774                 my $item;
775                 my $local_hold_match;
776
777                 if ($LocalHoldsPriority) {
778                     $patron = Koha::Patrons->find( $res->{borrowernumber} );
779                     $item = Koha::Items->find($itemnumber);
780
781                     my $local_holds_priority_item_branchcode =
782                       $item->$LocalHoldsPriorityItemControl;
783                     my $local_holds_priority_patron_branchcode =
784                       ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
785                       ? $res->{branchcode}
786                       : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
787                       ? $patron->branchcode
788                       : undef;
789                     $local_hold_match =
790                       $local_holds_priority_item_branchcode eq
791                       $local_holds_priority_patron_branchcode;
792                 }
793
794                 # See if this item is more important than what we've got so far
795                 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
796                     $item ||= Koha::Items->find($itemnumber);
797                     next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
798                     $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
799                     my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
800                     my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
801                     next if ($branchitemrule->{'holdallowed'} == 0);
802                     next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
803                     my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
804                     next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
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
985     # get the priority on this record....
986     my $priority = $hold->priority;
987
988     # update the hold statuses, no need to store it though, we will be deleting it anyway
989     $hold->set(
990         {
991             found    => 'F',
992             priority => 0,
993         }
994     );
995
996     # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
997     Koha::Old::Hold->new( $hold->unblessed() )->store();
998
999     $hold->delete();
1000
1001     if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1002         my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1003         ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1004     }
1005
1006     # now fix the priority on the others (if the priority wasn't
1007     # already sorted!)....
1008     unless ( $priority == 0 ) {
1009         _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1010     }
1011 }
1012
1013 =head2 ModReserveStatus
1014
1015   &ModReserveStatus($itemnumber, $newstatus);
1016
1017 Update the reserve status for the active (priority=0) reserve.
1018
1019 $itemnumber is the itemnumber the reserve is on
1020
1021 $newstatus is the new status.
1022
1023 =cut
1024
1025 sub ModReserveStatus {
1026
1027     #first : check if we have a reservation for this item .
1028     my ($itemnumber, $newstatus) = @_;
1029     my $dbh = C4::Context->dbh;
1030
1031     my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1032     my $sth_set = $dbh->prepare($query);
1033     $sth_set->execute( $newstatus, $itemnumber );
1034
1035     if ( C4::Context->preference("ReturnToShelvingCart") && $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
1088     if ( C4::Context->preference("ReturnToShelvingCart") ) {
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 = shift;
1169     my $borrower = shift;
1170     my $pickup_branchcode = shift;
1171
1172     my $dbh = C4::Context->dbh;
1173     # must check the notforloan setting of the itemtype
1174     # FIXME - a lot of places in the code do this
1175     #         or something similar - need to be
1176     #         consolidated
1177     my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
1178     my $item_object = Koha::Items->find( $item->{itemnumber } );
1179     my $itemtype = $item_object->effective_itemtype;
1180     my $notforloan_per_itemtype
1181       = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1182                               undef, $itemtype);
1183
1184     return 0 if
1185         $notforloan_per_itemtype ||
1186         $item->{itemlost}        ||
1187         $item->{notforloan} > 0  ||
1188         $item->{withdrawn}        ||
1189         ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1190
1191     my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item_object, patron => $patron } );
1192
1193     if ($pickup_branchcode) {
1194         my $destination = Koha::Libraries->find($pickup_branchcode);
1195         return 0 unless $destination;
1196         return 0 unless $destination->pickup_location;
1197         return 0 unless $item_object->can_be_transferred( { to => $destination } );
1198     }
1199
1200     if ( $on_shelf_holds == 1 ) {
1201         return 1;
1202     } elsif ( $on_shelf_holds == 2 ) {
1203         my @items =
1204           Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1205
1206         my $any_available = 0;
1207
1208         foreach my $i (@items) {
1209
1210             my $circ_control_branch = C4::Circulation::_GetCircControlBranch( $i->unblessed(), $borrower );
1211             my $branchitemrule = C4::Circulation::GetBranchItemRule( $circ_control_branch, $i->itype );
1212
1213             $any_available = 1
1214               unless $i->itemlost
1215               || $i->notforloan > 0
1216               || $i->withdrawn
1217               || $i->onloan
1218               || IsItemOnHoldAndFound( $i->id )
1219               || ( $i->damaged
1220                 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1221               || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1222               || $branchitemrule->{holdallowed} == 1 && $borrower->{branchcode} ne $i->homebranch;
1223         }
1224
1225         return $any_available ? 0 : 1;
1226     } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1227         return $item->{onloan} || IsItemOnHoldAndFound( $item->{itemnumber} );
1228     }
1229 }
1230
1231 sub _get_itype {
1232     my $item = shift;
1233
1234     my $itype;
1235     if (C4::Context->preference('item-level_itypes')) {
1236         # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1237         # When GetItem is fixed, we can remove this
1238         $itype = $item->{itype};
1239     }
1240     else {
1241         # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1242         # So if we already have a biblioitems join when calling this function,
1243         # we don't need to access the database again
1244         $itype = $item->{itemtype};
1245     }
1246     unless ($itype) {
1247         my $dbh = C4::Context->dbh;
1248         my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1249         my $sth = $dbh->prepare($query);
1250         $sth->execute($item->{biblioitemnumber});
1251         if (my $data = $sth->fetchrow_hashref()){
1252             $itype = $data->{itemtype};
1253         }
1254     }
1255     return $itype;
1256 }
1257
1258 =head2 AlterPriority
1259
1260   AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1261
1262 This function changes a reserve's priority up, down, to the top, or to the bottom.
1263 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1264
1265 =cut
1266
1267 sub AlterPriority {
1268     my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1269
1270     my $hold = Koha::Holds->find( $reserve_id );
1271     return unless $hold;
1272
1273     if ( $hold->cancellationdate ) {
1274         warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1275         return;
1276     }
1277
1278     if ( $where eq 'up' ) {
1279       return unless $prev_priority;
1280       _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1281     } elsif ( $where eq 'down' ) {
1282       return unless $next_priority;
1283       _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1284     } elsif ( $where eq 'top' ) {
1285       _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1286     } elsif ( $where eq 'bottom' ) {
1287       _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1288     }
1289
1290     # FIXME Should return the new priority
1291 }
1292
1293 =head2 ToggleLowestPriority
1294
1295   ToggleLowestPriority( $borrowernumber, $biblionumber );
1296
1297 This function sets the lowestPriority field to true if is false, and false if it is true.
1298
1299 =cut
1300
1301 sub ToggleLowestPriority {
1302     my ( $reserve_id ) = @_;
1303
1304     my $dbh = C4::Context->dbh;
1305
1306     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1307     $sth->execute( $reserve_id );
1308
1309     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1310 }
1311
1312 =head2 ToggleSuspend
1313
1314   ToggleSuspend( $reserve_id );
1315
1316 This function sets the suspend field to true if is false, and false if it is true.
1317 If the reserve is currently suspended with a suspend_until date, that date will
1318 be cleared when it is unsuspended.
1319
1320 =cut
1321
1322 sub ToggleSuspend {
1323     my ( $reserve_id, $suspend_until ) = @_;
1324
1325     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1326
1327     my $hold = Koha::Holds->find( $reserve_id );
1328
1329     if ( $hold->is_suspended ) {
1330         $hold->resume()
1331     } else {
1332         $hold->suspend_hold( $suspend_until );
1333     }
1334 }
1335
1336 =head2 SuspendAll
1337
1338   SuspendAll(
1339       borrowernumber   => $borrowernumber,
1340       [ biblionumber   => $biblionumber, ]
1341       [ suspend_until  => $suspend_until, ]
1342       [ suspend        => $suspend ]
1343   );
1344
1345   This function accepts a set of hash keys as its parameters.
1346   It requires either borrowernumber or biblionumber, or both.
1347
1348   suspend_until is wholly optional.
1349
1350 =cut
1351
1352 sub SuspendAll {
1353     my %params = @_;
1354
1355     my $borrowernumber = $params{'borrowernumber'} || undef;
1356     my $biblionumber   = $params{'biblionumber'}   || undef;
1357     my $suspend_until  = $params{'suspend_until'}  || undef;
1358     my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1359
1360     $suspend_until = eval { dt_from_string($suspend_until) }
1361       if ( defined($suspend_until) );
1362
1363     return unless ( $borrowernumber || $biblionumber );
1364
1365     my $params;
1366     $params->{found}          = undef;
1367     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1368     $params->{biblionumber}   = $biblionumber if $biblionumber;
1369
1370     my @holds = Koha::Holds->search($params);
1371
1372     if ($suspend) {
1373         map { $_->suspend_hold($suspend_until) } @holds;
1374     }
1375     else {
1376         map { $_->resume() } @holds;
1377     }
1378 }
1379
1380
1381 =head2 _FixPriority
1382
1383   _FixPriority({
1384     reserve_id => $reserve_id,
1385     [rank => $rank,]
1386     [ignoreSetLowestRank => $ignoreSetLowestRank]
1387   });
1388
1389   or
1390
1391   _FixPriority({ biblionumber => $biblionumber});
1392
1393 This routine adjusts the priority of a hold request and holds
1394 on the same bib.
1395
1396 In the first form, where a reserve_id is passed, the priority of the
1397 hold is set to supplied rank, and other holds for that bib are adjusted
1398 accordingly.  If the rank is "del", the hold is cancelled.  If no rank
1399 is supplied, all of the holds on that bib have their priority adjusted
1400 as if the second form had been used.
1401
1402 In the second form, where a biblionumber is passed, the holds on that
1403 bib (that are not captured) are sorted in order of increasing priority,
1404 then have reserves.priority set so that the first non-captured hold
1405 has its priority set to 1, the second non-captured hold has its priority
1406 set to 2, and so forth.
1407
1408 In both cases, holds that have the lowestPriority flag on are have their
1409 priority adjusted to ensure that they remain at the end of the line.
1410
1411 Note that the ignoreSetLowestRank parameter is meant to be used only
1412 when _FixPriority calls itself.
1413
1414 =cut
1415
1416 sub _FixPriority {
1417     my ( $params ) = @_;
1418     my $reserve_id = $params->{reserve_id};
1419     my $rank = $params->{rank} // '';
1420     my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1421     my $biblionumber = $params->{biblionumber};
1422
1423     my $dbh = C4::Context->dbh;
1424
1425     my $hold;
1426     if ( $reserve_id ) {
1427         $hold = Koha::Holds->find( $reserve_id );
1428         return unless $hold;
1429     }
1430
1431     unless ( $biblionumber ) { # FIXME This is a very weird API
1432         $biblionumber = $hold->biblionumber;
1433     }
1434
1435     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1436         $hold->cancel;
1437     }
1438     elsif ( $rank eq "W" || $rank eq "0" ) {
1439
1440         # make sure priority for waiting or in-transit items is 0
1441         my $query = "
1442             UPDATE reserves
1443             SET    priority = 0
1444             WHERE reserve_id = ?
1445             AND found IN ('W', 'T')
1446         ";
1447         my $sth = $dbh->prepare($query);
1448         $sth->execute( $reserve_id );
1449     }
1450     my @priority;
1451
1452     # get whats left
1453     my $query = "
1454         SELECT reserve_id, borrowernumber, reservedate
1455         FROM   reserves
1456         WHERE  biblionumber   = ?
1457           AND  ((found <> 'W' AND found <> 'T') OR found IS NULL)
1458         ORDER BY priority ASC
1459     ";
1460     my $sth = $dbh->prepare($query);
1461     $sth->execute( $biblionumber );
1462     while ( my $line = $sth->fetchrow_hashref ) {
1463         push( @priority,     $line );
1464     }
1465
1466     # To find the matching index
1467     my $i;
1468     my $key = -1;    # to allow for 0 to be a valid result
1469     for ( $i = 0 ; $i < @priority ; $i++ ) {
1470         if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1471             $key = $i;    # save the index
1472             last;
1473         }
1474     }
1475
1476     # if index exists in array then move it to new position
1477     if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1478         my $new_rank = $rank -
1479           1;    # $new_rank is what you want the new index to be in the array
1480         my $moving_item = splice( @priority, $key, 1 );
1481         splice( @priority, $new_rank, 0, $moving_item );
1482     }
1483
1484     # now fix the priority on those that are left....
1485     $query = "
1486         UPDATE reserves
1487         SET    priority = ?
1488         WHERE  reserve_id = ?
1489     ";
1490     $sth = $dbh->prepare($query);
1491     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1492         $sth->execute(
1493             $j + 1,
1494             $priority[$j]->{'reserve_id'}
1495         );
1496     }
1497
1498     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1499     $sth->execute();
1500
1501     unless ( $ignoreSetLowestRank ) {
1502       while ( my $res = $sth->fetchrow_hashref() ) {
1503         _FixPriority({
1504             reserve_id => $res->{'reserve_id'},
1505             rank => '999999',
1506             ignoreSetLowestRank => 1
1507         });
1508       }
1509     }
1510 }
1511
1512 =head2 _Findgroupreserve
1513
1514   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1515
1516 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1517 first match found.  If neither, then we look for non-holds-queue based holds.
1518 Lookahead is the number of days to look in advance.
1519
1520 C<&_Findgroupreserve> returns :
1521 C<@results> is an array of references-to-hash whose keys are mostly
1522 fields from the reserves table of the Koha database, plus
1523 C<biblioitemnumber>.
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, $all_reserves ) = 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;
1807         foreach (@$all_reserves) {
1808             $_->{'borrowernumber'} == $borrowernumber or next;
1809             $_->{'biblionumber'}   == $biblionumber   or next;
1810
1811             $borr_res = $_;
1812             last;
1813         }
1814
1815         if ( $borr_res ) {
1816             # The item is reserved by the current patron
1817             ModReserveFill($borr_res);
1818         }
1819
1820         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1821             RevertWaitingStatus({ itemnumber => $itemnumber });
1822         }
1823         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1824             my $hold = Koha::Holds->find( $res->{reserve_id} );
1825             $hold->cancel;
1826         }
1827     }
1828 }
1829
1830 =head2 MergeHolds
1831
1832   MergeHolds($dbh,$to_biblio, $from_biblio);
1833
1834 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1835
1836 =cut
1837
1838 sub MergeHolds {
1839     my ( $dbh, $to_biblio, $from_biblio ) = @_;
1840     my $sth = $dbh->prepare(
1841         "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1842     );
1843     $sth->execute($from_biblio);
1844     if ( my $data = $sth->fetchrow_hashref() ) {
1845
1846         # holds exist on old record, if not we don't need to do anything
1847         $sth = $dbh->prepare(
1848             "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1849         $sth->execute( $to_biblio, $from_biblio );
1850
1851         # Reorder by date
1852         # don't reorder those already waiting
1853
1854         $sth = $dbh->prepare(
1855 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1856         );
1857         my $upd_sth = $dbh->prepare(
1858 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1859         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1860         );
1861         $sth->execute( $to_biblio, 'W', 'T' );
1862         my $priority = 1;
1863         while ( my $reserve = $sth->fetchrow_hashref() ) {
1864             $upd_sth->execute(
1865                 $priority,                    $to_biblio,
1866                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1867                 $reserve->{'itemnumber'}
1868             );
1869             $priority++;
1870         }
1871     }
1872 }
1873
1874 =head2 RevertWaitingStatus
1875
1876   RevertWaitingStatus({ itemnumber => $itemnumber });
1877
1878   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1879
1880   Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1881           item level hold, even if it was only a bibliolevel hold to
1882           begin with. This is because we can no longer know if a hold
1883           was item-level or bib-level after a hold has been set to
1884           waiting status.
1885
1886 =cut
1887
1888 sub RevertWaitingStatus {
1889     my ( $params ) = @_;
1890     my $itemnumber = $params->{'itemnumber'};
1891
1892     return unless ( $itemnumber );
1893
1894     my $dbh = C4::Context->dbh;
1895
1896     ## Get the waiting reserve we want to revert
1897     my $query = "
1898         SELECT * FROM reserves
1899         WHERE itemnumber = ?
1900         AND found IS NOT NULL
1901     ";
1902     my $sth = $dbh->prepare( $query );
1903     $sth->execute( $itemnumber );
1904     my $reserve = $sth->fetchrow_hashref();
1905
1906     ## Increment the priority of all other non-waiting
1907     ## reserves for this bib record
1908     $query = "
1909         UPDATE reserves
1910         SET
1911           priority = priority + 1
1912         WHERE
1913           biblionumber =  ?
1914         AND
1915           priority > 0
1916     ";
1917     $sth = $dbh->prepare( $query );
1918     $sth->execute( $reserve->{'biblionumber'} );
1919
1920     ## Fix up the currently waiting reserve
1921     $query = "
1922     UPDATE reserves
1923     SET
1924       priority = 1,
1925       found = NULL,
1926       waitingdate = NULL
1927     WHERE
1928       reserve_id = ?
1929     ";
1930     $sth = $dbh->prepare( $query );
1931     $sth->execute( $reserve->{'reserve_id'} );
1932     _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1933 }
1934
1935 =head2 ReserveSlip
1936
1937 ReserveSlip(
1938     {
1939         branchcode     => $branchcode,
1940         borrowernumber => $borrowernumber,
1941         biblionumber   => $biblionumber,
1942         [ itemnumber   => $itemnumber, ]
1943         [ barcode      => $barcode, ]
1944     }
1945   )
1946
1947 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1948
1949 The letter code will be HOLD_SLIP, and the following tables are
1950 available within the slip:
1951
1952     reserves
1953     branches
1954     borrowers
1955     biblio
1956     biblioitems
1957     items
1958
1959 =cut
1960
1961 sub ReserveSlip {
1962     my ($args) = @_;
1963     my $branchcode     = $args->{branchcode};
1964     my $borrowernumber = $args->{borrowernumber};
1965     my $biblionumber   = $args->{biblionumber};
1966     my $itemnumber     = $args->{itemnumber};
1967     my $barcode        = $args->{barcode};
1968
1969
1970     my $patron = Koha::Patrons->find($borrowernumber);
1971
1972     my $hold;
1973     if ($itemnumber || $barcode ) {
1974         $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
1975
1976         $hold = Koha::Holds->search(
1977             {
1978                 biblionumber   => $biblionumber,
1979                 borrowernumber => $borrowernumber,
1980                 itemnumber     => $itemnumber
1981             }
1982         )->next;
1983     }
1984     else {
1985         $hold = Koha::Holds->search(
1986             {
1987                 biblionumber   => $biblionumber,
1988                 borrowernumber => $borrowernumber
1989             }
1990         )->next;
1991     }
1992
1993     return unless $hold;
1994     my $reserve = $hold->unblessed;
1995
1996     return  C4::Letters::GetPreparedLetter (
1997         module => 'circulation',
1998         letter_code => 'HOLD_SLIP',
1999         branchcode => $branchcode,
2000         lang => $patron->lang,
2001         tables => {
2002             'reserves'    => $reserve,
2003             'branches'    => $reserve->{branchcode},
2004             'borrowers'   => $reserve->{borrowernumber},
2005             'biblio'      => $reserve->{biblionumber},
2006             'biblioitems' => $reserve->{biblionumber},
2007             'items'       => $reserve->{itemnumber},
2008         },
2009     );
2010 }
2011
2012 =head2 GetReservesControlBranch
2013
2014   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2015
2016   Return the branchcode to be used to determine which reserves
2017   policy applies to a transaction.
2018
2019   C<$item> is a hashref for an item. Only 'homebranch' is used.
2020
2021   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2022
2023 =cut
2024
2025 sub GetReservesControlBranch {
2026     my ( $item, $borrower ) = @_;
2027
2028     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2029
2030     my $branchcode =
2031         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2032       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2033       :                                              undef;
2034
2035     return $branchcode;
2036 }
2037
2038 =head2 CalculatePriority
2039
2040     my $p = CalculatePriority($biblionumber, $resdate);
2041
2042 Calculate priority for a new reserve on biblionumber, placing it at
2043 the end of the line of all holds whose start date falls before
2044 the current system time and that are neither on the hold shelf
2045 or in transit.
2046
2047 The reserve date parameter is optional; if it is supplied, the
2048 priority is based on the set of holds whose start date falls before
2049 the parameter value.
2050
2051 After calculation of this priority, it is recommended to call
2052 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2053 AddReserves.
2054
2055 =cut
2056
2057 sub CalculatePriority {
2058     my ( $biblionumber, $resdate ) = @_;
2059
2060     my $sql = q{
2061         SELECT COUNT(*) FROM reserves
2062         WHERE biblionumber = ?
2063         AND   priority > 0
2064         AND   (found IS NULL OR found = '')
2065     };
2066     #skip found==W or found==T (waiting or transit holds)
2067     if( $resdate ) {
2068         $sql.= ' AND ( reservedate <= ? )';
2069     }
2070     else {
2071         $sql.= ' AND ( reservedate < NOW() )';
2072     }
2073     my $dbh = C4::Context->dbh();
2074     my @row = $dbh->selectrow_array(
2075         $sql,
2076         undef,
2077         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2078     );
2079
2080     return @row ? $row[0]+1 : 1;
2081 }
2082
2083 =head2 IsItemOnHoldAndFound
2084
2085     my $bool = IsItemFoundHold( $itemnumber );
2086
2087     Returns true if the item is currently on hold
2088     and that hold has a non-null found status ( W, T, etc. )
2089
2090 =cut
2091
2092 sub IsItemOnHoldAndFound {
2093     my ($itemnumber) = @_;
2094
2095     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2096
2097     my $found = $rs->count(
2098         {
2099             itemnumber => $itemnumber,
2100             found      => { '!=' => undef }
2101         }
2102     );
2103
2104     return $found;
2105 }
2106
2107 =head2 GetMaxPatronHoldsForRecord
2108
2109 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2110
2111 For multiple holds on a given record for a given patron, the max
2112 number of record level holds that a patron can be placed is the highest
2113 value of the holds_per_record rule for each item if the record for that
2114 patron. This subroutine finds and returns the highest holds_per_record
2115 rule value for a given patron id and record id.
2116
2117 =cut
2118
2119 sub GetMaxPatronHoldsForRecord {
2120     my ( $borrowernumber, $biblionumber ) = @_;
2121
2122     my $patron = Koha::Patrons->find($borrowernumber);
2123     my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2124
2125     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2126
2127     my $categorycode = $patron->categorycode;
2128     my $branchcode;
2129     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2130
2131     my $max = 0;
2132     foreach my $item (@items) {
2133         my $itemtype = $item->effective_itemtype();
2134
2135         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2136
2137         my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2138         my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2139         $max = $holds_per_record if $holds_per_record > $max;
2140     }
2141
2142     return $max;
2143 }
2144
2145 =head2 GetHoldRule
2146
2147 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2148
2149 Returns the matching hold related issuingrule fields for a given
2150 patron category, itemtype, and library.
2151
2152 =cut
2153
2154 sub GetHoldRule {
2155     my ( $categorycode, $itemtype, $branchcode ) = @_;
2156
2157     my $dbh = C4::Context->dbh;
2158
2159     my $sth = $dbh->prepare(
2160         q{
2161          SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2162            FROM issuingrules
2163           WHERE (categorycode in (?,'*') )
2164             AND (itemtype IN (?,'*'))
2165             AND (branchcode IN (?,'*'))
2166        ORDER BY categorycode DESC,
2167                 itemtype     DESC,
2168                 branchcode   DESC
2169         }
2170     );
2171
2172     $sth->execute( $categorycode, $itemtype, $branchcode );
2173
2174     return $sth->fetchrow_hashref();
2175 }
2176
2177 =head1 AUTHOR
2178
2179 Koha Development Team <http://koha-community.org/>
2180
2181 =cut
2182
2183 1;