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