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