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