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