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