barcodedecode() did not always return barcode
[koha.git] / C4 / Circulation.pm
1 package C4::Circulation;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 #use warnings;  # soon!
23 use C4::Context;
24 use C4::Stats;
25 use C4::Reserves;
26 use C4::Koha;
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 Date::Calc qw(
34   Today
35   Today_and_Now
36   Add_Delta_YM
37   Add_Delta_DHMS
38   Date_to_Days
39   Day_of_Week
40   Add_Delta_Days        
41 );
42 use POSIX qw(strftime);
43 use C4::Branch; # GetBranches
44 use C4::Log; # logaction
45
46 use Data::Dumper;
47
48 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
49
50 BEGIN {
51         require Exporter;
52         $VERSION = 3.02;        # for version checking
53         @ISA    = qw(Exporter);
54
55         # FIXME subs that should probably be elsewhere
56         push @EXPORT, qw(
57                 &FixOverduesOnReturn
58                 &barcodedecode
59         );
60
61         # subs to deal with issuing a book
62         push @EXPORT, qw(
63                 &CanBookBeIssued
64                 &CanBookBeRenewed
65                 &AddIssue
66                 &AddRenewal
67                 &GetRenewCount
68                 &GetItemIssue
69                 &GetItemIssues
70                 &GetBorrowerIssues
71                 &GetIssuingCharges
72                 &GetIssuingRule
73         &GetBranchBorrowerCircRule
74                 &GetBiblioIssues
75                 &AnonymiseIssueHistory
76         );
77
78         # subs to deal with returns
79         push @EXPORT, qw(
80                 &AddReturn
81         &MarkIssueReturned
82         );
83
84         # subs to deal with transfers
85         push @EXPORT, qw(
86                 &transferbook
87                 &GetTransfers
88                 &GetTransfersFromTo
89                 &updateWrongTransfer
90                 &DeleteTransfer
91         );
92 }
93
94 =head1 NAME
95
96 C4::Circulation - Koha circulation module
97
98 =head1 SYNOPSIS
99
100 use C4::Circulation;
101
102 =head1 DESCRIPTION
103
104 The functions in this module deal with circulation, issues, and
105 returns, as well as general information about the library.
106 Also deals with stocktaking.
107
108 =head1 FUNCTIONS
109
110 =head2 barcodedecode
111
112 =head3 $str = &barcodedecode($barcode, [$filter]);
113
114 =over 4
115
116 =item Generic filter function for barcode string.
117 Called on every circ if the System Pref itemBarcodeInputFilter is set.
118 Will do some manipulation of the barcode for systems that deliver a barcode
119 to circulation.pl that differs from the barcode stored for the item.
120 For proper functioning of this filter, calling the function on the 
121 correct barcode string (items.barcode) should return an unaltered barcode.
122
123 The optional $filter argument is to allow for testing or explicit 
124 behavior that ignores the System Pref.  Valid values are the same as the 
125 System Pref options.
126
127 =back
128
129 =cut
130
131 # FIXME -- the &decode fcn below should be wrapped into this one.
132 # FIXME -- these plugins should be moved out of Circulation.pm
133 #
134 sub barcodedecode {
135     my ($barcode, $filter) = @_;
136     $filter = C4::Context->preference('itemBarcodeInputFilter') unless $filter;
137     $filter or return $barcode;     # ensure filter is defined, else return untouched barcode
138         if ($filter eq 'whitespace') {
139                 $barcode =~ s/\s//g;
140         } elsif ($filter eq 'cuecat') {
141                 chomp($barcode);
142             my @fields = split( /\./, $barcode );
143             my @results = map( decode($_), @fields[ 1 .. $#fields ] );
144             ($#results == 2) and return $results[2];
145         } elsif ($filter eq 'T-prefix') {
146                 if ($barcode =~ /^[Tt](\d)/) {
147                         (defined($1) and $1 eq '0') and return $barcode;
148             $barcode = substr($barcode, 2) + 0;     # FIXME: probably should be substr($barcode, 1)
149                 }
150         return sprintf("T%07d", $barcode);
151         # FIXME: $barcode could be "T1", causing warning: substr outside of string
152         # Why drop the nonzero digit after the T?
153         # Why pass non-digits (or empty string) to "T%07d"?
154         }
155     return $barcode;    # return barcode, modified or not
156 }
157
158 =head2 decode
159
160 =head3 $str = &decode($chunk);
161
162 =over 4
163
164 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
165 returns it.
166
167 FIXME: Should be replaced with Barcode::Cuecat from CPAN
168 or Javascript based decoding on the client side.
169
170 =back
171
172 =cut
173
174 sub decode {
175     my ($encoded) = @_;
176     my $seq =
177       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
178     my @s = map { index( $seq, $_ ); } split( //, $encoded );
179     my $l = ( $#s + 1 ) % 4;
180     if ($l) {
181         if ( $l == 1 ) {
182             # warn "Error: Cuecat decode parsing failed!";
183             return;
184         }
185         $l = 4 - $l;
186         $#s += $l;
187     }
188     my $r = '';
189     while ( $#s >= 0 ) {
190         my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
191         $r .=
192             chr( ( $n >> 16 ) ^ 67 )
193          .chr( ( $n >> 8 & 255 ) ^ 67 )
194          .chr( ( $n & 255 ) ^ 67 );
195         @s = @s[ 4 .. $#s ];
196     }
197     $r = substr( $r, 0, length($r) - $l );
198     return $r;
199 }
200
201 =head2 transferbook
202
203 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
204
205 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
206
207 C<$newbranch> is the code for the branch to which the item should be transferred.
208
209 C<$barcode> is the barcode of the item to be transferred.
210
211 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
212 Otherwise, if an item is reserved, the transfer fails.
213
214 Returns three values:
215
216 =head3 $dotransfer 
217
218 is true if the transfer was successful.
219
220 =head3 $messages
221
222 is a reference-to-hash which may have any of the following keys:
223
224 =over 4
225
226 =item C<BadBarcode>
227
228 There is no item in the catalog with the given barcode. The value is C<$barcode>.
229
230 =item C<IsPermanent>
231
232 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.
233
234 =item C<DestinationEqualsHolding>
235
236 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.
237
238 =item C<WasReturned>
239
240 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.
241
242 =item C<ResFound>
243
244 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>.
245
246 =item C<WasTransferred>
247
248 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
249
250 =back
251
252 =cut
253
254 sub transferbook {
255     my ( $tbr, $barcode, $ignoreRs ) = @_;
256     my $messages;
257     my $dotransfer      = 1;
258     my $branches        = GetBranches();
259     my $itemnumber = GetItemnumberFromBarcode( $barcode );
260     my $issue      = GetItemIssue($itemnumber);
261     my $biblio = GetBiblioFromItemNumber($itemnumber);
262
263     # bad barcode..
264     if ( not $itemnumber ) {
265         $messages->{'BadBarcode'} = $barcode;
266         $dotransfer = 0;
267     }
268
269     # get branches of book...
270     my $hbr = $biblio->{'homebranch'};
271     my $fbr = $biblio->{'holdingbranch'};
272
273     # if is permanent...
274     if ( $hbr && $branches->{$hbr}->{'PE'} ) {
275         $messages->{'IsPermanent'} = $hbr;
276     }
277
278     # can't transfer book if is already there....
279     if ( $fbr eq $tbr ) {
280         $messages->{'DestinationEqualsHolding'} = 1;
281         $dotransfer = 0;
282     }
283
284     # check if it is still issued to someone, return it...
285     if ($issue->{borrowernumber}) {
286         AddReturn( $barcode, $fbr );
287         $messages->{'WasReturned'} = $issue->{borrowernumber};
288     }
289
290     # find reserves.....
291     # That'll save a database query.
292     my ( $resfound, $resrec ) =
293       CheckReserves( $itemnumber );
294     if ( $resfound and not $ignoreRs ) {
295         $resrec->{'ResFound'} = $resfound;
296
297         #         $messages->{'ResFound'} = $resrec;
298         $dotransfer = 1;
299     }
300
301     #actually do the transfer....
302     if ($dotransfer) {
303         ModItemTransfer( $itemnumber, $fbr, $tbr );
304
305         # don't need to update MARC anymore, we do it in batch now
306         $messages->{'WasTransfered'} = 1;
307                 ModDateLastSeen( $itemnumber );
308     }
309     return ( $dotransfer, $messages, $biblio );
310 }
311
312
313 sub TooMany {
314     my $borrower        = shift;
315     my $biblionumber = shift;
316         my $item                = shift;
317     my $cat_borrower    = $borrower->{'categorycode'};
318     my $dbh             = C4::Context->dbh;
319         my $branch;
320         # Get which branchcode we need
321         if (C4::Context->preference('CircControl') eq 'PickupLibrary'){
322                 $branch = C4::Context->userenv->{'branch'}; 
323         }
324         elsif (C4::Context->preference('CircControl') eq 'PatronLibrary'){
325         $branch = $borrower->{'branchcode'}; 
326         }
327         else {
328                 # items home library
329                 $branch = $item->{'homebranch'};
330         }
331         my $type = (C4::Context->preference('item-level_itypes')) 
332                         ? $item->{'itype'}         # item-level
333                         : $item->{'itemtype'};     # biblio-level
334  
335     # given branch, patron category, and item type, determine
336     # applicable issuing rule
337     my $issuing_rule = GetIssuingRule($cat_borrower, $type, $branch);
338
339     # if a rule is found and has a loan limit set, count
340     # how many loans the patron already has that meet that
341     # rule
342     if (defined($issuing_rule) and defined($issuing_rule->{'maxissueqty'})) {
343         my @bind_params;
344         my $count_query = "SELECT COUNT(*) FROM issues
345                            JOIN items USING (itemnumber) ";
346
347         my $rule_itemtype = $issuing_rule->{itemtype};
348         if ($rule_itemtype eq "*") {
349             # matching rule has the default item type, so count only
350             # those existing loans that don't fall under a more
351             # specific rule
352             if (C4::Context->preference('item-level_itypes')) {
353                 $count_query .= " WHERE items.itype NOT IN (
354                                     SELECT itemtype FROM issuingrules
355                                     WHERE branchcode = ?
356                                     AND   (categorycode = ? OR categorycode = ?)
357                                     AND   itemtype <> '*'
358                                   ) ";
359             } else { 
360                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
361                                   WHERE biblioitems.itemtype NOT IN (
362                                     SELECT itemtype FROM issuingrules
363                                     WHERE branchcode = ?
364                                     AND   (categorycode = ? OR categorycode = ?)
365                                     AND   itemtype <> '*'
366                                   ) ";
367             }
368             push @bind_params, $issuing_rule->{branchcode};
369             push @bind_params, $issuing_rule->{categorycode};
370             push @bind_params, $cat_borrower;
371         } else {
372             # rule has specific item type, so count loans of that
373             # specific item type
374             if (C4::Context->preference('item-level_itypes')) {
375                 $count_query .= " WHERE items.itype = ? ";
376             } else { 
377                 $count_query .= " JOIN  biblioitems USING (biblionumber) 
378                                   WHERE biblioitems.itemtype= ? ";
379             }
380             push @bind_params, $type;
381         }
382
383         $count_query .= " AND borrowernumber = ? ";
384         push @bind_params, $borrower->{'borrowernumber'};
385         my $rule_branch = $issuing_rule->{branchcode};
386         if ($rule_branch ne "*") {
387             if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
388                 $count_query .= " AND issues.branchcode = ? ";
389                 push @bind_params, $branch;
390             } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
391                 ; # if branch is the patron's home branch, then count all loans by patron
392             } else {
393                 $count_query .= " AND items.homebranch = ? ";
394                 push @bind_params, $branch;
395             }
396         }
397
398         my $count_sth = $dbh->prepare($count_query);
399         $count_sth->execute(@bind_params);
400         my ($current_loan_count) = $count_sth->fetchrow_array;
401
402         my $max_loans_allowed = $issuing_rule->{'maxissueqty'};
403         if ($current_loan_count >= $max_loans_allowed) {
404             return "$current_loan_count / $max_loans_allowed";
405         }
406     }
407
408     # Now count total loans against the limit for the branch
409     my $branch_borrower_circ_rule = GetBranchBorrowerCircRule($branch, $cat_borrower);
410     if (defined($branch_borrower_circ_rule->{maxissueqty})) {
411         my @bind_params = ();
412         my $branch_count_query = "SELECT COUNT(*) FROM issues 
413                                   JOIN items USING (itemnumber)
414                                   WHERE borrowernumber = ? ";
415         push @bind_params, $borrower->{borrowernumber};
416
417         if (C4::Context->preference('CircControl') eq 'PickupLibrary') {
418             $branch_count_query .= " AND issues.branchcode = ? ";
419             push @bind_params, $branch;
420         } elsif (C4::Context->preference('CircControl') eq 'PatronLibrary') {
421             ; # if branch is the patron's home branch, then count all loans by patron
422         } else {
423             $branch_count_query .= " AND items.homebranch = ? ";
424             push @bind_params, $branch;
425         }
426         my $branch_count_sth = $dbh->prepare($branch_count_query);
427         $branch_count_sth->execute(@bind_params);
428         my ($current_loan_count) = $branch_count_sth->fetchrow_array;
429
430         my $max_loans_allowed = $branch_borrower_circ_rule->{maxissueqty};
431         if ($current_loan_count >= $max_loans_allowed) {
432             return "$current_loan_count / $max_loans_allowed";
433         }
434     }
435
436     # OK, the patron can issue !!!
437     return;
438 }
439
440 =head2 itemissues
441
442   @issues = &itemissues($biblioitemnumber, $biblio);
443
444 Looks up information about who has borrowed the bookZ<>(s) with the
445 given biblioitemnumber.
446
447 C<$biblio> is ignored.
448
449 C<&itemissues> returns an array of references-to-hash. The keys
450 include the fields from the C<items> table in the Koha database.
451 Additional keys include:
452
453 =over 4
454
455 =item C<date_due>
456
457 If the item is currently on loan, this gives the due date.
458
459 If the item is not on loan, then this is either "Available" or
460 "Cancelled", if the item has been withdrawn.
461
462 =item C<card>
463
464 If the item is currently on loan, this gives the card number of the
465 patron who currently has the item.
466
467 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
468
469 These give the timestamp for the last three times the item was
470 borrowed.
471
472 =item C<card0>, C<card1>, C<card2>
473
474 The card number of the last three patrons who borrowed this item.
475
476 =item C<borrower0>, C<borrower1>, C<borrower2>
477
478 The borrower number of the last three patrons who borrowed this item.
479
480 =back
481
482 =cut
483
484 #'
485 sub itemissues {
486     my ( $bibitem, $biblio ) = @_;
487     my $dbh = C4::Context->dbh;
488     my $sth =
489       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
490       || die $dbh->errstr;
491     my $i = 0;
492     my @results;
493
494     $sth->execute($bibitem) || die $sth->errstr;
495
496     while ( my $data = $sth->fetchrow_hashref ) {
497
498         # Find out who currently has this item.
499         # FIXME - Wouldn't it be better to do this as a left join of
500         # some sort? Currently, this code assumes that if
501         # fetchrow_hashref() fails, then the book is on the shelf.
502         # fetchrow_hashref() can fail for any number of reasons (e.g.,
503         # database server crash), not just because no items match the
504         # search criteria.
505         my $sth2 = $dbh->prepare(
506             "SELECT * FROM issues
507                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
508                 WHERE itemnumber = ?
509             "
510         );
511
512         $sth2->execute( $data->{'itemnumber'} );
513         if ( my $data2 = $sth2->fetchrow_hashref ) {
514             $data->{'date_due'} = $data2->{'date_due'};
515             $data->{'card'}     = $data2->{'cardnumber'};
516             $data->{'borrower'} = $data2->{'borrowernumber'};
517         }
518         else {
519             $data->{'date_due'} = ($data->{'wthdrawn'} eq '1') ? 'Cancelled' : 'Available';
520         }
521
522         $sth2->finish;
523
524         # Find the last 3 people who borrowed this item.
525         $sth2 = $dbh->prepare(
526             "SELECT * FROM old_issues
527                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
528                 WHERE itemnumber = ?
529                 ORDER BY returndate DESC,timestamp DESC"
530         );
531
532         $sth2->execute( $data->{'itemnumber'} );
533         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
534         {    # FIXME : error if there is less than 3 pple borrowing this item
535             if ( my $data2 = $sth2->fetchrow_hashref ) {
536                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
537                 $data->{"card$i2"}      = $data2->{'cardnumber'};
538                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
539             }    # if
540         }    # for
541
542         $sth2->finish;
543         $results[$i] = $data;
544         $i++;
545     }
546
547     $sth->finish;
548     return (@results);
549 }
550
551 =head2 CanBookBeIssued
552
553 Check if a book can be issued.
554
555 ( $issuingimpossible, $needsconfirmation ) =  CanBookBeIssued( $borrower, $barcode, $duedatespec, $inprocess );
556
557 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
558
559 =over 4
560
561 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
562
563 =item C<$barcode> is the bar code of the book being issued.
564
565 =item C<$duedatespec> is a C4::Dates object.
566
567 =item C<$inprocess>
568
569 =back
570
571 Returns :
572
573 =over 4
574
575 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
576 Possible values are :
577
578 =back
579
580 =head3 INVALID_DATE 
581
582 sticky due date is invalid
583
584 =head3 GNA
585
586 borrower gone with no address
587
588 =head3 CARD_LOST
589
590 borrower declared it's card lost
591
592 =head3 DEBARRED
593
594 borrower debarred
595
596 =head3 UNKNOWN_BARCODE
597
598 barcode unknown
599
600 =head3 NOT_FOR_LOAN
601
602 item is not for loan
603
604 =head3 WTHDRAWN
605
606 item withdrawn.
607
608 =head3 RESTRICTED
609
610 item is restricted (set by ??)
611
612 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
613 Possible values are :
614
615 =head3 DEBT
616
617 borrower has debts.
618
619 =head3 RENEW_ISSUE
620
621 renewing, not issuing
622
623 =head3 ISSUED_TO_ANOTHER
624
625 issued to someone else.
626
627 =head3 RESERVED
628
629 reserved for someone else.
630
631 =head3 INVALID_DATE
632
633 sticky due date is invalid
634
635 =head3 TOO_MANY
636
637 if the borrower borrows to much things
638
639 =cut
640
641 sub CanBookBeIssued {
642     my ( $borrower, $barcode, $duedate, $inprocess ) = @_;
643     my %needsconfirmation;    # filled with problems that needs confirmations
644     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
645     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
646     my $issue = GetItemIssue($item->{itemnumber});
647         my $biblioitem = GetBiblioItemData($item->{biblioitemnumber});
648         $item->{'itemtype'}=$item->{'itype'}; 
649     my $dbh             = C4::Context->dbh;
650
651     #
652     # DUE DATE is OK ? -- should already have checked.
653     #
654     #$issuingimpossible{INVALID_DATE} = 1 unless ($duedate);
655
656     #
657     # BORROWER STATUS
658     #
659     if ( $borrower->{'category_type'} eq 'X' && (  $item->{barcode}  )) { 
660         # stats only borrower -- add entry to statistics table, and return issuingimpossible{STATS} = 1  .
661         &UpdateStats(C4::Context->userenv->{'branch'},'localuse','','',$item->{'itemnumber'},$item->{'itemtype'},$borrower->{'borrowernumber'});
662         return( { STATS => 1 }, {});
663     }
664     if ( $borrower->{flags}->{GNA} ) {
665         $issuingimpossible{GNA} = 1;
666     }
667     if ( $borrower->{flags}->{'LOST'} ) {
668         $issuingimpossible{CARD_LOST} = 1;
669     }
670     if ( $borrower->{flags}->{'DBARRED'} ) {
671         $issuingimpossible{DEBARRED} = 1;
672     }
673     if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
674         $issuingimpossible{EXPIRED} = 1;
675     } else {
676         my @expirydate=  split /-/,$borrower->{'dateexpiry'};
677         if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
678             Date_to_Days(Today) > Date_to_Days( @expirydate )) {
679             $issuingimpossible{EXPIRED} = 1;                                   
680         }
681     }
682     #
683     # BORROWER STATUS
684     #
685
686     # DEBTS
687     my ($amount) =
688       C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, '' && $duedate->output('iso') );
689     if ( C4::Context->preference("IssuingInProcess") ) {
690         my $amountlimit = C4::Context->preference("noissuescharge");
691         if ( $amount > $amountlimit && !$inprocess ) {
692             $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
693         }
694         elsif ( $amount > 0 && $amount <= $amountlimit && !$inprocess ) {
695             $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
696         }
697     }
698     else {
699         if ( $amount > 0 ) {
700             $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
701         }
702     }
703
704     #
705     # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
706     #
707         my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
708     $needsconfirmation{TOO_MANY} = $toomany if $toomany;
709
710     #
711     # ITEM CHECKING
712     #
713     unless ( $item->{barcode} ) {
714         $issuingimpossible{UNKNOWN_BARCODE} = 1;
715     }
716     if (   $item->{'notforloan'}
717         && $item->{'notforloan'} > 0 )
718     {
719         $issuingimpossible{NOT_FOR_LOAN} = 1;
720     }
721         elsif ( !$item->{'notforloan'} ){
722                 # we have to check itemtypes.notforloan also
723                 if (C4::Context->preference('item-level_itypes')){
724                         # this should probably be a subroutine
725                         my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
726                         $sth->execute($item->{'itemtype'});
727                         my $notforloan=$sth->fetchrow_hashref();
728                         $sth->finish();
729                         if ($notforloan->{'notforloan'} == 1){
730                                 $issuingimpossible{NOT_FOR_LOAN} = 1;                           
731                         }
732                 }
733                 elsif ($biblioitem->{'notforloan'} == 1){
734                         $issuingimpossible{NOT_FOR_LOAN} = 1;
735                 }
736         }
737     if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
738     {
739         $issuingimpossible{WTHDRAWN} = 1;
740     }
741     if (   $item->{'restricted'}
742         && $item->{'restricted'} == 1 )
743     {
744         $issuingimpossible{RESTRICTED} = 1;
745     }
746     if ( C4::Context->preference("IndependantBranches") ) {
747         my $userenv = C4::Context->userenv;
748         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
749             $issuingimpossible{NOTSAMEBRANCH} = 1
750               if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
751         }
752     }
753
754     #
755     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
756     #
757     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
758     {
759
760         # Already issued to current borrower. Ask whether the loan should
761         # be renewed.
762         my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
763             $borrower->{'borrowernumber'},
764             $item->{'itemnumber'}
765         );
766         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
767             $issuingimpossible{NO_MORE_RENEWALS} = 1;
768         }
769         else {
770             $needsconfirmation{RENEW_ISSUE} = 1;
771         }
772     }
773     elsif ($issue->{borrowernumber}) {
774
775         # issued to someone else
776         my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
777
778 #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
779         $needsconfirmation{ISSUED_TO_ANOTHER} =
780 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
781     }
782
783     # See if the item is on reserve.
784     my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
785     if ($restype) {
786                 my $resbor = $res->{'borrowernumber'};
787                 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
788                 my $branches  = GetBranches();
789                 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
790         if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
791         {
792             # The item is on reserve and waiting, but has been
793             # reserved by some other patron.
794             $needsconfirmation{RESERVE_WAITING} =
795 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
796         }
797         elsif ( $restype eq "Reserved" ) {
798             # The item is on reserve for someone else.
799             $needsconfirmation{RESERVED} =
800 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
801         }
802     }
803     if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
804         if ( $borrower->{'categorycode'} eq 'W' ) {
805             my %emptyhash;
806             return ( \%emptyhash, \%needsconfirmation );
807         }
808         }
809         return ( \%issuingimpossible, \%needsconfirmation );
810 }
811
812 =head2 AddIssue
813
814 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
815
816 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
817
818 =over 4
819
820 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
821
822 =item C<$barcode> is the barcode of the item being issued.
823
824 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
825 Calculated if empty.
826
827 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
828
829 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
830 Defaults to today.  Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
831
832 AddIssue does the following things :
833 - step 01: check that there is a borrowernumber & a barcode provided
834 - check for RENEWAL (book issued & being issued to the same patron)
835     - renewal YES = Calculate Charge & renew
836     - renewal NO  = 
837         * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
838         * RESERVE PLACED ?
839             - fill reserve if reserve to this patron
840             - cancel reserve or not, otherwise
841         * TRANSFERT PENDING ?
842             - complete the transfert
843         * ISSUE THE BOOK
844
845 =back
846
847 =cut
848
849 sub AddIssue {
850     my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
851     my $dbh = C4::Context->dbh;
852         my $barcodecheck=CheckValidBarcode($barcode);
853
854     # $issuedate defaults to today.
855     if ( ! defined $issuedate ) {
856         $issuedate = strftime( "%Y-%m-%d", localtime );
857         # TODO: for hourly circ, this will need to be a C4::Dates object
858         # and all calls to AddIssue including issuedate will need to pass a Dates object.
859     }
860         if ($borrower and $barcode and $barcodecheck ne '0'){
861                 # find which item we issue
862                 my $item = GetItem('', $barcode) or return undef;       # if we don't get an Item, abort.
863                 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
864                      (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'}        : 
865                      $item->{'homebranch'};     # fallback to item's homebranch
866                 
867                 # get actual issuing if there is one
868                 my $actualissue = GetItemIssue( $item->{itemnumber});
869                 
870                 # get biblioinformation for this item
871                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
872                 
873                 #
874                 # check if we just renew the issue.
875                 #
876                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
877                         $datedue = AddRenewal(
878                                 $borrower->{'borrowernumber'},
879                                 $item->{'itemnumber'},
880                                 $branch,
881                                 $datedue,
882                 $issuedate, # here interpreted as the renewal date
883                         );
884                 }
885                 else {
886         # it's NOT a renewal
887                         if ( $actualissue->{borrowernumber}) {
888                                 # This book is currently on loan, but not to the person
889                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
890                                 AddReturn(
891                                         $item->{'barcode'},
892                                         C4::Context->userenv->{'branch'}
893                                 );
894                         }
895
896                         # See if the item is on reserve.
897                         my ( $restype, $res ) =
898                           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
899                         if ($restype) {
900                                 my $resbor = $res->{'borrowernumber'};
901                                 if ( $resbor eq $borrower->{'borrowernumber'} ) {
902                                         # The item is reserved by the current patron
903                                         ModReserveFill($res);
904                                 }
905                                 elsif ( $restype eq "Waiting" ) {
906                                         # warn "Waiting";
907                                         # The item is on reserve and waiting, but has been
908                                         # reserved by some other patron.
909                                 }
910                                 elsif ( $restype eq "Reserved" ) {
911                                         # warn "Reserved";
912                                         # The item is reserved by someone else.
913                                         if ($cancelreserve) { # cancel reserves on this item
914                                                 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
915                                         }
916                                 }
917                                 if ($cancelreserve) {
918                                         CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
919                                 }
920                                 else {
921                                         # set waiting reserve to first in reserve queue as book isn't waiting now
922                                         ModReserve(1,
923                                                 $res->{'biblionumber'},
924                                                 $res->{'borrowernumber'},
925                                                 $res->{'branchcode'}
926                                         );
927                                 }
928                         }
929
930                         # Starting process for transfer job (checking transfert and validate it if we have one)
931             my ($datesent) = GetTransfers($item->{'itemnumber'});
932             if ($datesent) {
933         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
934                 my $sth =
935                     $dbh->prepare(
936                     "UPDATE branchtransfers 
937                         SET datearrived = now(),
938                         tobranch = ?,
939                         comments = 'Forced branchtransfer'
940                     WHERE itemnumber= ? AND datearrived IS NULL"
941                     );
942                 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
943             }
944
945         # Record in the database the fact that the book was issued.
946         my $sth =
947           $dbh->prepare(
948                 "INSERT INTO issues 
949                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
950                 VALUES (?,?,?,?,?)"
951           );
952         unless ($datedue) {
953             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
954             my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
955             $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
956
957             # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
958             if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
959                 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
960             }
961         }
962         $sth->execute(
963             $borrower->{'borrowernumber'},      # borrowernumber
964             $item->{'itemnumber'},              # itemnumber
965             $issuedate,                         # issuedate
966             $datedue->output('iso'),            # date_due
967             C4::Context->userenv->{'branch'}    # branchcode
968         );
969         $sth->finish;
970         $item->{'issues'}++;
971         ModItem({ issues           => $item->{'issues'},
972                   holdingbranch    => C4::Context->userenv->{'branch'},
973                   itemlost         => 0,
974                   datelastborrowed => C4::Dates->new()->output('iso'),
975                   onloan           => $datedue->output('iso'),
976                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
977         ModDateLastSeen( $item->{'itemnumber'} );
978         
979         # If it costs to borrow this book, charge it to the patron's account.
980         my ( $charge, $itemtype ) = GetIssuingCharges(
981             $item->{'itemnumber'},
982             $borrower->{'borrowernumber'}
983         );
984         if ( $charge > 0 ) {
985             AddIssuingCharge(
986                 $item->{'itemnumber'},
987                 $borrower->{'borrowernumber'}, $charge
988             );
989             $item->{'charge'} = $charge;
990         }
991
992         # Record the fact that this book was issued.
993         &UpdateStats(
994             C4::Context->userenv->{'branch'},
995             'issue', $charge,
996             ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
997             $item->{'itype'}, $borrower->{'borrowernumber'}
998         );
999     }
1000     
1001     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'}) 
1002         if C4::Context->preference("IssueLog");
1003   }
1004   return ($datedue);    # not necessarily the same as when it came in!
1005 }
1006
1007 =head2 GetLoanLength
1008
1009 Get loan length for an itemtype, a borrower type and a branch
1010
1011 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1012
1013 =cut
1014
1015 sub GetLoanLength {
1016     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1017     my $dbh = C4::Context->dbh;
1018     my $sth =
1019       $dbh->prepare(
1020 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1021       );
1022 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1023 # try to find issuelength & return the 1st available.
1024 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1025     $sth->execute( $borrowertype, $itemtype, $branchcode );
1026     my $loanlength = $sth->fetchrow_hashref;
1027     return $loanlength->{issuelength}
1028       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1029
1030     $sth->execute( $borrowertype, "*", $branchcode );
1031     $loanlength = $sth->fetchrow_hashref;
1032     return $loanlength->{issuelength}
1033       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1034
1035     $sth->execute( "*", $itemtype, $branchcode );
1036     $loanlength = $sth->fetchrow_hashref;
1037     return $loanlength->{issuelength}
1038       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1039
1040     $sth->execute( "*", "*", $branchcode );
1041     $loanlength = $sth->fetchrow_hashref;
1042     return $loanlength->{issuelength}
1043       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1044
1045     $sth->execute( $borrowertype, $itemtype, "*" );
1046     $loanlength = $sth->fetchrow_hashref;
1047     return $loanlength->{issuelength}
1048       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1049
1050     $sth->execute( $borrowertype, "*", "*" );
1051     $loanlength = $sth->fetchrow_hashref;
1052     return $loanlength->{issuelength}
1053       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1054
1055     $sth->execute( "*", $itemtype, "*" );
1056     $loanlength = $sth->fetchrow_hashref;
1057     return $loanlength->{issuelength}
1058       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1059
1060     $sth->execute( "*", "*", "*" );
1061     $loanlength = $sth->fetchrow_hashref;
1062     return $loanlength->{issuelength}
1063       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1064
1065     # if no rule is set => 21 days (hardcoded)
1066     return 21;
1067 }
1068
1069 =head2 GetIssuingRule
1070
1071 FIXME - This is a copy-paste of GetLoanLength 
1072 as a stop-gap.  Do not wish to change API for GetLoanLength 
1073 this close to release, however, Overdues::GetIssuingRules is broken.
1074
1075 Get the issuing rule for an itemtype, a borrower type and a branch
1076 Returns a hashref from the issuingrules table.
1077
1078 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1079
1080 =cut
1081
1082 sub GetIssuingRule {
1083     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1084     my $dbh = C4::Context->dbh;
1085     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"  );
1086     my $irule;
1087
1088         $sth->execute( $borrowertype, $itemtype, $branchcode );
1089     $irule = $sth->fetchrow_hashref;
1090     return $irule if defined($irule) ;
1091
1092     $sth->execute( $borrowertype, "*", $branchcode );
1093     $irule = $sth->fetchrow_hashref;
1094     return $irule if defined($irule) ;
1095
1096     $sth->execute( "*", $itemtype, $branchcode );
1097     $irule = $sth->fetchrow_hashref;
1098     return $irule if defined($irule) ;
1099
1100     $sth->execute( "*", "*", $branchcode );
1101     $irule = $sth->fetchrow_hashref;
1102     return $irule if defined($irule) ;
1103
1104     $sth->execute( $borrowertype, $itemtype, "*" );
1105     $irule = $sth->fetchrow_hashref;
1106     return $irule if defined($irule) ;
1107
1108     $sth->execute( $borrowertype, "*", "*" );
1109     $irule = $sth->fetchrow_hashref;
1110     return $irule if defined($irule) ;
1111
1112     $sth->execute( "*", $itemtype, "*" );
1113     $irule = $sth->fetchrow_hashref;
1114     return $irule if defined($irule) ;
1115
1116     $sth->execute( "*", "*", "*" );
1117     $irule = $sth->fetchrow_hashref;
1118     return $irule if defined($irule) ;
1119
1120     # if no rule matches,
1121     return undef;
1122 }
1123
1124 =head2 GetBranchBorrowerCircRule
1125
1126 =over 4
1127
1128 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1129
1130 =back
1131
1132 Retrieves circulation rule attributes that apply to the given
1133 branch and patron category, regardless of item type.  
1134 The return value is a hashref containing the following key:
1135
1136 maxissueqty - maximum number of loans that a
1137 patron of the given category can have at the given
1138 branch.  If the value is undef, no limit.
1139
1140 This will first check for a specific branch and
1141 category match from branch_borrower_circ_rules. 
1142
1143 If no rule is found, it will then check default_branch_circ_rules
1144 (same branch, default category).  If no rule is found,
1145 it will then check default_borrower_circ_rules (default 
1146 branch, same category), then failing that, default_circ_rules
1147 (default branch, default category).
1148
1149 If no rule has been found in the database, it will default to
1150 the buillt in rule:
1151
1152 maxissueqty - undef
1153
1154 C<$branchcode> and C<$categorycode> should contain the
1155 literal branch code and patron category code, respectively - no
1156 wildcards.
1157
1158 =cut
1159
1160 sub GetBranchBorrowerCircRule {
1161     my $branchcode = shift;
1162     my $categorycode = shift;
1163
1164     my $branch_cat_query = "SELECT maxissueqty
1165                             FROM branch_borrower_circ_rules
1166                             WHERE branchcode = ?
1167                             AND   categorycode = ?";
1168     my $dbh = C4::Context->dbh();
1169     my $sth = $dbh->prepare($branch_cat_query);
1170     $sth->execute($branchcode, $categorycode);
1171     my $result;
1172     if ($result = $sth->fetchrow_hashref()) {
1173         return $result;
1174     }
1175
1176     # try same branch, default borrower category
1177     my $branch_query = "SELECT maxissueqty
1178                         FROM default_branch_circ_rules
1179                         WHERE branchcode = ?";
1180     $sth = $dbh->prepare($branch_query);
1181     $sth->execute($branchcode);
1182     if ($result = $sth->fetchrow_hashref()) {
1183         return $result;
1184     }
1185
1186     # try default branch, same borrower category
1187     my $category_query = "SELECT maxissueqty
1188                           FROM default_borrower_circ_rules
1189                           WHERE categorycode = ?";
1190     $sth = $dbh->prepare($category_query);
1191     $sth->execute($categorycode);
1192     if ($result = $sth->fetchrow_hashref()) {
1193         return $result;
1194     }
1195   
1196     # try default branch, default borrower category
1197     my $default_query = "SELECT maxissueqty
1198                           FROM default_circ_rules";
1199     $sth = $dbh->prepare($default_query);
1200     $sth->execute();
1201     if ($result = $sth->fetchrow_hashref()) {
1202         return $result;
1203     }
1204     
1205     # built-in default circulation rule
1206     return {
1207         maxissueqty => undef,
1208     };
1209 }
1210
1211 =head2 AddReturn
1212
1213 ($doreturn, $messages, $iteminformation, $borrower) =
1214     &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1215
1216 Returns a book.
1217
1218 =over 4
1219
1220 =item C<$barcode> is the bar code of the book being returned.
1221
1222 =item C<$branch> is the code of the branch where the book is being returned.
1223
1224 =item C<$exemptfine> indicates that overdue charges for the item will be
1225 removed.
1226
1227 =item C<$dropbox> indicates that the check-in date is assumed to be
1228 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1229 overdue charges are applied and C<$dropbox> is true, the last charge
1230 will be removed.  This assumes that the fines accrual script has run
1231 for _today_.
1232
1233 =back
1234
1235 C<&AddReturn> returns a list of four items:
1236
1237 C<$doreturn> is true iff the return succeeded.
1238
1239 C<$messages> is a reference-to-hash giving the reason for failure:
1240
1241 =over 4
1242
1243 =item C<BadBarcode>
1244
1245 No item with this barcode exists. The value is C<$barcode>.
1246
1247 =item C<NotIssued>
1248
1249 The book is not currently on loan. The value is C<$barcode>.
1250
1251 =item C<IsPermanent>
1252
1253 The book's home branch is a permanent collection. If you have borrowed
1254 this book, you are not allowed to return it. The value is the code for
1255 the book's home branch.
1256
1257 =item C<wthdrawn>
1258
1259 This book has been withdrawn/cancelled. The value should be ignored.
1260
1261 =item C<ResFound>
1262
1263 The item was reserved. The value is a reference-to-hash whose keys are
1264 fields from the reserves table of the Koha database, and
1265 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1266 either C<Waiting>, C<Reserved>, or 0.
1267
1268 =back
1269
1270 C<$borrower> is a reference-to-hash, giving information about the
1271 patron who last borrowed the book.
1272
1273 =cut
1274
1275 sub AddReturn {
1276     my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1277     my $dbh      = C4::Context->dbh;
1278     my $messages;
1279     my $doreturn = 1;
1280     my $borrower;
1281     my $validTransfert = 0;
1282     my $reserveDone = 0;
1283     
1284     # get information on item
1285     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1286     my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1287 #     use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);  
1288     unless ($iteminformation->{'itemnumber'} ) {
1289         $messages->{'BadBarcode'} = $barcode;
1290         $doreturn = 0;
1291     } else {
1292         # find the borrower
1293         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1294             $messages->{'NotIssued'} = $barcode;
1295             # even though item is not on loan, it may still
1296             # be transferred; therefore, get current branch information
1297             my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1298             $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1299             $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1300             $doreturn = 0;
1301         }
1302     
1303         # check if the book is in a permanent collection....
1304         my $hbr      = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1305         my $branches = GetBranches();
1306                 # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1307         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1308             $messages->{'IsPermanent'} = $hbr;
1309         }
1310                 
1311                     # if independent branches are on and returning to different branch, refuse the return
1312         if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1313                           $messages->{'Wrongbranch'} = 1;
1314                           $doreturn=0;
1315                     }
1316                         
1317         # check that the book has been cancelled
1318         if ( $iteminformation->{'wthdrawn'} ) {
1319             $messages->{'wthdrawn'} = 1;
1320             $doreturn = 0;
1321         }
1322     
1323     #     new op dev : if the book returned in an other branch update the holding branch
1324     
1325     # update issues, thereby returning book (should push this out into another subroutine
1326         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1327     
1328     # case of a return of document (deal with issues and holdingbranch)
1329     
1330         if ($doreturn) {
1331                         my $circControlBranch;
1332                         if($dropbox) {
1333                                 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1334                                 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1335                                 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1336                                         $circControlBranch = $iteminformation->{homebranch};
1337                                 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1338                                         $circControlBranch = $borrower->{branchcode};
1339                                 } else { # CircControl must be PickupLibrary.
1340                                         $circControlBranch = $iteminformation->{holdingbranch};
1341                                         # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1342                                 }
1343                         }
1344             MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1345             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?  
1346             # continue to deal with returns cases, but not only if we have an issue
1347
1348             # the holdingbranch is updated if the document is returned in an other location .
1349             if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1350                            UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1351                            #           reload iteminformation holdingbranch with the userenv value
1352                            $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1353             }
1354             ModDateLastSeen( $iteminformation->{'itemnumber'} );
1355             ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1356
1357             if ($iteminformation->{borrowernumber}){
1358               ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1359             }
1360         }       
1361         # fix up the accounts.....
1362         if ( $iteminformation->{'itemlost'} ) {
1363             $messages->{'WasLost'} = 1;
1364         }
1365     
1366     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1367     #     check if we have a transfer for this document
1368         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1369     
1370     #     if we have a transfer to do, we update the line of transfers with the datearrived
1371         if ($datesent) {
1372             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1373                     my $sth =
1374                     $dbh->prepare(
1375                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1376                     );
1377                     $sth->execute( $iteminformation->{'itemnumber'} );
1378                     $sth->finish;
1379     #         now we check if there is a reservation with the validate of transfer if we have one, we can         set it with the status 'W'
1380             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1381             }
1382         else {
1383             $messages->{'WrongTransfer'} = $tobranch;
1384             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1385         }
1386         $validTransfert = 1;
1387         }
1388     
1389     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1390         # fix up the accounts.....
1391         if ($iteminformation->{'itemlost'}) {
1392                 FixAccountForLostAndReturned($iteminformation, $borrower);
1393                 $messages->{'WasLost'} = 1;
1394         }
1395         # fix up the overdues in accounts...
1396         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1397             $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1398     
1399     # find reserves.....
1400     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1401         my ( $resfound, $resrec ) =
1402         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1403         if ($resfound) {
1404             $resrec->{'ResFound'}   = $resfound;
1405             $messages->{'ResFound'} = $resrec;
1406             $reserveDone = 1;
1407         }
1408     
1409         # update stats?
1410         # Record the fact that this book was returned.
1411         UpdateStats(
1412             $branch, 'return', '0', '',
1413             $iteminformation->{'itemnumber'},
1414             $biblio->{'itemtype'},
1415             $borrower->{'borrowernumber'}
1416         );
1417         
1418         logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'}) 
1419             if C4::Context->preference("ReturnLog");
1420         
1421         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1422         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1423         
1424         if ($doreturn and ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1425                         if (C4::Context->preference("AutomaticItemReturn") == 1) {
1426                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1427                                 $messages->{'WasTransfered'} = 1;
1428                         }
1429                         else {
1430                                 $messages->{'NeedsTransfer'} = 1;
1431                         }
1432         }
1433     }
1434     return ( $doreturn, $messages, $iteminformation, $borrower );
1435 }
1436
1437 =head2 MarkIssueReturned
1438
1439 =over 4
1440
1441 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1442
1443 =back
1444
1445 Unconditionally marks an issue as being returned by
1446 moving the C<issues> row to C<old_issues> and
1447 setting C<returndate> to the current date, or
1448 the last non-holiday date of the branccode specified in
1449 C<dropbox_branch> .  Assumes you've already checked that 
1450 it's safe to do this, i.e. last non-holiday > issuedate.
1451
1452 if C<$returndate> is specified (in iso format), it is used as the date
1453 of the return. It is ignored when a dropbox_branch is passed in.
1454
1455 Ideally, this function would be internal to C<C4::Circulation>,
1456 not exported, but it is currently needed by one 
1457 routine in C<C4::Accounts>.
1458
1459 =cut
1460
1461 sub MarkIssueReturned {
1462     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1463     my $dbh   = C4::Context->dbh;
1464     my $query = "UPDATE issues SET returndate=";
1465     my @bind;
1466     if ($dropbox_branch) {
1467         my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1468         my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1469         $query .= " ? ";
1470         push @bind, $dropboxdate->output('iso');
1471     } elsif ($returndate) {
1472         $query .= " ? ";
1473         push @bind, $returndate;
1474     } else {
1475         $query .= " now() ";
1476     }
1477     $query .= " WHERE  borrowernumber = ?  AND itemnumber = ?";
1478     push @bind, $borrowernumber, $itemnumber;
1479     # FIXME transaction
1480     my $sth_upd  = $dbh->prepare($query);
1481     $sth_upd->execute(@bind);
1482     my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
1483                                   WHERE borrowernumber = ?
1484                                   AND itemnumber = ?");
1485     $sth_copy->execute($borrowernumber, $itemnumber);
1486     my $sth_del  = $dbh->prepare("DELETE FROM issues
1487                                   WHERE borrowernumber = ?
1488                                   AND itemnumber = ?");
1489     $sth_del->execute($borrowernumber, $itemnumber);
1490 }
1491
1492 =head2 FixOverduesOnReturn
1493
1494     &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1495
1496 C<$brn> borrowernumber
1497
1498 C<$itm> itemnumber
1499
1500 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
1501 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1502
1503 internal function, called only by AddReturn
1504
1505 =cut
1506
1507 sub FixOverduesOnReturn {
1508     my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1509     my $dbh = C4::Context->dbh;
1510
1511     # check for overdue fine
1512     my $sth =
1513       $dbh->prepare(
1514 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1515       );
1516     $sth->execute( $borrowernumber, $item );
1517
1518     # alter fine to show that the book has been returned
1519    my $data; 
1520         if ($data = $sth->fetchrow_hashref) {
1521         my $uquery;
1522                 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1523                 if ($exemptfine) {
1524                         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1525                         if (C4::Context->preference("FinesLog")) {
1526                         &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1527                         }
1528                 } elsif ($dropbox && $data->{lastincrement}) {
1529                         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1530                         my $amt = $data->{amount} - $data->{lastincrement} ;
1531                         if (C4::Context->preference("FinesLog")) {
1532                         &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1533                         }
1534                          $uquery = "update accountlines set accounttype='F' ";
1535                          if($outstanding  >= 0 && $amt >=0) {
1536                                 $uquery .= ", amount = ? , amountoutstanding=? ";
1537                                 unshift @bind, ($amt, $outstanding) ;
1538                         }
1539                 } else {
1540                         $uquery = "update accountlines set accounttype='F' ";
1541                 }
1542                 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1543         my $usth = $dbh->prepare($uquery);
1544         $usth->execute(@bind);
1545         $usth->finish();
1546     }
1547
1548     $sth->finish();
1549     return;
1550 }
1551
1552 =head2 FixAccountForLostAndReturned
1553
1554         &FixAccountForLostAndReturned($iteminfo,$borrower);
1555
1556 Calculates the charge for a book lost and returned (Not exported & used only once)
1557
1558 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1559
1560 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1561
1562 Internal function, called by AddReturn
1563
1564 =cut
1565
1566 sub FixAccountForLostAndReturned {
1567         my ($iteminfo, $borrower) = @_;
1568         my $dbh = C4::Context->dbh;
1569         my $itm = $iteminfo->{'itemnumber'};
1570         # check for charge made for lost book
1571         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1572         $sth->execute($itm);
1573         if (my $data = $sth->fetchrow_hashref) {
1574         # writeoff this amount
1575                 my $offset;
1576                 my $amount = $data->{'amount'};
1577                 my $acctno = $data->{'accountno'};
1578                 my $amountleft;
1579                 if ($data->{'amountoutstanding'} == $amount) {
1580                 $offset = $data->{'amount'};
1581                 $amountleft = 0;
1582                 } else {
1583                 $offset = $amount - $data->{'amountoutstanding'};
1584                 $amountleft = $data->{'amountoutstanding'} - $amount;
1585                 }
1586                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1587                         WHERE (borrowernumber = ?)
1588                         AND (itemnumber = ?) AND (accountno = ?) ");
1589                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1590                 $usth->finish;
1591         #check if any credit is left if so writeoff other accounts
1592                 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1593                 if ($amountleft < 0){
1594                 $amountleft*=-1;
1595                 }
1596                 if ($amountleft > 0){
1597                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1598                                                         AND (amountoutstanding >0) ORDER BY date");
1599                 $msth->execute($data->{'borrowernumber'});
1600         # offset transactions
1601                 my $newamtos;
1602                 my $accdata;
1603                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1604                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1605                         $newamtos = 0;
1606                         $amountleft -= $accdata->{'amountoutstanding'};
1607                         }  else {
1608                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1609                         $amountleft = 0;
1610                         }
1611                         my $thisacct = $accdata->{'accountno'};
1612                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1613                                         WHERE (borrowernumber = ?)
1614                                         AND (accountno=?)");
1615                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1616                         $usth->finish;
1617                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1618                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1619                                 VALUES
1620                                 (?,?,?,?)");
1621                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1622                         $usth->finish;
1623                 }
1624                 $msth->finish;
1625                 }
1626                 if ($amountleft > 0){
1627                         $amountleft*=-1;
1628                 }
1629                 my $desc="Item Returned ".$iteminfo->{'barcode'};
1630                 $usth = $dbh->prepare("INSERT INTO accountlines
1631                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1632                         VALUES (?,?,now(),?,?,'CR',?)");
1633                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1634                 $usth->finish;
1635                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1636                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1637                         VALUES (?,?,?,?)");
1638                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1639                 $usth->finish;
1640         ModItem({ paidfor => '' }, undef, $itm);
1641         }
1642         $sth->finish;
1643         return;
1644 }
1645
1646 =head2 GetItemIssue
1647
1648 $issues = &GetItemIssue($itemnumber);
1649
1650 Returns patrons currently having a book. nothing if item is not issued atm
1651
1652 C<$itemnumber> is the itemnumber
1653
1654 Returns an array of hashes
1655
1656 FIXME: Though the above says that this function returns nothing if the
1657 item is not issued, this actually returns a hasref that looks like
1658 this:
1659     {
1660       itemnumber => 1,
1661       overdue    => 1
1662     }
1663
1664
1665 =cut
1666
1667 sub GetItemIssue {
1668     my ( $itemnumber) = @_;
1669     return unless $itemnumber;
1670     my $dbh = C4::Context->dbh;
1671     my @GetItemIssues;
1672     
1673     # get today date
1674     my $today = POSIX::strftime("%Y%m%d", localtime);
1675
1676     my $sth = $dbh->prepare(
1677         "SELECT * FROM issues 
1678         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1679     WHERE
1680     issues.itemnumber=?");
1681     $sth->execute($itemnumber);
1682     my $data = $sth->fetchrow_hashref;
1683     my $datedue = $data->{'date_due'};
1684     $datedue =~ s/-//g;
1685     if ( $datedue < $today ) {
1686         $data->{'overdue'} = 1;
1687     }
1688     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1689     $sth->finish;
1690     return ($data);
1691 }
1692
1693 =head2 GetItemIssues
1694
1695 $issues = &GetItemIssues($itemnumber, $history);
1696
1697 Returns patrons that have issued a book
1698
1699 C<$itemnumber> is the itemnumber
1700 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1701
1702 Returns an array of hashes
1703
1704 =cut
1705
1706 sub GetItemIssues {
1707     my ( $itemnumber,$history ) = @_;
1708     my $dbh = C4::Context->dbh;
1709     my @GetItemIssues;
1710     
1711     # get today date
1712     my $today = POSIX::strftime("%Y%m%d", localtime);
1713
1714     my $sql = "SELECT * FROM issues 
1715               JOIN borrowers USING (borrowernumber)
1716               JOIN items USING (itemnumber)
1717               WHERE issues.itemnumber = ? ";
1718     if ($history) {
1719         $sql .= "UNION ALL
1720                  SELECT * FROM old_issues 
1721                  LEFT JOIN borrowers USING (borrowernumber)
1722                  JOIN items USING (itemnumber)
1723                  WHERE old_issues.itemnumber = ? ";
1724     }
1725     $sql .= "ORDER BY date_due DESC";
1726     my $sth = $dbh->prepare($sql);
1727     if ($history) {
1728         $sth->execute($itemnumber, $itemnumber);
1729     } else {
1730         $sth->execute($itemnumber);
1731     }
1732     while ( my $data = $sth->fetchrow_hashref ) {
1733         my $datedue = $data->{'date_due'};
1734         $datedue =~ s/-//g;
1735         if ( $datedue < $today ) {
1736             $data->{'overdue'} = 1;
1737         }
1738         my $itemnumber = $data->{'itemnumber'};
1739         push @GetItemIssues, $data;
1740     }
1741     $sth->finish;
1742     return ( \@GetItemIssues );
1743 }
1744
1745 =head2 GetBiblioIssues
1746
1747 $issues = GetBiblioIssues($biblionumber);
1748
1749 this function get all issues from a biblionumber.
1750
1751 Return:
1752 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1753 tables issues and the firstname,surname & cardnumber from borrowers.
1754
1755 =cut
1756
1757 sub GetBiblioIssues {
1758     my $biblionumber = shift;
1759     return undef unless $biblionumber;
1760     my $dbh   = C4::Context->dbh;
1761     my $query = "
1762         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1763         FROM issues
1764             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1765             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1766             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1767             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1768         WHERE biblio.biblionumber = ?
1769         UNION ALL
1770         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1771         FROM old_issues
1772             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1773             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1774             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1775             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1776         WHERE biblio.biblionumber = ?
1777         ORDER BY timestamp
1778     ";
1779     my $sth = $dbh->prepare($query);
1780     $sth->execute($biblionumber, $biblionumber);
1781
1782     my @issues;
1783     while ( my $data = $sth->fetchrow_hashref ) {
1784         push @issues, $data;
1785     }
1786     return \@issues;
1787 }
1788
1789 =head2 GetUpcomingDueIssues
1790
1791 =over 4
1792  
1793 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1794
1795 =back
1796
1797 =cut
1798
1799 sub GetUpcomingDueIssues {
1800     my $params = shift;
1801
1802     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1803     my $dbh = C4::Context->dbh;
1804
1805     my $statement = <<END_SQL;
1806 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1807 FROM issues 
1808 LEFT JOIN items USING (itemnumber)
1809 WhERE returndate is NULL
1810 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1811 END_SQL
1812
1813     my @bind_parameters = ( $params->{'days_in_advance'} );
1814     
1815     my $sth = $dbh->prepare( $statement );
1816     $sth->execute( @bind_parameters );
1817     my $upcoming_dues = $sth->fetchall_arrayref({});
1818     $sth->finish;
1819
1820     return $upcoming_dues;
1821 }
1822
1823 =head2 CanBookBeRenewed
1824
1825 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1826
1827 Find out whether a borrowed item may be renewed.
1828
1829 C<$dbh> is a DBI handle to the Koha database.
1830
1831 C<$borrowernumber> is the borrower number of the patron who currently
1832 has the item on loan.
1833
1834 C<$itemnumber> is the number of the item to renew.
1835
1836 C<$override_limit>, if supplied with a true value, causes
1837 the limit on the number of times that the loan can be renewed
1838 (as controlled by the item type) to be ignored.
1839
1840 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1841 item must currently be on loan to the specified borrower; renewals
1842 must be allowed for the item's type; and the borrower must not have
1843 already renewed the loan. $error will contain the reason the renewal can not proceed
1844
1845 =cut
1846
1847 sub CanBookBeRenewed {
1848
1849     # check renewal status
1850     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1851     my $dbh       = C4::Context->dbh;
1852     my $renews    = 1;
1853     my $renewokay = 0;
1854         my $error;
1855
1856     # Look in the issues table for this item, lent to this borrower,
1857     # and not yet returned.
1858
1859     # FIXME - I think this function could be redone to use only one SQL call.
1860     my $sth1 = $dbh->prepare(
1861         "SELECT * FROM issues
1862             WHERE borrowernumber = ?
1863             AND itemnumber = ?"
1864     );
1865     $sth1->execute( $borrowernumber, $itemnumber );
1866     if ( my $data1 = $sth1->fetchrow_hashref ) {
1867
1868         # Found a matching item
1869
1870         # See if this item may be renewed. This query is convoluted
1871         # because it's a bit messy: given the item number, we need to find
1872         # the biblioitem, which gives us the itemtype, which tells us
1873         # whether it may be renewed.
1874         my $query = "SELECT renewalsallowed FROM items ";
1875         $query .= (C4::Context->preference('item-level_itypes'))
1876                     ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1877                     : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1878                        LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1879         $query .= "WHERE items.itemnumber = ?";
1880         my $sth2 = $dbh->prepare($query);
1881         $sth2->execute($itemnumber);
1882         if ( my $data2 = $sth2->fetchrow_hashref ) {
1883             $renews = $data2->{'renewalsallowed'};
1884         }
1885         if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1886             $renewokay = 1;
1887         }
1888         else {
1889                         $error="too_many";
1890                 }
1891         $sth2->finish;
1892         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1893         if ($resfound) {
1894             $renewokay = 0;
1895                         $error="on_reserve"
1896         }
1897
1898     }
1899     $sth1->finish;
1900     return ($renewokay,$error);
1901 }
1902
1903 =head2 AddRenewal
1904
1905 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1906
1907 Renews a loan.
1908
1909 C<$borrowernumber> is the borrower number of the patron who currently
1910 has the item.
1911
1912 C<$itemnumber> is the number of the item to renew.
1913
1914 C<$branch> is the library branch.  Defaults to the homebranch of the ITEM.
1915
1916 C<$datedue> can be a C4::Dates object used to set the due date.
1917
1918 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
1919 this parameter is not supplied, lastreneweddate is set to the current date.
1920
1921 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1922 from the book's item type.
1923
1924 =cut
1925
1926 sub AddRenewal {
1927         my $borrowernumber = shift or return undef;
1928         my     $itemnumber = shift or return undef;
1929     my $item   = GetItem($itemnumber) or return undef;
1930     my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1931     my $branch  = (@_) ? shift : $item->{homebranch};   # opac-renew doesn't send branch
1932     my $datedue = shift;
1933     my $lastreneweddate = shift;
1934
1935     # If the due date wasn't specified, calculate it by adding the
1936     # book's loan length to today's date.
1937     unless ($datedue && $datedue->output('iso')) {
1938
1939         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1940         my $loanlength = GetLoanLength(
1941             $borrower->{'categorycode'},
1942              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1943                         $item->{homebranch}                     # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1944         );
1945                 #FIXME -- use circControl?
1946                 $datedue =  CalcDateDue(C4::Dates->new(),$loanlength,$branch);  # this branch is the transactional branch.
1947                                                                 # The question of whether to use item's homebranch calendar is open.
1948     }
1949
1950     # $lastreneweddate defaults to today.
1951     unless (defined $lastreneweddate) {
1952         $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1953     }
1954
1955     my $dbh = C4::Context->dbh;
1956     # Find the issues record for this book
1957     my $sth =
1958       $dbh->prepare("SELECT * FROM issues
1959                         WHERE borrowernumber=? 
1960                         AND itemnumber=?"
1961       );
1962     $sth->execute( $borrowernumber, $itemnumber );
1963     my $issuedata = $sth->fetchrow_hashref;
1964     $sth->finish;
1965
1966     # Update the issues record to have the new due date, and a new count
1967     # of how many times it has been renewed.
1968     my $renews = $issuedata->{'renewals'} + 1;
1969     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
1970                             WHERE borrowernumber=? 
1971                             AND itemnumber=?"
1972     );
1973     $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
1974     $sth->finish;
1975
1976     # Update the renewal count on the item, and tell zebra to reindex
1977     $renews = $biblio->{'renewals'} + 1;
1978     ModItem({ renewals => $renews }, $biblio->{'biblionumber'}, $itemnumber);
1979
1980     # Charge a new rental fee, if applicable?
1981     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1982     if ( $charge > 0 ) {
1983         my $accountno = getnextacctno( $borrowernumber );
1984         my $item = GetBiblioFromItemNumber($itemnumber);
1985         $sth = $dbh->prepare(
1986                 "INSERT INTO accountlines
1987                     (date,
1988                                         borrowernumber, accountno, amount,
1989                     description,
1990                                         accounttype, amountoutstanding, itemnumber
1991                                         )
1992                     VALUES (now(),?,?,?,?,?,?,?)"
1993         );
1994         $sth->execute( $borrowernumber, $accountno, $charge,
1995             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1996             'Rent', $charge, $itemnumber );
1997         $sth->finish;
1998     }
1999     # Log the renewal
2000     UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2001         return $datedue;
2002 }
2003
2004 sub GetRenewCount {
2005     # check renewal status
2006     my ($bornum,$itemno)=@_;
2007     my $dbh = C4::Context->dbh;
2008     my $renewcount = 0;
2009         my $renewsallowed = 0;
2010         my $renewsleft = 0;
2011     # Look in the issues table for this item, lent to this borrower,
2012     # and not yet returned.
2013
2014     # FIXME - I think this function could be redone to use only one SQL call.
2015     my $sth = $dbh->prepare("select * from issues
2016                                 where (borrowernumber = ?)
2017                                 and (itemnumber = ?)");
2018     $sth->execute($bornum,$itemno);
2019     my $data = $sth->fetchrow_hashref;
2020     $renewcount = $data->{'renewals'} if $data->{'renewals'};
2021     $sth->finish;
2022     my $query = "SELECT renewalsallowed FROM items ";
2023     $query .= (C4::Context->preference('item-level_itypes'))
2024                 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2025                 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2026                    LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2027     $query .= "WHERE items.itemnumber = ?";
2028     my $sth2 = $dbh->prepare($query);
2029     $sth2->execute($itemno);
2030     my $data2 = $sth2->fetchrow_hashref();
2031     $renewsallowed = $data2->{'renewalsallowed'};
2032     $renewsleft = $renewsallowed - $renewcount;
2033     return ($renewcount,$renewsallowed,$renewsleft);
2034 }
2035
2036 =head2 GetIssuingCharges
2037
2038 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2039
2040 Calculate how much it would cost for a given patron to borrow a given
2041 item, including any applicable discounts.
2042
2043 C<$itemnumber> is the item number of item the patron wishes to borrow.
2044
2045 C<$borrowernumber> is the patron's borrower number.
2046
2047 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2048 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2049 if it's a video).
2050
2051 =cut
2052
2053 sub GetIssuingCharges {
2054
2055     # calculate charges due
2056     my ( $itemnumber, $borrowernumber ) = @_;
2057     my $charge = 0;
2058     my $dbh    = C4::Context->dbh;
2059     my $item_type;
2060
2061     # Get the book's item type and rental charge (via its biblioitem).
2062     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
2063             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2064         $qcharge .= (C4::Context->preference('item-level_itypes'))
2065                 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2066                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2067         
2068     $qcharge .=      "WHERE items.itemnumber =?";
2069    
2070     my $sth1 = $dbh->prepare($qcharge);
2071     $sth1->execute($itemnumber);
2072     if ( my $data1 = $sth1->fetchrow_hashref ) {
2073         $item_type = $data1->{'itemtype'};
2074         $charge    = $data1->{'rentalcharge'};
2075         my $q2 = "SELECT rentaldiscount FROM borrowers
2076             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2077             WHERE borrowers.borrowernumber = ?
2078             AND issuingrules.itemtype = ?";
2079         my $sth2 = $dbh->prepare($q2);
2080         $sth2->execute( $borrowernumber, $item_type );
2081         if ( my $data2 = $sth2->fetchrow_hashref ) {
2082             my $discount = $data2->{'rentaldiscount'};
2083             if ( $discount eq 'NULL' ) {
2084                 $discount = 0;
2085             }
2086             $charge = ( $charge * ( 100 - $discount ) ) / 100;
2087         }
2088         $sth2->finish;
2089     }
2090
2091     $sth1->finish;
2092     return ( $charge, $item_type );
2093 }
2094
2095 =head2 AddIssuingCharge
2096
2097 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2098
2099 =cut
2100
2101 sub AddIssuingCharge {
2102     my ( $itemnumber, $borrowernumber, $charge ) = @_;
2103     my $dbh = C4::Context->dbh;
2104     my $nextaccntno = getnextacctno( $borrowernumber );
2105     my $query ="
2106         INSERT INTO accountlines
2107             (borrowernumber, itemnumber, accountno,
2108             date, amount, description, accounttype,
2109             amountoutstanding)
2110         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2111     ";
2112     my $sth = $dbh->prepare($query);
2113     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2114     $sth->finish;
2115 }
2116
2117 =head2 GetTransfers
2118
2119 GetTransfers($itemnumber);
2120
2121 =cut
2122
2123 sub GetTransfers {
2124     my ($itemnumber) = @_;
2125
2126     my $dbh = C4::Context->dbh;
2127
2128     my $query = '
2129         SELECT datesent,
2130                frombranch,
2131                tobranch
2132         FROM branchtransfers
2133         WHERE itemnumber = ?
2134           AND datearrived IS NULL
2135         ';
2136     my $sth = $dbh->prepare($query);
2137     $sth->execute($itemnumber);
2138     my @row = $sth->fetchrow_array();
2139     $sth->finish;
2140     return @row;
2141 }
2142
2143
2144 =head2 GetTransfersFromTo
2145
2146 @results = GetTransfersFromTo($frombranch,$tobranch);
2147
2148 Returns the list of pending transfers between $from and $to branch
2149
2150 =cut
2151
2152 sub GetTransfersFromTo {
2153     my ( $frombranch, $tobranch ) = @_;
2154     return unless ( $frombranch && $tobranch );
2155     my $dbh   = C4::Context->dbh;
2156     my $query = "
2157         SELECT itemnumber,datesent,frombranch
2158         FROM   branchtransfers
2159         WHERE  frombranch=?
2160           AND  tobranch=?
2161           AND datearrived IS NULL
2162     ";
2163     my $sth = $dbh->prepare($query);
2164     $sth->execute( $frombranch, $tobranch );
2165     my @gettransfers;
2166
2167     while ( my $data = $sth->fetchrow_hashref ) {
2168         push @gettransfers, $data;
2169     }
2170     $sth->finish;
2171     return (@gettransfers);
2172 }
2173
2174 =head2 DeleteTransfer
2175
2176 &DeleteTransfer($itemnumber);
2177
2178 =cut
2179
2180 sub DeleteTransfer {
2181     my ($itemnumber) = @_;
2182     my $dbh          = C4::Context->dbh;
2183     my $sth          = $dbh->prepare(
2184         "DELETE FROM branchtransfers
2185          WHERE itemnumber=?
2186          AND datearrived IS NULL "
2187     );
2188     $sth->execute($itemnumber);
2189     $sth->finish;
2190 }
2191
2192 =head2 AnonymiseIssueHistory
2193
2194 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2195
2196 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2197 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2198
2199 return the number of affected rows.
2200
2201 =cut
2202
2203 sub AnonymiseIssueHistory {
2204     my $date           = shift;
2205     my $borrowernumber = shift;
2206     my $dbh            = C4::Context->dbh;
2207     my $query          = "
2208         UPDATE old_issues
2209         SET    borrowernumber = NULL
2210         WHERE  returndate < '".$date."'
2211           AND borrowernumber IS NOT NULL
2212     ";
2213     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2214     my $rows_affected = $dbh->do($query);
2215     return $rows_affected;
2216 }
2217
2218 =head2 updateWrongTransfer
2219
2220 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2221
2222 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 
2223
2224 =cut
2225
2226 sub updateWrongTransfer {
2227         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2228         my $dbh = C4::Context->dbh;     
2229 # first step validate the actual line of transfert .
2230         my $sth =
2231                 $dbh->prepare(
2232                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2233                 );
2234                 $sth->execute($FromLibrary,$itemNumber);
2235                 $sth->finish;
2236
2237 # second step create a new line of branchtransfer to the right location .
2238         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2239
2240 #third step changing holdingbranch of item
2241         UpdateHoldingbranch($FromLibrary,$itemNumber);
2242 }
2243
2244 =head2 UpdateHoldingbranch
2245
2246 $items = UpdateHoldingbranch($branch,$itmenumber);
2247 Simple methode for updating hodlingbranch in items BDD line
2248
2249 =cut
2250
2251 sub UpdateHoldingbranch {
2252         my ( $branch,$itemnumber ) = @_;
2253     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2254 }
2255
2256 =head2 CalcDateDue
2257
2258 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2259 this function calculates the due date given the loan length ,
2260 checking against the holidays calendar as per the 'useDaysMode' syspref.
2261 C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
2262 C<$branch>  = location whose calendar to use
2263 C<$loanlength>  = loan length prior to adjustment
2264 =cut
2265
2266 sub CalcDateDue { 
2267         my ($startdate,$loanlength,$branch) = @_;
2268         if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
2269                 my $datedue = time + ($loanlength) * 86400;
2270         #FIXME - assumes now even though we take a startdate 
2271                 my @datearr  = localtime($datedue);
2272                 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2273         } else {
2274                 my $calendar = C4::Calendar->new(  branchcode => $branch );
2275                 my $datedue = $calendar->addDate($startdate, $loanlength);
2276                 return $datedue;
2277         }
2278 }
2279
2280 =head2 CheckValidDatedue
2281        This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2282        To be replaced by CalcDateDue() once C4::Calendar use is tested.
2283
2284 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2285 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2286 C<$date_due>   = returndate calculate with no day check
2287 C<$itemnumber>  = itemnumber
2288 C<$branchcode>  = location of issue (affected by 'CircControl' syspref)
2289 C<$loanlength>  = loan length prior to adjustment
2290 =cut
2291
2292 sub CheckValidDatedue {
2293 my ($date_due,$itemnumber,$branchcode)=@_;
2294 my @datedue=split('-',$date_due->output('iso'));
2295 my $years=$datedue[0];
2296 my $month=$datedue[1];
2297 my $day=$datedue[2];
2298 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2299 my $dow;
2300 for (my $i=0;$i<2;$i++){
2301     $dow=Day_of_Week($years,$month,$day);
2302     ($dow=0) if ($dow>6);
2303     my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2304     my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2305     my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2306         if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2307         $i=0;
2308         (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2309         }
2310     }
2311     my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2312 return $newdatedue;
2313 }
2314
2315
2316 =head2 CheckRepeatableHolidays
2317
2318 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2319 this function checks if the date due is a repeatable holiday
2320 C<$date_due>   = returndate calculate with no day check
2321 C<$itemnumber>  = itemnumber
2322 C<$branchcode>  = localisation of issue 
2323
2324 =cut
2325
2326 sub CheckRepeatableHolidays{
2327 my($itemnumber,$week_day,$branchcode)=@_;
2328 my $dbh = C4::Context->dbh;
2329 my $query = qq|SELECT count(*)  
2330         FROM repeatable_holidays 
2331         WHERE branchcode=?
2332         AND weekday=?|;
2333 my $sth = $dbh->prepare($query);
2334 $sth->execute($branchcode,$week_day);
2335 my $result=$sth->fetchrow;
2336 $sth->finish;
2337 return $result;
2338 }
2339
2340
2341 =head2 CheckSpecialHolidays
2342
2343 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2344 this function check if the date is a special holiday
2345 C<$years>   = the years of datedue
2346 C<$month>   = the month of datedue
2347 C<$day>     = the day of datedue
2348 C<$itemnumber>  = itemnumber
2349 C<$branchcode>  = localisation of issue 
2350
2351 =cut
2352
2353 sub CheckSpecialHolidays{
2354 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2355 my $dbh = C4::Context->dbh;
2356 my $query=qq|SELECT count(*) 
2357              FROM `special_holidays`
2358              WHERE year=?
2359              AND month=?
2360              AND day=?
2361              AND branchcode=?
2362             |;
2363 my $sth = $dbh->prepare($query);
2364 $sth->execute($years,$month,$day,$branchcode);
2365 my $countspecial=$sth->fetchrow ;
2366 $sth->finish;
2367 return $countspecial;
2368 }
2369
2370 =head2 CheckRepeatableSpecialHolidays
2371
2372 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2373 this function check if the date is a repeatble special holidays
2374 C<$month>   = the month of datedue
2375 C<$day>     = the day of datedue
2376 C<$itemnumber>  = itemnumber
2377 C<$branchcode>  = localisation of issue 
2378
2379 =cut
2380
2381 sub CheckRepeatableSpecialHolidays{
2382 my ($month,$day,$itemnumber,$branchcode) = @_;
2383 my $dbh = C4::Context->dbh;
2384 my $query=qq|SELECT count(*) 
2385              FROM `repeatable_holidays`
2386              WHERE month=?
2387              AND day=?
2388              AND branchcode=?
2389             |;
2390 my $sth = $dbh->prepare($query);
2391 $sth->execute($month,$day,$branchcode);
2392 my $countspecial=$sth->fetchrow ;
2393 $sth->finish;
2394 return $countspecial;
2395 }
2396
2397
2398
2399 sub CheckValidBarcode{
2400 my ($barcode) = @_;
2401 my $dbh = C4::Context->dbh;
2402 my $query=qq|SELECT count(*) 
2403              FROM items 
2404              WHERE barcode=?
2405             |;
2406 my $sth = $dbh->prepare($query);
2407 $sth->execute($barcode);
2408 my $exist=$sth->fetchrow ;
2409 $sth->finish;
2410 return $exist;
2411 }
2412
2413 1;
2414
2415 __END__
2416
2417 =head1 AUTHOR
2418
2419 Koha Developement team <info@koha.org>
2420
2421 =cut
2422