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