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