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