Added an overdue variable to the itemdata returned by the currentissues
[koha.git] / C4 / Circulation / Circ2.pm
1 package C4::Circulation::Circ2;
2
3 #package to deal with Returns
4 #written 3/11/99 by olwen@katipo.co.nz
5
6 use strict;
7 require Exporter;
8 use DBI;
9 use C4::Database;
10 #use C4::Accounts;
11 #use C4::InterfaceCDK;
12 #use C4::Circulation::Main;
13 #use C4::Format;
14 #use C4::Circulation::Renewals;
15 #use C4::Scan;
16 use C4::Stats;
17 #use C4::Search;
18 #use C4::Print;
19
20 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
21   
22 # set the version for version checking
23 $VERSION = 0.01;
24     
25 @ISA = qw(Exporter);
26 @EXPORT = qw(&getbranches &getprinters &getpatroninformation &currentissues &getiteminformation &findborrower &issuebook &returnbook);
27 %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
28                   
29 # your exported package globals go here,
30 # as well as any optionally exported functions
31
32 @EXPORT_OK   = qw($Var1 %Hashit);
33
34
35 # non-exported package globals go here
36 #use vars qw(@more $stuff);
37         
38 # initalize package globals, first exported ones
39
40 my $Var1   = '';
41 my %Hashit = ();
42                     
43 # then the others (which are still accessible as $Some::Module::stuff)
44 my $stuff  = '';
45 my @more   = ();
46         
47 # all file-scoped lexicals must be created before
48 # the functions below that use them.
49                 
50 # file-private lexicals go here
51 my $priv_var    = '';
52 my %secret_hash = ();
53                             
54 # here's a file-private function as a closure,
55 # callable as &$priv_func;  it cannot be prototyped.
56 my $priv_func = sub {
57   # stuff goes here.
58 };
59                                                     
60 # make all your functions, whether exported or not;
61
62
63 sub getbranches {
64     my ($env) = @_;
65     my %branches;
66     my $dbh=&C4Connect;  
67     my $sth=$dbh->prepare("select * from branches");
68     $sth->execute;
69     while (my $branch=$sth->fetchrow_hashref) {
70 #       (next) if ($branch->{'branchcode'} eq 'TR');
71         $branches{$branch->{'branchcode'}}=$branch;
72     }
73     $dbh->disconnect;
74     return (\%branches);
75 }
76
77
78 sub getprinters {
79     my ($env) = @_;
80     my %printers;
81     my $dbh=&C4Connect;  
82     my $sth=$dbh->prepare("select * from printers");
83     $sth->execute;
84     while (my $printer=$sth->fetchrow_hashref) {
85         $printers{$printer->{'printqueue'}}=$printer;
86     }
87     $dbh->disconnect;
88     return (\%printers);
89 }
90
91
92
93 sub getpatroninformation {
94 # returns 
95     my ($env, $borrowernumber,$cardnumber) = @_;
96     my $dbh=&C4Connect;  
97     my $sth;
98     open O, ">>/root/tkcirc.out";
99     print O "Looking up patron $borrowernumber / $cardnumber\n";
100     if ($borrowernumber) {
101         $sth=$dbh->prepare("select * from borrowers where borrowernumber=$borrowernumber");
102     } elsif ($cardnumber) {
103         $sth=$dbh->prepare("select * from borrowers where cardnumber=$cardnumber");
104     } else {
105          # error condition.  This subroutine must be called with either a
106          # borrowernumber or a card number.
107         $env->{'apierror'}="invalid borrower information passed to getpatroninformation subroutine";
108          return();
109     }
110     $sth->execute;
111     my $borrower=$sth->fetchrow_hashref;
112     my $flags=patronflags($env, $borrower, $dbh);
113     $sth->finish;
114     $dbh->disconnect;
115     print O "$borrower->{'surname'} <---\n";
116     close O;
117     $borrower->{'flags'}=$flags;
118     return($borrower, $flags);
119 }
120
121
122
123
124
125 sub getiteminformation {
126 # returns a hash of item information given either the itemnumber or the barcode
127     my ($env, $itemnumber, $barcode) = @_;
128     my $dbh=&C4Connect;
129     my $sth;
130     if ($itemnumber) {
131         $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.itemnumber=$itemnumber and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
132     } elsif ($barcode) {
133         my $q_barcode=$dbh->quote($barcode);
134         $sth=$dbh->prepare("select * from biblio,items,biblioitems where items.barcode=$q_barcode and biblio.biblionumber=items.biblionumber and biblioitems.biblioitemnumber = items.biblioitemnumber");
135     } else {
136         $env->{'apierror'}="getiteminformation() subroutine must be called with either an itemnumber or a barcode";
137         # Error condition.  
138         return();
139     }
140     $sth->execute;
141     my $iteminformation=$sth->fetchrow_hashref;
142     $sth->finish;
143     if ($iteminformation) {
144         $sth=$dbh->prepare("select date_due from issues where itemnumber=$iteminformation->{'itemnumber'} and isnull(returndate)");
145         $sth->execute;
146         my ($date_due) = $sth->fetchrow;
147         $iteminformation->{'date_due'}=$date_due;
148         $sth->finish;
149         #$iteminformation->{'dewey'}=~s/0*$//;
150         ($iteminformation->{'dewey'} == 0) && ($iteminformation->{'dewey'}='');
151         $sth=$dbh->prepare("select * from itemtypes where itemtype='$iteminformation->{'itemtype'}'");
152         $sth->execute;
153         my $itemtype=$sth->fetchrow_hashref;
154         $iteminformation->{'loanlength'}=$itemtype->{'loanlength'};
155         $sth->finish;
156     }
157     $dbh->disconnect;
158     return($iteminformation);
159 }
160
161 sub findborrower {
162 # returns an array of borrower hash references, given a cardnumber or a partial
163 # surname 
164     my ($env, $key) = @_;
165     my $dbh=&C4Connect;
166     my @borrowers;
167     my $q_key=$dbh->quote($key);
168     my $sth=$dbh->prepare("select * from borrowers where cardnumber=$q_key");
169     $sth->execute;
170     if ($sth->rows) {
171         my ($borrower)=$sth->fetchrow_hashref;
172         push (@borrowers, $borrower);
173     } else {
174         $q_key=$dbh->quote("$key%");
175         $sth->finish;
176         $sth=$dbh->prepare("select * from borrowers where surname like $q_key");
177         $sth->execute;
178         while (my $borrower = $sth->fetchrow_hashref) {
179             push (@borrowers, $borrower);
180         }
181     }
182     $sth->finish;
183     $dbh->disconnect;
184     return(\@borrowers);
185 }
186
187
188 sub issuebook {
189     my ($env, $patroninformation, $barcode, $responses, $date) = @_;
190     my $dbh=&C4Connect;
191     my $iteminformation=getiteminformation($env, 0, $barcode);
192     my ($datedue);
193     my ($rejected,$question,$defaultanswer,$questionnumber, $noissue);
194     SWITCH: {
195         if ($patroninformation->{'gonenoaddress'}) {
196             $rejected="Patron is gone, with no known address.";
197             last SWITCH;
198         }
199         if ($patroninformation->{'lost'}) {
200             $rejected="Patron's card has been reported lost.";
201             last SWITCH;
202         }
203         if ($patroninformation->{'debarred'}) {
204             $rejected="Patron is Debarred";
205             last SWITCH;
206         }
207         my $amount = checkaccount($env,$patroninformation->{'borrowernumber'}, $dbh,$date);
208         if ($amount>5 && $patroninformation->{'categorycode'} ne 'L' &&
209 $patroninformation->{'categorycode'} ne 'W' &&
210 $patroninformation->{'categorycode'} ne 'I'
211 && $patroninformation->{'categorycode'} ne 'B' &&
212 $patroninformation->{'categorycode'} ne 'P') {
213             $rejected=sprintf "Patron owes \$%.02f.", $amount;
214             last SWITCH;
215         }
216         unless ($iteminformation) {
217             $rejected="$barcode is not a valid barcode.";
218             last SWITCH;
219         }
220         if ($iteminformation->{'notforloan'} == 1) {
221             $rejected="Item not for loan.";
222             last SWITCH;
223         }
224         if ($iteminformation->{'wthdrawn'} == 1) {
225             $rejected="Item withdrawn.";
226             last SWITCH;
227         }
228         if ($iteminformation->{'restricted'} == 1) {
229             $rejected="Restricted item.";
230             last SWITCH;
231         }
232         if ($iteminformation->{'itemtype'} eq 'REF') {
233             $rejected="Reference item:  Not for loan.";
234             last SWITCH;
235         }
236         my ($currentborrower) = currentborrower($env, $iteminformation->{'itemnumber'}, $dbh);
237         if ($currentborrower eq $patroninformation->{'borrowernumber'}) {
238 # Already issued to current borrower
239             my ($renewstatus) = renewstatus($env,$dbh,$patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'});
240             if ($renewstatus == 0) {
241                 $rejected="No more renewals allowed for this item.";
242                 last SWITCH;
243             } else {
244                 if ($responses->{4} eq '') {
245                     $questionnumber=4;
246                     $question="Book is issued to this borrower.\nRenew?";
247                     $defaultanswer='Y';
248                     last SWITCH;
249                 } elsif ($responses->{4} eq 'Y') {
250                     my $charge=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'});
251                     if ($charge > 0) {
252                         createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'}, $charge);
253                         $iteminformation->{'charge'}=$charge;
254                     }
255                     &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'});
256                     renewbook($env,$dbh, $patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'});
257                     $noissue=1;
258                 } else {
259                     $rejected=-1;
260                     last SWITCH;
261                 }
262             }
263         } elsif ($currentborrower ne '') {
264             my ($currborrower, $cbflags)=getpatroninformation($env,$currentborrower,0);
265             if ($responses->{1} eq '') {
266                 $questionnumber=1;
267                 $question="Issued to $currborrower->{'firstname'} $currborrower->{'surname'} ($currborrower->{'cardnumber'}).\nMark as returned?";
268                 $defaultanswer='Y';
269                 last SWITCH;
270             } elsif ($responses->{1} eq 'Y') {
271                 returnbook($env,$iteminformation->{'barcode'});
272             } else {
273                 $rejected=-1;
274                 last SWITCH;
275             }
276         }
277
278         my ($resbor, $resrec) = checkreserve($env, $dbh, $iteminformation->{'itemnumber'});
279
280         if ($resbor eq $patroninformation->{'borrowernumber'}) {
281              my $rquery = "update reserves set found = 'F' where reservedate = '$resrec->{'reservedate'}' and borrowernumber = '$resrec->{'borrowernumber'}' and biblionumber = '$resrec->{'biblionumber'}'";
282              my $rsth = $dbh->prepare($rquery);
283              $rsth->execute;
284              $rsth->finish;
285         } elsif ($resbor ne "") {
286             my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
287             if ($responses->{2} eq '') {
288                 $questionnumber=2;
289                 $question="Reserved for $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}) since $resrec->{'reservedate'}\nAllow issue?";
290                 $defaultanswer='N';
291                 last SWITCH;
292             } elsif ($responses->{2} eq 'N') {
293                 #printreserve($env, $resrec, $resborrower, $iteminformation);
294                 $rejected=-1;
295                 last SWITCH;
296             } else {
297                 if ($responses->{3} eq '') {
298                     $questionnumber=3;
299                     $question="Cancel reserve for $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})?";
300                     $defaultanswer='N';
301                     last SWITCH;
302                 } elsif ($responses->{3} eq 'Y') {
303                     my $rquery = "update reserves set found = 'F' where reservedate = '$resrec->{'reservedate'}' and borrowernumber = '$resrec->{'borrowernumber'}' and biblionumber = '$resrec->{'biblionumber'}'";
304                     my $rsth = $dbh->prepare($rquery);
305                     $rsth->execute;
306                     $rsth->finish;
307                 }
308             }
309         }
310     }
311     my $dateduef;
312     unless (($question) || ($rejected) || ($noissue)) {
313         my $loanlength=21;
314         if ($iteminformation->{'loanlength'}) {
315             $loanlength=$iteminformation->{'loanlength'};
316         }
317         my $ti=time;
318         my $datedue=time+($loanlength)*86400;
319         my @datearr = localtime($datedue);
320         $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
321         if ($env->{'datedue'}) {
322             $dateduef=$env->{'datedue'};
323         }
324         $dateduef=~ s/2001\-4\-25/2001\-4\-26/;
325         my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values ($patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'}, '$dateduef', '$env->{'branchcode'}')");
326         $sth->execute;
327         $sth->finish;
328         $iteminformation->{'issues'}++;
329         $sth=$dbh->prepare("update items set issues=$iteminformation->{'issues'} where itemnumber=$iteminformation->{'itemnumber'}");
330         $sth->execute;
331         $sth->finish;
332         my $charge=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'});
333         if ($charge > 0) {
334             createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'}, $charge);
335             $iteminformation->{'charge'}=$charge;
336         }
337         &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'});
338     }
339     my $message='';
340     if ($iteminformation->{'charge'}) {
341         $message=sprintf "Rental charge of \$%.02f applies.", $iteminformation->{'charge'};
342     }
343     $dbh->disconnect;
344     return ($iteminformation, $dateduef, $rejected, $question, $questionnumber, $defaultanswer, $message);
345 }
346
347 sub updateitemlost{
348   my ($dbh,$itemno)=@_;
349   my $query="update items set itemlost=0 where itemnumber=$itemno";
350   my $sth=$dbh->prepare($query);
351   $sth->execute;
352   $sth->finish;
353 }
354
355 sub returnbook {
356     my ($env, $barcode) = @_;
357     my ($messages, $overduecharge);
358     my $dbh=&C4Connect;
359     my ($iteminformation) = getiteminformation($env, 0, $barcode);
360     my $borrower;
361     if ($iteminformation) {
362         my $sth=$dbh->prepare("select * from issues where (itemnumber='$iteminformation->{'itemnumber'}') and (returndate is null)");
363         $sth->execute;
364         my ($currentborrower) = currentborrower($env, $iteminformation->{'itemnumber'}, $dbh);
365         updatelastseen($env,$dbh,$iteminformation->{'itemnumber'});
366         updateitemlost($dbh,$iteminformation->{'itemnumber'});
367         if ($currentborrower) {
368             ($borrower)=getpatroninformation($env,$currentborrower,0);
369             my @datearr = localtime(time);
370             my $dateret = (1900+$datearr[5])."-".$datearr[4]."-".$datearr[3];
371             my $query = "update issues set returndate = now(), branchcode ='$env->{'branchcode'}' where (borrowernumber = $borrower->{'borrowernumber'}) and (itemnumber = $iteminformation->{'itemnumber'}) and (returndate is null)";
372             my $sth = $dbh->prepare($query);
373             $sth->execute;
374             $sth->finish;
375
376
377             # check for overdue fine
378
379             $overduecharge;
380             $sth=$dbh->prepare("select * from accountlines where (borrowernumber=$borrower->{'borrowernumber'}) and (itemnumber = $iteminformation->{'itemnumber'}) and (accounttype='FU' or accounttype='O')");
381             $sth->execute;
382             # alter fine to show that the book has been returned
383             if (my $data = $sth->fetchrow_hashref) {
384                 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber=$borrower->{'borrowernumber'}) and (itemnumber=$iteminformation->{'itemnumber'}) and (acccountno='$data->{'accountno'}')");
385                 $usth->execute();
386                 $usth->finish();
387                 $overduecharge=$data->{'amountoutstanding'};
388             }
389             $sth->finish;
390          }
391          if ($iteminformation->{'itemlost'} eq '1'){
392             # check for charge made for lost book
393             my $query="select * from accountlines where (itemnumber =
394             $iteminformation->{'itemnumber'}) and (accounttype='L' or accounttype='Rep') 
395             order by date desc";
396 #           print $query;
397             $sth=$dbh->prepare($query);
398             $sth->execute;
399             if (my $data = $sth->fetchrow_hashref) {
400                 # writeoff this amount
401                 my $offset;
402                 my $amount = $data->{'amount'};
403                 my $acctno = $data->{'accountno'};
404                 my $amountleft;
405 #               print $amount;
406                 if ($data->{'amountoutstanding'} == $amount) {
407                     $offset = $data->{'amount'};
408                     $amountleft = 0;
409                 } else {
410                     $offset = $amount - $data->{'amountoutstanding'};
411                     $amountleft = $data->{'amountoutstanding'} - $amount;
412                 }
413                 my $uquery = "update accountlines
414                   set accounttype = 'LR',amountoutstanding='0'
415                   where (borrowernumber = $data->{'borrowernumber'})
416                   and (itemnumber = $iteminformation->{'itemnumber'})
417                   and (accountno = '$acctno') ";
418 #               print $uquery;
419                 my $usth = $dbh->prepare($uquery);
420                 $usth->execute();
421                 $usth->finish;
422                 my $nextaccntno = getnextacctno($env,$data->{'borrowernumber'},$dbh);
423                 my $desc="Book Returned ".$iteminformation->{'barcode'};
424                 $uquery = "insert into accountlines
425                   (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
426                   values ($data->{'borrowernumber'},$nextaccntno,now(),0-$amount,'$desc',
427                   'CR',$amountleft)";
428                 $usth = $dbh->prepare($uquery);
429 #               print $uquery;
430                 $usth->execute;
431                 $usth->finish;
432                 $uquery = "insert into accountoffsets
433                   (borrowernumber, accountno, offsetaccount,  offsetamount)
434                   values ($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset)";
435                 $usth = $dbh->prepare($uquery);
436                 $usth->execute;
437                 $usth->finish;
438                 $uquery="update items set itemnotes='' where itemnumber=$iteminformation->{'itemnumber'}";
439                 $usth = $dbh->prepare($uquery);
440                 $usth->execute;
441                 $usth->finish;
442             }
443             $sth->finish;
444         }       
445         my ($resfound,$resrec) = find_reserves($env, $dbh, $iteminformation->{'itemnumber'});
446         if ($resfound eq 'y') {
447            my ($borrower) = getpatroninformation($env,$resrec->{'borrowernumber'},0);
448            #printreserve($env,$resrec,$resborrower,$itemrec);
449            my ($branches) = getbranches();
450            my $branchname=$branches->{$resrec->{'branchcode'}}->{'branchname'};
451            push (@$messages, "<b><font color=red>RESERVED</font></b> for collection by $borrower->{'firstname'} $borrower->{'surname'} ($borrower->{'cardnumber'}) at $branchname");
452         }
453         UpdateStats($env,$env->{'branchcode'},'return','0','',$iteminformation->{'itemnumber'});
454     }
455     $dbh->disconnect;
456     return ($iteminformation, $borrower, $messages, $overduecharge);
457 }
458
459
460 sub patronflags {
461 # Original subroutine for Circ2.pm
462     my %flags;
463     my ($env,$patroninformation,$dbh) = @_;
464     my $amount = checkaccount($env,$patroninformation->{'borrowernumber'}, $dbh);
465     if ($amount>0) { 
466         my %flaginfo;
467         $flaginfo{'message'}=sprintf "Patron owes \$%.02f", $amount; 
468         if ($amount>5) {
469             $flaginfo{'noissues'}=1;
470         }
471         $flags{'CHARGES'}=\%flaginfo;
472     }
473     if ($patroninformation->{'gonenoaddress'} == 1) {
474         my %flaginfo;
475         $flaginfo{'message'}='Borrower has no valid address.'; 
476         $flaginfo{'noissues'}=1;
477         $flags{'GNA'}=\%flaginfo;
478     }
479     if ($patroninformation->{'lost'} == 1) {
480         my %flaginfo;
481         $flaginfo{'message'}='Borrower\'s card reported lost.'; 
482         $flaginfo{'noissues'}=1;
483         $flags{'LOST'}=\%flaginfo;
484     }
485     if ($patroninformation->{'debarred'} == 1) {
486         my %flaginfo;
487         $flaginfo{'message'}='Borrower is Debarred.'; 
488         $flaginfo{'noissues'}=1;
489         $flags{'DBARRED'}=\%flaginfo;
490     }
491     if ($patroninformation->{'borrowernotes'}) {
492         my %flaginfo;
493         $flaginfo{'message'}="$patroninformation->{'borrowernotes'}";
494         $flags{'NOTES'}=\%flaginfo;
495     }
496     my ($odues, $itemsoverdue) = checkoverdues($env,$patroninformation->{'borrowernumber'},$dbh);
497     if ($odues > 0) {
498         my %flaginfo;
499         $flaginfo{'message'}="Yes";
500         $flaginfo{'itemlist'}=$itemsoverdue;
501         foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
502             $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
503         }
504         $flags{'ODUES'}=\%flaginfo;
505     }
506     my ($nowaiting,$itemswaiting) = checkwaiting($env,$dbh,$patroninformation->{'borrowernumber'});
507     if ($nowaiting>0) {
508         my %flaginfo;
509         $flaginfo{'message'}="Reserved items available";
510         $flaginfo{'itemlist'}=$itemswaiting;
511         $flaginfo{'itemfields'}=['barcode', 'title', 'author', 'dewey', 'subclass', 'holdingbranch'];
512         $flags{'WAITING'}=\%flaginfo;
513     }
514     my $flag;
515     my $key;
516     return(\%flags);
517 }
518
519
520 sub checkoverdues {
521 # From Main.pm, modified to return a list of overdueitems, in addition to a count
522   #checks whether a borrower has overdue items
523   my ($env,$bornum,$dbh)=@_;
524   my @datearr = localtime;
525   my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
526   my @overdueitems;
527   my $count=0;
528   my $query = "Select * from issues,biblio,biblioitems,items where items.biblioitemnumber=biblioitems.biblioitemnumber and items.biblionumber=biblio.biblionumber and issues.itemnumber=items.itemnumber and borrowernumber=$bornum and returndate is NULL and date_due < '$today'";
529   my $sth=$dbh->prepare($query);
530   $sth->execute;
531   while (my $data = $sth->fetchrow_hashref) {
532       push (@overdueitems, $data);
533       $count++;
534   }
535   $sth->finish;
536   return ($count, \@overdueitems);
537 }
538
539 sub updatelastseen {
540 # Stolen from Returns.pm
541     my ($env,$dbh,$itemnumber)= @_;
542     my $br = $env->{'branchcode'};
543     my $query = "update items 
544     set datelastseen = now(), holdingbranch = '$br'
545     where (itemnumber = '$itemnumber')";
546     my $sth = $dbh->prepare($query);
547     $sth->execute;
548     $sth->finish;
549
550
551 sub currentborrower {
552 # Original subroutine for Circ2.pm
553     my ($env, $itemnumber, $dbh) = @_;
554     my $q_itemnumber=$dbh->quote($itemnumber);
555     my $sth=$dbh->prepare("select borrowers.borrowernumber from
556     issues,borrowers where issues.itemnumber=$q_itemnumber and
557     issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
558     NULL");
559     $sth->execute;
560     my ($previousborrower)=$sth->fetchrow;
561     return($previousborrower);
562 }
563
564 sub checkreserve {
565 # Stolen from Main.pm
566   # Check for reserves for biblio 
567   my ($env,$dbh,$itemnum)=@_;
568   my $resbor = "";
569   my $query = "select * from reserves,items 
570     where (items.itemnumber = '$itemnum')
571     and (reserves.cancellationdate is NULL)
572     and (items.biblionumber = reserves.biblionumber)
573     and ((reserves.found = 'W')
574     or (reserves.found is null)) 
575     order by priority";
576   my $sth = $dbh->prepare($query);
577   $sth->execute();
578   my $resrec;
579   my $data=$sth->fetchrow_hashref;
580   while ($data && $resbor eq '') {
581     $resrec=$data;
582     my $const = $data->{'constrainttype'};
583     if ($const eq "a") {
584       $resbor = $data->{'borrowernumber'};
585     } else {
586       my $found = 0;
587       my $cquery = "select * from reserveconstraints,items 
588          where (borrowernumber='$data->{'borrowernumber'}') 
589          and reservedate='$data->{'reservedate'}'
590          and reserveconstraints.biblionumber='$data->{'biblionumber'}'
591          and (items.itemnumber=$itemnum and 
592          items.biblioitemnumber = reserveconstraints.biblioitemnumber)";
593       my $csth = $dbh->prepare($cquery);
594       $csth->execute;
595       if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
596       if ($const eq 'o') {
597         if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
598       } else {
599         if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
600       }
601       $csth->finish();
602     }
603     $data=$sth->fetchrow_hashref;
604   }
605   $sth->finish;
606   return ($resbor,$resrec);
607 }
608
609 sub currentissues {
610 # New subroutine for Circ2.pm
611     my ($env, $borrower) = @_;
612     my $dbh=&C4Connect;
613     my %currentissues;
614     my $counter=1;
615     my $borrowernumber=$borrower->{'borrowernumber'};
616     my $crit='';
617     if ($env->{'todaysissues'}) {
618         my @datearr = localtime(time());
619         my $today = (1900+$datearr[5]).sprintf "0%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
620         $crit=" and issues.timestamp like '$today%' ";
621     }
622     if ($env->{'nottodaysissues'}) {
623         my @datearr = localtime(time());
624         my $today = (1900+$datearr[5]).sprintf "0%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
625         $crit=" and !(issues.timestamp like '$today%') ";
626     }
627     my $select="select * from issues,items,biblioitems,biblio where
628     borrowernumber='$borrowernumber' and issues.itemnumber=items.itemnumber and
629     items.biblionumber=biblio.biblionumber and
630     items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
631     $crit order by issues.timestamp desc";
632 #    print $select;
633     my $sth=$dbh->prepare($select);
634     $sth->execute;
635     while (my $data = $sth->fetchrow_hashref) {
636         $data->{'dewey'}=~s/0*$//;
637         ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
638         my @datearr = localtime(time());
639         my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]
640         +1)).sprintf ("%0.2d", $datearr[3]);
641         my $datedue=$data->{'date_due'};
642         $datedue=~s/-//g;
643         if ($datedue < $todaysdate) {
644             $data->{'overdue'}=1;
645         }
646         my $itemnumber=$data->{'itemnumber'};
647         $currentissues{$counter}=$data;
648         $counter++;
649     }
650     $sth->finish;
651     $dbh->disconnect;
652     return(\%currentissues);
653 }
654
655 sub checkwaiting {
656 #Stolen from Main.pm
657   # check for reserves waiting
658   my ($env,$dbh,$bornum)=@_;
659   my @itemswaiting;
660   my $query = "select * from reserves
661     where (borrowernumber = '$bornum')
662     and (reserves.found='W') and cancellationdate is NULL";
663   my $sth = $dbh->prepare($query);
664   $sth->execute();
665   my $cnt=0;
666   if (my $data=$sth->fetchrow_hashref) {
667     @itemswaiting[$cnt] =$data;
668     $cnt ++
669   }
670   $sth->finish;
671   return ($cnt,\@itemswaiting);
672 }
673
674
675 sub checkaccount  {
676 # Stolen from Accounts.pm
677   #take borrower number
678   #check accounts and list amounts owing
679   my ($env,$bornumber,$dbh,$date)=@_;
680   my $select="Select sum(amountoutstanding) from accountlines where
681   borrowernumber=$bornumber and amountoutstanding<>0";
682   if ($date ne ''){
683     $select.=" and date < '$date'";
684   }
685 #  print $select;
686   my $sth=$dbh->prepare($select);
687   $sth->execute;
688   my $total=0;
689   while (my $data=$sth->fetchrow_hashref){
690     $total=$total+$data->{'sum(amountoutstanding)'};
691   }
692   $sth->finish;
693   # output(1,2,"borrower owes $total");
694   #if ($total > 0){
695   #  # output(1,2,"borrower owes $total");
696   #  if ($total > 5){
697   #    reconcileaccount($env,$dbh,$bornumber,$total);
698   #  }
699   #}
700   #  pause();
701   return($total);
702 }    
703
704 sub renewstatus {
705 # Stolen from Renewals.pm
706   # check renewal status
707   my ($env,$dbh,$bornum,$itemno)=@_;
708   my $renews = 1;
709   my $renewokay = 0;
710   my $q1 = "select * from issues 
711     where (borrowernumber = '$bornum')
712     and (itemnumber = '$itemno') 
713     and returndate is null";
714   my $sth1 = $dbh->prepare($q1);
715   $sth1->execute;
716   if (my $data1 = $sth1->fetchrow_hashref) {
717     my $q2 = "select renewalsallowed from items,biblioitems,itemtypes
718        where (items.itemnumber = '$itemno')
719        and (items.biblioitemnumber = biblioitems.biblioitemnumber) 
720        and (biblioitems.itemtype = itemtypes.itemtype)";
721     my $sth2 = $dbh->prepare($q2);
722     $sth2->execute;     
723     if (my $data2=$sth2->fetchrow_hashref) {
724       $renews = $data2->{'renewalsallowed'};
725     }
726     if ($renews > $data1->{'renewals'}) {
727       $renewokay = 1;
728     }
729     $sth2->finish;
730   }   
731   $sth1->finish;
732   return($renewokay);    
733 }
734
735 sub renewbook {
736 # Stolen from Renewals.pm
737   # mark book as renewed
738   my ($env,$dbh,$bornum,$itemno,$datedue)=@_;
739   $datedue=$env->{'datedue'};
740   if ($datedue eq "" ) {    
741     my $loanlength=21;
742     my $query= "Select * from biblioitems,items,itemtypes
743        where (items.itemnumber = '$itemno')
744        and (biblioitems.biblioitemnumber = items.biblioitemnumber)
745        and (biblioitems.itemtype = itemtypes.itemtype)";
746     my $sth=$dbh->prepare($query);
747     $sth->execute;
748     if (my $data=$sth->fetchrow_hashref) {
749       $loanlength = $data->{'loanlength'}
750     }
751     $sth->finish;
752     my $ti = time;
753     my $datedu = time + ($loanlength * 86400);
754     my @datearr = localtime($datedu);
755     $datedue = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
756   }
757   my @date = split("-",$datedue);
758   my $odatedue = (@date[2]+0)."-".(@date[1]+0)."-".@date[0];
759   my $issquery = "select * from issues where borrowernumber='$bornum' and
760     itemnumber='$itemno' and returndate is null";
761   my $sth=$dbh->prepare($issquery);
762   $sth->execute;
763   my $issuedata=$sth->fetchrow_hashref;
764   $sth->finish;
765   my $renews = $issuedata->{'renewals'} +1;
766   my $updquery = "update issues 
767     set date_due = '$datedue', renewals = '$renews'
768     where borrowernumber='$bornum' and
769     itemnumber='$itemno' and returndate is null";
770   my $sth=$dbh->prepare($updquery);
771   
772   $sth->execute;
773   $sth->finish;
774   return($odatedue);
775 }
776
777 sub calc_charges {
778 # Stolen from Issues.pm
779 # calculate charges due
780     my ($env, $dbh, $itemno, $bornum)=@_;
781     my $charge=0;
782     my $item_type;
783     my $q1 = "select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes where (items.itemnumber ='$itemno') and (biblioitems.biblioitemnumber = items.biblioitemnumber) and (biblioitems.itemtype = itemtypes.itemtype)";
784     my $sth1= $dbh->prepare($q1);
785     $sth1->execute;
786     if (my $data1=$sth1->fetchrow_hashref) {
787         $item_type = $data1->{'itemtype'};
788         $charge = $data1->{'rentalcharge'};
789         my $q2 = "select rentaldiscount from borrowers,categoryitem 
790         where (borrowers.borrowernumber = '$bornum') 
791         and (borrowers.categorycode = categoryitem.categorycode)
792         and (categoryitem.itemtype = '$item_type')";
793         my $sth2=$dbh->prepare($q2);
794         $sth2->execute;
795         if (my $data2=$sth2->fetchrow_hashref) {
796             my $discount = $data2->{'rentaldiscount'};
797             $charge = ($charge *(100 - $discount)) / 100;
798         }
799         $sth2->{'finish'};
800     }      
801     $sth1->finish;
802     return ($charge);
803 }
804
805 sub createcharge {
806 #Stolen from Issues.pm
807     my ($env,$dbh,$itemno,$bornum,$charge) = @_;
808     my $nextaccntno = getnextacctno($env,$bornum,$dbh);
809     my $query = "insert into accountlines (borrowernumber,itemnumber,accountno,date,amount, description,accounttype,amountoutstanding) values ($bornum,$itemno,$nextaccntno,now(),$charge,'Rental','Rent',$charge)";
810     my $sth = $dbh->prepare($query);
811     $sth->execute;
812     $sth->finish;
813 }
814
815
816 sub getnextacctno {
817 # Stolen from Accounts.pm
818     my ($env,$bornumber,$dbh)=@_;
819     my $nextaccntno = 1;
820     my $query = "select * from accountlines where (borrowernumber = '$bornumber') order by accountno desc";
821     my $sth = $dbh->prepare($query);
822     $sth->execute;
823     if (my $accdata=$sth->fetchrow_hashref){
824         $nextaccntno = $accdata->{'accountno'} + 1;
825     }
826     $sth->finish;
827     return($nextaccntno);
828 }
829
830 sub find_reserves {
831 # Stolen from Returns.pm
832   my ($env,$dbh,$itemno) = @_;
833   my ($itemdata) = getiteminformation($env,$itemno,0);
834   my $query = "select * from reserves where 
835   ((reserves.found = 'W')                                   
836   or (reserves.found is null)) 
837   and biblionumber = $itemdata->{'biblionumber'} and cancellationdate is NULL
838   order by priority,reservedate ";
839   my $sth = $dbh->prepare($query);
840   $sth->execute;
841   my $resfound = "n";
842   my $resrec;
843   my $lastrec;
844   while (($resrec=$sth->fetchrow_hashref) && ($resfound eq "n")) {
845       $lastrec=$resrec;
846     if ($resrec->{'found'} eq "W") {
847       if ($resrec->{'itemnumber'} eq $itemno) {
848         $resfound = "y";
849       }
850     } 
851     if ($resrec->{'constrainttype'} eq "a") {
852       $resfound = "y";
853     } else {
854       my $conquery = "select * from reserveconstraints where borrowernumber
855 = $resrec->{'borrowernumber'} and reservedate = '$resrec->{'reservedate'}' and biblionumber = $resrec->{'biblionumber'} and biblioitemnumber = $itemdata->{'biblioitemnumber'}";
856       my $consth = $dbh->prepare($conquery);
857       $consth->execute;
858       if (my $conrec=$consth->fetchrow_hashref) {
859         if ($resrec->{'constrainttype'} eq "o") {
860            $resfound = "y";
861          }
862       } else {
863         if ($resrec->{'constrainttype'} eq "e") {
864           $resfound = "y";
865         }
866       }
867       $consth->finish;
868     }
869     if ($resfound eq "y") {
870       my $updquery = "update reserves 
871         set found = 'W',itemnumber='$itemno'
872         where borrowernumber = $resrec->{'borrowernumber'}
873         and reservedate = '$resrec->{'reservedate'}'
874         and biblionumber = $resrec->{'biblionumber'}";
875       my $updsth = $dbh->prepare($updquery);
876       $updsth->execute;
877       $updsth->finish;
878       my $itbr = $resrec->{'branchcode'};
879       if ($resrec->{'branchcode'} ne $env->{'branchcode'}) {
880          my $updquery = "update items
881           set holdingbranch = 'TR'
882           where itemnumber = $itemno";
883         my $updsth = $dbh->prepare($updquery);
884         $updsth->execute;
885         $updsth->finish;
886       } 
887     }
888   }
889   $sth->finish;
890   return ($resfound,$lastrec);
891 }
892
893 END { }       # module clean-up code here (global destructor)