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