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