Bug 20990: Add Koha::Account->outstanding_credits
[koha-equinox.git] / Koha / Account.pm
1 package Koha::Account;
2
3 # Copyright 2016 ByWater Solutions
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 use Modern::Perl;
21
22 use Carp;
23 use Data::Dumper;
24 use List::MoreUtils qw( uniq );
25
26 use C4::Log qw( logaction );
27 use C4::Stats qw( UpdateStats );
28
29 use Koha::Account::Lines;
30 use Koha::Account::Offsets;
31 use Koha::DateUtils qw( dt_from_string );
32
33 =head1 NAME
34
35 Koha::Accounts - Module for managing payments and fees for patrons
36
37 =cut
38
39 sub new {
40     my ( $class, $params ) = @_;
41
42     Carp::croak("No patron id passed in!") unless $params->{patron_id};
43
44     return bless( $params, $class );
45 }
46
47 =head2 pay
48
49 This method allows payments to be made against fees/fines
50
51 Koha::Account->new( { patron_id => $borrowernumber } )->pay(
52     {
53         amount      => $amount,
54         sip         => $sipmode,
55         note        => $note,
56         description => $description,
57         library_id  => $branchcode,
58         lines        => $lines, # Arrayref of Koha::Account::Line objects to pay
59         account_type => $type,  # accounttype code
60         offset_type => $offset_type,    # offset type code
61     }
62 );
63
64 =cut
65
66 sub pay {
67     my ( $self, $params ) = @_;
68
69     my $amount       = $params->{amount};
70     my $sip          = $params->{sip};
71     my $description  = $params->{description};
72     my $note         = $params->{note} || q{};
73     my $library_id   = $params->{library_id};
74     my $lines        = $params->{lines};
75     my $type         = $params->{type} || 'payment';
76     my $payment_type = $params->{payment_type} || undef;
77     my $account_type = $params->{account_type};
78     my $offset_type  = $params->{offset_type} || $type eq 'writeoff' ? 'Writeoff' : 'Payment';
79
80     my $userenv = C4::Context->userenv;
81
82     # We should remove accountno, it is no longer needed
83     my $last = Koha::Account::Lines->search(
84         {
85             borrowernumber => $self->{patron_id}
86         },
87         {
88             order_by => 'accountno'
89         }
90     )->next();
91     my $accountno = $last ? $last->accountno + 1 : 1;
92
93     my $manager_id = $userenv ? $userenv->{number} : 0;
94
95     my @fines_paid; # List of account lines paid on with this payment
96
97     my $balance_remaining = $amount; # Set it now so we can adjust the amount if necessary
98     $balance_remaining ||= 0;
99
100     my @account_offsets;
101
102     # We were passed a specific line to pay
103     foreach my $fine ( @$lines ) {
104         my $amount_to_pay =
105             $fine->amountoutstanding > $balance_remaining
106           ? $balance_remaining
107           : $fine->amountoutstanding;
108
109         my $old_amountoutstanding = $fine->amountoutstanding;
110         my $new_amountoutstanding = $old_amountoutstanding - $amount_to_pay;
111         $fine->amountoutstanding($new_amountoutstanding)->store();
112         $balance_remaining = $balance_remaining - $amount_to_pay;
113
114         if ( $fine->itemnumber && $fine->accounttype && ( $fine->accounttype eq 'Rep' || $fine->accounttype eq 'L' ) )
115         {
116             C4::Circulation::ReturnLostItem( $self->{patron_id}, $fine->itemnumber );
117         }
118
119         my $account_offset = Koha::Account::Offset->new(
120             {
121                 debit_id => $fine->id,
122                 type     => $offset_type,
123                 amount   => $amount_to_pay * -1,
124             }
125         );
126         push( @account_offsets, $account_offset );
127
128         if ( C4::Context->preference("FinesLog") ) {
129             logaction(
130                 "FINES", 'MODIFY',
131                 $self->{patron_id},
132                 Dumper(
133                     {
134                         action                => 'fee_payment',
135                         borrowernumber        => $fine->borrowernumber,
136                         old_amountoutstanding => $old_amountoutstanding,
137                         new_amountoutstanding => 0,
138                         amount_paid           => $old_amountoutstanding,
139                         accountlines_id       => $fine->id,
140                         accountno             => $fine->accountno,
141                         manager_id            => $manager_id,
142                         note                  => $note,
143                     }
144                 )
145             );
146             push( @fines_paid, $fine->id );
147         }
148     }
149
150     # Were not passed a specific line to pay, or the payment was for more
151     # than the what was owed on the given line. In that case pay down other
152     # lines with remaining balance.
153     my @outstanding_fines;
154     @outstanding_fines = Koha::Account::Lines->search(
155         {
156             borrowernumber    => $self->{patron_id},
157             amountoutstanding => { '>' => 0 },
158         }
159     ) if $balance_remaining > 0;
160
161     foreach my $fine (@outstanding_fines) {
162         my $amount_to_pay =
163             $fine->amountoutstanding > $balance_remaining
164           ? $balance_remaining
165           : $fine->amountoutstanding;
166
167         my $old_amountoutstanding = $fine->amountoutstanding;
168         $fine->amountoutstanding( $old_amountoutstanding - $amount_to_pay );
169         $fine->store();
170
171         my $account_offset = Koha::Account::Offset->new(
172             {
173                 debit_id => $fine->id,
174                 type     => $offset_type,
175                 amount   => $amount_to_pay * -1,
176             }
177         );
178         push( @account_offsets, $account_offset );
179
180         if ( C4::Context->preference("FinesLog") ) {
181             logaction(
182                 "FINES", 'MODIFY',
183                 $self->{patron_id},
184                 Dumper(
185                     {
186                         action                => "fee_$type",
187                         borrowernumber        => $fine->borrowernumber,
188                         old_amountoutstanding => $old_amountoutstanding,
189                         new_amountoutstanding => $fine->amountoutstanding,
190                         amount_paid           => $amount_to_pay,
191                         accountlines_id       => $fine->id,
192                         accountno             => $fine->accountno,
193                         manager_id            => $manager_id,
194                         note                  => $note,
195                     }
196                 )
197             );
198             push( @fines_paid, $fine->id );
199         }
200
201         $balance_remaining = $balance_remaining - $amount_to_pay;
202         last unless $balance_remaining > 0;
203     }
204
205     $account_type ||=
206         $type eq 'writeoff' ? 'W'
207       : defined($sip)       ? "Pay$sip"
208       :                       'Pay';
209
210     $description ||= $type eq 'writeoff' ? 'Writeoff' : q{};
211
212     my $payment = Koha::Account::Line->new(
213         {
214             borrowernumber    => $self->{patron_id},
215             accountno         => $accountno,
216             date              => dt_from_string(),
217             amount            => 0 - $amount,
218             description       => $description,
219             accounttype       => $account_type,
220             payment_type      => $payment_type,
221             amountoutstanding => 0 - $balance_remaining,
222             manager_id        => $manager_id,
223             note              => $note,
224         }
225     )->store();
226
227     foreach my $o ( @account_offsets ) {
228         $o->credit_id( $payment->id() );
229         $o->store();
230     }
231
232     $library_id ||= $userenv ? $userenv->{'branch'} : undef;
233
234     UpdateStats(
235         {
236             branch         => $library_id,
237             type           => $type,
238             amount         => $amount,
239             borrowernumber => $self->{patron_id},
240             accountno      => $accountno,
241         }
242     );
243
244     if ( C4::Context->preference("FinesLog") ) {
245         logaction(
246             "FINES", 'CREATE',
247             $self->{patron_id},
248             Dumper(
249                 {
250                     action            => "create_$type",
251                     borrowernumber    => $self->{patron_id},
252                     accountno         => $accountno,
253                     amount            => 0 - $amount,
254                     amountoutstanding => 0 - $balance_remaining,
255                     accounttype       => $account_type,
256                     accountlines_paid => \@fines_paid,
257                     manager_id        => $manager_id,
258                 }
259             )
260         );
261     }
262
263     return $payment->id;
264 }
265
266 =head3 add_credit
267
268 This method allows adding credits to a patron's account
269
270 my $credit_line = Koha::Account->new({ patron_id => $patron_id })->add_credit(
271     {
272         amount       => $amount,
273         description  => $description,
274         note         => $note,
275         user_id      => $user_id,
276         library_id   => $library_id,
277         sip          => $sip,
278         payment_type => $payment_type,
279         type         => $credit_type,
280         item_id      => $item_id
281     }
282 );
283
284 $credit_type can be any of:
285   - 'credit'
286   - 'payment'
287   - 'forgiven'
288   - 'lost_item_return'
289   - 'writeoff'
290
291 =cut
292
293 sub add_credit {
294
295     my ( $self, $params ) = @_;
296
297     # amount is passed as a positive value, but we store credit as negative values
298     my $amount       = $params->{amount} * -1;
299     my $description  = $params->{description} // q{};
300     my $note         = $params->{note} // q{};
301     my $user_id      = $params->{user_id};
302     my $library_id   = $params->{library_id};
303     my $sip          = $params->{sip};
304     my $payment_type = $params->{payment_type};
305     my $type         = $params->{type} || 'payment';
306     my $item_id      = $params->{item_id};
307
308     my $schema = Koha::Database->new->schema;
309
310     my $account_type = $Koha::Account::account_type->{$type};
311     $account_type .= $sip
312         if defined $sip &&
313            $type eq 'payment';
314
315     my $line;
316
317     $schema->txn_do(
318         sub {
319             # We should remove accountno, it is no longer needed
320             my $last = Koha::Account::Lines->search( { borrowernumber => $self->{patron_id} },
321                 { order_by => 'accountno' } )->next();
322             my $accountno = $last ? $last->accountno + 1 : 1;
323
324             # Insert the account line
325             $line = Koha::Account::Line->new(
326                 {   borrowernumber    => $self->{patron_id},
327                     date              => \'NOW()',
328                     amount            => $amount,
329                     description       => $description,
330                     accounttype       => $account_type,
331                     amountoutstanding => $amount,
332                     payment_type      => $payment_type,
333                     note              => $note,
334                     manager_id        => $user_id,
335                     itemnumber        => $item_id
336                 }
337             )->store();
338
339             # Record the account offset
340             my $account_offset = Koha::Account::Offset->new(
341                 {   credit_id => $line->id,
342                     type      => $Koha::Account::offset_type->{$type},
343                     amount    => $amount
344                 }
345             )->store();
346
347             UpdateStats(
348                 {   branch         => $library_id,
349                     type           => $type,
350                     amount         => $amount,
351                     borrowernumber => $self->{patron_id},
352                     accountno      => $accountno,
353                 }
354             ) if grep { $type eq $_ } ('payment', 'writeoff') ;
355
356             if ( C4::Context->preference("FinesLog") ) {
357                 logaction(
358                     "FINES", 'CREATE',
359                     $self->{patron_id},
360                     Dumper(
361                         {   action            => "create_$type",
362                             borrowernumber    => $self->{patron_id},
363                             accountno         => $accountno,
364                             amount            => $amount,
365                             description       => $description,
366                             amountoutstanding => $amount,
367                             accounttype       => $account_type,
368                             note              => $note,
369                             itemnumber        => $item_id,
370                             manager_id        => $user_id,
371                         }
372                     )
373                 );
374             }
375         }
376     );
377
378     return $line;
379 }
380
381 =head3 balance
382
383 my $balance = $self->balance
384
385 Return the balance (sum of amountoutstanding columns)
386
387 =cut
388
389 sub balance {
390     my ($self) = @_;
391     my $fines = Koha::Account::Lines->search(
392         {
393             borrowernumber => $self->{patron_id},
394         },
395         {
396             select => [ { sum => 'amountoutstanding' } ],
397             as => ['total_amountoutstanding'],
398         }
399     );
400
401     return ( $fines->count )
402       ? $fines->next->get_column('total_amountoutstanding') + 0
403       : 0;
404 }
405
406 =head3 outstanding_debits
407
408 my $lines = Koha::Account->new({ patron_id => $patron_id })->outstanding_debits;
409
410 =cut
411
412 sub outstanding_debits {
413     my ($self) = @_;
414
415     my $lines = Koha::Account::Lines->search(
416         {
417             borrowernumber    => $self->{patron_id},
418             amountoutstanding => { '>' => 0 }
419         }
420     );
421
422     return $lines;
423 }
424
425 =head3 outstanding_credits
426
427 my ( $total, $lines ) = Koha::Account->new({ patron_id => $patron_id })->outstanding_credits;
428
429 =cut
430
431 sub outstanding_credits {
432     my ($self) = @_;
433
434     my $outstanding_credits = Koha::Account::Lines->search(
435         {   borrowernumber    => $self->{patron_id},
436             amountoutstanding => { '<' => 0 }
437         },
438         {   select => [ { sum => 'amountoutstanding' } ],
439             as     => ['outstanding_credits_total'],
440         }
441     );
442     my $total
443         = ( $outstanding_credits->count )
444         ? $outstanding_credits->next->get_column('outstanding_credits_total') + 0
445         : 0;
446
447     my $lines = Koha::Account::Lines->search(
448         {
449             borrowernumber    => $self->{patron_id},
450             amountoutstanding => { '<' => 0 }
451         }
452     );
453
454     return ( $total, $lines );
455 }
456
457 =head3 non_issues_charges
458
459 my $non_issues_charges = $self->non_issues_charges
460
461 Calculates amount immediately owing by the patron - non-issue charges.
462
463 Charges exempt from non-issue are:
464 * Res (holds) if HoldsInNoissuesCharge syspref is set to false
465 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
466 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
467
468 =cut
469
470 sub non_issues_charges {
471     my ($self) = @_;
472
473     # FIXME REMOVE And add a warning in the about page + update DB if length(MANUAL_INV) > 5
474     my $ACCOUNT_TYPE_LENGTH = 5;    # this is plain ridiculous...
475
476     my @not_fines;
477     push @not_fines, 'Res'
478       unless C4::Context->preference('HoldsInNoissuesCharge');
479     push @not_fines, 'Rent'
480       unless C4::Context->preference('RentalsInNoissuesCharge');
481     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
482         my $dbh = C4::Context->dbh;
483         push @not_fines,
484           @{
485             $dbh->selectcol_arrayref(q|
486                 SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'
487             |)
488           };
489     }
490     @not_fines = map { substr( $_, 0, $ACCOUNT_TYPE_LENGTH ) } uniq(@not_fines);
491
492     my $non_issues_charges = Koha::Account::Lines->search(
493         {
494             borrowernumber => $self->{patron_id},
495             accounttype    => { -not_in => \@not_fines }
496         },
497         {
498             select => [ { sum => 'amountoutstanding' } ],
499             as     => ['non_issues_charges'],
500         }
501     );
502     return $non_issues_charges->count
503       ? $non_issues_charges->next->get_column('non_issues_charges') + 0
504       : 0;
505 }
506
507 1;
508
509 =head2 Name mappings
510
511 =head3 $offset_type
512
513 =cut
514
515 our $offset_type = {
516     'credit'           => 'Manual Credit',
517     'forgiven'         => 'Writeoff',
518     'lost_item_return' => 'Lost Item Return',
519     'payment'          => 'Payment',
520     'writeoff'         => 'Writeoff'
521 };
522
523 =head3 $account_type
524
525 =cut
526
527 our $account_type = {
528     'credit'           => 'C',
529     'forgiven'         => 'FOR',
530     'lost_item_return' => 'CR',
531     'payment'          => 'Pay',
532     'writeoff'         => 'W'
533 };
534
535 =head1 AUTHOR
536
537 Kyle M Hall <kyle.m.hall@gmail.com>
538
539 =cut