Making a change to the way charges are handled, the system originally worked such...
[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) {
209             $rejected=sprintf "Patron owes \$%.02f.", $amount;
210             last SWITCH;
211         }
212         unless ($iteminformation) {
213             $rejected="$barcode is not a valid barcode.";
214             last SWITCH;
215         }
216         if ($iteminformation->{'notforloan'} == 1) {
217             $rejected="Item not for loan.";
218             last SWITCH;
219         }
220         if ($iteminformation->{'wthdrawn'} == 1) {
221             $rejected="Item withdrawn.";
222             last SWITCH;
223         }
224         if ($iteminformation->{'restricted'} == 1) {
225             $rejected="Restricted item.";
226             last SWITCH;
227         }
228         if ($iteminformation->{'itemtype'} eq 'REF') {
229             $rejected="Reference item:  Not for loan.";
230             last SWITCH;
231         }
232         my ($currentborrower) = currentborrower($env, $iteminformation->{'itemnumber'}, $dbh);
233         if ($currentborrower eq $patroninformation->{'borrowernumber'}) {
234 # Already issued to current borrower
235             my ($renewstatus) = renewstatus($env,$dbh,$patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'});
236             if ($renewstatus == 0) {
237                 $rejected="No more renewals allowed for this item.";
238                 last SWITCH;
239             } else {
240                 if ($responses->{4} eq '') {
241                     $questionnumber=4;
242                     $question="Book is issued to this borrower.\nRenew?";
243                     $defaultanswer='Y';
244                     last SWITCH;
245                 } elsif ($responses->{4} eq 'Y') {
246                     my $charge=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'});
247                     if ($charge > 0) {
248                         createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'}, $charge);
249                         $iteminformation->{'charge'}=$charge;
250                     }
251                     &UpdateStats($env,$env->{'branchcode'},'renew',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'});
252                     renewbook($env,$dbh, $patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'});
253                     $noissue=1;
254                 } else {
255                     $rejected=-1;
256                     last SWITCH;
257                 }
258             }
259         } elsif ($currentborrower ne '') {
260             my ($currborrower, $cbflags)=getpatroninformation($env,$currentborrower,0);
261             if ($responses->{1} eq '') {
262                 $questionnumber=1;
263                 $question="Issued to $currborrower->{'firstname'} $currborrower->{'surname'} ($currborrower->{'cardnumber'}).\nMark as returned?";
264                 $defaultanswer='Y';
265                 last SWITCH;
266             } elsif ($responses->{1} eq 'Y') {
267                 returnbook($env,$iteminformation->{'barcode'});
268             } else {
269                 $rejected=-1;
270                 last SWITCH;
271             }
272         }
273
274         my ($resbor, $resrec) = checkreserve($env, $dbh, $iteminformation->{'itemnumber'});
275
276         if ($resbor eq $patroninformation->{'borrowernumber'}) {
277              my $rquery = "update reserves set found = 'F' where reservedate = '$resrec->{'reservedate'}' and borrowernumber = '$resrec->{'borrowernumber'}' and biblionumber = '$resrec->{'biblionumber'}'";
278              my $rsth = $dbh->prepare($rquery);
279              $rsth->execute;
280              $rsth->finish;
281         } elsif ($resbor ne "") {
282             my ($resborrower, $flags)=getpatroninformation($env, $resbor,0);
283             if ($responses->{2} eq '') {
284                 $questionnumber=2;
285                 $question="Reserved for $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'}) since $resrec->{'reservedate'}\nAllow issue?";
286                 $defaultanswer='N';
287                 last SWITCH;
288             } elsif ($responses->{2} eq 'N') {
289                 #printreserve($env, $resrec, $resborrower, $iteminformation);
290                 $rejected=-1;
291                 last SWITCH;
292             } else {
293                 if ($responses->{3} eq '') {
294                     $questionnumber=3;
295                     $question="Cancel reserve for $resborrower->{'firstname'} $resborrower->{'surname'} ($resborrower->{'cardnumber'})?";
296                     $defaultanswer='N';
297                     last SWITCH;
298                 } elsif ($responses->{3} eq 'Y') {
299                     my $rquery = "update reserves set found = 'F' where reservedate = '$resrec->{'reservedate'}' and borrowernumber = '$resrec->{'borrowernumber'}' and biblionumber = '$resrec->{'biblionumber'}'";
300                     my $rsth = $dbh->prepare($rquery);
301                     $rsth->execute;
302                     $rsth->finish;
303                 }
304             }
305         }
306     }
307     my $dateduef;
308     unless (($question) || ($rejected) || ($noissue)) {
309         my $loanlength=21;
310         if ($iteminformation->{'loanlength'}) {
311             $loanlength=$iteminformation->{'loanlength'};
312         }
313         my $ti=time;
314         my $datedue=time+($loanlength)*86400;
315         my @datearr = localtime($datedue);
316         $dateduef = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
317         if ($env->{'datedue'}) {
318             $dateduef=$env->{'datedue'};
319         }
320         $dateduef=~ s/2001\-4\-25/2001\-4\-26/;
321         my $sth=$dbh->prepare("insert into issues (borrowernumber, itemnumber, date_due, branchcode) values ($patroninformation->{'borrowernumber'}, $iteminformation->{'itemnumber'}, '$dateduef', '$env->{'branchcode'}')");
322         $sth->execute;
323         $sth->finish;
324         $iteminformation->{'issues'}++;
325         $sth=$dbh->prepare("update items set issues=$iteminformation->{'issues'} where itemnumber=$iteminformation->{'itemnumber'}");
326         $sth->execute;
327         $sth->finish;
328         my $charge=calc_charges($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'});
329         if ($charge > 0) {
330             createcharge($env, $dbh, $iteminformation->{'itemnumber'}, $patroninformation->{'borrowernumber'}, $charge);
331             $iteminformation->{'charge'}=$charge;
332         }
333         &UpdateStats($env,$env->{'branchcode'},'issue',$charge,'',$iteminformation->{'itemnumber'},$iteminformation->{'itemtype'});
334     }
335     my $message='';
336     if ($iteminformation->{'charge'}) {
337         $message=sprintf "Rental charge of \$%.02f applies.", $iteminformation->{'charge'};
338     }
339     $dbh->disconnect;
340     return ($iteminformation, $dateduef, $rejected, $question, $questionnumber, $defaultanswer, $message);
341 }
342
343
344 sub returnbook {
345     my ($env, $barcode) = @_;
346     my ($messages, $overduecharge);
347     my $dbh=&C4Connect;
348     my ($iteminformation) = getiteminformation($env, 0, $barcode);
349     my $borrower;
350     if ($iteminformation) {
351         my $sth=$dbh->prepare("select * from issues where (itemnumber='$iteminformation->{'itemnumber'}') and (returndate is null)");
352         $sth->execute;
353         my ($currentborrower) = currentborrower($env, $iteminformation->{'itemnumber'}, $dbh);
354         updatelastseen($env,$dbh,$iteminformation->{'itemnumber'});
355         if ($currentborrower) {
356             ($borrower)=getpatroninformation($env,$currentborrower,0);
357             my @datearr = localtime(time);
358             my $dateret = (1900+$datearr[5])."-".$datearr[4]."-".$datearr[3];
359             my $query = "update issues set returndate = now(), branchcode ='$env->{'branchcode'}' where (borrowernumber = $borrower->{'borrowernumber'}) and (itemnumber = $iteminformation->{'itemnumber'}) and (returndate is null)";
360             my $sth = $dbh->prepare($query);
361             $sth->execute;
362             $sth->finish;
363
364
365             # check for overdue fine
366
367             $overduecharge;
368             $sth=$dbh->prepare("select * from accountlines where (borrowernumber=$borrower->{'borrowernumber'}) and (itemnumber = $iteminformation->{'itemnumber'}) and (accounttype='FU' or accounttype='O')");
369             $sth->execute;
370             # alter fine to show that the book has been returned
371             if (my $data = $sth->fetchrow_hashref) {
372                 my $usth=$dbh->prepare("update accountlines set accounttype='F' where (borrowernumber=$borrower->{'borrowernumber'}) and (itemnumber=$iteminformation->{'itemnumber'}) and (acccountno='$data->{'accountno'}')");
373                 $usth->execute();
374                 $usth->finish();
375                 $overduecharge=$data->{'amountoutstanding'};
376             }
377             $sth->finish;
378             # check for charge made for lost book
379             $sth=$dbh->prepare("select * from accountlines where (borrowernumber=$borrower->{'borrowernumber'}) and (itemnumber = $iteminformation->{'itemnumber'}) and (accounttype='L')");
380             $sth->execute;
381             if (my $data = $sth->fetchrow_hashref) {
382                 # writeoff this amount
383                 my $offset;
384                 my $amount = $data->{'amount'};
385                 my $acctno = $data->{'accountno'};
386                 my $amountleft;
387                 if ($data->{'amountoutstanding'} == $amount) {
388                     $offset = $data->{'amount'};
389                     $amountleft = 0;
390                 } else {
391                     $offset = $amount - $data->{'amountoutstanding'};
392                     $amountleft = $data->{'amountoutstanding'} - $amount;
393                 }
394                 my $uquery = "update accountlines
395                   set accounttype = 'LR',amountoutstanding='0'
396                   where (borrowernumber = $borrower->{'borrowernumber'})
397                   and (itemnumber = $iteminformation->{'itemnumber'})
398                   and (accountno = '$acctno') ";
399                 my $usth = $dbh->prepare($uquery);
400                 $usth->execute();
401                 $usth->finish;
402                 my $nextaccntno = C4::Accounts::getnextacctno($env,$borrower->{'borrowernumber'},$dbh);
403                 $uquery = "insert into accountlines
404                   (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding)
405                   values ($borrower->{'borrowernumber'},$nextaccntno,now(),0-$amount,'Book Returned',
406                   'CR',$amountleft)";
407                 $usth = $dbh->prepare($uquery);
408                 $usth->execute;
409                 $usth->finish;
410                 $uquery = "insert into accountoffsets
411                   (borrowernumber, accountno, offsetaccount,  offsetamount)
412                   values ($borrower->{'borrowernumber'},$data->{'accountno'},$nextaccntno,$offset)";
413                 $usth = $dbh->prepare($uquery);
414                 $usth->execute;
415                 $usth->finish;
416             }
417             $sth->finish;
418         }
419         my ($resfound,$resrec) = find_reserves($env, $dbh, $iteminformation->{'itemnumber'});
420         if ($resfound eq 'y') {
421            my ($borrower) = getpatroninformation($env,$resrec->{'borrowernumber'},0);
422            #printreserve($env,$resrec,$resborrower,$itemrec);
423            my ($branches) = getbranches();
424            my $branchname=$branches->{$resrec->{'branchcode'}}->{'branchname'};
425            push (@$messages, "<b><font color=red>RESERVED</font></b> for collection by $borrower->{'firstname'} $borrower->{'surname'} ($borrower->{'cardnumber'}) at $branchname");
426         }
427         UpdateStats($env,$env->{'branchcode'},'return','0','',$iteminformation->{'itemnumber'});
428     }
429     $dbh->disconnect;
430     return ($iteminformation, $borrower, $messages, $overduecharge);
431 }
432
433
434 sub patronflags {
435 # Original subroutine for Circ2.pm
436     my %flags;
437     my ($env,$patroninformation,$dbh) = @_;
438     my $amount = checkaccount($env,$patroninformation->{'borrowernumber'}, $dbh);
439     if ($amount>0) { 
440         my %flaginfo;
441         $flaginfo{'message'}=sprintf "Patron owes \$%.02f", $amount; 
442         if ($amount>5) {
443             $flaginfo{'noissues'}=1;
444         }
445         $flags{'CHARGES'}=\%flaginfo;
446     }
447     if ($patroninformation->{'gonenoaddress'} == 1) {
448         my %flaginfo;
449         $flaginfo{'message'}='Borrower has no valid address.'; 
450         $flaginfo{'noissues'}=1;
451         $flags{'GNA'}=\%flaginfo;
452     }
453     if ($patroninformation->{'lost'} == 1) {
454         my %flaginfo;
455         $flaginfo{'message'}='Borrower\'s card reported lost.'; 
456         $flaginfo{'noissues'}=1;
457         $flags{'LOST'}=\%flaginfo;
458     }
459     if ($patroninformation->{'debarred'} == 1) {
460         my %flaginfo;
461         $flaginfo{'message'}='Borrower is Debarred.'; 
462         $flaginfo{'noissues'}=1;
463         $flags{'DBARRED'}=\%flaginfo;
464     }
465     if ($patroninformation->{'borrowernotes'}) {
466         my %flaginfo;
467         $flaginfo{'message'}="$patroninformation->{'borrowernotes'}";
468         $flags{'NOTES'}=\%flaginfo;
469     }
470     my ($odues, $itemsoverdue) = checkoverdues($env,$patroninformation->{'borrowernumber'},$dbh);
471     if ($odues > 0) {
472         my %flaginfo;
473         $flaginfo{'message'}="Yes";
474         $flaginfo{'itemlist'}=$itemsoverdue;
475         foreach (sort {$a->{'date_due'} cmp $b->{'date_due'}} @$itemsoverdue) {
476             $flaginfo{'itemlisttext'}.="$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
477         }
478         $flags{'ODUES'}=\%flaginfo;
479     }
480     my ($nowaiting,$itemswaiting) = checkwaiting($env,$dbh,$patroninformation->{'borrowernumber'});
481     if ($nowaiting>0) {
482         my %flaginfo;
483         $flaginfo{'message'}="Reserved items available";
484         $flaginfo{'itemlist'}=$itemswaiting;
485         $flaginfo{'itemfields'}=['barcode', 'title', 'author', 'dewey', 'subclass', 'holdingbranch'];
486         $flags{'WAITING'}=\%flaginfo;
487     }
488     my $flag;
489     my $key;
490     return(\%flags);
491 }
492
493
494 sub checkoverdues {
495 # From Main.pm, modified to return a list of overdueitems, in addition to a count
496   #checks whether a borrower has overdue items
497   my ($env,$bornum,$dbh)=@_;
498   my @datearr = localtime;
499   my $today = ($datearr[5] + 1900)."-".($datearr[4]+1)."-".$datearr[3];
500   my @overdueitems;
501   my $count=0;
502   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'";
503   my $sth=$dbh->prepare($query);
504   $sth->execute;
505   while (my $data = $sth->fetchrow_hashref) {
506       push (@overdueitems, $data);
507       $count++;
508   }
509   $sth->finish;
510   return ($count, \@overdueitems);
511 }
512
513 sub updatelastseen {
514 # Stolen from Returns.pm
515     my ($env,$dbh,$itemnumber)= @_;
516     my $br = $env->{'branchcode'};
517     my $query = "update items 
518     set datelastseen = now(), holdingbranch = '$br'
519     where (itemnumber = '$itemnumber')";
520     my $sth = $dbh->prepare($query);
521     $sth->execute;
522     $sth->finish;
523
524
525 sub currentborrower {
526 # Original subroutine for Circ2.pm
527     my ($env, $itemnumber, $dbh) = @_;
528     my $q_itemnumber=$dbh->quote($itemnumber);
529     my $sth=$dbh->prepare("select borrowers.borrowernumber from
530     issues,borrowers where issues.itemnumber=$q_itemnumber and
531     issues.borrowernumber=borrowers.borrowernumber and issues.returndate is
532     NULL");
533     $sth->execute;
534     my ($previousborrower)=$sth->fetchrow;
535     return($previousborrower);
536 }
537
538 sub checkreserve {
539 # Stolen from Main.pm
540   # Check for reserves for biblio 
541   my ($env,$dbh,$itemnum)=@_;
542   my $resbor = "";
543   my $query = "select * from reserves,items 
544     where (items.itemnumber = '$itemnum')
545     and (reserves.cancellationdate is NULL)
546     and (items.biblionumber = reserves.biblionumber)
547     and ((reserves.found = 'W')
548     or (reserves.found is null)) 
549     order by priority";
550   my $sth = $dbh->prepare($query);
551   $sth->execute();
552   my $resrec;
553   my $data=$sth->fetchrow_hashref;
554   while ($data && $resbor eq '') {
555     $resrec=$data;
556     my $const = $data->{'constrainttype'};
557     if ($const eq "a") {
558       $resbor = $data->{'borrowernumber'};
559     } else {
560       my $found = 0;
561       my $cquery = "select * from reserveconstraints,items 
562          where (borrowernumber='$data->{'borrowernumber'}') 
563          and reservedate='$data->{'reservedate'}'
564          and reserveconstraints.biblionumber='$data->{'biblionumber'}'
565          and (items.itemnumber=$itemnum and 
566          items.biblioitemnumber = reserveconstraints.biblioitemnumber)";
567       my $csth = $dbh->prepare($cquery);
568       $csth->execute;
569       if (my $cdata=$csth->fetchrow_hashref) {$found = 1;}
570       if ($const eq 'o') {
571         if ($found eq 1) {$resbor = $data->{'borrowernumber'};}
572       } else {
573         if ($found eq 0) {$resbor = $data->{'borrowernumber'};}
574       }
575       $csth->finish();
576     }
577     $data=$sth->fetchrow_hashref;
578   }
579   $sth->finish;
580   return ($resbor,$resrec);
581 }
582
583 sub currentissues {
584 # New subroutine for Circ2.pm
585     my ($env, $borrower) = @_;
586     my $dbh=&C4Connect;
587     my %currentissues;
588     my $counter=1;
589     my $borrowernumber=$borrower->{'borrowernumber'};
590     my $crit='';
591     if ($env->{'todaysissues'}) {
592         my @datearr = localtime(time());
593         my $today = (1900+$datearr[5]).sprintf "0%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
594         $crit=" and issues.timestamp like '$today%' ";
595     }
596     if ($env->{'nottodaysissues'}) {
597         my @datearr = localtime(time());
598         my $today = (1900+$datearr[5]).sprintf "0%02d", ($datearr[4]+1).sprintf "%02d", $datearr[3];
599         $crit=" and !(issues.timestamp like '$today%') ";
600     }
601     my $select="select * from issues,items,biblioitems,biblio where
602     borrowernumber=$borrowernumber and issues.itemnumber=items.itemnumber and
603     items.biblionumber=biblio.biblionumber and
604     items.biblioitemnumber=biblioitems.biblioitemnumber and returndate is null
605     $crit order by issues.timestamp desc";
606 #    print $select;
607     my $sth=$dbh->prepare($select);
608     $sth->execute;
609     while (my $data = $sth->fetchrow_hashref) {
610         $data->{'dewey'}=~s/0*$//;
611         ($data->{'dewey'} == 0) && ($data->{'dewey'}='');
612         my $datedue=$data->{'date_due'};
613         my $itemnumber=$data->{'itemnumber'};
614         $currentissues{$counter}=$data;
615         $counter++;
616     }
617     $sth->finish;
618     $dbh->disconnect;
619     return(\%currentissues);
620 }
621
622 sub checkwaiting {
623 #Stolen from Main.pm
624   # check for reserves waiting
625   my ($env,$dbh,$bornum)=@_;
626   my @itemswaiting;
627   my $query = "select * from reserves
628     where (borrowernumber = '$bornum')
629     and (reserves.found='W') and cancellationdate is NULL";
630   my $sth = $dbh->prepare($query);
631   $sth->execute();
632   my $cnt=0;
633   if (my $data=$sth->fetchrow_hashref) {
634     @itemswaiting[$cnt] =$data;
635     $cnt ++
636   }
637   $sth->finish;
638   return ($cnt,\@itemswaiting);
639 }
640
641
642 sub checkaccount  {
643 # Stolen from Accounts.pm
644   #take borrower number
645   #check accounts and list amounts owing
646   my ($env,$bornumber,$dbh,$date)=@_;
647   my $select="Select sum(amountoutstanding) from accountlines where
648   borrowernumber=$bornumber and amountoutstanding<>0";
649   if ($date ne ''){
650     $select.=" and date < '$date'";
651   }
652 #  print $select;
653   my $sth=$dbh->prepare($select);
654   $sth->execute;
655   my $total=0;
656   while (my $data=$sth->fetchrow_hashref){
657     $total=$total+$data->{'sum(amountoutstanding)'};
658   }
659   $sth->finish;
660   # output(1,2,"borrower owes $total");
661   #if ($total > 0){
662   #  # output(1,2,"borrower owes $total");
663   #  if ($total > 5){
664   #    reconcileaccount($env,$dbh,$bornumber,$total);
665   #  }
666   #}
667   #  pause();
668   return($total);
669 }    
670
671 sub renewstatus {
672 # Stolen from Renewals.pm
673   # check renewal status
674   my ($env,$dbh,$bornum,$itemno)=@_;
675   my $renews = 1;
676   my $renewokay = 0;
677   my $q1 = "select * from issues 
678     where (borrowernumber = '$bornum')
679     and (itemnumber = '$itemno') 
680     and returndate is null";
681   my $sth1 = $dbh->prepare($q1);
682   $sth1->execute;
683   if (my $data1 = $sth1->fetchrow_hashref) {
684     my $q2 = "select renewalsallowed from items,biblioitems,itemtypes
685        where (items.itemnumber = '$itemno')
686        and (items.biblioitemnumber = biblioitems.biblioitemnumber) 
687        and (biblioitems.itemtype = itemtypes.itemtype)";
688     my $sth2 = $dbh->prepare($q2);
689     $sth2->execute;     
690     if (my $data2=$sth2->fetchrow_hashref) {
691       $renews = $data2->{'renewalsallowed'};
692     }
693     if ($renews > $data1->{'renewals'}) {
694       $renewokay = 1;
695     }
696     $sth2->finish;
697   }   
698   $sth1->finish;
699   return($renewokay);    
700 }
701
702 sub renewbook {
703 # Stolen from Renewals.pm
704   # mark book as renewed
705   my ($env,$dbh,$bornum,$itemno,$datedue)=@_;
706   $datedue=$env->{'datedue'};
707   if ($datedue eq "" ) {    
708     my $loanlength=21;
709     my $query= "Select * from biblioitems,items,itemtypes
710        where (items.itemnumber = '$itemno')
711        and (biblioitems.biblioitemnumber = items.biblioitemnumber)
712        and (biblioitems.itemtype = itemtypes.itemtype)";
713     my $sth=$dbh->prepare($query);
714     $sth->execute;
715     if (my $data=$sth->fetchrow_hashref) {
716       $loanlength = $data->{'loanlength'}
717     }
718     $sth->finish;
719     my $ti = time;
720     my $datedu = time + ($loanlength * 86400);
721     my @datearr = localtime($datedu);
722     $datedue = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
723   }
724   my @date = split("-",$datedue);
725   my $odatedue = (@date[2]+0)."-".(@date[1]+0)."-".@date[0];
726   my $issquery = "select * from issues where borrowernumber='$bornum' and
727     itemnumber='$itemno' and returndate is null";
728   my $sth=$dbh->prepare($issquery);
729   $sth->execute;
730   my $issuedata=$sth->fetchrow_hashref;
731   $sth->finish;
732   my $renews = $issuedata->{'renewals'} +1;
733   my $updquery = "update issues 
734     set date_due = '$datedue', renewals = '$renews'
735     where borrowernumber='$bornum' and
736     itemnumber='$itemno' and returndate is null";
737   my $sth=$dbh->prepare($updquery);
738   
739   $sth->execute;
740   $sth->finish;
741   return($odatedue);
742 }
743
744 sub calc_charges {
745 # Stolen from Issues.pm
746 # calculate charges due
747     my ($env, $dbh, $itemno, $bornum)=@_;
748     my $charge=0;
749     my $item_type;
750     my $q1 = "select itemtypes.itemtype,rentalcharge from items,biblioitems,itemtypes where (items.itemnumber ='$itemno') and (biblioitems.biblioitemnumber = items.biblioitemnumber) and (biblioitems.itemtype = itemtypes.itemtype)";
751     my $sth1= $dbh->prepare($q1);
752     $sth1->execute;
753     if (my $data1=$sth1->fetchrow_hashref) {
754         $item_type = $data1->{'itemtype'};
755         $charge = $data1->{'rentalcharge'};
756         my $q2 = "select rentaldiscount from borrowers,categoryitem 
757         where (borrowers.borrowernumber = '$bornum') 
758         and (borrowers.categorycode = categoryitem.categorycode)
759         and (categoryitem.itemtype = '$item_type')";
760         my $sth2=$dbh->prepare($q2);
761         $sth2->execute;
762         if (my $data2=$sth2->fetchrow_hashref) {
763             my $discount = $data2->{'rentaldiscount'};
764             $charge = ($charge *(100 - $discount)) / 100;
765         }
766         $sth2->{'finish'};
767     }      
768     $sth1->finish;
769     return ($charge);
770 }
771
772 sub createcharge {
773 #Stolen from Issues.pm
774     my ($env,$dbh,$itemno,$bornum,$charge) = @_;
775     my $nextaccntno = getnextacctno($env,$bornum,$dbh);
776     my $query = "insert into accountlines (borrowernumber,itemnumber,accountno,date,amount, description,accounttype,amountoutstanding) values ($bornum,$itemno,$nextaccntno,now(),$charge,'Rental','Rent',$charge)";
777     my $sth = $dbh->prepare($query);
778     $sth->execute;
779     $sth->finish;
780 }
781
782
783 sub getnextacctno {
784 # Stolen from Accounts.pm
785     my ($env,$bornumber,$dbh)=@_;
786     my $nextaccntno = 1;
787     my $query = "select * from accountlines where (borrowernumber = '$bornumber') order by accountno desc";
788     my $sth = $dbh->prepare($query);
789     $sth->execute;
790     if (my $accdata=$sth->fetchrow_hashref){
791         $nextaccntno = $accdata->{'accountno'} + 1;
792     }
793     $sth->finish;
794     return($nextaccntno);
795 }
796
797 sub find_reserves {
798 # Stolen from Returns.pm
799   my ($env,$dbh,$itemno) = @_;
800   my ($itemdata) = getiteminformation($env,$itemno,0);
801   my $query = "select * from reserves where 
802   ((reserves.found = 'W')                                   
803   or (reserves.found is null)) 
804   and biblionumber = $itemdata->{'biblionumber'} and cancellationdate is NULL
805   order by priority,reservedate ";
806   my $sth = $dbh->prepare($query);
807   $sth->execute;
808   my $resfound = "n";
809   my $resrec;
810   my $lastrec;
811   while (($resrec=$sth->fetchrow_hashref) && ($resfound eq "n")) {
812       $lastrec=$resrec;
813     if ($resrec->{'found'} eq "W") {
814       if ($resrec->{'itemnumber'} eq $itemno) {
815         $resfound = "y";
816       }
817     } 
818     if ($resrec->{'constrainttype'} eq "a") {
819       $resfound = "y";
820     } else {
821       my $conquery = "select * from reserveconstraints where borrowernumber
822 = $resrec->{'borrowernumber'} and reservedate = '$resrec->{'reservedate'}' and biblionumber = $resrec->{'biblionumber'} and biblioitemnumber = $itemdata->{'biblioitemnumber'}";
823       my $consth = $dbh->prepare($conquery);
824       $consth->execute;
825       if (my $conrec=$consth->fetchrow_hashref) {
826         if ($resrec->{'constrainttype'} eq "o") {
827            $resfound = "y";
828          }
829       } else {
830         if ($resrec->{'constrainttype'} eq "e") {
831           $resfound = "y";
832         }
833       }
834       $consth->finish;
835     }
836     if ($resfound eq "y") {
837       my $updquery = "update reserves 
838         set found = 'W',itemnumber='$itemno'
839         where borrowernumber = $resrec->{'borrowernumber'}
840         and reservedate = '$resrec->{'reservedate'}'
841         and biblionumber = $resrec->{'biblionumber'}";
842       my $updsth = $dbh->prepare($updquery);
843       $updsth->execute;
844       $updsth->finish;
845       my $itbr = $resrec->{'branchcode'};
846       if ($resrec->{'branchcode'} ne $env->{'branchcode'}) {
847          my $updquery = "update items
848           set holdingbranch = 'TR'
849           where itemnumber = $itemno";
850         my $updsth = $dbh->prepare($updquery);
851         $updsth->execute;
852         $updsth->finish;
853       } 
854     }
855   }
856   $sth->finish;
857   return ($resfound,$lastrec);
858 }
859
860 END { }       # module clean-up code here (global destructor)