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