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