Bug 22284: Add "patron's hold group" as new hold_fulfillment_policy option
[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 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 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 eq 'CART' && $item->permanent_location ne 'CART'  ) && $newstatus ) {
1071       CartToShelf( $itemnumber );
1072     }
1073 }
1074
1075 =head2 ModReserveAffect
1076
1077   &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1078
1079 This function affect an item and a status for a given reserve, either fetched directly
1080 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1081 is given, only first reserve returned is affected, which is ok for anything but
1082 multi-item holds.
1083
1084 if $transferToDo is not set, then the status is set to "Waiting" as well.
1085 otherwise, a transfer is on the way, and the end of the transfer will
1086 take care of the waiting status
1087
1088 =cut
1089
1090 sub ModReserveAffect {
1091     my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1092     my $dbh = C4::Context->dbh;
1093
1094     # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1095     # attached to $itemnumber
1096     my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1097     $sth->execute($itemnumber);
1098     my ($biblionumber) = $sth->fetchrow;
1099
1100     # get request - need to find out if item is already
1101     # waiting in order to not send duplicate hold filled notifications
1102
1103     my $hold;
1104     # Find hold by id if we have it
1105     $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1106     # Find item level hold for this item if there is one
1107     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1108     # Find record level hold if there is no item level hold
1109     $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1110
1111     return unless $hold;
1112
1113     my $already_on_shelf = $hold->found && $hold->found eq 'W';
1114
1115     $hold->itemnumber($itemnumber);
1116     $hold->set_waiting($transferToDo);
1117
1118     _koha_notify_reserve( $hold->reserve_id )
1119       if ( !$transferToDo && !$already_on_shelf );
1120
1121     _FixPriority( { biblionumber => $biblionumber } );
1122     my $item = Koha::Items->find($itemnumber);
1123     if ( ( $item->location eq 'CART' && $item->permanent_location ne 'CART'  ) ) {
1124       CartToShelf( $itemnumber );
1125     }
1126
1127     return;
1128 }
1129
1130 =head2 ModReserveCancelAll
1131
1132   ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1133
1134 function to cancel reserv,check other reserves, and transfer document if it's necessary
1135
1136 =cut
1137
1138 sub ModReserveCancelAll {
1139     my $messages;
1140     my $nextreservinfo;
1141     my ( $itemnumber, $borrowernumber ) = @_;
1142
1143     #step 1 : cancel the reservation
1144     my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1145     return unless $holds->count;
1146     $holds->next->cancel;
1147
1148     #step 2 launch the subroutine of the others reserves
1149     ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1150
1151     return ( $messages, $nextreservinfo );
1152 }
1153
1154 =head2 ModReserveMinusPriority
1155
1156   &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1157
1158 Reduce the values of queued list
1159
1160 =cut
1161
1162 sub ModReserveMinusPriority {
1163     my ( $itemnumber, $reserve_id ) = @_;
1164
1165     #first step update the value of the first person on reserv
1166     my $dbh   = C4::Context->dbh;
1167     my $query = "
1168         UPDATE reserves
1169         SET    priority = 0 , itemnumber = ?
1170         WHERE  reserve_id = ?
1171     ";
1172     my $sth_upd = $dbh->prepare($query);
1173     $sth_upd->execute( $itemnumber, $reserve_id );
1174     # second step update all others reserves
1175     _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1176 }
1177
1178 =head2 IsAvailableForItemLevelRequest
1179
1180   my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1181
1182 Checks whether a given item record is available for an
1183 item-level hold request.  An item is available if
1184
1185 * it is not lost AND
1186 * it is not damaged AND
1187 * it is not withdrawn AND
1188 * a waiting or in transit reserve is placed on
1189 * does not have a not for loan value > 0
1190
1191 Need to check the issuingrules onshelfholds column,
1192 if this is set items on the shelf can be placed on hold
1193
1194 Note that IsAvailableForItemLevelRequest() does not
1195 check if the staff operator is authorized to place
1196 a request on the item - in particular,
1197 this routine does not check IndependentBranches
1198 and canreservefromotherbranches.
1199
1200 =cut
1201
1202 sub IsAvailableForItemLevelRequest {
1203     my ( $item, $patron, $pickup_branchcode ) = @_;
1204
1205     my $dbh = C4::Context->dbh;
1206     # must check the notforloan setting of the itemtype
1207     # FIXME - a lot of places in the code do this
1208     #         or something similar - need to be
1209     #         consolidated
1210     my $itemtype = $item->effective_itemtype;
1211     my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1212
1213     return 0 if
1214         $notforloan_per_itemtype ||
1215         $item->itemlost        ||
1216         $item->notforloan > 0  ||
1217         $item->withdrawn        ||
1218         ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1219
1220     my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1221
1222     if ($pickup_branchcode) {
1223         my $destination = Koha::Libraries->find($pickup_branchcode);
1224         return 0 unless $destination;
1225         return 0 unless $destination->pickup_location;
1226         return 0 unless $item->can_be_transferred( { to => $destination } );
1227         my $reserves_control_branch =
1228             GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1229         my $branchitemrule =
1230             C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1231         my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1232         return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1233     }
1234
1235     if ( $on_shelf_holds == 1 ) {
1236         return 1;
1237     } elsif ( $on_shelf_holds == 2 ) {
1238         my @items =
1239           Koha::Items->search( { biblionumber => $item->biblionumber } );
1240
1241         my $any_available = 0;
1242
1243         foreach my $i (@items) {
1244             my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1245             my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1246             my $item_library = Koha::Libraries->find( {branchcode => $i->homebranch} );
1247
1248
1249             $any_available = 1
1250               unless $i->itemlost
1251               || $i->notforloan > 0
1252               || $i->withdrawn
1253               || $i->onloan
1254               || IsItemOnHoldAndFound( $i->id )
1255               || ( $i->damaged
1256                 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1257               || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1258               || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch
1259               || $branchitemrule->{holdallowed} == 3 && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} );
1260         }
1261
1262         return $any_available ? 0 : 1;
1263     } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1264         return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1265     }
1266 }
1267
1268 sub _get_itype {
1269     my $item = shift;
1270
1271     my $itype;
1272     if (C4::Context->preference('item-level_itypes')) {
1273         # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1274         # When GetItem is fixed, we can remove this
1275         $itype = $item->{itype};
1276     }
1277     else {
1278         # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1279         # So if we already have a biblioitems join when calling this function,
1280         # we don't need to access the database again
1281         $itype = $item->{itemtype};
1282     }
1283     unless ($itype) {
1284         my $dbh = C4::Context->dbh;
1285         my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1286         my $sth = $dbh->prepare($query);
1287         $sth->execute($item->{biblioitemnumber});
1288         if (my $data = $sth->fetchrow_hashref()){
1289             $itype = $data->{itemtype};
1290         }
1291     }
1292     return $itype;
1293 }
1294
1295 =head2 AlterPriority
1296
1297   AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1298
1299 This function changes a reserve's priority up, down, to the top, or to the bottom.
1300 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1301
1302 =cut
1303
1304 sub AlterPriority {
1305     my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1306
1307     my $hold = Koha::Holds->find( $reserve_id );
1308     return unless $hold;
1309
1310     if ( $hold->cancellationdate ) {
1311         warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1312         return;
1313     }
1314
1315     if ( $where eq 'up' ) {
1316       return unless $prev_priority;
1317       _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1318     } elsif ( $where eq 'down' ) {
1319       return unless $next_priority;
1320       _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1321     } elsif ( $where eq 'top' ) {
1322       _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1323     } elsif ( $where eq 'bottom' ) {
1324       _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1325     }
1326
1327     # FIXME Should return the new priority
1328 }
1329
1330 =head2 ToggleLowestPriority
1331
1332   ToggleLowestPriority( $borrowernumber, $biblionumber );
1333
1334 This function sets the lowestPriority field to true if is false, and false if it is true.
1335
1336 =cut
1337
1338 sub ToggleLowestPriority {
1339     my ( $reserve_id ) = @_;
1340
1341     my $dbh = C4::Context->dbh;
1342
1343     my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1344     $sth->execute( $reserve_id );
1345
1346     _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1347 }
1348
1349 =head2 ToggleSuspend
1350
1351   ToggleSuspend( $reserve_id );
1352
1353 This function sets the suspend field to true if is false, and false if it is true.
1354 If the reserve is currently suspended with a suspend_until date, that date will
1355 be cleared when it is unsuspended.
1356
1357 =cut
1358
1359 sub ToggleSuspend {
1360     my ( $reserve_id, $suspend_until ) = @_;
1361
1362     $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1363
1364     my $hold = Koha::Holds->find( $reserve_id );
1365
1366     if ( $hold->is_suspended ) {
1367         $hold->resume()
1368     } else {
1369         $hold->suspend_hold( $suspend_until );
1370     }
1371 }
1372
1373 =head2 SuspendAll
1374
1375   SuspendAll(
1376       borrowernumber   => $borrowernumber,
1377       [ biblionumber   => $biblionumber, ]
1378       [ suspend_until  => $suspend_until, ]
1379       [ suspend        => $suspend ]
1380   );
1381
1382   This function accepts a set of hash keys as its parameters.
1383   It requires either borrowernumber or biblionumber, or both.
1384
1385   suspend_until is wholly optional.
1386
1387 =cut
1388
1389 sub SuspendAll {
1390     my %params = @_;
1391
1392     my $borrowernumber = $params{'borrowernumber'} || undef;
1393     my $biblionumber   = $params{'biblionumber'}   || undef;
1394     my $suspend_until  = $params{'suspend_until'}  || undef;
1395     my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1396
1397     $suspend_until = eval { dt_from_string($suspend_until) }
1398       if ( defined($suspend_until) );
1399
1400     return unless ( $borrowernumber || $biblionumber );
1401
1402     my $params;
1403     $params->{found}          = undef;
1404     $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1405     $params->{biblionumber}   = $biblionumber if $biblionumber;
1406
1407     my @holds = Koha::Holds->search($params);
1408
1409     if ($suspend) {
1410         map { $_->suspend_hold($suspend_until) } @holds;
1411     }
1412     else {
1413         map { $_->resume() } @holds;
1414     }
1415 }
1416
1417
1418 =head2 _FixPriority
1419
1420   _FixPriority({
1421     reserve_id => $reserve_id,
1422     [rank => $rank,]
1423     [ignoreSetLowestRank => $ignoreSetLowestRank]
1424   });
1425
1426   or
1427
1428   _FixPriority({ biblionumber => $biblionumber});
1429
1430 This routine adjusts the priority of a hold request and holds
1431 on the same bib.
1432
1433 In the first form, where a reserve_id is passed, the priority of the
1434 hold is set to supplied rank, and other holds for that bib are adjusted
1435 accordingly.  If the rank is "del", the hold is cancelled.  If no rank
1436 is supplied, all of the holds on that bib have their priority adjusted
1437 as if the second form had been used.
1438
1439 In the second form, where a biblionumber is passed, the holds on that
1440 bib (that are not captured) are sorted in order of increasing priority,
1441 then have reserves.priority set so that the first non-captured hold
1442 has its priority set to 1, the second non-captured hold has its priority
1443 set to 2, and so forth.
1444
1445 In both cases, holds that have the lowestPriority flag on are have their
1446 priority adjusted to ensure that they remain at the end of the line.
1447
1448 Note that the ignoreSetLowestRank parameter is meant to be used only
1449 when _FixPriority calls itself.
1450
1451 =cut
1452
1453 sub _FixPriority {
1454     my ( $params ) = @_;
1455     my $reserve_id = $params->{reserve_id};
1456     my $rank = $params->{rank} // '';
1457     my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1458     my $biblionumber = $params->{biblionumber};
1459
1460     my $dbh = C4::Context->dbh;
1461
1462     my $hold;
1463     if ( $reserve_id ) {
1464         $hold = Koha::Holds->find( $reserve_id );
1465         return unless $hold;
1466     }
1467
1468     unless ( $biblionumber ) { # FIXME This is a very weird API
1469         $biblionumber = $hold->biblionumber;
1470     }
1471
1472     if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1473         $hold->cancel;
1474     }
1475     elsif ( $rank eq "W" || $rank eq "0" ) {
1476
1477         # make sure priority for waiting or in-transit items is 0
1478         my $query = "
1479             UPDATE reserves
1480             SET    priority = 0
1481             WHERE reserve_id = ?
1482             AND found IN ('W', 'T')
1483         ";
1484         my $sth = $dbh->prepare($query);
1485         $sth->execute( $reserve_id );
1486     }
1487     my @priority;
1488
1489     # get whats left
1490     my $query = "
1491         SELECT reserve_id, borrowernumber, reservedate
1492         FROM   reserves
1493         WHERE  biblionumber   = ?
1494           AND  ((found <> 'W' AND found <> 'T') OR found IS NULL)
1495         ORDER BY priority ASC
1496     ";
1497     my $sth = $dbh->prepare($query);
1498     $sth->execute( $biblionumber );
1499     while ( my $line = $sth->fetchrow_hashref ) {
1500         push( @priority,     $line );
1501     }
1502
1503     # To find the matching index
1504     my $i;
1505     my $key = -1;    # to allow for 0 to be a valid result
1506     for ( $i = 0 ; $i < @priority ; $i++ ) {
1507         if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1508             $key = $i;    # save the index
1509             last;
1510         }
1511     }
1512
1513     # if index exists in array then move it to new position
1514     if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1515         my $new_rank = $rank -
1516           1;    # $new_rank is what you want the new index to be in the array
1517         my $moving_item = splice( @priority, $key, 1 );
1518         splice( @priority, $new_rank, 0, $moving_item );
1519     }
1520
1521     # now fix the priority on those that are left....
1522     $query = "
1523         UPDATE reserves
1524         SET    priority = ?
1525         WHERE  reserve_id = ?
1526     ";
1527     $sth = $dbh->prepare($query);
1528     for ( my $j = 0 ; $j < @priority ; $j++ ) {
1529         $sth->execute(
1530             $j + 1,
1531             $priority[$j]->{'reserve_id'}
1532         );
1533     }
1534
1535     $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1536     $sth->execute();
1537
1538     unless ( $ignoreSetLowestRank ) {
1539       while ( my $res = $sth->fetchrow_hashref() ) {
1540         _FixPriority({
1541             reserve_id => $res->{'reserve_id'},
1542             rank => '999999',
1543             ignoreSetLowestRank => 1
1544         });
1545       }
1546     }
1547 }
1548
1549 =head2 _Findgroupreserve
1550
1551   @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1552
1553 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1554 first match found.  If neither, then we look for non-holds-queue based holds.
1555 Lookahead is the number of days to look in advance.
1556
1557 C<&_Findgroupreserve> returns :
1558 C<@results> is an array of references-to-hash whose keys are mostly
1559 fields from the reserves table of the Koha database, plus
1560 C<biblioitemnumber>.
1561
1562 This routine with either return:
1563 1 - Item specific holds from the holds queue
1564 2 - Title level holds from the holds queue
1565 3 - All holds for this biblionumber
1566
1567 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1568
1569 =cut
1570
1571 sub _Findgroupreserve {
1572     my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1573     my $dbh   = C4::Context->dbh;
1574
1575     # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1576     # check for exact targeted match
1577     my $item_level_target_query = qq{
1578         SELECT reserves.biblionumber        AS biblionumber,
1579                reserves.borrowernumber      AS borrowernumber,
1580                reserves.reservedate         AS reservedate,
1581                reserves.branchcode          AS branchcode,
1582                reserves.cancellationdate    AS cancellationdate,
1583                reserves.found               AS found,
1584                reserves.reservenotes        AS reservenotes,
1585                reserves.priority            AS priority,
1586                reserves.timestamp           AS timestamp,
1587                biblioitems.biblioitemnumber AS biblioitemnumber,
1588                reserves.itemnumber          AS itemnumber,
1589                reserves.reserve_id          AS reserve_id,
1590                reserves.itemtype            AS itemtype
1591         FROM reserves
1592         JOIN biblioitems USING (biblionumber)
1593         JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1594         WHERE found IS NULL
1595         AND priority > 0
1596         AND item_level_request = 1
1597         AND itemnumber = ?
1598         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1599         AND suspend = 0
1600         ORDER BY priority
1601     };
1602     my $sth = $dbh->prepare($item_level_target_query);
1603     $sth->execute($itemnumber, $lookahead||0);
1604     my @results;
1605     if ( my $data = $sth->fetchrow_hashref ) {
1606         push( @results, $data )
1607           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1608     }
1609     return @results if @results;
1610
1611     # check for title-level targeted match
1612     my $title_level_target_query = qq{
1613         SELECT reserves.biblionumber        AS biblionumber,
1614                reserves.borrowernumber      AS borrowernumber,
1615                reserves.reservedate         AS reservedate,
1616                reserves.branchcode          AS branchcode,
1617                reserves.cancellationdate    AS cancellationdate,
1618                reserves.found               AS found,
1619                reserves.reservenotes        AS reservenotes,
1620                reserves.priority            AS priority,
1621                reserves.timestamp           AS timestamp,
1622                biblioitems.biblioitemnumber AS biblioitemnumber,
1623                reserves.itemnumber          AS itemnumber,
1624                reserves.reserve_id          AS reserve_id,
1625                reserves.itemtype            AS itemtype
1626         FROM reserves
1627         JOIN biblioitems USING (biblionumber)
1628         JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1629         WHERE found IS NULL
1630         AND priority > 0
1631         AND item_level_request = 0
1632         AND hold_fill_targets.itemnumber = ?
1633         AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1634         AND suspend = 0
1635         ORDER BY priority
1636     };
1637     $sth = $dbh->prepare($title_level_target_query);
1638     $sth->execute($itemnumber, $lookahead||0);
1639     @results = ();
1640     if ( my $data = $sth->fetchrow_hashref ) {
1641         push( @results, $data )
1642           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1643     }
1644     return @results if @results;
1645
1646     my $query = qq{
1647         SELECT reserves.biblionumber               AS biblionumber,
1648                reserves.borrowernumber             AS borrowernumber,
1649                reserves.reservedate                AS reservedate,
1650                reserves.waitingdate                AS waitingdate,
1651                reserves.branchcode                 AS branchcode,
1652                reserves.cancellationdate           AS cancellationdate,
1653                reserves.found                      AS found,
1654                reserves.reservenotes               AS reservenotes,
1655                reserves.priority                   AS priority,
1656                reserves.timestamp                  AS timestamp,
1657                reserves.itemnumber                 AS itemnumber,
1658                reserves.reserve_id                 AS reserve_id,
1659                reserves.itemtype                   AS itemtype
1660         FROM reserves
1661         WHERE reserves.biblionumber = ?
1662           AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1663           AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1664           AND suspend = 0
1665           ORDER BY priority
1666     };
1667     $sth = $dbh->prepare($query);
1668     $sth->execute( $biblio, $itemnumber, $lookahead||0);
1669     @results = ();
1670     while ( my $data = $sth->fetchrow_hashref ) {
1671         push( @results, $data )
1672           unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1673     }
1674     return @results;
1675 }
1676
1677 =head2 _koha_notify_reserve
1678
1679   _koha_notify_reserve( $hold->reserve_id );
1680
1681 Sends a notification to the patron that their hold has been filled (through
1682 ModReserveAffect, _not_ ModReserveFill)
1683
1684 The letter code for this notice may be found using the following query:
1685
1686     select distinct letter_code
1687     from message_transports
1688     inner join message_attributes using (message_attribute_id)
1689     where message_name = 'Hold_Filled'
1690
1691 This will probably sipmly be 'HOLD', but because it is defined in the database,
1692 it is subject to addition or change.
1693
1694 The following tables are availalbe witin the notice:
1695
1696     branches
1697     borrowers
1698     biblio
1699     biblioitems
1700     reserves
1701     items
1702
1703 =cut
1704
1705 sub _koha_notify_reserve {
1706     my $reserve_id = shift;
1707     my $hold = Koha::Holds->find($reserve_id);
1708     my $borrowernumber = $hold->borrowernumber;
1709
1710     my $patron = Koha::Patrons->find( $borrowernumber );
1711
1712     # Try to get the borrower's email address
1713     my $to_address = $patron->notice_email_address;
1714
1715     my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1716             borrowernumber => $borrowernumber,
1717             message_name => 'Hold_Filled'
1718     } );
1719
1720     my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1721
1722     my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1723
1724     my %letter_params = (
1725         module => 'reserves',
1726         branchcode => $hold->branchcode,
1727         lang => $patron->lang,
1728         tables => {
1729             'branches'       => $library,
1730             'borrowers'      => $patron->unblessed,
1731             'biblio'         => $hold->biblionumber,
1732             'biblioitems'    => $hold->biblionumber,
1733             'reserves'       => $hold->unblessed,
1734             'items'          => $hold->itemnumber,
1735         },
1736     );
1737
1738     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.
1739     my $send_notification = sub {
1740         my ( $mtt, $letter_code ) = (@_);
1741         return unless defined $letter_code;
1742         $letter_params{letter_code} = $letter_code;
1743         $letter_params{message_transport_type} = $mtt;
1744         my $letter =  C4::Letters::GetPreparedLetter ( %letter_params );
1745         unless ($letter) {
1746             warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1747             return;
1748         }
1749
1750         C4::Letters::EnqueueLetter( {
1751             letter => $letter,
1752             borrowernumber => $borrowernumber,
1753             from_address => $admin_email_address,
1754             message_transport_type => $mtt,
1755         } );
1756     };
1757
1758     while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1759         next if (
1760                ( $mtt eq 'email' and not $to_address ) # No email address
1761             or ( $mtt eq 'sms'   and not $patron->smsalertnumber ) # No SMS number
1762             or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1763         );
1764
1765         &$send_notification($mtt, $letter_code);
1766         $notification_sent++;
1767     }
1768     #Making sure that a print notification is sent if no other transport types can be utilized.
1769     if (! $notification_sent) {
1770         &$send_notification('print', 'HOLD');
1771     }
1772
1773 }
1774
1775 =head2 _ShiftPriorityByDateAndPriority
1776
1777   $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1778
1779 This increments the priority of all reserves after the one
1780 with either the lowest date after C<$reservedate>
1781 or the lowest priority after C<$priority>.
1782
1783 It effectively makes room for a new reserve to be inserted with a certain
1784 priority, which is returned.
1785
1786 This is most useful when the reservedate can be set by the user.  It allows
1787 the new reserve to be placed before other reserves that have a later
1788 reservedate.  Since priority also is set by the form in reserves/request.pl
1789 the sub accounts for that too.
1790
1791 =cut
1792
1793 sub _ShiftPriorityByDateAndPriority {
1794     my ( $biblio, $resdate, $new_priority ) = @_;
1795
1796     my $dbh = C4::Context->dbh;
1797     my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1798     my $sth = $dbh->prepare( $query );
1799     $sth->execute( $biblio, $resdate, $new_priority );
1800     my $min_priority = $sth->fetchrow;
1801     # if no such matches are found, $new_priority remains as original value
1802     $new_priority = $min_priority if ( $min_priority );
1803
1804     # Shift the priority up by one; works in conjunction with the next SQL statement
1805     $query = "UPDATE reserves
1806               SET priority = priority+1
1807               WHERE biblionumber = ?
1808               AND borrowernumber = ?
1809               AND reservedate = ?
1810               AND found IS NULL";
1811     my $sth_update = $dbh->prepare( $query );
1812
1813     # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1814     $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1815     $sth = $dbh->prepare( $query );
1816     $sth->execute( $new_priority, $biblio );
1817     while ( my $row = $sth->fetchrow_hashref ) {
1818         $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1819     }
1820
1821     return $new_priority;  # so the caller knows what priority they wind up receiving
1822 }
1823
1824 =head2 MoveReserve
1825
1826   MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1827
1828 Use when checking out an item to handle reserves
1829 If $cancelreserve boolean is set to true, it will remove existing reserve
1830
1831 =cut
1832
1833 sub MoveReserve {
1834     my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1835
1836     my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1837     my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1838     return unless $res;
1839
1840     my $biblionumber     =  $res->{biblionumber};
1841
1842     if ($res->{borrowernumber} == $borrowernumber) {
1843         ModReserveFill($res);
1844     }
1845     else {
1846         # warn "Reserved";
1847         # The item is reserved by someone else.
1848         # Find this item in the reserves
1849
1850         my $borr_res  = Koha::Holds->search({
1851             borrowernumber => $borrowernumber,
1852             biblionumber   => $biblionumber,
1853         },{
1854             order_by       => 'priority'
1855         })->next();
1856
1857         if ( $borr_res ) {
1858             # The item is reserved by the current patron
1859             ModReserveFill($borr_res->unblessed);
1860         }
1861
1862         if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1863             RevertWaitingStatus({ itemnumber => $itemnumber });
1864         }
1865         elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1866             my $hold = Koha::Holds->find( $res->{reserve_id} );
1867             $hold->cancel;
1868         }
1869     }
1870 }
1871
1872 =head2 MergeHolds
1873
1874   MergeHolds($dbh,$to_biblio, $from_biblio);
1875
1876 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1877
1878 =cut
1879
1880 sub MergeHolds {
1881     my ( $dbh, $to_biblio, $from_biblio ) = @_;
1882     my $sth = $dbh->prepare(
1883         "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1884     );
1885     $sth->execute($from_biblio);
1886     if ( my $data = $sth->fetchrow_hashref() ) {
1887
1888         # holds exist on old record, if not we don't need to do anything
1889         $sth = $dbh->prepare(
1890             "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1891         $sth->execute( $to_biblio, $from_biblio );
1892
1893         # Reorder by date
1894         # don't reorder those already waiting
1895
1896         $sth = $dbh->prepare(
1897 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1898         );
1899         my $upd_sth = $dbh->prepare(
1900 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1901         AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1902         );
1903         $sth->execute( $to_biblio, 'W', 'T' );
1904         my $priority = 1;
1905         while ( my $reserve = $sth->fetchrow_hashref() ) {
1906             $upd_sth->execute(
1907                 $priority,                    $to_biblio,
1908                 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1909                 $reserve->{'itemnumber'}
1910             );
1911             $priority++;
1912         }
1913     }
1914 }
1915
1916 =head2 RevertWaitingStatus
1917
1918   RevertWaitingStatus({ itemnumber => $itemnumber });
1919
1920   Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1921
1922   Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1923           item level hold, even if it was only a bibliolevel hold to
1924           begin with. This is because we can no longer know if a hold
1925           was item-level or bib-level after a hold has been set to
1926           waiting status.
1927
1928 =cut
1929
1930 sub RevertWaitingStatus {
1931     my ( $params ) = @_;
1932     my $itemnumber = $params->{'itemnumber'};
1933
1934     return unless ( $itemnumber );
1935
1936     my $dbh = C4::Context->dbh;
1937
1938     ## Get the waiting reserve we want to revert
1939     my $query = "
1940         SELECT * FROM reserves
1941         WHERE itemnumber = ?
1942         AND found IS NOT NULL
1943     ";
1944     my $sth = $dbh->prepare( $query );
1945     $sth->execute( $itemnumber );
1946     my $reserve = $sth->fetchrow_hashref();
1947
1948     my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1949
1950     ## Increment the priority of all other non-waiting
1951     ## reserves for this bib record
1952     $query = "
1953         UPDATE reserves
1954         SET
1955           priority = priority + 1
1956         WHERE
1957           biblionumber =  ?
1958         AND
1959           priority > 0
1960     ";
1961     $sth = $dbh->prepare( $query );
1962     $sth->execute( $reserve->{'biblionumber'} );
1963
1964     ## Fix up the currently waiting reserve
1965     $query = "
1966     UPDATE reserves
1967     SET
1968       priority = 1,
1969       found = NULL,
1970       waitingdate = NULL
1971     WHERE
1972       reserve_id = ?
1973     ";
1974     $sth = $dbh->prepare( $query );
1975     $sth->execute( $reserve->{'reserve_id'} );
1976
1977     unless ( $hold->item_level_hold ) {
1978         $hold->itemnumber(undef)->store;
1979     }
1980
1981     _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1982 }
1983
1984 =head2 ReserveSlip
1985
1986 ReserveSlip(
1987     {
1988         branchcode     => $branchcode,
1989         borrowernumber => $borrowernumber,
1990         biblionumber   => $biblionumber,
1991         [ itemnumber   => $itemnumber, ]
1992         [ barcode      => $barcode, ]
1993     }
1994   )
1995
1996 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1997
1998 The letter code will be HOLD_SLIP, and the following tables are
1999 available within the slip:
2000
2001     reserves
2002     branches
2003     borrowers
2004     biblio
2005     biblioitems
2006     items
2007
2008 =cut
2009
2010 sub ReserveSlip {
2011     my ($args) = @_;
2012     my $branchcode     = $args->{branchcode};
2013     my $borrowernumber = $args->{borrowernumber};
2014     my $biblionumber   = $args->{biblionumber};
2015     my $itemnumber     = $args->{itemnumber};
2016     my $barcode        = $args->{barcode};
2017
2018
2019     my $patron = Koha::Patrons->find($borrowernumber);
2020
2021     my $hold;
2022     if ($itemnumber || $barcode ) {
2023         $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2024
2025         $hold = Koha::Holds->search(
2026             {
2027                 biblionumber   => $biblionumber,
2028                 borrowernumber => $borrowernumber,
2029                 itemnumber     => $itemnumber
2030             }
2031         )->next;
2032     }
2033     else {
2034         $hold = Koha::Holds->search(
2035             {
2036                 biblionumber   => $biblionumber,
2037                 borrowernumber => $borrowernumber
2038             }
2039         )->next;
2040     }
2041
2042     return unless $hold;
2043     my $reserve = $hold->unblessed;
2044
2045     return  C4::Letters::GetPreparedLetter (
2046         module => 'circulation',
2047         letter_code => 'HOLD_SLIP',
2048         branchcode => $branchcode,
2049         lang => $patron->lang,
2050         tables => {
2051             'reserves'    => $reserve,
2052             'branches'    => $reserve->{branchcode},
2053             'borrowers'   => $reserve->{borrowernumber},
2054             'biblio'      => $reserve->{biblionumber},
2055             'biblioitems' => $reserve->{biblionumber},
2056             'items'       => $reserve->{itemnumber},
2057         },
2058     );
2059 }
2060
2061 =head2 GetReservesControlBranch
2062
2063   my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2064
2065   Return the branchcode to be used to determine which reserves
2066   policy applies to a transaction.
2067
2068   C<$item> is a hashref for an item. Only 'homebranch' is used.
2069
2070   C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2071
2072 =cut
2073
2074 sub GetReservesControlBranch {
2075     my ( $item, $borrower ) = @_;
2076
2077     my $reserves_control = C4::Context->preference('ReservesControlBranch');
2078
2079     my $branchcode =
2080         ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2081       : ( $reserves_control eq 'PatronLibrary' )   ? $borrower->{'branchcode'}
2082       :                                              undef;
2083
2084     return $branchcode;
2085 }
2086
2087 =head2 CalculatePriority
2088
2089     my $p = CalculatePriority($biblionumber, $resdate);
2090
2091 Calculate priority for a new reserve on biblionumber, placing it at
2092 the end of the line of all holds whose start date falls before
2093 the current system time and that are neither on the hold shelf
2094 or in transit.
2095
2096 The reserve date parameter is optional; if it is supplied, the
2097 priority is based on the set of holds whose start date falls before
2098 the parameter value.
2099
2100 After calculation of this priority, it is recommended to call
2101 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2102 AddReserves.
2103
2104 =cut
2105
2106 sub CalculatePriority {
2107     my ( $biblionumber, $resdate ) = @_;
2108
2109     my $sql = q{
2110         SELECT COUNT(*) FROM reserves
2111         WHERE biblionumber = ?
2112         AND   priority > 0
2113         AND   (found IS NULL OR found = '')
2114     };
2115     #skip found==W or found==T (waiting or transit holds)
2116     if( $resdate ) {
2117         $sql.= ' AND ( reservedate <= ? )';
2118     }
2119     else {
2120         $sql.= ' AND ( reservedate < NOW() )';
2121     }
2122     my $dbh = C4::Context->dbh();
2123     my @row = $dbh->selectrow_array(
2124         $sql,
2125         undef,
2126         $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2127     );
2128
2129     return @row ? $row[0]+1 : 1;
2130 }
2131
2132 =head2 IsItemOnHoldAndFound
2133
2134     my $bool = IsItemFoundHold( $itemnumber );
2135
2136     Returns true if the item is currently on hold
2137     and that hold has a non-null found status ( W, T, etc. )
2138
2139 =cut
2140
2141 sub IsItemOnHoldAndFound {
2142     my ($itemnumber) = @_;
2143
2144     my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2145
2146     my $found = $rs->count(
2147         {
2148             itemnumber => $itemnumber,
2149             found      => { '!=' => undef }
2150         }
2151     );
2152
2153     return $found;
2154 }
2155
2156 =head2 GetMaxPatronHoldsForRecord
2157
2158 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2159
2160 For multiple holds on a given record for a given patron, the max
2161 number of record level holds that a patron can be placed is the highest
2162 value of the holds_per_record rule for each item if the record for that
2163 patron. This subroutine finds and returns the highest holds_per_record
2164 rule value for a given patron id and record id.
2165
2166 =cut
2167
2168 sub GetMaxPatronHoldsForRecord {
2169     my ( $borrowernumber, $biblionumber ) = @_;
2170
2171     my $patron = Koha::Patrons->find($borrowernumber);
2172     my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2173
2174     my $controlbranch = C4::Context->preference('ReservesControlBranch');
2175
2176     my $categorycode = $patron->categorycode;
2177     my $branchcode;
2178     $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2179
2180     my $max = 0;
2181     foreach my $item (@items) {
2182         my $itemtype = $item->effective_itemtype();
2183
2184         $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2185
2186         my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2187         my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2188         $max = $holds_per_record if $holds_per_record > $max;
2189     }
2190
2191     return $max;
2192 }
2193
2194 =head2 GetHoldRule
2195
2196 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2197
2198 Returns the matching hold related issuingrule fields for a given
2199 patron category, itemtype, and library.
2200
2201 =cut
2202
2203 sub GetHoldRule {
2204     my ( $categorycode, $itemtype, $branchcode ) = @_;
2205
2206     my $dbh = C4::Context->dbh;
2207
2208     my $sth = $dbh->prepare(
2209         q{
2210          SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2211            FROM issuingrules
2212           WHERE (categorycode in (?,'*') )
2213             AND (itemtype IN (?,'*'))
2214             AND (branchcode IN (?,'*'))
2215        ORDER BY categorycode DESC,
2216                 itemtype     DESC,
2217                 branchcode   DESC
2218         }
2219     );
2220
2221     $sth->execute( $categorycode, $itemtype, $branchcode );
2222
2223     return $sth->fetchrow_hashref();
2224 }
2225
2226 =head1 AUTHOR
2227
2228 Koha Development Team <http://koha-community.org/>
2229
2230 =cut
2231
2232 1;