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