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