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