(bug #2750) Cannot return to another branch if the independantbranch option is set...
[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     my ($blocktype, $count) = C4::Members::IsMemberBlocked($borrower->{'borrowernumber'});
705     if($blocktype == -1){
706         ## remaining overdue documents
707         $issuingimpossible{USERBLOCKEDREMAINING} = $count;
708     }elsif($blocktype == 1){
709         ## blocked because of overdue return
710         $issuingimpossible{USERBLOCKEDOVERDUE} = $count;
711     }
712
713     #
714     # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
715     #
716         my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
717     $needsconfirmation{TOO_MANY} = $toomany if $toomany;
718
719     #
720     # ITEM CHECKING
721     #
722     unless ( $item->{barcode} ) {
723         $issuingimpossible{UNKNOWN_BARCODE} = 1;
724     }
725     if (   $item->{'notforloan'}
726         && $item->{'notforloan'} > 0 )
727     {
728         if(C4::Context->preference("AllowNotForLoanOverride")){
729             $issuingimpossible{NOT_FOR_LOAN_CAN_FORCE} = 1;
730         }else{
731             $issuingimpossible{NOT_FOR_LOAN} = 1;
732         }
733     }
734         elsif ( !$item->{'notforloan'} ){
735                 # we have to check itemtypes.notforloan also
736                 if (C4::Context->preference('item-level_itypes')){
737                         # this should probably be a subroutine
738                         my $sth = $dbh->prepare("SELECT notforloan FROM itemtypes WHERE itemtype = ?");
739                         $sth->execute($item->{'itemtype'});
740                         my $notforloan=$sth->fetchrow_hashref();
741                         $sth->finish();
742                         if ($notforloan->{'notforloan'} == 1){
743                                 $issuingimpossible{NOT_FOR_LOAN} = 1;                           
744                         }
745                 }
746                 elsif ($biblioitem->{'notforloan'} == 1){
747                         $issuingimpossible{NOT_FOR_LOAN} = 1;
748                 }
749         }
750     if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
751     {
752         $issuingimpossible{WTHDRAWN} = 1;
753     }
754     if (   $item->{'restricted'}
755         && $item->{'restricted'} == 1 )
756     {
757         $issuingimpossible{RESTRICTED} = 1;
758     }
759     if ( C4::Context->preference("IndependantBranches") ) {
760         my $userenv = C4::Context->userenv;
761         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
762             $issuingimpossible{NOTSAMEBRANCH} = 1
763               if ( $item->{C4::Context->preference("HomeOrHoldingBranch")} ne $userenv->{branch} );
764         }
765     }
766
767     #
768     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
769     #
770     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
771     {
772
773         # Already issued to current borrower. Ask whether the loan should
774         # be renewed.
775         my ($CanBookBeRenewed,$renewerror) = CanBookBeRenewed(
776             $borrower->{'borrowernumber'},
777             $item->{'itemnumber'}
778         );
779         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
780             $issuingimpossible{NO_MORE_RENEWALS} = 1;
781         }
782         else {
783             $needsconfirmation{RENEW_ISSUE} = 1;
784         }
785     }
786     elsif ($issue->{borrowernumber}) {
787
788         # issued to someone else
789         my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
790
791 #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
792         $needsconfirmation{ISSUED_TO_ANOTHER} =
793 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
794     }
795
796     # See if the item is on reserve.
797     my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
798     if ($restype) {
799                 my $resbor = $res->{'borrowernumber'};
800                 my ( $resborrower ) = C4::Members::GetMemberDetails( $resbor, 0 );
801                 my $branches  = GetBranches();
802                 my $branchname = $branches->{ $res->{'branchcode'} }->{'branchname'};
803         if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
804         {
805             # The item is on reserve and waiting, but has been
806             # reserved by some other patron.
807             $needsconfirmation{RESERVE_WAITING} =
808 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
809         }
810         elsif ( $restype eq "Reserved" ) {
811             # The item is on reserve for someone else.
812             $needsconfirmation{RESERVED} =
813 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
814         }
815     }
816     if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
817         if ( $borrower->{'categorycode'} eq 'W' ) {
818             my %emptyhash;
819             return ( \%emptyhash, \%needsconfirmation );
820         }
821         }
822         return ( \%issuingimpossible, \%needsconfirmation );
823 }
824
825 =head2 AddIssue
826
827 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
828
829 &AddIssue($borrower, $barcode, [$datedue], [$cancelreserve], [$issuedate])
830
831 =over 4
832
833 =item C<$borrower> is a hash with borrower informations (from GetMemberDetails).
834
835 =item C<$barcode> is the barcode of the item being issued.
836
837 =item C<$datedue> is a C4::Dates object for the max date of return, i.e. the date due (optional).
838 Calculated if empty.
839
840 =item C<$cancelreserve> is 1 to override and cancel any pending reserves for the item (optional).
841
842 =item C<$issuedate> is the date to issue the item in iso (YYYY-MM-DD) format (optional).
843 Defaults to today.  Unlike C<$datedue>, NOT a C4::Dates object, unfortunately.
844
845 AddIssue does the following things :
846 - step 01: check that there is a borrowernumber & a barcode provided
847 - check for RENEWAL (book issued & being issued to the same patron)
848     - renewal YES = Calculate Charge & renew
849     - renewal NO  = 
850         * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
851         * RESERVE PLACED ?
852             - fill reserve if reserve to this patron
853             - cancel reserve or not, otherwise
854         * TRANSFERT PENDING ?
855             - complete the transfert
856         * ISSUE THE BOOK
857
858 =back
859
860 =cut
861
862 sub AddIssue {
863     my ( $borrower, $barcode, $datedue, $cancelreserve, $issuedate, $sipmode) = @_;
864     my $dbh = C4::Context->dbh;
865         my $barcodecheck=CheckValidBarcode($barcode);
866
867     # $issuedate defaults to today.
868     if ( ! defined $issuedate ) {
869         $issuedate = strftime( "%Y-%m-%d", localtime );
870         # TODO: for hourly circ, this will need to be a C4::Dates object
871         # and all calls to AddIssue including issuedate will need to pass a Dates object.
872     }
873         if ($borrower and $barcode and $barcodecheck ne '0'){
874                 # find which item we issue
875                 my $item = GetItem('', $barcode) or return undef;       # if we don't get an Item, abort.
876                 my $branch = (C4::Context->preference('CircControl') eq 'PickupLibrary') ? C4::Context->userenv->{'branch'} :
877                      (C4::Context->preference('CircControl') eq 'PatronLibrary') ? $borrower->{'branchcode'}        : 
878                      $item->{'homebranch'};     # fallback to item's homebranch
879                 
880                 # get actual issuing if there is one
881                 my $actualissue = GetItemIssue( $item->{itemnumber});
882                 
883                 # get biblioinformation for this item
884                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
885                 
886                 #
887                 # check if we just renew the issue.
888                 #
889                 if ($actualissue->{borrowernumber} eq $borrower->{'borrowernumber'}) {
890                         $datedue = AddRenewal(
891                                 $borrower->{'borrowernumber'},
892                                 $item->{'itemnumber'},
893                                 $branch,
894                                 $datedue,
895                 $issuedate, # here interpreted as the renewal date
896                         );
897                 }
898                 else {
899         # it's NOT a renewal
900                         if ( $actualissue->{borrowernumber}) {
901                                 # This book is currently on loan, but not to the person
902                                 # who wants to borrow it now. mark it returned before issuing to the new borrower
903                                 AddReturn(
904                                         $item->{'barcode'},
905                                         C4::Context->userenv->{'branch'}
906                                 );
907                         }
908
909                         # See if the item is on reserve.
910                         my ( $restype, $res ) =
911                           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
912                         if ($restype) {
913                                 my $resbor = $res->{'borrowernumber'};
914                                 if ( $resbor eq $borrower->{'borrowernumber'} ) {
915                                         # The item is reserved by the current patron
916                                         ModReserveFill($res);
917                                 }
918                                 elsif ( $restype eq "Waiting" ) {
919                                         # warn "Waiting";
920                                         # The item is on reserve and waiting, but has been
921                                         # reserved by some other patron.
922                                 }
923                                 elsif ( $restype eq "Reserved" ) {
924                                         # warn "Reserved";
925                                         # The item is reserved by someone else.
926                                         if ($cancelreserve) { # cancel reserves on this item
927                                                 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
928                                         }
929                                 }
930                                 if ($cancelreserve) {
931                                         CancelReserve($res->{'biblionumber'}, 0, $res->{'borrowernumber'});
932                                 }
933                                 else {
934                                         # set waiting reserve to first in reserve queue as book isn't waiting now
935                                         ModReserve(1,
936                                                 $res->{'biblionumber'},
937                                                 $res->{'borrowernumber'},
938                                                 $res->{'branchcode'}
939                                         );
940                                 }
941                         }
942
943                         # Starting process for transfer job (checking transfert and validate it if we have one)
944             my ($datesent) = GetTransfers($item->{'itemnumber'});
945             if ($datesent) {
946         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for visibility of this case (maybe for stats ....)
947                 my $sth =
948                     $dbh->prepare(
949                     "UPDATE branchtransfers 
950                         SET datearrived = now(),
951                         tobranch = ?,
952                         comments = 'Forced branchtransfer'
953                     WHERE itemnumber= ? AND datearrived IS NULL"
954                     );
955                 $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
956             }
957
958         # Record in the database the fact that the book was issued.
959         my $sth =
960           $dbh->prepare(
961                 "INSERT INTO issues 
962                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
963                 VALUES (?,?,?,?,?)"
964           );
965         unless ($datedue) {
966             my $itype = ( C4::Context->preference('item-level_itypes') ) ? $biblio->{'itype'} : $biblio->{'itemtype'};
967             my $loanlength = GetLoanLength( $borrower->{'categorycode'}, $itype, $branch );
968             $datedue = CalcDateDue( C4::Dates->new( $issuedate, 'iso' ), $loanlength, $branch );
969
970             # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
971             if ( C4::Context->preference('ReturnBeforeExpiry') && $datedue->output('iso') gt $borrower->{dateexpiry} ) {
972                 $datedue = C4::Dates->new( $borrower->{dateexpiry}, 'iso' );
973             }
974         }
975         $sth->execute(
976             $borrower->{'borrowernumber'},      # borrowernumber
977             $item->{'itemnumber'},              # itemnumber
978             $issuedate,                         # issuedate
979             $datedue->output('iso'),            # date_due
980             C4::Context->userenv->{'branch'}    # branchcode
981         );
982         $sth->finish;
983         $item->{'issues'}++;
984         ModItem({ issues           => $item->{'issues'},
985                   holdingbranch    => C4::Context->userenv->{'branch'},
986                   itemlost         => 0,
987                   datelastborrowed => C4::Dates->new()->output('iso'),
988                   onloan           => $datedue->output('iso'),
989                 }, $item->{'biblionumber'}, $item->{'itemnumber'});
990         ModDateLastSeen( $item->{'itemnumber'} );
991         
992         # If it costs to borrow this book, charge it to the patron's account.
993         my ( $charge, $itemtype ) = GetIssuingCharges(
994             $item->{'itemnumber'},
995             $borrower->{'borrowernumber'}
996         );
997         if ( $charge > 0 ) {
998             AddIssuingCharge(
999                 $item->{'itemnumber'},
1000                 $borrower->{'borrowernumber'}, $charge
1001             );
1002             $item->{'charge'} = $charge;
1003         }
1004
1005         # Record the fact that this book was issued.
1006         &UpdateStats(
1007             C4::Context->userenv->{'branch'},
1008             'issue', $charge,
1009             ($sipmode ? "SIP-$sipmode" : ''), $item->{'itemnumber'},
1010             $item->{'itype'}, $borrower->{'borrowernumber'}
1011         );
1012     }
1013     
1014     logaction("CIRCULATION", "ISSUE", $borrower->{'borrowernumber'}, $biblio->{'biblionumber'}) 
1015         if C4::Context->preference("IssueLog");
1016   }
1017   return ($datedue);    # not necessarily the same as when it came in!
1018 }
1019
1020 =head2 GetLoanLength
1021
1022 Get loan length for an itemtype, a borrower type and a branch
1023
1024 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1025
1026 =cut
1027
1028 sub GetLoanLength {
1029     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1030     my $dbh = C4::Context->dbh;
1031     my $sth =
1032       $dbh->prepare(
1033 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1034       );
1035 # warn "in get loan lenght $borrowertype $itemtype $branchcode ";
1036 # try to find issuelength & return the 1st available.
1037 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1038     $sth->execute( $borrowertype, $itemtype, $branchcode );
1039     my $loanlength = $sth->fetchrow_hashref;
1040     return $loanlength->{issuelength}
1041       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1042
1043     $sth->execute( $borrowertype, "*", $branchcode );
1044     $loanlength = $sth->fetchrow_hashref;
1045     return $loanlength->{issuelength}
1046       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1047
1048     $sth->execute( "*", $itemtype, $branchcode );
1049     $loanlength = $sth->fetchrow_hashref;
1050     return $loanlength->{issuelength}
1051       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1052
1053     $sth->execute( "*", "*", $branchcode );
1054     $loanlength = $sth->fetchrow_hashref;
1055     return $loanlength->{issuelength}
1056       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1057
1058     $sth->execute( $borrowertype, $itemtype, "*" );
1059     $loanlength = $sth->fetchrow_hashref;
1060     return $loanlength->{issuelength}
1061       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1062
1063     $sth->execute( $borrowertype, "*", "*" );
1064     $loanlength = $sth->fetchrow_hashref;
1065     return $loanlength->{issuelength}
1066       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1067
1068     $sth->execute( "*", $itemtype, "*" );
1069     $loanlength = $sth->fetchrow_hashref;
1070     return $loanlength->{issuelength}
1071       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1072
1073     $sth->execute( "*", "*", "*" );
1074     $loanlength = $sth->fetchrow_hashref;
1075     return $loanlength->{issuelength}
1076       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1077
1078     # if no rule is set => 21 days (hardcoded)
1079     return 21;
1080 }
1081
1082 =head2 GetIssuingRule
1083
1084 FIXME - This is a copy-paste of GetLoanLength 
1085 as a stop-gap.  Do not wish to change API for GetLoanLength 
1086 this close to release, however, Overdues::GetIssuingRules is broken.
1087
1088 Get the issuing rule for an itemtype, a borrower type and a branch
1089 Returns a hashref from the issuingrules table.
1090
1091 my $irule = &GetIssuingRule($borrowertype,$itemtype,branchcode)
1092
1093 =cut
1094
1095 sub GetIssuingRule {
1096     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1097     my $dbh = C4::Context->dbh;
1098     my $sth =  $dbh->prepare( "select * from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"  );
1099     my $irule;
1100
1101         $sth->execute( $borrowertype, $itemtype, $branchcode );
1102     $irule = $sth->fetchrow_hashref;
1103     return $irule if defined($irule) ;
1104
1105     $sth->execute( $borrowertype, "*", $branchcode );
1106     $irule = $sth->fetchrow_hashref;
1107     return $irule if defined($irule) ;
1108
1109     $sth->execute( "*", $itemtype, $branchcode );
1110     $irule = $sth->fetchrow_hashref;
1111     return $irule if defined($irule) ;
1112
1113     $sth->execute( "*", "*", $branchcode );
1114     $irule = $sth->fetchrow_hashref;
1115     return $irule if defined($irule) ;
1116
1117     $sth->execute( $borrowertype, $itemtype, "*" );
1118     $irule = $sth->fetchrow_hashref;
1119     return $irule if defined($irule) ;
1120
1121     $sth->execute( $borrowertype, "*", "*" );
1122     $irule = $sth->fetchrow_hashref;
1123     return $irule if defined($irule) ;
1124
1125     $sth->execute( "*", $itemtype, "*" );
1126     $irule = $sth->fetchrow_hashref;
1127     return $irule if defined($irule) ;
1128
1129     $sth->execute( "*", "*", "*" );
1130     $irule = $sth->fetchrow_hashref;
1131     return $irule if defined($irule) ;
1132
1133     # if no rule matches,
1134     return undef;
1135 }
1136
1137 =head2 GetBranchBorrowerCircRule
1138
1139 =over 4
1140
1141 my $branch_cat_rule = GetBranchBorrowerCircRule($branchcode, $categorycode);
1142
1143 =back
1144
1145 Retrieves circulation rule attributes that apply to the given
1146 branch and patron category, regardless of item type.  
1147 The return value is a hashref containing the following key:
1148
1149 maxissueqty - maximum number of loans that a
1150 patron of the given category can have at the given
1151 branch.  If the value is undef, no limit.
1152
1153 This will first check for a specific branch and
1154 category match from branch_borrower_circ_rules. 
1155
1156 If no rule is found, it will then check default_branch_circ_rules
1157 (same branch, default category).  If no rule is found,
1158 it will then check default_borrower_circ_rules (default 
1159 branch, same category), then failing that, default_circ_rules
1160 (default branch, default category).
1161
1162 If no rule has been found in the database, it will default to
1163 the buillt in rule:
1164
1165 maxissueqty - undef
1166
1167 C<$branchcode> and C<$categorycode> should contain the
1168 literal branch code and patron category code, respectively - no
1169 wildcards.
1170
1171 =cut
1172
1173 sub GetBranchBorrowerCircRule {
1174     my $branchcode = shift;
1175     my $categorycode = shift;
1176
1177     my $branch_cat_query = "SELECT maxissueqty
1178                             FROM branch_borrower_circ_rules
1179                             WHERE branchcode = ?
1180                             AND   categorycode = ?";
1181     my $dbh = C4::Context->dbh();
1182     my $sth = $dbh->prepare($branch_cat_query);
1183     $sth->execute($branchcode, $categorycode);
1184     my $result;
1185     if ($result = $sth->fetchrow_hashref()) {
1186         return $result;
1187     }
1188
1189     # try same branch, default borrower category
1190     my $branch_query = "SELECT maxissueqty
1191                         FROM default_branch_circ_rules
1192                         WHERE branchcode = ?";
1193     $sth = $dbh->prepare($branch_query);
1194     $sth->execute($branchcode);
1195     if ($result = $sth->fetchrow_hashref()) {
1196         return $result;
1197     }
1198
1199     # try default branch, same borrower category
1200     my $category_query = "SELECT maxissueqty
1201                           FROM default_borrower_circ_rules
1202                           WHERE categorycode = ?";
1203     $sth = $dbh->prepare($category_query);
1204     $sth->execute($categorycode);
1205     if ($result = $sth->fetchrow_hashref()) {
1206         return $result;
1207     }
1208   
1209     # try default branch, default borrower category
1210     my $default_query = "SELECT maxissueqty
1211                           FROM default_circ_rules";
1212     $sth = $dbh->prepare($default_query);
1213     $sth->execute();
1214     if ($result = $sth->fetchrow_hashref()) {
1215         return $result;
1216     }
1217     
1218     # built-in default circulation rule
1219     return {
1220         maxissueqty => undef,
1221     };
1222 }
1223
1224 =head2 AddReturn
1225
1226 ($doreturn, $messages, $iteminformation, $borrower) =
1227     &AddReturn($barcode, $branch, $exemptfine, $dropbox);
1228
1229 Returns a book.
1230
1231 =over 4
1232
1233 =item C<$barcode> is the bar code of the book being returned.
1234
1235 =item C<$branch> is the code of the branch where the book is being returned.
1236
1237 =item C<$exemptfine> indicates that overdue charges for the item will be
1238 removed.
1239
1240 =item C<$dropbox> indicates that the check-in date is assumed to be
1241 yesterday, or the last non-holiday as defined in C4::Calendar .  If
1242 overdue charges are applied and C<$dropbox> is true, the last charge
1243 will be removed.  This assumes that the fines accrual script has run
1244 for _today_.
1245
1246 =back
1247
1248 C<&AddReturn> returns a list of four items:
1249
1250 C<$doreturn> is true iff the return succeeded.
1251
1252 C<$messages> is a reference-to-hash giving the reason for failure:
1253
1254 =over 4
1255
1256 =item C<BadBarcode>
1257
1258 No item with this barcode exists. The value is C<$barcode>.
1259
1260 =item C<NotIssued>
1261
1262 The book is not currently on loan. The value is C<$barcode>.
1263
1264 =item C<IsPermanent>
1265
1266 The book's home branch is a permanent collection. If you have borrowed
1267 this book, you are not allowed to return it. The value is the code for
1268 the book's home branch.
1269
1270 =item C<wthdrawn>
1271
1272 This book has been withdrawn/cancelled. The value should be ignored.
1273
1274 =item C<ResFound>
1275
1276 The item was reserved. The value is a reference-to-hash whose keys are
1277 fields from the reserves table of the Koha database, and
1278 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1279 either C<Waiting>, C<Reserved>, or 0.
1280
1281 =back
1282
1283 C<$borrower> is a reference-to-hash, giving information about the
1284 patron who last borrowed the book.
1285
1286 =cut
1287
1288 sub AddReturn {
1289     my ( $barcode, $branch, $exemptfine, $dropbox ) = @_;
1290     my $dbh      = C4::Context->dbh;
1291     my $messages;
1292     my $doreturn = 1;
1293     my $borrower;
1294     my $validTransfert = 0;
1295     my $reserveDone = 0;
1296     
1297     # get information on item
1298     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1299     my $biblio = GetBiblioItemData($iteminformation->{'biblioitemnumber'});
1300 #     use Data::Dumper;warn Data::Dumper::Dumper($iteminformation);  
1301     unless ($iteminformation->{'itemnumber'} ) {
1302         $messages->{'BadBarcode'} = $barcode;
1303         $doreturn = 0;
1304     } else {
1305         # find the borrower
1306         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1307             $messages->{'NotIssued'} = $barcode;
1308             # even though item is not on loan, it may still
1309             # be transferred; therefore, get current branch information
1310             my $curr_iteminfo = GetItem($iteminformation->{'itemnumber'});
1311             $iteminformation->{'homebranch'} = $curr_iteminfo->{'homebranch'};
1312             $iteminformation->{'holdingbranch'} = $curr_iteminfo->{'holdingbranch'};
1313             $iteminformation->{'itemlost'} = $curr_iteminfo->{'itemlost'};
1314             $doreturn = 0;
1315         }
1316     
1317         # check if the book is in a permanent collection....
1318         my $hbr      = $iteminformation->{C4::Context->preference("HomeOrHoldingBranch")};
1319         my $branches = GetBranches();
1320                 # FIXME -- This 'PE' attribute is largely undocumented.  afaict, there's no user interface that reflects this functionality.
1321         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1322             $messages->{'IsPermanent'} = $hbr;
1323         }
1324                 
1325                     # if independent branches are on and returning to different branch, refuse the return
1326         if ($hbr ne C4::Context->userenv->{'branch'} && C4::Context->preference("IndependantBranches")){
1327                           $messages->{'Wrongbranch'} = 1;
1328                           $doreturn=0;
1329                     }
1330                         
1331         # check that the book has been cancelled
1332         if ( $iteminformation->{'wthdrawn'} ) {
1333             $messages->{'wthdrawn'} = 1;
1334             $doreturn = 0;
1335         }
1336     
1337     #     new op dev : if the book returned in an other branch update the holding branch
1338     
1339     # update issues, thereby returning book (should push this out into another subroutine
1340         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1341     
1342     # case of a return of document (deal with issues and holdingbranch)
1343     
1344         if ($doreturn) {
1345                         my $circControlBranch;
1346                         if($dropbox) {
1347                                 # don't allow dropbox mode to create an invalid entry in issues (issuedate > returndate) FIXME: actually checks eq, not gt
1348                                 undef($dropbox) if ( $iteminformation->{'issuedate'} eq C4::Dates->today('iso') );
1349                                 if (C4::Context->preference('CircControl') eq 'ItemHomeBranch' ) {
1350                                         $circControlBranch = $iteminformation->{homebranch};
1351                                 } elsif ( C4::Context->preference('CircControl') eq 'PatronLibrary') {
1352                                         $circControlBranch = $borrower->{branchcode};
1353                                 } else { # CircControl must be PickupLibrary.
1354                                         $circControlBranch = $iteminformation->{holdingbranch};
1355                                         # FIXME - is this right ? are we sure that the holdingbranch is still the pickup branch?
1356                                 }
1357                         }
1358             MarkIssueReturned($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'},$circControlBranch);
1359             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?  
1360             # continue to deal with returns cases, but not only if we have an issue
1361
1362             # the holdingbranch is updated if the document is returned in an other location .
1363             if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1364                            UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});
1365                            #           reload iteminformation holdingbranch with the userenv value
1366                            $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1367             }
1368             ModDateLastSeen( $iteminformation->{'itemnumber'} );
1369             ModItem({ onloan => undef }, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'});
1370
1371             if ($iteminformation->{borrowernumber}){
1372               ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1373             }
1374         }       
1375         # fix up the accounts.....
1376         if ( $iteminformation->{'itemlost'} ) {
1377             $messages->{'WasLost'} = 1;
1378         }
1379     
1380     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1381     #     check if we have a transfer for this document
1382         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1383     
1384     #     if we have a transfer to do, we update the line of transfers with the datearrived
1385         if ($datesent) {
1386             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1387                     my $sth =
1388                     $dbh->prepare(
1389                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1390                     );
1391                     $sth->execute( $iteminformation->{'itemnumber'} );
1392                     $sth->finish;
1393     #         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'
1394             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1395             }
1396         else {
1397             $messages->{'WrongTransfer'} = $tobranch;
1398             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1399         }
1400         $validTransfert = 1;
1401         }
1402     
1403     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1404         # fix up the accounts.....
1405         if ($iteminformation->{'itemlost'}) {
1406                 FixAccountForLostAndReturned($iteminformation, $borrower);
1407                 $messages->{'WasLost'} = 1;
1408         }
1409         # fix up the overdues in accounts...
1410         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1411             $iteminformation->{'itemnumber'}, $exemptfine, $dropbox );
1412     
1413     # find reserves.....
1414     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1415         my ( $resfound, $resrec ) =
1416         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1417         if ($resfound) {
1418             $resrec->{'ResFound'}   = $resfound;
1419             $messages->{'ResFound'} = $resrec;
1420             $reserveDone = 1;
1421         }
1422     
1423         # update stats?
1424         # Record the fact that this book was returned.
1425         UpdateStats(
1426             $branch, 'return', '0', '',
1427             $iteminformation->{'itemnumber'},
1428             $biblio->{'itemtype'},
1429             $borrower->{'borrowernumber'}
1430         );
1431         
1432         logaction("CIRCULATION", "RETURN", $iteminformation->{borrowernumber}, $iteminformation->{'biblionumber'}) 
1433             if C4::Context->preference("ReturnLog");
1434         
1435         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1436         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1437         
1438         if ($doreturn and ($branch ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1439                         if (C4::Context->preference("AutomaticItemReturn") == 1) {
1440                                 ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1441                                 $messages->{'WasTransfered'} = 1;
1442                         }
1443                         else {
1444                                 $messages->{'NeedsTransfer'} = 1;
1445                         }
1446         }
1447     }
1448     return ( $doreturn, $messages, $iteminformation, $borrower );
1449 }
1450
1451 =head2 MarkIssueReturned
1452
1453 =over 4
1454
1455 MarkIssueReturned($borrowernumber, $itemnumber, $dropbox_branch, $returndate);
1456
1457 =back
1458
1459 Unconditionally marks an issue as being returned by
1460 moving the C<issues> row to C<old_issues> and
1461 setting C<returndate> to the current date, or
1462 the last non-holiday date of the branccode specified in
1463 C<dropbox_branch> .  Assumes you've already checked that 
1464 it's safe to do this, i.e. last non-holiday > issuedate.
1465
1466 if C<$returndate> is specified (in iso format), it is used as the date
1467 of the return. It is ignored when a dropbox_branch is passed in.
1468
1469 Ideally, this function would be internal to C<C4::Circulation>,
1470 not exported, but it is currently needed by one 
1471 routine in C<C4::Accounts>.
1472
1473 =cut
1474
1475 sub MarkIssueReturned {
1476     my ( $borrowernumber, $itemnumber, $dropbox_branch, $returndate ) = @_;
1477     my $dbh   = C4::Context->dbh;
1478     my $query = "UPDATE issues SET returndate=";
1479     my @bind;
1480     if ($dropbox_branch) {
1481         my $calendar = C4::Calendar->new( branchcode => $dropbox_branch );
1482         my $dropboxdate = $calendar->addDate( C4::Dates->new(), -1 );
1483         $query .= " ? ";
1484         push @bind, $dropboxdate->output('iso');
1485     } elsif ($returndate) {
1486         $query .= " ? ";
1487         push @bind, $returndate;
1488     } else {
1489         $query .= " now() ";
1490     }
1491     $query .= " WHERE  borrowernumber = ?  AND itemnumber = ?";
1492     push @bind, $borrowernumber, $itemnumber;
1493     # FIXME transaction
1494     my $sth_upd  = $dbh->prepare($query);
1495     $sth_upd->execute(@bind);
1496     my $sth_copy = $dbh->prepare("INSERT INTO old_issues SELECT * FROM issues 
1497                                   WHERE borrowernumber = ?
1498                                   AND itemnumber = ?");
1499     $sth_copy->execute($borrowernumber, $itemnumber);
1500     my $sth_del  = $dbh->prepare("DELETE FROM issues
1501                                   WHERE borrowernumber = ?
1502                                   AND itemnumber = ?");
1503     $sth_del->execute($borrowernumber, $itemnumber);
1504 }
1505
1506 =head2 FixOverduesOnReturn
1507
1508     &FixOverduesOnReturn($brn,$itm, $exemptfine, $dropboxmode);
1509
1510 C<$brn> borrowernumber
1511
1512 C<$itm> itemnumber
1513
1514 C<$exemptfine> BOOL -- remove overdue charge associated with this issue. 
1515 C<$dropboxmode> BOOL -- remove lastincrement on overdue charge associated with this issue.
1516
1517 internal function, called only by AddReturn
1518
1519 =cut
1520
1521 sub FixOverduesOnReturn {
1522     my ( $borrowernumber, $item, $exemptfine, $dropbox ) = @_;
1523     my $dbh = C4::Context->dbh;
1524
1525     # check for overdue fine
1526     my $sth =
1527       $dbh->prepare(
1528 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1529       );
1530     $sth->execute( $borrowernumber, $item );
1531
1532     # alter fine to show that the book has been returned
1533    my $data; 
1534         if ($data = $sth->fetchrow_hashref) {
1535         my $uquery;
1536                 my @bind = ($borrowernumber,$item ,$data->{'accountno'});
1537                 if ($exemptfine) {
1538                         $uquery = "update accountlines set accounttype='FFOR', amountoutstanding=0";
1539                         if (C4::Context->preference("FinesLog")) {
1540                         &logaction("FINES", 'MODIFY',$borrowernumber,"Overdue forgiven: item $item");
1541                         }
1542                 } elsif ($dropbox && $data->{lastincrement}) {
1543                         my $outstanding = $data->{amountoutstanding} - $data->{lastincrement} ;
1544                         my $amt = $data->{amount} - $data->{lastincrement} ;
1545                         if (C4::Context->preference("FinesLog")) {
1546                         &logaction("FINES", 'MODIFY',$borrowernumber,"Dropbox adjustment $amt, item $item");
1547                         }
1548                          $uquery = "update accountlines set accounttype='F' ";
1549                          if($outstanding  >= 0 && $amt >=0) {
1550                                 $uquery .= ", amount = ? , amountoutstanding=? ";
1551                                 unshift @bind, ($amt, $outstanding) ;
1552                         }
1553                 } else {
1554                         $uquery = "update accountlines set accounttype='F' ";
1555                 }
1556                 $uquery .= " where (borrowernumber = ?) and (itemnumber = ?) and (accountno = ?)";
1557         my $usth = $dbh->prepare($uquery);
1558         $usth->execute(@bind);
1559         $usth->finish();
1560     }
1561
1562     $sth->finish();
1563     return;
1564 }
1565
1566 =head2 FixAccountForLostAndReturned
1567
1568         &FixAccountForLostAndReturned($iteminfo,$borrower);
1569
1570 Calculates the charge for a book lost and returned (Not exported & used only once)
1571
1572 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1573
1574 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1575
1576 Internal function, called by AddReturn
1577
1578 =cut
1579
1580 sub FixAccountForLostAndReturned {
1581         my ($iteminfo, $borrower) = @_;
1582         my $dbh = C4::Context->dbh;
1583         my $itm = $iteminfo->{'itemnumber'};
1584         # check for charge made for lost book
1585         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1586         $sth->execute($itm);
1587         if (my $data = $sth->fetchrow_hashref) {
1588         # writeoff this amount
1589                 my $offset;
1590                 my $amount = $data->{'amount'};
1591                 my $acctno = $data->{'accountno'};
1592                 my $amountleft;
1593                 if ($data->{'amountoutstanding'} == $amount) {
1594                 $offset = $data->{'amount'};
1595                 $amountleft = 0;
1596                 } else {
1597                 $offset = $amount - $data->{'amountoutstanding'};
1598                 $amountleft = $data->{'amountoutstanding'} - $amount;
1599                 }
1600                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1601                         WHERE (borrowernumber = ?)
1602                         AND (itemnumber = ?) AND (accountno = ?) ");
1603                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1604                 $usth->finish;
1605         #check if any credit is left if so writeoff other accounts
1606                 my $nextaccntno = getnextacctno($data->{'borrowernumber'});
1607                 if ($amountleft < 0){
1608                 $amountleft*=-1;
1609                 }
1610                 if ($amountleft > 0){
1611                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1612                                                         AND (amountoutstanding >0) ORDER BY date");
1613                 $msth->execute($data->{'borrowernumber'});
1614         # offset transactions
1615                 my $newamtos;
1616                 my $accdata;
1617                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1618                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1619                         $newamtos = 0;
1620                         $amountleft -= $accdata->{'amountoutstanding'};
1621                         }  else {
1622                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1623                         $amountleft = 0;
1624                         }
1625                         my $thisacct = $accdata->{'accountno'};
1626                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1627                                         WHERE (borrowernumber = ?)
1628                                         AND (accountno=?)");
1629                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1630                         $usth->finish;
1631                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1632                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1633                                 VALUES
1634                                 (?,?,?,?)");
1635                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1636                         $usth->finish;
1637                 }
1638                 $msth->finish;
1639                 }
1640                 if ($amountleft > 0){
1641                         $amountleft*=-1;
1642                 }
1643                 my $desc="Item Returned ".$iteminfo->{'barcode'};
1644                 $usth = $dbh->prepare("INSERT INTO accountlines
1645                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1646                         VALUES (?,?,now(),?,?,'CR',?)");
1647                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1648                 $usth->finish;
1649                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1650                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1651                         VALUES (?,?,?,?)");
1652                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1653                 $usth->finish;
1654         ModItem({ paidfor => '' }, undef, $itm);
1655         }
1656         $sth->finish;
1657         return;
1658 }
1659
1660 =head2 GetItemIssue
1661
1662 $issues = &GetItemIssue($itemnumber);
1663
1664 Returns patrons currently having a book. nothing if item is not issued atm
1665
1666 C<$itemnumber> is the itemnumber
1667
1668 Returns an array of hashes
1669
1670 FIXME: Though the above says that this function returns nothing if the
1671 item is not issued, this actually returns a hasref that looks like
1672 this:
1673     {
1674       itemnumber => 1,
1675       overdue    => 1
1676     }
1677
1678
1679 =cut
1680
1681 sub GetItemIssue {
1682     my ( $itemnumber) = @_;
1683     return unless $itemnumber;
1684     my $dbh = C4::Context->dbh;
1685     my @GetItemIssues;
1686     
1687     # get today date
1688     my $today = POSIX::strftime("%Y%m%d", localtime);
1689
1690     my $sth = $dbh->prepare(
1691         "SELECT * FROM issues 
1692         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1693     WHERE
1694     issues.itemnumber=?");
1695     $sth->execute($itemnumber);
1696     my $data = $sth->fetchrow_hashref;
1697     my $datedue = $data->{'date_due'};
1698     $datedue =~ s/-//g;
1699     if ( $datedue < $today ) {
1700         $data->{'overdue'} = 1;
1701     }
1702     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1703     $sth->finish;
1704     return ($data);
1705 }
1706
1707 =head2 GetItemIssues
1708
1709 $issues = &GetItemIssues($itemnumber, $history);
1710
1711 Returns patrons that have issued a book
1712
1713 C<$itemnumber> is the itemnumber
1714 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1715
1716 Returns an array of hashes
1717
1718 =cut
1719
1720 sub GetItemIssues {
1721     my ( $itemnumber,$history ) = @_;
1722     my $dbh = C4::Context->dbh;
1723     my @GetItemIssues;
1724     
1725     # get today date
1726     my $today = POSIX::strftime("%Y%m%d", localtime);
1727
1728     my $sql = "SELECT * FROM issues 
1729               JOIN borrowers USING (borrowernumber)
1730               JOIN items USING (itemnumber)
1731               WHERE issues.itemnumber = ? ";
1732     if ($history) {
1733         $sql .= "UNION ALL
1734                  SELECT * FROM old_issues 
1735                  LEFT JOIN borrowers USING (borrowernumber)
1736                  JOIN items USING (itemnumber)
1737                  WHERE old_issues.itemnumber = ? ";
1738     }
1739     $sql .= "ORDER BY date_due DESC";
1740     my $sth = $dbh->prepare($sql);
1741     if ($history) {
1742         $sth->execute($itemnumber, $itemnumber);
1743     } else {
1744         $sth->execute($itemnumber);
1745     }
1746     while ( my $data = $sth->fetchrow_hashref ) {
1747         my $datedue = $data->{'date_due'};
1748         $datedue =~ s/-//g;
1749         if ( $datedue < $today ) {
1750             $data->{'overdue'} = 1;
1751         }
1752         my $itemnumber = $data->{'itemnumber'};
1753         push @GetItemIssues, $data;
1754     }
1755     $sth->finish;
1756     return ( \@GetItemIssues );
1757 }
1758
1759 =head2 GetBiblioIssues
1760
1761 $issues = GetBiblioIssues($biblionumber);
1762
1763 this function get all issues from a biblionumber.
1764
1765 Return:
1766 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1767 tables issues and the firstname,surname & cardnumber from borrowers.
1768
1769 =cut
1770
1771 sub GetBiblioIssues {
1772     my $biblionumber = shift;
1773     return undef unless $biblionumber;
1774     my $dbh   = C4::Context->dbh;
1775     my $query = "
1776         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1777         FROM issues
1778             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1779             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1780             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1781             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1782         WHERE biblio.biblionumber = ?
1783         UNION ALL
1784         SELECT old_issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1785         FROM old_issues
1786             LEFT JOIN borrowers ON borrowers.borrowernumber = old_issues.borrowernumber
1787             LEFT JOIN items ON old_issues.itemnumber = items.itemnumber
1788             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1789             LEFT JOIN biblio ON biblio.biblionumber = items.biblionumber
1790         WHERE biblio.biblionumber = ?
1791         ORDER BY timestamp
1792     ";
1793     my $sth = $dbh->prepare($query);
1794     $sth->execute($biblionumber, $biblionumber);
1795
1796     my @issues;
1797     while ( my $data = $sth->fetchrow_hashref ) {
1798         push @issues, $data;
1799     }
1800     return \@issues;
1801 }
1802
1803 =head2 GetUpcomingDueIssues
1804
1805 =over 4
1806  
1807 my $upcoming_dues = GetUpcomingDueIssues( { days_in_advance => 4 } );
1808
1809 =back
1810
1811 =cut
1812
1813 sub GetUpcomingDueIssues {
1814     my $params = shift;
1815
1816     $params->{'days_in_advance'} = 7 unless exists $params->{'days_in_advance'};
1817     my $dbh = C4::Context->dbh;
1818
1819     my $statement = <<END_SQL;
1820 SELECT issues.*, items.itype as itemtype, items.homebranch, TO_DAYS( date_due )-TO_DAYS( NOW() ) as days_until_due
1821 FROM issues 
1822 LEFT JOIN items USING (itemnumber)
1823 WhERE returndate is NULL
1824 AND ( TO_DAYS( NOW() )-TO_DAYS( date_due ) ) < ?
1825 END_SQL
1826
1827     my @bind_parameters = ( $params->{'days_in_advance'} );
1828     
1829     my $sth = $dbh->prepare( $statement );
1830     $sth->execute( @bind_parameters );
1831     my $upcoming_dues = $sth->fetchall_arrayref({});
1832     $sth->finish;
1833
1834     return $upcoming_dues;
1835 }
1836
1837 =head2 CanBookBeRenewed
1838
1839 ($ok,$error) = &CanBookBeRenewed($borrowernumber, $itemnumber[, $override_limit]);
1840
1841 Find out whether a borrowed item may be renewed.
1842
1843 C<$dbh> is a DBI handle to the Koha database.
1844
1845 C<$borrowernumber> is the borrower number of the patron who currently
1846 has the item on loan.
1847
1848 C<$itemnumber> is the number of the item to renew.
1849
1850 C<$override_limit>, if supplied with a true value, causes
1851 the limit on the number of times that the loan can be renewed
1852 (as controlled by the item type) to be ignored.
1853
1854 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1855 item must currently be on loan to the specified borrower; renewals
1856 must be allowed for the item's type; and the borrower must not have
1857 already renewed the loan. $error will contain the reason the renewal can not proceed
1858
1859 =cut
1860
1861 sub CanBookBeRenewed {
1862
1863     # check renewal status
1864     my ( $borrowernumber, $itemnumber, $override_limit ) = @_;
1865     my $dbh       = C4::Context->dbh;
1866     my $renews    = 1;
1867     my $renewokay = 0;
1868         my $error;
1869
1870     # Look in the issues table for this item, lent to this borrower,
1871     # and not yet returned.
1872
1873     # FIXME - I think this function could be redone to use only one SQL call.
1874     my $sth1 = $dbh->prepare(
1875         "SELECT * FROM issues
1876             WHERE borrowernumber = ?
1877             AND itemnumber = ?"
1878     );
1879     $sth1->execute( $borrowernumber, $itemnumber );
1880     if ( my $data1 = $sth1->fetchrow_hashref ) {
1881
1882         # Found a matching item
1883
1884         # See if this item may be renewed. This query is convoluted
1885         # because it's a bit messy: given the item number, we need to find
1886         # the biblioitem, which gives us the itemtype, which tells us
1887         # whether it may be renewed.
1888         my $query = "SELECT renewalsallowed FROM items ";
1889         $query .= (C4::Context->preference('item-level_itypes'))
1890                     ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1891                     : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1892                        LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1893         $query .= "WHERE items.itemnumber = ?";
1894         my $sth2 = $dbh->prepare($query);
1895         $sth2->execute($itemnumber);
1896         if ( my $data2 = $sth2->fetchrow_hashref ) {
1897             $renews = $data2->{'renewalsallowed'};
1898         }
1899         if ( ( $renews && $renews > $data1->{'renewals'} ) || $override_limit ) {
1900             $renewokay = 1;
1901         }
1902         else {
1903                         $error="too_many";
1904                 }
1905         $sth2->finish;
1906         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1907         if ($resfound) {
1908             $renewokay = 0;
1909                         $error="on_reserve"
1910         }
1911
1912     }
1913     $sth1->finish;
1914     return ($renewokay,$error);
1915 }
1916
1917 =head2 AddRenewal
1918
1919 &AddRenewal($borrowernumber, $itemnumber, $branch, [$datedue], [$lastreneweddate]);
1920
1921 Renews a loan.
1922
1923 C<$borrowernumber> is the borrower number of the patron who currently
1924 has the item.
1925
1926 C<$itemnumber> is the number of the item to renew.
1927
1928 C<$branch> is the library branch.  Defaults to the homebranch of the ITEM.
1929
1930 C<$datedue> can be a C4::Dates object used to set the due date.
1931
1932 C<$lastreneweddate> is an optional ISO-formatted date used to set issues.lastreneweddate.  If
1933 this parameter is not supplied, lastreneweddate is set to the current date.
1934
1935 If C<$datedue> is the empty string, C<&AddRenewal> will calculate the due date automatically
1936 from the book's item type.
1937
1938 =cut
1939
1940 sub AddRenewal {
1941         my $borrowernumber = shift or return undef;
1942         my     $itemnumber = shift or return undef;
1943     my $item   = GetItem($itemnumber) or return undef;
1944     my $biblio = GetBiblioFromItemNumber($itemnumber) or return undef;
1945     my $branch  = (@_) ? shift : $item->{homebranch};   # opac-renew doesn't send branch
1946     my $datedue = shift;
1947     my $lastreneweddate = shift;
1948
1949     # If the due date wasn't specified, calculate it by adding the
1950     # book's loan length to today's date.
1951     unless ($datedue && $datedue->output('iso')) {
1952
1953         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1954         my $loanlength = GetLoanLength(
1955             $borrower->{'categorycode'},
1956              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1957                         $item->{homebranch}                     # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1958         );
1959                 #FIXME -- use circControl?
1960                 $datedue =  CalcDateDue(C4::Dates->new(),$loanlength,$branch);  # this branch is the transactional branch.
1961                                                                 # The question of whether to use item's homebranch calendar is open.
1962     }
1963
1964     # $lastreneweddate defaults to today.
1965     unless (defined $lastreneweddate) {
1966         $lastreneweddate = strftime( "%Y-%m-%d", localtime );
1967     }
1968
1969     my $dbh = C4::Context->dbh;
1970     # Find the issues record for this book
1971     my $sth =
1972       $dbh->prepare("SELECT * FROM issues
1973                         WHERE borrowernumber=? 
1974                         AND itemnumber=?"
1975       );
1976     $sth->execute( $borrowernumber, $itemnumber );
1977     my $issuedata = $sth->fetchrow_hashref;
1978     $sth->finish;
1979
1980     # If the due date wasn't specified, calculate it by adding the
1981     # book's loan length to due's date.
1982     unless (@_ and $datedue = shift and $datedue->output('iso')) {
1983
1984         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 ) or return undef;
1985         my $loanlength = GetLoanLength(
1986             $borrower->{'categorycode'},
1987              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1988                         $item->{homebranch}                     # item's homebranch determines loanlength OR do we want the branch specified by the AddRenewal argument?
1989         );
1990
1991         $datedue = (C4::Context->preference('RenewalPeriodBase') eq 'date_due') ?
1992                                         C4::Dates->new($issuedata->{date_due}, 'iso') :
1993                                         C4::Dates->new();
1994         #FIXME -- use circControl?
1995         $datedue =  CalcDateDue($datedue,$loanlength,$branch);  # this branch is the transactional branch.
1996         # The question of whether to use item's homebranch calendar is open.
1997     }
1998
1999     # Update the issues record to have the new due date, and a new count
2000     # of how many times it has been renewed.
2001     my $renews = $issuedata->{'renewals'} + 1;
2002     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?, lastreneweddate = ?
2003                             WHERE borrowernumber=? 
2004                             AND itemnumber=?"
2005     );
2006     $sth->execute( $datedue->output('iso'), $renews, $lastreneweddate, $borrowernumber, $itemnumber );
2007     $sth->finish;
2008
2009     # Update the renewal count on the item, and tell zebra to reindex
2010     $renews = $biblio->{'renewals'} + 1;
2011     ModItem({ renewals => $renews, onloan => $datedue->output('iso') }, $biblio->{'biblionumber'}, $itemnumber);
2012
2013     # Charge a new rental fee, if applicable?
2014     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
2015     if ( $charge > 0 ) {
2016         my $accountno = getnextacctno( $borrowernumber );
2017         my $item = GetBiblioFromItemNumber($itemnumber);
2018         $sth = $dbh->prepare(
2019                 "INSERT INTO accountlines
2020                     (date,
2021                                         borrowernumber, accountno, amount,
2022                     description,
2023                                         accounttype, amountoutstanding, itemnumber
2024                                         )
2025                     VALUES (now(),?,?,?,?,?,?,?)"
2026         );
2027         $sth->execute( $borrowernumber, $accountno, $charge,
2028             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
2029             'Rent', $charge, $itemnumber );
2030         $sth->finish;
2031     }
2032     # Log the renewal
2033     UpdateStats( $branch, 'renew', $charge, '', $itemnumber, $item->{itype}, $borrowernumber);
2034         return $datedue;
2035 }
2036
2037 sub GetRenewCount {
2038     # check renewal status
2039     my ($bornum,$itemno)=@_;
2040     my $dbh = C4::Context->dbh;
2041     my $renewcount = 0;
2042         my $renewsallowed = 0;
2043         my $renewsleft = 0;
2044     # Look in the issues table for this item, lent to this borrower,
2045     # and not yet returned.
2046
2047     # FIXME - I think this function could be redone to use only one SQL call.
2048     my $sth = $dbh->prepare("select * from issues
2049                                 where (borrowernumber = ?)
2050                                 and (itemnumber = ?)");
2051     $sth->execute($bornum,$itemno);
2052     my $data = $sth->fetchrow_hashref;
2053     $renewcount = $data->{'renewals'} if $data->{'renewals'};
2054     $sth->finish;
2055     my $query = "SELECT renewalsallowed FROM items ";
2056     $query .= (C4::Context->preference('item-level_itypes'))
2057                 ? "LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2058                 : "LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
2059                    LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2060     $query .= "WHERE items.itemnumber = ?";
2061     my $sth2 = $dbh->prepare($query);
2062     $sth2->execute($itemno);
2063     my $data2 = $sth2->fetchrow_hashref();
2064     $renewsallowed = $data2->{'renewalsallowed'};
2065     $renewsleft = $renewsallowed - $renewcount;
2066     return ($renewcount,$renewsallowed,$renewsleft);
2067 }
2068
2069 =head2 GetIssuingCharges
2070
2071 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
2072
2073 Calculate how much it would cost for a given patron to borrow a given
2074 item, including any applicable discounts.
2075
2076 C<$itemnumber> is the item number of item the patron wishes to borrow.
2077
2078 C<$borrowernumber> is the patron's borrower number.
2079
2080 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
2081 and C<$item_type> is the code for the item's item type (e.g., C<VID>
2082 if it's a video).
2083
2084 =cut
2085
2086 sub GetIssuingCharges {
2087
2088     # calculate charges due
2089     my ( $itemnumber, $borrowernumber ) = @_;
2090     my $charge = 0;
2091     my $dbh    = C4::Context->dbh;
2092     my $item_type;
2093
2094     # Get the book's item type and rental charge (via its biblioitem).
2095     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
2096             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
2097         $qcharge .= (C4::Context->preference('item-level_itypes'))
2098                 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
2099                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
2100         
2101     $qcharge .=      "WHERE items.itemnumber =?";
2102    
2103     my $sth1 = $dbh->prepare($qcharge);
2104     $sth1->execute($itemnumber);
2105     if ( my $data1 = $sth1->fetchrow_hashref ) {
2106         $item_type = $data1->{'itemtype'};
2107         $charge    = $data1->{'rentalcharge'};
2108         my $q2 = "SELECT rentaldiscount FROM borrowers
2109             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
2110             WHERE borrowers.borrowernumber = ?
2111             AND issuingrules.itemtype = ?";
2112         my $sth2 = $dbh->prepare($q2);
2113         $sth2->execute( $borrowernumber, $item_type );
2114         if ( my $data2 = $sth2->fetchrow_hashref ) {
2115             my $discount = $data2->{'rentaldiscount'};
2116             if ( $discount eq 'NULL' ) {
2117                 $discount = 0;
2118             }
2119             $charge = ( $charge * ( 100 - $discount ) ) / 100;
2120         }
2121         $sth2->finish;
2122     }
2123
2124     $sth1->finish;
2125     return ( $charge, $item_type );
2126 }
2127
2128 =head2 AddIssuingCharge
2129
2130 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
2131
2132 =cut
2133
2134 sub AddIssuingCharge {
2135     my ( $itemnumber, $borrowernumber, $charge ) = @_;
2136     my $dbh = C4::Context->dbh;
2137     my $nextaccntno = getnextacctno( $borrowernumber );
2138     my $query ="
2139         INSERT INTO accountlines
2140             (borrowernumber, itemnumber, accountno,
2141             date, amount, description, accounttype,
2142             amountoutstanding)
2143         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
2144     ";
2145     my $sth = $dbh->prepare($query);
2146     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
2147     $sth->finish;
2148 }
2149
2150 =head2 GetTransfers
2151
2152 GetTransfers($itemnumber);
2153
2154 =cut
2155
2156 sub GetTransfers {
2157     my ($itemnumber) = @_;
2158
2159     my $dbh = C4::Context->dbh;
2160
2161     my $query = '
2162         SELECT datesent,
2163                frombranch,
2164                tobranch
2165         FROM branchtransfers
2166         WHERE itemnumber = ?
2167           AND datearrived IS NULL
2168         ';
2169     my $sth = $dbh->prepare($query);
2170     $sth->execute($itemnumber);
2171     my @row = $sth->fetchrow_array();
2172     $sth->finish;
2173     return @row;
2174 }
2175
2176
2177 =head2 GetTransfersFromTo
2178
2179 @results = GetTransfersFromTo($frombranch,$tobranch);
2180
2181 Returns the list of pending transfers between $from and $to branch
2182
2183 =cut
2184
2185 sub GetTransfersFromTo {
2186     my ( $frombranch, $tobranch ) = @_;
2187     return unless ( $frombranch && $tobranch );
2188     my $dbh   = C4::Context->dbh;
2189     my $query = "
2190         SELECT itemnumber,datesent,frombranch
2191         FROM   branchtransfers
2192         WHERE  frombranch=?
2193           AND  tobranch=?
2194           AND datearrived IS NULL
2195     ";
2196     my $sth = $dbh->prepare($query);
2197     $sth->execute( $frombranch, $tobranch );
2198     my @gettransfers;
2199
2200     while ( my $data = $sth->fetchrow_hashref ) {
2201         push @gettransfers, $data;
2202     }
2203     $sth->finish;
2204     return (@gettransfers);
2205 }
2206
2207 =head2 DeleteTransfer
2208
2209 &DeleteTransfer($itemnumber);
2210
2211 =cut
2212
2213 sub DeleteTransfer {
2214     my ($itemnumber) = @_;
2215     my $dbh          = C4::Context->dbh;
2216     my $sth          = $dbh->prepare(
2217         "DELETE FROM branchtransfers
2218          WHERE itemnumber=?
2219          AND datearrived IS NULL "
2220     );
2221     $sth->execute($itemnumber);
2222     $sth->finish;
2223 }
2224
2225 =head2 AnonymiseIssueHistory
2226
2227 $rows = AnonymiseIssueHistory($borrowernumber,$date)
2228
2229 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
2230 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
2231
2232 return the number of affected rows.
2233
2234 =cut
2235
2236 sub AnonymiseIssueHistory {
2237     my $date           = shift;
2238     my $borrowernumber = shift;
2239     my $dbh            = C4::Context->dbh;
2240     my $query          = "
2241         UPDATE old_issues
2242         SET    borrowernumber = NULL
2243         WHERE  returndate < '".$date."'
2244           AND borrowernumber IS NOT NULL
2245     ";
2246     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
2247     my $rows_affected = $dbh->do($query);
2248     return $rows_affected;
2249 }
2250
2251 =head2 updateWrongTransfer
2252
2253 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
2254
2255 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 
2256
2257 =cut
2258
2259 sub updateWrongTransfer {
2260         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
2261         my $dbh = C4::Context->dbh;     
2262 # first step validate the actual line of transfert .
2263         my $sth =
2264                 $dbh->prepare(
2265                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
2266                 );
2267                 $sth->execute($FromLibrary,$itemNumber);
2268                 $sth->finish;
2269
2270 # second step create a new line of branchtransfer to the right location .
2271         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
2272
2273 #third step changing holdingbranch of item
2274         UpdateHoldingbranch($FromLibrary,$itemNumber);
2275 }
2276
2277 =head2 UpdateHoldingbranch
2278
2279 $items = UpdateHoldingbranch($branch,$itmenumber);
2280 Simple methode for updating hodlingbranch in items BDD line
2281
2282 =cut
2283
2284 sub UpdateHoldingbranch {
2285         my ( $branch,$itemnumber ) = @_;
2286     ModItem({ holdingbranch => $branch }, undef, $itemnumber);
2287 }
2288
2289 =head2 CalcDateDue
2290
2291 $newdatedue = CalcDateDue($startdate,$loanlength,$branchcode);
2292 this function calculates the due date given the loan length ,
2293 checking against the holidays calendar as per the 'useDaysMode' syspref.
2294 C<$startdate>   = C4::Dates object representing start date of loan period (assumed to be today)
2295 C<$branch>  = location whose calendar to use
2296 C<$loanlength>  = loan length prior to adjustment
2297 =cut
2298
2299 sub CalcDateDue { 
2300         my ($startdate,$loanlength,$branch) = @_;
2301         if(C4::Context->preference('useDaysMode') eq 'Days') {  # ignoring calendar
2302                 my $datedue = time + ($loanlength) * 86400;
2303         #FIXME - assumes now even though we take a startdate 
2304                 my @datearr  = localtime($datedue);
2305                 return C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
2306         } else {
2307                 my $calendar = C4::Calendar->new(  branchcode => $branch );
2308                 my $datedue = $calendar->addDate($startdate, $loanlength);
2309                 return $datedue;
2310         }
2311 }
2312
2313 =head2 CheckValidDatedue
2314        This function does not account for holiday exceptions nor does it handle the 'useDaysMode' syspref .
2315        To be replaced by CalcDateDue() once C4::Calendar use is tested.
2316
2317 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
2318 this function validates the loan length against the holidays calendar, and adjusts the due date as per the 'useDaysMode' syspref.
2319 C<$date_due>   = returndate calculate with no day check
2320 C<$itemnumber>  = itemnumber
2321 C<$branchcode>  = location of issue (affected by 'CircControl' syspref)
2322 C<$loanlength>  = loan length prior to adjustment
2323 =cut
2324
2325 sub CheckValidDatedue {
2326 my ($date_due,$itemnumber,$branchcode)=@_;
2327 my @datedue=split('-',$date_due->output('iso'));
2328 my $years=$datedue[0];
2329 my $month=$datedue[1];
2330 my $day=$datedue[2];
2331 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
2332 my $dow;
2333 for (my $i=0;$i<2;$i++){
2334     $dow=Day_of_Week($years,$month,$day);
2335     ($dow=0) if ($dow>6);
2336     my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
2337     my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2338     my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2339         if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
2340         $i=0;
2341         (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
2342         }
2343     }
2344     my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
2345 return $newdatedue;
2346 }
2347
2348
2349 =head2 CheckRepeatableHolidays
2350
2351 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
2352 this function checks if the date due is a repeatable holiday
2353 C<$date_due>   = returndate calculate with no day check
2354 C<$itemnumber>  = itemnumber
2355 C<$branchcode>  = localisation of issue 
2356
2357 =cut
2358
2359 sub CheckRepeatableHolidays{
2360 my($itemnumber,$week_day,$branchcode)=@_;
2361 my $dbh = C4::Context->dbh;
2362 my $query = qq|SELECT count(*)  
2363         FROM repeatable_holidays 
2364         WHERE branchcode=?
2365         AND weekday=?|;
2366 my $sth = $dbh->prepare($query);
2367 $sth->execute($branchcode,$week_day);
2368 my $result=$sth->fetchrow;
2369 $sth->finish;
2370 return $result;
2371 }
2372
2373
2374 =head2 CheckSpecialHolidays
2375
2376 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2377 this function check if the date is a special holiday
2378 C<$years>   = the years of datedue
2379 C<$month>   = the month of datedue
2380 C<$day>     = the day of datedue
2381 C<$itemnumber>  = itemnumber
2382 C<$branchcode>  = localisation of issue 
2383
2384 =cut
2385
2386 sub CheckSpecialHolidays{
2387 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2388 my $dbh = C4::Context->dbh;
2389 my $query=qq|SELECT count(*) 
2390              FROM `special_holidays`
2391              WHERE year=?
2392              AND month=?
2393              AND day=?
2394              AND branchcode=?
2395             |;
2396 my $sth = $dbh->prepare($query);
2397 $sth->execute($years,$month,$day,$branchcode);
2398 my $countspecial=$sth->fetchrow ;
2399 $sth->finish;
2400 return $countspecial;
2401 }
2402
2403 =head2 CheckRepeatableSpecialHolidays
2404
2405 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2406 this function check if the date is a repeatble special holidays
2407 C<$month>   = the month of datedue
2408 C<$day>     = the day of datedue
2409 C<$itemnumber>  = itemnumber
2410 C<$branchcode>  = localisation of issue 
2411
2412 =cut
2413
2414 sub CheckRepeatableSpecialHolidays{
2415 my ($month,$day,$itemnumber,$branchcode) = @_;
2416 my $dbh = C4::Context->dbh;
2417 my $query=qq|SELECT count(*) 
2418              FROM `repeatable_holidays`
2419              WHERE month=?
2420              AND day=?
2421              AND branchcode=?
2422             |;
2423 my $sth = $dbh->prepare($query);
2424 $sth->execute($month,$day,$branchcode);
2425 my $countspecial=$sth->fetchrow ;
2426 $sth->finish;
2427 return $countspecial;
2428 }
2429
2430
2431
2432 sub CheckValidBarcode{
2433 my ($barcode) = @_;
2434 my $dbh = C4::Context->dbh;
2435 my $query=qq|SELECT count(*) 
2436              FROM items 
2437              WHERE barcode=?
2438             |;
2439 my $sth = $dbh->prepare($query);
2440 $sth->execute($barcode);
2441 my $exist=$sth->fetchrow ;
2442 $sth->finish;
2443 return $exist;
2444 }
2445
2446 1;
2447
2448 __END__
2449
2450 =head1 AUTHOR
2451
2452 Koha Developement team <info@koha.org>
2453
2454 =cut
2455