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