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