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