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