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