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