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