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