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