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