IMPORTANT: BUGFIXING STATUSES
[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::Dates;
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                 my $datedue; 
846                 
847                 # get actual issuing if there is one
848                 my $actualissue = GetItemIssue( $item->{itemnumber});
849                 
850                 # get biblioinformation for this item
851                 my $biblio = GetBiblioFromItemNumber($item->{itemnumber});
852                 
853                 #
854                 # check if we just renew the issue.
855                 #
856                 if ( $actualissue->{borrowernumber} eq $borrower->{'borrowernumber'} ) {
857                         AddRenewal(
858                                 $borrower->{'borrowernumber'},
859                                 $item->{'itemnumber'},
860                                 C4::Context->userenv->{'branch'},
861                                 $date
862                         );
863
864                 }
865                 else {
866         # it's NOT a renewal
867         if ( $actualissue->{borrowernumber}) {
868             # This book is currently on loan, but not to the person
869             # who wants to borrow it now. mark it returned before issuing to the new borrower
870             AddReturn(
871                 $item->{'barcode'},
872                 C4::Context->userenv->{'branch'}
873             );
874         }
875
876         # See if the item is on reserve.
877         my ( $restype, $res ) =
878           C4::Reserves::CheckReserves( $item->{'itemnumber'} );
879         if ($restype) {
880             my $resbor = $res->{'borrowernumber'};
881             if ( $resbor eq $borrower->{'borrowernumber'} ) {
882
883                 # The item is reserved by the current patron
884                 ModReserveFill($res);
885             }
886             elsif ( $restype eq "Waiting" ) {
887
888                 # warn "Waiting";
889                 # The item is on reserve and waiting, but has been
890                 # reserved by some other patron.
891                 my ( $resborrower, $flags ) = GetMemberDetails( $resbor, 0 );
892                 my $branches   = GetBranches();
893                 my $branchname =
894                   $branches->{ $res->{'branchcode'} }->{'branchname'};
895             }
896             elsif ( $restype eq "Reserved" ) {
897
898                 # warn "Reserved";
899                 # The item is reserved by someone else.
900                 my ( $resborrower, $flags ) =
901                   GetMemberDetails( $resbor, 0 );
902                 my $branches   = GetBranches();
903                 my $branchname =
904                   $branches->{ $res->{'branchcode'} }->{'branchname'};
905                 if ($cancelreserve) { # cancel reserves on this item
906                     CancelReserve( 0, $res->{'itemnumber'},
907                         $res->{'borrowernumber'} );
908                 }
909             }
910             if ($cancelreserve) {
911                 CancelReserve( $res->{'biblionumber'}, 0,
912                     $res->{'borrowernumber'} );
913             }
914             else {
915     # set waiting reserve to first in reserve queue as book isn't waiting now
916                 ModReserve(
917                     1,
918                     $res->{'biblionumber'},
919                     $res->{'borrowernumber'},
920                     $res->{'branchcode'}
921                 );
922             }
923         }
924
925         # Starting process for transfer job (checking transfert and validate it if we have one)
926             my ($datesent) = GetTransfers($item->{'itemnumber'});
927             if ($datesent) {
928         #       updating line of branchtranfert to finish it, and changing the to branch value, implement a comment for lisibility of this case (maybe for stats ....)
929             my $sth =
930                     $dbh->prepare(
931                     "UPDATE branchtransfers 
932                         SET datearrived = now(),
933                         tobranch = ?,
934                         comments = 'Forced branchtransfert'
935                     WHERE itemnumber= ? AND datearrived IS NULL"
936                     );
937                     $sth->execute(C4::Context->userenv->{'branch'},$item->{'itemnumber'});
938                     $sth->finish;
939             }
940
941         # Record in the database the fact that the book was issued.
942         my $sth =
943           $dbh->prepare(
944                 "INSERT INTO issues 
945                     (borrowernumber, itemnumber,issuedate, date_due, branchcode)
946                 VALUES (?,?,?,?,?)"
947           );
948                 my $dateduef;
949         if ($date) {
950             $dateduef = $date;
951         } else {
952                         my $itype=(C4::Context->preference('item-level_itypes')) ?  $biblio->{'itype'} : $biblio->{'itemtype'} ;
953                 my $loanlength = GetLoanLength(
954                     $borrower->{'categorycode'},
955                     $itype,
956                     $borrower->{'branchcode'}
957                 );
958                 $datedue  = time + ($loanlength) * 86400;
959                 my @datearr  = localtime($datedue);
960                         $dateduef = C4::Dates->new( sprintf("%04d-%02d-%02d", 1900 + $datearr[5], $datearr[4] + 1, $datearr[3]), 'iso');
961                         $dateduef=CheckValidDatedue($dateduef,$item->{'itemnumber'},C4::Context->userenv->{'branch'});
962                 
963                 # if ReturnBeforeExpiry ON the datedue can't be after borrower expirydate
964                 if ( C4::Context->preference('ReturnBeforeExpiry') && $dateduef->output('iso') gt $borrower->{dateexpiry} ) {
965                     $dateduef = C4::Dates->new($borrower->{dateexpiry},'iso');
966                 }
967         };
968                 $sth->execute(
969             $borrower->{'borrowernumber'},
970             $item->{'itemnumber'},
971             strftime( "%Y-%m-%d", localtime ),$dateduef->output('iso'), C4::Context->userenv->{'branch'}
972         );
973         $sth->finish;
974         $item->{'issues'}++;
975         $sth =
976           $dbh->prepare(
977             "UPDATE items SET issues=?, holdingbranch=?, itemlost=0, datelastborrowed  = now(), onloan = ? WHERE itemnumber=?");
978         $sth->execute(
979             $item->{'issues'},
980             C4::Context->userenv->{'branch'},
981                         $dateduef->output('iso'),
982             $item->{'itemnumber'}
983         );
984         $sth->finish;
985         &ModDateLastSeen( $item->{'itemnumber'} );
986         my $record = GetMarcItem( $item->{'biblionumber'}, $item->{'itemnumber'} );
987         my $frameworkcode = GetFrameworkCode( $item->{'biblionumber'} );                                                                                         
988         ModItemInMarc( $record, $item->{'biblionumber'}, $item->{'itemnumber'}, $frameworkcode );
989         # If it costs to borrow this book, charge it to the patron's account.
990         my ( $charge, $itemtype ) = GetIssuingCharges(
991             $item->{'itemnumber'},
992             $borrower->{'borrowernumber'}
993         );
994         if ( $charge > 0 ) {
995             AddIssuingCharge(
996                 $item->{'itemnumber'},
997                 $borrower->{'borrowernumber'}, $charge
998             );
999             $item->{'charge'} = $charge;
1000         }
1001
1002         # Record the fact that this book was issued.
1003         &UpdateStats(
1004             C4::Context->userenv->{'branch'},
1005             'issue',                        $charge,
1006             '',                             $item->{'itemnumber'},
1007             $item->{'itemtype'}, $borrower->{'borrowernumber'}
1008         );
1009     }
1010     
1011     &logaction(C4::Context->userenv->{'number'},"CIRCULATION","ISSUE",$borrower->{'borrowernumber'},$biblio->{'biblionumber'}) 
1012         if C4::Context->preference("IssueLog");
1013     return ($datedue);
1014   }  
1015 }
1016
1017 =head2 GetLoanLength
1018
1019 Get loan length for an itemtype, a borrower type and a branch
1020
1021 my $loanlength = &GetLoanLength($borrowertype,$itemtype,branchcode)
1022
1023 =cut
1024
1025 sub GetLoanLength {
1026     my ( $borrowertype, $itemtype, $branchcode ) = @_;
1027     my $dbh = C4::Context->dbh;
1028     my $sth =
1029       $dbh->prepare(
1030 "select issuelength from issuingrules where categorycode=? and itemtype=? and branchcode=? and issuelength is not null"
1031       );
1032
1033 # try to find issuelength & return the 1st available.
1034 # check with borrowertype, itemtype and branchcode, then without one of those parameters
1035     $sth->execute( $borrowertype, $itemtype, $branchcode );
1036     my $loanlength = $sth->fetchrow_hashref;
1037     return $loanlength->{issuelength}
1038       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1039
1040     $sth->execute( $borrowertype, $itemtype, "*" );
1041     $loanlength = $sth->fetchrow_hashref;
1042     return $loanlength->{issuelength}
1043       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1044
1045     $sth->execute( $borrowertype, "*", $branchcode );
1046     $loanlength = $sth->fetchrow_hashref;
1047     return $loanlength->{issuelength}
1048       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1049
1050     $sth->execute( "*", $itemtype, $branchcode );
1051     $loanlength = $sth->fetchrow_hashref;
1052     return $loanlength->{issuelength}
1053       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1054
1055     $sth->execute( $borrowertype, "*", "*" );
1056     $loanlength = $sth->fetchrow_hashref;
1057     return $loanlength->{issuelength}
1058       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1059
1060     $sth->execute( "*", "*", $branchcode );
1061     $loanlength = $sth->fetchrow_hashref;
1062     return $loanlength->{issuelength}
1063       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1064
1065     $sth->execute( "*", $itemtype, "*" );
1066     $loanlength = $sth->fetchrow_hashref;
1067     return $loanlength->{issuelength}
1068       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1069
1070     $sth->execute( "*", "*", "*" );
1071     $loanlength = $sth->fetchrow_hashref;
1072     return $loanlength->{issuelength}
1073       if defined($loanlength) && $loanlength->{issuelength} ne 'NULL';
1074
1075     # if no rule is set => 21 days (hardcoded)
1076     return 21;
1077 }
1078
1079 =head2 AddReturn
1080
1081 ($doreturn, $messages, $iteminformation, $borrower) =
1082     &AddReturn($barcode, $branch);
1083
1084 Returns a book.
1085
1086 C<$barcode> is the bar code of the book being returned. C<$branch> is
1087 the code of the branch where the book is being returned.
1088
1089 C<&AddReturn> returns a list of four items:
1090
1091 C<$doreturn> is true iff the return succeeded.
1092
1093 C<$messages> is a reference-to-hash giving the reason for failure:
1094
1095 =over 4
1096
1097 =item C<BadBarcode>
1098
1099 No item with this barcode exists. The value is C<$barcode>.
1100
1101 =item C<NotIssued>
1102
1103 The book is not currently on loan. The value is C<$barcode>.
1104
1105 =item C<IsPermanent>
1106
1107 The book's home branch is a permanent collection. If you have borrowed
1108 this book, you are not allowed to return it. The value is the code for
1109 the book's home branch.
1110
1111 =item C<wthdrawn>
1112
1113 This book has been withdrawn/cancelled. The value should be ignored.
1114
1115 =item C<ResFound>
1116
1117 The item was reserved. The value is a reference-to-hash whose keys are
1118 fields from the reserves table of the Koha database, and
1119 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
1120 either C<Waiting>, C<Reserved>, or 0.
1121
1122 =back
1123
1124 C<$borrower> is a reference-to-hash, giving information about the
1125 patron who last borrowed the book.
1126
1127 =cut
1128
1129 sub AddReturn {
1130     my ( $barcode, $branch ) = @_;
1131     my $dbh      = C4::Context->dbh;
1132     my $messages;
1133     my $doreturn = 1;
1134     my $borrower;
1135     my $validTransfert = 0;
1136     my $reserveDone = 0;
1137     
1138     # get information on item
1139     my $iteminformation = GetItemIssue( GetItemnumberFromBarcode($barcode));
1140     my $biblio = GetBiblioFromItemNumber($iteminformation->{'itemnumber'});
1141     unless ($iteminformation->{'itemnumber'} ) {
1142         $messages->{'BadBarcode'} = $barcode;
1143         $doreturn = 0;
1144     } else {
1145         # find the borrower
1146         if ( ( not $iteminformation->{borrowernumber} ) && $doreturn ) {
1147             $messages->{'NotIssued'} = $barcode;
1148             $doreturn = 0;
1149         }
1150     
1151         # check if the book is in a permanent collection....
1152         my $hbr      = $iteminformation->{'homebranch'};
1153         my $branches = GetBranches();
1154         if ( $hbr && $branches->{$hbr}->{'PE'} ) {
1155             $messages->{'IsPermanent'} = $hbr;
1156         }
1157     
1158         # check that the book has been cancelled
1159         if ( $iteminformation->{'wthdrawn'} ) {
1160             $messages->{'wthdrawn'} = 1;
1161             $doreturn = 0;
1162         }
1163     
1164     #     new op dev : if the book returned in an other branch update the holding branch
1165     
1166     # update issues, thereby returning book (should push this out into another subroutine
1167         $borrower = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1168     
1169     # case of a return of document (deal with issues and holdingbranch)
1170     
1171         if ($doreturn) {
1172             my $sth =
1173             $dbh->prepare(
1174     "UPDATE issues SET returndate = now() WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (returndate IS NULL)"
1175             );
1176             $sth->execute( $borrower->{'borrowernumber'},
1177                 $iteminformation->{'itemnumber'} );
1178             $messages->{'WasReturned'} = 1;    # FIXME is the "= 1" right?
1179         }
1180     
1181     # continue to deal with returns cases, but not only if we have an issue
1182     
1183     # the holdingbranch is updated if the document is returned in an other location .
1184     if ( $iteminformation->{'holdingbranch'} ne C4::Context->userenv->{'branch'} ) {
1185                 UpdateHoldingbranch(C4::Context->userenv->{'branch'},$iteminformation->{'itemnumber'}); 
1186                 #               reload iteminformation holdingbranch with the userenv value
1187                 $iteminformation->{'holdingbranch'} = C4::Context->userenv->{'branch'};
1188         }
1189         ModDateLastSeen( $iteminformation->{'itemnumber'} );
1190                 my $sth = $dbh->prepare("UPDATE items SET onloan = NULL where itemnumber = ?");
1191                 $sth->execute($iteminformation->{'itemnumber'});
1192                 $sth->finish();
1193                 my $record = GetMarcItem( $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'} );
1194                 my $frameworkcode = GetFrameworkCode( $biblio->{'biblionumber'} );
1195                 ModItemInMarc( $record, $biblio->{'biblionumber'}, $iteminformation->{'itemnumber'}, $frameworkcode );
1196                 
1197                 if ($iteminformation->{borrowernumber}){
1198                         ($borrower) = C4::Members::GetMemberDetails( $iteminformation->{borrowernumber}, 0 );
1199                 }       
1200         # fix up the accounts.....
1201         if ( $iteminformation->{'itemlost'} ) {
1202             $messages->{'WasLost'} = 1;
1203         }
1204     
1205     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
1206     #     check if we have a transfer for this document
1207         my ($datesent,$frombranch,$tobranch) = GetTransfers( $iteminformation->{'itemnumber'} );
1208     
1209     #     if we have a transfer to do, we update the line of transfers with the datearrived
1210         if ($datesent) {
1211             if ( $tobranch eq C4::Context->userenv->{'branch'} ) {
1212                     my $sth =
1213                     $dbh->prepare(
1214                             "UPDATE branchtransfers SET datearrived = now() WHERE itemnumber= ? AND datearrived IS NULL"
1215                     );
1216                     $sth->execute( $iteminformation->{'itemnumber'} );
1217                     $sth->finish;
1218     #         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'
1219             C4::Reserves::ModReserveStatus( $iteminformation->{'itemnumber'},'W' );
1220             }
1221         else {
1222             $messages->{'WrongTransfer'} = $tobranch;
1223             $messages->{'WrongTransferItem'} = $iteminformation->{'itemnumber'};
1224         }
1225         $validTransfert = 1;
1226         }
1227     
1228     # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
1229         # fix up the accounts.....
1230         if ($iteminformation->{'itemlost'}) {
1231                 FixAccountForLostAndReturned($iteminformation, $borrower);
1232                 $messages->{'WasLost'} = 1;
1233         }
1234         # fix up the overdues in accounts...
1235         FixOverduesOnReturn( $borrower->{'borrowernumber'},
1236             $iteminformation->{'itemnumber'} );
1237     
1238     # find reserves.....
1239     #     if we don't have a reserve with the status W, we launch the Checkreserves routine
1240         my ( $resfound, $resrec ) =
1241         C4::Reserves::CheckReserves( $iteminformation->{'itemnumber'} );
1242         if ($resfound) {
1243             $resrec->{'ResFound'}   = $resfound;
1244             $messages->{'ResFound'} = $resrec;
1245             $reserveDone = 1;
1246         }
1247     
1248         # update stats?
1249         # Record the fact that this book was returned.
1250         UpdateStats(
1251             $branch, 'return', '0', '',
1252             $iteminformation->{'itemnumber'},
1253             $iteminformation->{'itemtype'},
1254             $borrower->{'borrowernumber'}
1255         );
1256         
1257         &logaction(C4::Context->userenv->{'number'},"CIRCULATION","RETURN",$iteminformation->{borrowernumber},$iteminformation->{'biblionumber'}) 
1258             if C4::Context->preference("ReturnLog");
1259         
1260         #adding message if holdingbranch is non equal a userenv branch to return the document to homebranch
1261         #we check, if we don't have reserv or transfert for this document, if not, return it to homebranch .
1262         
1263         if ( ($iteminformation->{'holdingbranch'} ne $iteminformation->{'homebranch'}) and not $messages->{'WrongTransfer'} and ($validTransfert ne 1) and ($reserveDone ne 1) ){
1264                     if (C4::Context->preference("AutomaticItemReturn") == 1) {
1265                     ModItemTransfer($iteminformation->{'itemnumber'}, C4::Context->userenv->{'branch'}, $iteminformation->{'homebranch'});
1266                     $messages->{'WasTransfered'} = 1;
1267                     warn "was transfered";
1268                     }
1269         }
1270     }
1271     return ( $doreturn, $messages, $iteminformation, $borrower );
1272 }
1273
1274 =head2 FixOverduesOnReturn
1275
1276     &FixOverduesOnReturn($brn,$itm);
1277
1278 C<$brn> borrowernumber
1279
1280 C<$itm> itemnumber
1281
1282 internal function, called only by AddReturn
1283
1284 =cut
1285
1286 sub FixOverduesOnReturn {
1287     my ( $borrowernumber, $item ) = @_;
1288     my $dbh = C4::Context->dbh;
1289
1290     # check for overdue fine
1291     my $sth =
1292       $dbh->prepare(
1293 "SELECT * FROM accountlines WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accounttype='FU' OR accounttype='O')"
1294       );
1295     $sth->execute( $borrowernumber, $item );
1296
1297     # alter fine to show that the book has been returned
1298     if ( my $data = $sth->fetchrow_hashref ) {
1299         my $usth =
1300           $dbh->prepare(
1301 "UPDATE accountlines SET accounttype='F' WHERE (borrowernumber = ?) AND (itemnumber = ?) AND (accountno = ?)"
1302           );
1303         $usth->execute( $borrowernumber, $item, $data->{'accountno'} );
1304         $usth->finish();
1305     }
1306     $sth->finish();
1307     return;
1308 }
1309
1310 =head2 FixAccountForLostAndReturned
1311
1312         &FixAccountForLostAndReturned($iteminfo,$borrower);
1313
1314 Calculates the charge for a book lost and returned (Not exported & used only once)
1315
1316 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1317
1318 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1319
1320 Internal function, called by AddReturn
1321
1322 =cut
1323
1324 sub FixAccountForLostAndReturned {
1325         my ($iteminfo, $borrower) = @_;
1326         my %env;
1327         my $dbh = C4::Context->dbh;
1328         my $itm = $iteminfo->{'itemnumber'};
1329         # check for charge made for lost book
1330         my $sth = $dbh->prepare("SELECT * FROM accountlines WHERE (itemnumber = ?) AND (accounttype='L' OR accounttype='Rep') ORDER BY date DESC");
1331         $sth->execute($itm);
1332         if (my $data = $sth->fetchrow_hashref) {
1333         # writeoff this amount
1334                 my $offset;
1335                 my $amount = $data->{'amount'};
1336                 my $acctno = $data->{'accountno'};
1337                 my $amountleft;
1338                 if ($data->{'amountoutstanding'} == $amount) {
1339                 $offset = $data->{'amount'};
1340                 $amountleft = 0;
1341                 } else {
1342                 $offset = $amount - $data->{'amountoutstanding'};
1343                 $amountleft = $data->{'amountoutstanding'} - $amount;
1344                 }
1345                 my $usth = $dbh->prepare("UPDATE accountlines SET accounttype = 'LR',amountoutstanding='0'
1346                         WHERE (borrowernumber = ?)
1347                         AND (itemnumber = ?) AND (accountno = ?) ");
1348                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1349                 $usth->finish;
1350         #check if any credit is left if so writeoff other accounts
1351                 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1352                 if ($amountleft < 0){
1353                 $amountleft*=-1;
1354                 }
1355                 if ($amountleft > 0){
1356                 my $msth = $dbh->prepare("SELECT * FROM accountlines WHERE (borrowernumber = ?)
1357                                                         AND (amountoutstanding >0) ORDER BY date");
1358                 $msth->execute($data->{'borrowernumber'});
1359         # offset transactions
1360                 my $newamtos;
1361                 my $accdata;
1362                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1363                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1364                         $newamtos = 0;
1365                         $amountleft -= $accdata->{'amountoutstanding'};
1366                         }  else {
1367                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1368                         $amountleft = 0;
1369                         }
1370                         my $thisacct = $accdata->{'accountno'};
1371                         my $usth = $dbh->prepare("UPDATE accountlines SET amountoutstanding= ?
1372                                         WHERE (borrowernumber = ?)
1373                                         AND (accountno=?)");
1374                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1375                         $usth->finish;
1376                         $usth = $dbh->prepare("INSERT INTO accountoffsets
1377                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1378                                 VALUES
1379                                 (?,?,?,?)");
1380                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1381                         $usth->finish;
1382                 }
1383                 $msth->finish;
1384                 }
1385                 if ($amountleft > 0){
1386                         $amountleft*=-1;
1387                 }
1388                 my $desc="Item Returned ".$iteminfo->{'barcode'};
1389                 $usth = $dbh->prepare("INSERT INTO accountlines
1390                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1391                         VALUES (?,?,now(),?,?,'CR',?)");
1392                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1393                 $usth->finish;
1394                 $usth = $dbh->prepare("INSERT INTO accountoffsets
1395                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1396                         VALUES (?,?,?,?)");
1397                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1398                 $usth->finish;
1399                 $usth = $dbh->prepare("UPDATE items SET paidfor='' WHERE itemnumber=?");
1400                 $usth->execute($itm);
1401                 $usth->finish;
1402         }
1403         $sth->finish;
1404         return;
1405 }
1406
1407 =head2 GetItemIssue
1408
1409 $issues = &GetItemIssue($itemnumber);
1410
1411 Returns patrons currently having a book. nothing if item is not issued atm
1412
1413 C<$itemnumber> is the itemnumber
1414
1415 Returns an array of hashes
1416 =cut
1417
1418 sub GetItemIssue {
1419     my ( $itemnumber) = @_;
1420     return unless $itemnumber;
1421     my $dbh = C4::Context->dbh;
1422     my @GetItemIssues;
1423     
1424     # get today date
1425     my $today = POSIX::strftime("%Y%m%d", localtime);
1426
1427     my $sth = $dbh->prepare(
1428         "SELECT * FROM issues 
1429         LEFT JOIN items ON issues.itemnumber=items.itemnumber
1430     WHERE
1431     issues.itemnumber=?  AND returndate IS NULL ");
1432     $sth->execute($itemnumber);
1433     my $data = $sth->fetchrow_hashref;
1434     my $datedue = $data->{'date_due'};
1435     $datedue =~ s/-//g;
1436     if ( $datedue < $today ) {
1437         $data->{'overdue'} = 1;
1438     }
1439     $data->{'itemnumber'} = $itemnumber; # fill itemnumber, in case item is not on issue
1440     $sth->finish;
1441     return ($data);
1442 }
1443
1444 =head2 GetItemIssues
1445
1446 $issues = &GetItemIssues($itemnumber, $history);
1447
1448 Returns patrons that have issued a book
1449
1450 C<$itemnumber> is the itemnumber
1451 C<$history> is 0 if you want actuel "issuer" (if it exist) and 1 if you want issues history
1452
1453 Returns an array of hashes
1454 =cut
1455
1456 sub GetItemIssues {
1457     my ( $itemnumber,$history ) = @_;
1458     my $dbh = C4::Context->dbh;
1459     my @GetItemIssues;
1460     
1461     # get today date
1462     my $today = POSIX::strftime("%Y%m%d", localtime);
1463
1464     my $sth = $dbh->prepare(
1465         "SELECT * FROM issues 
1466         LEFT JOIN borrowers ON borrowers.borrowernumber 
1467         LEFT JOIN items ON items.itemnumber=issues.itemnumber 
1468     WHERE
1469     issues.itemnumber=?".($history?"":" AND returndate IS NULL ").
1470     "ORDER BY issues.date_due DESC"
1471     );
1472     $sth->execute($itemnumber);
1473     while ( my $data = $sth->fetchrow_hashref ) {
1474         my $datedue = $data->{'date_due'};
1475         $datedue =~ s/-//g;
1476         if ( $datedue < $today ) {
1477             $data->{'overdue'} = 1;
1478         }
1479         my $itemnumber = $data->{'itemnumber'};
1480         push @GetItemIssues, $data;
1481     }
1482     $sth->finish;
1483     return ( \@GetItemIssues );
1484 }
1485
1486 =head2 GetBiblioIssues
1487
1488 $issues = GetBiblioIssues($biblionumber);
1489
1490 this function get all issues from a biblionumber.
1491
1492 Return:
1493 C<$issues> is a reference to array which each value is ref-to-hash. This ref-to-hash containts all column from
1494 tables issues and the firstname,surname & cardnumber from borrowers.
1495
1496 =cut
1497
1498 sub GetBiblioIssues {
1499     my $biblionumber = shift;
1500     return undef unless $biblionumber;
1501     my $dbh   = C4::Context->dbh;
1502     my $query = "
1503         SELECT issues.*,items.barcode,biblio.biblionumber,biblio.title, biblio.author,borrowers.cardnumber,borrowers.surname,borrowers.firstname
1504         FROM issues
1505             LEFT JOIN borrowers ON borrowers.borrowernumber = issues.borrowernumber
1506             LEFT JOIN items ON issues.itemnumber = items.itemnumber
1507             LEFT JOIN biblioitems ON items.itemnumber = biblioitems.biblioitemnumber
1508             LEFT JOIN biblio ON biblio.biblionumber = items.biblioitemnumber
1509         WHERE biblio.biblionumber = ?
1510         ORDER BY issues.timestamp
1511     ";
1512     my $sth = $dbh->prepare($query);
1513     $sth->execute($biblionumber);
1514
1515     my @issues;
1516     while ( my $data = $sth->fetchrow_hashref ) {
1517         push @issues, $data;
1518     }
1519     return \@issues;
1520 }
1521
1522 =head2 CanBookBeRenewed
1523
1524 $ok = &CanBookBeRenewed($borrowernumber, $itemnumber);
1525
1526 Find out whether a borrowed item may be renewed.
1527
1528 C<$dbh> is a DBI handle to the Koha database.
1529
1530 C<$borrowernumber> is the borrower number of the patron who currently
1531 has the item on loan.
1532
1533 C<$itemnumber> is the number of the item to renew.
1534
1535 C<$CanBookBeRenewed> returns a true value iff the item may be renewed. The
1536 item must currently be on loan to the specified borrower; renewals
1537 must be allowed for the item's type; and the borrower must not have
1538 already renewed the loan.
1539
1540 =cut
1541
1542 sub CanBookBeRenewed {
1543
1544     # check renewal status
1545     my ( $borrowernumber, $itemnumber ) = @_;
1546     my $dbh       = C4::Context->dbh;
1547     my $renews    = 1;
1548     my $renewokay = 0;
1549
1550     # Look in the issues table for this item, lent to this borrower,
1551     # and not yet returned.
1552
1553     # FIXME - I think this function could be redone to use only one SQL call.
1554     my $sth1 = $dbh->prepare(
1555         "SELECT * FROM issues
1556             WHERE borrowernumber = ?
1557             AND itemnumber = ?
1558             AND returndate IS NULL"
1559     );
1560     $sth1->execute( $borrowernumber, $itemnumber );
1561     if ( my $data1 = $sth1->fetchrow_hashref ) {
1562
1563         # Found a matching item
1564
1565         # See if this item may be renewed. This query is convoluted
1566         # because it's a bit messy: given the item number, we need to find
1567         # the biblioitem, which gives us the itemtype, which tells us
1568         # whether it may be renewed.
1569         my $sth2 = $dbh->prepare(
1570             "SELECT renewalsallowed FROM items
1571                 LEFT JOIN biblioitems on items.biblioitemnumber = biblioitems.biblioitemnumber
1572                 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
1573                 WHERE items.itemnumber = ?
1574                 "
1575         );
1576         $sth2->execute($itemnumber);
1577         if ( my $data2 = $sth2->fetchrow_hashref ) {
1578             $renews = $data2->{'renewalsallowed'};
1579         }
1580         if ( $renews && $renews >= $data1->{'renewals'} ) {
1581             $renewokay = 1;
1582         }
1583         $sth2->finish;
1584         my ( $resfound, $resrec ) = C4::Reserves::CheckReserves($itemnumber);
1585         if ($resfound) {
1586             $renewokay = 0;
1587         }
1588
1589     }
1590     $sth1->finish;
1591     return ($renewokay);
1592 }
1593
1594 =head2 AddRenewal
1595
1596 &AddRenewal($borrowernumber, $itemnumber, $datedue);
1597
1598 Renews a loan.
1599
1600 C<$borrowernumber> is the borrower number of the patron who currently
1601 has the item.
1602
1603 C<$itemnumber> is the number of the item to renew.
1604
1605 C<$datedue> can be used to set the due date. If C<$datedue> is the
1606 empty string, C<&AddRenewal> will calculate the due date automatically
1607 from the book's item type. If you wish to set the due date manually,
1608 C<$datedue> should be in the form YYYY-MM-DD.
1609
1610 =cut
1611
1612 sub AddRenewal {
1613
1614     my ( $borrowernumber, $itemnumber, $branch ,$datedue ) = @_;
1615     my $dbh = C4::Context->dbh;
1616         
1617         my $biblio = GetBiblioFromItemNumber($itemnumber);
1618     # If the due date wasn't specified, calculate it by adding the
1619     # book's loan length to today's date.
1620     unless ( $datedue ) {
1621
1622
1623         my $borrower = C4::Members::GetMemberDetails( $borrowernumber, 0 );
1624         my $loanlength = GetLoanLength(
1625             $borrower->{'categorycode'},
1626              (C4::Context->preference('item-level_itypes')) ? $biblio->{'itype'} : $biblio->{'itemtype'} ,
1627                         $borrower->{'branchcode'}
1628         );
1629                 #FIXME --  choose issuer or borrower branch.
1630                 #FIXME -- where's the calendar ?
1631                 #FIXME -- $debug-ify the (0)
1632         my @darray = Add_Delta_DHMS( Today_and_Now(), $loanlength, 0, 0, 0 );
1633         $datedue = C4::Dates->new( sprintf("%04d-%02d-%02d",@darray[0..2]), 'iso');
1634                 (0) and print STDERR  "C4::Dates->new->output = " . C4::Dates->new()->output()
1635                                 . "\ndatedue->output = " . $datedue->output()
1636                                 . "\n(Y,M,D) = " . join ',', @darray;
1637                 $datedue=CheckValidDatedue($datedue,$itemnumber,$branch);
1638     }
1639
1640     # Find the issues record for this book
1641     my $sth =
1642       $dbh->prepare("SELECT * FROM issues
1643                         WHERE borrowernumber=? 
1644                         AND itemnumber=? 
1645                         AND returndate IS NULL"
1646       );
1647     $sth->execute( $borrowernumber, $itemnumber );
1648     my $issuedata = $sth->fetchrow_hashref;
1649     $sth->finish;
1650
1651     # Update the issues record to have the new due date, and a new count
1652     # of how many times it has been renewed.
1653     my $renews = $issuedata->{'renewals'} + 1;
1654     $sth = $dbh->prepare("UPDATE issues SET date_due = ?, renewals = ?
1655                             WHERE borrowernumber=? 
1656                             AND itemnumber=? 
1657                             AND returndate IS NULL"
1658     );
1659     $sth->execute( $datedue->output('iso'), $renews, $borrowernumber, $itemnumber );
1660     $sth->finish;
1661
1662     # Update the renewal count on the item, and tell zebra to reindex
1663     $renews = $biblio->{'renewals'} + 1;
1664     $sth = $dbh->prepare("UPDATE items SET renewals = ? WHERE itemnumber = ?");
1665     $sth->execute($renews,$itemnumber);
1666     $sth->finish();
1667     my $record = GetMarcItem( $biblio->{'biblionumber'}, $itemnumber );
1668     my $frameworkcode = GetFrameworkCode( $biblio->{'biblionumber'} );
1669     ModItemInMarc( $record, $biblio->{'biblionumber'}, $itemnumber, $frameworkcode );
1670
1671     # Charge a new rental fee, if applicable?
1672     my ( $charge, $type ) = GetIssuingCharges( $itemnumber, $borrowernumber );
1673     if ( $charge > 0 ) {
1674         my $accountno = getnextacctno( $borrowernumber );
1675         my $item = GetBiblioFromItemNumber($itemnumber);
1676         $sth = $dbh->prepare(
1677                 "INSERT INTO accountlines
1678                     (borrowernumber,accountno,date,amount,
1679                         description,accounttype,amountoutstanding,
1680                     itemnumber)
1681                     VALUES (?,?,now(),?,?,?,?,?)"
1682         );
1683         $sth->execute( $borrowernumber, $accountno, $charge,
1684             "Renewal of Rental Item $item->{'title'} $item->{'barcode'}",
1685             'Rent', $charge, $itemnumber );
1686         $sth->finish;
1687     }
1688     # Log the renewal
1689     UpdateStats( $branch, 'renew', $charge, '', $itemnumber );
1690 }
1691
1692 sub GetRenewCount {
1693     # check renewal status
1694     my ($bornum,$itemno)=@_;
1695     my $dbh = C4::Context->dbh;
1696     my $renewcount = 0;
1697         my $renewsallowed = 0;
1698         my $renewsleft = 0;
1699     # Look in the issues table for this item, lent to this borrower,
1700     # and not yet returned.
1701
1702     # FIXME - I think this function could be redone to use only one SQL call.
1703     my $sth = $dbh->prepare("select * from issues
1704                                 where (borrowernumber = ?)
1705                                 and (itemnumber = ?)
1706                                 and returndate is null");
1707     $sth->execute($bornum,$itemno);
1708         my $data = $sth->fetchrow_hashref;
1709         $renewcount = $data->{'renewals'} if $data->{'renewals'};
1710     my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1711         where (items.itemnumber = ?)
1712                 and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1713         and (biblioitems.itemtype = itemtypes.itemtype)");
1714     $sth2->execute($itemno);
1715         my $data2 = $sth2->fetchrow_hashref();
1716         $renewsallowed = $data2->{'renewalsallowed'};
1717         $renewsleft = $renewsallowed - $renewcount;
1718         warn "Renewcount:$renewcount RenewsAll:$renewsallowed RenewLeft:$renewsleft";
1719         return ($renewcount,$renewsallowed,$renewsleft);
1720 }
1721 =head2 GetIssuingCharges
1722
1723 ($charge, $item_type) = &GetIssuingCharges($itemnumber, $borrowernumber);
1724
1725 Calculate how much it would cost for a given patron to borrow a given
1726 item, including any applicable discounts.
1727
1728 C<$itemnumber> is the item number of item the patron wishes to borrow.
1729
1730 C<$borrowernumber> is the patron's borrower number.
1731
1732 C<&GetIssuingCharges> returns two values: C<$charge> is the rental charge,
1733 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1734 if it's a video).
1735
1736 =cut
1737
1738 sub GetIssuingCharges {
1739
1740     # calculate charges due
1741     my ( $itemnumber, $borrowernumber ) = @_;
1742     my $charge = 0;
1743     my $dbh    = C4::Context->dbh;
1744     my $item_type;
1745
1746     # Get the book's item type and rental charge (via its biblioitem).
1747     my $qcharge =     "SELECT itemtypes.itemtype,rentalcharge FROM items
1748             LEFT JOIN biblioitems ON biblioitems.biblioitemnumber = items.biblioitemnumber";
1749         $qcharge .= (C4::Context->preference('item-level_itypes'))
1750                 ? " LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype "
1751                 : " LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype ";
1752         
1753     $qcharge .=      "WHERE items.itemnumber =?";
1754    
1755     my $sth1 = $dbh->prepare($qcharge);
1756     $sth1->execute($itemnumber);
1757     if ( my $data1 = $sth1->fetchrow_hashref ) {
1758         $item_type = $data1->{'itemtype'};
1759         $charge    = $data1->{'rentalcharge'};
1760         my $q2 = "SELECT rentaldiscount FROM borrowers
1761             LEFT JOIN issuingrules ON borrowers.categorycode = issuingrules.categorycode
1762             WHERE borrowers.borrowernumber = ?
1763             AND issuingrules.itemtype = ?";
1764         my $sth2 = $dbh->prepare($q2);
1765         $sth2->execute( $borrowernumber, $item_type );
1766         if ( my $data2 = $sth2->fetchrow_hashref ) {
1767             my $discount = $data2->{'rentaldiscount'};
1768             if ( $discount eq 'NULL' ) {
1769                 $discount = 0;
1770             }
1771             $charge = ( $charge * ( 100 - $discount ) ) / 100;
1772         }
1773         $sth2->finish;
1774     }
1775
1776     $sth1->finish;
1777     return ( $charge, $item_type );
1778 }
1779
1780 =head2 AddIssuingCharge
1781
1782 &AddIssuingCharge( $itemno, $borrowernumber, $charge )
1783
1784 =cut
1785
1786 sub AddIssuingCharge {
1787     my ( $itemnumber, $borrowernumber, $charge ) = @_;
1788     my $dbh = C4::Context->dbh;
1789     my $nextaccntno = getnextacctno( $borrowernumber );
1790     my $query ="
1791         INSERT INTO accountlines
1792             (borrowernumber, itemnumber, accountno,
1793             date, amount, description, accounttype,
1794             amountoutstanding)
1795         VALUES (?, ?, ?,now(), ?, 'Rental', 'Rent',?)
1796     ";
1797     my $sth = $dbh->prepare($query);
1798     $sth->execute( $borrowernumber, $itemnumber, $nextaccntno, $charge, $charge );
1799     $sth->finish;
1800 }
1801
1802 =head2 GetTransfers
1803
1804 GetTransfers($itemnumber);
1805
1806 =cut
1807
1808 sub GetTransfers {
1809     my ($itemnumber) = @_;
1810
1811     my $dbh = C4::Context->dbh;
1812
1813     my $query = '
1814         SELECT datesent,
1815                frombranch,
1816                tobranch
1817         FROM branchtransfers
1818         WHERE itemnumber = ?
1819           AND datearrived IS NULL
1820         ';
1821     my $sth = $dbh->prepare($query);
1822     $sth->execute($itemnumber);
1823     my @row = $sth->fetchrow_array();
1824     $sth->finish;
1825     return @row;
1826 }
1827
1828
1829 =head2 GetTransfersFromTo
1830
1831 @results = GetTransfersFromTo($frombranch,$tobranch);
1832
1833 Returns the list of pending transfers between $from and $to branch
1834
1835 =cut
1836
1837 sub GetTransfersFromTo {
1838     my ( $frombranch, $tobranch ) = @_;
1839     return unless ( $frombranch && $tobranch );
1840     my $dbh   = C4::Context->dbh;
1841     my $query = "
1842         SELECT itemnumber,datesent,frombranch
1843         FROM   branchtransfers
1844         WHERE  frombranch=?
1845           AND  tobranch=?
1846           AND datearrived IS NULL
1847     ";
1848     my $sth = $dbh->prepare($query);
1849     $sth->execute( $frombranch, $tobranch );
1850     my @gettransfers;
1851
1852     while ( my $data = $sth->fetchrow_hashref ) {
1853         push @gettransfers, $data;
1854     }
1855     $sth->finish;
1856     return (@gettransfers);
1857 }
1858
1859 =head2 DeleteTransfer
1860
1861 &DeleteTransfer($itemnumber);
1862
1863 =cut
1864
1865 sub DeleteTransfer {
1866     my ($itemnumber) = @_;
1867     my $dbh          = C4::Context->dbh;
1868     my $sth          = $dbh->prepare(
1869         "DELETE FROM branchtransfers
1870          WHERE itemnumber=?
1871          AND datearrived IS NULL "
1872     );
1873     $sth->execute($itemnumber);
1874     $sth->finish;
1875 }
1876
1877 =head2 AnonymiseIssueHistory
1878
1879 $rows = AnonymiseIssueHistory($borrowernumber,$date)
1880
1881 This function write NULL instead of C<$borrowernumber> given on input arg into the table issues.
1882 if C<$borrowernumber> is not set, it will delete the issue history for all borrower older than C<$date>.
1883
1884 return the number of affected rows.
1885
1886 =cut
1887
1888 sub AnonymiseIssueHistory {
1889     my $date           = shift;
1890     my $borrowernumber = shift;
1891     my $dbh            = C4::Context->dbh;
1892     my $query          = "
1893         UPDATE issues
1894         SET    borrowernumber = NULL
1895         WHERE  returndate < '".$date."'
1896           AND borrowernumber IS NOT NULL
1897     ";
1898     $query .= " AND borrowernumber = '".$borrowernumber."'" if defined $borrowernumber;
1899     my $rows_affected = $dbh->do($query);
1900     return $rows_affected;
1901 }
1902
1903 =head2 updateWrongTransfer
1904
1905 $items = updateWrongTransfer($itemNumber,$borrowernumber,$waitingAtLibrary,$FromLibrary);
1906
1907 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 
1908
1909 =cut
1910
1911 sub updateWrongTransfer {
1912         my ( $itemNumber,$waitingAtLibrary,$FromLibrary ) = @_;
1913         my $dbh = C4::Context->dbh;     
1914 # first step validate the actual line of transfert .
1915         my $sth =
1916                 $dbh->prepare(
1917                         "update branchtransfers set datearrived = now(),tobranch=?,comments='wrongtransfer' where itemnumber= ? AND datearrived IS NULL"
1918                 );
1919                 $sth->execute($FromLibrary,$itemNumber);
1920                 $sth->finish;
1921
1922 # second step create a new line of branchtransfer to the right location .
1923         ModItemTransfer($itemNumber, $FromLibrary, $waitingAtLibrary);
1924
1925 #third step changing holdingbranch of item
1926         UpdateHoldingbranch($FromLibrary,$itemNumber);
1927 }
1928
1929 =head2 UpdateHoldingbranch
1930
1931 $items = UpdateHoldingbranch($branch,$itmenumber);
1932 Simple methode for updating hodlingbranch in items BDD line
1933 =cut
1934
1935 sub UpdateHoldingbranch {
1936         my ( $branch,$itmenumber ) = @_;
1937         my $dbh = C4::Context->dbh;     
1938 # first step validate the actual line of transfert .
1939         my $sth =
1940                 $dbh->prepare(
1941                         "update items set holdingbranch = ? where itemnumber= ?"
1942                 );
1943                 $sth->execute($branch,$itmenumber);
1944                 $sth->finish;
1945         
1946         
1947 }
1948 =head2 CheckValidDatedue
1949
1950 $newdatedue = CheckValidDatedue($date_due,$itemnumber,$branchcode);
1951 this function return a new date due after checked if it's a repeatable or special holiday
1952 C<$date_due>   = returndate calculate with no day check
1953 C<$itemnumber>  = itemnumber
1954 C<$branchcode>  = localisation of issue 
1955 =cut
1956 # Why not create calendar object?  - 
1957 # TODO add 'duedate' option to useDaysMode .
1958 sub CheckValidDatedue { 
1959 my ($date_due,$itemnumber,$branchcode)=@_;
1960 my @datedue=split('-',$date_due->output('iso'));
1961 my $years=$datedue[0];
1962 my $month=$datedue[1];
1963 my $day=$datedue[2];
1964 # die "Item# $itemnumber ($branchcode) due: " . ${date_due}->output() . "\n(Y,M,D) = ($years,$month,$day)":
1965 my $dow;
1966 for (my $i=0;$i<2;$i++){
1967         $dow=Day_of_Week($years,$month,$day);
1968         ($dow=0) if ($dow>6);
1969         my $result=CheckRepeatableHolidays($itemnumber,$dow,$branchcode);
1970         my $countspecial=CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
1971         my $countspecialrepeatable=CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
1972                 if (($result ne '0') or ($countspecial ne '0') or ($countspecialrepeatable ne '0') ){
1973                 $i=0;
1974                 (($years,$month,$day) = Add_Delta_Days($years,$month,$day, 1))if ($i ne '1');
1975                 }
1976         }
1977         my $newdatedue=C4::Dates->new(sprintf("%04d-%02d-%02d",$years,$month,$day),'iso');
1978 return $newdatedue;
1979 }
1980 =head2 CheckRepeatableHolidays
1981
1982 $countrepeatable = CheckRepeatableHoliday($itemnumber,$week_day,$branchcode);
1983 this function check if the date due is a repeatable holiday
1984 C<$date_due>   = returndate calculate with no day check
1985 C<$itemnumber>  = itemnumber
1986 C<$branchcode>  = localisation of issue 
1987
1988 =cut
1989
1990 sub CheckRepeatableHolidays{
1991 my($itemnumber,$week_day,$branchcode)=@_;
1992 my $dbh = C4::Context->dbh;
1993 my $query = qq|SELECT count(*)  
1994         FROM repeatable_holidays 
1995         WHERE branchcode=?
1996         AND weekday=?|;
1997 my $sth = $dbh->prepare($query);
1998 $sth->execute($branchcode,$week_day);
1999 my $result=$sth->fetchrow;
2000 $sth->finish;
2001 return $result;
2002 }
2003
2004
2005 =head2 CheckSpecialHolidays
2006
2007 $countspecial = CheckSpecialHolidays($years,$month,$day,$itemnumber,$branchcode);
2008 this function check if the date is a special holiday
2009 C<$years>   = the years of datedue
2010 C<$month>   = the month of datedue
2011 C<$day>     = the day of datedue
2012 C<$itemnumber>  = itemnumber
2013 C<$branchcode>  = localisation of issue 
2014 =cut
2015 sub CheckSpecialHolidays{
2016 my ($years,$month,$day,$itemnumber,$branchcode) = @_;
2017 my $dbh = C4::Context->dbh;
2018 my $query=qq|SELECT count(*) 
2019              FROM `special_holidays`
2020              WHERE year=?
2021              AND month=?
2022              AND day=?
2023              AND branchcode=?
2024             |;
2025 my $sth = $dbh->prepare($query);
2026 $sth->execute($years,$month,$day,$branchcode);
2027 my $countspecial=$sth->fetchrow ;
2028 $sth->finish;
2029 return $countspecial;
2030 }
2031
2032 =head2 CheckRepeatableSpecialHolidays
2033
2034 $countspecial = CheckRepeatableSpecialHolidays($month,$day,$itemnumber,$branchcode);
2035 this function check if the date is a repeatble special holidays
2036 C<$month>   = the month of datedue
2037 C<$day>     = the day of datedue
2038 C<$itemnumber>  = itemnumber
2039 C<$branchcode>  = localisation of issue 
2040 =cut
2041 sub CheckRepeatableSpecialHolidays{
2042 my ($month,$day,$itemnumber,$branchcode) = @_;
2043 my $dbh = C4::Context->dbh;
2044 my $query=qq|SELECT count(*) 
2045              FROM `repeatable_holidays`
2046              WHERE month=?
2047              AND day=?
2048              AND branchcode=?
2049             |;
2050 my $sth = $dbh->prepare($query);
2051 $sth->execute($month,$day,$branchcode);
2052 my $countspecial=$sth->fetchrow ;
2053 $sth->finish;
2054 return $countspecial;
2055 }
2056
2057
2058
2059 sub CheckValidBarcode{
2060 my ($barcode) = @_;
2061 my $dbh = C4::Context->dbh;
2062 my $query=qq|SELECT count(*) 
2063              FROM items 
2064              WHERE barcode=?
2065             |;
2066 my $sth = $dbh->prepare($query);
2067 $sth->execute($barcode);
2068 my $exist=$sth->fetchrow ;
2069 $sth->finish;
2070 return $exist;
2071 }
2072
2073 1;
2074
2075 __END__
2076
2077 =head1 AUTHOR
2078
2079 Koha Developement team <info@koha.org>
2080
2081 =cut
2082