Can check an item out now
[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 require Exporter;
23 use C4::Context;
24 use C4::Stats;
25 use C4::Reserves;
26 use C4::Koha;
27 use C4::Biblio;
28 use C4::Members;
29 use C4::Date;
30 use Date::Calc qw(
31   Today
32   Today_and_Now
33   Add_Delta_YM
34   Add_Delta_DHMS
35   Date_to_Days
36   Day_of_Week
37   Add_Delta_Days        
38 );
39 use POSIX qw(strftime);
40 use C4::Branch; # GetBranches
41 use C4::Log; # logaction
42
43 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,%EXPORT_TAGS);
44
45 # set the version for version checking
46 $VERSION = 3.00;
47
48 =head1 NAME
49
50 C4::Circulation - Koha circulation module
51
52 =head1 SYNOPSIS
53
54 use C4::Circulation;
55
56 =head1 DESCRIPTION
57
58 The functions in this module deal with circulation, issues, and
59 returns, as well as general information about the library.
60 Also deals with stocktaking.
61
62 =head1 FUNCTIONS
63
64 =cut
65
66 @ISA    = qw(Exporter);
67
68 # FIXME subs that should probably be elsewhere
69 push @EXPORT, qw(
70   &FixOverduesOnReturn
71   &cuecatbarcodedecode
72 );
73
74 # subs to deal with issuing a book
75 push @EXPORT, qw(
76   &CanBookBeIssued
77   &CanBookBeRenewed
78   &AddIssue
79   &AddRenewal
80   &GetItemIssue
81   &GetItemIssues
82   &GetBorrowerIssues
83   &GetIssuingCharges
84   &GetBiblioIssues
85   &AnonymiseIssueHistory
86 );
87 # subs to deal with returns
88 push @EXPORT, qw(
89   &AddReturn
90 );
91
92 # subs to deal with transfers
93 push @EXPORT, qw(
94   &transferbook
95   &GetTransfers
96   &GetTransfersFromTo
97   &updateWrongTransfer
98   &DeleteTransfer
99 );
100
101 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
102 # FIXME From Paul : i don't understand what this sub does & why it has to be called on every circ. Speak of this with chris maybe ?
103
104 =head2 decode
105
106 =head3 $str = &decode($chunk);
107
108 =over 4
109
110 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
111 returns it.
112
113 =back
114
115 =cut
116
117 sub cuecatbarcodedecode {
118     my ($barcode) = @_;
119     chomp($barcode);
120     my @fields = split( /\./, $barcode );
121     my @results = map( decode($_), @fields[ 1 .. $#fields ] );
122     if ( $#results == 2 ) {
123         return $results[2];
124     }
125     else {
126         return $barcode;
127     }
128 }
129
130 =head2 decode
131
132 =head3 $str = &decode($chunk);
133
134 =over 4
135
136 =item Decodes a segment of a string emitted by a CueCat barcode scanner and
137 returns it.
138
139 =back
140
141 =cut
142
143 sub decode {
144     my ($encoded) = @_;
145     my $seq =
146       'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
147     my @s = map { index( $seq, $_ ); } split( //, $encoded );
148     my $l = ( $#s + 1 ) % 4;
149     if ($l) {
150         if ( $l == 1 ) {
151             warn "Error!";
152             return;
153         }
154         $l = 4 - $l;
155         $#s += $l;
156     }
157     my $r = '';
158     while ( $#s >= 0 ) {
159         my $n = ( ( $s[0] << 6 | $s[1] ) << 6 | $s[2] ) << 6 | $s[3];
160         $r .=
161             chr( ( $n >> 16 ) ^ 67 )
162          .chr( ( $n >> 8 & 255 ) ^ 67 )
163          .chr( ( $n & 255 ) ^ 67 );
164         @s = @s[ 4 .. $#s ];
165     }
166     $r = substr( $r, 0, length($r) - $l );
167     return $r;
168 }
169
170 =head2 transferbook
171
172 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
173
174 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
175
176 C<$newbranch> is the code for the branch to which the item should be transferred.
177
178 C<$barcode> is the barcode of the item to be transferred.
179
180 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
181 Otherwise, if an item is reserved, the transfer fails.
182
183 Returns three values:
184
185 =head3 $dotransfer 
186
187 is true if the transfer was successful.
188
189 =head3 $messages
190
191 is a reference-to-hash which may have any of the following keys:
192
193 =over 4
194
195 =item C<BadBarcode>
196
197 There is no item in the catalog with the given barcode. The value is C<$barcode>.
198
199 =item C<IsPermanent>
200
201 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.
202
203 =item C<DestinationEqualsHolding>
204
205 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.
206
207 =item C<WasReturned>
208
209 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.
210
211 =item C<ResFound>
212
213 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>.
214
215 =item C<WasTransferred>
216
217 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
218
219 =back
220
221 =cut
222
223 sub transferbook {
224     my ( $tbr, $barcode, $ignoreRs ) = @_;
225     my $messages;
226     my $dotransfer      = 1;
227     my $branches        = GetBranches();
228     my $itemnumber = GetItemnumberFromBarcode( $barcode );
229     my $issue      = GetItemIssue($itemnumber);
230     my $biblio = GetBiblioFromItemNumber($itemnumber);
231
232     # bad barcode..
233     if ( not $itemnumber ) {
234         $messages->{'BadBarcode'} = $barcode;
235         $dotransfer = 0;
236     }
237
238     # get branches of book...
239     my $hbr = $biblio->{'homebranch'};
240     my $fbr = $biblio->{'holdingbranch'};
241
242     # if is permanent...
243     if ( $hbr && $branches->{$hbr}->{'PE'} ) {
244         $messages->{'IsPermanent'} = $hbr;
245     }
246
247     # can't transfer book if is already there....
248     if ( $fbr eq $tbr ) {
249         $messages->{'DestinationEqualsHolding'} = 1;
250         $dotransfer = 0;
251     }
252
253     # check if it is still issued to someone, return it...
254     if ($issue->{borrowernumber}) {
255         AddReturn( $barcode, $fbr );
256         $messages->{'WasReturned'} = $issue->{borrowernumber};
257     }
258
259     # find reserves.....
260     # That'll save a database query.
261     my ( $resfound, $resrec ) =
262       CheckReserves( $itemnumber );
263     if ( $resfound and not $ignoreRs ) {
264         $resrec->{'ResFound'} = $resfound;
265
266         #         $messages->{'ResFound'} = $resrec;
267         $dotransfer = 1;
268     }
269
270     #actually do the transfer....
271     if ($dotransfer) {
272         ModItemTransfer( $itemnumber, $fbr, $tbr );
273
274         # don't need to update MARC anymore, we do it in batch now
275         $messages->{'WasTransfered'} = 1;
276                 ModDateLastSeen( $itemnumber );
277     }
278     return ( $dotransfer, $messages, $biblio );
279 }
280
281 =head2 CanBookBeIssued
282
283 Check if a book can be issued.
284
285 my ($issuingimpossible,$needsconfirmation) = CanBookBeIssued($borrower,$barcode,$year,$month,$day);
286
287 =over 4
288
289 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
290
291 =item C<$barcode> is the bar code of the book being issued.
292
293 =item C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
294
295 =back
296
297 Returns :
298
299 =over 4
300
301 =item C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
302 Possible values are :
303
304 =back
305
306 =head3 INVALID_DATE 
307
308 sticky due date is invalid
309
310 =head3 GNA
311
312 borrower gone with no address
313
314 =head3 CARD_LOST
315
316 borrower declared it's card lost
317
318 =head3 DEBARRED
319
320 borrower debarred
321
322 =head3 UNKNOWN_BARCODE
323
324 barcode unknown
325
326 =head3 NOT_FOR_LOAN
327
328 item is not for loan
329
330 =head3 WTHDRAWN
331
332 item withdrawn.
333
334 =head3 RESTRICTED
335
336 item is restricted (set by ??)
337
338 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
339 Possible values are :
340
341 =head3 DEBT
342
343 borrower has debts.
344
345 =head3 RENEW_ISSUE
346
347 renewing, not issuing
348
349 =head3 ISSUED_TO_ANOTHER
350
351 issued to someone else.
352
353 =head3 RESERVED
354
355 reserved for someone else.
356
357 =head3 INVALID_DATE
358
359 sticky due date is invalid
360
361 =head3 TOO_MANY
362
363 if the borrower borrows to much things
364
365 =cut
366
367 # check if a book can be issued.
368
369
370 sub TooMany {
371     my $borrower        = shift;
372     my $biblionumber = shift;
373         my $item                = shift;
374     my $cat_borrower    = $borrower->{'categorycode'};
375     my $branch_borrower = $borrower->{'branchcode'};
376     my $dbh             = C4::Context->dbh;
377
378  my $branch_issuer = C4::Context->userenv->{'branchcode'};
379 #TODO : specify issuer or borrower for circrule.
380   my $type = (C4::Context->preference('item-level_itypes')) 
381                         ? $item->{'ccode'}         # item-level
382                         : $item->{'itemtype'};     # biblio-level
383   
384   my $sth =
385       $dbh->prepare(
386                 'SELECT * FROM issuingrules 
387                         WHERE categorycode = ? 
388                             AND branchcode = ?
389                             AND itemtype = ? '
390       );
391
392     my $query2 = "SELECT  COUNT(*) FROM issues i, biblioitems s1, items s2 
393                 WHERE i.borrowernumber = ? 
394                     AND i.returndate IS NULL 
395                     AND i.itemnumber = s2.itemnumber 
396                     AND s1.biblioitemnumber = s2.biblioitemnumber"
397                                 . (C4::Context->preference('item-level_itypes'))
398                                 ? " AND s2.ccode=? "
399                 : " AND s1.itemtype= ? ";
400     my $sth2=  $dbh->prepare($query2);
401     my $sth3 =
402       $dbh->prepare(
403             'SELECT COUNT(*) FROM issues
404                 WHERE borrowernumber = ?
405                     AND returndate IS NULL'
406             );
407     my $alreadyissued;
408
409     # check the 3 parameters (branch / itemtype / category code
410     $sth->execute( $cat_borrower, $type, $branch_borrower );
411     my $result = $sth->fetchrow_hashref;
412 #     warn "$cat_borrower, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
413
414     if ( $result->{maxissueqty} ne '' ) {
415 #         warn "checking on everything set";
416         $sth2->execute( $borrower->{'borrowernumber'}, $type );
417         my $alreadyissued = $sth2->fetchrow;
418         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
419             return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/itemtype failed)" );
420         }
421         # now checking for total
422         $sth->execute( $cat_borrower, '', $branch_borrower );
423         my $result = $sth->fetchrow_hashref;
424         if ( $result->{maxissueqty} ne '*' ) {
425             $sth2->execute( $borrower->{'borrowernumber'}, $type );
426             my $alreadyissued = $sth2->fetchrow;
427             if ( $result->{'maxissueqty'} <= $alreadyissued ) {
428                 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch/category/total failed)"  );
429             }
430         }
431     }
432
433     # check the 2 parameters (branch / itemtype / default categorycode
434     $sth->execute( '*', $type, $branch_borrower );
435     my $result = $sth->fetchrow_hashref;
436 #     warn "*, $type, $branch_borrower = ".Data::Dumper::Dumper($result);
437
438     if ( $result->{maxissueqty} ne '' ) {
439 #         warn "checking on 2 parameters (default categorycode)";
440         $sth2->execute( $borrower->{'borrowernumber'}, $type );
441         my $alreadyissued = $sth2->fetchrow;
442         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
443             return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / itemtype failed)"  );
444         }
445         # now checking for total
446         $sth->execute( '*', '*', $branch_borrower );
447         my $result = $sth->fetchrow_hashref;
448         if ( $result->{maxissueqty} ne '' ) {
449             $sth2->execute( $borrower->{'borrowernumber'}, $type );
450             my $alreadyissued = $sth2->fetchrow;
451             if ( $result->{'maxissueqty'} <= $alreadyissued ) {
452                 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on branch / default category / total failed)" );
453             }
454         }
455     }
456     
457     # check the 1 parameters (default branch / itemtype / categorycode
458     $sth->execute( $cat_borrower, $type, '*' );
459     my $result = $sth->fetchrow_hashref;
460 #     warn "$cat_borrower, $type, * = ".Data::Dumper::Dumper($result);
461     
462     if ( $result->{maxissueqty} ne '' ) {
463 #         warn "checking on 1 parameter (default branch + categorycode)";
464         $sth2->execute( $borrower->{'borrowernumber'}, $type );
465         my $alreadyissued = $sth2->fetchrow;
466         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
467             return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch/category/itemtype failed)"  );
468         }
469         # now checking for total
470         $sth->execute( $cat_borrower, '*', '*' );
471         my $result = $sth->fetchrow_hashref;
472         if ( $result->{maxissueqty} ne '' ) {
473             $sth2->execute( $borrower->{'borrowernumber'}, $type );
474             my $alreadyissued = $sth2->fetchrow;
475             if ( $result->{'maxissueqty'} <= $alreadyissued ) {
476                 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / category / total failed)"  );
477             }
478         }
479     }
480
481     # check the 0 parameters (default branch / itemtype / default categorycode
482     $sth->execute( '*', $type, '*' );
483     my $result = $sth->fetchrow_hashref;
484 #     warn "*, $type, * = ".Data::Dumper::Dumper($result);
485
486     if ( $result->{maxissueqty} ne '' ) {
487 #         warn "checking on default branch and default categorycode";
488         $sth2->execute( $borrower->{'borrowernumber'}, $type );
489         my $alreadyissued = $sth2->fetchrow;
490         if ( $result->{'maxissueqty'} <= $alreadyissued ) {
491             return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / itemtype failed)"  );
492         }
493         # now checking for total
494         $sth->execute( '*', '*', '*' );
495         my $result = $sth->fetchrow_hashref;
496         if ( $result->{maxissueqty} ne '' ) {
497             $sth2->execute( $borrower->{'borrowernumber'}, $type );
498             my $alreadyissued = $sth2->fetchrow;
499             if ( $result->{'maxissueqty'} <= $alreadyissued ) {
500                 return ( "$alreadyissued / ".( $result->{maxissueqty} + 0 )." (rule on default branch / default category / total failed)"  );
501             }
502         }
503     }
504
505     #OK, the patron can issue !!!
506     return;
507 }
508
509 =head2 itemissues
510
511   @issues = &itemissues($biblioitemnumber, $biblio);
512
513 Looks up information about who has borrowed the bookZ<>(s) with the
514 given biblioitemnumber.
515
516 C<$biblio> is ignored.
517
518 C<&itemissues> returns an array of references-to-hash. The keys
519 include the fields from the C<items> table in the Koha database.
520 Additional keys include:
521
522 =over 4
523
524 =item C<date_due>
525
526 If the item is currently on loan, this gives the due date.
527
528 If the item is not on loan, then this is either "Available" or
529 "Cancelled", if the item has been withdrawn.
530
531 =item C<card>
532
533 If the item is currently on loan, this gives the card number of the
534 patron who currently has the item.
535
536 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
537
538 These give the timestamp for the last three times the item was
539 borrowed.
540
541 =item C<card0>, C<card1>, C<card2>
542
543 The card number of the last three patrons who borrowed this item.
544
545 =item C<borrower0>, C<borrower1>, C<borrower2>
546
547 The borrower number of the last three patrons who borrowed this item.
548
549 =back
550
551 =cut
552
553 #'
554 sub itemissues {
555     my ( $bibitem, $biblio ) = @_;
556     my $dbh = C4::Context->dbh;
557
558     # FIXME - If this function die()s, the script will abort, and the
559     # user won't get anything; depending on how far the script has
560     # gotten, the user might get a blank page. It would be much better
561     # to at least print an error message. The easiest way to do this
562     # is to set $SIG{__DIE__}.
563     my $sth =
564       $dbh->prepare("Select * from items where items.biblioitemnumber = ?")
565       || die $dbh->errstr;
566     my $i = 0;
567     my @results;
568
569     $sth->execute($bibitem) || die $sth->errstr;
570
571     while ( my $data = $sth->fetchrow_hashref ) {
572
573         # Find out who currently has this item.
574         # FIXME - Wouldn't it be better to do this as a left join of
575         # some sort? Currently, this code assumes that if
576         # fetchrow_hashref() fails, then the book is on the shelf.
577         # fetchrow_hashref() can fail for any number of reasons (e.g.,
578         # database server crash), not just because no items match the
579         # search criteria.
580         my $sth2 = $dbh->prepare(
581             "SELECT * FROM issues
582                 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
583                 WHERE itemnumber = ?
584                     AND returndate IS NULL
585             "
586         );
587
588         $sth2->execute( $data->{'itemnumber'} );
589         if ( my $data2 = $sth2->fetchrow_hashref ) {
590             $data->{'date_due'} = $data2->{'date_due'};
591             $data->{'card'}     = $data2->{'cardnumber'};
592             $data->{'borrower'} = $data2->{'borrowernumber'};
593         }
594         else {
595             if ( $data->{'wthdrawn'} eq '1' ) {
596                 $data->{'date_due'} = 'Cancelled';
597             }
598             else {
599                 $data->{'date_due'} = 'Available';
600             }    # else
601         }    # else
602
603         $sth2->finish;
604
605         # Find the last 3 people who borrowed this item.
606         $sth2 = $dbh->prepare(
607             "SELECT * FROM issues
608                 LEFT JOIN borrowers ON  issues.borrowernumber = borrowers.borrowernumber
609                 WHERE itemnumber = ?
610                 AND returndate IS NOT NULL
611                 ORDER BY returndate DESC,timestamp DESC"
612         );
613
614         $sth2->execute( $data->{'itemnumber'} );
615         for ( my $i2 = 0 ; $i2 < 2 ; $i2++ )
616         {    # FIXME : error if there is less than 3 pple borrowing this item
617             if ( my $data2 = $sth2->fetchrow_hashref ) {
618                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
619                 $data->{"card$i2"}      = $data2->{'cardnumber'};
620                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
621             }    # if
622         }    # for
623
624         $sth2->finish;
625         $results[$i] = $data;
626         $i++;
627     }
628
629     $sth->finish;
630     return (@results);
631 }
632
633 =head2 CanBookBeIssued
634
635 $issuingimpossible, $needsconfirmation = 
636         CanBookBeIssued( $borrower, $barcode, $year, $month, $day, $inprocess );
637
638 C<$issuingimpossible> and C<$needsconfirmation> are some hashref.
639
640 =cut
641
642 sub CanBookBeIssued {
643     my ( $borrower, $barcode, $year, $month, $day, $inprocess ) = @_;
644     my %needsconfirmation;    # filled with problems that needs confirmations
645     my %issuingimpossible;    # filled with problems that causes the issue to be IMPOSSIBLE
646     my $item = GetItem(GetItemnumberFromBarcode( $barcode ));
647     my $issue = GetItemIssue($item->{itemnumber});
648     my $dbh             = C4::Context->dbh;
649
650     #
651     # DUE DATE is OK ?
652     #
653     my ( $duedate, $invalidduedate ) = fixdate( $year, $month, $day );
654     $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
655
656     #
657     # BORROWER STATUS
658     #
659     if ( $borrower->{flags}->{GNA} ) {
660         $issuingimpossible{GNA} = 1;
661     }
662     if ( $borrower->{flags}->{'LOST'} ) {
663         $issuingimpossible{CARD_LOST} = 1;
664     }
665     if ( $borrower->{flags}->{'DBARRED'} ) {
666         $issuingimpossible{DEBARRED} = 1;
667     }
668     if ( $borrower->{'dateexpiry'} eq '0000-00-00') {
669         $issuingimpossible{EXPIRED} = 1;
670     } else {
671         my @expirydate=  split /-/,$borrower->{'dateexpiry'};
672         if($expirydate[0]==0 || $expirydate[1]==0|| $expirydate[2]==0 ||
673             Date_to_Days(Today) > Date_to_Days( @expirydate )) {
674             $issuingimpossible{EXPIRED} = 1;                                   
675         }
676     }
677     #
678     # BORROWER STATUS
679     #
680
681     # DEBTS
682     my ($amount) =
683       C4::Members::GetMemberAccountRecords( $borrower->{'borrowernumber'}, $duedate );
684     if ( C4::Context->preference("IssuingInProcess") ) {
685         my $amountlimit = C4::Context->preference("noissuescharge");
686         if ( $amount > $amountlimit && !$inprocess ) {
687             $issuingimpossible{DEBT} = sprintf( "%.2f", $amount );
688         }
689         elsif ( $amount <= $amountlimit && !$inprocess ) {
690             $needsconfirmation{DEBT} = sprintf( "%.2f", $amount );
691         }
692     }
693     else {
694         if ( $amount > 0 ) {
695             $needsconfirmation{DEBT} = $amount;
696         }
697     }
698
699     #
700     # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
701     #
702     
703         my $toomany = TooMany( $borrower, $item->{biblionumber}, $item );
704     $needsconfirmation{TOO_MANY} = $toomany if $toomany;
705
706     #
707     # ITEM CHECKING
708     #
709     unless ( $item->{barcode} ) {
710         $issuingimpossible{UNKNOWN_BARCODE} = 1;
711     }
712     if (   $item->{'notforloan'}
713         && $item->{'notforloan'} > 0 )
714     {
715         $issuingimpossible{NOT_FOR_LOAN} = 1;
716     }
717     if ( $item->{'wthdrawn'} && $item->{'wthdrawn'} == 1 )
718     {
719         $issuingimpossible{WTHDRAWN} = 1;
720     }
721     if (   $item->{'restricted'}
722         && $item->{'restricted'} == 1 )
723     {
724         $issuingimpossible{RESTRICTED} = 1;
725     }
726     if ( C4::Context->preference("IndependantBranches") ) {
727         my $userenv = C4::Context->userenv;
728         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
729             $issuingimpossible{NOTSAMEBRANCH} = 1
730               if ( $item->{'holdingbranch'} ne $userenv->{branch} );
731         }
732     }
733
734     #
735     # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
736     #
737     if ( $issue->{borrowernumber} && $issue->{borrowernumber} eq $borrower->{'borrowernumber'} )
738     {
739
740         # Already issued to current borrower. Ask whether the loan should
741         # be renewed.
742         my ($CanBookBeRenewed) = CanBookBeRenewed(
743             $borrower->{'borrowernumber'},
744             $item->{'itemnumber'}
745         );
746         if ( $CanBookBeRenewed == 0 ) {    # no more renewals allowed
747             $issuingimpossible{NO_MORE_RENEWALS} = 1;
748         }
749         else {
750             $needsconfirmation{RENEW_ISSUE} = 1;
751         }
752     }
753     elsif ($issue->{borrowernumber}) {
754
755         # issued to someone else
756         my $currborinfo = GetMemberDetails( $issue->{borrowernumber} );
757
758 #        warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
759         $needsconfirmation{ISSUED_TO_ANOTHER} =
760 "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
761     }
762
763     # See if the item is on reserve.
764     my ( $restype, $res ) = C4::Reserves::CheckReserves( $item->{'itemnumber'} );
765     if ($restype) {
766         my $resbor = $res->{'borrowernumber'};
767         if ( $resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting" )
768         {
769
770             # The item is on reserve and waiting, but has been
771             # reserved by some other patron.
772             my ( $resborrower, $flags ) =
773               GetMemberDetails( $resbor, 0 );
774             my $branches   = GetBranches();
775             my $branchname =
776               $branches->{ $res->{'branchcode'} }->{'branchname'};
777             $needsconfirmation{RESERVE_WAITING} =
778 "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
779
780 # CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'}); Doesn't belong in a checking subroutine.
781         }
782         elsif ( $restype eq "Reserved" ) {
783
784             # The item is on reserve for someone else.
785             my ( $resborrower, $flags ) =
786               GetMemberDetails( $resbor, 0 );
787             my $branches   = GetBranches();
788             my $branchname =
789               $branches->{ $res->{'branchcode'} }->{'branchname'};
790             $needsconfirmation{RESERVED} =
791 "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
792         }
793     }
794     if ( C4::Context->preference("LibraryName") eq "Horowhenua Library Trust" ) {
795         if ( $borrower->{'categorycode'} eq 'W' ) {
796             my %issuingimpossible;
797             return ( \%issuingimpossible, \%needsconfirmation );
798         } else {
799             return ( \%issuingimpossible, \%needsconfirmation );
800         }
801     } else {
802         return ( \%issuingimpossible, \%needsconfirmation );
803     }
804 }
805
806 =head2 AddIssue
807
808 Issue a book. Does no check, they are done in CanBookBeIssued. If we reach this sub, it means the user confirmed if needed.
809
810 &AddIssue($borrower,$barcode,$date)
811
812 =over 4
813
814 =item C<$borrower> hash with borrower informations (from GetMemberDetails)
815
816 =item C<$barcode> is the bar code of the book being issued.
817
818 =item C<$date> contains the max date of return. calculated if empty.
819
820 AddIssue does the following things :
821 - step 01: check that there is a borrowernumber & a barcode provided
822 - check for RENEWAL (book issued & being issued to the same patron)
823     - renewal YES = Calculate Charge & renew
824     - renewal NO  = 
825         * BOOK ACTUALLY ISSUED ? do a return if book is actually issued (but to someone else)
826         * RESERVE PLACED ?
827             - fill reserve if reserve to this patron
828             - cancel reserve or not, otherwise
829         * TRANSFERT PENDING ?
830             - complete the transfert
831         * ISSUE THE BOOK
832
833 =back
834
835 =cut
836
837 sub AddIssue {
838     my ( $borrower, $barcode, $date, $cancelreserve ) = @_;
839     my $dbh = C4::Context->dbh;
840 my $barcodecheck=CheckValidBarcode($barcode);
841 if ($borrower and $barcode and $barcodecheck ne '0'){
842 #   my ($borrower, $flags) = &GetMemberDetails($borrowernumber, 0);
843     # find which item we issue
844     my $item = GetItem('', $barcode);
845         
846         my $datedue;
847     
848     # get actual issuing if there is one
849     my $actualissue = GetItemIssue( $item->{itemnumber});
850     
851     # get biblioinformation for this item
852     my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
853
854     #
855     # check if we just renew the issue.
856     #
857     if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
858         # we renew, do we need to add some charge ?
859         my ( $charge, $itemtype ) = GetIssuingCharges(
860             $item->{'itemnumber'},
861             $borrower->{'borrowernumber'}
862         );
863         if ( $charge > 0 ) {
864             AddIssuingCharge(
865                 $item->{'itemnumber'},
866                 $borrower->{'borrowernumber'}, $charge
867             );
868             $item->{'charge'} = $charge;
869         }
870         &UpdateStats(
871             C4::Context->userenv->{'branch'},
872             'renew',                        $charge,
873             '',                             $item->{'itemnumber'},
874             $biblio->{'itemtype'}, $borrower->{'borrowernumber'}
875         );
876         AddRenewal(
877             $borrower->{'borrowernumber'},
878             $item->{'itemnumber'}
879         );
880     }
881     else {# it's NOT a renewal
882         if ( $actualissue->{borrowernumber}) {
883             # This book is currently on loan, but not to the person
884             # who wants to borrow it now. mark it returned before issuing to the new borrower
885             AddReturn(
886                 $item->{'barcode'},
887                 C4::Context->userenv->{'branch'}
888             );
889         }
890
891         # See if the item is on reserve.
892         my ( $restype, $res ) =
893           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
894         if ($restype) {
895             my $resbor = $res->{'borrowernumber'};
896             if ( $resbor eq $borrower->{'borrowernumber'} ) {
897
898                 # The item is reserved by the current patron
899                 ModReserveFill($res);
900             }
901             elsif ( $restype eq "Waiting" ) {
902
903                 # warn "Waiting";
904                 # The item is on reserve and waiting, but has been
905                 # reserved by some other patron.
906                 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
907                 my $branches   = GetBranches();
908                 my $branchname =
909                   $branches->{ $res->{'branchcode'} }->{'branchname'};
910             }
911             elsif ( $restype eq "Reserved" ) {
912
913                 # warn "Reserved";
914                 # The item is reserved by someone else.
915                 my ( $resborrower, $flags ) =
916                   GetMemberDetails( $resbor, 0 );
917                 my $branches   = GetBranches();
918                 my $branchname =
919                   $branches->{ $res->{'branchcode'} }->{'branchname'};
920                 if ($cancelreserve) { # cancel reserves on this item
921                     CancelReserve( 0, $res->{'itemnumber'},
922                         $res->{'borrowernumber'} );
923                 }
924             }
925             if ($cancelreserve) {
926                 CancelReserve( $res->{'biblionumber'}, 0,
927                     $res->{'borrowernumber'} );
928             }
929             else {
930     # set waiting reserve to first in reserve queue as book isn't waiting now
931                 ModReserve(
932                     1,
933                     $res->{'biblionumber'},
934                     $res->{'borrowernumber'},
935                     $res->{'branchcode'}
936                 );
937             }
938         }
939
940         # Starting process for transfer job (checking transfert and validate it if we have one)
941             my ($datesent) = GetTransfers($item->{'itemnumber'});
942             if ($datesent) {
943         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
944             my $sth =
945                     $dbh->prepare(
946                     "UPDATE branchtransfers 
947                         SET datearrived = now(),
948                         tobranch = ?,
949                         comments = 'Forced branchtransfert'
950                     WHERE itemnumber= ? AND datearrived IS NULL"
951                     );
952                     $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
953                     $sth->finish;
954             }
955
956         # Record in the database the fact that the book was issued.
957         my $sth =
958           $dbh->prepare(
959                 "INSERT INTO issues 
960                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
961                 VALUES (?,?,?,?,?)"
962           );
963                 my $itype=(C4::Context->preference('item-level_itypes')) ? $biblio->{'itemtype'} : $biblio->{'ccode'};
964         my $loanlength = GetLoanLength(
965             $borrower->{'categorycode'},
966             $itype,
967             $borrower->{'branchcode'}
968         );
969         $datedue  = time + ($loanlength) * 86400;
970         my @datearr  = localtime($datedue);
971         my $dateduef =
972             sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]);
973         if ($date) {
974             $dateduef = $date;
975         }
976        $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
977        # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
978         if ( C4::Context->preference('ReturnBeforeExpiry')
979             && $dateduef gt $borrower->{dateexpiry} )
980         {
981             $dateduef = $borrower->{dateexpiry};
982         }
983         $sth->execute(
984             $borrower->{'borrowernumber'},
985             $item->{'itemnumber'},
986             strftime( "%Y-%m-%d", localtime ),$dateduef, C4::Context->userenv->{'branch'}
987         );
988         $sth->finish;
989         $item->{'issues'}++;
990         $sth =
991           $dbh->prepare(
992             "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed  = now() WHERE itemnumber=?");
993         $sth->execute(
994             $item->{'issues'},
995             C4::Context->userenv->{'branch'},
996             $item->{'itemnumber'}
997         );
998         $sth->finish;
999         &ModDateLastSeen( $item->{'itemnumber'} );
1000         # If it costs to borrow this book, charge it to the patron's account.
1001         my ( $charge, $itemtype ) = GetIssuingCharges(
1002             $item->{'itemnumber'},
1003             $borrower->{'borrowernumber'}
1004         );
1005         if ( $charge > 0 ) {
1006             AddIssuingCharge(
1007                 $item->{'itemnumber'},
1008                 $borrower->{'borrowernumber'}, $charge
1009             );
1010             $item->{'charge'} = $charge;
1011         }
1012
1013         # Record the fact that this book was issued.
1014         &UpdateStats(
1015             C4::Context->userenv->{'branch'},
1016             'issue',                        $charge,
1017             '',                             $item->{'itemnumber'},
1018             $item->{'itemtype'}, $borrower->{'borrowernumber'}
1019         );
1020     }
1021     
1022     &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'}) 
1023         if C4::Context->preference("IssueLog");
1024     return ($datedue);
1025   }  
1026 }
1027
1028 =head2 GetLoanLength
1029
1030 Get loan length for an itemtype, a borrower type and a branch
1031
1032 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1033
1034 =cut
1035
1036 sub GetLoanLength {
1037     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1038     my $dbh = C4::Context->dbh;
1039     my $sth =
1040       $dbh->prepare(
1041 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1042       );
1043
1044 # try to find issuelength & return the 1st available.
1045 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1046     $sth->execute( $borrowertype, $itemtype, $branchcode );
1047     my $loanlength = $sth->fetchrow_hashref;
1048     return $loanlength->{issuelength}
1049       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1050
1051     $sth->execute( $borrowertype, $itemtype, "" );
1052     $loanlength = $sth->fetchrow_hashref;
1053     return $loanlength->{issuelength}
1054       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1055
1056     $sth->execute( $borrowertype, "*", $branchcode );
1057     $loanlength = $sth->fetchrow_hashref;
1058     return $loanlength->{issuelength}
1059       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1060
1061     $sth->execute( "*", $itemtype, $branchcode );
1062     $loanlength = $sth->fetchrow_hashref;
1063     return $loanlength->{issuelength}
1064       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1065
1066     $sth->execute( $borrowertype, "*", "" );
1067     $loanlength = $sth->fetchrow_hashref;
1068     return $loanlength->{issuelength}
1069       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1070
1071     $sth->execute( "*", "*", $branchcode );
1072     $loanlength = $sth->fetchrow_hashref;
1073     return $loanlength->{issuelength}
1074       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1075
1076     $sth->execute( "*", $itemtype, "" );
1077     $loanlength = $sth->fetchrow_hashref;
1078     return $loanlength->{issuelength}
1079       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1080
1081     $sth->execute( "*", "*", "" );
1082     $loanlength = $sth->fetchrow_hashref;
1083     return $loanlength->{issuelength}
1084       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1085
1086     # if no rule is set => 21 days (hardcoded)
1087     return 21;
1088 }
1089
1090 =head2 AddReturn
1091
1092 ($doreturn, $messages, $iteminformation, $borrower) =
1093     &AddReturn($barcode, $branch);
1094
1095 Returns a book.
1096
1097 C<$barcode> is the bar code of the book being returned. C<$branch> is
1098 the code of the branch where the book is being returned.
1099
1100 C<&AddReturn> returns a list of four items:
1101
1102 C<$doreturn> is true iff the return succeeded.
1103
1104 C<$messages> is a reference-to-hash giving the reason for failure:
1105
1106 =over 4
1107
1108 =item C<BadBarcode>
1109
1110 No item with this barcode exists. The value is C<$barcode>.
1111
1112 =item C<NotIssued>
1113
1114 The book is not currently on loan. The value is C<$barcode>.
1115
1116 =item C<IsPermanent>
1117
1118 The book's home branch is a permanent collection. If you have borrowed
1119 this book, you are not allowed to return it. The value is the code for
1120 the book's home branch.
1121
1122 =item C<wthdrawn>
1123
1124 This book has been withdrawn/cancelled. The value should be ignored.
1125
1126 =item C<ResFound>
1127
1128 The item was reserved. The value is a reference-to-hash whose keys are
1129 fields from the reserves table of the Koha database, and
1130 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1131 either C<Waiting>, C<Reserved>, or 0.
1132
1133 =back
1134
1135 C<$borrower> is a reference-to-hash, giving information about the
1136 patron who last borrowed the book.
1137
1138 =cut
1139
1140 sub AddReturn {
1141     my ( $barcode, $branch ) = @_;
1142     my $dbh      = C4::Context->dbh;
1143     my $messages;
1144     my $doreturn = 1;
1145     my $borrower;
1146     my $validTransfert = 0;
1147     my $reserveDone = 0;
1148     
1149     # get information on item
1150     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1151     unless ($iteminformation->{'itemnumber'} ) {
1152         $messages->{'BadBarcode'} = $barcode;
1153         $doreturn = 0;
1154     } else {
1155         # find the borrower
1156         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1157             $messages->{'NotIssued'} = $barcode;
1158             $doreturn = 0;
1159         }
1160     
1161         # check if the book is in a permanent collection....
1162         my $hbr      = $iteminformation->{'homebranch'};
1163         my $branches = GetBranches();
1164         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1165             $messages->{'IsPermanent'} = $hbr;
1166         }
1167     
1168         # check that the book has been cancelled
1169         if ( $iteminformation->{'wthdrawn'} ) {
1170             $messages->{'wthdrawn'} = 1;
1171             $doreturn = 0;
1172         }
1173     
1174     #     new op dev : if the book returned in an other branch update the holding branch
1175     
1176     # update issues, thereby returning book (should push this out into another subroutine
1177         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1178     
1179     # case of a return of document (deal with issues and holdingbranch)
1180     
1181         if ($doreturn) {
1182             my $sth =
1183             $dbh->prepare(
1184     "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1185             );
1186             $sth->execute( $borrower->{'borrowernumber'},
1187                 $iteminformation->{'itemnumber'} );
1188             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?
1189         }
1190     
1191     # continue to deal with returns cases, but not only if we have an issue
1192     
1193     # the holdingbranch is updated if the document is returned in an other location .
1194     if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} )
1195             {
1196                     UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'});     
1197     #           reload iteminformation holdingbranch with the userenv value
1198                     $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1199             }
1200         ModDateLastSeen( $iteminformation->{'itemnumber'} );
1201         ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1202         
1203         # fix up the accounts.....
1204         if ( $iteminformation->{'itemlost'} ) {
1205             $messages->{'WasLost'} = 1;
1206         }
1207     
1208     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1209     #     check if we have a transfer for this document
1210         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1211     
1212     #     if we have a transfer to do, we update the line of transfers with the datearrived
1213         if ($datesent) {
1214             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1215                     my $sth =
1216                     $dbh->prepare(
1217                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1218                     );
1219                     $sth->execute( $iteminformation->{'itemnumber'} );
1220                     $sth->finish;
1221     #         now we check if there is a reservation with the validate of transfer if we have one, we can         set it with the status 'W'
1222             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1223             }
1224         else {
1225             $messages->{'WrongTransfer'} = $tobranch;
1226             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1227         }
1228         $validTransfert = 1;
1229         }
1230     
1231     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1232         # fix up the accounts.....
1233         if ($iteminformation->{'itemlost'}) {
1234                 FixAccountForLostAndReturned($iteminformation, $borrower);
1235                 $messages->{'WasLost'} = 1;
1236         }
1237         # fix up the overdues in accounts...
1238         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1239             $iteminformation->{'itemnumber'} );
1240     
1241     # find reserves.....
1242     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1243         my ( $resfound, $resrec ) =
1244         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1245         if ($resfound) {
1246             $resrec->{'ResFound'}   = $resfound;
1247             $messages->{'ResFound'} = $resrec;
1248             $reserveDone = 1;
1249         }
1250     
1251         # update stats?
1252         # Record the fact that this book was returned.
1253         UpdateStats(
1254             $branch, 'return', '0', '',
1255             $iteminformation->{'itemnumber'},
1256             $iteminformation->{'itemtype'},
1257             $borrower->{'borrowernumber'}
1258         );
1259         
1260         &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'}) 
1261             if C4::Context->preference("ReturnLog");
1262         
1263         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1264         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1265         
1266         if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1267                     if (C4::Context->preference("AutomaticItemReturn") == 1) {
1268                     ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1269                     $messages->{'WasTransfered'} = 1;
1270                     warn "was transfered";
1271                     }
1272         }
1273     }
1274     return ( $doreturn, $messages, $iteminformation, $borrower );
1275 }
1276
1277 =head2 FixOverduesOnReturn
1278
1279     &FixOverduesOnReturn($brn,$itm);
1280
1281 C<$brn> borrowernumber
1282
1283 C<$itm> itemnumber
1284
1285 internal function, called only by AddReturn
1286
1287 =cut
1288
1289 sub FixOverduesOnReturn {
1290     my ( $borrowernumber, $item ) = @_;
1291     my $dbh = C4::Context->dbh;
1292
1293     # check for overdue fine
1294     my $sth =
1295       $dbh->prepare(
1296 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1297       );
1298     $sth->execute( $borrowernumber, $item );
1299
1300     # alter fine to show that the book has been returned
1301     if ( my $data = $sth->fetchrow_hashref ) {
1302         my $usth =
1303           $dbh->prepare(
1304 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1305           );
1306         $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1307         $usth->finish();
1308     }
1309     $sth->finish();
1310     return;
1311 }
1312
1313 =head2 FixAccountForLostAndReturned
1314
1315         &FixAccountForLostAndReturned($iteminfo,$borrower);
1316
1317 Calculates the charge for a book lost and returned (Not exported & used only once)
1318
1319 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1320
1321 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1322
1323 Internal function, called by AddReturn
1324
1325 =cut
1326
1327 sub FixAccountForLostAndReturned {
1328         my ($iteminfo, $borrower) = @_;
1329         my %env;
1330         my $dbh = C4::Context->dbh;
1331         my $itm = $iteminfo->{'itemnumber'};
1332         # check for charge made for lost book
1333         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1334         $sth->execute($itm);
1335         if (my $data = $sth->fetchrow_hashref) {
1336         # writeoff this amount
1337                 my $offset;
1338                 my $amount = $data->{'amount'};
1339                 my $acctno = $data->{'accountno'};
1340                 my $amountleft;
1341                 if ($data->{'amountoutstanding'} == $amount) {
1342                 $offset = $data->{'amount'};
1343                 $amountleft = 0;
1344                 } else {
1345                 $offset = $amount - $data->{'amountoutstanding'};
1346                 $amountleft = $data->{'amountoutstanding'} - $amount;
1347                 }
1348                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1349                         WHERE (borrowernumber = ?)
1350                         AND (itemnumber = ?) AND (accountno = ?) ");
1351                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1352                 $usth->finish;
1353         #check if any credit is left if so writeoff other accounts
1354                 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1355                 if ($amountleft < 0){
1356                 $amountleft*=-1;
1357                 }
1358                 if ($amountleft > 0){
1359                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1360                                                         AND (amountoutstanding >0) ORDER BY date");
1361                 $msth->execute($data->{'borrowernumber'});
1362         # offset transactions
1363                 my $newamtos;
1364                 my $accdata;
1365                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1366                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1367                         $newamtos = 0;
1368                         $amountleft -= $accdata->{'amountoutstanding'};
1369                         }  else {
1370                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1371                         $amountleft = 0;
1372                         }
1373                         my $thisacct = $accdata->{'accountno'};
1374                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1375                                         WHERE (borrowernumber = ?)
1376                                         AND (accountno=?)");
1377                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1378                         $usth->finish;
1379                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1380                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1381                                 VALUES
1382                                 (?,?,?,?)");
1383                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1384                         $usth->finish;
1385                 }
1386                 $msth->finish;
1387                 }
1388                 if ($amountleft > 0){
1389                         $amountleft*=-1;
1390                 }
1391                 my $desc="Book Returned ".$iteminfo->{'barcode'};
1392                 $usth = $dbh->prepare("INSERT INTO accountlines
1393                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1394                         VALUES (?,?,now(),?,?,'CR',?)");
1395                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1396                 $usth->finish;
1397                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1398                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1399                         VALUES (?,?,?,?)");
1400                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1401                 $usth->finish;
1402                 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1403                 $usth->execute($itm);
1404                 $usth->finish;
1405         }
1406         $sth->finish;
1407         return;
1408 }
1409
1410 =head2 GetItemIssue
1411
1412 $issues = &GetItemIssue($itemnumber);
1413
1414 Returns patrons currently having a book. nothing if item is not issued atm
1415
1416 C<$itemnumber> is the itemnumber
1417
1418 Returns an array of hashes
1419 =cut
1420
1421 sub GetItemIssue {
1422     my ( $itemnumber) = @_;
1423     return unless $itemnumber;
1424     my $dbh = C4::Context->dbh;
1425     my @GetItemIssues;
1426     
1427     # get today date
1428     my $today = POSIX::strftime("%Y%m%d", localtime);
1429
1430     my $sth = $dbh->prepare(
1431         "SELECT * FROM issues 
1432         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1433     WHERE
1434     issues.itemnumber=?  AND returndate IS NULL ");
1435     $sth->execute($itemnumber);
1436     my $data = $sth->fetchrow_hashref;
1437     my $datedue = $data->{'date_due'};
1438     $datedue =~ s/-//g;
1439     if ( $datedue < $today ) {
1440         $data->{'overdue'} = 1;
1441     }
1442     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1443     $sth->finish;
1444     return ($data);
1445 }
1446
1447 =head2 GetItemIssues
1448
1449 $issues = &GetItemIssues($itemnumber, $history);
1450
1451 Returns patrons that have issued a book
1452
1453 C<$itemnumber> is the itemnumber
1454 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1455
1456 Returns an array of hashes
1457 =cut
1458
1459 sub GetItemIssues {
1460     my ( $itemnumber,$history ) = @_;
1461     my $dbh = C4::Context->dbh;
1462     my @GetItemIssues;
1463     
1464     # get today date
1465     my $today = POSIX::strftime("%Y%m%d", localtime);
1466
1467     my $sth = $dbh->prepare(
1468         "SELECT * FROM issues 
1469         LEFT JOIN borrowers ON borrowers.borrowernumber 
1470         LEFT JOIN items ON items.itemnumber=issues.itemnumber 
1471     WHERE
1472     issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1473     "ORDER BY issues.date_due DESC"
1474     );
1475     $sth->execute($itemnumber);
1476     while ( my $data = $sth->fetchrow_hashref ) {
1477         my $datedue = $data->{'date_due'};
1478         $datedue =~ s/-//g;
1479         if ( $datedue < $today ) {
1480             $data->{'overdue'} = 1;
1481         }
1482         my $itemnumber = $data->{'itemnumber'};
1483         push @GetItemIssues, $data;
1484     }
1485     $sth->finish;
1486     return ( \@GetItemIssues );
1487 }
1488
1489 =head2 GetBiblioIssues
1490
1491 $issues = GetBiblioIssues($biblionumber);
1492
1493 this function get all issues from a biblionumber.
1494
1495 Return:
1496 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1497 tables issues and the firstname,surname & cardnumber from borrowers.
1498
1499 =cut
1500
1501 sub GetBiblioIssues {
1502     my $biblionumber = shift;
1503     return undef unless $biblionumber;
1504     my $dbh   = C4::Context->dbh;
1505     my $query = "
1506         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1507         FROM issues
1508             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1509             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1510             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1511             LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1512         WHERE biblio.biblionumber = ?
1513         ORDER BY issues.timestamp
1514     ";
1515     my $sth = $dbh->prepare($query);
1516     $sth->execute($biblionumber);
1517
1518     my @issues;
1519     while ( my $data = $sth->fetchrow_hashref ) {
1520         push @issues, $data;
1521     }
1522     return \@issues;
1523 }
1524
1525 =head2 CanBookBeRenewed
1526
1527 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1528
1529 Find out whether a borrowed item may be renewed.
1530
1531 C<$dbh> is a DBI handle to the Koha database.
1532
1533 C<$borrowernumber> is the borrower number of the patron who currently
1534 has the item on loan.
1535
1536 C<$itemnumber> is the number of the item to renew.
1537
1538 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1539 item must currently be on loan to the specified borrower; renewals
1540 must be allowed for the item's type; and the borrower must not have
1541 already renewed the loan.
1542
1543 =cut
1544
1545 sub CanBookBeRenewed {
1546
1547     # check renewal status
1548     my ( $borrowernumber, $itemnumber ) = @_;
1549     my $dbh       = C4::Context->dbh;
1550     my $renews    = 1;
1551     my $renewokay = 0;
1552
1553     # Look in the issues table for this item, lent to this borrower,
1554     # and not yet returned.
1555
1556     # FIXME - I think this function could be redone to use only one SQL call.
1557     my $sth1 = $dbh->prepare(
1558         "SELECT * FROM issues
1559             WHERE borrowernumber = ?
1560             AND itemnumber = ?
1561             AND returndate IS NULL"
1562     );
1563     $sth1->execute( $borrowernumber, $itemnumber );
1564     if ( my $data1 = $sth1->fetchrow_hashref ) {
1565
1566         # Found a matching item
1567
1568         # See if this item may be renewed. This query is convoluted
1569         # because it's a bit messy: given the item number, we need to find
1570         # the biblioitem, which gives us the itemtype, which tells us
1571         # whether it may be renewed.
1572         my $sth2 = $dbh->prepare(
1573             "SELECT renewalsallowed FROM items
1574                 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1575                 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1576                 WHERE items.itemnumber = ?
1577                 "
1578         );
1579         $sth2->execute($itemnumber);
1580         if ( my $data2 = $sth2->fetchrow_hashref ) {
1581             $renews = $data2->{'renewalsallowed'};
1582         }
1583         if ( $renews && $renews >= $data1->{'renewals'} ) {
1584             $renewokay = 1;
1585         }
1586         $sth2->finish;
1587         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1588         if ($resfound) {
1589             $renewokay = 0;
1590         }
1591
1592     }
1593     $sth1->finish;
1594     return ($renewokay);
1595 }
1596
1597 =head2 AddRenewal
1598
1599 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1600
1601 Renews a loan.
1602
1603 C<$borrowernumber> is the borrower number of the patron who currently
1604 has the item.
1605
1606 C<$itemnumber> is the number of the item to renew.
1607
1608 C<$datedue> can be used to set the due date. If C<$datedue> is the
1609 empty string, C<&AddRenewal> will calculate the due date automatically
1610 from the book's item type. If you wish to set the due date manually,
1611 C<$datedue> should be in the form YYYY-MM-DD.
1612
1613 =cut
1614
1615 sub AddRenewal {
1616
1617     my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1618     my $dbh = C4::Context->dbh;
1619
1620     # If the due date wasn't specified, calculate it by adding the
1621     # book's loan length to today's date.
1622     if ( $datedue eq "" ) {
1623
1624         my $biblio = GetBiblioFromItemNumber($itemnumber);
1625         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1626         my $loanlength = GetLoanLength(
1627             $borrower->{'categorycode'},
1628              (C4::Context->preference('item-level_itypes')) ? $biblio->{'ccode'} : $biblio->{'itemtype'} ,
1629                         $borrower->{'branchcode'}
1630         );
1631                 #FIXME --  choose issuer or borrower branch.
1632                 #FIXME -- where's the calendar ?
1633         my ( $due_year, $due_month, $due_day ) =
1634           Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1635         $datedue = "$due_year-$due_month-$due_day";
1636         $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1637     }
1638
1639     # Find the issues record for this book
1640     my $sth =
1641       $dbh->prepare("SELECT * FROM issues
1642                         WHERE borrowernumber=? 
1643                         AND itemnumber=? 
1644                         AND returndate IS NULL"
1645       );
1646     $sth->execute( $borrowernumber, $itemnumber );
1647     my $issuedata = $sth->fetchrow_hashref;
1648     $sth->finish;
1649
1650     # Update the issues record to have the new due date, and a new count
1651     # of how many times it has been renewed.
1652     my $renews = $issuedata->{'renewals'} + 1;
1653     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1654                             WHERE borrowernumber=? 
1655                             AND itemnumber=? 
1656                             AND returndate IS NULL"
1657     );
1658     $sth->execute( $datedue, $renews, $borrowernumber, $itemnumber );
1659     $sth->finish;
1660
1661     # Log the renewal
1662     UpdateStats( C4::Context->userenv->{'branchcode'}, 'renew', '', '', $itemnumber );
1663
1664     # Charge a new rental fee, if applicable?
1665     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1666     if ( $charge > 0 ) {
1667         my $accountno = getnextacctno( $borrowernumber );
1668         my $item = GetBiblioFromItemNumber($itemnumber);
1669         $sth = $dbh->prepare(
1670                 "INSERT INTO accountlines
1671                     (borrowernumber,accountno,date,amount,
1672                         description,accounttype,amountoutstanding,
1673                     itemnumber)
1674                     VALUES (?,?,now(),?,?,?,?,?)"
1675         );
1676         $sth->execute( $borrowernumber, $accountno, $charge,
1677             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1678             'Rent', $charge, $itemnumber );
1679         $sth->finish;
1680     }
1681 }
1682
1683 =head2 GetIssuingCharges
1684
1685 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1686
1687 Calculate how much it would cost for a given patron to borrow a given
1688 item, including any applicable discounts.
1689
1690 C<$itemnumber> is the item number of item the patron wishes to borrow.
1691
1692 C<$borrowernumber> is the patron's borrower number.
1693
1694 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1695 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1696 if it's a video).
1697
1698 =cut
1699
1700 sub GetIssuingCharges {
1701
1702     # calculate charges due
1703     my ( $itemnumber, $borrowernumber ) = @_;
1704     my $charge = 0;
1705     my $dbh    = C4::Context->dbh;
1706     my $item_type;
1707
1708     # Get the book's item type and rental charge (via its biblioitem).
1709     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
1710             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1711         $qcharge .= (C4::Context->preference('item-level_itypes'))
1712                 ? " LEFT JOIN itemtypes ON items.ccode = itemtypes.itemtype "
1713                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1714         
1715     $qcharge .=      "WHERE items.itemnumber =?";
1716    
1717 warn $qcharge;
1718     my $sth1 = $dbh->prepare($qcharge);
1719     $sth1->execute($itemnumber);
1720     if ( my $data1 = $sth1->fetchrow_hashref ) {
1721         $item_type = $data1->{'itemtype'};
1722         $charge    = $data1->{'rentalcharge'};
1723         my $q2 = "SELECT rentaldiscount FROM borrowers
1724             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1725             WHERE borrowers.borrowernumber = ?
1726             AND issuingrules.itemtype = ?";
1727         my $sth2 = $dbh->prepare($q2);
1728         $sth2->execute( $borrowernumber, $item_type );
1729         if ( my $data2 = $sth2->fetchrow_hashref ) {
1730             my $discount = $data2->{'rentaldiscount'};
1731             if ( $discount eq 'NULL' ) {
1732                 $discount = 0;
1733             }
1734             $charge = ( $charge * ( 100 - $discount ) ) / 100;
1735         }
1736         $sth2->finish;
1737     }
1738
1739     $sth1->finish;
1740     return ( $charge, $item_type );
1741 }
1742
1743 =head2 AddIssuingCharge
1744
1745 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1746
1747 =cut
1748
1749 sub AddIssuingCharge {
1750     my ( $itemnumber, $borrowernumber, $charge ) = @_;
1751     my $dbh = C4::Context->dbh;
1752     my $nextaccntno = getnextacctno( $borrowernumber );
1753     my $query ="
1754         INSERT INTO accountlines
1755             (borrowernumber, itemnumber, accountno,
1756             date, amount, description, accounttype,
1757             amountoutstanding)
1758         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1759     ";
1760     my $sth = $dbh->prepare($query);
1761     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1762     $sth->finish;
1763 }
1764
1765 =head2 GetTransfers
1766
1767 GetTransfers($itemnumber);
1768
1769 =cut
1770
1771 sub GetTransfers {
1772     my ($itemnumber) = @_;
1773
1774     my $dbh = C4::Context->dbh;
1775
1776     my $query = '
1777         SELECT datesent,
1778                frombranch,
1779                tobranch
1780         FROM branchtransfers
1781         WHERE itemnumber = ?
1782           AND datearrived IS NULL
1783         ';
1784     my $sth = $dbh->prepare($query);
1785     $sth->execute($itemnumber);
1786     my @row = $sth->fetchrow_array();
1787     $sth->finish;
1788     return @row;
1789 }
1790
1791
1792 =head2 GetTransfersFromTo
1793
1794 @results = GetTransfersFromTo($frombranch,$tobranch);
1795
1796 Returns the list of pending transfers between $from and $to branch
1797
1798 =cut
1799
1800 sub GetTransfersFromTo {
1801     my ( $frombranch, $tobranch ) = @_;
1802     return unless ( $frombranch && $tobranch );
1803     my $dbh   = C4::Context->dbh;
1804     my $query = "
1805         SELECT itemnumber,datesent,frombranch
1806         FROM   branchtransfers
1807         WHERE  frombranch=?
1808           AND  tobranch=?
1809           AND datearrived IS NULL
1810     ";
1811     my $sth = $dbh->prepare($query);
1812     $sth->execute( $frombranch, $tobranch );
1813     my @gettransfers;
1814
1815     while ( my $data = $sth->fetchrow_hashref ) {
1816         push @gettransfers, $data;
1817     }
1818     $sth->finish;
1819     return (@gettransfers);
1820 }
1821
1822 =head2 DeleteTransfer
1823
1824 &DeleteTransfer($itemnumber);
1825
1826 =cut
1827
1828 sub DeleteTransfer {
1829     my ($itemnumber) = @_;
1830     my $dbh          = C4::Context->dbh;
1831     my $sth          = $dbh->prepare(
1832         "DELETE FROM branchtransfers
1833          WHERE itemnumber=?
1834          AND datearrived IS NULL "
1835     );
1836     $sth->execute($itemnumber);
1837     $sth->finish;
1838 }
1839
1840 =head2 AnonymiseIssueHistory
1841
1842 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1843
1844 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1845 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1846
1847 return the number of affected rows.
1848
1849 =cut
1850
1851 sub AnonymiseIssueHistory {
1852     my $date           = shift;
1853     my $borrowernumber = shift;
1854     my $dbh            = C4::Context->dbh;
1855     my $query          = "
1856         UPDATE issues
1857         SET    borrowernumber = NULL
1858         WHERE  returndate < '".$date."'
1859           AND borrowernumber IS NOT NULL
1860     ";
1861     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1862     my $rows_affected = $dbh->do($query);
1863     return $rows_affected;
1864 }
1865
1866 =head2 updateWrongTransfer
1867
1868 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1869
1870 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 
1871
1872 =cut
1873
1874 sub updateWrongTransfer {
1875         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1876         my $dbh = C4::Context->dbh;     
1877 # first step validate the actual line of transfert .
1878         my $sth =
1879                 $dbh->prepare(
1880                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1881                 );
1882                 $sth->execute($FromLibrary,$itemNumber);
1883                 $sth->finish;
1884
1885 # second step create a new line of branchtransfer to the right location .
1886         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1887
1888 #third step changing holdingbranch of item
1889         UpdateHoldingbranch($FromLibrary,$itemNumber);
1890 }
1891
1892 =head2 UpdateHoldingbranch
1893
1894 $items = UpdateHoldingbranch($branch,$itmenumber);
1895 Simple methode for updating hodlingbranch in items BDD line
1896 =cut
1897
1898 sub UpdateHoldingbranch {
1899         my ( $branch,$itmenumber ) = @_;
1900         my $dbh = C4::Context->dbh;     
1901 # first step validate the actual line of transfert .
1902         my $sth =
1903                 $dbh->prepare(
1904                         "update items set holdingbranch = ? where itemnumber= ?"
1905                 );
1906                 $sth->execute($branch,$itmenumber);
1907                 $sth->finish;
1908         
1909         
1910 }
1911 =head2 CheckValidDatedue
1912
1913 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1914 this function return a new date due after checked if it's a repeatable or special holiday
1915 C<$date_due>   = returndate calculate with no day check
1916 C<$itemnumber>  = itemnumber
1917 C<$branchcode>  = localisation of issue 
1918 =cut
1919 sub CheckValidDatedue{
1920 my ($date_due,$itemnumber,$branchcode)=@_;
1921 my @datedue=split('-',$date_due);
1922 my $years=$datedue[0];
1923 my $month=$datedue[1];
1924 my $day=$datedue[2];
1925 my $dow;
1926 for (my $i=0;$i<2;$i++){
1927         $dow=Day_of_Week($years,$month,$day);
1928         ($dow=0) if ($dow>6);
1929         my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1930         my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1931         my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1932                 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1933                 $i=0;
1934                 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1935                 }
1936         }
1937 my $newdatedue=$years."-".$month."-".$day;
1938 return $newdatedue;
1939 }
1940 =head2 CheckRepeatableHolidays
1941
1942 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1943 this function check if the date due is a repeatable holiday
1944 C<$date_due>   = returndate calculate with no day check
1945 C<$itemnumber>  = itemnumber
1946 C<$branchcode>  = localisation of issue 
1947
1948 =cut
1949
1950 sub CheckRepeatableHolidays{
1951 my($itemnumber,$week_day,$branchcode)=@_;
1952 my $dbh = C4::Context->dbh;
1953 my $query = qq|SELECT count(*)  
1954         FROM repeatable_holidays 
1955         WHERE branchcode=?
1956         AND weekday=?|;
1957 my $sth = $dbh->prepare($query);
1958 $sth->execute($branchcode,$week_day);
1959 my $result=$sth->fetchrow;
1960 $sth->finish;
1961 return $result;
1962 }
1963
1964
1965 =head2 CheckSpecialHolidays
1966
1967 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1968 this function check if the date is a special holiday
1969 C<$years>   = the years of datedue
1970 C<$month>   = the month of datedue
1971 C<$day>     = the day of datedue
1972 C<$itemnumber>  = itemnumber
1973 C<$branchcode>  = localisation of issue 
1974 =cut
1975 sub CheckSpecialHolidays{
1976 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
1977 my $dbh = C4::Context->dbh;
1978 my $query=qq|SELECT count(*) 
1979              FROM `special_holidays`
1980              WHERE year=?
1981              AND month=?
1982              AND day=?
1983              AND branchcode=?
1984             |;
1985 my $sth = $dbh->prepare($query);
1986 $sth->execute($years,$month,$day,$branchcode);
1987 my $countspecial=$sth->fetchrow ;
1988 $sth->finish;
1989 return $countspecial;
1990 }
1991
1992 =head2 CheckRepeatableSpecialHolidays
1993
1994 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1995 this function check if the date is a repeatble special holidays
1996 C<$month>   = the month of datedue
1997 C<$day>     = the day of datedue
1998 C<$itemnumber>  = itemnumber
1999 C<$branchcode>  = localisation of issue 
2000 =cut
2001 sub CheckRepeatableSpecialHolidays{
2002 my ($month,$day,$itemnumber,$branchcode) = @_;
2003 my $dbh = C4::Context->dbh;
2004 my $query=qq|SELECT count(*) 
2005              FROM `repeatable_holidays`
2006              WHERE month=?
2007              AND day=?
2008              AND branchcode=?
2009             |;
2010 my $sth = $dbh->prepare($query);
2011 $sth->execute($month,$day,$branchcode);
2012 my $countspecial=$sth->fetchrow ;
2013 $sth->finish;
2014 return $countspecial;
2015 }
2016
2017
2018
2019 sub CheckValidBarcode{
2020 my ($barcode) = @_;
2021 my $dbh = C4::Context->dbh;
2022 my $query=qq|SELECT count(*) 
2023              FROM items 
2024              WHERE barcode=?
2025             |;
2026 my $sth = $dbh->prepare($query);
2027 $sth->execute($barcode);
2028 my $exist=$sth->fetchrow ;
2029 $sth->finish;
2030 return $exist;
2031 }
2032
2033 1;
2034
2035 __END__
2036
2037 =head1 AUTHOR
2038
2039 Koha Developement team <info@koha.org>
2040
2041 =cut
2042