Bug 6273: add support for recording type of payment made via SIP2
[koha.git] / C4 / Accounts.pm
1 package C4::Accounts;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use C4::Context;
24 use C4::Stats;
25 use C4::Members;
26 use C4::Circulation qw(ReturnLostItem);
27 use C4::Log qw(logaction);
28
29 use Data::Dumper qw(Dumper);
30
31 use vars qw($VERSION @ISA @EXPORT);
32
33 BEGIN {
34         # set the version for version checking
35     $VERSION = 3.07.00.049;
36         require Exporter;
37         @ISA    = qw(Exporter);
38         @EXPORT = qw(
39                 &recordpayment
40                 &makepayment
41                 &manualinvoice
42                 &getnextacctno
43                 &getcharges
44                 &ModNote
45                 &getcredits
46                 &getrefunds
47                 &chargelostitem
48                 &ReversePayment
49                 &makepartialpayment
50                 &recordpayment_selectaccts
51                 &WriteOffFee
52         );
53 }
54
55 =head1 NAME
56
57 C4::Accounts - Functions for dealing with Koha accounts
58
59 =head1 SYNOPSIS
60
61 use C4::Accounts;
62
63 =head1 DESCRIPTION
64
65 The functions in this module deal with the monetary aspect of Koha,
66 including looking up and modifying the amount of money owed by a
67 patron.
68
69 =head1 FUNCTIONS
70
71 =head2 recordpayment
72
73   &recordpayment($borrowernumber, $payment, $sip_paytype);
74
75 Record payment by a patron. C<$borrowernumber> is the patron's
76 borrower number. C<$payment> is a floating-point number, giving the
77 amount that was paid. C<$sip_paytype> is an optional flag to indicate this
78 payment was made over a SIP2 interface, rather than the staff client. The
79 value passed is the SIP2 payment type value (message 37, characters 21-22)
80
81 Amounts owed are paid off oldest first. That is, if the patron has a
82 $1 fine from Feb. 1, another $1 fine from Mar. 1, and makes a payment
83 of $1.50, then the oldest fine will be paid off in full, and $0.50
84 will be credited to the next one.
85
86 =cut
87
88 #'
89 sub recordpayment {
90
91     #here we update the account lines
92     my ( $borrowernumber, $data, $sip_paytype ) = @_;
93     my $dbh        = C4::Context->dbh;
94     my $newamtos   = 0;
95     my $accdata    = "";
96     my $branch     = C4::Context->userenv->{'branch'};
97     my $amountleft = $data;
98     my $manager_id = 0;
99     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
100
101     # begin transaction
102     my $nextaccntno = getnextacctno($borrowernumber);
103
104     # get lines with outstanding amounts to offset
105     my $sth = $dbh->prepare(
106         "SELECT * FROM accountlines
107   WHERE (borrowernumber = ?) AND (amountoutstanding<>0)
108   ORDER BY date"
109     );
110     $sth->execute($borrowernumber);
111
112     # offset transactions
113     my @ids;
114     while ( ( $accdata = $sth->fetchrow_hashref ) and ( $amountleft > 0 ) ) {
115         if ( $accdata->{'amountoutstanding'} < $amountleft ) {
116             $newamtos = 0;
117             $amountleft -= $accdata->{'amountoutstanding'};
118         }
119         else {
120             $newamtos   = $accdata->{'amountoutstanding'} - $amountleft;
121             $amountleft = 0;
122         }
123         my $thisacct = $accdata->{accountlines_id};
124         my $usth     = $dbh->prepare(
125             "UPDATE accountlines SET amountoutstanding= ?
126      WHERE (accountlines_id = ?)"
127         );
128         $usth->execute( $newamtos, $thisacct );
129
130         if ( C4::Context->preference("FinesLog") ) {
131             $accdata->{'amountoutstanding_new'} = $newamtos;
132             logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
133                 action                => 'fee_payment',
134                 borrowernumber        => $accdata->{'borrowernumber'},
135                 old_amountoutstanding => $accdata->{'amountoutstanding'},
136                 new_amountoutstanding => $newamtos,
137                 amount_paid           => $accdata->{'amountoutstanding'} - $newamtos,
138                 accountlines_id       => $accdata->{'accountlines_id'},
139                 accountno             => $accdata->{'accountno'},
140                 manager_id            => $manager_id,
141             }));
142             push( @ids, $accdata->{'accountlines_id'} );
143         }
144     }
145
146     # create new line
147     my $usth = $dbh->prepare(
148         "INSERT INTO accountlines
149   (borrowernumber, accountno,date,amount,description,accounttype,amountoutstanding,manager_id)
150   VALUES (?,?,now(),?,'Payment,thanks','Pay',?,?)"
151     );
152
153     my $payment_description = "Payment, thanks";
154     $payment_description .= " (via SIP2)" if defined $sip_paytype;
155     my $paytype = "Pay";
156     $paytype .= "-$sip_paytype" if defined $sip_paytype;
157     $usth->execute( $borrowernumber, $nextaccntno, 0 - $data, $payment_description, $paytype, 0 - $amountleft, $manager_id );
158     $usth->finish;
159
160     UpdateStats( $branch, 'payment', $data, '', '', '', $borrowernumber, $nextaccntno );
161
162     if ( C4::Context->preference("FinesLog") ) {
163         $accdata->{'amountoutstanding_new'} = $newamtos;
164         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
165             action            => 'create_payment',
166             borrowernumber    => $borrowernumber,
167             accountno         => $nextaccntno,
168             amount            => $data * -1,
169             amountoutstanding => $amountleft * -1,
170             accounttype       => 'Pay',
171             accountlines_paid => \@ids,
172             manager_id        => $manager_id,
173         }));
174     }
175
176 }
177
178 =head2 makepayment
179
180   &makepayment($accountlines_id, $borrowernumber, $acctnumber, $amount, $branchcode);
181
182 Records the fact that a patron has paid off the entire amount he or
183 she owes.
184
185 C<$borrowernumber> is the patron's borrower number. C<$acctnumber> is
186 the account that was credited. C<$amount> is the amount paid (this is
187 only used to record the payment. It is assumed to be equal to the
188 amount owed). C<$branchcode> is the code of the branch where payment
189 was made.
190
191 =cut
192
193 #'
194 # FIXME - I'm not at all sure about the above, because I don't
195 # understand what the acct* tables in the Koha database are for.
196 sub makepayment {
197
198     #here we update both the accountoffsets and the account lines
199     #updated to check, if they are paying off a lost item, we return the item
200     # from their card, and put a note on the item record
201     my ( $accountlines_id, $borrowernumber, $accountno, $amount, $user, $branch, $payment_note ) = @_;
202     my $dbh = C4::Context->dbh;
203     my $manager_id = 0;
204     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv; 
205
206     # begin transaction
207     my $nextaccntno = getnextacctno($borrowernumber);
208     my $newamtos    = 0;
209     my $sth         = $dbh->prepare("SELECT * FROM accountlines WHERE accountlines_id=?");
210     $sth->execute( $accountlines_id );
211     my $data = $sth->fetchrow_hashref;
212
213     my $payment;
214     if ( $data->{'accounttype'} eq "Pay" ){
215         my $udp =               
216             $dbh->prepare(
217                 "UPDATE accountlines
218                     SET amountoutstanding = 0
219                     WHERE accountlines_id = ?
220                 "
221             );
222         $udp->execute($accountlines_id);
223     }else{
224         my $udp =               
225             $dbh->prepare(
226                 "UPDATE accountlines
227                     SET amountoutstanding = 0
228                     WHERE accountlines_id = ?
229                 "
230             );
231         $udp->execute($accountlines_id);
232
233          # create new line
234         my $payment = 0 - $amount;
235         $payment_note //= "";
236         
237         my $ins = 
238             $dbh->prepare( 
239                 "INSERT 
240                     INTO accountlines (borrowernumber, accountno, date, amount, itemnumber, description, accounttype, amountoutstanding, manager_id, note)
241                     VALUES ( ?, ?, now(), ?, ?, '', 'Pay', 0, ?, ?)"
242             );
243         $ins->execute($borrowernumber, $nextaccntno, $payment, $data->{'itemnumber'}, $manager_id, $payment_note);
244     }
245
246     if ( C4::Context->preference("FinesLog") ) {
247         logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
248             action                => 'fee_payment',
249             borrowernumber        => $borrowernumber,
250             old_amountoutstanding => $data->{'amountoutstanding'},
251             new_amountoutstanding => 0,
252             amount_paid           => $data->{'amountoutstanding'},
253             accountlines_id       => $data->{'accountlines_id'},
254             accountno             => $data->{'accountno'},
255             manager_id            => $manager_id,
256         }));
257
258
259         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
260             action            => 'create_payment',
261             borrowernumber    => $borrowernumber,
262             accountno         => $nextaccntno,
263             amount            => $payment,
264             amountoutstanding => 0,,
265             accounttype       => 'Pay',
266             accountlines_paid => [$data->{'accountlines_id'}],
267             manager_id        => $manager_id,
268         }));
269     }
270
271
272     # FIXME - The second argument to &UpdateStats is supposed to be the
273     # branch code.
274     # UpdateStats is now being passed $accountno too. MTJ
275     UpdateStats( $user, 'payment', $amount, '', '', '', $borrowernumber,
276         $accountno );
277
278     #check to see what accounttype
279     if ( $data->{'accounttype'} eq 'Rep' || $data->{'accounttype'} eq 'L' ) {
280         C4::Circulation::ReturnLostItem( $borrowernumber, $data->{'itemnumber'} );
281     }
282     my $sthr = $dbh->prepare("SELECT max(accountlines_id) AS lastinsertid FROM accountlines");
283     $sthr->execute();
284     my $datalastinsertid = $sthr->fetchrow_hashref;
285     return $datalastinsertid->{'lastinsertid'};
286 }
287
288 =head2 getnextacctno
289
290   $nextacct = &getnextacctno($borrowernumber);
291
292 Returns the next unused account number for the patron with the given
293 borrower number.
294
295 =cut
296
297 #'
298 # FIXME - Okay, so what does the above actually _mean_?
299 sub getnextacctno {
300     my ($borrowernumber) = shift or return;
301     my $sth = C4::Context->dbh->prepare(
302         "SELECT accountno+1 FROM accountlines
303             WHERE    (borrowernumber = ?)
304             ORDER BY accountno DESC
305             LIMIT 1"
306     );
307     $sth->execute($borrowernumber);
308     return ($sth->fetchrow || 1);
309 }
310
311 =head2 fixaccounts (removed)
312
313   &fixaccounts($accountlines_id, $borrowernumber, $accountnumber, $amount);
314
315 #'
316 # FIXME - I don't understand what this function does.
317 sub fixaccounts {
318     my ( $accountlines_id, $borrowernumber, $accountno, $amount ) = @_;
319     my $dbh = C4::Context->dbh;
320     my $sth = $dbh->prepare(
321         "SELECT * FROM accountlines WHERE accountlines_id=?"
322     );
323     $sth->execute( $accountlines_id );
324     my $data = $sth->fetchrow_hashref;
325
326     # FIXME - Error-checking
327     my $diff        = $amount - $data->{'amount'};
328     my $outstanding = $data->{'amountoutstanding'} + $diff;
329     $sth->finish;
330
331     $dbh->do(<<EOT);
332         UPDATE  accountlines
333         SET     amount = '$amount',
334                 amountoutstanding = '$outstanding'
335         WHERE   accountlines_id = $accountlines_id
336 EOT
337         # FIXME: exceedingly bad form.  Use prepare with placholders ("?") in query and execute args.
338 }
339
340 =cut
341
342 sub chargelostitem{
343 # lost ==1 Lost, lost==2 longoverdue, lost==3 lost and paid for
344 # FIXME: itemlost should be set to 3 after payment is made, should be a warning to the interface that
345 # a charge has been added
346 # FIXME : if no replacement price, borrower just doesn't get charged?
347     my $dbh = C4::Context->dbh();
348     my ($borrowernumber, $itemnumber, $amount, $description) = @_;
349
350     # first make sure the borrower hasn't already been charged for this item
351     my $sth1=$dbh->prepare("SELECT * from accountlines
352     WHERE borrowernumber=? AND itemnumber=? and accounttype='L'");
353     $sth1->execute($borrowernumber,$itemnumber);
354     my $existing_charge_hashref=$sth1->fetchrow_hashref();
355
356     # OK, they haven't
357     unless ($existing_charge_hashref) {
358         my $manager_id = 0;
359         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
360         # This item is on issue ... add replacement cost to the borrower's record and mark it returned
361         #  Note that we add this to the account even if there's no replacement price, allowing some other
362         #  process (or person) to update it, since we don't handle any defaults for replacement prices.
363         my $accountno = getnextacctno($borrowernumber);
364         my $sth2=$dbh->prepare("INSERT INTO accountlines
365         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber,manager_id)
366         VALUES (?,?,now(),?,?,'L',?,?,?)");
367         $sth2->execute($borrowernumber,$accountno,$amount,
368         $description,$amount,$itemnumber,$manager_id);
369
370         if ( C4::Context->preference("FinesLog") ) {
371             logaction("FINES", 'CREATE', $borrowernumber, Dumper({
372                 action            => 'create_fee',
373                 borrowernumber    => $borrowernumber,
374                 accountno         => $accountno,
375                 amount            => $amount,
376                 amountoutstanding => $amount,
377                 description       => $description,
378                 accounttype       => 'L',
379                 itemnumber        => $itemnumber,
380                 manager_id        => $manager_id,
381             }));
382         }
383
384     }
385 }
386
387 =head2 manualinvoice
388
389   &manualinvoice($borrowernumber, $itemnumber, $description, $type,
390                  $amount, $note);
391
392 C<$borrowernumber> is the patron's borrower number.
393 C<$description> is a description of the transaction.
394 C<$type> may be one of C<CS>, C<CB>, C<CW>, C<CF>, C<CL>, C<N>, C<L>,
395 or C<REF>.
396 C<$itemnumber> is the item involved, if pertinent; otherwise, it
397 should be the empty string.
398
399 =cut
400
401 #'
402 # FIXME: In Koha 3.0 , the only account adjustment 'types' passed to this function
403 # are :  
404 #               'C' = CREDIT
405 #               'FOR' = FORGIVEN  (Formerly 'F', but 'F' is taken to mean 'FINE' elsewhere)
406 #               'N' = New Card fee
407 #               'F' = Fine
408 #               'A' = Account Management fee
409 #               'M' = Sundry
410 #               'L' = Lost Item
411 #
412
413 sub manualinvoice {
414     my ( $borrowernumber, $itemnum, $desc, $type, $amount, $note ) = @_;
415     my $manager_id = 0;
416     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
417     my $dbh      = C4::Context->dbh;
418     my $notifyid = 0;
419     my $insert;
420     my $accountno  = getnextacctno($borrowernumber);
421     my $amountleft = $amount;
422
423     if (   ( $type eq 'L' )
424         or ( $type eq 'F' )
425         or ( $type eq 'A' )
426         or ( $type eq 'N' )
427         or ( $type eq 'M' ) )
428     {
429         $notifyid = 1;
430     }
431
432     if ( $itemnum ) {
433         $desc .= ' ' . $itemnum;
434         my $sth = $dbh->prepare(
435             'INSERT INTO  accountlines
436                         (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding, itemnumber,notify_id, note, manager_id)
437         VALUES (?, ?, now(), ?,?, ?,?,?,?,?,?)');
438      $sth->execute($borrowernumber, $accountno, $amount, $desc, $type, $amountleft, $itemnum,$notifyid, $note, $manager_id) || return $sth->errstr;
439   } else {
440     my $sth=$dbh->prepare("INSERT INTO  accountlines
441             (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding,notify_id, note, manager_id)
442             VALUES (?, ?, now(), ?, ?, ?, ?,?,?,?)"
443         );
444         $sth->execute( $borrowernumber, $accountno, $amount, $desc, $type,
445             $amountleft, $notifyid, $note, $manager_id );
446     }
447
448     if ( C4::Context->preference("FinesLog") ) {
449         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
450             action            => 'create_fee',
451             borrowernumber    => $borrowernumber,
452             accountno         => $accountno,
453             amount            => $amount,
454             description       => $desc,
455             accounttype       => $type,
456             amountoutstanding => $amountleft,
457             notify_id         => $notifyid,
458             note              => $note,
459             itemnumber        => $itemnum,
460             manager_id        => $manager_id,
461         }));
462     }
463
464     return 0;
465 }
466
467 sub getcharges {
468         my ( $borrowerno, $timestamp, $accountno ) = @_;
469         my $dbh        = C4::Context->dbh;
470         my $timestamp2 = $timestamp - 1;
471         my $query      = "";
472         my $sth = $dbh->prepare(
473                         "SELECT * FROM accountlines WHERE borrowernumber=? AND accountno = ?"
474           );
475         $sth->execute( $borrowerno, $accountno );
476         
477     my @results;
478     while ( my $data = $sth->fetchrow_hashref ) {
479                 push @results,$data;
480         }
481     return (@results);
482 }
483
484 sub ModNote {
485     my ( $accountlines_id, $note ) = @_;
486     my $dbh = C4::Context->dbh;
487     my $sth = $dbh->prepare('UPDATE accountlines SET note = ? WHERE accountlines_id = ?');
488     $sth->execute( $note, $accountlines_id );
489 }
490
491 sub getcredits {
492         my ( $date, $date2 ) = @_;
493         my $dbh = C4::Context->dbh;
494         my $sth = $dbh->prepare(
495                                 "SELECT * FROM accountlines,borrowers
496       WHERE amount < 0 AND accounttype not like 'Pay%' AND accountlines.borrowernumber = borrowers.borrowernumber
497           AND timestamp >=TIMESTAMP(?) AND timestamp < TIMESTAMP(?)"
498       );  
499
500     $sth->execute( $date, $date2 );                                                                                                              
501     my @results;          
502     while ( my $data = $sth->fetchrow_hashref ) {
503                 $data->{'date'} = $data->{'timestamp'};
504                 push @results,$data;
505         }
506     return (@results);
507
508
509
510 sub getrefunds {
511         my ( $date, $date2 ) = @_;
512         my $dbh = C4::Context->dbh;
513         
514         my $sth = $dbh->prepare(
515                                 "SELECT *,timestamp AS datetime                                                                                      
516                   FROM accountlines,borrowers
517                   WHERE (accounttype = 'REF'
518                                           AND accountlines.borrowernumber = borrowers.borrowernumber
519                                                           AND date  >=?  AND date  <?)"
520     );
521
522     $sth->execute( $date, $date2 );
523
524     my @results;
525     while ( my $data = $sth->fetchrow_hashref ) {
526                 push @results,$data;
527                 
528         }
529     return (@results);
530 }
531
532 sub ReversePayment {
533     my ( $accountlines_id ) = @_;
534     my $dbh = C4::Context->dbh;
535
536     my $sth = $dbh->prepare('SELECT * FROM accountlines WHERE accountlines_id = ?');
537     $sth->execute( $accountlines_id );
538     my $row = $sth->fetchrow_hashref();
539     my $amount_outstanding = $row->{'amountoutstanding'};
540
541     if ( $amount_outstanding <= 0 ) {
542         $sth = $dbh->prepare('UPDATE accountlines SET amountoutstanding = amount * -1, description = CONCAT( description, " Reversed -" ) WHERE accountlines_id = ?');
543         $sth->execute( $accountlines_id );
544     } else {
545         $sth = $dbh->prepare('UPDATE accountlines SET amountoutstanding = 0, description = CONCAT( description, " Reversed -" ) WHERE accountlines_id = ?');
546         $sth->execute( $accountlines_id );
547     }
548
549     if ( C4::Context->preference("FinesLog") ) {
550         my $manager_id = 0;
551         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
552
553         if ( $amount_outstanding <= 0 ) {
554             $row->{'amountoutstanding'} *= -1;
555         } else {
556             $row->{'amountoutstanding'} = '0';
557         }
558         $row->{'description'} .= ' Reversed -';
559         logaction("FINES", 'MODIFY', $row->{'borrowernumber'}, Dumper({
560             action                => 'reverse_fee_payment',
561             borrowernumber        => $row->{'borrowernumber'},
562             old_amountoutstanding => $row->{'amountoutstanding'},
563             new_amountoutstanding => 0 - $amount_outstanding,,
564             accountlines_id       => $row->{'accountlines_id'},
565             accountno             => $row->{'accountno'},
566             manager_id            => $manager_id,
567         }));
568
569     }
570
571 }
572
573 =head2 recordpayment_selectaccts
574
575   recordpayment_selectaccts($borrowernumber, $payment,$accts);
576
577 Record payment by a patron. C<$borrowernumber> is the patron's
578 borrower number. C<$payment> is a floating-point number, giving the
579 amount that was paid. C<$accts> is an array ref to a list of
580 accountnos which the payment can be recorded against
581
582 Amounts owed are paid off oldest first. That is, if the patron has a
583 $1 fine from Feb. 1, another $1 fine from Mar. 1, and makes a payment
584 of $1.50, then the oldest fine will be paid off in full, and $0.50
585 will be credited to the next one.
586
587 =cut
588
589 sub recordpayment_selectaccts {
590     my ( $borrowernumber, $amount, $accts, $note ) = @_;
591
592     my $dbh        = C4::Context->dbh;
593     my $newamtos   = 0;
594     my $accdata    = q{};
595     my $branch     = C4::Context->userenv->{branch};
596     my $amountleft = $amount;
597     my $manager_id = 0;
598     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
599     my $sql = 'SELECT * FROM accountlines WHERE (borrowernumber = ?) ' .
600     'AND (amountoutstanding<>0) ';
601     if (@{$accts} ) {
602         $sql .= ' AND accountno IN ( ' .  join ',', @{$accts};
603         $sql .= ' ) ';
604     }
605     $sql .= ' ORDER BY date';
606     # begin transaction
607     my $nextaccntno = getnextacctno($borrowernumber);
608
609     # get lines with outstanding amounts to offset
610     my $rows = $dbh->selectall_arrayref($sql, { Slice => {} }, $borrowernumber);
611
612     # offset transactions
613     my $sth     = $dbh->prepare('UPDATE accountlines SET amountoutstanding= ? ' .
614         'WHERE accountlines_id=?');
615
616     my @ids;
617     for my $accdata ( @{$rows} ) {
618         if ($amountleft == 0) {
619             last;
620         }
621         if ( $accdata->{amountoutstanding} < $amountleft ) {
622             $newamtos = 0;
623             $amountleft -= $accdata->{amountoutstanding};
624         }
625         else {
626             $newamtos   = $accdata->{amountoutstanding} - $amountleft;
627             $amountleft = 0;
628         }
629         my $thisacct = $accdata->{accountlines_id};
630         $sth->execute( $newamtos, $thisacct );
631
632         if ( C4::Context->preference("FinesLog") ) {
633             logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
634                 action                => 'fee_payment',
635                 borrowernumber        => $borrowernumber,
636                 old_amountoutstanding => $accdata->{'amountoutstanding'},
637                 new_amountoutstanding => $newamtos,
638                 amount_paid           => $accdata->{'amountoutstanding'} - $newamtos,
639                 accountlines_id       => $accdata->{'accountlines_id'},
640                 accountno             => $accdata->{'accountno'},
641                 manager_id            => $manager_id,
642             }));
643             push( @ids, $accdata->{'accountlines_id'} );
644         }
645
646     }
647
648     # create new line
649     $sql = 'INSERT INTO accountlines ' .
650     '(borrowernumber, accountno,date,amount,description,accounttype,amountoutstanding,manager_id,note) ' .
651     q|VALUES (?,?,now(),?,'','Pay',?,?,?)|;
652     $dbh->do($sql,{},$borrowernumber, $nextaccntno, 0 - $amount, 0 - $amountleft, $manager_id, $note );
653     UpdateStats( $branch, 'payment', $amount, '', '', '', $borrowernumber, $nextaccntno );
654
655     if ( C4::Context->preference("FinesLog") ) {
656         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
657             action            => 'create_payment',
658             borrowernumber    => $borrowernumber,
659             accountno         => $nextaccntno,
660             amount            => 0 - $amount,
661             amountoutstanding => 0 - $amountleft,
662             accounttype       => 'Pay',
663             accountlines_paid => \@ids,
664             manager_id        => $manager_id,
665         }));
666     }
667
668     return;
669 }
670
671 # makepayment needs to be fixed to handle partials till then this separate subroutine
672 # fills in
673 sub makepartialpayment {
674     my ( $accountlines_id, $borrowernumber, $accountno, $amount, $user, $branch, $payment_note ) = @_;
675     my $manager_id = 0;
676     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
677     if (!$amount || $amount < 0) {
678         return;
679     }
680     $payment_note //= "";
681     my $dbh = C4::Context->dbh;
682
683     my $nextaccntno = getnextacctno($borrowernumber);
684     my $newamtos    = 0;
685
686     my $data = $dbh->selectrow_hashref(
687         'SELECT * FROM accountlines WHERE  accountlines_id=?',undef,$accountlines_id);
688     my $new_outstanding = $data->{amountoutstanding} - $amount;
689
690     my $update = 'UPDATE  accountlines SET amountoutstanding = ?  WHERE   accountlines_id = ? ';
691     $dbh->do( $update, undef, $new_outstanding, $accountlines_id);
692
693     if ( C4::Context->preference("FinesLog") ) {
694         logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
695             action                => 'fee_payment',
696             borrowernumber        => $borrowernumber,
697             old_amountoutstanding => $data->{'amountoutstanding'},
698             new_amountoutstanding => $new_outstanding,
699             amount_paid           => $data->{'amountoutstanding'} - $new_outstanding,
700             accountlines_id       => $data->{'accountlines_id'},
701             accountno             => $data->{'accountno'},
702             manager_id            => $manager_id,
703         }));
704     }
705
706     # create new line
707     my $insert = 'INSERT INTO accountlines (borrowernumber, accountno, date, amount, '
708     .  'description, accounttype, amountoutstanding, itemnumber, manager_id, note) '
709     . ' VALUES (?, ?, now(), ?, ?, ?, 0, ?, ?, ?)';
710
711     $dbh->do(  $insert, undef, $borrowernumber, $nextaccntno, $amount,
712         "Payment, thanks - $user", 'Pay', $data->{'itemnumber'}, $manager_id, $payment_note);
713
714     UpdateStats( $user, 'payment', $amount, '', '', '', $borrowernumber, $accountno );
715
716     if ( C4::Context->preference("FinesLog") ) {
717         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
718             action            => 'create_payment',
719             borrowernumber    => $user,
720             accountno         => $nextaccntno,
721             amount            => 0 - $amount,
722             accounttype       => 'Pay',
723             itemnumber        => $data->{'itemnumber'},
724             accountlines_paid => [ $data->{'accountlines_id'} ],
725             manager_id        => $manager_id,
726         }));
727     }
728
729     return;
730 }
731
732 =head2 WriteOffFee
733
734   WriteOffFee( $borrowernumber, $accountline_id, $itemnum, $accounttype, $amount, $branch, $payment_note );
735
736 Write off a fine for a patron.
737 C<$borrowernumber> is the patron's borrower number.
738 C<$accountline_id> is the accountline_id of the fee to write off.
739 C<$itemnum> is the itemnumber of of item whose fine is being written off.
740 C<$accounttype> is the account type of the fine being written off.
741 C<$amount> is a floating-point number, giving the amount that is being written off.
742 C<$branch> is the branchcode of the library where the writeoff occurred.
743 C<$payment_note> is the note to attach to this payment
744
745 =cut
746
747 sub WriteOffFee {
748     my ( $borrowernumber, $accountlines_id, $itemnum, $accounttype, $amount, $branch, $payment_note ) = @_;
749     $payment_note //= "";
750     $branch ||= C4::Context->userenv->{branch};
751     my $manager_id = 0;
752     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
753
754     # if no item is attached to fine, make sure to store it as a NULL
755     $itemnum ||= undef;
756
757     my ( $sth, $query );
758     my $dbh = C4::Context->dbh();
759
760     $query = "
761         UPDATE accountlines SET amountoutstanding = 0
762         WHERE accountlines_id = ? AND borrowernumber = ?
763     ";
764     $sth = $dbh->prepare( $query );
765     $sth->execute( $accountlines_id, $borrowernumber );
766
767     if ( C4::Context->preference("FinesLog") ) {
768         logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
769             action                => 'fee_writeoff',
770             borrowernumber        => $borrowernumber,
771             accountlines_id       => $accountlines_id,
772             manager_id            => $manager_id,
773         }));
774     }
775
776     $query ="
777         INSERT INTO accountlines
778         ( borrowernumber, accountno, itemnumber, date, amount, description, accounttype, manager_id, note )
779         VALUES ( ?, ?, ?, NOW(), ?, 'Writeoff', 'W', ?, ? )
780     ";
781     $sth = $dbh->prepare( $query );
782     my $acct = getnextacctno($borrowernumber);
783     $sth->execute( $borrowernumber, $acct, $itemnum, $amount, $manager_id, $payment_note );
784
785     if ( C4::Context->preference("FinesLog") ) {
786         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
787             action            => 'create_writeoff',
788             borrowernumber    => $borrowernumber,
789             accountno         => $acct,
790             amount            => 0 - $amount,
791             accounttype       => 'W',
792             itemnumber        => $itemnum,
793             accountlines_paid => [ $accountlines_id ],
794             manager_id        => $manager_id,
795         }));
796     }
797
798     UpdateStats( $branch, 'writeoff', $amount, q{}, q{}, q{}, $borrowernumber );
799
800 }
801
802 END { }    # module clean-up code here (global destructor)
803
804 1;
805 __END__
806
807 =head1 SEE ALSO
808
809 DBI(3)
810
811 =cut
812