Bug 15905 - Remove use of makepayment
[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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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 use Koha::Account;
29
30 use Data::Dumper qw(Dumper);
31
32 use vars qw(@ISA @EXPORT);
33
34 BEGIN {
35         require Exporter;
36         @ISA    = qw(Exporter);
37         @EXPORT = qw(
38                 &manualinvoice
39                 &getnextacctno
40                 &getcharges
41                 &ModNote
42                 &getcredits
43                 &getrefunds
44                 &chargelostitem
45                 &ReversePayment
46         &WriteOffFee
47         &purge_zero_balance_fees
48         );
49 }
50
51 =head1 NAME
52
53 C4::Accounts - Functions for dealing with Koha accounts
54
55 =head1 SYNOPSIS
56
57 use C4::Accounts;
58
59 =head1 DESCRIPTION
60
61 The functions in this module deal with the monetary aspect of Koha,
62 including looking up and modifying the amount of money owed by a
63 patron.
64
65 =head1 FUNCTIONS
66
67 =head2 getnextacctno
68
69   $nextacct = &getnextacctno($borrowernumber);
70
71 Returns the next unused account number for the patron with the given
72 borrower number.
73
74 =cut
75
76 #'
77 # FIXME - Okay, so what does the above actually _mean_?
78 sub getnextacctno {
79     my ($borrowernumber) = shift or return;
80     my $sth = C4::Context->dbh->prepare(
81         "SELECT accountno+1 FROM accountlines
82             WHERE    (borrowernumber = ?)
83             ORDER BY accountno DESC
84             LIMIT 1"
85     );
86     $sth->execute($borrowernumber);
87     return ($sth->fetchrow || 1);
88 }
89
90 =head2 fixaccounts (removed)
91
92   &fixaccounts($accountlines_id, $borrowernumber, $accountnumber, $amount);
93
94 #'
95 # FIXME - I don't understand what this function does.
96 sub fixaccounts {
97     my ( $accountlines_id, $borrowernumber, $accountno, $amount ) = @_;
98     my $dbh = C4::Context->dbh;
99     my $sth = $dbh->prepare(
100         "SELECT * FROM accountlines WHERE accountlines_id=?"
101     );
102     $sth->execute( $accountlines_id );
103     my $data = $sth->fetchrow_hashref;
104
105     # FIXME - Error-checking
106     my $diff        = $amount - $data->{'amount'};
107     my $outstanding = $data->{'amountoutstanding'} + $diff;
108     $sth->finish;
109
110     $dbh->do(<<EOT);
111         UPDATE  accountlines
112         SET     amount = '$amount',
113                 amountoutstanding = '$outstanding'
114         WHERE   accountlines_id = $accountlines_id
115 EOT
116         # FIXME: exceedingly bad form.  Use prepare with placholders ("?") in query and execute args.
117 }
118
119 =cut
120
121 sub chargelostitem{
122 # lost ==1 Lost, lost==2 longoverdue, lost==3 lost and paid for
123 # FIXME: itemlost should be set to 3 after payment is made, should be a warning to the interface that
124 # a charge has been added
125 # FIXME : if no replacement price, borrower just doesn't get charged?
126     my $dbh = C4::Context->dbh();
127     my ($borrowernumber, $itemnumber, $amount, $description) = @_;
128
129     # first make sure the borrower hasn't already been charged for this item
130     my $sth1=$dbh->prepare("SELECT * from accountlines
131     WHERE borrowernumber=? AND itemnumber=? and accounttype='L'");
132     $sth1->execute($borrowernumber,$itemnumber);
133     my $existing_charge_hashref=$sth1->fetchrow_hashref();
134
135     # OK, they haven't
136     unless ($existing_charge_hashref) {
137         my $manager_id = 0;
138         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
139         # This item is on issue ... add replacement cost to the borrower's record and mark it returned
140         #  Note that we add this to the account even if there's no replacement price, allowing some other
141         #  process (or person) to update it, since we don't handle any defaults for replacement prices.
142         my $accountno = getnextacctno($borrowernumber);
143         my $sth2=$dbh->prepare("INSERT INTO accountlines
144         (borrowernumber,accountno,date,amount,description,accounttype,amountoutstanding,itemnumber,manager_id)
145         VALUES (?,?,now(),?,?,'L',?,?,?)");
146         $sth2->execute($borrowernumber,$accountno,$amount,
147         $description,$amount,$itemnumber,$manager_id);
148
149         if ( C4::Context->preference("FinesLog") ) {
150             logaction("FINES", 'CREATE', $borrowernumber, Dumper({
151                 action            => 'create_fee',
152                 borrowernumber    => $borrowernumber,
153                 accountno         => $accountno,
154                 amount            => $amount,
155                 amountoutstanding => $amount,
156                 description       => $description,
157                 accounttype       => 'L',
158                 itemnumber        => $itemnumber,
159                 manager_id        => $manager_id,
160             }));
161         }
162
163     }
164 }
165
166 =head2 manualinvoice
167
168   &manualinvoice($borrowernumber, $itemnumber, $description, $type,
169                  $amount, $note);
170
171 C<$borrowernumber> is the patron's borrower number.
172 C<$description> is a description of the transaction.
173 C<$type> may be one of C<CS>, C<CB>, C<CW>, C<CF>, C<CL>, C<N>, C<L>,
174 or C<REF>.
175 C<$itemnumber> is the item involved, if pertinent; otherwise, it
176 should be the empty string.
177
178 =cut
179
180 #'
181 # FIXME: In Koha 3.0 , the only account adjustment 'types' passed to this function
182 # are :  
183 #               'C' = CREDIT
184 #               'FOR' = FORGIVEN  (Formerly 'F', but 'F' is taken to mean 'FINE' elsewhere)
185 #               'N' = New Card fee
186 #               'F' = Fine
187 #               'A' = Account Management fee
188 #               'M' = Sundry
189 #               'L' = Lost Item
190 #
191
192 sub manualinvoice {
193     my ( $borrowernumber, $itemnum, $desc, $type, $amount, $note ) = @_;
194     my $manager_id = 0;
195     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
196     my $dbh      = C4::Context->dbh;
197     my $notifyid = 0;
198     my $insert;
199     my $accountno  = getnextacctno($borrowernumber);
200     my $amountleft = $amount;
201
202     if (   ( $type eq 'L' )
203         or ( $type eq 'F' )
204         or ( $type eq 'A' )
205         or ( $type eq 'N' )
206         or ( $type eq 'M' ) )
207     {
208         $notifyid = 1;
209     }
210
211     if ( $itemnum ) {
212         $desc .= ' ' . $itemnum;
213         my $sth = $dbh->prepare(
214             'INSERT INTO  accountlines
215                         (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding, itemnumber,notify_id, note, manager_id)
216         VALUES (?, ?, now(), ?,?, ?,?,?,?,?,?)');
217      $sth->execute($borrowernumber, $accountno, $amount, $desc, $type, $amountleft, $itemnum,$notifyid, $note, $manager_id) || return $sth->errstr;
218   } else {
219     my $sth=$dbh->prepare("INSERT INTO  accountlines
220             (borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding,notify_id, note, manager_id)
221             VALUES (?, ?, now(), ?, ?, ?, ?,?,?,?)"
222         );
223         $sth->execute( $borrowernumber, $accountno, $amount, $desc, $type,
224             $amountleft, $notifyid, $note, $manager_id );
225     }
226
227     if ( C4::Context->preference("FinesLog") ) {
228         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
229             action            => 'create_fee',
230             borrowernumber    => $borrowernumber,
231             accountno         => $accountno,
232             amount            => $amount,
233             description       => $desc,
234             accounttype       => $type,
235             amountoutstanding => $amountleft,
236             notify_id         => $notifyid,
237             note              => $note,
238             itemnumber        => $itemnum,
239             manager_id        => $manager_id,
240         }));
241     }
242
243     return 0;
244 }
245
246 sub getcharges {
247         my ( $borrowerno, $timestamp, $accountno ) = @_;
248         my $dbh        = C4::Context->dbh;
249         my $timestamp2 = $timestamp - 1;
250         my $query      = "";
251         my $sth = $dbh->prepare(
252                         "SELECT * FROM accountlines WHERE borrowernumber=? AND accountno = ?"
253           );
254         $sth->execute( $borrowerno, $accountno );
255         
256     my @results;
257     while ( my $data = $sth->fetchrow_hashref ) {
258                 push @results,$data;
259         }
260     return (@results);
261 }
262
263 sub ModNote {
264     my ( $accountlines_id, $note ) = @_;
265     my $dbh = C4::Context->dbh;
266     my $sth = $dbh->prepare('UPDATE accountlines SET note = ? WHERE accountlines_id = ?');
267     $sth->execute( $note, $accountlines_id );
268 }
269
270 sub getcredits {
271         my ( $date, $date2 ) = @_;
272         my $dbh = C4::Context->dbh;
273         my $sth = $dbh->prepare(
274                                 "SELECT * FROM accountlines,borrowers
275       WHERE amount < 0 AND accounttype not like 'Pay%' AND accountlines.borrowernumber = borrowers.borrowernumber
276           AND timestamp >=TIMESTAMP(?) AND timestamp < TIMESTAMP(?)"
277       );  
278
279     $sth->execute( $date, $date2 );                                                                                                              
280     my @results;          
281     while ( my $data = $sth->fetchrow_hashref ) {
282                 $data->{'date'} = $data->{'timestamp'};
283                 push @results,$data;
284         }
285     return (@results);
286
287
288
289 sub getrefunds {
290         my ( $date, $date2 ) = @_;
291         my $dbh = C4::Context->dbh;
292         
293         my $sth = $dbh->prepare(
294                                 "SELECT *,timestamp AS datetime                                                                                      
295                   FROM accountlines,borrowers
296                   WHERE (accounttype = 'REF'
297                                           AND accountlines.borrowernumber = borrowers.borrowernumber
298                                                           AND date  >=?  AND date  <?)"
299     );
300
301     $sth->execute( $date, $date2 );
302
303     my @results;
304     while ( my $data = $sth->fetchrow_hashref ) {
305                 push @results,$data;
306                 
307         }
308     return (@results);
309 }
310
311 sub ReversePayment {
312     my ( $accountlines_id ) = @_;
313     my $dbh = C4::Context->dbh;
314
315     my $sth = $dbh->prepare('SELECT * FROM accountlines WHERE accountlines_id = ?');
316     $sth->execute( $accountlines_id );
317     my $row = $sth->fetchrow_hashref();
318     my $amount_outstanding = $row->{'amountoutstanding'};
319
320     if ( $amount_outstanding <= 0 ) {
321         $sth = $dbh->prepare('UPDATE accountlines SET amountoutstanding = amount * -1, description = CONCAT( description, " Reversed -" ) WHERE accountlines_id = ?');
322         $sth->execute( $accountlines_id );
323     } else {
324         $sth = $dbh->prepare('UPDATE accountlines SET amountoutstanding = 0, description = CONCAT( description, " Reversed -" ) WHERE accountlines_id = ?');
325         $sth->execute( $accountlines_id );
326     }
327
328     if ( C4::Context->preference("FinesLog") ) {
329         my $manager_id = 0;
330         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
331
332         if ( $amount_outstanding <= 0 ) {
333             $row->{'amountoutstanding'} *= -1;
334         } else {
335             $row->{'amountoutstanding'} = '0';
336         }
337         $row->{'description'} .= ' Reversed -';
338         logaction("FINES", 'MODIFY', $row->{'borrowernumber'}, Dumper({
339             action                => 'reverse_fee_payment',
340             borrowernumber        => $row->{'borrowernumber'},
341             old_amountoutstanding => $row->{'amountoutstanding'},
342             new_amountoutstanding => 0 - $amount_outstanding,,
343             accountlines_id       => $row->{'accountlines_id'},
344             accountno             => $row->{'accountno'},
345             manager_id            => $manager_id,
346         }));
347
348     }
349
350 }
351
352 =head2 WriteOffFee
353
354   WriteOffFee( $borrowernumber, $accountline_id, $itemnum, $accounttype, $amount, $branch, $payment_note );
355
356 Write off a fine for a patron.
357 C<$borrowernumber> is the patron's borrower number.
358 C<$accountline_id> is the accountline_id of the fee to write off.
359 C<$itemnum> is the itemnumber of of item whose fine is being written off.
360 C<$accounttype> is the account type of the fine being written off.
361 C<$amount> is a floating-point number, giving the amount that is being written off.
362 C<$branch> is the branchcode of the library where the writeoff occurred.
363 C<$payment_note> is the note to attach to this payment
364
365 =cut
366
367 sub WriteOffFee {
368     my ( $borrowernumber, $accountlines_id, $itemnum, $accounttype, $amount, $branch, $payment_note ) = @_;
369     $payment_note //= "";
370     $branch ||= C4::Context->userenv->{branch};
371     my $manager_id = 0;
372     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
373
374     # if no item is attached to fine, make sure to store it as a NULL
375     $itemnum ||= undef;
376
377     my ( $sth, $query );
378     my $dbh = C4::Context->dbh();
379
380     $query = "
381         UPDATE accountlines SET amountoutstanding = 0
382         WHERE accountlines_id = ? AND borrowernumber = ?
383     ";
384     $sth = $dbh->prepare( $query );
385     $sth->execute( $accountlines_id, $borrowernumber );
386
387     if ( C4::Context->preference("FinesLog") ) {
388         logaction("FINES", 'MODIFY', $borrowernumber, Dumper({
389             action                => 'fee_writeoff',
390             borrowernumber        => $borrowernumber,
391             accountlines_id       => $accountlines_id,
392             manager_id            => $manager_id,
393         }));
394     }
395
396     $query ="
397         INSERT INTO accountlines
398         ( borrowernumber, accountno, itemnumber, date, amount, description, accounttype, manager_id, note )
399         VALUES ( ?, ?, ?, NOW(), ?, 'Writeoff', 'W', ?, ? )
400     ";
401     $sth = $dbh->prepare( $query );
402     my $acct = getnextacctno($borrowernumber);
403     $sth->execute( $borrowernumber, $acct, $itemnum, $amount, $manager_id, $payment_note );
404
405     if ( C4::Context->preference("FinesLog") ) {
406         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
407             action            => 'create_writeoff',
408             borrowernumber    => $borrowernumber,
409             accountno         => $acct,
410             amount            => 0 - $amount,
411             accounttype       => 'W',
412             itemnumber        => $itemnum,
413             accountlines_paid => [ $accountlines_id ],
414             manager_id        => $manager_id,
415         }));
416     }
417
418     UpdateStats({
419                 branch => $branch,
420                 type => 'writeoff',
421                 amount => $amount,
422                 borrowernumber => $borrowernumber}
423     );
424
425 }
426
427 =head2 purge_zero_balance_fees
428
429   purge_zero_balance_fees( $days );
430
431 Delete accountlines entries where amountoutstanding is 0 or NULL which are more than a given number of days old.
432
433 B<$days> -- Zero balance fees older than B<$days> days old will be deleted.
434
435 B<Warning:> Because fines and payments are not linked in accountlines, it is
436 possible for a fine to be deleted without the accompanying payment,
437 or vise versa. This won't affect the account balance, but might be
438 confusing to staff.
439
440 =cut
441
442 sub purge_zero_balance_fees {
443     my $days  = shift;
444     my $count = 0;
445
446     my $dbh = C4::Context->dbh;
447     my $sth = $dbh->prepare(
448         q{
449             DELETE FROM accountlines
450             WHERE date < date_sub(curdate(), INTERVAL ? DAY)
451               AND ( amountoutstanding = 0 or amountoutstanding IS NULL );
452         }
453     );
454     $sth->execute($days) or die $dbh->errstr;
455 }
456
457 END { }    # module clean-up code here (global destructor)
458
459 1;
460 __END__
461
462 =head1 SEE ALSO
463
464 DBI(3)
465
466 =cut
467