Bug 16534: Block AddIssue from issuing if the return is not possible
[koha.git] / C4 / Circulation.pm
1 package C4::Circulation;
2
3 # Copyright 2000-2002 Katipo Communications
4 # copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21
22 use strict;
23 #use warnings; FIXME - Bug 2505
24 use DateTime;
25 use Koha::DateUtils;
26 use C4::Context;
27 use C4::Stats;
28 use C4::Reserves;
29 use C4::Biblio;
30 use C4::Items;
31 use C4::Members;
32 use C4::Accounts;
33 use C4::ItemCirculationAlertPreference;
34 use C4::Message;
35 use C4::Debug;
36 use C4::Branch; # GetBranches
37 use C4::Log; # logaction
38 use C4::Koha qw(
39     GetAuthorisedValueByCode
40     GetAuthValCode
41     GetKohaAuthorisedValueLib
42 );
43 use C4::Overdues qw(CalcFine UpdateFine get_chargeable_units);
44 use C4::RotatingCollections qw(GetCollectionItemBranches);
45 use Algorithm::CheckDigits;
46
47 use Data::Dumper;
48 use Koha::DateUtils;
49 use Koha::Calendar;
50 use Koha::Items;
51 use Koha::Patrons;
52 use Koha::Patron::Debarments;
53 use Koha::Database;
54 use Koha::Libraries;
55 use Koha::Holds;
56 use Carp;
57 use List::MoreUtils qw( uniq );
58 use Scalar::Util qw( looks_like_number );
59 use Date::Calc qw(
60   Today
61   Today_and_Now
62   Add_Delta_YM
63   Add_Delta_DHMS
64   Date_to_Days
65   Day_of_Week
66   Add_Delta_Days
67 );
68 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
69
70 BEGIN {
71         require Exporter;
72         @ISA    = qw(Exporter);
73
74         # FIXME subs that should probably be elsewhere
75         push @EXPORT, qw(
76                 &barcodedecode
77         &LostItem
78         &ReturnLostItem
79         &GetPendingOnSiteCheckouts
80         );
81
82         # subs to deal with issuing a book
83         push @EXPORT, qw(
84                 &CanBookBeIssued
85                 &CanBookBeRenewed
86                 &AddIssue
87                 &AddRenewal
88                 &GetRenewCount
89         &GetSoonestRenewDate
90                 &GetItemIssue
91                 &GetItemIssues
92                 &GetIssuingCharges
93                 &GetIssuingRule
94         &GetBranchBorrowerCircRule
95         &GetBranchItemRule
96                 &GetBiblioIssues
97                 &GetOpenIssue
98                 &AnonymiseIssueHistory
99         &CheckIfIssuedToPatron
100         &IsItemIssued
101         GetTopIssues
102         );
103
104         # subs to deal with returns
105         push @EXPORT, qw(
106                 &AddReturn
107         &MarkIssueReturned
108         );
109
110         # subs to deal with transfers
111         push @EXPORT, qw(
112                 &transferbook
113                 &GetTransfers
114                 &GetTransfersFromTo
115                 &updateWrongTransfer
116                 &DeleteTransfer
117                 &IsBranchTransferAllowed
118                 &CreateBranchTransferLimit
119                 &DeleteBranchTransferLimits
120         &TransferSlip
121         );
122
123     # subs to deal with offline circulation
124     push @EXPORT, qw(
125       &GetOfflineOperations
126       &GetOfflineOperation
127       &AddOfflineOperation
128       &DeleteOfflineOperation
129       &ProcessOfflineOperation
130     );
131 }
132
133 =head1 NAME
134
135 C4::Circulation - Koha circulation module
136
137 =head1 SYNOPSIS
138
139 use C4::Circulation;
140
141 =head1 DESCRIPTION
142
143 The functions in this module deal with circulation, issues, and
144 returns, as well as general information about the library.
145 Also deals with inventory.
146
147 =head1 FUNCTIONS
148
149 =head2 barcodedecode
150
151   $str = &barcodedecode($barcode, [$filter]);
152
153 Generic filter function for barcode string.
154 Called on every circ if the System Pref itemBarcodeInputFilter is set.
155 Will do some manipulation of the barcode for systems that deliver a barcode
156 to circulation.pl that differs from the barcode stored for the item.
157 For proper functioning of this filter, calling the function on the 
158 correct barcode string (items.barcode) should return an unaltered barcode.
159
160 The optional $filter argument is to allow for testing or explicit 
161 behavior that ignores the System Pref.  Valid values are the same as the 
162 System Pref options.
163
164 =cut
165
166 # FIXME -- the &decode fcn below should be wrapped into this one.
167 # FIXME -- these plugins should be moved out of Circulation.pm
168 #
169 sub barcodedecode {
170     my ($barcode, $filter) = @_;
171     my $branch = C4::Branch::mybranch();
172     $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
173     $filter or return $barcode;     # ensure filter is defined, else return untouched barcode
174         if ($filter eq 'whitespace') {
175                 $barcode =~ s/\s//g;
176         } elsif ($filter eq 'cuecat') {
177                 chomp($barcode);
178             my @fields = split( /\./, $barcode );
179             my @results = map( decode($_), @fields[ 1 .. $#fields ] );
180             ($#results == 2) and return $results[2];
181         } elsif ($filter eq 'T-prefix') {
182                 if ($barcode =~ /^[Tt](\d)/) {
183                         (defined($1) and $1 eq '0') and return $barcode;
184             $barcode = substr($barcode, 2) + 0;     # FIXME: probably should be substr($barcode, 1)
185                 }
186         return sprintf("T%07d", $barcode);
187         # FIXME: $barcode could be "T1", causing warning: substr outside of string
188         # Why drop the nonzero digit after the T?
189         # Why pass non-digits (or empty string) to "T%07d"?
190         } elsif ($filter eq 'libsuite8') {
191                 unless($barcode =~ m/^($branch)-/i){    #if barcode starts with branch code its in Koha style. Skip it.
192                         if($barcode =~ m/^(\d)/i){      #Some barcodes even start with 0's & numbers and are assumed to have b as the item type in the libsuite8 software
193                                 $barcode =~ s/^[0]*(\d+)$/$branch-b-$1/i;
194                         }else{
195                                 $barcode =~ s/^(\D+)[0]*(\d+)$/$branch-$1-$2/i;
196                         }
197                 }
198     } elsif ($filter eq 'EAN13') {
199         my $ean = CheckDigits('ean');
200         if ( $ean->is_valid($barcode) ) {
201             #$barcode = sprintf('%013d',$barcode); # this doesn't work on 32-bit systems
202             $barcode = '0' x ( 13 - length($barcode) ) . $barcode;
203         } else {
204             warn "# [$barcode] not valid EAN-13/UPC-A\n";
205         }
206         }
207     return $barcode;    # return barcode, modified or not
208 }
209
210 =head2 decode
211
212   $str = &decode($chunk);
213
214 Decodes a segment of a string emitted by a CueCat barcode scanner and
215 returns it.
216
217 FIXME: Should be replaced with Barcode::Cuecat from CPAN
218 or Javascript based decoding on the client side.
219
220 =cut
221
222 sub decode {
223     my ($encoded) = @_;
224     my $seq =
225       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
226     my @s = map { index( $seq, $_ ); } split( //, $encoded );
227     my $l = ( $#s + 1 ) % 4;
228     if ($l) {
229         if ( $l == 1 ) {
230             # warn "Error: Cuecat decode parsing failed!";
231             return;
232         }
233         $l = 4 - $l;
234         $#s += $l;
235     }
236     my $r = '';
237     while ( $#s >= 0 ) {
238         my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
239         $r .=
240             chr( ( $n >> 16 ) ^ 67 )
241          .chr( ( $n >> 8 & 255 ) ^ 67 )
242          .chr( ( $n & 255 ) ^ 67 );
243         @s = @s[ 4 .. $#s ];
244     }
245     $r = substr( $r, 0, length($r) - $l );
246     return $r;
247 }
248
249 =head2 transferbook
250
251   ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, 
252                                             $barcode, $ignore_reserves);
253
254 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
255
256 C<$newbranch> is the code for the branch to which the item should be transferred.
257
258 C<$barcode> is the barcode of the item to be transferred.
259
260 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
261 Otherwise, if an item is reserved, the transfer fails.
262
263 Returns three values:
264
265 =over
266
267 =item $dotransfer 
268
269 is true if the transfer was successful.
270
271 =item $messages
272
273 is a reference-to-hash which may have any of the following keys:
274
275 =over
276
277 =item C<BadBarcode>
278
279 There is no item in the catalog with the given barcode. The value is C<$barcode>.
280
281 =item C<IsPermanent>
282
283 The item's home branch is permanent. This doesn't prevent the item from being transferred, though. The value is the code of the item's home branch.
284
285 =item C<DestinationEqualsHolding>
286
287 The item is already at the branch to which it is being transferred. The transfer is nonetheless considered to have failed. The value should be ignored.
288
289 =item C<WasReturned>
290
291 The item was on loan, and C<&transferbook> automatically returned it before transferring it. The value is the borrower number of the patron who had the item.
292
293 =item C<ResFound>
294
295 The item was reserved. The value is a reference-to-hash whose keys are fields from the reserves table of the Koha database, and C<biblioitemnumber>. It also has the key C<ResFound>, whose value is either C<Waiting> or C<Reserved>.
296
297 =item C<WasTransferred>
298
299 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
300
301 =back
302
303 =back
304
305 =cut
306
307 sub transferbook {
308     my ( $tbr, $barcode, $ignoreRs ) = @_;
309     my $messages;
310     my $dotransfer      = 1;
311     my $branches        = GetBranches();
312     my $itemnumber = GetItemnumberFromBarcode( $barcode );
313     my $issue      = GetItemIssue($itemnumber);
314     my $biblio = GetBiblioFromItemNumber($itemnumber);
315
316     # bad barcode..
317     if ( not $itemnumber ) {
318         $messages->{'BadBarcode'} = $barcode;
319         $dotransfer = 0;
320     }
321
322     # get branches of book...
323     my $hbr = $biblio->{'homebranch'};
324     my $fbr = $biblio->{'holdingbranch'};
325
326     # if using Branch Transfer Limits
327     if ( C4::Context->preference("UseBranchTransferLimits") == 1 ) {
328         if ( C4::Context->preference("item-level_itypes") && C4::Context->preference("BranchTransferLimitsType") eq 'itemtype' ) {
329             if ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{'itype'} ) ) {
330                 $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{'itype'};
331                 $dotransfer = 0;
332             }
333         } elsif ( ! IsBranchTransferAllowed( $tbr, $fbr, $biblio->{ C4::Context->preference("BranchTransferLimitsType") } ) ) {
334             $messages->{'NotAllowed'} = $tbr . "::" . $biblio->{ C4::Context->preference("BranchTransferLimitsType") };
335             $dotransfer = 0;
336         }
337     }
338
339     # if is permanent...
340     if ( $hbr && $branches->{$hbr}->{'PE'} ) {
341         $messages->{'IsPermanent'} = $hbr;
342         $dotransfer = 0;
343     }
344
345     # can't transfer book if is already there....
346     if ( $fbr eq $tbr ) {
347         $messages->{'DestinationEqualsHolding'} = 1;
348         $dotransfer = 0;
349     }
350
351     # check if it is still issued to someone, return it...
352     if ($issue->{borrowernumber}) {
353         AddReturn( $barcode, $fbr );
354         $messages->{'WasReturned'} = $issue->{borrowernumber};
355     }
356
357     # find reserves.....
358     # That'll save a database query.
359     my ( $resfound, $resrec, undef ) =
360       CheckReserves( $itemnumber );
361     if ( $resfound and not $ignoreRs ) {
362         $resrec->{'ResFound'} = $resfound;
363
364         #         $messages->{'ResFound'} = $resrec;
365         $dotransfer = 1;
366     }
367
368     #actually do the transfer....
369     if ($dotransfer) {
370         ModItemTransfer( $itemnumber, $fbr, $tbr );
371
372         # don't need to update MARC anymore, we do it in batch now
373         $messages->{'WasTransfered'} = 1;
374
375     }
376     ModDateLastSeen( $itemnumber );
377     return ( $dotransfer, $messages, $biblio );
378 }
379
380
381 sub TooMany {
382     my $borrower        = shift;
383     my $biblionumber = shift;
384         my $item                = shift;
385     my $params = shift;
386     my $onsite_checkout = $params->{onsite_checkout} || 0;
387     my $cat_borrower    = $borrower->{'categorycode'};
388     my $dbh             = C4::Context->dbh;
389         my $branch;
390         # Get which branchcode we need
391         $branch = _GetCircControlBranch($item,$borrower);
392         my $type = (C4::Context->preference('item-level_itypes')) 
393                         ? $item->{'itype'}         # item-level
394                         : $item->{'itemtype'};     # biblio-level
395  
396     # given branch, patron category, and item type, determine
397     # applicable issuing rule
398     my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
399
400     # if a rule is found and has a loan limit set, count
401     # how many loans the patron already has that meet that
402     # rule
403     if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
404         my @bind_params;
405         my $count_query = q|
406             SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
407             FROM issues
408             JOIN items USING (itemnumber)
409         |;
410
411         my $rule_itemtype = $issuing_rule->{itemtype};
412         if ($rule_itemtype eq "*") {
413             # matching rule has the default item type, so count only
414             # those existing loans that don't fall under a more
415             # specific rule
416             if (C4::Context->preference('item-level_itypes')) {
417                 $count_query .= " WHERE items.itype NOT IN (
418                                     SELECT itemtype FROM issuingrules
419                                     WHERE branchcode = ?
420                                     AND   (categorycode = ? OR categorycode = ?)
421                                     AND   itemtype <> '*'
422                                   ) ";
423             } else { 
424                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
425                                   WHERE biblioitems.itemtype NOT IN (
426                                     SELECT itemtype FROM issuingrules
427                                     WHERE branchcode = ?
428                                     AND   (categorycode = ? OR categorycode = ?)
429                                     AND   itemtype <> '*'
430                                   ) ";
431             }
432             push @bind_params, $issuing_rule->{branchcode};
433             push @bind_params, $issuing_rule->{categorycode};
434             push @bind_params, $cat_borrower;
435         } else {
436             # rule has specific item type, so count loans of that
437             # specific item type
438             if (C4::Context->preference('item-level_itypes')) {
439                 $count_query .= " WHERE items.itype = ? ";
440             } else { 
441                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
442                                   WHERE biblioitems.itemtype= ? ";
443             }
444             push @bind_params, $type;
445         }
446
447         $count_query .= " AND borrowernumber = ? ";
448         push @bind_params, $borrower->{'borrowernumber'};
449         my $rule_branch = $issuing_rule->{branchcode};
450         if ($rule_branch ne "*") {
451             if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
452                 $count_query .= " AND issues.branchcode = ? ";
453                 push @bind_params, $branch;
454             } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
455                 ; # if branch is the patron's home branch, then count all loans by patron
456             } else {
457                 $count_query .= " AND items.homebranch = ? ";
458                 push @bind_params, $branch;
459             }
460         }
461
462         my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $count_query, {}, @bind_params );
463
464         my $max_checkouts_allowed = $issuing_rule->{maxissueqty};
465         my $max_onsite_checkouts_allowed = $issuing_rule->{maxonsiteissueqty};
466
467         if ( $onsite_checkout ) {
468             if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed )  {
469                 return {
470                     reason => 'TOO_MANY_ONSITE_CHECKOUTS',
471                     count => $onsite_checkout_count,
472                     max_allowed => $max_onsite_checkouts_allowed,
473                 }
474             }
475         }
476         if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
477             if ( $checkout_count >= $max_checkouts_allowed ) {
478                 return {
479                     reason => 'TOO_MANY_CHECKOUTS',
480                     count => $checkout_count,
481                     max_allowed => $max_checkouts_allowed,
482                 };
483             }
484         } elsif ( not $onsite_checkout ) {
485             if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed )  {
486                 return {
487                     reason => 'TOO_MANY_CHECKOUTS',
488                     count => $checkout_count - $onsite_checkout_count,
489                     max_allowed => $max_checkouts_allowed,
490                 };
491             }
492         }
493     }
494
495     # Now count total loans against the limit for the branch
496     my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
497     if (defined($branch_borrower_circ_rule->{maxissueqty})) {
498         my @bind_params = ();
499         my $branch_count_query = q|
500             SELECT COUNT(*) AS total, COALESCE(SUM(onsite_checkout), 0) AS onsite_checkouts
501             FROM issues
502             JOIN items USING (itemnumber)
503             WHERE borrowernumber = ?
504         |;
505         push @bind_params, $borrower->{borrowernumber};
506
507         if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
508             $branch_count_query .= " AND issues.branchcode = ? ";
509             push @bind_params, $branch;
510         } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
511             ; # if branch is the patron's home branch, then count all loans by patron
512         } else {
513             $branch_count_query .= " AND items.homebranch = ? ";
514             push @bind_params, $branch;
515         }
516         my ( $checkout_count, $onsite_checkout_count ) = $dbh->selectrow_array( $branch_count_query, {}, @bind_params );
517         my $max_checkouts_allowed = $branch_borrower_circ_rule->{maxissueqty};
518         my $max_onsite_checkouts_allowed = $branch_borrower_circ_rule->{maxonsiteissueqty};
519
520         if ( $onsite_checkout ) {
521             if ( $onsite_checkout_count >= $max_onsite_checkouts_allowed )  {
522                 return {
523                     reason => 'TOO_MANY_ONSITE_CHECKOUTS',
524                     count => $onsite_checkout_count,
525                     max_allowed => $max_onsite_checkouts_allowed,
526                 }
527             }
528         }
529         if ( C4::Context->preference('ConsiderOnSiteCheckoutsAsNormalCheckouts') ) {
530             if ( $checkout_count >= $max_checkouts_allowed ) {
531                 return {
532                     reason => 'TOO_MANY_CHECKOUTS',
533                     count => $checkout_count,
534                     max_allowed => $max_checkouts_allowed,
535                 };
536             }
537         } elsif ( not $onsite_checkout ) {
538             if ( $checkout_count - $onsite_checkout_count >= $max_checkouts_allowed )  {
539                 return {
540                     reason => 'TOO_MANY_CHECKOUTS',
541                     count => $checkout_count - $onsite_checkout_count,
542                     max_allowed => $max_checkouts_allowed,
543                 };
544             }
545         }
546     }
547
548     # OK, the patron can issue !!!
549     return;
550 }
551
552 =head2 itemissues
553
554   @issues = &itemissues($biblioitemnumber, $biblio);
555
556 Looks up information about who has borrowed the bookZ<>(s) with the
557 given biblioitemnumber.
558
559 C<$biblio> is ignored.
560
561 C<&itemissues> returns an array of references-to-hash. The keys
562 include the fields from the C<items> table in the Koha database.
563 Additional keys include:
564
565 =over 4
566
567 =item C<date_due>
568
569 If the item is currently on loan, this gives the due date.
570
571 If the item is not on loan, then this is either "Available" or
572 "Cancelled", if the item has been withdrawn.
573
574 =item C<card>
575
576 If the item is currently on loan, this gives the card number of the
577 patron who currently has the item.
578
579 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
580
581 These give the timestamp for the last three times the item was
582 borrowed.
583
584 =item C<card0>, C<card1>, C<card2>
585
586 The card number of the last three patrons who borrowed this item.
587
588 =item C<borrower0>, C<borrower1>, C<borrower2>
589
590 The borrower number of the last three patrons who borrowed this item.
591
592 =back
593
594 =cut
595
596 #'
597 sub itemissues {
598     my ( $bibitem, $biblio ) = @_;
599     my $dbh = C4::Context->dbh;
600     my $sth =
601       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
602       || die $dbh->errstr;
603     my $i = 0;
604     my @results;
605
606     $sth->execute($bibitem) || die $sth->errstr;
607
608     while ( my $data = $sth->fetchrow_hashref ) {
609
610         # Find out who currently has this item.
611         # FIXME - Wouldn't it be better to do this as a left join of
612         # some sort? Currently, this code assumes that if
613         # fetchrow_hashref() fails, then the book is on the shelf.
614         # fetchrow_hashref() can fail for any number of reasons (e.g.,
615         # database server crash), not just because no items match the
616         # search criteria.
617         my $sth2 = $dbh->prepare(
618             "SELECT * FROM issues
619                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
620                 WHERE itemnumber = ?
621             "
622         );
623
624         $sth2->execute( $data->{'itemnumber'} );
625         if ( my $data2 = $sth2->fetchrow_hashref ) {
626             $data->{'date_due'} = $data2->{'date_due'};
627             $data->{'card'}     = $data2->{'cardnumber'};
628             $data->{'borrower'} = $data2->{'borrowernumber'};
629         }
630         else {
631             $data->{'date_due'} = ($data->{'withdrawn'} eq '1') ? 'Cancelled' : 'Available';
632         }
633
634
635         # Find the last 3 people who borrowed this item.
636         $sth2 = $dbh->prepare(
637             "SELECT * FROM old_issues
638                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
639                 WHERE itemnumber = ?
640                 ORDER BY returndate DESC,timestamp DESC"
641         );
642
643         $sth2->execute( $data->{'itemnumber'} );
644         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
645         {    # FIXME : error if there is less than 3 pple borrowing this item
646             if ( my $data2 = $sth2->fetchrow_hashref ) {
647                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
648                 $data->{"card$i2"}      = $data2->{'cardnumber'};
649                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
650             }    # if
651         }    # for
652
653         $results[$i] = $data;
654         $i++;
655     }
656
657     return (@results);
658 }
659
660 =head2 CanBookBeIssued
661
662   ( $issuingimpossible, $needsconfirmation ) =  CanBookBeIssued( $borrower, 
663                       $barcode, $duedate, $inprocess, $ignore_reserves, $params );
664
665 Check if a book can be issued.
666
667 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
668
669 =over 4
670
671 =item C<$borrower> hash with borrower informations (from GetMember or GetMemberDetails)
672
673 =item C<$barcode> is the bar code of the book being issued.
674
675 =item C<$duedates> is a DateTime object.
676
677 =item C<$inprocess> boolean switch
678
679 =item C<$ignore_reserves> boolean switch
680
681 =item C<$params> Hashref of additional parameters
682
683 Available keys:
684     override_high_holds - Ignore high holds
685     onsite_checkout     - Checkout is an onsite checkout that will not leave the library
686
687 =back
688
689 Returns :
690
691 =over 4
692
693 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
694 Possible values are :
695
696 =back
697
698 =head3 INVALID_DATE 
699
700 sticky due date is invalid
701
702 =head3 GNA
703
704 borrower gone with no address
705
706 =head3 CARD_LOST
707
708 borrower declared it's card lost
709
710 =head3 DEBARRED
711
712 borrower debarred
713
714 =head3 UNKNOWN_BARCODE
715
716 barcode unknown
717
718 =head3 NOT_FOR_LOAN
719
720 item is not for loan
721
722 =head3 WTHDRAWN
723
724 item withdrawn.
725
726 =head3 RESTRICTED
727
728 item is restricted (set by ??)
729
730 C<$needsconfirmation> a reference to a hash. It contains reasons why the loan 
731 could be prevented, but ones that can be overriden by the operator.
732
733 Possible values are :
734
735 =head3 DEBT
736
737 borrower has debts.
738
739 =head3 RENEW_ISSUE
740
741 renewing, not issuing
742
743 =head3 ISSUED_TO_ANOTHER
744
745 issued to someone else.
746
747 =head3 RESERVED
748
749 reserved for someone else.
750
751 =head3 INVALID_DATE
752
753 sticky due date is invalid or due date in the past
754
755 =head3 TOO_MANY
756
757 if the borrower borrows to much things
758
759 =cut
760
761 sub CanBookBeIssued {
762     my ( $borrower, $barcode, $duedate, $inprocess, $ignore_reserves, $params ) = @_;
763     my %needsconfirmation;    # filled with problems that needs confirmations
764     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
765     my %alerts;               # filled with messages that shouldn't stop issuing, but the librarian should be aware of.
766
767     my $onsite_checkout     = $params->{onsite_checkout}     || 0;
768     my $override_high_holds = $params->{override_high_holds} || 0;
769
770     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
771     my $issue = GetItemIssue($item->{itemnumber});
772         my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
773         $item->{'itemtype'}=$item->{'itype'}; 
774     my $dbh             = C4::Context->dbh;
775
776     # MANDATORY CHECKS - unless item exists, nothing else matters
777     unless ( $item->{barcode} ) {
778         $issuingimpossible{UNKNOWN_BARCODE} = 1;
779     }
780         return ( \%issuingimpossible, \%needsconfirmation ) if %issuingimpossible;
781
782     #
783     # DUE DATE is OK ? -- should already have checked.
784     #
785     if ($duedate && ref $duedate ne 'DateTime') {
786         $duedate = dt_from_string($duedate);
787     }
788     my $now = DateTime->now( time_zone => C4::Context->tz() );
789     unless ( $duedate ) {
790         my $issuedate = $now->clone();
791
792         my $branch = _GetCircControlBranch($item,$borrower);
793         my $itype = ( C4::Context->preference('item-level_itypes') ) ? $item->{'itype'} : $biblioitem->{'itemtype'};
794         $duedate = CalcDateDue( $issuedate, $itype, $branch, $borrower );
795
796         # Offline circ calls AddIssue directly, doesn't run through here
797         #  So issuingimpossible should be ok.
798     }
799     if ($duedate) {
800         my $today = $now->clone();
801         $today->truncate( to => 'minute');
802         if (DateTime->compare($duedate,$today) == -1 ) { # duedate cannot be before now
803             $needsconfirmation{INVALID_DATE} = output_pref($duedate);
804         }
805     } else {
806             $issuingimpossible{INVALID_DATE} = output_pref($duedate);
807     }
808
809     #
810     # BORROWER STATUS
811     #
812     if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
813         # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
814         &UpdateStats({
815                      branch => C4::Context->userenv->{'branch'},
816                      type => 'localuse',
817                      itemnumber => $item->{'itemnumber'},
818                      itemtype => $item->{'itemtype'},
819                      borrowernumber => $borrower->{'borrowernumber'},
820                      ccode => $item->{'ccode'}}
821                     );
822         ModDateLastSeen( $item->{'itemnumber'} );
823         return( { STATS => 1 }, {});
824     }
825     if ( ref $borrower->{flags} ) {
826         if ( $borrower->{flags}->{GNA} ) {
827             $issuingimpossible{GNA} = 1;
828         }
829         if ( $borrower->{flags}->{'LOST'} ) {
830             $issuingimpossible{CARD_LOST} = 1;
831         }
832         if ( $borrower->{flags}->{'DBARRED'} ) {
833             $issuingimpossible{DEBARRED} = 1;
834         }
835     }
836     if ( !defined $borrower->{dateexpiry} || $borrower->{'dateexpiry'} eq '0000-00-00') {
837         $issuingimpossible{EXPIRED} = 1;
838     } else {
839         my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'sql', 'floating' );
840         $expiry_dt->truncate( to => 'day');
841         my $today = $now->clone()->truncate(to => 'day');
842         $today->set_time_zone( 'floating' );
843         if ( DateTime->compare($today, $expiry_dt) == 1 ) {
844             $issuingimpossible{EXPIRED} = 1;
845         }
846     }
847
848     #
849     # BORROWER STATUS
850     #
851
852     # DEBTS
853     my ($balance, $non_issue_charges, $other_charges) =
854       C4::Members::GetMemberAccountBalance( $borrower->{'borrowernumber'} );
855
856     my $amountlimit = C4::Context->preference("noissuescharge");
857     my $allowfineoverride = C4::Context->preference("AllowFineOverride");
858     my $allfinesneedoverride = C4::Context->preference("AllFinesNeedOverride");
859
860     # Check the debt of this patrons guarantees
861     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
862     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
863     if ( defined $no_issues_charge_guarantees ) {
864         my $p = Koha::Patrons->find( $borrower->{borrowernumber} );
865         my @guarantees = $p->guarantees();
866         my $guarantees_non_issues_charges;
867         foreach my $g ( @guarantees ) {
868             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
869             $guarantees_non_issues_charges += $n;
870         }
871
872         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees && !$inprocess && !$allowfineoverride) {
873             $issuingimpossible{DEBT_GUARANTEES} = $guarantees_non_issues_charges;
874         } elsif ( $guarantees_non_issues_charges > $no_issues_charge_guarantees && !$inprocess && $allowfineoverride) {
875             $needsconfirmation{DEBT_GUARANTEES} = $guarantees_non_issues_charges;
876         } elsif ( $allfinesneedoverride && $guarantees_non_issues_charges > 0 && $guarantees_non_issues_charges <= $no_issues_charge_guarantees && !$inprocess ) {
877             $needsconfirmation{DEBT_GUARANTEES} = $guarantees_non_issues_charges;
878         }
879     }
880
881     if ( C4::Context->preference("IssuingInProcess") ) {
882         if ( $non_issue_charges > $amountlimit && !$inprocess && !$allowfineoverride) {
883             $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
884         } elsif ( $non_issue_charges > $amountlimit && !$inprocess && $allowfineoverride) {
885             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
886         } elsif ( $allfinesneedoverride && $non_issue_charges > 0 && $non_issue_charges <= $amountlimit && !$inprocess ) {
887             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
888         }
889     }
890     else {
891         if ( $non_issue_charges > $amountlimit && $allowfineoverride ) {
892             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
893         } elsif ( $non_issue_charges > $amountlimit && !$allowfineoverride) {
894             $issuingimpossible{DEBT} = sprintf( "%.2f", $non_issue_charges );
895         } elsif ( $non_issue_charges > 0 && $allfinesneedoverride ) {
896             $needsconfirmation{DEBT} = sprintf( "%.2f", $non_issue_charges );
897         }
898     }
899
900     if ($balance > 0 && $other_charges > 0) {
901         $alerts{OTHER_CHARGES} = sprintf( "%.2f", $other_charges );
902     }
903
904     my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
905     if ($blocktype == -1) {
906         ## patron has outstanding overdue loans
907             if ( C4::Context->preference("OverduesBlockCirc") eq 'block'){
908                 $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
909             }
910             elsif ( C4::Context->preference("OverduesBlockCirc") eq 'confirmation'){
911                 $needsconfirmation{USERBLOCKEDOVERDUE} = $count;
912             }
913     } elsif($blocktype == 1) {
914         # patron has accrued fine days or has a restriction. $count is a date
915         if ($count eq '9999-12-31') {
916             $issuingimpossible{USERBLOCKEDNOENDDATE} = $count;
917         }
918         else {
919             $issuingimpossible{USERBLOCKEDWITHENDDATE} = $count;
920         }
921     }
922
923 #
924     # JB34 CHECKS IF BORROWERS DON'T HAVE ISSUE TOO MANY BOOKS
925     #
926     my $toomany = TooMany( $borrower, $item->{biblionumber}, $item, { onsite_checkout => $onsite_checkout } );
927     # if TooMany max_allowed returns 0 the user doesn't have permission to check out this book
928     if ( $toomany ) {
929         if ( $toomany->{max_allowed} == 0 ) {
930             $needsconfirmation{PATRON_CANT} = 1;
931         }
932         if ( C4::Context->preference("AllowTooManyOverride") ) {
933             $needsconfirmation{TOO_MANY} = $toomany->{reason};
934             $needsconfirmation{current_loan_count} = $toomany->{count};
935             $needsconfirmation{max_loans_allowed} = $toomany->{max_allowed};
936         } else {
937             $issuingimpossible{TOO_MANY} = $toomany->{reason};
938             $issuingimpossible{current_loan_count} = $toomany->{count};
939             $issuingimpossible{max_loans_allowed} = $toomany->{max_allowed};
940         }
941     }
942
943     #
944     # ITEM CHECKING
945     #
946     if ( $item->{'notforloan'} )
947     {
948         if(!C4::Context->preference("AllowNotForLoanOverride")){
949             $issuingimpossible{NOT_FOR_LOAN} = 1;
950             $issuingimpossible{item_notforloan} = $item->{'notforloan'};
951         }else{
952             $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
953             $needsconfirmation{item_notforloan} = $item->{'notforloan'};
954         }
955     }
956     else {
957         # we have to check itemtypes.notforloan also
958         if (C4::Context->preference('item-level_itypes')){
959             # this should probably be a subroutine
960             my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
961             $sth->execute($item->{'itemtype'});
962             my $notforloan=$sth->fetchrow_hashref();
963             if ($notforloan->{'notforloan'}) {
964                 if (!C4::Context->preference("AllowNotForLoanOverride")) {
965                     $issuingimpossible{NOT_FOR_LOAN} = 1;
966                     $issuingimpossible{itemtype_notforloan} = $item->{'itype'};
967                 } else {
968                     $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
969                     $needsconfirmation{itemtype_notforloan} = $item->{'itype'};
970                 }
971             }
972         }
973         elsif ($biblioitem->{'notforloan'} == 1){
974             if (!C4::Context->preference("AllowNotForLoanOverride")) {
975                 $issuingimpossible{NOT_FOR_LOAN} = 1;
976                 $issuingimpossible{itemtype_notforloan} = $biblioitem->{'itemtype'};
977             } else {
978                 $needsconfirmation{NOT_FOR_LOAN_FORCING} = 1;
979                 $needsconfirmation{itemtype_notforloan} = $biblioitem->{'itemtype'};
980             }
981         }
982     }
983     if ( $item->{'withdrawn'} && $item->{'withdrawn'} > 0 )
984     {
985         $issuingimpossible{WTHDRAWN} = 1;
986     }
987     if (   $item->{'restricted'}
988         && $item->{'restricted'} == 1 )
989     {
990         $issuingimpossible{RESTRICTED} = 1;
991     }
992     if ( $item->{'itemlost'} && C4::Context->preference("IssueLostItem") ne 'nothing' ) {
993         my $code = GetAuthorisedValueByCode( 'LOST', $item->{'itemlost'} );
994         $needsconfirmation{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'confirm' );
995         $alerts{ITEM_LOST} = $code if ( C4::Context->preference("IssueLostItem") eq 'alert' );
996     }
997     if ( C4::Context->preference("IndependentBranches") ) {
998         my $userenv = C4::Context->userenv;
999         unless ( C4::Context->IsSuperLibrarian() ) {
1000             if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} ){
1001                 $issuingimpossible{ITEMNOTSAMEBRANCH} = 1;
1002                 $issuingimpossible{'itemhomebranch'} = $item->{C4::Context->preference("HomeOrHoldingBranch")};
1003             }
1004             $needsconfirmation{BORRNOTSAMEBRANCH} = GetBranchName( $borrower->{'branchcode'} )
1005               if ( $borrower->{'branchcode'} ne $userenv->{branch} );
1006         }
1007     }
1008     #
1009     # CHECK IF THERE IS RENTAL CHARGES. RENTAL MUST BE CONFIRMED BY THE BORROWER
1010     #
1011     my $rentalConfirmation = C4::Context->preference("RentalFeesCheckoutConfirmation");
1012
1013     if ( $rentalConfirmation ){
1014         my ($rentalCharge) = GetIssuingCharges( $item->{'itemnumber'}, $borrower->{'borrowernumber'} );
1015         if ( $rentalCharge > 0 ){
1016             $rentalCharge = sprintf("%.02f", $rentalCharge);
1017             $needsconfirmation{RENTALCHARGE} = $rentalCharge;
1018         }
1019     }
1020
1021     #
1022     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
1023     #
1024     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} ){
1025
1026         # Already issued to current borrower. Ask whether the loan should
1027         # be renewed.
1028         my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
1029             $borrower->{'borrowernumber'},
1030             $item->{'itemnumber'}
1031         );
1032         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
1033             if ( $renewerror eq 'onsite_checkout' ) {
1034                 $issuingimpossible{NO_RENEWAL_FOR_ONSITE_CHECKOUTS} = 1;
1035             }
1036             else {
1037                 $issuingimpossible{NO_MORE_RENEWALS} = 1;
1038             }
1039         }
1040         else {
1041             $needsconfirmation{RENEW_ISSUE} = 1;
1042         }
1043     }
1044     elsif ($issue->{borrowernumber}) {
1045
1046         # issued to someone else
1047         my $currborinfo =    C4::Members::GetMember( borrowernumber => $issue->{borrowernumber} );
1048
1049
1050         my ( $can_be_returned, $message ) = CanBookBeReturned( $item, C4::Context->userenv->{branch} );
1051
1052         unless ( $can_be_returned ) {
1053             $issuingimpossible{RETURN_IMPOSSIBLE} = 1;
1054             $issuingimpossible{branch_to_return} = $message;
1055         } else {
1056             $needsconfirmation{ISSUED_TO_ANOTHER} = 1;
1057             $needsconfirmation{issued_firstname} = $currborinfo->{'firstname'};
1058             $needsconfirmation{issued_surname} = $currborinfo->{'surname'};
1059             $needsconfirmation{issued_cardnumber} = $currborinfo->{'cardnumber'};
1060             $needsconfirmation{issued_borrowernumber} = $currborinfo->{'borrowernumber'};
1061         }
1062     }
1063
1064     unless ( $ignore_reserves ) {
1065         # See if the item is on reserve.
1066         my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
1067         if ($restype) {
1068             my $resbor = $res->{'borrowernumber'};
1069             if ( $resbor ne $borrower->{'borrowernumber'} ) {
1070                 my ( $resborrower ) = C4::Members::GetMember( borrowernumber => $resbor );
1071                 my $branchname = GetBranchName( $res->{'branchcode'} );
1072                 if ( $restype eq "Waiting" )
1073                 {
1074                     # The item is on reserve and waiting, but has been
1075                     # reserved by some other patron.
1076                     $needsconfirmation{RESERVE_WAITING} = 1;
1077                     $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1078                     $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1079                     $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1080                     $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1081                     $needsconfirmation{'resbranchname'} = $branchname;
1082                     $needsconfirmation{'reswaitingdate'} = $res->{'waitingdate'};
1083                 }
1084                 elsif ( $restype eq "Reserved" ) {
1085                     # The item is on reserve for someone else.
1086                     $needsconfirmation{RESERVED} = 1;
1087                     $needsconfirmation{'resfirstname'} = $resborrower->{'firstname'};
1088                     $needsconfirmation{'ressurname'} = $resborrower->{'surname'};
1089                     $needsconfirmation{'rescardnumber'} = $resborrower->{'cardnumber'};
1090                     $needsconfirmation{'resborrowernumber'} = $resborrower->{'borrowernumber'};
1091                     $needsconfirmation{'resbranchname'} = $branchname;
1092                     $needsconfirmation{'resreservedate'} = $res->{'reservedate'};
1093                 }
1094             }
1095         }
1096     }
1097
1098     ## CHECK AGE RESTRICTION
1099     my $agerestriction  = $biblioitem->{'agerestriction'};
1100     my ($restriction_age, $daysToAgeRestriction) = GetAgeRestriction( $agerestriction, $borrower );
1101     if ( $daysToAgeRestriction && $daysToAgeRestriction > 0 ) {
1102         if ( C4::Context->preference('AgeRestrictionOverride') ) {
1103             $needsconfirmation{AGE_RESTRICTION} = "$agerestriction";
1104         }
1105         else {
1106             $issuingimpossible{AGE_RESTRICTION} = "$agerestriction";
1107         }
1108     }
1109
1110     ## check for high holds decreasing loan period
1111     if ( C4::Context->preference('decreaseLoanHighHolds') ) {
1112         my $check = checkHighHolds( $item, $borrower );
1113
1114         if ( $check->{exceeded} ) {
1115             if ($override_high_holds) {
1116                 $alerts{HIGHHOLDS} = {
1117                     num_holds  => $check->{outstanding},
1118                     duration   => $check->{duration},
1119                     returndate => output_pref( $check->{due_date} ),
1120                 };
1121             }
1122             else {
1123                 $needsconfirmation{HIGHHOLDS} = {
1124                     num_holds  => $check->{outstanding},
1125                     duration   => $check->{duration},
1126                     returndate => output_pref( $check->{due_date} ),
1127                 };
1128             }
1129         }
1130     }
1131
1132     if (
1133         !C4::Context->preference('AllowMultipleIssuesOnABiblio') &&
1134         # don't do the multiple loans per bib check if we've
1135         # already determined that we've got a loan on the same item
1136         !$issuingimpossible{NO_MORE_RENEWALS} &&
1137         !$needsconfirmation{RENEW_ISSUE}
1138     ) {
1139         # Check if borrower has already issued an item from the same biblio
1140         # Only if it's not a subscription
1141         my $biblionumber = $item->{biblionumber};
1142         require C4::Serials;
1143         my $is_a_subscription = C4::Serials::CountSubscriptionFromBiblionumber($biblionumber);
1144         unless ($is_a_subscription) {
1145             my $issues = GetIssues( {
1146                 borrowernumber => $borrower->{borrowernumber},
1147                 biblionumber   => $biblionumber,
1148             } );
1149             my @issues = $issues ? @$issues : ();
1150             # if we get here, we don't already have a loan on this item,
1151             # so if there are any loans on this bib, ask for confirmation
1152             if (scalar @issues > 0) {
1153                 $needsconfirmation{BIBLIO_ALREADY_ISSUED} = 1;
1154             }
1155         }
1156     }
1157
1158     return ( \%issuingimpossible, \%needsconfirmation, \%alerts );
1159 }
1160
1161 =head2 CanBookBeReturned
1162
1163   ($returnallowed, $message) = CanBookBeReturned($item, $branch)
1164
1165 Check whether the item can be returned to the provided branch
1166
1167 =over 4
1168
1169 =item C<$item> is a hash of item information as returned from GetItem
1170
1171 =item C<$branch> is the branchcode where the return is taking place
1172
1173 =back
1174
1175 Returns:
1176
1177 =over 4
1178
1179 =item C<$returnallowed> is 0 or 1, corresponding to whether the return is allowed (1) or not (0)
1180
1181 =item C<$message> is the branchcode where the item SHOULD be returned, if the return is not allowed
1182
1183 =back
1184
1185 =cut
1186
1187 sub CanBookBeReturned {
1188   my ($item, $branch) = @_;
1189   my $allowreturntobranch = C4::Context->preference("AllowReturnToBranch") || 'anywhere';
1190
1191   # assume return is allowed to start
1192   my $allowed = 1;
1193   my $message;
1194
1195   # identify all cases where return is forbidden
1196   if ($allowreturntobranch eq 'homebranch' && $branch ne $item->{'homebranch'}) {
1197      $allowed = 0;
1198      $message = $item->{'homebranch'};
1199   } elsif ($allowreturntobranch eq 'holdingbranch' && $branch ne $item->{'holdingbranch'}) {
1200      $allowed = 0;
1201      $message = $item->{'holdingbranch'};
1202   } elsif ($allowreturntobranch eq 'homeorholdingbranch' && $branch ne $item->{'homebranch'} && $branch ne $item->{'holdingbranch'}) {
1203      $allowed = 0;
1204      $message = $item->{'homebranch'}; # FIXME: choice of homebranch is arbitrary
1205   }
1206
1207   return ($allowed, $message);
1208 }
1209
1210 =head2 CheckHighHolds
1211
1212     used when syspref decreaseLoanHighHolds is active. Returns 1 or 0 to define whether the minimum value held in
1213     decreaseLoanHighHoldsValue is exceeded, the total number of outstanding holds, the number of days the loan
1214     has been decreased to (held in syspref decreaseLoanHighHoldsValue), and the new due date
1215
1216 =cut
1217
1218 sub checkHighHolds {
1219     my ( $item, $borrower ) = @_;
1220     my $biblio = GetBiblioFromItemNumber( $item->{itemnumber} );
1221     my $branch = _GetCircControlBranch( $item, $borrower );
1222
1223     my $return_data = {
1224         exceeded    => 0,
1225         outstanding => 0,
1226         duration    => 0,
1227         due_date    => undef,
1228     };
1229
1230     my $holds = Koha::Holds->search( { biblionumber => $item->{'biblionumber'} } );
1231
1232     if ( $holds->count() ) {
1233         $return_data->{outstanding} = $holds->count();
1234
1235         my $decreaseLoanHighHoldsControl        = C4::Context->preference('decreaseLoanHighHoldsControl');
1236         my $decreaseLoanHighHoldsValue          = C4::Context->preference('decreaseLoanHighHoldsValue');
1237         my $decreaseLoanHighHoldsIgnoreStatuses = C4::Context->preference('decreaseLoanHighHoldsIgnoreStatuses');
1238
1239         my @decreaseLoanHighHoldsIgnoreStatuses = split( /,/, $decreaseLoanHighHoldsIgnoreStatuses );
1240
1241         if ( $decreaseLoanHighHoldsControl eq 'static' ) {
1242
1243             # static means just more than a given number of holds on the record
1244
1245             # If the number of holds is less than the threshold, we can stop here
1246             if ( $holds->count() < $decreaseLoanHighHoldsValue ) {
1247                 return $return_data;
1248             }
1249         }
1250         elsif ( $decreaseLoanHighHoldsControl eq 'dynamic' ) {
1251
1252             # dynamic means X more than the number of holdable items on the record
1253
1254             # let's get the items
1255             my @items = $holds->next()->biblio()->items();
1256
1257             # Remove any items with status defined to be ignored even if the would not make item unholdable
1258             foreach my $status (@decreaseLoanHighHoldsIgnoreStatuses) {
1259                 @items = grep { !$_->$status } @items;
1260             }
1261
1262             # Remove any items that are not holdable for this patron
1263             @items = grep { CanItemBeReserved( $borrower->{borrowernumber}, $_->itemnumber ) eq 'OK' } @items;
1264
1265             my $items_count = scalar @items;
1266
1267             my $threshold = $items_count + $decreaseLoanHighHoldsValue;
1268
1269             # If the number of holds is less than the count of items we have
1270             # plus the number of holds allowed above that count, we can stop here
1271             if ( $holds->count() <= $threshold ) {
1272                 return $return_data;
1273             }
1274         }
1275
1276         my $issuedate = DateTime->now( time_zone => C4::Context->tz() );
1277
1278         my $calendar = Koha::Calendar->new( branchcode => $branch );
1279
1280         my $itype =
1281           ( C4::Context->preference('item-level_itypes') )
1282           ? $biblio->{'itype'}
1283           : $biblio->{'itemtype'};
1284
1285         my $orig_due = C4::Circulation::CalcDateDue( $issuedate, $itype, $branch, $borrower );
1286
1287         my $decreaseLoanHighHoldsDuration = C4::Context->preference('decreaseLoanHighHoldsDuration');
1288
1289         my $reduced_datedue = $calendar->addDate( $issuedate, $decreaseLoanHighHoldsDuration );
1290
1291         if ( DateTime->compare( $reduced_datedue, $orig_due ) == -1 ) {
1292             $return_data->{exceeded} = 1;
1293             $return_data->{duration} = $decreaseLoanHighHoldsDuration;
1294             $return_data->{due_date} = $reduced_datedue;
1295         }
1296     }
1297
1298     return $return_data;
1299 }
1300
1301 =head2 AddIssue
1302
1303   &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
1304
1305 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
1306
1307 =over 4
1308
1309 =item C<$borrower> is a hash with borrower informations (from GetMember or GetMemberDetails).
1310
1311 =item C<$barcode> is the barcode of the item being issued.
1312
1313 =item C<$datedue> is a DateTime object for the max date of return, i.e. the date due (optional).
1314 Calculated if empty.
1315
1316 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
1317
1318 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
1319 Defaults to today.  Unlike C<$datedue>, NOT a DateTime object, unfortunately.
1320
1321 AddIssue does the following things :
1322
1323   - step 01: check that there is a borrowernumber & a barcode provided
1324   - check for RENEWAL (book issued & being issued to the same patron)
1325       - renewal YES = Calculate Charge & renew
1326       - renewal NO  =
1327           * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
1328           * RESERVE PLACED ?
1329               - fill reserve if reserve to this patron
1330               - cancel reserve or not, otherwise
1331           * TRANSFERT PENDING ?
1332               - complete the transfert
1333           * ISSUE THE BOOK
1334
1335 =back
1336
1337 =cut
1338
1339 sub AddIssue {
1340     my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode, $params ) = @_;
1341     my $onsite_checkout = $params && $params->{onsite_checkout} ? 1 : 0;
1342     my $auto_renew = $params && $params->{auto_renew};
1343     my $dbh = C4::Context->dbh;
1344     my $barcodecheck=CheckValidBarcode($barcode);
1345
1346     my $issue;
1347
1348     if ($datedue && ref $datedue ne 'DateTime') {
1349         $datedue = dt_from_string($datedue);
1350     }
1351     # $issuedate defaults to today.
1352     if ( ! defined $issuedate ) {
1353         $issuedate = DateTime->now(time_zone => C4::Context->tz());
1354     }
1355     else {
1356         if ( ref $issuedate ne 'DateTime') {
1357             $issuedate = dt_from_string($issuedate);
1358
1359         }
1360     }
1361         if ($borrower and $barcode and $barcodecheck ne '0'){#??? wtf
1362                 # find which item we issue
1363                 my $item = GetItem('', $barcode) or return;     # if we don't get an Item, abort.
1364                 my $branch = _GetCircControlBranch($item,$borrower);
1365                 
1366                 # get actual issuing if there is one
1367                 my $actualissue = GetItemIssue( $item->{itemnumber});
1368                 
1369                 # get biblioinformation for this item
1370                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
1371                 
1372                 #
1373                 # check if we just renew the issue.
1374                 #
1375                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
1376                     $datedue = AddRenewal(
1377                         $borrower->{'borrowernumber'},
1378                         $item->{'itemnumber'},
1379                         $branch,
1380                         $datedue,
1381                         $issuedate, # here interpreted as the renewal date
1382                         );
1383                 }
1384                 else {
1385         # it's NOT a renewal
1386                         if ( $actualissue->{borrowernumber}) {
1387                                 # This book is currently on loan, but not to the person
1388                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
1389                 my ( $allowed, $message ) = CanBookBeReturned( $item, C4::Context->userenv->{branch} );
1390                 return unless $allowed;
1391                                 AddReturn(
1392                                         $item->{'barcode'},
1393                                         C4::Context->userenv->{'branch'}
1394                                 );
1395                         }
1396
1397             MoveReserve( $item->{'itemnumber'}, $borrower->{'borrowernumber'}, $cancelreserve );
1398                         # Starting process for transfer job (checking transfert and validate it if we have one)
1399             my ($datesent) = GetTransfers($item->{'itemnumber'});
1400             if ($datesent) {
1401         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
1402                 my $sth =
1403                     $dbh->prepare(
1404                     "UPDATE branchtransfers 
1405                         SET datearrived = now(),
1406                         tobranch = ?,
1407                         comments = 'Forced branchtransfer'
1408                     WHERE itemnumber= ? AND datearrived IS NULL"
1409                     );
1410                 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
1411             }
1412
1413         # If automatic renewal wasn't selected while issuing, set the value according to the issuing rule.
1414         unless ($auto_renew) {
1415             my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branch);
1416             $auto_renew = $issuingrule->{auto_renew};
1417         }
1418
1419         # Record in the database the fact that the book was issued.
1420         unless ($datedue) {
1421             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
1422             $datedue = CalcDateDue( $issuedate, $itype, $branch, $borrower );
1423
1424         }
1425         $datedue->truncate( to => 'minute');
1426
1427         $issue = Koha::Database->new()->schema()->resultset('Issue')->create(
1428             {
1429                 borrowernumber  => $borrower->{'borrowernumber'},
1430                 itemnumber      => $item->{'itemnumber'},
1431                 issuedate       => $issuedate->strftime('%Y-%m-%d %H:%M:%S'),
1432                 date_due        => $datedue->strftime('%Y-%m-%d %H:%M:%S'),
1433                 branchcode      => C4::Context->userenv->{'branch'},
1434                 onsite_checkout => $onsite_checkout,
1435                 auto_renew      => $auto_renew ? 1 : 0
1436             }
1437         );
1438
1439         if ( C4::Context->preference('ReturnToShelvingCart') ) { ## ReturnToShelvingCart is on, anything issued should be taken off the cart.
1440           CartToShelf( $item->{'itemnumber'} );
1441         }
1442         $item->{'issues'}++;
1443         if ( C4::Context->preference('UpdateTotalIssuesOnCirc') ) {
1444             UpdateTotalIssues($item->{'biblionumber'}, 1);
1445         }
1446
1447         ## If item was lost, it has now been found, reverse any list item charges if necessary.
1448         if ( $item->{'itemlost'} ) {
1449             if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
1450                 _FixAccountForLostAndReturned( $item->{'itemnumber'}, undef, $item->{'barcode'} );
1451             }
1452         }
1453
1454         ModItem({ issues           => $item->{'issues'},
1455                   holdingbranch    => C4::Context->userenv->{'branch'},
1456                   itemlost         => 0,
1457                   datelastborrowed => DateTime->now(time_zone => C4::Context->tz())->ymd(),
1458                   onloan           => $datedue->ymd(),
1459                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
1460         ModDateLastSeen( $item->{'itemnumber'} );
1461
1462         # If it costs to borrow this book, charge it to the patron's account.
1463         my ( $charge, $itemtype ) = GetIssuingCharges(
1464             $item->{'itemnumber'},
1465             $borrower->{'borrowernumber'}
1466         );
1467         if ( $charge > 0 ) {
1468             AddIssuingCharge(
1469                 $item->{'itemnumber'},
1470                 $borrower->{'borrowernumber'}, $charge
1471             );
1472             $item->{'charge'} = $charge;
1473         }
1474
1475         # Record the fact that this book was issued.
1476         &UpdateStats({
1477                       branch => C4::Context->userenv->{'branch'},
1478                       type => ( $onsite_checkout ? 'onsite_checkout' : 'issue' ),
1479                       amount => $charge,
1480                       other => ($sipmode ? "SIP-$sipmode" : ''),
1481                       itemnumber => $item->{'itemnumber'},
1482                       itemtype => $item->{'itype'},
1483                       borrowernumber => $borrower->{'borrowernumber'},
1484                       ccode => $item->{'ccode'}}
1485         );
1486
1487         # Send a checkout slip.
1488         my $circulation_alert = 'C4::ItemCirculationAlertPreference';
1489         my %conditions = (
1490             branchcode   => $branch,
1491             categorycode => $borrower->{categorycode},
1492             item_type    => $item->{itype},
1493             notification => 'CHECKOUT',
1494         );
1495         if ($circulation_alert->is_enabled_for(\%conditions)) {
1496             SendCirculationAlert({
1497                 type     => 'CHECKOUT',
1498                 item     => $item,
1499                 borrower => $borrower,
1500                 branch   => $branch,
1501             });
1502         }
1503     }
1504
1505     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'itemnumber'})
1506         if C4::Context->preference("IssueLog");
1507   }
1508   return $issue;
1509 }
1510
1511 =head2 GetLoanLength
1512
1513   my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1514
1515 Get loan length for an itemtype, a borrower type and a branch
1516
1517 =cut
1518
1519 sub GetLoanLength {
1520     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1521     my $dbh = C4::Context->dbh;
1522     my $sth = $dbh->prepare(qq{
1523         SELECT issuelength, lengthunit, renewalperiod
1524         FROM issuingrules
1525         WHERE   categorycode=?
1526             AND itemtype=?
1527             AND branchcode=?
1528             AND issuelength IS NOT NULL
1529     });
1530
1531     # try to find issuelength & return the 1st available.
1532     # check with borrowertype, itemtype and branchcode, then without one of those parameters
1533     $sth->execute( $borrowertype, $itemtype, $branchcode );
1534     my $loanlength = $sth->fetchrow_hashref;
1535
1536     return $loanlength
1537       if defined($loanlength) && defined $loanlength->{issuelength};
1538
1539     $sth->execute( $borrowertype, '*', $branchcode );
1540     $loanlength = $sth->fetchrow_hashref;
1541     return $loanlength
1542       if defined($loanlength) && defined $loanlength->{issuelength};
1543
1544     $sth->execute( '*', $itemtype, $branchcode );
1545     $loanlength = $sth->fetchrow_hashref;
1546     return $loanlength
1547       if defined($loanlength) && defined $loanlength->{issuelength};
1548
1549     $sth->execute( '*', '*', $branchcode );
1550     $loanlength = $sth->fetchrow_hashref;
1551     return $loanlength
1552       if defined($loanlength) && defined $loanlength->{issuelength};
1553
1554     $sth->execute( $borrowertype, $itemtype, '*' );
1555     $loanlength = $sth->fetchrow_hashref;
1556     return $loanlength
1557       if defined($loanlength) && defined $loanlength->{issuelength};
1558
1559     $sth->execute( $borrowertype, '*', '*' );
1560     $loanlength = $sth->fetchrow_hashref;
1561     return $loanlength
1562       if defined($loanlength) && defined $loanlength->{issuelength};
1563
1564     $sth->execute( '*', $itemtype, '*' );
1565     $loanlength = $sth->fetchrow_hashref;
1566     return $loanlength
1567       if defined($loanlength) && defined $loanlength->{issuelength};
1568
1569     $sth->execute( '*', '*', '*' );
1570     $loanlength = $sth->fetchrow_hashref;
1571     return $loanlength
1572       if defined($loanlength) && defined $loanlength->{issuelength};
1573
1574     # if no rule is set => 0 day (hardcoded)
1575     return {
1576         issuelength => 0,
1577         renewalperiod => 0,
1578         lengthunit => 'days',
1579     };
1580
1581 }
1582
1583
1584 =head2 GetHardDueDate
1585
1586   my ($hardduedate,$hardduedatecompare) = &GetHardDueDate($borrowertype,$itemtype,branchcode)
1587
1588 Get the Hard Due Date and it's comparison for an itemtype, a borrower type and a branch
1589
1590 =cut
1591
1592 sub GetHardDueDate {
1593     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1594
1595     my $rule = GetIssuingRule( $borrowertype, $itemtype, $branchcode );
1596
1597     if ( defined( $rule ) ) {
1598         if ( $rule->{hardduedate} ) {
1599             return (dt_from_string($rule->{hardduedate}, 'iso'),$rule->{hardduedatecompare});
1600         } else {
1601             return (undef, undef);
1602         }
1603     }
1604 }
1605
1606 =head2 GetIssuingRule
1607
1608   my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1609
1610 FIXME - This is a copy-paste of GetLoanLength
1611 as a stop-gap.  Do not wish to change API for GetLoanLength 
1612 this close to release.
1613
1614 Get the issuing rule for an itemtype, a borrower type and a branch
1615 Returns a hashref from the issuingrules table.
1616
1617 =cut
1618
1619 sub GetIssuingRule {
1620     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1621     my $dbh = C4::Context->dbh;
1622     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=?"  );
1623     my $irule;
1624
1625     $sth->execute( $borrowertype, $itemtype, $branchcode );
1626     $irule = $sth->fetchrow_hashref;
1627     return $irule if defined($irule) ;
1628
1629     $sth->execute( $borrowertype, "*", $branchcode );
1630     $irule = $sth->fetchrow_hashref;
1631     return $irule if defined($irule) ;
1632
1633     $sth->execute( "*", $itemtype, $branchcode );
1634     $irule = $sth->fetchrow_hashref;
1635     return $irule if defined($irule) ;
1636
1637     $sth->execute( "*", "*", $branchcode );
1638     $irule = $sth->fetchrow_hashref;
1639     return $irule if defined($irule) ;
1640
1641     $sth->execute( $borrowertype, $itemtype, "*" );
1642     $irule = $sth->fetchrow_hashref;
1643     return $irule if defined($irule) ;
1644
1645     $sth->execute( $borrowertype, "*", "*" );
1646     $irule = $sth->fetchrow_hashref;
1647     return $irule if defined($irule) ;
1648
1649     $sth->execute( "*", $itemtype, "*" );
1650     $irule = $sth->fetchrow_hashref;
1651     return $irule if defined($irule) ;
1652
1653     $sth->execute( "*", "*", "*" );
1654     $irule = $sth->fetchrow_hashref;
1655     return $irule if defined($irule) ;
1656
1657     # if no rule matches,
1658     return;
1659 }
1660
1661 =head2 GetBranchBorrowerCircRule
1662
1663   my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1664
1665 Retrieves circulation rule attributes that apply to the given
1666 branch and patron category, regardless of item type.  
1667 The return value is a hashref containing the following key:
1668
1669 maxissueqty - maximum number of loans that a
1670 patron of the given category can have at the given
1671 branch.  If the value is undef, no limit.
1672
1673 maxonsiteissueqty - maximum of on-site checkouts that a
1674 patron of the given category can have at the given
1675 branch.  If the value is undef, no limit.
1676
1677 This will first check for a specific branch and
1678 category match from branch_borrower_circ_rules. 
1679
1680 If no rule is found, it will then check default_branch_circ_rules
1681 (same branch, default category).  If no rule is found,
1682 it will then check default_borrower_circ_rules (default 
1683 branch, same category), then failing that, default_circ_rules
1684 (default branch, default category).
1685
1686 If no rule has been found in the database, it will default to
1687 the buillt in rule:
1688
1689 maxissueqty - undef
1690 maxonsiteissueqty - undef
1691
1692 C<$branchcode> and C<$categorycode> should contain the
1693 literal branch code and patron category code, respectively - no
1694 wildcards.
1695
1696 =cut
1697
1698 sub GetBranchBorrowerCircRule {
1699     my ( $branchcode, $categorycode ) = @_;
1700
1701     my $rules;
1702     my $dbh = C4::Context->dbh();
1703     $rules = $dbh->selectrow_hashref( q|
1704         SELECT maxissueqty, maxonsiteissueqty
1705         FROM branch_borrower_circ_rules
1706         WHERE branchcode = ?
1707         AND   categorycode = ?
1708     |, {}, $branchcode, $categorycode ) ;
1709     return $rules if $rules;
1710
1711     # try same branch, default borrower category
1712     $rules = $dbh->selectrow_hashref( q|
1713         SELECT maxissueqty, maxonsiteissueqty
1714         FROM default_branch_circ_rules
1715         WHERE branchcode = ?
1716     |, {}, $branchcode ) ;
1717     return $rules if $rules;
1718
1719     # try default branch, same borrower category
1720     $rules = $dbh->selectrow_hashref( q|
1721         SELECT maxissueqty, maxonsiteissueqty
1722         FROM default_borrower_circ_rules
1723         WHERE categorycode = ?
1724     |, {}, $categorycode ) ;
1725     return $rules if $rules;
1726
1727     # try default branch, default borrower category
1728     $rules = $dbh->selectrow_hashref( q|
1729         SELECT maxissueqty, maxonsiteissueqty
1730         FROM default_circ_rules
1731     |, {} );
1732     return $rules if $rules;
1733
1734     # built-in default circulation rule
1735     return {
1736         maxissueqty => undef,
1737         maxonsiteissueqty => undef,
1738     };
1739 }
1740
1741 =head2 GetBranchItemRule
1742
1743   my $branch_item_rule = GetBranchItemRule($branchcode, $itemtype);
1744
1745 Retrieves circulation rule attributes that apply to the given
1746 branch and item type, regardless of patron category.
1747
1748 The return value is a hashref containing the following keys:
1749
1750 holdallowed => Hold policy for this branch and itemtype. Possible values:
1751   0: No holds allowed.
1752   1: Holds allowed only by patrons that have the same homebranch as the item.
1753   2: Holds allowed from any patron.
1754
1755 returnbranch => branch to which to return item.  Possible values:
1756   noreturn: do not return, let item remain where checked in (floating collections)
1757   homebranch: return to item's home branch
1758   holdingbranch: return to issuer branch
1759
1760 This searches branchitemrules in the following order:
1761
1762   * Same branchcode and itemtype
1763   * Same branchcode, itemtype '*'
1764   * branchcode '*', same itemtype
1765   * branchcode and itemtype '*'
1766
1767 Neither C<$branchcode> nor C<$itemtype> should be '*'.
1768
1769 =cut
1770
1771 sub GetBranchItemRule {
1772     my ( $branchcode, $itemtype ) = @_;
1773     my $dbh = C4::Context->dbh();
1774     my $result = {};
1775
1776     my @attempts = (
1777         ['SELECT holdallowed, returnbranch, hold_fulfillment_policy
1778             FROM branch_item_rules
1779             WHERE branchcode = ?
1780               AND itemtype = ?', $branchcode, $itemtype],
1781         ['SELECT holdallowed, returnbranch, hold_fulfillment_policy
1782             FROM default_branch_circ_rules
1783             WHERE branchcode = ?', $branchcode],
1784         ['SELECT holdallowed, returnbranch, hold_fulfillment_policy
1785             FROM default_branch_item_rules
1786             WHERE itemtype = ?', $itemtype],
1787         ['SELECT holdallowed, returnbranch, hold_fulfillment_policy
1788             FROM default_circ_rules'],
1789     );
1790
1791     foreach my $attempt (@attempts) {
1792         my ($query, @bind_params) = @{$attempt};
1793         my $search_result = $dbh->selectrow_hashref ( $query , {}, @bind_params )
1794           or next;
1795
1796         # Since branch/category and branch/itemtype use the same per-branch
1797         # defaults tables, we have to check that the key we want is set, not
1798         # just that a row was returned
1799         $result->{'holdallowed'}  = $search_result->{'holdallowed'}  unless ( defined $result->{'holdallowed'} );
1800         $result->{'hold_fulfillment_policy'} = $search_result->{'hold_fulfillment_policy'} unless ( defined $result->{'hold_fulfillment_policy'} );
1801         $result->{'returnbranch'} = $search_result->{'returnbranch'} unless ( defined $result->{'returnbranch'} );
1802     }
1803     
1804     # built-in default circulation rule
1805     $result->{'holdallowed'} = 2 unless ( defined $result->{'holdallowed'} );
1806     $result->{'hold_fulfillment_policy'} = 'any' unless ( defined $result->{'hold_fulfillment_policy'} );
1807     $result->{'returnbranch'} = 'homebranch' unless ( defined $result->{'returnbranch'} );
1808
1809     return $result;
1810 }
1811
1812 =head2 AddReturn
1813
1814   ($doreturn, $messages, $iteminformation, $borrower) =
1815       &AddReturn( $barcode, $branch [,$exemptfine] [,$dropbox] [,$returndate] );
1816
1817 Returns a book.
1818
1819 =over 4
1820
1821 =item C<$barcode> is the bar code of the book being returned.
1822
1823 =item C<$branch> is the code of the branch where the book is being returned.
1824
1825 =item C<$exemptfine> indicates that overdue charges for the item will be
1826 removed. Optional.
1827
1828 =item C<$dropbox> indicates that the check-in date is assumed to be
1829 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1830 overdue charges are applied and C<$dropbox> is true, the last charge
1831 will be removed.  This assumes that the fines accrual script has run
1832 for _today_. Optional.
1833
1834 =item C<$return_date> allows the default return date to be overridden
1835 by the given return date. Optional.
1836
1837 =back
1838
1839 C<&AddReturn> returns a list of four items:
1840
1841 C<$doreturn> is true iff the return succeeded.
1842
1843 C<$messages> is a reference-to-hash giving feedback on the operation.
1844 The keys of the hash are:
1845
1846 =over 4
1847
1848 =item C<BadBarcode>
1849
1850 No item with this barcode exists. The value is C<$barcode>.
1851
1852 =item C<NotIssued>
1853
1854 The book is not currently on loan. The value is C<$barcode>.
1855
1856 =item C<IsPermanent>
1857
1858 The book's home branch is a permanent collection. If you have borrowed
1859 this book, you are not allowed to return it. The value is the code for
1860 the book's home branch.
1861
1862 =item C<withdrawn>
1863
1864 This book has been withdrawn/cancelled. The value should be ignored.
1865
1866 =item C<Wrongbranch>
1867
1868 This book has was returned to the wrong branch.  The value is a hashref
1869 so that C<$messages->{Wrongbranch}->{Wrongbranch}> and C<$messages->{Wrongbranch}->{Rightbranch}>
1870 contain the branchcode of the incorrect and correct return library, respectively.
1871
1872 =item C<ResFound>
1873
1874 The item was reserved. The value is a reference-to-hash whose keys are
1875 fields from the reserves table of the Koha database, and
1876 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1877 either C<Waiting>, C<Reserved>, or 0.
1878
1879 =item C<WasReturned>
1880
1881 Value 1 if return is successful.
1882
1883 =item C<NeedsTransfer>
1884
1885 If AutomaticItemReturn is disabled, return branch is given as value of NeedsTransfer.
1886
1887 =back
1888
1889 C<$iteminformation> is a reference-to-hash, giving information about the
1890 returned item from the issues table.
1891
1892 C<$borrower> is a reference-to-hash, giving information about the
1893 patron who last borrowed the book.
1894
1895 =cut
1896
1897 sub AddReturn {
1898     my ( $barcode, $branch, $exemptfine, $dropbox, $return_date, $dropboxdate ) = @_;
1899
1900     if ($branch and not Koha::Libraries->find($branch)) {
1901         warn "AddReturn error: branch '$branch' not found.  Reverting to " . C4::Context->userenv->{'branch'};
1902         undef $branch;
1903     }
1904     $branch = C4::Context->userenv->{'branch'} unless $branch;  # we trust userenv to be a safe fallback/default
1905     my $messages;
1906     my $borrower;
1907     my $biblio;
1908     my $doreturn       = 1;
1909     my $validTransfert = 0;
1910     my $stat_type = 'return';
1911
1912     # get information on item
1913     my $itemnumber = GetItemnumberFromBarcode( $barcode );
1914     unless ($itemnumber) {
1915         return (0, { BadBarcode => $barcode }); # no barcode means no item or borrower.  bail out.
1916     }
1917     my $issue  = GetItemIssue($itemnumber);
1918     if ($issue and $issue->{borrowernumber}) {
1919         $borrower = C4::Members::GetMemberDetails($issue->{borrowernumber})
1920             or die "Data inconsistency: barcode $barcode (itemnumber:$itemnumber) claims to be issued to non-existent borrowernumber '$issue->{borrowernumber}'\n"
1921                 . Dumper($issue) . "\n";
1922     } else {
1923         $messages->{'NotIssued'} = $barcode;
1924         # even though item is not on loan, it may still be transferred;  therefore, get current branch info
1925         $doreturn = 0;
1926         # No issue, no borrowernumber.  ONLY if $doreturn, *might* you have a $borrower later.
1927         # Record this as a local use, instead of a return, if the RecordLocalUseOnReturn is on
1928         if (C4::Context->preference("RecordLocalUseOnReturn")) {
1929            $messages->{'LocalUse'} = 1;
1930            $stat_type = 'localuse';
1931         }
1932     }
1933
1934     my $item = GetItem($itemnumber) or die "GetItem($itemnumber) failed";
1935
1936     if ( $item->{'location'} eq 'PROC' ) {
1937         if ( C4::Context->preference("InProcessingToShelvingCart") ) {
1938             $item->{'location'} = 'CART';
1939         }
1940         else {
1941             $item->{location} = $item->{permanent_location};
1942         }
1943
1944         ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
1945     }
1946
1947         # full item data, but no borrowernumber or checkout info (no issue)
1948         # we know GetItem should work because GetItemnumberFromBarcode worked
1949     my $hbr = GetBranchItemRule($item->{'homebranch'}, $item->{'itype'})->{'returnbranch'} || "homebranch";
1950         # get the proper branch to which to return the item
1951     my $returnbranch = $item->{$hbr} || $branch ;
1952         # if $hbr was "noreturn" or any other non-item table value, then it should 'float' (i.e. stay at this branch)
1953
1954     my $borrowernumber = $borrower->{'borrowernumber'} || undef;    # we don't know if we had a borrower or not
1955
1956     my $yaml = C4::Context->preference('UpdateNotForLoanStatusOnCheckin');
1957     if ($yaml) {
1958         $yaml = "$yaml\n\n";  # YAML is anal on ending \n. Surplus does not hurt
1959         my $rules;
1960         eval { $rules = YAML::Load($yaml); };
1961         if ($@) {
1962             warn "Unable to parse UpdateNotForLoanStatusOnCheckin syspref : $@";
1963         }
1964         else {
1965             foreach my $key ( keys %$rules ) {
1966                 if ( $item->{notforloan} eq $key ) {
1967                     $messages->{'NotForLoanStatusUpdated'} = { from => $item->{notforloan}, to => $rules->{$key} };
1968                     ModItem( { notforloan => $rules->{$key} }, undef, $itemnumber );
1969                     last;
1970                 }
1971             }
1972         }
1973     }
1974
1975
1976     # check if the book is in a permanent collection....
1977     # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1978     if ( $returnbranch ) {
1979         my $branches = GetBranches();    # a potentially expensive call for a non-feature.
1980         $branches->{$returnbranch}->{PE} and $messages->{'IsPermanent'} = $returnbranch;
1981     }
1982
1983     # check if the return is allowed at this branch
1984     my ($returnallowed, $message) = CanBookBeReturned($item, $branch);
1985     unless ($returnallowed){
1986         $messages->{'Wrongbranch'} = {
1987             Wrongbranch => $branch,
1988             Rightbranch => $message
1989         };
1990         $doreturn = 0;
1991         return ( $doreturn, $messages, $issue, $borrower );
1992     }
1993
1994     if ( $item->{'withdrawn'} ) { # book has been cancelled
1995         $messages->{'withdrawn'} = 1;
1996         $doreturn = 0 if C4::Context->preference("BlockReturnOfWithdrawnItems");
1997     }
1998
1999     # case of a return of document (deal with issues and holdingbranch)
2000     my $today = DateTime->now( time_zone => C4::Context->tz() );
2001
2002     if ($doreturn) {
2003         my $datedue = $issue->{date_due};
2004         $borrower or warn "AddReturn without current borrower";
2005                 my $circControlBranch;
2006         if ($dropbox) {
2007             # define circControlBranch only if dropbox mode is set
2008             # don't allow dropbox mode to create an invalid entry in issues (issuedate > today)
2009             # FIXME: check issuedate > returndate, factoring in holidays
2010
2011             $circControlBranch = _GetCircControlBranch($item,$borrower);
2012             $issue->{'overdue'} = DateTime->compare($issue->{'date_due'}, $dropboxdate ) == -1 ? 1 : 0;
2013         }
2014
2015         if ($borrowernumber) {
2016             if ( ( C4::Context->preference('CalculateFinesOnReturn') && $issue->{'overdue'} ) || $return_date ) {
2017                 # we only need to calculate and change the fines if we want to do that on return
2018                 # Should be on for hourly loans
2019                 my $control = C4::Context->preference('CircControl');
2020                 my $control_branchcode =
2021                     ( $control eq 'ItemHomeLibrary' ) ? $item->{homebranch}
2022                   : ( $control eq 'PatronLibrary' )   ? $borrower->{branchcode}
2023                   :                                     $issue->{branchcode};
2024
2025                 my $date_returned =
2026                   $return_date ? dt_from_string($return_date) : $today;
2027
2028                 my ( $amount, $type, $unitcounttotal ) =
2029                   C4::Overdues::CalcFine( $item, $borrower->{categorycode},
2030                     $control_branchcode, $datedue, $date_returned );
2031
2032                 $type ||= q{};
2033
2034                 if ( C4::Context->preference('finesMode') eq 'production' ) {
2035                     if ( $amount > 0 ) {
2036                         C4::Overdues::UpdateFine(
2037                             {
2038                                 issue_id       => $issue->{issue_id},
2039                                 itemnumber     => $issue->{itemnumber},
2040                                 borrowernumber => $issue->{borrowernumber},
2041                                 amount         => $amount,
2042                                 type           => $type,
2043                                 due            => output_pref($datedue),
2044                             }
2045                         );
2046                     }
2047                     elsif ($return_date) {
2048
2049                         # Backdated returns may have fines that shouldn't exist,
2050                         # so in this case, we need to drop those fines to 0
2051
2052                         C4::Overdues::UpdateFine(
2053                             {
2054                                 issue_id       => $issue->{issue_id},
2055                                 itemnumber     => $issue->{itemnumber},
2056                                 borrowernumber => $issue->{borrowernumber},
2057                                 amount         => 0,
2058                                 type           => $type,
2059                                 due            => output_pref($datedue),
2060                             }
2061                         );
2062                     }
2063                 }
2064             }
2065
2066             eval {
2067                 MarkIssueReturned( $borrowernumber, $item->{'itemnumber'},
2068                     $circControlBranch, $return_date, $borrower->{'privacy'} );
2069             };
2070             if ( $@ ) {
2071                 $messages->{'Wrongbranch'} = {
2072                     Wrongbranch => $branch,
2073                     Rightbranch => $message
2074                 };
2075                 carp $@;
2076                 return ( 0, { WasReturned => 0 }, $issue, $borrower );
2077             }
2078
2079             # FIXME is the "= 1" right?  This could be the borrower hash.
2080             $messages->{'WasReturned'} = 1;
2081
2082         }
2083
2084         ModItem({ onloan => undef }, $issue->{'biblionumber'}, $item->{'itemnumber'});
2085     }
2086
2087     # the holdingbranch is updated if the document is returned to another location.
2088     # this is always done regardless of whether the item was on loan or not
2089     if ($item->{'holdingbranch'} ne $branch) {
2090         UpdateHoldingbranch($branch, $item->{'itemnumber'});
2091         $item->{'holdingbranch'} = $branch; # update item data holdingbranch too
2092     }
2093     ModDateLastSeen( $item->{'itemnumber'} );
2094
2095     # check if we have a transfer for this document
2096     my ($datesent,$frombranch,$tobranch) = GetTransfers( $item->{'itemnumber'} );
2097
2098     # if we have a transfer to do, we update the line of transfers with the datearrived
2099     my $is_in_rotating_collection = C4::RotatingCollections::isItemInAnyCollection( $item->{'itemnumber'} );
2100     if ($datesent) {
2101         if ( $tobranch eq $branch ) {
2102             my $sth = C4::Context->dbh->prepare(
2103                 "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
2104             );
2105             $sth->execute( $item->{'itemnumber'} );
2106             # if we have a reservation with valid transfer, we can set it's status to 'W'
2107             ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
2108             C4::Reserves::ModReserveStatus($item->{'itemnumber'}, 'W');
2109         } else {
2110             $messages->{'WrongTransfer'}     = $tobranch;
2111             $messages->{'WrongTransferItem'} = $item->{'itemnumber'};
2112         }
2113         $validTransfert = 1;
2114     } else {
2115         ShelfToCart( $item->{'itemnumber'} ) if ( C4::Context->preference("ReturnToShelvingCart") );
2116     }
2117
2118     # fix up the accounts.....
2119     if ( $item->{'itemlost'} ) {
2120         $messages->{'WasLost'} = 1;
2121
2122         if ( C4::Context->preference('RefundLostItemFeeOnReturn' ) ) {
2123             _FixAccountForLostAndReturned($item->{'itemnumber'}, $borrowernumber, $barcode);    # can tolerate undef $borrowernumber
2124             $messages->{'LostItemFeeRefunded'} = 1;
2125         }
2126     }
2127
2128     # fix up the overdues in accounts...
2129     if ($borrowernumber) {
2130         my $fix = _FixOverduesOnReturn($borrowernumber, $item->{itemnumber}, $exemptfine, $dropbox);
2131         defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $item->{itemnumber}...) failed!";  # zero is OK, check defined
2132         
2133         if ( $issue->{overdue} && $issue->{date_due} ) {
2134         # fix fine days
2135             $today = $dropboxdate if $dropbox;
2136             my ($debardate,$reminder) = _debar_user_on_return( $borrower, $item, $issue->{date_due}, $today );
2137             if ($reminder){
2138                 $messages->{'PrevDebarred'} = $debardate;
2139             } else {
2140                 $messages->{'Debarred'} = $debardate if $debardate;
2141             }
2142         # there's no overdue on the item but borrower had been previously debarred
2143         } elsif ( $issue->{date_due} and $borrower->{'debarred'} ) {
2144              if ( $borrower->{debarred} eq "9999-12-31") {
2145                 $messages->{'ForeverDebarred'} = $borrower->{'debarred'};
2146              } else {
2147                   my $borrower_debar_dt = dt_from_string( $borrower->{debarred} );
2148                   $borrower_debar_dt->truncate(to => 'day');
2149                   my $today_dt = $today->clone()->truncate(to => 'day');
2150                   if ( DateTime->compare( $borrower_debar_dt, $today_dt ) != -1 ) {
2151                       $messages->{'PrevDebarred'} = $borrower->{'debarred'};
2152                   }
2153              }
2154         }
2155     }
2156
2157     # find reserves.....
2158     # if we don't have a reserve with the status W, we launch the Checkreserves routine
2159     my ($resfound, $resrec);
2160     my $lookahead= C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2161     ($resfound, $resrec, undef) = C4::Reserves::CheckReserves( $item->{'itemnumber'}, undef, $lookahead ) unless ( $item->{'withdrawn'} );
2162     if ($resfound) {
2163           $resrec->{'ResFound'} = $resfound;
2164         $messages->{'ResFound'} = $resrec;
2165     }
2166
2167     # Record the fact that this book was returned.
2168     # FIXME itemtype should record item level type, not bibliolevel type
2169     UpdateStats({
2170                 branch => $branch,
2171                 type => $stat_type,
2172                 itemnumber => $item->{'itemnumber'},
2173                 itemtype => $biblio->{'itemtype'},
2174                 borrowernumber => $borrowernumber,
2175                 ccode => $item->{'ccode'}}
2176     );
2177
2178     # Send a check-in slip. # NOTE: borrower may be undef.  probably shouldn't try to send messages then.
2179     my $circulation_alert = 'C4::ItemCirculationAlertPreference';
2180     my %conditions = (
2181         branchcode   => $branch,
2182         categorycode => $borrower->{categorycode},
2183         item_type    => $item->{itype},
2184         notification => 'CHECKIN',
2185     );
2186     if ($doreturn && $circulation_alert->is_enabled_for(\%conditions)) {
2187         SendCirculationAlert({
2188             type     => 'CHECKIN',
2189             item     => $item,
2190             borrower => $borrower,
2191             branch   => $branch,
2192         });
2193     }
2194     
2195     logaction("CIRCULATION", "RETURN", $borrowernumber, $item->{'itemnumber'})
2196         if C4::Context->preference("ReturnLog");
2197     
2198     # Remove any OVERDUES related debarment if the borrower has no overdues
2199     if ( $borrowernumber
2200       && $borrower->{'debarred'}
2201       && C4::Context->preference('AutoRemoveOverduesRestrictions')
2202       && !C4::Members::HasOverdues( $borrowernumber )
2203       && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
2204     ) {
2205         DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
2206     }
2207
2208     # Transfer to returnbranch if Automatic transfer set or append message NeedsTransfer
2209     if (!$is_in_rotating_collection && ($doreturn or $messages->{'NotIssued'}) and !$resfound and ($branch ne $returnbranch) and not $messages->{'WrongTransfer'}){
2210         if  (C4::Context->preference("AutomaticItemReturn"    ) or
2211             (C4::Context->preference("UseBranchTransferLimits") and
2212              ! IsBranchTransferAllowed($branch, $returnbranch, $item->{C4::Context->preference("BranchTransferLimitsType")} )
2213            )) {
2214             $debug and warn sprintf "about to call ModItemTransfer(%s, %s, %s)", $item->{'itemnumber'},$branch, $returnbranch;
2215             $debug and warn "item: " . Dumper($item);
2216             ModItemTransfer($item->{'itemnumber'}, $branch, $returnbranch);
2217             $messages->{'WasTransfered'} = 1;
2218         } else {
2219             $messages->{'NeedsTransfer'} = $returnbranch;
2220         }
2221     }
2222
2223     return ( $doreturn, $messages, $issue, $borrower );
2224 }
2225
2226 =head2 MarkIssueReturned
2227
2228   MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy);
2229
2230 Unconditionally marks an issue as being returned by
2231 moving the C<issues> row to C<old_issues> and
2232 setting C<returndate> to the current date, or
2233 the last non-holiday date of the branccode specified in
2234 C<dropbox_branch> .  Assumes you've already checked that 
2235 it's safe to do this, i.e. last non-holiday > issuedate.
2236
2237 if C<$returndate> is specified (in iso format), it is used as the date
2238 of the return. It is ignored when a dropbox_branch is passed in.
2239
2240 C<$privacy> contains the privacy parameter. If the patron has set privacy to 2,
2241 the old_issue is immediately anonymised
2242
2243 Ideally, this function would be internal to C<C4::Circulation>,
2244 not exported, but it is currently needed by one 
2245 routine in C<C4::Accounts>.
2246
2247 =cut
2248
2249 sub MarkIssueReturned {
2250     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate, $privacy ) = @_;
2251
2252     my $anonymouspatron;
2253     if ( $privacy == 2 ) {
2254         # The default of 0 will not work due to foreign key constraints
2255         # The anonymisation will fail if AnonymousPatron is not a valid entry
2256         # We need to check if the anonymous patron exist, Koha will fail loudly if it does not
2257         # Note that a warning should appear on the about page (System information tab).
2258         $anonymouspatron = C4::Context->preference('AnonymousPatron');
2259         die "Fatal error: the patron ($borrowernumber) has requested their circulation history be anonymized on check-in, but the AnonymousPatron system preference is empty or not set correctly."
2260             unless C4::Members::GetMember( borrowernumber => $anonymouspatron );
2261     }
2262     my $dbh   = C4::Context->dbh;
2263     my $query = 'UPDATE issues SET returndate=';
2264     my @bind;
2265     if ($dropbox_branch) {
2266         my $calendar = Koha::Calendar->new( branchcode => $dropbox_branch );
2267         my $dropboxdate = $calendar->addDate( DateTime->now( time_zone => C4::Context->tz), -1 );
2268         $query .= ' ? ';
2269         push @bind, $dropboxdate->strftime('%Y-%m-%d %H:%M');
2270     } elsif ($returndate) {
2271         $query .= ' ? ';
2272         push @bind, $returndate;
2273     } else {
2274         $query .= ' now() ';
2275     }
2276     $query .= ' WHERE  borrowernumber = ?  AND itemnumber = ?';
2277     push @bind, $borrowernumber, $itemnumber;
2278     # FIXME transaction
2279     my $sth_upd  = $dbh->prepare($query);
2280     $sth_upd->execute(@bind);
2281     my $sth_copy = $dbh->prepare('INSERT INTO old_issues SELECT * FROM issues
2282                                   WHERE borrowernumber = ?
2283                                   AND itemnumber = ?');
2284     $sth_copy->execute($borrowernumber, $itemnumber);
2285     # anonymise patron checkout immediately if $privacy set to 2 and AnonymousPatron is set to a valid borrowernumber
2286     if ( $privacy == 2) {
2287         my $sth_ano = $dbh->prepare("UPDATE old_issues SET borrowernumber=?
2288                                   WHERE borrowernumber = ?
2289                                   AND itemnumber = ?");
2290        $sth_ano->execute($anonymouspatron, $borrowernumber, $itemnumber);
2291     }
2292     my $sth_del  = $dbh->prepare("DELETE FROM issues
2293                                   WHERE borrowernumber = ?
2294                                   AND itemnumber = ?");
2295     $sth_del->execute($borrowernumber, $itemnumber);
2296
2297     ModItem( { 'onloan' => undef }, undef, $itemnumber );
2298
2299     if ( C4::Context->preference('StoreLastBorrower') ) {
2300         my $item = Koha::Items->find( $itemnumber );
2301         my $patron = Koha::Patrons->find( $borrowernumber );
2302         $item->last_returned_by( $patron );
2303     }
2304 }
2305
2306 =head2 _debar_user_on_return
2307
2308     _debar_user_on_return($borrower, $item, $datedue, today);
2309
2310 C<$borrower> borrower hashref
2311
2312 C<$item> item hashref
2313
2314 C<$datedue> date due DateTime object
2315
2316 C<$today> DateTime object representing the return time
2317
2318 Internal function, called only by AddReturn that calculates and updates
2319  the user fine days, and debars him if necessary.
2320
2321 Should only be called for overdue returns
2322
2323 =cut
2324
2325 sub _debar_user_on_return {
2326     my ( $borrower, $item, $dt_due, $dt_today ) = @_;
2327
2328     my $branchcode = _GetCircControlBranch( $item, $borrower );
2329
2330     my $circcontrol = C4::Context->preference('CircControl');
2331     my $issuingrule =
2332       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2333     my $finedays = $issuingrule->{finedays};
2334     my $unit     = $issuingrule->{lengthunit};
2335     my $chargeable_units = C4::Overdues::get_chargeable_units($unit, $dt_due, $dt_today, $branchcode);
2336
2337     if ($finedays) {
2338
2339         # finedays is in days, so hourly loans must multiply by 24
2340         # thus 1 hour late equals 1 day suspension * finedays rate
2341         $finedays = $finedays * 24 if ( $unit eq 'hours' );
2342
2343         # grace period is measured in the same units as the loan
2344         my $grace =
2345           DateTime::Duration->new( $unit => $issuingrule->{firstremind} );
2346
2347         my $deltadays = DateTime::Duration->new(
2348             days => $chargeable_units
2349         );
2350         if ( $deltadays->subtract($grace)->is_positive() ) {
2351             my $suspension_days = $deltadays * $finedays;
2352
2353             # If the max suspension days is < than the suspension days
2354             # the suspension days is limited to this maximum period.
2355             my $max_sd = $issuingrule->{maxsuspensiondays};
2356             if ( defined $max_sd ) {
2357                 $max_sd = DateTime::Duration->new( days => $max_sd );
2358                 $suspension_days = $max_sd
2359                   if DateTime::Duration->compare( $max_sd, $suspension_days ) < 0;
2360             }
2361
2362             my $new_debar_dt =
2363               $dt_today->clone()->add_duration( $suspension_days );
2364
2365             Koha::Patron::Debarments::AddUniqueDebarment({
2366                 borrowernumber => $borrower->{borrowernumber},
2367                 expiration     => $new_debar_dt->ymd(),
2368                 type           => 'SUSPENSION',
2369             });
2370             # if borrower was already debarred but does not get an extra debarment
2371             if ( $borrower->{debarred} eq Koha::Patron::Debarments::IsDebarred($borrower->{borrowernumber}) ) {
2372                     return ($borrower->{debarred},1);
2373             }
2374             return $new_debar_dt->ymd();
2375         }
2376     }
2377     return;
2378 }
2379
2380 =head2 _FixOverduesOnReturn
2381
2382    &_FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
2383
2384 C<$brn> borrowernumber
2385
2386 C<$itm> itemnumber
2387
2388 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
2389 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
2390
2391 Internal function, called only by AddReturn
2392
2393 =cut
2394
2395 sub _FixOverduesOnReturn {
2396     my ($borrowernumber, $item);
2397     unless ($borrowernumber = shift) {
2398         warn "_FixOverduesOnReturn() not supplied valid borrowernumber";
2399         return;
2400     }
2401     unless ($item = shift) {
2402         warn "_FixOverduesOnReturn() not supplied valid itemnumber";
2403         return;
2404     }
2405     my ($exemptfine, $dropbox) = @_;
2406     my $dbh = C4::Context->dbh;
2407
2408     # check for overdue fine
2409     my $sth = $dbh->prepare(
2410 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
2411     );
2412     $sth->execute( $borrowernumber, $item );
2413
2414     # alter fine to show that the book has been returned
2415     my $data = $sth->fetchrow_hashref;
2416     return 0 unless $data;    # no warning, there's just nothing to fix
2417
2418     my $uquery;
2419     my @bind = ($data->{'accountlines_id'});
2420     if ($exemptfine) {
2421         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
2422         if (C4::Context->preference("FinesLog")) {
2423             &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
2424         }
2425     } elsif ($dropbox && $data->{lastincrement}) {
2426         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
2427         my $amt = $data->{amount} - $data->{lastincrement} ;
2428         if (C4::Context->preference("FinesLog")) {
2429             &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
2430         }
2431          $uquery = "update accountlines set accounttype='F' ";
2432          if($outstanding  >= 0 && $amt >=0) {
2433             $uquery .= ", amount = ? , amountoutstanding=? ";
2434             unshift @bind, ($amt, $outstanding) ;
2435         }
2436     } else {
2437         $uquery = "update accountlines set accounttype='F' ";
2438     }
2439     $uquery .= " where (accountlines_id = ?)";
2440     my $usth = $dbh->prepare($uquery);
2441     return $usth->execute(@bind);
2442 }
2443
2444 =head2 _FixAccountForLostAndReturned
2445
2446   &_FixAccountForLostAndReturned($itemnumber, [$borrowernumber, $barcode]);
2447
2448 Calculates the charge for a book lost and returned.
2449
2450 Internal function, not exported, called only by AddReturn.
2451
2452 FIXME: This function reflects how inscrutable fines logic is.  Fix both.
2453 FIXME: Give a positive return value on success.  It might be the $borrowernumber who received credit, or the amount forgiven.
2454
2455 =cut
2456
2457 sub _FixAccountForLostAndReturned {
2458     my $itemnumber     = shift or return;
2459     my $borrowernumber = @_ ? shift : undef;
2460     my $item_id        = @_ ? shift : $itemnumber;  # Send the barcode if you want that logged in the description
2461     my $dbh = C4::Context->dbh;
2462     # check for charge made for lost book
2463     my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE itemnumber = ? AND accounttype IN ('L', 'Rep', 'W') ORDER BY date DESC, accountno DESC");
2464     $sth->execute($itemnumber);
2465     my $data = $sth->fetchrow_hashref;
2466     $data or return;    # bail if there is nothing to do
2467     $data->{accounttype} eq 'W' and return;    # Written off
2468
2469     # writeoff this amount
2470     my $offset;
2471     my $amount = $data->{'amount'};
2472     my $acctno = $data->{'accountno'};
2473     my $amountleft;                                             # Starts off undef/zero.
2474     if ($data->{'amountoutstanding'} == $amount) {
2475         $offset     = $data->{'amount'};
2476         $amountleft = 0;                                        # Hey, it's zero here, too.
2477     } else {
2478         $offset     = $amount - $data->{'amountoutstanding'};   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2479         $amountleft = $data->{'amountoutstanding'} - $amount;   # Um, isn't this the same as ZERO?  We just tested those two things are ==
2480     }
2481     my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
2482         WHERE (accountlines_id = ?)");
2483     $usth->execute($data->{'accountlines_id'});      # We might be adjusting an account for some OTHER borrowernumber now.  Not the one we passed in.
2484     #check if any credit is left if so writeoff other accounts
2485     my $nextaccntno = getnextacctno($data->{'borrowernumber'});
2486     $amountleft *= -1 if ($amountleft < 0);
2487     if ($amountleft > 0) {
2488         my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
2489                             AND (amountoutstanding >0) ORDER BY date");     # might want to order by amountoustanding ASC (pay smallest first)
2490         $msth->execute($data->{'borrowernumber'});
2491         # offset transactions
2492         my $newamtos;
2493         my $accdata;
2494         while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
2495             if ($accdata->{'amountoutstanding'} < $amountleft) {
2496                 $newamtos = 0;
2497                 $amountleft -= $accdata->{'amountoutstanding'};
2498             }  else {
2499                 $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
2500                 $amountleft = 0;
2501             }
2502             my $thisacct = $accdata->{'accountlines_id'};
2503             # FIXME: move prepares outside while loop!
2504             my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
2505                     WHERE (accountlines_id = ?)");
2506             $usth->execute($newamtos,$thisacct);
2507             $usth = $dbh->prepare("INSERT INTO accountoffsets
2508                 (borrowernumber, accountno, offsetaccount,  offsetamount)
2509                 VALUES
2510                 (?,?,?,?)");
2511             $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
2512         }
2513     }
2514     $amountleft *= -1 if ($amountleft > 0);
2515     my $desc = "Item Returned " . $item_id;
2516     $usth = $dbh->prepare("INSERT INTO accountlines
2517         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
2518         VALUES (?,?,now(),?,?,'CR',?)");
2519     $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
2520     if ($borrowernumber) {
2521         # FIXME: same as query above.  use 1 sth for both
2522         $usth = $dbh->prepare("INSERT INTO accountoffsets
2523             (borrowernumber, accountno, offsetaccount,  offsetamount)
2524             VALUES (?,?,?,?)");
2525         $usth->execute($borrowernumber, $data->{'accountno'}, $nextaccntno, $offset);
2526     }
2527     ModItem({ paidfor => '' }, undef, $itemnumber);
2528     return;
2529 }
2530
2531 =head2 _GetCircControlBranch
2532
2533    my $circ_control_branch = _GetCircControlBranch($iteminfos, $borrower);
2534
2535 Internal function : 
2536
2537 Return the library code to be used to determine which circulation
2538 policy applies to a transaction.  Looks up the CircControl and
2539 HomeOrHoldingBranch system preferences.
2540
2541 C<$iteminfos> is a hashref to iteminfo. Only {homebranch or holdingbranch} is used.
2542
2543 C<$borrower> is a hashref to borrower. Only {branchcode} is used.
2544
2545 =cut
2546
2547 sub _GetCircControlBranch {
2548     my ($item, $borrower) = @_;
2549     my $circcontrol = C4::Context->preference('CircControl');
2550     my $branch;
2551
2552     if ($circcontrol eq 'PickupLibrary' and (C4::Context->userenv and C4::Context->userenv->{'branch'}) ) {
2553         $branch= C4::Context->userenv->{'branch'};
2554     } elsif ($circcontrol eq 'PatronLibrary') {
2555         $branch=$borrower->{branchcode};
2556     } else {
2557         my $branchfield = C4::Context->preference('HomeOrHoldingBranch') || 'homebranch';
2558         $branch = $item->{$branchfield};
2559         # default to item home branch if holdingbranch is used
2560         # and is not defined
2561         if (!defined($branch) && $branchfield eq 'holdingbranch') {
2562             $branch = $item->{homebranch};
2563         }
2564     }
2565     return $branch;
2566 }
2567
2568
2569
2570
2571
2572
2573 =head2 GetItemIssue
2574
2575   $issue = &GetItemIssue($itemnumber);
2576
2577 Returns patron currently having a book, or undef if not checked out.
2578
2579 C<$itemnumber> is the itemnumber.
2580
2581 C<$issue> is a hashref of the row from the issues table.
2582
2583 =cut
2584
2585 sub GetItemIssue {
2586     my ($itemnumber) = @_;
2587     return unless $itemnumber;
2588     my $sth = C4::Context->dbh->prepare(
2589         "SELECT items.*, issues.*
2590         FROM issues
2591         LEFT JOIN items ON issues.itemnumber=items.itemnumber
2592         WHERE issues.itemnumber=?");
2593     $sth->execute($itemnumber);
2594     my $data = $sth->fetchrow_hashref;
2595     return unless $data;
2596     $data->{issuedate_sql} = $data->{issuedate};
2597     $data->{date_due_sql} = $data->{date_due};
2598     $data->{issuedate} = dt_from_string($data->{issuedate}, 'sql');
2599     $data->{issuedate}->truncate(to => 'minute');
2600     $data->{date_due} = dt_from_string($data->{date_due}, 'sql');
2601     $data->{date_due}->truncate(to => 'minute');
2602     my $dt = DateTime->now( time_zone => C4::Context->tz)->truncate( to => 'minute');
2603     $data->{'overdue'} = DateTime->compare($data->{'date_due'}, $dt ) == -1 ? 1 : 0;
2604     return $data;
2605 }
2606
2607 =head2 GetOpenIssue
2608
2609   $issue = GetOpenIssue( $itemnumber );
2610
2611 Returns the row from the issues table if the item is currently issued, undef if the item is not currently issued
2612
2613 C<$itemnumber> is the item's itemnumber
2614
2615 Returns a hashref
2616
2617 =cut
2618
2619 sub GetOpenIssue {
2620   my ( $itemnumber ) = @_;
2621   return unless $itemnumber;
2622   my $dbh = C4::Context->dbh;  
2623   my $sth = $dbh->prepare( "SELECT * FROM issues WHERE itemnumber = ? AND returndate IS NULL" );
2624   $sth->execute( $itemnumber );
2625   return $sth->fetchrow_hashref();
2626
2627 }
2628
2629 =head2 GetIssues
2630
2631     $issues = GetIssues({});    # return all issues!
2632     $issues = GetIssues({ borrowernumber => $borrowernumber, biblionumber => $biblionumber });
2633
2634 Returns all pending issues that match given criteria.
2635 Returns a arrayref or undef if an error occurs.
2636
2637 Allowed criteria are:
2638
2639 =over 2
2640
2641 =item * borrowernumber
2642
2643 =item * biblionumber
2644
2645 =item * itemnumber
2646
2647 =back
2648
2649 =cut
2650
2651 sub GetIssues {
2652     my ($criteria) = @_;
2653
2654     # Build filters
2655     my @filters;
2656     my @allowed = qw(borrowernumber biblionumber itemnumber);
2657     foreach (@allowed) {
2658         if (defined $criteria->{$_}) {
2659             push @filters, {
2660                 field => $_,
2661                 value => $criteria->{$_},
2662             };
2663         }
2664     }
2665
2666     # Do we need to join other tables ?
2667     my %join;
2668     if (defined $criteria->{biblionumber}) {
2669         $join{items} = 1;
2670     }
2671
2672     # Build SQL query
2673     my $where = '';
2674     if (@filters) {
2675         $where = "WHERE " . join(' AND ', map { "$_->{field} = ?" } @filters);
2676     }
2677     my $query = q{
2678         SELECT issues.*
2679         FROM issues
2680     };
2681     if (defined $join{items}) {
2682         $query .= q{
2683             LEFT JOIN items ON (issues.itemnumber = items.itemnumber)
2684         };
2685     }
2686     $query .= $where;
2687
2688     # Execute SQL query
2689     my $dbh = C4::Context->dbh;
2690     my $sth = $dbh->prepare($query);
2691     my $rv = $sth->execute(map { $_->{value} } @filters);
2692
2693     return $rv ? $sth->fetchall_arrayref({}) : undef;
2694 }
2695
2696 =head2 GetItemIssues
2697
2698   $issues = &GetItemIssues($itemnumber, $history);
2699
2700 Returns patrons that have issued a book
2701
2702 C<$itemnumber> is the itemnumber
2703 C<$history> is false if you just want the current "issuer" (if any)
2704 and true if you want issues history from old_issues also.
2705
2706 Returns reference to an array of hashes
2707
2708 =cut
2709
2710 sub GetItemIssues {
2711     my ( $itemnumber, $history ) = @_;
2712     
2713     my $today = DateTime->now( time_zome => C4::Context->tz);  # get today date
2714     $today->truncate( to => 'minute' );
2715     my $sql = "SELECT * FROM issues
2716               JOIN borrowers USING (borrowernumber)
2717               JOIN items     USING (itemnumber)
2718               WHERE issues.itemnumber = ? ";
2719     if ($history) {
2720         $sql .= "UNION ALL
2721                  SELECT * FROM old_issues
2722                  LEFT JOIN borrowers USING (borrowernumber)
2723                  JOIN items USING (itemnumber)
2724                  WHERE old_issues.itemnumber = ? ";
2725     }
2726     $sql .= "ORDER BY date_due DESC";
2727     my $sth = C4::Context->dbh->prepare($sql);
2728     if ($history) {
2729         $sth->execute($itemnumber, $itemnumber);
2730     } else {
2731         $sth->execute($itemnumber);
2732     }
2733     my $results = $sth->fetchall_arrayref({});
2734     foreach (@$results) {
2735         my $date_due = dt_from_string($_->{date_due},'sql');
2736         $date_due->truncate( to => 'minute' );
2737
2738         $_->{overdue} = (DateTime->compare($date_due, $today) == -1) ? 1 : 0;
2739     }
2740     return $results;
2741 }
2742
2743 =head2 GetBiblioIssues
2744
2745   $issues = GetBiblioIssues($biblionumber);
2746
2747 this function get all issues from a biblionumber.
2748
2749 Return:
2750 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
2751 tables issues and the firstname,surname & cardnumber from borrowers.
2752
2753 =cut
2754
2755 sub GetBiblioIssues {
2756     my $biblionumber = shift;
2757     return unless $biblionumber;
2758     my $dbh   = C4::Context->dbh;
2759     my $query = "
2760         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2761         FROM issues
2762             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
2763             LEFT JOIN items ON issues.itemnumber = items.itemnumber
2764             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2765             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2766         WHERE biblio.biblionumber = ?
2767         UNION ALL
2768         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
2769         FROM old_issues
2770             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
2771             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
2772             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
2773             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
2774         WHERE biblio.biblionumber = ?
2775         ORDER BY timestamp
2776     ";
2777     my $sth = $dbh->prepare($query);
2778     $sth->execute($biblionumber, $biblionumber);
2779
2780     my @issues;
2781     while ( my $data = $sth->fetchrow_hashref ) {
2782         push @issues, $data;
2783     }
2784     return \@issues;
2785 }
2786
2787 =head2 GetUpcomingDueIssues
2788
2789   my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
2790
2791 =cut
2792
2793 sub GetUpcomingDueIssues {
2794     my $params = shift;
2795
2796     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
2797     my $dbh = C4::Context->dbh;
2798
2799     my $statement = <<END_SQL;
2800 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due, branches.branchemail
2801 FROM issues 
2802 LEFT JOIN items USING (itemnumber)
2803 LEFT OUTER JOIN branches USING (branchcode)
2804 WHERE returndate is NULL
2805 HAVING days_until_due >= 0 AND days_until_due <= ?
2806 END_SQL
2807
2808     my @bind_parameters = ( $params->{'days_in_advance'} );
2809     
2810     my $sth = $dbh->prepare( $statement );
2811     $sth->execute( @bind_parameters );
2812     my $upcoming_dues = $sth->fetchall_arrayref({});
2813
2814     return $upcoming_dues;
2815 }
2816
2817 =head2 CanBookBeRenewed
2818
2819   ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
2820
2821 Find out whether a borrowed item may be renewed.
2822
2823 C<$borrowernumber> is the borrower number of the patron who currently
2824 has the item on loan.
2825
2826 C<$itemnumber> is the number of the item to renew.
2827
2828 C<$override_limit>, if supplied with a true value, causes
2829 the limit on the number of times that the loan can be renewed
2830 (as controlled by the item type) to be ignored. Overriding also allows
2831 to renew sooner than "No renewal before" and to manually renew loans
2832 that are automatically renewed.
2833
2834 C<$CanBookBeRenewed> returns a true value if the item may be renewed. The
2835 item must currently be on loan to the specified borrower; renewals
2836 must be allowed for the item's type; and the borrower must not have
2837 already renewed the loan. $error will contain the reason the renewal can not proceed
2838
2839 =cut
2840
2841 sub CanBookBeRenewed {
2842     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
2843
2844     my $dbh    = C4::Context->dbh;
2845     my $renews = 1;
2846
2847     my $item      = GetItem($itemnumber)      or return ( 0, 'no_item' );
2848     my $itemissue = GetItemIssue($itemnumber) or return ( 0, 'no_checkout' );
2849     return ( 0, 'onsite_checkout' ) if $itemissue->{onsite_checkout};
2850
2851     $borrowernumber ||= $itemissue->{borrowernumber};
2852     my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber )
2853       or return;
2854
2855     my ( $resfound, $resrec, undef ) = C4::Reserves::CheckReserves($itemnumber);
2856
2857     # This item can fill one or more unfilled reserve, can those unfilled reserves
2858     # all be filled by other available items?
2859     if ( $resfound
2860         && C4::Context->preference('AllowRenewalIfOtherItemsAvailable') )
2861     {
2862         my $schema = Koha::Database->new()->schema();
2863
2864         my $item_holds = $schema->resultset('Reserve')->search( { itemnumber => $itemnumber, found => undef } )->count();
2865         if ($item_holds) {
2866             # There is an item level hold on this item, no other item can fill the hold
2867             $resfound = 1;
2868         }
2869         else {
2870
2871             # Get all other items that could possibly fill reserves
2872             my @itemnumbers = $schema->resultset('Item')->search(
2873                 {
2874                     biblionumber => $resrec->{biblionumber},
2875                     onloan       => undef,
2876                     notforloan   => 0,
2877                     -not         => { itemnumber => $itemnumber }
2878                 },
2879                 { columns => 'itemnumber' }
2880             )->get_column('itemnumber')->all();
2881
2882             # Get all other reserves that could have been filled by this item
2883             my @borrowernumbers;
2884             while (1) {
2885                 my ( $reserve_found, $reserve, undef ) =
2886                   C4::Reserves::CheckReserves( $itemnumber, undef, undef, \@borrowernumbers );
2887
2888                 if ($reserve_found) {
2889                     push( @borrowernumbers, $reserve->{borrowernumber} );
2890                 }
2891                 else {
2892                     last;
2893                 }
2894             }
2895
2896             # If the count of the union of the lists of reservable items for each borrower
2897             # is equal or greater than the number of borrowers, we know that all reserves
2898             # can be filled with available items. We can get the union of the sets simply
2899             # by pushing all the elements onto an array and removing the duplicates.
2900             my @reservable;
2901             foreach my $b (@borrowernumbers) {
2902                 my ($borr) = C4::Members::GetMemberDetails($b);
2903                 foreach my $i (@itemnumbers) {
2904                     my $item = GetItem($i);
2905                     if (   IsAvailableForItemLevelRequest( $item, $borr )
2906                         && CanItemBeReserved( $b, $i )
2907                         && !IsItemOnHoldAndFound($i) )
2908                     {
2909                         push( @reservable, $i );
2910                     }
2911                 }
2912             }
2913
2914             @reservable = uniq(@reservable);
2915
2916             if ( @reservable >= @borrowernumbers ) {
2917                 $resfound = 0;
2918             }
2919         }
2920     }
2921     return ( 0, "on_reserve" ) if $resfound;    # '' when no hold was found
2922
2923     return ( 1, undef ) if $override_limit;
2924
2925     my $branchcode = _GetCircControlBranch( $item, $borrower );
2926     my $issuingrule =
2927       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
2928
2929     return ( 0, "too_many" )
2930       if $issuingrule->{renewalsallowed} <= $itemissue->{renewals};
2931
2932     my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
2933     my $restrictionblockrenewing = C4::Context->preference('RestrictionBlockRenewing');
2934     my $restricted = Koha::Patron::Debarments::IsDebarred($borrowernumber);
2935     my $hasoverdues = C4::Members::HasOverdues($borrowernumber);
2936
2937     if ( $restricted and $restrictionblockrenewing ) {
2938         return ( 0, 'restriction');
2939     } elsif ( ($hasoverdues and $overduesblockrenewing eq 'block') || ($itemissue->{overdue} and $overduesblockrenewing eq 'blockitem') ) {
2940         return ( 0, 'overdue');
2941     }
2942
2943     if ( defined $issuingrule->{norenewalbefore}
2944         and $issuingrule->{norenewalbefore} ne "" )
2945     {
2946
2947         # Calculate soonest renewal by subtracting 'No renewal before' from due date
2948         my $soonestrenewal =
2949           $itemissue->{date_due}->clone()
2950           ->subtract(
2951             $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore} );
2952
2953         # Depending on syspref reset the exact time, only check the date
2954         if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date'
2955             and $issuingrule->{lengthunit} eq 'days' )
2956         {
2957             $soonestrenewal->truncate( to => 'day' );
2958         }
2959
2960         if ( $soonestrenewal > DateTime->now( time_zone => C4::Context->tz() ) )
2961         {
2962             return ( 0, "auto_too_soon" ) if $itemissue->{auto_renew};
2963             return ( 0, "too_soon" );
2964         }
2965         elsif ( $itemissue->{auto_renew} ) {
2966             return ( 0, "auto_renew" );
2967         }
2968     }
2969
2970     # Fallback for automatic renewals:
2971     # If norenewalbefore is undef, don't renew before due date.
2972     elsif ( $itemissue->{auto_renew} ) {
2973         my $now = dt_from_string;
2974         return ( 0, "auto_renew" )
2975           if $now >= $itemissue->{date_due};
2976         return ( 0, "auto_too_soon" );
2977     }
2978
2979     return ( 1, undef );
2980 }
2981
2982 =head2 AddRenewal
2983
2984   &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
2985
2986 Renews a loan.
2987
2988 C<$borrowernumber> is the borrower number of the patron who currently
2989 has the item.
2990
2991 C<$itemnumber> is the number of the item to renew.
2992
2993 C<$branch> is the library where the renewal took place (if any).
2994            The library that controls the circ policies for the renewal is retrieved from the issues record.
2995
2996 C<$datedue> can be a DateTime object used to set the due date.
2997
2998 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
2999 this parameter is not supplied, lastreneweddate is set to the current date.
3000
3001 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
3002 from the book's item type.
3003
3004 =cut
3005
3006 sub AddRenewal {
3007     my $borrowernumber  = shift;
3008     my $itemnumber      = shift or return;
3009     my $branch          = shift;
3010     my $datedue         = shift;
3011     my $lastreneweddate = shift || DateTime->now(time_zone => C4::Context->tz)->ymd();
3012
3013     my $item   = GetItem($itemnumber) or return;
3014     my $biblio = GetBiblioFromItemNumber($itemnumber) or return;
3015
3016     my $dbh = C4::Context->dbh;
3017
3018     # Find the issues record for this book
3019     my $sth =
3020       $dbh->prepare("SELECT * FROM issues WHERE itemnumber = ?");
3021     $sth->execute( $itemnumber );
3022     my $issuedata = $sth->fetchrow_hashref;
3023
3024     return unless ( $issuedata );
3025
3026     $borrowernumber ||= $issuedata->{borrowernumber};
3027
3028     if ( defined $datedue && ref $datedue ne 'DateTime' ) {
3029         carp 'Invalid date passed to AddRenewal.';
3030         return;
3031     }
3032
3033     # If the due date wasn't specified, calculate it by adding the
3034     # book's loan length to today's date or the current due date
3035     # based on the value of the RenewalPeriodBase syspref.
3036     unless ($datedue) {
3037
3038         my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber ) or return;
3039         my $itemtype = (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'};
3040
3041         $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
3042                                         dt_from_string( $issuedata->{date_due} ) :
3043                                         DateTime->now( time_zone => C4::Context->tz());
3044         $datedue =  CalcDateDue($datedue, $itemtype, $issuedata->{'branchcode'}, $borrower, 'is a renewal');
3045     }
3046
3047     # Update the issues record to have the new due date, and a new count
3048     # of how many times it has been renewed.
3049     my $renews = $issuedata->{'renewals'} + 1;
3050     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
3051                             WHERE borrowernumber=? 
3052                             AND itemnumber=?"
3053     );
3054
3055     $sth->execute( $datedue->strftime('%Y-%m-%d %H:%M'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
3056
3057     # Update the renewal count on the item, and tell zebra to reindex
3058     $renews = $biblio->{'renewals'} + 1;
3059     ModItem({ renewals => $renews, onloan => $datedue->strftime('%Y-%m-%d %H:%M')}, $biblio->{'biblionumber'}, $itemnumber);
3060
3061     # Charge a new rental fee, if applicable?
3062     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
3063     if ( $charge > 0 ) {
3064         my $accountno = getnextacctno( $borrowernumber );
3065         my $item = GetBiblioFromItemNumber($itemnumber);
3066         my $manager_id = 0;
3067         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
3068         $sth = $dbh->prepare(
3069                 "INSERT INTO accountlines
3070                     (date, borrowernumber, accountno, amount, manager_id,
3071                     description,accounttype, amountoutstanding, itemnumber)
3072                     VALUES (now(),?,?,?,?,?,?,?,?)"
3073         );
3074         $sth->execute( $borrowernumber, $accountno, $charge, $manager_id,
3075             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
3076             'Rent', $charge, $itemnumber );
3077     }
3078
3079     # Send a renewal slip according to checkout alert preferencei
3080     if ( C4::Context->preference('RenewalSendNotice') eq '1') {
3081         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
3082         my $circulation_alert = 'C4::ItemCirculationAlertPreference';
3083         my %conditions = (
3084                 branchcode   => $branch,
3085                 categorycode => $borrower->{categorycode},
3086                 item_type    => $item->{itype},
3087                 notification => 'CHECKOUT',
3088         );
3089         if ($circulation_alert->is_enabled_for(\%conditions)) {
3090                 SendCirculationAlert({
3091                         type     => 'RENEWAL',
3092                         item     => $item,
3093                 borrower => $borrower,
3094                 branch   => $branch,
3095                 });
3096         }
3097     }
3098
3099     # Remove any OVERDUES related debarment if the borrower has no overdues
3100     my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
3101     if ( $borrowernumber
3102       && $borrower->{'debarred'}
3103       && !C4::Members::HasOverdues( $borrowernumber )
3104       && @{ GetDebarments({ borrowernumber => $borrowernumber, type => 'OVERDUES' }) }
3105     ) {
3106         DelUniqueDebarment({ borrowernumber => $borrowernumber, type => 'OVERDUES' });
3107     }
3108
3109     # Log the renewal
3110     UpdateStats({branch => $branch,
3111                 type => 'renew',
3112                 amount => $charge,
3113                 itemnumber => $itemnumber,
3114                 itemtype => $item->{itype},
3115                 borrowernumber => $borrowernumber,
3116                 ccode => $item->{'ccode'}}
3117                 );
3118         return $datedue;
3119 }
3120
3121 sub GetRenewCount {
3122     # check renewal status
3123     my ( $bornum, $itemno ) = @_;
3124     my $dbh           = C4::Context->dbh;
3125     my $renewcount    = 0;
3126     my $renewsallowed = 0;
3127     my $renewsleft    = 0;
3128
3129     my $borrower = C4::Members::GetMember( borrowernumber => $bornum);
3130     my $item     = GetItem($itemno); 
3131
3132     # Look in the issues table for this item, lent to this borrower,
3133     # and not yet returned.
3134
3135     # FIXME - I think this function could be redone to use only one SQL call.
3136     my $sth = $dbh->prepare(
3137         "select * from issues
3138                                 where (borrowernumber = ?)
3139                                 and (itemnumber = ?)"
3140     );
3141     $sth->execute( $bornum, $itemno );
3142     my $data = $sth->fetchrow_hashref;
3143     $renewcount = $data->{'renewals'} if $data->{'renewals'};
3144     # $item and $borrower should be calculated
3145     my $branchcode = _GetCircControlBranch($item, $borrower);
3146     
3147     my $issuingrule = GetIssuingRule($borrower->{categorycode}, $item->{itype}, $branchcode);
3148     
3149     $renewsallowed = $issuingrule->{'renewalsallowed'};
3150     $renewsleft    = $renewsallowed - $renewcount;
3151     if($renewsleft < 0){ $renewsleft = 0; }
3152     return ( $renewcount, $renewsallowed, $renewsleft );
3153 }
3154
3155 =head2 GetSoonestRenewDate
3156
3157   $NoRenewalBeforeThisDate = &GetSoonestRenewDate($borrowernumber, $itemnumber);
3158
3159 Find out the soonest possible renew date of a borrowed item.
3160
3161 C<$borrowernumber> is the borrower number of the patron who currently
3162 has the item on loan.
3163
3164 C<$itemnumber> is the number of the item to renew.
3165
3166 C<$GetSoonestRenewDate> returns the DateTime of the soonest possible
3167 renew date, based on the value "No renewal before" of the applicable
3168 issuing rule. Returns the current date if the item can already be
3169 renewed, and returns undefined if the borrower, loan, or item
3170 cannot be found.
3171
3172 =cut
3173
3174 sub GetSoonestRenewDate {
3175     my ( $borrowernumber, $itemnumber ) = @_;
3176
3177     my $dbh = C4::Context->dbh;
3178
3179     my $item      = GetItem($itemnumber)      or return;
3180     my $itemissue = GetItemIssue($itemnumber) or return;
3181
3182     $borrowernumber ||= $itemissue->{borrowernumber};
3183     my $borrower = C4::Members::GetMemberDetails($borrowernumber)
3184       or return;
3185
3186     my $branchcode = _GetCircControlBranch( $item, $borrower );
3187     my $issuingrule =
3188       GetIssuingRule( $borrower->{categorycode}, $item->{itype}, $branchcode );
3189
3190     my $now = dt_from_string;
3191
3192     if ( defined $issuingrule->{norenewalbefore}
3193         and $issuingrule->{norenewalbefore} ne "" )
3194     {
3195         my $soonestrenewal =
3196           $itemissue->{date_due}->clone()
3197           ->subtract(
3198             $issuingrule->{lengthunit} => $issuingrule->{norenewalbefore} );
3199
3200         if ( C4::Context->preference('NoRenewalBeforePrecision') eq 'date'
3201             and $issuingrule->{lengthunit} eq 'days' )
3202         {
3203             $soonestrenewal->truncate( to => 'day' );
3204         }
3205         return $soonestrenewal if $now < $soonestrenewal;
3206     }
3207     return $now;
3208 }
3209
3210 =head2 GetIssuingCharges
3211
3212   ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
3213
3214 Calculate how much it would cost for a given patron to borrow a given
3215 item, including any applicable discounts.
3216
3217 C<$itemnumber> is the item number of item the patron wishes to borrow.
3218
3219 C<$borrowernumber> is the patron's borrower number.
3220
3221 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
3222 and C<$item_type> is the code for the item's item type (e.g., C<VID>
3223 if it's a video).
3224
3225 =cut
3226
3227 sub GetIssuingCharges {
3228
3229     # calculate charges due
3230     my ( $itemnumber, $borrowernumber ) = @_;
3231     my $charge = 0;
3232     my $dbh    = C4::Context->dbh;
3233     my $item_type;
3234
3235     # Get the book's item type and rental charge (via its biblioitem).
3236     my $charge_query = 'SELECT itemtypes.itemtype,rentalcharge FROM items
3237         LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber';
3238     $charge_query .= (C4::Context->preference('item-level_itypes'))
3239         ? ' LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype'
3240         : ' LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype';
3241
3242     $charge_query .= ' WHERE items.itemnumber =?';
3243
3244     my $sth = $dbh->prepare($charge_query);
3245     $sth->execute($itemnumber);
3246     if ( my $item_data = $sth->fetchrow_hashref ) {
3247         $item_type = $item_data->{itemtype};
3248         $charge    = $item_data->{rentalcharge};
3249         my $branch = C4::Branch::mybranch();
3250         my $discount_query = q|SELECT rentaldiscount,
3251             issuingrules.itemtype, issuingrules.branchcode
3252             FROM borrowers
3253             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
3254             WHERE borrowers.borrowernumber = ?
3255             AND (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
3256             AND (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')|;
3257         my $discount_sth = $dbh->prepare($discount_query);
3258         $discount_sth->execute( $borrowernumber, $item_type, $branch );
3259         my $discount_rules = $discount_sth->fetchall_arrayref({});
3260         if (@{$discount_rules}) {
3261             # We may have multiple rules so get the most specific
3262             my $discount = _get_discount_from_rule($discount_rules, $branch, $item_type);
3263             $charge = ( $charge * ( 100 - $discount ) ) / 100;
3264         }
3265     }
3266
3267     return ( $charge, $item_type );
3268 }
3269
3270 # Select most appropriate discount rule from those returned
3271 sub _get_discount_from_rule {
3272     my ($rules_ref, $branch, $itemtype) = @_;
3273     my $discount;
3274
3275     if (@{$rules_ref} == 1) { # only 1 applicable rule use it
3276         $discount = $rules_ref->[0]->{rentaldiscount};
3277         return (defined $discount) ? $discount : 0;
3278     }
3279     # could have up to 4 does one match $branch and $itemtype
3280     my @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq $itemtype } @{$rules_ref};
3281     if (@d) {
3282         $discount = $d[0]->{rentaldiscount};
3283         return (defined $discount) ? $discount : 0;
3284     }
3285     # do we have item type + all branches
3286     @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq $itemtype } @{$rules_ref};
3287     if (@d) {
3288         $discount = $d[0]->{rentaldiscount};
3289         return (defined $discount) ? $discount : 0;
3290     }
3291     # do we all item types + this branch
3292     @d = grep { $_->{branchcode} eq $branch && $_->{itemtype} eq q{*} } @{$rules_ref};
3293     if (@d) {
3294         $discount = $d[0]->{rentaldiscount};
3295         return (defined $discount) ? $discount : 0;
3296     }
3297     # so all and all (surely we wont get here)
3298     @d = grep { $_->{branchcode} eq q{*} && $_->{itemtype} eq q{*} } @{$rules_ref};
3299     if (@d) {
3300         $discount = $d[0]->{rentaldiscount};
3301         return (defined $discount) ? $discount : 0;
3302     }
3303     # none of the above
3304     return 0;
3305 }
3306
3307 =head2 AddIssuingCharge
3308
3309   &AddIssuingCharge( $itemno, $borrowernumber, $charge )
3310
3311 =cut
3312
3313 sub AddIssuingCharge {
3314     my ( $itemnumber, $borrowernumber, $charge ) = @_;
3315     my $dbh = C4::Context->dbh;
3316     my $nextaccntno = getnextacctno( $borrowernumber );
3317     my $manager_id = 0;
3318     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
3319     my $query ="
3320         INSERT INTO accountlines
3321             (borrowernumber, itemnumber, accountno,
3322             date, amount, description, accounttype,
3323             amountoutstanding, manager_id)
3324         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?,?)
3325     ";
3326     my $sth = $dbh->prepare($query);
3327     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge, $manager_id );
3328 }
3329
3330 =head2 GetTransfers
3331
3332   GetTransfers($itemnumber);
3333
3334 =cut
3335
3336 sub GetTransfers {
3337     my ($itemnumber) = @_;
3338
3339     my $dbh = C4::Context->dbh;
3340
3341     my $query = '
3342         SELECT datesent,
3343                frombranch,
3344                tobranch
3345         FROM branchtransfers
3346         WHERE itemnumber = ?
3347           AND datearrived IS NULL
3348         ';
3349     my $sth = $dbh->prepare($query);
3350     $sth->execute($itemnumber);
3351     my @row = $sth->fetchrow_array();
3352     return @row;
3353 }
3354
3355 =head2 GetTransfersFromTo
3356
3357   @results = GetTransfersFromTo($frombranch,$tobranch);
3358
3359 Returns the list of pending transfers between $from and $to branch
3360
3361 =cut
3362
3363 sub GetTransfersFromTo {
3364     my ( $frombranch, $tobranch ) = @_;
3365     return unless ( $frombranch && $tobranch );
3366     my $dbh   = C4::Context->dbh;
3367     my $query = "
3368         SELECT itemnumber,datesent,frombranch
3369         FROM   branchtransfers
3370         WHERE  frombranch=?
3371           AND  tobranch=?
3372           AND datearrived IS NULL
3373     ";
3374     my $sth = $dbh->prepare($query);
3375     $sth->execute( $frombranch, $tobranch );
3376     my @gettransfers;
3377
3378     while ( my $data = $sth->fetchrow_hashref ) {
3379         push @gettransfers, $data;
3380     }
3381     return (@gettransfers);
3382 }
3383
3384 =head2 DeleteTransfer
3385
3386   &DeleteTransfer($itemnumber);
3387
3388 =cut
3389
3390 sub DeleteTransfer {
3391     my ($itemnumber) = @_;
3392     return unless $itemnumber;
3393     my $dbh          = C4::Context->dbh;
3394     my $sth          = $dbh->prepare(
3395         "DELETE FROM branchtransfers
3396          WHERE itemnumber=?
3397          AND datearrived IS NULL "
3398     );
3399     return $sth->execute($itemnumber);
3400 }
3401
3402 =head2 AnonymiseIssueHistory
3403
3404   ($rows,$err_history_not_deleted) = AnonymiseIssueHistory($date,$borrowernumber)
3405
3406 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
3407 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
3408
3409 If c<$borrowernumber> is set, it will delete issue history for only that borrower, regardless of their opac privacy
3410 setting (force delete).
3411
3412 return the number of affected rows and a value that evaluates to true if an error occurred deleting the history.
3413
3414 =cut
3415
3416 sub AnonymiseIssueHistory {
3417     my $date           = shift;
3418     my $borrowernumber = shift;
3419     my $dbh            = C4::Context->dbh;
3420     my $query          = "
3421         UPDATE old_issues
3422         SET    borrowernumber = ?
3423         WHERE  returndate < ?
3424           AND borrowernumber IS NOT NULL
3425     ";
3426
3427     # The default of 0 does not work due to foreign key constraints
3428     # The anonymisation should not fail quietly if AnonymousPatron is not a valid entry
3429     # Set it to undef (NULL)
3430     my $anonymouspatron = C4::Context->preference('AnonymousPatron') || undef;
3431     my @bind_params = ($anonymouspatron, $date);
3432     if (defined $borrowernumber) {
3433        $query .= " AND borrowernumber = ?";
3434        push @bind_params, $borrowernumber;
3435     } else {
3436        $query .= " AND (SELECT privacy FROM borrowers WHERE borrowers.borrowernumber=old_issues.borrowernumber) <> 0";
3437     }
3438     my $sth = $dbh->prepare($query);
3439     $sth->execute(@bind_params);
3440     my $anonymisation_err = $dbh->err;
3441     my $rows_affected = $sth->rows;  ### doublecheck row count return function
3442     return ($rows_affected, $anonymisation_err);
3443 }
3444
3445 =head2 SendCirculationAlert
3446
3447 Send out a C<check-in> or C<checkout> alert using the messaging system.
3448
3449 B<Parameters>:
3450
3451 =over 4
3452
3453 =item type
3454
3455 Valid values for this parameter are: C<CHECKIN> and C<CHECKOUT>.
3456
3457 =item item
3458
3459 Hashref of information about the item being checked in or out.
3460
3461 =item borrower
3462
3463 Hashref of information about the borrower of the item.
3464
3465 =item branch
3466
3467 The branchcode from where the checkout or check-in took place.
3468
3469 =back
3470
3471 B<Example>:
3472
3473     SendCirculationAlert({
3474         type     => 'CHECKOUT',
3475         item     => $item,
3476         borrower => $borrower,
3477         branch   => $branch,
3478     });
3479
3480 =cut
3481
3482 sub SendCirculationAlert {
3483     my ($opts) = @_;
3484     my ($type, $item, $borrower, $branch) =
3485         ($opts->{type}, $opts->{item}, $opts->{borrower}, $opts->{branch});
3486     my %message_name = (
3487         CHECKIN  => 'Item_Check_in',
3488         CHECKOUT => 'Item_Checkout',
3489         RENEWAL  => 'Item_Checkout',
3490     );
3491     my $borrower_preferences = C4::Members::Messaging::GetMessagingPreferences({
3492         borrowernumber => $borrower->{borrowernumber},
3493         message_name   => $message_name{$type},
3494     });
3495     my $issues_table = ( $type eq 'CHECKOUT' || $type eq 'RENEWAL' ) ? 'issues' : 'old_issues';
3496
3497     my @transports = keys %{ $borrower_preferences->{transports} };
3498     # warn "no transports" unless @transports;
3499     for (@transports) {
3500         # warn "transport: $_";
3501         my $message = C4::Message->find_last_message($borrower, $type, $_);
3502         if (!$message) {
3503             #warn "create new message";
3504             my $letter =  C4::Letters::GetPreparedLetter (
3505                 module => 'circulation',
3506                 letter_code => $type,
3507                 branchcode => $branch,
3508                 message_transport_type => $_,
3509                 tables => {
3510                     $issues_table => $item->{itemnumber},
3511                     'items'       => $item->{itemnumber},
3512                     'biblio'      => $item->{biblionumber},
3513                     'biblioitems' => $item->{biblionumber},
3514                     'borrowers'   => $borrower,
3515                     'branches'    => $branch,
3516                 }
3517             ) or next;
3518             C4::Message->enqueue($letter, $borrower, $_);
3519         } else {
3520             #warn "append to old message";
3521             my $letter =  C4::Letters::GetPreparedLetter (
3522                 module => 'circulation',
3523                 letter_code => $type,
3524                 branchcode => $branch,
3525                 message_transport_type => $_,
3526                 tables => {
3527                     $issues_table => $item->{itemnumber},
3528                     'items'       => $item->{itemnumber},
3529                     'biblio'      => $item->{biblionumber},
3530                     'biblioitems' => $item->{biblionumber},
3531                     'borrowers'   => $borrower,
3532                     'branches'    => $branch,
3533                 }
3534             ) or next;
3535             $message->append($letter);
3536             $message->update;
3537         }
3538     }
3539
3540     return;
3541 }
3542
3543 =head2 updateWrongTransfer
3544
3545   $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
3546
3547 This function validate the line of brachtransfer but with the wrong destination (mistake from a librarian ...), and create a new line in branchtransfer from the actual library to the original library of reservation 
3548
3549 =cut
3550
3551 sub updateWrongTransfer {
3552         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
3553         my $dbh = C4::Context->dbh;     
3554 # first step validate the actual line of transfert .
3555         my $sth =
3556                 $dbh->prepare(
3557                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
3558                 );
3559                 $sth->execute($FromLibrary,$itemNumber);
3560
3561 # second step create a new line of branchtransfer to the right location .
3562         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
3563
3564 #third step changing holdingbranch of item
3565         UpdateHoldingbranch($FromLibrary,$itemNumber);
3566 }
3567
3568 =head2 UpdateHoldingbranch
3569
3570   $items = UpdateHoldingbranch($branch,$itmenumber);
3571
3572 Simple methode for updating hodlingbranch in items BDD line
3573
3574 =cut
3575
3576 sub UpdateHoldingbranch {
3577         my ( $branch,$itemnumber ) = @_;
3578     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
3579 }
3580
3581 =head2 CalcDateDue
3582
3583 $newdatedue = CalcDateDue($startdate,$itemtype,$branchcode,$borrower);
3584
3585 this function calculates the due date given the start date and configured circulation rules,
3586 checking against the holidays calendar as per the 'useDaysMode' syspref.
3587 C<$startdate>   = DateTime object representing start date of loan period (assumed to be today)
3588 C<$itemtype>  = itemtype code of item in question
3589 C<$branch>  = location whose calendar to use
3590 C<$borrower> = Borrower object
3591 C<$isrenewal> = Boolean: is true if we want to calculate the date due for a renewal. Else is false.
3592
3593 =cut
3594
3595 sub CalcDateDue {
3596     my ( $startdate, $itemtype, $branch, $borrower, $isrenewal ) = @_;
3597
3598     $isrenewal ||= 0;
3599
3600     # loanlength now a href
3601     my $loanlength =
3602             GetLoanLength( $borrower->{'categorycode'}, $itemtype, $branch );
3603
3604     my $length_key = ( $isrenewal and defined $loanlength->{renewalperiod} )
3605             ? qq{renewalperiod}
3606             : qq{issuelength};
3607
3608     my $datedue;
3609     if ( $startdate ) {
3610         if (ref $startdate ne 'DateTime' ) {
3611             $datedue = dt_from_string($datedue);
3612         } else {
3613             $datedue = $startdate->clone;
3614         }
3615     } else {
3616         $datedue =
3617           DateTime->now( time_zone => C4::Context->tz() )
3618           ->truncate( to => 'minute' );
3619     }
3620
3621
3622     # calculate the datedue as normal
3623     if ( C4::Context->preference('useDaysMode') eq 'Days' )
3624     {    # ignoring calendar
3625         if ( $loanlength->{lengthunit} eq 'hours' ) {
3626             $datedue->add( hours => $loanlength->{$length_key} );
3627         } else {    # days
3628             $datedue->add( days => $loanlength->{$length_key} );
3629             $datedue->set_hour(23);
3630             $datedue->set_minute(59);
3631         }
3632     } else {
3633         my $dur;
3634         if ($loanlength->{lengthunit} eq 'hours') {
3635             $dur = DateTime::Duration->new( hours => $loanlength->{$length_key});
3636         }
3637         else { # days
3638             $dur = DateTime::Duration->new( days => $loanlength->{$length_key});
3639         }
3640         my $calendar = Koha::Calendar->new( branchcode => $branch );
3641         $datedue = $calendar->addDate( $datedue, $dur, $loanlength->{lengthunit} );
3642         if ($loanlength->{lengthunit} eq 'days') {
3643             $datedue->set_hour(23);
3644             $datedue->set_minute(59);
3645         }
3646     }
3647
3648     # if Hard Due Dates are used, retrieve them and apply as necessary
3649     my ( $hardduedate, $hardduedatecompare ) =
3650       GetHardDueDate( $borrower->{'categorycode'}, $itemtype, $branch );
3651     if ($hardduedate) {    # hardduedates are currently dates
3652         $hardduedate->truncate( to => 'minute' );
3653         $hardduedate->set_hour(23);
3654         $hardduedate->set_minute(59);
3655         my $cmp = DateTime->compare( $hardduedate, $datedue );
3656
3657 # if the calculated due date is after the 'before' Hard Due Date (ceiling), override
3658 # if the calculated date is before the 'after' Hard Due Date (floor), override
3659 # if the hard due date is set to 'exactly', overrride
3660         if ( $hardduedatecompare == 0 || $hardduedatecompare == $cmp ) {
3661             $datedue = $hardduedate->clone;
3662         }
3663
3664         # in all other cases, keep the date due as it is
3665
3666     }
3667
3668     # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
3669     if ( C4::Context->preference('ReturnBeforeExpiry') ) {
3670         my $expiry_dt = dt_from_string( $borrower->{dateexpiry}, 'iso', 'floating');
3671         if( $expiry_dt ) { #skip empty expiry date..
3672             $expiry_dt->set( hour => 23, minute => 59);
3673             my $d1= $datedue->clone->set_time_zone('floating');
3674             if ( DateTime->compare( $d1, $expiry_dt ) == 1 ) {
3675                 $datedue = $expiry_dt->clone->set_time_zone( C4::Context->tz );
3676             }
3677         }
3678     }
3679
3680     return $datedue;
3681 }
3682
3683
3684 sub CheckValidBarcode{
3685 my ($barcode) = @_;
3686 my $dbh = C4::Context->dbh;
3687 my $query=qq|SELECT count(*) 
3688              FROM items 
3689              WHERE barcode=?
3690             |;
3691 my $sth = $dbh->prepare($query);
3692 $sth->execute($barcode);
3693 my $exist=$sth->fetchrow ;
3694 return $exist;
3695 }
3696
3697 =head2 IsBranchTransferAllowed
3698
3699   $allowed = IsBranchTransferAllowed( $toBranch, $fromBranch, $code );
3700
3701 Code is either an itemtype or collection doe depending on the pref BranchTransferLimitsType
3702
3703 =cut
3704
3705 sub IsBranchTransferAllowed {
3706         my ( $toBranch, $fromBranch, $code ) = @_;
3707
3708         if ( $toBranch eq $fromBranch ) { return 1; } ## Short circuit for speed.
3709         
3710         my $limitType = C4::Context->preference("BranchTransferLimitsType");   
3711         my $dbh = C4::Context->dbh;
3712             
3713         my $sth = $dbh->prepare("SELECT * FROM branch_transfer_limits WHERE toBranch = ? AND fromBranch = ? AND $limitType = ?");
3714         $sth->execute( $toBranch, $fromBranch, $code );
3715         my $limit = $sth->fetchrow_hashref();
3716                         
3717         ## If a row is found, then that combination is not allowed, if no matching row is found, then the combination *is allowed*
3718         if ( $limit->{'limitId'} ) {
3719                 return 0;
3720         } else {
3721                 return 1;
3722         }
3723 }                                                        
3724
3725 =head2 CreateBranchTransferLimit
3726
3727   CreateBranchTransferLimit( $toBranch, $fromBranch, $code );
3728
3729 $code is either itemtype or collection code depending on what the pref BranchTransferLimitsType is set to.
3730
3731 =cut
3732
3733 sub CreateBranchTransferLimit {
3734    my ( $toBranch, $fromBranch, $code ) = @_;
3735    return unless defined($toBranch) && defined($fromBranch);
3736    my $limitType = C4::Context->preference("BranchTransferLimitsType");
3737    
3738    my $dbh = C4::Context->dbh;
3739    
3740    my $sth = $dbh->prepare("INSERT INTO branch_transfer_limits ( $limitType, toBranch, fromBranch ) VALUES ( ?, ?, ? )");
3741    return $sth->execute( $code, $toBranch, $fromBranch );
3742 }
3743
3744 =head2 DeleteBranchTransferLimits
3745
3746     my $result = DeleteBranchTransferLimits($frombranch);
3747
3748 Deletes all the library transfer limits for one library.  Returns the
3749 number of limits deleted, 0e0 if no limits were deleted, or undef if
3750 no arguments are supplied.
3751
3752 =cut
3753
3754 sub DeleteBranchTransferLimits {
3755     my $branch = shift;
3756     return unless defined $branch;
3757     my $dbh    = C4::Context->dbh;
3758     my $sth    = $dbh->prepare("DELETE FROM branch_transfer_limits WHERE fromBranch = ?");
3759     return $sth->execute($branch);
3760 }
3761
3762 sub ReturnLostItem{
3763     my ( $borrowernumber, $itemnum ) = @_;
3764
3765     MarkIssueReturned( $borrowernumber, $itemnum );
3766     my $borrower = C4::Members::GetMember( 'borrowernumber'=>$borrowernumber );
3767     my $item = C4::Items::GetItem( $itemnum );
3768     my $old_note = ($item->{'paidfor'} && ($item->{'paidfor'} ne q{})) ? $item->{'paidfor'}.' / ' : q{};
3769     my @datearr = localtime(time);
3770     my $date = ( 1900 + $datearr[5] ) . "-" . ( $datearr[4] + 1 ) . "-" . $datearr[3];
3771     my $bor = "$borrower->{'firstname'} $borrower->{'surname'} $borrower->{'cardnumber'}";
3772     ModItem({ paidfor =>  $old_note."Paid for by $bor $date" }, undef, $itemnum);
3773 }
3774
3775
3776 sub LostItem{
3777     my ($itemnumber, $mark_returned) = @_;
3778
3779     my $dbh = C4::Context->dbh();
3780     my $sth=$dbh->prepare("SELECT issues.*,items.*,biblio.title 
3781                            FROM issues 
3782                            JOIN items USING (itemnumber) 
3783                            JOIN biblio USING (biblionumber)
3784                            WHERE issues.itemnumber=?");
3785     $sth->execute($itemnumber);
3786     my $issues=$sth->fetchrow_hashref();
3787
3788     # If a borrower lost the item, add a replacement cost to the their record
3789     if ( my $borrowernumber = $issues->{borrowernumber} ){
3790         my $borrower = C4::Members::GetMemberDetails( $borrowernumber );
3791
3792         if (C4::Context->preference('WhenLostForgiveFine')){
3793             my $fix = _FixOverduesOnReturn($borrowernumber, $itemnumber, 1, 0); # 1, 0 = exemptfine, no-dropbox
3794             defined($fix) or warn "_FixOverduesOnReturn($borrowernumber, $itemnumber...) failed!";  # zero is OK, check defined
3795         }
3796         if (C4::Context->preference('WhenLostChargeReplacementFee')){
3797             C4::Accounts::chargelostitem($borrowernumber, $itemnumber, $issues->{'replacementprice'}, "Lost Item $issues->{'title'} $issues->{'barcode'}");
3798             #FIXME : Should probably have a way to distinguish this from an item that really was returned.
3799             #warn " $issues->{'borrowernumber'}  /  $itemnumber ";
3800         }
3801
3802         MarkIssueReturned($borrowernumber,$itemnumber,undef,undef,$borrower->{'privacy'}) if $mark_returned;
3803     }
3804 }
3805
3806 sub GetOfflineOperations {
3807     my $dbh = C4::Context->dbh;
3808     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE branchcode=? ORDER BY timestamp");
3809     $sth->execute(C4::Context->userenv->{'branch'});
3810     my $results = $sth->fetchall_arrayref({});
3811     return $results;
3812 }
3813
3814 sub GetOfflineOperation {
3815     my $operationid = shift;
3816     return unless $operationid;
3817     my $dbh = C4::Context->dbh;
3818     my $sth = $dbh->prepare("SELECT * FROM pending_offline_operations WHERE operationid=?");
3819     $sth->execute( $operationid );
3820     return $sth->fetchrow_hashref;
3821 }
3822
3823 sub AddOfflineOperation {
3824     my ( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount ) = @_;
3825     my $dbh = C4::Context->dbh;
3826     my $sth = $dbh->prepare("INSERT INTO pending_offline_operations (userid, branchcode, timestamp, action, barcode, cardnumber, amount) VALUES(?,?,?,?,?,?,?)");
3827     $sth->execute( $userid, $branchcode, $timestamp, $action, $barcode, $cardnumber, $amount );
3828     return "Added.";
3829 }
3830
3831 sub DeleteOfflineOperation {
3832     my $dbh = C4::Context->dbh;
3833     my $sth = $dbh->prepare("DELETE FROM pending_offline_operations WHERE operationid=?");
3834     $sth->execute( shift );
3835     return "Deleted.";
3836 }
3837
3838 sub ProcessOfflineOperation {
3839     my $operation = shift;
3840
3841     my $report;
3842     if ( $operation->{action} eq 'return' ) {
3843         $report = ProcessOfflineReturn( $operation );
3844     } elsif ( $operation->{action} eq 'issue' ) {
3845         $report = ProcessOfflineIssue( $operation );
3846     } elsif ( $operation->{action} eq 'payment' ) {
3847         $report = ProcessOfflinePayment( $operation );
3848     }
3849
3850     DeleteOfflineOperation( $operation->{operationid} ) if $operation->{operationid};
3851
3852     return $report;
3853 }
3854
3855 sub ProcessOfflineReturn {
3856     my $operation = shift;
3857
3858     my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3859
3860     if ( $itemnumber ) {
3861         my $issue = GetOpenIssue( $itemnumber );
3862         if ( $issue ) {
3863             MarkIssueReturned(
3864                 $issue->{borrowernumber},
3865                 $itemnumber,
3866                 undef,
3867                 $operation->{timestamp},
3868             );
3869             ModItem(
3870                 { renewals => 0, onloan => undef },
3871                 $issue->{'biblionumber'},
3872                 $itemnumber
3873             );
3874             return "Success.";
3875         } else {
3876             return "Item not issued.";
3877         }
3878     } else {
3879         return "Item not found.";
3880     }
3881 }
3882
3883 sub ProcessOfflineIssue {
3884     my $operation = shift;
3885
3886     my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3887
3888     if ( $borrower->{borrowernumber} ) {
3889         my $itemnumber = C4::Items::GetItemnumberFromBarcode( $operation->{barcode} );
3890         unless ($itemnumber) {
3891             return "Barcode not found.";
3892         }
3893         my $issue = GetOpenIssue( $itemnumber );
3894
3895         if ( $issue and ( $issue->{borrowernumber} ne $borrower->{borrowernumber} ) ) { # Item already issued to another borrower, mark it returned
3896             MarkIssueReturned(
3897                 $issue->{borrowernumber},
3898                 $itemnumber,
3899                 undef,
3900                 $operation->{timestamp},
3901             );
3902         }
3903         AddIssue(
3904             $borrower,
3905             $operation->{'barcode'},
3906             undef,
3907             1,
3908             $operation->{timestamp},
3909             undef,
3910         );
3911         return "Success.";
3912     } else {
3913         return "Borrower not found.";
3914     }
3915 }
3916
3917 sub ProcessOfflinePayment {
3918     my $operation = shift;
3919
3920     my $borrower = C4::Members::GetMemberDetails( undef, $operation->{cardnumber} ); # Get borrower from operation cardnumber
3921     my $amount = $operation->{amount};
3922
3923     recordpayment( $borrower->{borrowernumber}, $amount );
3924
3925     return "Success."
3926 }
3927
3928
3929 =head2 TransferSlip
3930
3931   TransferSlip($user_branch, $itemnumber, $barcode, $to_branch)
3932
3933   Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
3934
3935 =cut
3936
3937 sub TransferSlip {
3938     my ($branch, $itemnumber, $barcode, $to_branch) = @_;
3939
3940     my $item =  GetItem( $itemnumber, $barcode )
3941       or return;
3942
3943     return C4::Letters::GetPreparedLetter (
3944         module => 'circulation',
3945         letter_code => 'TRANSFERSLIP',
3946         branchcode => $branch,
3947         tables => {
3948             'branches'    => $to_branch,
3949             'biblio'      => $item->{biblionumber},
3950             'items'       => $item,
3951         },
3952     );
3953 }
3954
3955 =head2 CheckIfIssuedToPatron
3956
3957   CheckIfIssuedToPatron($borrowernumber, $biblionumber)
3958
3959   Return 1 if any record item is issued to patron, otherwise return 0
3960
3961 =cut
3962
3963 sub CheckIfIssuedToPatron {
3964     my ($borrowernumber, $biblionumber) = @_;
3965
3966     my $dbh = C4::Context->dbh;
3967     my $query = q|
3968         SELECT COUNT(*) FROM issues
3969         LEFT JOIN items ON items.itemnumber = issues.itemnumber
3970         WHERE items.biblionumber = ?
3971         AND issues.borrowernumber = ?
3972     |;
3973     my $is_issued = $dbh->selectrow_array($query, {}, $biblionumber, $borrowernumber );
3974     return 1 if $is_issued;
3975     return;
3976 }
3977
3978 =head2 IsItemIssued
3979
3980   IsItemIssued( $itemnumber )
3981
3982   Return 1 if the item is on loan, otherwise return 0
3983
3984 =cut
3985
3986 sub IsItemIssued {
3987     my $itemnumber = shift;
3988     my $dbh = C4::Context->dbh;
3989     my $sth = $dbh->prepare(q{
3990         SELECT COUNT(*)
3991         FROM issues
3992         WHERE itemnumber = ?
3993     });
3994     $sth->execute($itemnumber);
3995     return $sth->fetchrow;
3996 }
3997
3998 =head2 GetAgeRestriction
3999
4000   my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions, $borrower);
4001   my ($ageRestriction, $daysToAgeRestriction) = GetAgeRestriction($record_restrictions);
4002
4003   if($daysToAgeRestriction <= 0) { #Borrower is allowed to access this material, as he is older or as old as the agerestriction }
4004   if($daysToAgeRestriction > 0) { #Borrower is this many days from meeting the agerestriction }
4005
4006 @PARAM1 the koha.biblioitems.agerestriction value, like K18, PEGI 13, ...
4007 @PARAM2 a borrower-object with koha.borrowers.dateofbirth. (OPTIONAL)
4008 @RETURNS The age restriction age in years and the days to fulfill the age restriction for the given borrower.
4009          Negative days mean the borrower has gone past the age restriction age.
4010
4011 =cut
4012
4013 sub GetAgeRestriction {
4014     my ($record_restrictions, $borrower) = @_;
4015     my $markers = C4::Context->preference('AgeRestrictionMarker');
4016
4017     # Split $record_restrictions to something like FSK 16 or PEGI 6
4018     my @values = split ' ', uc($record_restrictions);
4019     return unless @values;
4020
4021     # Search first occurrence of one of the markers
4022     my @markers = split /\|/, uc($markers);
4023     return unless @markers;
4024
4025     my $index            = 0;
4026     my $restriction_year = 0;
4027     for my $value (@values) {
4028         $index++;
4029         for my $marker (@markers) {
4030             $marker =~ s/^\s+//;    #remove leading spaces
4031             $marker =~ s/\s+$//;    #remove trailing spaces
4032             if ( $marker eq $value ) {
4033                 if ( $index <= $#values ) {
4034                     $restriction_year += $values[$index];
4035                 }
4036                 last;
4037             }
4038             elsif ( $value =~ /^\Q$marker\E(\d+)$/ ) {
4039
4040                 # Perhaps it is something like "K16" (as in Finland)
4041                 $restriction_year += $1;
4042                 last;
4043             }
4044         }
4045         last if ( $restriction_year > 0 );
4046     }
4047
4048     #Check if the borrower is age restricted for this material and for how long.
4049     if ($restriction_year && $borrower) {
4050         if ( $borrower->{'dateofbirth'} ) {
4051             my @alloweddate = split /-/, $borrower->{'dateofbirth'};
4052             $alloweddate[0] += $restriction_year;
4053
4054             #Prevent runime eror on leap year (invalid date)
4055             if ( ( $alloweddate[1] == 2 ) && ( $alloweddate[2] == 29 ) ) {
4056                 $alloweddate[2] = 28;
4057             }
4058
4059             #Get how many days the borrower has to reach the age restriction
4060             my @Today = split /-/, DateTime->today->ymd();
4061             my $daysToAgeRestriction = Date_to_Days(@alloweddate) - Date_to_Days(@Today);
4062             #Negative days means the borrower went past the age restriction age
4063             return ($restriction_year, $daysToAgeRestriction);
4064         }
4065     }
4066
4067     return ($restriction_year);
4068 }
4069
4070
4071 =head2 GetPendingOnSiteCheckouts
4072
4073 =cut
4074
4075 sub GetPendingOnSiteCheckouts {
4076     my $dbh = C4::Context->dbh;
4077     return $dbh->selectall_arrayref(q|
4078         SELECT
4079           items.barcode,
4080           items.biblionumber,
4081           items.itemnumber,
4082           items.itemnotes,
4083           items.itemcallnumber,
4084           items.location,
4085           issues.date_due,
4086           issues.branchcode,
4087           issues.date_due < NOW() AS is_overdue,
4088           biblio.author,
4089           biblio.title,
4090           borrowers.firstname,
4091           borrowers.surname,
4092           borrowers.cardnumber,
4093           borrowers.borrowernumber
4094         FROM items
4095         LEFT JOIN issues ON items.itemnumber = issues.itemnumber
4096         LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
4097         LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
4098         WHERE issues.onsite_checkout = 1
4099     |, { Slice => {} } );
4100 }
4101
4102 sub GetTopIssues {
4103     my ($params) = @_;
4104
4105     my ($count, $branch, $itemtype, $ccode, $newness)
4106         = @$params{qw(count branch itemtype ccode newness)};
4107
4108     my $dbh = C4::Context->dbh;
4109     my $query = q{
4110         SELECT b.biblionumber, b.title, b.author, bi.itemtype, bi.publishercode,
4111           bi.place, bi.publicationyear, b.copyrightdate, bi.pages, bi.size,
4112           i.ccode, SUM(i.issues) AS count
4113         FROM biblio b
4114         LEFT JOIN items i ON (i.biblionumber = b.biblionumber)
4115         LEFT JOIN biblioitems bi ON (bi.biblionumber = b.biblionumber)
4116     };
4117
4118     my (@where_strs, @where_args);
4119
4120     if ($branch) {
4121         push @where_strs, 'i.homebranch = ?';
4122         push @where_args, $branch;
4123     }
4124     if ($itemtype) {
4125         if (C4::Context->preference('item-level_itypes')){
4126             push @where_strs, 'i.itype = ?';
4127             push @where_args, $itemtype;
4128         } else {
4129             push @where_strs, 'bi.itemtype = ?';
4130             push @where_args, $itemtype;
4131         }
4132     }
4133     if ($ccode) {
4134         push @where_strs, 'i.ccode = ?';
4135         push @where_args, $ccode;
4136     }
4137     if ($newness) {
4138         push @where_strs, 'TO_DAYS(NOW()) - TO_DAYS(b.datecreated) <= ?';
4139         push @where_args, $newness;
4140     }
4141
4142     if (@where_strs) {
4143         $query .= 'WHERE ' . join(' AND ', @where_strs);
4144     }
4145
4146     $query .= q{
4147         GROUP BY b.biblionumber
4148         HAVING count > 0
4149         ORDER BY count DESC
4150     };
4151
4152     $count = int($count);
4153     if ($count > 0) {
4154         $query .= "LIMIT $count";
4155     }
4156
4157     my $rows = $dbh->selectall_arrayref($query, { Slice => {} }, @where_args);
4158
4159     return @$rows;
4160 }
4161
4162 1;
4163 __END__
4164
4165 =head1 AUTHOR
4166
4167 Koha Development Team <http://koha-community.org/>
4168
4169 =cut
4170