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