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