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