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