Bug 14826: (QA follow-up) Only use plural modules in other modules
[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
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
138     # first make sure the borrower hasn't already been charged for this item
139     my $existing_charges = Koha::Account::Lines->search(
140         {
141             borrowernumber => $borrowernumber,
142             itemnumber     => $itemnumber,
143             accounttype    => 'L',
144         }
145     )->count();
146
147     # OK, they haven't
148     unless ($existing_charges) {
149         my $manager_id = 0;
150         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
151         # This item is on issue ... add replacement cost to the borrower's record and mark it returned
152         #  Note that we add this to the account even if there's no replacement price, allowing some other
153         #  process (or person) to update it, since we don't handle any defaults for replacement prices.
154         my $accountno = getnextacctno($borrowernumber);
155
156         my $accountline = Koha::Account::Line->new(
157             {
158                 borrowernumber    => $borrowernumber,
159                 accountno         => $accountno,
160                 date              => \'NOW()',
161                 amount            => $amount,
162                 description       => $description,
163                 accounttype       => 'L',
164                 amountoutstanding => $amount,
165                 itemnumber        => $itemnumber,
166                 manager_id        => $manager_id,
167             }
168         )->store();
169
170         my $account_offset = Koha::Account::Offset->new(
171             {
172                 debit_id => $accountline->id,
173                 type     => 'Lost Item',
174                 amount   => $amount,
175             }
176         )->store();
177
178         if ( C4::Context->preference("FinesLog") ) {
179             logaction("FINES", 'CREATE', $borrowernumber, Dumper({
180                 action            => 'create_fee',
181                 borrowernumber    => $borrowernumber,
182                 accountno         => $accountno,
183                 amount            => $amount,
184                 amountoutstanding => $amount,
185                 description       => $description,
186                 accounttype       => 'L',
187                 itemnumber        => $itemnumber,
188                 manager_id        => $manager_id,
189             }));
190         }
191
192     }
193 }
194
195 =head2 manualinvoice
196
197   &manualinvoice($borrowernumber, $itemnumber, $description, $type,
198                  $amount, $note);
199
200 C<$borrowernumber> is the patron's borrower number.
201 C<$description> is a description of the transaction.
202 C<$type> may be one of C<CS>, C<CB>, C<CW>, C<CF>, C<CL>, C<N>, C<L>,
203 or C<REF>.
204 C<$itemnumber> is the item involved, if pertinent; otherwise, it
205 should be the empty string.
206
207 =cut
208
209 #'
210 # FIXME: In Koha 3.0 , the only account adjustment 'types' passed to this function
211 # are:
212 #               'C' = CREDIT
213 #               'FOR' = FORGIVEN  (Formerly 'F', but 'F' is taken to mean 'FINE' elsewhere)
214 #               'N' = New Card fee
215 #               'F' = Fine
216 #               'A' = Account Management fee
217 #               'M' = Sundry
218 #               'L' = Lost Item
219 #
220
221 sub manualinvoice {
222     my ( $borrowernumber, $itemnum, $desc, $type, $amount, $note ) = @_;
223     my $manager_id = 0;
224     $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
225     my $dbh      = C4::Context->dbh;
226     my $notifyid = 0;
227     my $insert;
228     my $accountno  = getnextacctno($borrowernumber);
229     my $amountleft = $amount;
230
231     if (   ( $type eq 'L' )
232         or ( $type eq 'F' )
233         or ( $type eq 'A' )
234         or ( $type eq 'N' )
235         or ( $type eq 'M' ) )
236     {
237         $notifyid = 1;
238     }
239
240     my $accountline = Koha::Account::Line->new(
241         {
242             borrowernumber    => $borrowernumber,
243             accountno         => $accountno,
244             date              => \'NOW()',
245             amount            => $amount,
246             description       => $desc,
247             accounttype       => $type,
248             amountoutstanding => $amountleft,
249             itemnumber        => $itemnum || undef,
250             notify_id         => $notifyid,
251             note              => $note,
252             manager_id        => $manager_id,
253         }
254     )->store();
255
256     my $account_offset = Koha::Account::Offset->new(
257         {
258             debit_id => $accountline->id,
259             type     => 'Manual Debit',
260             amount   => $amount,
261         }
262     )->store();
263
264     if ( C4::Context->preference("FinesLog") ) {
265         logaction("FINES", 'CREATE',$borrowernumber,Dumper({
266             action            => 'create_fee',
267             borrowernumber    => $borrowernumber,
268             accountno         => $accountno,
269             amount            => $amount,
270             description       => $desc,
271             accounttype       => $type,
272             amountoutstanding => $amountleft,
273             notify_id         => $notifyid,
274             note              => $note,
275             itemnumber        => $itemnum,
276             manager_id        => $manager_id,
277         }));
278     }
279
280     return 0;
281 }
282
283 sub getcharges {
284         my ( $borrowerno, $timestamp, $accountno ) = @_;
285         my $dbh        = C4::Context->dbh;
286         my $timestamp2 = $timestamp - 1;
287         my $query      = "";
288         my $sth = $dbh->prepare(
289                         "SELECT * FROM accountlines WHERE borrowernumber=? AND accountno = ?"
290           );
291         $sth->execute( $borrowerno, $accountno );
292         
293     my @results;
294     while ( my $data = $sth->fetchrow_hashref ) {
295                 push @results,$data;
296         }
297     return (@results);
298 }
299
300 sub ModNote {
301     my ( $accountlines_id, $note ) = @_;
302     my $dbh = C4::Context->dbh;
303     my $sth = $dbh->prepare('UPDATE accountlines SET note = ? WHERE accountlines_id = ?');
304     $sth->execute( $note, $accountlines_id );
305 }
306
307 sub getcredits {
308         my ( $date, $date2 ) = @_;
309         my $dbh = C4::Context->dbh;
310         my $sth = $dbh->prepare(
311                                 "SELECT * FROM accountlines,borrowers
312       WHERE amount < 0 AND accounttype not like 'Pay%' AND accountlines.borrowernumber = borrowers.borrowernumber
313           AND timestamp >=TIMESTAMP(?) AND timestamp < TIMESTAMP(?)"
314       );  
315
316     $sth->execute( $date, $date2 );
317     my @results;          
318     while ( my $data = $sth->fetchrow_hashref ) {
319                 $data->{'date'} = $data->{'timestamp'};
320                 push @results,$data;
321         }
322     return (@results);
323
324
325
326 sub getrefunds {
327         my ( $date, $date2 ) = @_;
328         my $dbh = C4::Context->dbh;
329         
330         my $sth = $dbh->prepare(
331                                 "SELECT *,timestamp AS datetime                                                                                      
332                   FROM accountlines,borrowers
333                   WHERE (accounttype = 'REF'
334                                           AND accountlines.borrowernumber = borrowers.borrowernumber
335                                                           AND date  >=?  AND date  <?)"
336     );
337
338     $sth->execute( $date, $date2 );
339
340     my @results;
341     while ( my $data = $sth->fetchrow_hashref ) {
342                 push @results,$data;
343                 
344         }
345     return (@results);
346 }
347
348 #FIXME: ReversePayment should be replaced with a Void Payment feature
349 sub ReversePayment {
350     my ($accountlines_id) = @_;
351     my $dbh = C4::Context->dbh;
352
353     my $accountline        = Koha::Account::Lines->find($accountlines_id);
354     my $amount_outstanding = $accountline->amountoutstanding;
355
356     my $new_amountoutstanding =
357       $amount_outstanding <= 0 ? $accountline->amount * -1 : 0;
358
359     $accountline->description( $accountline->description . " Reversed -" );
360     $accountline->amountoutstanding($new_amountoutstanding);
361     $accountline->store();
362
363     my $account_offset = Koha::Account::Offset->new(
364         {
365             credit_id => $accountline->id,
366             type      => 'Reverse Payment',
367             amount    => $amount_outstanding - $new_amountoutstanding,
368         }
369     )->store();
370
371     if ( C4::Context->preference("FinesLog") ) {
372         my $manager_id = 0;
373         $manager_id = C4::Context->userenv->{'number'} if C4::Context->userenv;
374
375         logaction(
376             "FINES", 'MODIFY',
377             $accountline->borrowernumber,
378             Dumper(
379                 {
380                     action                => 'reverse_fee_payment',
381                     borrowernumber        => $accountline->borrowernumber,
382                     old_amountoutstanding => $amount_outstanding,
383                     new_amountoutstanding => $new_amountoutstanding,
384                     ,
385                     accountlines_id => $accountline->id,
386                     accountno       => $accountline->accountno,
387                     manager_id      => $manager_id,
388                 }
389             )
390         );
391     }
392 }
393
394 =head2 purge_zero_balance_fees
395
396   purge_zero_balance_fees( $days );
397
398 Delete accountlines entries where amountoutstanding is 0 or NULL which are more than a given number of days old.
399
400 B<$days> -- Zero balance fees older than B<$days> days old will be deleted.
401
402 B<Warning:> Because fines and payments are not linked in accountlines, it is
403 possible for a fine to be deleted without the accompanying payment,
404 or vise versa. This won't affect the account balance, but might be
405 confusing to staff.
406
407 =cut
408
409 sub purge_zero_balance_fees {
410     my $days  = shift;
411     my $count = 0;
412
413     my $dbh = C4::Context->dbh;
414     my $sth = $dbh->prepare(
415         q{
416             DELETE FROM accountlines
417             WHERE date < date_sub(curdate(), INTERVAL ? DAY)
418               AND ( amountoutstanding = 0 or amountoutstanding IS NULL );
419         }
420     );
421     $sth->execute($days) or die $dbh->errstr;
422 }
423
424 END { }    # module clean-up code here (global destructor)
425
426 1;
427 __END__
428
429 =head1 SEE ALSO
430
431 DBI(3)
432
433 =cut
434