per row inserts
[koha.git] / C4 / Accounts2.pm
1 package C4::Accounts2; #assumes C4/Accounts2
2
3
4 # Copyright 2000-2002 Katipo Communications
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 # $Id$
22
23 use strict;
24 require Exporter;
25 use C4::Context;
26 use C4::Stats;
27 use C4::Members;
28 #use C4::Circulation::Circ2;
29 use vars qw($VERSION @ISA @EXPORT);
30
31 # set the version for version checking
32 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; 
33 shift(@v) . "." . join("_", map {sprintf "%03d", $_ } @v); };
34
35 =head1 NAME
36
37 C4::Accounts - Functions for dealing with Koha accounts
38
39 =head1 SYNOPSIS
40
41   use C4::Accounts2;
42
43 =head1 DESCRIPTION
44
45 The functions in this module deal with the monetary aspect of Koha,
46 including looking up and modifying the amount of money owed by a
47 patron.
48
49 =head1 FUNCTIONS
50
51 =cut
52
53 @ISA = qw(Exporter);
54 @EXPORT = qw(&checkaccount &recordpayment &fixaccounts &makepayment &manualinvoice
55 &getnextacctno &reconcileaccount);
56
57 =head2 checkaccount
58
59   $owed = &checkaccount($env, $borrowernumber, $dbh, $date);
60
61 Looks up the total amount of money owed by a borrower (fines, etc.).
62
63 C<$borrowernumber> specifies the borrower to look up.
64
65 C<$dbh> is a DBI::db handle for the Koha database.
66
67 C<$env> is ignored.
68
69 =cut
70
71 #'
72 sub checkaccount  {
73   #take borrower number
74   #check accounts and list amounts owing
75         my ($env,$borrowernumber,$dbh,$date)=@_;
76         my $select="SELECT SUM(amountoutstanding) AS total
77                         FROM accountlines
78                 WHERE borrowernumber = ?
79                         AND amountoutstanding<>0";
80         my @bind = ($borrowernumber);
81         if ($date && $date ne ''){
82         $select.=" AND date < ?";
83         push(@bind,$date);
84         }
85         #  print $select;
86         my $sth=$dbh->prepare($select);
87         $sth->execute(@bind);
88         my $data=$sth->fetchrow_hashref;
89         my $total = $data->{'total'} || 0;
90         $sth->finish;
91         # output(1,2,"borrower owes $total");
92         #if ($total > 0){
93         #  # output(1,2,"borrower owes $total");
94         #  if ($total > 5){
95         #    reconcileaccount($env,$dbh,$borrowernumber,$total);
96         #  }
97         #}
98         #  pause();
99         return($total);
100 }
101
102 =head2 recordpayment
103
104   &recordpayment($env, $borrowernumber, $payment);
105
106 Record payment by a patron. C<$borrowernumber> is the patron's
107 borrower number. C<$payment> is a floating-point number, giving the
108 amount that was paid. C<$env> is a reference-to-hash;
109 C<$env-E<gt>{branchcode}> is the code of the branch where payment was
110 made.
111
112 Amounts owed are paid off oldest first. That is, if the patron has a
113 $1 fine from Feb. 1, another $1 fine from Mar. 1, and makes a payment
114 of $1.50, then the oldest fine will be paid off in full, and $0.50
115 will be credited to the next one.
116
117 =cut
118
119 #'
120 sub recordpayment{
121   #here we update both the accountoffsets and the account lines
122   my ($env,$borrowernumber,$data)=@_;
123   my $dbh = C4::Context->dbh;
124   my $newamtos = 0;
125   my $accdata = "";
126   my $branch=$env->{'branchcode'};
127     warn $branch;
128   my $amountleft = $data;
129   # begin transaction
130   my $nextaccntno = getnextacctno($env,$borrowernumber,$dbh);
131   # get lines with outstanding amounts to offset
132   my $sth = $dbh->prepare("select * from accountlines
133   where (borrowernumber = ?) and (amountoutstanding<>0)
134   order by date");
135   $sth->execute($borrowernumber);
136   # offset transactions
137   while (($accdata=$sth->fetchrow_hashref) and ($amountleft>0)){
138      if ($accdata->{'amountoutstanding'} < $amountleft) {
139         $newamtos = 0;
140         $amountleft -= $accdata->{'amountoutstanding'};
141      }  else {
142         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
143         $amountleft = 0;
144      }
145      my $thisacct = $accdata->{accountno};
146      my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
147      where (borrowernumber = ?) and (accountno=?)");
148      $usth->execute($newamtos,$borrowernumber,$thisacct);
149      $usth->finish;
150      $usth = $dbh->prepare("insert into accountoffsets
151      (borrowernumber, accountno, offsetaccount,  offsetamount)
152      values (?,?,?,?)");
153      $usth->execute($borrowernumber,$accdata->{'accountno'},$nextaccntno,$newamtos);
154      $usth->finish;
155   }
156   # create new line
157   my $usth = $dbh->prepare("insert into accountlines
158   (borrowernumber, accountno,date,amount,description,accounttype,amountoutstanding)
159   values (?,?,now(),?,'Payment,thanks','Pay',?)");
160   $usth->execute($borrowernumber,$nextaccntno,0-$data,0-$amountleft);
161   $usth->finish;
162   UpdateStats($env,$branch,'payment',$data,'','','',$borrowernumber);
163   $sth->finish;
164 }
165
166 =head2 makepayment
167
168   &makepayment($borrowernumber, $acctnumber, $amount, $branchcode);
169
170 Records the fact that a patron has paid off the entire amount he or
171 she owes.
172
173 C<$borrowernumber> is the patron's borrower number. C<$acctnumber> is
174 the account that was credited. C<$amount> is the amount paid (this is
175 only used to record the payment. It is assumed to be equal to the
176 amount owed). C<$branchcode> is the code of the branch where payment
177 was made.
178
179 =cut
180
181 #'
182 # FIXME - I'm not at all sure about the above, because I don't
183 # understand what the acct* tables in the Koha database are for.
184 sub makepayment{
185   #here we update both the accountoffsets and the account lines
186   #updated to check, if they are paying off a lost item, we return the item
187   # from their card, and put a note on the item record
188   my ($borrowernumber,$accountno,$amount,$user,$branch)=@_;
189   my %env;
190   $env{'branchcode'}=$branch;
191   my $dbh = C4::Context->dbh;
192   # begin transaction
193   my $nextaccntno = getnextacctno(\%env,$borrowernumber,$dbh);
194   my $newamtos=0;
195   my $sth=$dbh->prepare("Select * from accountlines where  borrowernumber=? and accountno=?");
196   $sth->execute($borrowernumber,$accountno);
197   my $data=$sth->fetchrow_hashref;
198   $sth->finish;
199
200   $dbh->do(<<EOT);
201         UPDATE  accountlines
202         SET     amountoutstanding = 0
203         WHERE   borrowernumber = $borrowernumber
204           AND   accountno = $accountno
205 EOT
206
207 #  print $updquery;
208   $dbh->do(<<EOT);
209         INSERT INTO     accountoffsets
210                         (borrowernumber, accountno, offsetaccount,
211                          offsetamount)
212         VALUES          ($borrowernumber, $accountno, $nextaccntno, $newamtos)
213 EOT
214
215   # create new line
216   my $payment=0-$amount;
217   $dbh->do(<<EOT);
218         INSERT INTO     accountlines
219                         (borrowernumber, accountno, date, amount,
220                          description, accounttype, amountoutstanding)
221         VALUES          ($borrowernumber, $nextaccntno, now(), $payment,
222                         'Payment,thanks - $user', 'Pay', 0)
223 EOT
224
225   # FIXME - The second argument to &UpdateStats is supposed to be the
226   # branch code.
227   # UpdateStats is now being passed $accountno too. MTJ
228   UpdateStats(\%env,$user,'payment',$amount,'','','',$borrowernumber,$accountno);
229   $sth->finish;
230   #check to see what accounttype
231   if ($data->{'accounttype'} eq 'Rep' || $data->{'accounttype'} eq 'L'){
232     returnlost($borrowernumber,$data->{'itemnumber'});
233   }
234 }
235
236 =head2 getnextacctno
237
238   $nextacct = &getnextacctno($env, $borrowernumber, $dbh);
239
240 Returns the next unused account number for the patron with the given
241 borrower number.
242
243 C<$dbh> is a DBI::db handle to the Koha database.
244
245 C<$env> is ignored.
246
247 =cut
248
249 #'
250 # FIXME - Okay, so what does the above actually _mean_?
251 sub getnextacctno {
252   my ($env,$borrowernumber,$dbh)=@_;
253   my $nextaccntno = 1;
254   my $sth = $dbh->prepare("select * from accountlines
255   where (borrowernumber = ?)
256   order by accountno desc");
257   $sth->execute($borrowernumber);
258   if (my $accdata=$sth->fetchrow_hashref){
259     $nextaccntno = $accdata->{'accountno'} + 1;
260   }
261   $sth->finish;
262   return($nextaccntno);
263 }
264
265 =head2 fixaccounts
266
267   &fixaccounts($borrowernumber, $accountnumber, $amount);
268
269 =cut
270
271 #'
272 # FIXME - I don't understand what this function does.
273 sub fixaccounts {
274   my ($borrowernumber,$accountno,$amount)=@_;
275   my $dbh = C4::Context->dbh;
276   my $sth=$dbh->prepare("Select * from accountlines where borrowernumber=?
277      and accountno=?");
278   $sth->execute($borrowernumber,$accountno);
279   my $data=$sth->fetchrow_hashref;
280         # FIXME - Error-checking
281   my $diff=$amount-$data->{'amount'};
282   my $outstanding=$data->{'amountoutstanding'}+$diff;
283   $sth->finish;
284
285   $dbh->do(<<EOT);
286         UPDATE  accountlines
287         SET     amount = '$amount',
288                 amountoutstanding = '$outstanding'
289         WHERE   borrowernumber = $borrowernumber
290           AND   accountno = $accountno
291 EOT
292  }
293
294 # FIXME - Never used, but not exported, either.
295 sub returnlost{
296   my ($borrowernumber,$itemnum)=@_;
297   my $dbh = C4::Context->dbh;
298   my $borrower=borrdata('',$borrowernumber);
299   my $sth=$dbh->prepare("Update issues set returndate=now() where
300   borrowernumber=? and itemnumber=? and returndate is null");
301   $sth->execute($borrowernumber,$itemnum);
302   $sth->finish;
303   my @datearr = localtime(time);
304   my $date = (1900+$datearr[5])."-".($datearr[4]+1)."-".$datearr[3];
305   my $bor="$borrower->{'firstname'} $borrower->{'surname'} $borrower->{'cardnumber'}";
306   $sth=$dbh->prepare("Update items set paidfor=? where itemnumber=?");
307   $sth->execute("Paid for by $bor $date",$itemnum);
308   $sth->finish;
309 }
310
311 =head2 manualinvoice
312
313   &manualinvoice($borrowernumber, $itemnumber, $description, $type,
314                  $amount, $user);
315
316 C<$borrowernumber> is the patron's borrower number.
317 C<$description> is a description of the transaction.
318 C<$type> may be one of C<CS>, C<CB>, C<CW>, C<CF>, C<CL>, C<N>, C<L>,
319 or C<REF>.
320 C<$itemnumber> is the item involved, if pertinent; otherwise, it
321 should be the empty string.
322
323 =cut
324
325 #'
326 # FIXME - Okay, so what does this function do, really?
327 sub manualinvoice{
328   my ($borrowernumber,$itemnum,$desc,$type,$amount,$user)=@_;
329   my $dbh = C4::Context->dbh;
330   my $notifyid;
331   my $insert;
332   $itemnum=~ s/ //g;
333   my %env;
334   my $accountno=getnextacctno('',$borrowernumber,$dbh);
335   my $amountleft=$amount;
336
337   if ($type eq 'CS' || $type eq 'CB' || $type eq 'CW'
338   || $type eq 'CF' || $type eq 'CL'){
339     my $amount2=$amount*-1;     # FIXME - $amount2 = -$amount
340     $amountleft=fixcredit(\%env,$borrowernumber,$amount2,$itemnum,$type,$user);
341   }
342   if ($type eq 'N'){
343     $desc.="New Card";
344   }
345   if ($type eq 'F'){
346     $desc.="Fine";
347   }
348   if ($type eq 'A'){
349     $desc.="Account Management fee";
350   }
351   if ($type eq 'M'){
352     $desc.="Sundry";
353   }             
354                 
355   if ($type eq 'L' && $desc eq ''){
356     
357     $desc="Lost Item";
358   }
359   if ($type eq 'REF'){
360         $desc.="Cash Refund";    
361         $amountleft=refund('',$borrowernumber,$amount);
362   }
363   if(($type eq 'L') or ($type eq 'F') or ($type eq 'A') or ($type eq 'N') or ($type eq 'M') ){
364   $notifyid=1;  
365   }
366         
367   if ($itemnum ne ''){
368     $desc.=" ".$itemnum;
369     my $sth=$dbh->prepare("INSERT INTO  accountlines
370                         (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding, itemnumber,notify_id)
371         VALUES (?, ?, now(), ?,?, ?,?,?,?)");
372 #     $sth->execute($borrowernumber, $accountno, $amount, $desc, $type, $amountleft, $data->{'itemnumber'});
373      $sth->execute($borrowernumber, $accountno, $amount, $desc, $type, $amountleft, $itemnum,$notifyid);
374   } else {
375     my $sth=$dbh->prepare("INSERT INTO  accountlines
376                         (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding,notify_id)
377                         VALUES (?, ?, now(), ?, ?, ?, ?,?)");
378     $sth->execute($borrowernumber, $accountno, $amount, $desc, $type, $amountleft,$notifyid);
379   }
380 }
381
382 =head2 fixcredit
383
384  $amountleft = &fixcredit($env, $borrowernumber, $data, $barcode, $type, $user);
385
386  This function is only used internally, not exported.
387  FIXME - Figure out what this function does, and write it down.
388
389 =cut
390
391 sub fixcredit{
392   #here we update both the accountoffsets and the account lines
393   my ($env,$borrowernumber,$data,$barcode,$type,$user)=@_;
394   my $dbh = C4::Context->dbh;
395   my $newamtos = 0;
396   my $accdata = "";
397   my $amountleft = $data;
398   if ($barcode ne ''){
399     my $item=getiteminformation('',$barcode);
400     my $nextaccntno = getnextacctno($env,$borrowernumber,$dbh);
401     my $query="Select * from accountlines where (borrowernumber=?
402     and itemnumber=? and amountoutstanding > 0)";
403     if ($type eq 'CL'){
404       $query.=" and (accounttype = 'L' or accounttype = 'Rep')";
405     } elsif ($type eq 'CF'){
406       $query.=" and (accounttype = 'F' or accounttype = 'FU' or
407       accounttype='Res' or accounttype='Rent')";
408     } elsif ($type eq 'CB'){
409       $query.=" and accounttype='A'";
410     }
411 #    print $query;
412     my $sth=$dbh->prepare($query);
413     $sth->execute($borrowernumber,$item->{'itemnumber'});
414     $accdata=$sth->fetchrow_hashref;
415     $sth->finish;
416     if ($accdata->{'amountoutstanding'} < $amountleft) {
417         $newamtos = 0;
418         $amountleft -= $accdata->{'amountoutstanding'};
419      }  else {
420         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
421         $amountleft = 0;
422      }
423           my $thisacct = $accdata->{accountno};
424      my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
425      where (borrowernumber = ?) and (accountno=?)");
426      $usth->execute($newamtos,$borrowernumber,$thisacct);
427      $usth->finish;
428      $usth = $dbh->prepare("insert into accountoffsets
429      (borrowernumber, accountno, offsetaccount,  offsetamount)
430      values (?,?,?,?)");
431      $usth->execute($borrowernumber,$accdata->{'accountno'},$nextaccntno,$newamtos);
432      $usth->finish;
433   }
434   # begin transaction
435   my $nextaccntno = getnextacctno($env,$borrowernumber,$dbh);
436   # get lines with outstanding amounts to offset
437   my $sth = $dbh->prepare("select * from accountlines
438   where (borrowernumber = ?) and (amountoutstanding >0)
439   order by date");
440   $sth->execute($borrowernumber);
441 #  print $query;
442   # offset transactions
443   while (($accdata=$sth->fetchrow_hashref) and ($amountleft>0)){
444      if ($accdata->{'amountoutstanding'} < $amountleft) {
445         $newamtos = 0;
446         $amountleft -= $accdata->{'amountoutstanding'};
447      }  else {
448         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
449         $amountleft = 0;
450      }
451      my $thisacct = $accdata->{accountno};
452      my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
453      where (borrowernumber = ?) and (accountno=?)");
454      $usth->execute($newamtos,$borrowernumber,$thisacct);
455      $usth->finish;
456      $usth = $dbh->prepare("insert into accountoffsets
457      (borrowernumber, accountno, offsetaccount,  offsetamount)
458      values (?,?,?,?)");
459      $usth->execute($borrowernumber,$accdata->{'accountno'},$nextaccntno,$newamtos);
460      $usth->finish;
461   }
462   $sth->finish;
463   $env->{'branch'}=$user;
464   $type="Credit ".$type;
465   UpdateStats($env,$user,$type,$data,$user,'','',$borrowernumber);
466   $amountleft*=-1;
467   return($amountleft);
468
469 }
470
471 =head2 refund
472
473 # FIXME - Figure out what this function does, and write it down.
474
475 =cut 
476
477 sub refund{
478   #here we update both the accountoffsets and the account lines
479   my ($env,$borrowernumber,$data)=@_;
480   my $dbh = C4::Context->dbh;
481   my $newamtos = 0;
482   my $accdata = "";
483 #  my $branch=$env->{'branchcode'};
484   my $amountleft = $data *-1;
485
486   # begin transaction
487   my $nextaccntno = getnextacctno($env,$borrowernumber,$dbh);
488   # get lines with outstanding amounts to offset
489   my $sth = $dbh->prepare("select * from accountlines
490   where (borrowernumber = ?) and (amountoutstanding<0)
491   order by date");
492   $sth->execute($borrowernumber);
493 #  print $amountleft;
494   # offset transactions
495   while (($accdata=$sth->fetchrow_hashref) and ($amountleft<0)){
496      if ($accdata->{'amountoutstanding'} > $amountleft) {
497         $newamtos = 0;
498         $amountleft -= $accdata->{'amountoutstanding'};
499      }  else {
500         $newamtos = $accdata->{'amountoutstanding'} - $amountleft;
501         $amountleft = 0;
502      }
503 #     print $amountleft;
504      my $thisacct = $accdata->{accountno};
505      my $usth = $dbh->prepare("update accountlines set amountoutstanding= ?
506      where (borrowernumber = ?) and (accountno=?)");
507      $usth->execute($newamtos,$borrowernumber,$thisacct);
508      $usth->finish;
509      $usth = $dbh->prepare("insert into accountoffsets
510      (borrowernumber, accountno, offsetaccount,  offsetamount)
511      values (?,?,?,?)");
512      $usth->execute($borrowernumber,$accdata->{'accountno'},$nextaccntno,$newamtos);
513      $usth->finish;
514   }
515   $sth->finish;
516   return($amountleft);
517 }
518
519
520 END { }       # module clean-up code here (global destructor)
521
522 1;
523 __END__
524
525
526 =head1 SEE ALSO
527
528 DBI(3)
529
530 =cut
531