Debugged issuing rules n01
[koha.git] / C4 / Circulation / Circ2.pm
1 # -*- tab-width: 8 -*-
2 # Please use 8-character tabs for this file (indents are every 4 characters)
3
4 package C4::Circulation::Circ2;
5
6 # $Id$
7
8 #package to deal with Returns
9 #written 3/11/99 by olwen@katipo.co.nz
10
11
12 # Copyright 2000-2002 Katipo Communications
13 #
14 # This file is part of Koha.
15 #
16 # Koha is free software; you can redistribute it and/or modify it under the
17 # terms of the GNU General Public License as published by the Free Software
18 # Foundation; either version 2 of the License, or (at your option) any later
19 # version.
20 #
21 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
22 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
23 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License along with
26 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
27 # Suite 330, Boston, MA  02111-1307 USA
28
29 use strict;
30 # use warnings;
31 require Exporter;
32 use DBI;
33 use C4::Context;
34 use C4::Stats;
35 use C4::Reserves2;
36 use C4::Koha;
37 use C4::Accounts;
38
39 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
40
41 # set the version for version checking
42 $VERSION = 0.01;
43
44 =head1 NAME
45
46 C4::Circulation::Circ2 - Koha circulation module
47
48 =head1 SYNOPSIS
49
50   use C4::Circulation::Circ2;
51
52 =head1 DESCRIPTION
53
54 The functions in this module deal with circulation, issues, and
55 returns, as well as general information about the library.
56 Also deals with stocktaking.
57
58 =head1 FUNCTIONS
59
60 =over 2
61
62 =cut
63
64 @ISA = qw(Exporter);
65 @EXPORT = qw(&getpatroninformation
66         &currentissues &getissues &getiteminformation
67         &canbookbeissued &issuebook &returnbook &find_reserves &transferbook &decode
68         &calc_charges &listitemsforinventory &itemseen &fixdate);
69
70 # &getbranches &getprinters &getbranch &getprinter => moved to C4::Koha.pm
71
72 =head2 itemseen
73
74 &itemseen($itemnum)
75 Mark item as seen. Is called when an item is issued, returned or manually marked during inventory/stocktaking
76 C<$itemnum> is the item number
77
78 =cut
79
80 sub itemseen {
81         my ($itemnum) = @_;
82         my $dbh = C4::Context->dbh;
83         my $sth = $dbh->prepare("update items set itemlost=0, datelastseen  = now() where items.itemnumber = ?");
84         $sth->execute($itemnum);
85         return;
86 }
87
88 sub listitemsforinventory {
89         my ($minlocation,$maxlocation,$datelastseen,$offset,$size) = @_;
90         my $dbh = C4::Context->dbh;
91         my $sth = $dbh->prepare("select itemnumber,barcode,itemcallnumber,title,author from items,biblio where items.biblionumber=biblio.biblionumber and itemcallnumber>= ? and itemcallnumber <=? and (datelastseen< ? or datelastseen is null) order by itemcallnumber,title");
92         $sth->execute($minlocation,$maxlocation,$datelastseen);
93         my @results;
94         while (my $row = $sth->fetchrow_hashref) {
95                 $offset-- if ($offset);
96                 if ((!$offset) && $size) {
97                         push @results,$row;
98                         $size--;
99                 }
100         }
101         return \@results;
102 }
103
104 =head2 getpatroninformation
105
106   ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, $cardnumber);
107
108 Looks up a patron and returns information about him or her. If
109 C<$borrowernumber> is true (nonzero), C<&getpatroninformation> looks
110 up the borrower by number; otherwise, it looks up the borrower by card
111 number.
112
113 C<$env> is effectively ignored, but should be a reference-to-hash.
114
115 C<$borrower> is a reference-to-hash whose keys are the fields of the
116 borrowers table in the Koha database. In addition,
117 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
118 about the patron. Its keys act as flags :
119
120         if $borrower->{flags}->{LOST} {
121                 # Patron's card was reported lost
122         }
123
124 Each flag has a C<message> key, giving a human-readable explanation of
125 the flag. If the state of a flag means that the patron should not be
126 allowed to borrow any more books, then it will have a C<noissues> key
127 with a true value.
128
129 The possible flags are:
130
131 =head3 CHARGES
132
133 =over 4
134
135 Shows the patron's credit or debt, if any.
136
137 =back
138
139 =head3 GNA
140
141 =over 4
142
143 (Gone, no address.) Set if the patron has left without giving a
144 forwarding address.
145
146 =back
147
148 =head3 LOST
149
150 =over 4
151
152 Set if the patron's card has been reported as lost.
153
154 =back
155
156 =head3 DBARRED
157
158 =over 4
159
160 Set if the patron has been debarred.
161
162 =back
163
164 =head3 NOTES
165
166 =over 4
167
168 Any additional notes about the patron.
169
170 =back
171
172 =head3 ODUES
173
174 =over 4
175
176 Set if the patron has overdue items. This flag has several keys:
177
178 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
179 overdue items. Its elements are references-to-hash, each describing an
180 overdue item. The keys are selected fields from the issues, biblio,
181 biblioitems, and items tables of the Koha database.
182
183 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
184 the overdue items, one per line.
185
186 =back
187
188 =head3 WAITING
189
190 =over 4
191
192 Set if any items that the patron has reserved are available.
193
194 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
195 available items. Each element is a reference-to-hash whose keys are
196 fields from the reserves table of the Koha database.
197
198 =back
199
200 =back
201
202 =cut
203
204
205 sub getpatroninformation {
206 # returns
207         my ($env, $borrowernumber,$cardnumber) = @_;
208         my $dbh = C4::Context->dbh;
209         my $query;
210         my $sth;
211         if ($borrowernumber) {
212                 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
213                 $sth->execute($borrowernumber);
214         } elsif ($cardnumber) {
215                 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
216                 $sth->execute($cardnumber);
217         } else {
218                 $env->{'apierror'} = "invalid borrower information passed to getpatroninformation subroutine";
219                 return();
220         }
221         my $borrower = $sth->fetchrow_hashref;
222         my $amount = checkaccount($env, $borrowernumber, $dbh);
223         $borrower->{'amountoutstanding'} = $amount;
224         my $flags = patronflags($env, $borrower, $dbh);
225         my $accessflagshash;
226  
227         $sth=$dbh->prepare("select bit,flag from userflags");
228         $sth->execute;
229         while (my ($bit, $flag) = $sth->fetchrow) {
230                 if ($borrower->{'flags'} & 2**$bit) {
231                 $accessflagshash->{$flag}=1;
232                 }
233         }
234         $sth->finish;
235         $borrower->{'flags'}=$flags;
236         $borrower->{'authflags'} = $accessflagshash;
237         return ($borrower); #, $flags, $accessflagshash);
238 }
239
240 =head2 decode
241
242 =over 4
243
244 =head3 $str = &decode($chunk);
245
246 =over 4
247
248 Decodes a segment of a string emitted by a CueCat barcode scanner and
249 returns it.
250
251 =back
252
253 =back
254
255 =cut
256
257 # FIXME - At least, I'm pretty sure this is for decoding CueCat stuff.
258 sub decode {
259         my ($encoded) = @_;
260         my $seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
261         my @s = map { index($seq,$_); } split(//,$encoded);
262         my $l = ($#s+1) % 4;
263         if ($l)
264         {
265                 if ($l == 1)
266                 {
267                         print "Error!";
268                         return;
269                 }
270                 $l = 4-$l;
271                 $#s += $l;
272         }
273         my $r = '';
274         while ($#s >= 0)
275         {
276                 my $n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
277                 $r .=chr(($n >> 16) ^ 67) .
278                 chr(($n >> 8 & 255) ^ 67) .
279                 chr(($n & 255) ^ 67);
280                 @s = @s[4..$#s];
281         }
282         $r = substr($r,0,length($r)-$l);
283         return $r;
284 }
285
286 =head2 getiteminformation
287
288 =over 4
289
290 $item = &getiteminformation($env, $itemnumber, $barcode);
291
292 Looks up information about an item, given either its item number or
293 its barcode. If C<$itemnumber> is a nonzero value, it is used;
294 otherwise, C<$barcode> is used.
295
296 C<$env> is effectively ignored, but should be a reference-to-hash.
297
298 C<$item> is a reference-to-hash whose keys are fields from the biblio,
299 items, and biblioitems tables of the Koha database. It may also
300 contain the following keys:
301
302 =head3 date_due
303
304 =over 4
305
306 The due date on this item, if it has been borrowed and not returned
307 yet. The date is in YYYY-MM-DD format.
308
309 =back
310
311 =head3 loanlength
312
313 =over 4
314
315 The length of time for which the item can be borrowed, in days.
316
317 =back
318
319 =head3 notforloan
320
321 =over 4
322
323 True if the item may not be borrowed.
324
325 =back
326
327 =back
328
329 =cut
330
331
332 sub getiteminformation {
333 # returns a hash of item information given either the itemnumber or the barcode
334         my ($env, $itemnumber, $barcode) = @_;
335         my $dbh = C4::Context->dbh;
336         my $sth;
337         if ($itemnumber) {
338                 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.itemnumber=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
339                 $sth->execute($itemnumber);
340         } elsif ($barcode) {
341                 $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.barcode=? and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
342                 $sth->execute($barcode);
343         } else {
344                 $env->{'apierror'}="getiteminformation() subroutine must be called with either an itemnumber or a barcode";
345                 # Error condition.
346                 return();
347         }
348         my $iteminformation=$sth->fetchrow_hashref;
349         $sth->finish;
350         if ($iteminformation) {
351                 $sth=$dbh->prepare("select date_due from issues where itemnumber=? and isnull(returndate)");
352                 $sth->execute($iteminformation->{'itemnumber'});
353                 my ($date_due) = $sth->fetchrow;
354                 $iteminformation->{'date_due'}=$date_due;
355                 $sth->finish;
356                 ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
357                 $sth=$dbh->prepare("select * from itemtypes where itemtype=?");
358                 $sth->execute($iteminformation->{'itemtype'});
359                 my $itemtype=$sth->fetchrow_hashref;
360                 $iteminformation->{'loanlength'}=$itemtype->{'loanlength'};
361                 # if specific item notforloan, don't use itemtype notforloan field.
362                 # otherwise, use itemtype notforloan value to see if item can be issued.
363                 $iteminformation->{'notforloan'}=$itemtype->{'notforloan'} unless $iteminformation->{'notforloan'};
364                 $sth->finish;
365         }
366         return($iteminformation);
367 }
368
369 =head2 transferbook
370
371 =over 4
372
373 ($dotransfer, $messages, $iteminformation) = &transferbook($newbranch, $barcode, $ignore_reserves);
374
375 Transfers an item to a new branch. If the item is currently on loan, it is automatically returned before the actual transfer.
376
377 C<$newbranch> is the code for the branch to which the item should be transferred.
378
379 C<$barcode> is the barcode of the item to be transferred.
380
381 If C<$ignore_reserves> is true, C<&transferbook> ignores reserves.
382 Otherwise, if an item is reserved, the transfer fails.
383
384 Returns three values:
385
386 =head3 $dotransfer 
387
388 is true if the transfer was successful.
389
390 =head3 $messages
391  
392 is a reference-to-hash which may have any of the following keys:
393
394 =over 4
395
396 C<BadBarcode>
397
398 There is no item in the catalog with the given barcode. The value is C<$barcode>.
399
400 C<IsPermanent>
401
402 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.
403
404 C<DestinationEqualsHolding>
405
406 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.
407
408 C<WasReturned>
409
410 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.
411
412 C<ResFound>
413
414 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>.
415
416 C<WasTransferred>
417
418 The item was eligible to be transferred. Barring problems communicating with the database, the transfer should indeed have succeeded. The value should be ignored.
419
420 =back
421
422 =back
423
424 =back
425
426 =cut
427
428 #'
429 # FIXME - This function tries to do too much, and its API is clumsy.
430 # If it didn't also return books, it could be used to change the home
431 # branch of a book while the book is on loan.
432 #
433 # Is there any point in returning the item information? The caller can
434 # look that up elsewhere if ve cares.
435 #
436 # This leaves the ($dotransfer, $messages) tuple. This seems clumsy.
437 # If the transfer succeeds, that's all the caller should need to know.
438 # Thus, this function could simply return 1 or 0 to indicate success
439 # or failure, and set $C4::Circulation::Circ2::errmsg in case of
440 # failure. Or this function could return undef if successful, and an
441 # error message in case of failure (this would feel more like C than
442 # Perl, though).
443 sub transferbook {
444 # transfer book code....
445         my ($tbr, $barcode, $ignoreRs) = @_;
446         my $messages;
447         my %env;
448         my $dotransfer = 1;
449         my $branches = getbranches();
450         my $iteminformation = getiteminformation(\%env, 0, $barcode);
451         # bad barcode..
452         if (not $iteminformation) {
453                 $messages->{'BadBarcode'} = $barcode;
454                 $dotransfer = 0;
455         }
456         # get branches of book...
457         my $hbr = $iteminformation->{'homebranch'};
458         my $fbr = $iteminformation->{'holdingbranch'};
459         # if is permanent...
460         if ($branches->{$hbr}->{'PE'}) {
461                 $messages->{'IsPermanent'} = $hbr;
462         }
463         # can't transfer book if is already there....
464         # FIXME - Why not? Shouldn't it trivially succeed?
465         if ($fbr eq $tbr) {
466                 $messages->{'DestinationEqualsHolding'} = 1;
467                 $dotransfer = 0;
468         }
469         # check if it is still issued to someone, return it...
470         my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
471         if ($currentborrower) {
472                 returnbook($barcode, $fbr);
473                 $messages->{'WasReturned'} = $currentborrower;
474         }
475         # find reserves.....
476         # FIXME - Don't call &CheckReserves unless $ignoreRs is true.
477         # That'll save a database query.
478         my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
479         if ($resfound and not $ignoreRs) {
480                 $resrec->{'ResFound'} = $resfound;
481                 $messages->{'ResFound'} = $resrec;
482                 $dotransfer = 0;
483         }
484         #actually do the transfer....
485         if ($dotransfer) {
486                 dotransfer($iteminformation->{'itemnumber'}, $fbr, $tbr);
487                 $messages->{'WasTransfered'} = 1;
488         }
489         return ($dotransfer, $messages, $iteminformation);
490 }
491
492 # Not exported
493 # FIXME - This is only used in &transferbook. Why bother making it a
494 # separate function?
495 sub dotransfer {
496         my ($itm, $fbr, $tbr) = @_;
497         my $dbh = C4::Context->dbh;
498         $itm = $dbh->quote($itm);
499         $fbr = $dbh->quote($fbr);
500         $tbr = $dbh->quote($tbr);
501         #new entry in branchtransfers....
502         $dbh->do("INSERT INTO   branchtransfers (itemnumber, frombranch, datearrived, tobranch)
503                                         VALUES ($itm, $fbr, now(), $tbr)");
504         #update holdingbranch in items .....
505         $dbh->do("UPDATE items set holdingbranch = $tbr WHERE   items.itemnumber = $itm");
506         &itemseen($itm);
507         return;
508 }
509
510 =head2 canbookbeissued
511
512 Check if a book can be issued.
513
514 my ($issuingimpossible,$needsconfirmation) = canbookbeissued($env,$borrower,$barcode,$year,$month,$day);
515
516 =over 4
517
518 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
519
520 C<$borrower> hash with borrower informations (from getpatroninformation)
521
522 C<$barcode> is the bar code of the book being issued.
523
524 C<$year> C<$month> C<$day> contains the date of the return (in case it's forced by "stickyduedate".
525
526 =back
527
528 Returns :
529
530 =over 4
531
532 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
533 Possible values are :
534
535 =head3 INVALID_DATE 
536
537 sticky due date is invalid
538
539 =head3 GNA
540
541 borrower gone with no address
542
543 =head3 CARD_LOST
544  
545 borrower declared it's card lost
546
547 =head3 DEBARRED
548
549 borrower debarred
550
551 =head3 UNKNOWN_BARCODE
552
553 barcode unknown
554
555 =head3 NOT_FOR_LOAN
556
557 item is not for loan
558
559 =head3 WTHDRAWN
560
561 item withdrawn.
562
563 =head3 RESTRICTED
564
565 item is restricted (set by ??)
566
567 =back
568
569 C<$issuingimpossible> a reference to a hash. It contains reasons why issuing is impossible.
570 Possible values are :
571
572 =head3 DEBT
573
574 borrower has debts.
575
576 =head3 RENEW_ISSUE
577
578 renewing, not issuing
579
580 =head3 ISSUED_TO_ANOTHER
581
582 issued to someone else.
583
584 =head3 RESERVED
585
586 reserved for someone else.
587
588 =head3 INVALID_DATE
589
590 sticky due date is invalid
591
592 =head3 TOO_MANY
593
594 if the borrower borrows to much things
595
596 =cut
597
598 # check if a book can be issued.
599 # returns an array with errors if any
600
601 sub TooMany ($$){
602     my $borrower = shift;
603     my $iteminformation = shift;
604     my $cat_borrower = $borrower->{'categorycode'};
605     my $branch_borrower = $borrower->{'branchcode'};
606     my $dbh = C4::Context->dbh;
607     
608
609     my $sth = $dbh->prepare('select itemtype from biblioitems where biblionumber = ?');
610     $sth->execute($iteminformation->{'biblionumber'});
611     my $type = $sth->fetchrow;
612
613     $sth = $dbh->prepare('select * from issuingrules where categorycode = ? and itemtype = ? and branchcode = ?');
614     my $sth2 = $dbh->prepare("select COUNT(i.borrowernumber) from issues i, biblioitems s where i.borrowernumber = ? and i.returndate is null and i.itemnumber = s.biblioitemnumber and s.itemtype like ?");
615     my $sth3 = $dbh->prepare('select COUNT(borrowernumber) from issues where borrowernumber = ? and returndate is null');
616     
617     $sth->execute($cat_borrower, $type, $branch_borrower);
618     my $result = $sth->fetchrow_hashref;
619     if (defined($result))
620     {
621         $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
622         return (0) if ($result->{'maxissueqty'} <= $sth2->fetchrow);
623     }
624
625     $sth->execute($cat_borrower, $type, "*");
626     my $result = $sth->fetchrow_hashref;
627     if (defined($result))
628     {
629         $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
630         return (0) if ($result->{'maxissueqty'} <= $sth2->fetchrow);
631     }
632
633     $sth->execute($cat_borrower, "*", $branch_borrower);
634     my $result = $sth->fetchrow_hashref;
635     if (defined($result))
636     {
637         $sth3->execute($borrower->{'borrowernumber'});
638         return (0) if ($result->{'maxissueqty'} <= $sth3->fetchrow);
639     }
640
641     $sth->execute("*", $type, $branch_borrower);
642     my $result = $sth->fetchrow_hashref;
643     if (defined($result))
644     {
645         $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
646         return (0) if ($result->{'maxissueqty'} <= $sth2->fetchrow);
647     }
648
649     $sth->execute("*", "*", $branch_borrower);
650     my $result = $sth->fetchrow_hashref;
651     if (defined($result))
652     {
653         $sth3->execute($borrower->{'borrowernumber'});
654         return (0) if ($result->{'maxissueqty'} <= $sth3->fetchrow);
655     }
656
657     $sth->execute("*", $type, "*");
658     my $result = $sth->fetchrow_hashref;
659     if (defined($result))
660     {
661         $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
662         return (0) if ($result->{'maxissueqty'} <= $sth2->fetchrow);
663     }
664
665     $sth->execute($cat_borrower, "*", "*");
666     my $result = $sth->fetchrow_hashref;
667     if (defined($result))
668     {
669         $sth2->execute($borrower->{'borrowernumber'}, "%$type%");
670         return (0) if ($result->{'maxissueqty'} <= $sth2->fetchrow);
671     }
672
673     $sth->execute("*", "*", "*");
674     my $result = $sth->fetchrow_hashref;
675     if (defined($result))
676     {
677         $sth3->execute($borrower->{'borrowernumber'});
678         return (0) if ($result->{'maxissueqty'} <= $sth3->fetchrow);
679     }
680
681     return (1);
682 }
683
684
685 sub canbookbeissued {
686         my ($env,$borrower,$barcode,$year,$month,$day) = @_;
687         warn "CHECKING CANBEISSUED for $borrower->{'borrowernumber'}, $barcode";
688         my %needsconfirmation; # filled with problems that needs confirmations
689         my %issuingimpossible; # filled with problems that causes the issue to be IMPOSSIBLE
690         my $iteminformation = getiteminformation($env, 0, $barcode);
691         my $dbh = C4::Context->dbh;
692 #
693 # DUE DATE is OK ?
694 #
695         my ($duedate, $invalidduedate) = fixdate($year, $month, $day);
696         $issuingimpossible{INVALID_DATE} = 1 if ($invalidduedate);
697
698 #
699 # BORROWER STATUS
700 #
701         if ($borrower->{flags}->{'gonenoaddress'}) {
702                 $issuingimpossible{GNA} = 1;
703         }
704         if ($borrower->{flags}->{'lost'}) {
705                 $issuingimpossible{CARD_LOST} = 1;
706         }
707         if ($borrower->{flags}->{'debarred'}) {
708                 $issuingimpossible{DEBARRED} = 1;
709         }
710 #
711 # BORROWER STATUS
712 #
713
714 # DEBTS
715         my $amount = checkaccount($env,$borrower->{'borrowernumber'}, $dbh,$duedate);
716         if ($amount >0) {
717                 $needsconfirmation{DEBT} = $amount;
718         }
719
720
721 #
722 # JB34 CHECKS IF BORROWERS DONT HAVE ISSUE TOO MANY BOOKS
723 #
724         
725         $needsconfirmation{TOO_MANY} = 1 
726             if (!TooMany($borrower, $iteminformation));
727
728
729 #
730 # ITEM CHECKING
731 #
732         unless ($iteminformation->{barcode}) {
733                 $issuingimpossible{UNKNOWN_BARCODE} = 1;
734         }
735         if ($iteminformation->{'notforloan'} == 1) {
736                 $issuingimpossible{NOT_FOR_LOAN} = 1;
737         }
738         if ($iteminformation->{'itemtype'} eq 'REF') {
739                 $issuingimpossible{NOT_FOR_LOAN} = 1;
740         }
741         if ($iteminformation->{'wthdrawn'} == 1) {
742                 $issuingimpossible{WTHDRAWN} = 1;
743         }
744         if ($iteminformation->{'restricted'} == 1) {
745                 $issuingimpossible{RESTRICTED} = 1;
746         }
747
748             
749
750 #
751 # CHECK IF BOOK ALREADY ISSUED TO THIS BORROWER
752 #
753         my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
754         if ($currentborrower eq $borrower->{'borrowernumber'}) {
755 # Already issued to current borrower. Ask whether the loan should
756 # be renewed.
757                 my ($renewstatus) = renewstatus($env,$dbh,$borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
758                 if ($renewstatus == 0) { # no more renewals allowed
759                         $issuingimpossible{NO_MORE_RENEWALS} = 1;
760                 } else {
761                         $needsconfirmation{RENEW_ISSUE} = 1;
762                 }
763         } elsif ($currentborrower) {
764 # issued to someone else
765                 my $currborinfo = getpatroninformation(0,$currentborrower);
766 #               warn "=>.$currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
767                 $needsconfirmation{ISSUED_TO_ANOTHER} = "$currborinfo->{'reservedate'} : $currborinfo->{'firstname'} $currborinfo->{'surname'} ($currborinfo->{'cardnumber'})";
768         }
769 # See if the item is on reserve.
770         my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
771         if ($restype) {
772                 my $resbor = $res->{'borrowernumber'};
773                 if ($resbor ne $borrower->{'borrowernumber'} && $restype eq "Waiting") {
774                         # The item is on reserve and waiting, but has been
775                         # reserved by some other patron.
776                         my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
777                         my $branches = getbranches();
778                         my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
779                         $needsconfirmation{RESERVE_WAITING} = "$resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}, $branchname)";
780                 } elsif ($restype eq "Reserved") {
781                         # The item is on reserve for someone else.
782                         my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
783                         my $branches = getbranches();
784                         my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
785                         $needsconfirmation{RESERVED} = "$res->{'reservedate'} : $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})";
786                 }
787         }
788         return(\%issuingimpossible,\%needsconfirmation);
789 }
790
791 =head2 issuebook
792
793 Issue a book. Does no check, they are done in canbookbeissued. If we reach this sub, it means the user confirmed if needed.
794
795 &issuebook($env,$borrower,$barcode,$date)
796
797 =over 4
798
799 C<$env> Environment variable. Should be empty usually, but used by other subs. Next code cleaning could drop it.
800
801 C<$borrower> hash with borrower informations (from getpatroninformation)
802
803 C<$barcode> is the bar code of the book being issued.
804
805 C<$date> contains the max date of return. calculated if empty.
806
807 =cut
808
809 #
810 # issuing book. We already have checked it can be issued, so, just issue it !
811 #
812 sub issuebook {
813         my ($env,$borrower,$barcode,$date) = @_;
814         my $dbh = C4::Context->dbh;
815 #       my ($borrower, $flags) = &getpatroninformation($env, $borrowernumber, 0);
816         my $iteminformation = getiteminformation($env, 0, $barcode);
817 #               warn "B : ".$borrower->{borrowernumber}." / I : ".$iteminformation->{'itemnumber'};
818 #
819 # check if we just renew the issue.
820 #
821         my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
822         if ($currentborrower eq $borrower->{'borrowernumber'}) {
823                 my ($charge,$itemtype) = calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
824                 if ($charge > 0) {
825                         createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
826                         $iteminformation->{'charge'} = $charge;
827                 }
828                 &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
829                 renewbook($env,$dbh, $borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
830         } else {
831 #
832 # NOT a renewal
833 #
834                 if ($currentborrower ne '') {
835                         # This book is currently on loan, but not to the person
836                         # who wants to borrow it now. mark it returned before issuing to the new borrower
837                         returnbook($iteminformation->{'barcode'}, $env->{'branchcode'});
838                 }
839                 # See if the item is on reserve.
840                 my ($restype, $res) = CheckReserves($iteminformation->{'itemnumber'});
841                 if ($restype) {
842                         my $resbor = $res->{'borrowernumber'};
843                         if ($resbor eq $borrower->{'borrowernumber'}) {
844                                 # The item is on reserve to the current patron
845                                 FillReserve($res);
846                         } elsif ($restype eq "Waiting") {
847                                 # The item is on reserve and waiting, but has been
848                                 # reserved by some other patron.
849                                 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
850                                 my $branches = getbranches();
851                                 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
852                                 CancelReserve(0, $res->{'itemnumber'}, $res->{'borrowernumber'});
853                         } elsif ($restype eq "Reserved") {
854                                 # The item is on reserve for someone else.
855                                 my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
856                                 my $branches = getbranches();
857                                 my $branchname = $branches->{$res->{'branchcode'}}->{'branchname'};
858                                 my $tobrcd = ReserveWaiting($res->{'itemnumber'}, $res->{'borrowernumber'});
859                                 transferbook($tobrcd,$barcode, 1);
860                         }
861                 }
862                 # Record in the database the fact that the book was issued.
863                 my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values (?,?,?,?)");
864                 my $loanlength = $iteminformation->{loanlength} || 21;
865                 my $datedue=time+($loanlength)*86400;
866                 my @datearr = localtime($datedue);
867                 my $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
868                 if ($env->{'datedue'}) {
869                         $dateduef=$env->{'datedue'};
870                 }
871                 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'}, $dateduef, $env->{'branchcode'});
872                 $sth->finish;
873                 $iteminformation->{'issues'}++;
874                 $sth=$dbh->prepare("update items set issues=? where itemnumber=?");
875                 $sth->execute($iteminformation->{'issues'},$iteminformation->{'itemnumber'});
876                 $sth->finish;
877                 &itemseen($iteminformation->{'itemnumber'});
878                 # If it costs to borrow this book, charge it to the patron's account.
879                 my ($charge,$itemtype)=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'});
880                 if ($charge > 0) {
881                         createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $borrower->{'borrowernumber'}, $charge);
882                         $iteminformation->{'charge'}=$charge;
883                 }
884                 # Record the fact that this book was issued.
885                 &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
886         }
887 }
888
889 =head2 returnbook
890
891   ($doreturn, $messages, $iteminformation, $borrower) =
892           &returnbook($barcode, $branch);
893
894 Returns a book.
895
896 C<$barcode> is the bar code of the book being returned. C<$branch> is
897 the code of the branch where the book is being returned.
898
899 C<&returnbook> returns a list of four items:
900
901 C<$doreturn> is true iff the return succeeded.
902
903 C<$messages> is a reference-to-hash giving the reason for failure:
904
905 =over 4
906
907 =item C<BadBarcode>
908
909 No item with this barcode exists. The value is C<$barcode>.
910
911 =item C<NotIssued>
912
913 The book is not currently on loan. The value is C<$barcode>.
914
915 =item C<IsPermanent>
916
917 The book's home branch is a permanent collection. If you have borrowed
918 this book, you are not allowed to return it. The value is the code for
919 the book's home branch.
920
921 =item C<wthdrawn>
922
923 This book has been withdrawn/cancelled. The value should be ignored.
924
925 =item C<ResFound>
926
927 The item was reserved. The value is a reference-to-hash whose keys are
928 fields from the reserves table of the Koha database, and
929 C<biblioitemnumber>. It also has the key C<ResFound>, whose value is
930 either C<Waiting>, C<Reserved>, or 0.
931
932 =back
933
934 C<$borrower> is a reference-to-hash, giving information about the
935 patron who last borrowed the book.
936
937 =cut
938
939 # FIXME - This API is bogus. There's no need to return $borrower and
940 # $iteminformation; the caller can ask about those separately, if it
941 # cares (it'd be inefficient to make two database calls instead of
942 # one, but &getpatroninformation and &getiteminformation can be
943 # memoized if this is an issue).
944 #
945 # The ($doreturn, $messages) tuple is redundant: if the return
946 # succeeded, that's all the caller needs to know. So &returnbook can
947 # return 1 and 0 on success and failure, and set
948 # $C4::Circulation::Circ2::errmsg to indicate the error. Or it can
949 # return undef for success, and an error message on error (though this
950 # is more C-ish than Perl-ish).
951
952 sub returnbook {
953         my ($barcode, $branch) = @_;
954         my %env;
955         my $messages;
956         my $dbh = C4::Context->dbh;
957         my $doreturn = 1;
958         die '$branch not defined' unless defined $branch; # just in case (bug 170)
959         # get information on item
960         my ($iteminformation) = getiteminformation(\%env, 0, $barcode);
961         if (not $iteminformation) {
962                 $messages->{'BadBarcode'} = $barcode;
963                 $doreturn = 0;
964         }
965         # find the borrower
966         my ($currentborrower) = currentborrower($iteminformation->{'itemnumber'});
967         if ((not $currentborrower) && $doreturn) {
968                 $messages->{'NotIssued'} = $barcode;
969                 $doreturn = 0;
970         }
971         # check if the book is in a permanent collection....
972         my $hbr = $iteminformation->{'homebranch'};
973         my $branches = getbranches();
974         if ($branches->{$hbr}->{'PE'}) {
975                 $messages->{'IsPermanent'} = $hbr;
976         }
977         # check that the book has been cancelled
978         if ($iteminformation->{'wthdrawn'}) {
979                 $messages->{'wthdrawn'} = 1;
980                 $doreturn = 0;
981         }
982         # update issues, thereby returning book (should push this out into another subroutine
983         my ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
984         if ($doreturn) {
985                 my $sth = $dbh->prepare("update issues set returndate = now() where (borrowernumber = ?) and (itemnumber = ?) and (returndate is null)");
986                 $sth->execute($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
987                 $messages->{'WasReturned'} = 1; # FIXME is the "= 1" right?
988         }
989         ($borrower) = getpatroninformation(\%env, $currentborrower, 0);
990         # transfer book to the current branch
991         my ($transfered, $mess, $item) = transferbook($branch, $barcode, 1);
992         if ($transfered) {
993                 $messages->{'WasTransfered'} = 1; # FIXME is the "= 1" right?
994         }
995         # fix up the accounts.....
996         if ($iteminformation->{'itemlost'}) {
997                 fixaccountforlostandreturned($iteminformation, $borrower);
998                 $messages->{'WasLost'} = 1; # FIXME is the "= 1" right?
999         }
1000         # fix up the overdues in accounts...
1001         fixoverduesonreturn($borrower->{'borrowernumber'}, $iteminformation->{'itemnumber'});
1002         # find reserves.....
1003         my ($resfound, $resrec) = CheckReserves($iteminformation->{'itemnumber'});
1004         if ($resfound) {
1005         #       my $tobrcd = ReserveWaiting($resrec->{'itemnumber'}, $resrec->{'borrowernumber'});
1006                 $resrec->{'ResFound'} = $resfound;
1007                 $messages->{'ResFound'} = $resrec;
1008         }
1009         # update stats?
1010         # Record the fact that this book was returned.
1011         UpdateStats(\%env, $branch ,'return','0','',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'},$borrower->{'borrowernumber'});
1012         return ($doreturn, $messages, $iteminformation, $borrower);
1013 }
1014
1015 =head2 fixaccountforlostandreturned
1016
1017         &fixaccountforlostandreturned($iteminfo,$borrower);
1018
1019 Calculates the charge for a book lost and returned (Not exported & used only once)
1020
1021 C<$iteminfo> is a hashref to iteminfo. Only {itemnumber} is used.
1022
1023 C<$borrower> is a hashref to borrower. Only {borrowernumber is used.
1024
1025 =cut
1026
1027 sub fixaccountforlostandreturned {
1028         my ($iteminfo, $borrower) = @_;
1029         my %env;
1030         my $dbh = C4::Context->dbh;
1031         my $itm = $iteminfo->{'itemnumber'};
1032         # check for charge made for lost book
1033         my $sth = $dbh->prepare("select * from accountlines where (itemnumber = ?) and (accounttype='L' or accounttype='Rep') order by date desc");
1034         $sth->execute($itm);
1035         if (my $data = $sth->fetchrow_hashref) {
1036         # writeoff this amount
1037                 my $offset;
1038                 my $amount = $data->{'amount'};
1039                 my $acctno = $data->{'accountno'};
1040                 my $amountleft;
1041                 if ($data->{'amountoutstanding'} == $amount) {
1042                 $offset = $data->{'amount'};
1043                 $amountleft = 0;
1044                 } else {
1045                 $offset = $amount - $data->{'amountoutstanding'};
1046                 $amountleft = $data->{'amountoutstanding'} - $amount;
1047                 }
1048                 my $usth = $dbh->prepare("update accountlines set accounttype = 'LR',amountoutstanding='0'
1049                         where (borrowernumber = ?)
1050                         and (itemnumber = ?) and (accountno = ?) ");
1051                 $usth->execute($data->{'borrowernumber'},$itm,$acctno);
1052                 $usth->finish;
1053         #check if any credit is left if so writeoff other accounts
1054                 my $nextaccntno = getnextacctno(\%env,$data->{'borrowernumber'},$dbh);
1055                 if ($amountleft < 0){
1056                 $amountleft*=-1;
1057                 }
1058                 if ($amountleft > 0){
1059                 my $msth = $dbh->prepare("select * from accountlines where (borrowernumber = ?)
1060                                                         and (amountoutstanding >0) order by date");
1061                 $msth->execute($data->{'borrowernumber'});
1062         # offset transactions
1063                 my $newamtos;
1064                 my $accdata;
1065                 while (($accdata=$msth->fetchrow_hashref) and ($amountleft>0)){
1066                         if ($accdata->{'amountoutstanding'} < $amountleft) {
1067                         $newamtos = 0;
1068                         $amountleft -= $accdata->{'amountoutstanding'};
1069                         }  else {
1070                         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
1071                         $amountleft = 0;
1072                         }
1073                         my $thisacct = $accdata->{'accountno'};
1074                         my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
1075                                         where (borrowernumber = ?)
1076                                         and (accountno=?)");
1077                         $usth->execute($newamtos,$data->{'borrowernumber'},'$thisacct');
1078                         $usth->finish;
1079                         $usth = $dbh->prepare("insert into accountoffsets
1080                                 (borrowernumber, accountno, offsetaccount,  offsetamount)
1081                                 values
1082                                 (?,?,?,?)");
1083                         $usth->execute($data->{'borrowernumber'},$accdata->{'accountno'},$nextaccntno,$newamtos);
1084                         $usth->finish;
1085                 }
1086                 $msth->finish;
1087                 }
1088                 if ($amountleft > 0){
1089                         $amountleft*=-1;
1090                 }
1091                 my $desc="Book Returned ".$iteminfo->{'barcode'};
1092                 $usth = $dbh->prepare("insert into accountlines
1093                         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
1094                         values (?,?,now(),?,?,'CR',?)");
1095                 $usth->execute($data->{'borrowernumber'},$nextaccntno,0-$amount,$desc,$amountleft);
1096                 $usth->finish;
1097                 $usth = $dbh->prepare("insert into accountoffsets
1098                         (borrowernumber, accountno, offsetaccount,  offsetamount)
1099                         values (?,?,?,?)");
1100                 $usth->execute($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset);
1101                 $usth->finish;
1102                 $usth = $dbh->prepare("update items set paidfor='' where itemnumber=?");
1103                 $usth->execute($itm);
1104                 $usth->finish;
1105         }
1106         $sth->finish;
1107         return;
1108 }
1109
1110 =head2 fixoverdueonreturn
1111
1112         &fixoverdueonreturn($brn,$itm);
1113
1114 ??
1115
1116 C<$brn> borrowernumber
1117
1118 C<$itm> itemnumber
1119
1120 =cut
1121
1122 sub fixoverduesonreturn {
1123         my ($brn, $itm) = @_;
1124         my $dbh = C4::Context->dbh;
1125         # check for overdue fine
1126         my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) and (itemnumber = ?) and (accounttype='FU' or accounttype='O')");
1127         $sth->execute($brn,$itm);
1128         # alter fine to show that the book has been returned
1129         if (my $data = $sth->fetchrow_hashref) {
1130                 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber = ?) and (itemnumber = ?) and (acccountno = ?)");
1131                 $usth->execute($brn,$itm,$data->{'accountno'});
1132                 $usth->finish();
1133         }
1134         $sth->finish();
1135         return;
1136 }
1137
1138 # Not exported
1139 #
1140 # NOTE!: If you change this function, be sure to update the POD for
1141 # &getpatroninformation.
1142 #
1143 # $flags = &patronflags($env, $patron, $dbh);
1144 #
1145 # $flags->{CHARGES}
1146 #               {message}       Message showing patron's credit or debt
1147 #               {noissues}      Set if patron owes >$5.00
1148 #         {GNA}                 Set if patron gone w/o address
1149 #               {message}       "Borrower has no valid address"
1150 #               {noissues}      Set.
1151 #         {LOST}                Set if patron's card reported lost
1152 #               {message}       Message to this effect
1153 #               {noissues}      Set.
1154 #         {DBARRED}             Set is patron is debarred
1155 #               {message}       Message to this effect
1156 #               {noissues}      Set.
1157 #         {NOTES}               Set if patron has notes
1158 #               {message}       Notes about patron
1159 #         {ODUES}               Set if patron has overdue books
1160 #               {message}       "Yes"
1161 #               {itemlist}      ref-to-array: list of overdue books
1162 #               {itemlisttext}  Text list of overdue items
1163 #         {WAITING}             Set if there are items available that the
1164 #                               patron reserved
1165 #               {message}       Message to this effect
1166 #               {itemlist}      ref-to-array: list of available items
1167 sub patronflags {
1168 # Original subroutine for Circ2.pm
1169         my %flags;
1170         my ($env, $patroninformation, $dbh) = @_;
1171         my $amount = checkaccount($env, $patroninformation->{'borrowernumber'}, $dbh);
1172         if ($amount > 0) {
1173                 my %flaginfo;
1174                 my $noissuescharge = C4::Context->preference("noissuescharge");
1175                 $flaginfo{'message'}= sprintf "Patron owes \$%.02f", $amount;
1176                 if ($amount > $noissuescharge) {
1177                 $flaginfo{'noissues'} = 1;
1178                 }
1179                 $flags{'CHARGES'} = \%flaginfo;
1180         } elsif ($amount < 0){
1181         my %flaginfo;
1182         $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
1183                 $flags{'CHARGES'} = \%flaginfo;
1184         }
1185         if ($patroninformation->{'gonenoaddress'} == 1) {
1186                 my %flaginfo;
1187                 $flaginfo{'message'} = 'Borrower has no valid address.';
1188                 $flaginfo{'noissues'} = 1;
1189                 $flags{'GNA'} = \%flaginfo;
1190         }
1191         if ($patroninformation->{'lost'} == 1) {
1192                 my %flaginfo;
1193                 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
1194                 $flaginfo{'noissues'} = 1;
1195                 $flags{'LOST'} = \%flaginfo;
1196         }
1197         if ($patroninformation->{'debarred'} == 1) {
1198                 my %flaginfo;
1199                 $flaginfo{'message'} = 'Borrower is Debarred.';
1200                 $flaginfo{'noissues'} = 1;
1201                 $flags{'DBARRED'} = \%flaginfo;
1202         }
1203         if ($patroninformation->{'borrowernotes'}) {
1204                 my %flaginfo;
1205                 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
1206                 $flags{'NOTES'} = \%flaginfo;
1207         }
1208         my ($odues, $itemsoverdue)
1209                         = checkoverdues($env, $patroninformation->{'borrowernumber'}, $dbh);
1210         if ($odues > 0) {
1211                 my %flaginfo;
1212                 $flaginfo{'message'} = "Yes";
1213                 $flaginfo{'itemlist'} = $itemsoverdue;
1214                 foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
1215                 $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
1216                 }
1217                 $flags{'ODUES'} = \%flaginfo;
1218         }
1219         my ($nowaiting, $itemswaiting)
1220                         = CheckWaiting($patroninformation->{'borrowernumber'});
1221         if ($nowaiting > 0) {
1222                 my %flaginfo;
1223                 $flaginfo{'message'} = "Reserved items available";
1224                 $flaginfo{'itemlist'} = $itemswaiting;
1225                 $flags{'WAITING'} = \%flaginfo;
1226         }
1227         return(\%flags);
1228 }
1229
1230
1231 # Not exported
1232 sub checkoverdues {
1233 # From Main.pm, modified to return a list of overdueitems, in addition to a count
1234   #checks whether a borrower has overdue items
1235         my ($env, $bornum, $dbh)=@_;
1236         my @datearr = localtime;
1237         my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
1238         my @overdueitems;
1239         my $count = 0;
1240         my $sth = $dbh->prepare("SELECT * FROM issues,biblio,biblioitems,items
1241                         WHERE items.biblioitemnumber = biblioitems.biblioitemnumber
1242                                 AND items.biblionumber     = biblio.biblionumber
1243                                 AND issues.itemnumber      = items.itemnumber
1244                                 AND issues.borrowernumber  = ?
1245                                 AND issues.returndate is NULL
1246                                 AND issues.date_due < ?");
1247         $sth->execute($bornum,$today);
1248         while (my $data = $sth->fetchrow_hashref) {
1249         push (@overdueitems, $data);
1250         $count++;
1251         }
1252         $sth->finish;
1253         return ($count, \@overdueitems);
1254 }
1255
1256 # Not exported
1257 sub currentborrower {
1258 # Original subroutine for Circ2.pm
1259         my ($itemnumber) = @_;
1260         my $dbh = C4::Context->dbh;
1261         my $q_itemnumber = $dbh->quote($itemnumber);
1262         my $sth=$dbh->prepare("select borrowers.borrowernumber from
1263         issues,borrowers where issues.itemnumber=$q_itemnumber and
1264         issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
1265         NULL");
1266         $sth->execute;
1267         my ($borrower) = $sth->fetchrow;
1268         return($borrower);
1269 }
1270
1271 # FIXME - Not exported, but used in 'updateitem.pl' anyway.
1272 sub checkreserve {
1273 # Stolen from Main.pm
1274 # Check for reserves for biblio
1275         my ($env,$dbh,$itemnum)=@_;
1276         my $resbor = "";
1277         my $sth = $dbh->prepare("select * from reserves,items
1278         where (items.itemnumber = ?)
1279         and (reserves.cancellationdate is NULL)
1280         and (items.biblionumber = reserves.biblionumber)
1281         and ((reserves.found = 'W')
1282         or (reserves.found is null))
1283         order by priority");
1284         $sth->execute($itemnum);
1285         my $resrec;
1286         my $data=$sth->fetchrow_hashref;
1287         while ($data && $resbor eq '') {
1288         $resrec=$data;
1289         my $const = $data->{'constrainttype'};
1290         if ($const eq "a") {
1291         $resbor = $data->{'borrowernumber'};
1292         } else {
1293         my $found = 0;
1294         my $csth = $dbh->prepare("select * from reserveconstraints,items
1295                 where (borrowernumber=?)
1296                 and reservedate=?
1297                 and reserveconstraints.biblionumber=?
1298                 and (items.itemnumber=? and
1299                 items.biblioitemnumber = reserveconstraints.biblioitemnumber)");
1300         $csth->execute($data->{'borrowernumber'},$data->{'biblionumber'},$data->{'reservedate'},$itemnum);
1301         if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
1302         if ($const eq 'o') {
1303                 if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
1304         } else {
1305                 if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
1306         }
1307         $csth->finish();
1308         }
1309         $data=$sth->fetchrow_hashref;
1310         }
1311         $sth->finish;
1312         return ($resbor,$resrec);
1313 }
1314
1315 =head2 currentissues
1316
1317   $issues = &currentissues($env, $borrower);
1318
1319 Returns a list of books currently on loan to a patron.
1320
1321 If C<$env-E<gt>{todaysissues}> is set and true, C<&currentissues> only
1322 returns information about books issued today. If
1323 C<$env-E<gt>{nottodaysissues}> is set and true, C<&currentissues> only
1324 returns information about books issued before today. If both are
1325 specified, C<$env-E<gt>{todaysissues}> is ignored. If neither is
1326 specified, C<&currentissues> returns all of the patron's issues.
1327
1328 C<$borrower->{borrowernumber}> is the borrower number of the patron
1329 whose issues we want to list.
1330
1331 C<&currentissues> returns a PHP-style array: C<$issues> is a
1332 reference-to-hash whose keys are integers in the range 1...I<n>, where
1333 I<n> is the number of items on issue (either today or before today).
1334 C<$issues-E<gt>{I<n>}> is a reference-to-hash whose keys are all of
1335 the fields of the biblio, biblioitems, items, and issues fields of the
1336 Koha database for that particular item.
1337
1338 =cut
1339
1340 #'
1341 sub currentissues {
1342 # New subroutine for Circ2.pm
1343         my ($env, $borrower) = @_;
1344         my $dbh = C4::Context->dbh;
1345         my %currentissues;
1346         my $counter=1;
1347         my $borrowernumber = $borrower->{'borrowernumber'};
1348         my $crit='';
1349
1350         # Figure out whether to get the books issued today, or earlier.
1351         # FIXME - $env->{todaysissues} and $env->{nottodaysissues} can
1352         # both be specified, but are mutually-exclusive. This is bogus.
1353         # Make this a flag. Or better yet, return everything in (reverse)
1354         # chronological order and let the caller figure out which books
1355         # were issued today.
1356         if ($env->{'todaysissues'}) {
1357                 # FIXME - Could use
1358                 #       $today = POSIX::strftime("%Y%m%d", localtime);
1359                 # FIXME - Since $today will be used in either case, move it
1360                 # out of the two if-blocks.
1361                 my @datearr = localtime(time());
1362                 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1363                 # FIXME - MySQL knows about dates. Just use
1364                 #       and issues.timestamp = curdate();
1365                 $crit=" and issues.timestamp like '$today%' ";
1366         }
1367         if ($env->{'nottodaysissues'}) {
1368                 # FIXME - Could use
1369                 #       $today = POSIX::strftime("%Y%m%d", localtime);
1370                 # FIXME - Since $today will be used in either case, move it
1371                 # out of the two if-blocks.
1372                 my @datearr = localtime(time());
1373                 my $today = (1900+$datearr[5]).sprintf "%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
1374                 # FIXME - MySQL knows about dates. Just use
1375                 #       and issues.timestamp < curdate();
1376                 $crit=" and !(issues.timestamp like '$today%') ";
1377         }
1378
1379         # FIXME - Does the caller really need every single field from all
1380         # four tables?
1381         my $sth=$dbh->prepare("select * from issues,items,biblioitems,biblio where
1382         borrowernumber=? and issues.itemnumber=items.itemnumber and
1383         items.biblionumber=biblio.biblionumber and
1384         items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
1385         $crit order by issues.date_due");
1386         $sth->execute($borrowernumber);
1387         while (my $data = $sth->fetchrow_hashref) {
1388                 # FIXME - The Dewey code is a string, not a number.
1389                 $data->{'dewey'}=~s/0*$//;
1390                 ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
1391                 # FIXME - Could use
1392                 #       $todaysdate = POSIX::strftime("%Y%m%d", localtime)
1393                 # or better yet, just reuse $today which was calculated above.
1394                 # This function isn't going to run until midnight, is it?
1395                 # Alternately, use
1396                 #       $todaysdate = POSIX::strftime("%Y-%m-%d", localtime)
1397                 #       if ($data->{'date_due'} lt $todaysdate)
1398                 #               ...
1399                 # Either way, the date should be be formatted outside of the
1400                 # loop.
1401                 my @datearr = localtime(time());
1402                 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1403                 my $datedue=$data->{'date_due'};
1404                 $datedue=~s/-//g;
1405                 if ($datedue < $todaysdate) {
1406                         $data->{'overdue'}=1;
1407                 }
1408                 my $itemnumber=$data->{'itemnumber'};
1409                 # FIXME - Consecutive integers as hash keys? You have GOT to
1410                 # be kidding me! Use an array, fercrissakes!
1411                 $currentissues{$counter}=$data;
1412                 $counter++;
1413         }
1414         $sth->finish;
1415         return(\%currentissues);
1416 }
1417
1418 =head2 getissues
1419
1420   $issues = &getissues($borrowernumber);
1421
1422 Returns the set of books currently on loan to a patron.
1423
1424 C<$borrowernumber> is the patron's borrower number.
1425
1426 C<&getissues> returns a PHP-style array: C<$issues> is a
1427 reference-to-hash whose keys are integers in the range 0..I<n>-1,
1428 where I<n> is the number of books the patron currently has on loan.
1429
1430 The values of C<$issues> are references-to-hash whose keys are
1431 selected fields from the issues, items, biblio, and biblioitems tables
1432 of the Koha database.
1433
1434 =cut
1435 #'
1436 sub getissues {
1437 # New subroutine for Circ2.pm
1438         my ($borrower) = @_;
1439         my $dbh = C4::Context->dbh;
1440         my $borrowernumber = $borrower->{'borrowernumber'};
1441         my %currentissues;
1442         my $select = "SELECT issues.timestamp      AS timestamp,
1443                                 issues.date_due       AS date_due,
1444                                 items.biblionumber    AS biblionumber,
1445                                 items.itemnumber    AS itemnumber,
1446                                 items.barcode         AS barcode,
1447                                 biblio.title          AS title,
1448                                 biblio.author         AS author,
1449                                 biblioitems.dewey     AS dewey,
1450                                 itemtypes.description AS itemtype,
1451                                 biblioitems.subclass  AS subclass,
1452                                 biblioitems.classification AS classification
1453                         FROM issues,items,biblioitems,biblio, itemtypes
1454                         WHERE issues.borrowernumber  = ?
1455                         AND issues.itemnumber      = items.itemnumber
1456                         AND items.biblionumber     = biblio.biblionumber
1457                         AND items.biblioitemnumber = biblioitems.biblioitemnumber
1458                         AND itemtypes.itemtype     = biblioitems.itemtype
1459                         AND issues.returndate      IS NULL
1460                         ORDER BY issues.date_due";
1461         #    print $select;
1462         my $sth=$dbh->prepare($select);
1463         $sth->execute($borrowernumber);
1464         my $counter = 0;
1465         while (my $data = $sth->fetchrow_hashref) {
1466                 $data->{'dewey'} =~ s/0*$//;
1467                 ($data->{'dewey'} == 0) && ($data->{'dewey'} = '');
1468                         # FIXME - The Dewey code is a string, not a number.
1469                 # FIXME - Use POSIX::strftime to get a text version of today's
1470                 # date. That's what it's for.
1471                 # FIXME - Move the date calculation outside of the loop.
1472                 my @datearr = localtime(time());
1473                 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", $datearr[3]);
1474
1475                 # FIXME - Instead of converting the due date to YYYYMMDD, just
1476                 # use
1477                 #       $todaysdate = POSIX::strftime("%Y-%m-%d", localtime);
1478                 #       ...
1479                 #       if ($date->{date_due} lt $todaysdate)
1480                 my $datedue = $data->{'date_due'};
1481                 $datedue =~ s/-//g;
1482                 if ($datedue < $todaysdate) {
1483                         $data->{'overdue'} = 1;
1484                 }
1485                 $currentissues{$counter} = $data;
1486                 $counter++;
1487                         # FIXME - This is ludicrous. If you want to return an
1488                         # array of values, just use an array. That's what
1489                         # they're there for.
1490         }
1491         $sth->finish;
1492         return(\%currentissues);
1493 }
1494
1495 # Not exported
1496 sub checkwaiting {
1497 #Stolen from Main.pm
1498 # check for reserves waiting
1499         my ($env,$dbh,$bornum)=@_;
1500         my @itemswaiting;
1501         my $sth = $dbh->prepare("select * from reserves where (borrowernumber = ?) and (reserves.found='W') and cancellationdate is NULL");
1502         $sth->execute($bornum);
1503         my $cnt=0;
1504         if (my $data=$sth->fetchrow_hashref) {
1505                 $itemswaiting[$cnt] =$data;
1506                 $cnt ++
1507         }
1508         $sth->finish;
1509         return ($cnt,\@itemswaiting);
1510 }
1511
1512 =head2 renewstatus
1513
1514   $ok = &renewstatus($env, $dbh, $borrowernumber, $itemnumber);
1515
1516 Find out whether a borrowed item may be renewed.
1517
1518 C<$env> is ignored.
1519
1520 C<$dbh> is a DBI handle to the Koha database.
1521
1522 C<$borrowernumber> is the borrower number of the patron who currently
1523 has the item on loan.
1524
1525 C<$itemnumber> is the number of the item to renew.
1526
1527 C<$renewstatus> returns a true value iff the item may be renewed. The
1528 item must currently be on loan to the specified borrower; renewals
1529 must be allowed for the item's type; and the borrower must not have
1530 already renewed the loan.
1531
1532 =cut
1533
1534 sub renewstatus {
1535   # check renewal status
1536   # FIXME - Two people can't borrow the same book at once, so
1537   # presumably we can get $bornum from $itemno.
1538   my ($env,$bornum,$itemno)=@_;
1539   my $dbh = C4::Context->dbh;
1540   my $renews = 1;
1541   my $renewokay = 0;
1542   # Look in the issues table for this item, lent to this borrower,
1543   # and not yet returned.
1544
1545   # FIXME - I think this function could be redone to use only one SQL
1546   # call.
1547   my $sth1 = $dbh->prepare("select * from issues
1548     where (borrowernumber = ?)
1549     and (itemnumber = ?')
1550     and returndate is null");
1551   $sth1->execute($bornum,$itemno);
1552   if (my $data1 = $sth1->fetchrow_hashref) {
1553     # Found a matching item
1554
1555     # See if this item may be renewed. This query is convoluted
1556     # because it's a bit messy: given the item number, we need to find
1557     # the biblioitem, which gives us the itemtype, which tells us
1558     # whether it may be renewed.
1559     my $sth2 = $dbh->prepare("select renewalsallowed from items,biblioitems,itemtypes
1560        where (items.itemnumber = ?)
1561        and (items.biblioitemnumber = biblioitems.biblioitemnumber)
1562        and (biblioitems.itemtype = itemtypes.itemtype)");
1563     $sth2->execute($itemno);
1564     if (my $data2=$sth2->fetchrow_hashref) {
1565       $renews = $data2->{'renewalsallowed'};
1566     }
1567     if ($renews > $data1->{'renewals'}) {
1568       $renewokay = 1;
1569     }
1570     $sth2->finish;
1571   }
1572   $sth1->finish;
1573   return($renewokay);
1574 }
1575
1576 =head2 renewbook
1577
1578   &renewbook($env, $borrowernumber, $itemnumber, $datedue);
1579
1580 Renews a loan.
1581
1582 C<$env-E<gt>{branchcode}> is the code of the branch where the
1583 renewal is taking place.
1584
1585 C<$env-E<gt>{usercode}> is the value to log in C<statistics.usercode>
1586 in the Koha database.
1587
1588 C<$borrowernumber> is the borrower number of the patron who currently
1589 has the item.
1590
1591 C<$itemnumber> is the number of the item to renew.
1592
1593 C<$datedue> can be used to set the due date. If C<$datedue> is the
1594 empty string, C<&renewbook> will calculate the due date automatically
1595 from the book's item type. If you wish to set the due date manually,
1596 C<$datedue> should be in the form YYYY-MM-DD.
1597
1598 =cut
1599
1600 sub renewbook {
1601   # mark book as renewed
1602   # FIXME - A book can't be on loan to two people at once, so
1603   # presumably we can get $bornum from $itemno.
1604   my ($env,$bornum,$itemno,$datedue)=@_;
1605   my $dbh = C4::Context->dbh;
1606
1607   # If the due date wasn't specified, calculate it by adding the
1608   # book's loan length to today's date.
1609   if ($datedue eq "" ) {
1610     #debug_msg($env, "getting date");
1611     my $loanlength=21;          # Default loan length?
1612                                 # FIXME - This is bogus. If there's no
1613                                 # loan length defined for some book
1614                                 # type or whatever, then that should
1615                                 # be an error
1616     # Find this item's item type, via its biblioitem.
1617     my $sth=$dbh->prepare("Select * from biblioitems,items,itemtypes
1618        where (items.itemnumber = ?)
1619        and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1620        and (biblioitems.itemtype = itemtypes.itemtype)");
1621     $sth->execute($itemno);
1622     if (my $data=$sth->fetchrow_hashref) {
1623       $loanlength = $data->{'loanlength'}
1624     }
1625     $sth->finish;
1626     my $ti = time;              # FIXME - Unused
1627     # FIXME - Use
1628     #   POSIX::strftime("%Y-%m-%d", localtime(time + ...));
1629     my $datedu = time + ($loanlength * 86400);
1630     my @datearr = localtime($datedu);
1631     $datedue = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
1632   }
1633
1634   # Find the issues record for this book
1635   my $sth=$dbh->prepare("select * from issues where borrowernumber=? and
1636     itemnumber=? and returndate is null");
1637   $sth->execute($bornum,$itemno);
1638   my $issuedata=$sth->fetchrow_hashref;
1639         # FIXME - Error-checking
1640   $sth->finish;
1641
1642   # Update the issues record to have the new due date, and a new count
1643   # of how many times it has been renewed.
1644   my $renews = $issuedata->{'renewals'} +1;
1645   $sth=$dbh->prepare("update issues
1646     set date_due = ?, renewals = ?
1647     where borrowernumber=? and
1648     itemnumber=? and returndate is null");
1649   $sth->execute($datedue,$renews,$bornum,$itemno);
1650   $sth->finish;
1651
1652   # Log the renewal
1653   UpdateStats($env,$env->{'branchcode'},'renew','','',$itemno);
1654
1655   # Charge a new rental fee, if applicable?
1656   my ($charge,$type)=calc_charges($env, $itemno, $bornum);
1657   if ($charge > 0){
1658     my $accountno=getnextacctno($env,$bornum,$dbh);
1659     my $item=getiteminformation($env, $itemno);
1660     $sth=$dbh->prepare("Insert into accountlines (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber)
1661                                                 values (?,?,now(),?,?,?,?,?)");
1662     $sth->execute($bornum,$accountno,$charge,"Renewal of Rental Item $item->{'title'} $item->{'barcode'}",'Rent',$charge,$itemno);
1663     $sth->finish;
1664 #     print $account;
1665   }
1666
1667 #  return();
1668 }
1669
1670
1671
1672 =item calc_charges
1673
1674   ($charge, $item_type) = &calc_charges($env, $itemnumber, $borrowernumber);
1675
1676 Calculate how much it would cost for a given patron to borrow a given
1677 item, including any applicable discounts.
1678
1679 C<$env> is ignored.
1680
1681 C<$itemnumber> is the item number of item the patron wishes to borrow.
1682
1683 C<$borrowernumber> is the patron's borrower number.
1684
1685 C<&calc_charges> returns two values: C<$charge> is the rental charge,
1686 and C<$item_type> is the code for the item's item type (e.g., C<VID>
1687 if it's a video).
1688
1689 =cut
1690
1691 sub calc_charges {
1692   # calculate charges due
1693   my ($env, $itemno, $bornum)=@_;
1694   my $charge=0;
1695   my $dbh = C4::Context->dbh;
1696   my $item_type;
1697
1698   # Get the book's item type and rental charge (via its biblioitem).
1699   my $sth1= $dbh->prepare("select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes
1700                                                  where (items.itemnumber =?)
1701                                                                 and (biblioitems.biblioitemnumber = items.biblioitemnumber)
1702                                                                 and (biblioitems.itemtype = itemtypes.itemtype)");
1703   $sth1->execute($itemno);
1704   # FIXME - Why not just use fetchrow_array?
1705   if (my $data1=$sth1->fetchrow_hashref) {
1706     $item_type = $data1->{'itemtype'};
1707     $charge = $data1->{'rentalcharge'};
1708
1709     # Figure out the applicable rental discount
1710     my $sth2=$dbh->prepare("select rentaldiscount from
1711     borrowers,categoryitem
1712     where (borrowers.borrowernumber = ?)
1713     and (borrowers.categorycode = categoryitem.categorycode)
1714     and (categoryitem.itemtype = ?)");
1715     $sth2->execute($bornum,$item_type);
1716     if (my$data2=$sth2->fetchrow_hashref) {
1717       my $discount = $data2->{'rentaldiscount'};
1718       $charge *= (100 - $discount) / 100;
1719     }
1720     $sth2->finish;
1721   }
1722   $sth1->finish;
1723 #  print "item $item_type";
1724   return ($charge,$item_type);
1725 }
1726
1727
1728 # FIXME - A virtually identical function appears in
1729 # C4::Circulation::Issues. Pick one and stick with it.
1730 sub createcharge {
1731 #Stolen from Issues.pm
1732     my ($env,$dbh,$itemno,$bornum,$charge) = @_;
1733     my $nextaccntno = getnextacctno($env,$bornum,$dbh);
1734     my $sth = $dbh->prepare(<<EOT);
1735         INSERT INTO     accountlines
1736                         (borrowernumber, itemnumber, accountno,
1737                          date, amount, description, accounttype,
1738                          amountoutstanding)
1739         VALUES          (?, ?, ?,
1740                          now(), ?, 'Rental', 'Rent',
1741                          ?)
1742 EOT
1743     $sth->execute($bornum, $itemno, $nextaccntno, $charge, $charge);
1744     $sth->finish;
1745 }
1746
1747
1748 sub getnextacctno {
1749 # Stolen from Accounts.pm
1750     my ($env,$bornumber,$dbh)=@_;
1751     my $nextaccntno = 1;
1752     my $sth = $dbh->prepare("select * from accountlines where (borrowernumber = ?) order by accountno desc");
1753     $sth->execute($bornumber);
1754     if (my $accdata=$sth->fetchrow_hashref){
1755         $nextaccntno = $accdata->{'accountno'} + 1;
1756     }
1757     $sth->finish;
1758     return($nextaccntno);
1759 }
1760
1761 =item find_reserves
1762
1763   ($status, $record) = &find_reserves($itemnumber);
1764
1765 Looks up an item in the reserves.
1766
1767 C<$itemnumber> is the itemnumber to look up.
1768
1769 C<$status> is true iff the search was successful.
1770
1771 C<$record> is a reference-to-hash describing the reserve. Its keys are
1772 the fields from the reserves table of the Koha database.
1773
1774 =cut
1775 #'
1776 # FIXME - This API is bogus: just return the record, or undef if none
1777 # was found.
1778 # FIXME - There's also a &C4::Circulation::Returns::find_reserves, but
1779 # that one looks rather different.
1780 sub find_reserves {
1781 # Stolen from Returns.pm
1782     my ($itemno) = @_;
1783     my %env;
1784     my $dbh = C4::Context->dbh;
1785     my ($itemdata) = getiteminformation(\%env, $itemno,0);
1786     my $bibno = $dbh->quote($itemdata->{'biblionumber'});
1787     my $bibitm = $dbh->quote($itemdata->{'biblioitemnumber'});
1788     my $sth = $dbh->prepare("select * from reserves where ((found = 'W') or (found is null)) and biblionumber = ? and cancellationdate is NULL order by priority, reservedate");
1789     $sth->execute($bibno);
1790     my $resfound = 0;
1791     my $resrec;
1792     my $lastrec;
1793 # print $query;
1794
1795     # FIXME - I'm not really sure what's going on here, but since we
1796     # only want one result, wouldn't it be possible (and far more
1797     # efficient) to do something clever in SQL that only returns one
1798     # set of values?
1799     while (($resrec = $sth->fetchrow_hashref) && (not $resfound)) {
1800                 # FIXME - Unlike Pascal, Perl allows you to exit loops
1801                 # early. Take out the "&& (not $resfound)" and just
1802                 # use "last" at the appropriate point in the loop.
1803                 # (Oh, and just in passing: if you'd used "!" instead
1804                 # of "not", you wouldn't have needed the parentheses.)
1805         $lastrec = $resrec;
1806         my $brn = $dbh->quote($resrec->{'borrowernumber'});
1807         my $rdate = $dbh->quote($resrec->{'reservedate'});
1808         my $bibno = $dbh->quote($resrec->{'biblionumber'});
1809         if ($resrec->{'found'} eq "W") {
1810             if ($resrec->{'itemnumber'} eq $itemno) {
1811                 $resfound = 1;
1812             }
1813         } else {
1814             # FIXME - Use 'elsif' to avoid unnecessary indentation.
1815             if ($resrec->{'constrainttype'} eq "a") {
1816                 $resfound = 1;
1817             } else {
1818                         my $consth = $dbh->prepare("select * from reserveconstraints where borrowernumber = ? and reservedate = ? and biblionumber = ? and biblioitemnumber = ?");
1819                         $consth->execute($brn,$rdate,$bibno,$bibitm);
1820                         if (my $conrec = $consth->fetchrow_hashref) {
1821                                 if ($resrec->{'constrainttype'} eq "o") {
1822                                 $resfound = 1;
1823                                 }
1824                         }
1825                 $consth->finish;
1826                 }
1827         }
1828         if ($resfound) {
1829             my $updsth = $dbh->prepare("update reserves set found = 'W', itemnumber = ? where borrowernumber = ? and reservedate = ? and biblionumber = ?");
1830             $updsth->execute($itemno,$brn,$rdate,$bibno);
1831             $updsth->finish;
1832             # FIXME - "last;" here to break out of the loop early.
1833         }
1834     }
1835     $sth->finish;
1836     return ($resfound,$lastrec);
1837 }
1838
1839 sub fixdate {
1840     my ($year, $month, $day) = @_;
1841     my $invalidduedate;
1842     my $date;
1843     if (($year eq 0) && ($month eq 0) && ($year eq 0)) {
1844 #       $env{'datedue'}='';
1845     } else {
1846         if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
1847             $invalidduedate=1;
1848         } else {
1849             if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
1850                 $invalidduedate = 1;
1851             } elsif (($day > 29) && ($month == 2)) {
1852                 $invalidduedate=1;
1853             } elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
1854                 $invalidduedate=1;
1855             } else {
1856                 $date="$year-$month-$day";
1857             }
1858         }
1859     }
1860     return ($date, $invalidduedate);
1861 }
1862
1863 1;
1864 __END__
1865
1866 =back
1867
1868 =head1 AUTHOR
1869
1870 Koha Developement team <info@koha.org>
1871
1872 =cut