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