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