Bug 15897 [QA Followup] - Update unit tests
[koha.git] / t / db_dependent / Accounts.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, see <http://www.gnu.org/licenses>.
18
19 use Modern::Perl;
20
21 use Test::More tests => 21;
22 use Test::MockModule;
23 use Test::Warn;
24
25 use t::lib::TestBuilder;
26
27 use Koha::Account::Lines;
28 use Koha::Account::Line;
29
30 BEGIN {
31     use_ok('C4::Accounts');
32     use_ok('Koha::Object');
33     use_ok('Koha::Patron');
34     use_ok('Data::Dumper');
35 }
36
37 can_ok( 'C4::Accounts',
38     qw(
39         makepayment
40         getnextacctno
41         chargelostitem
42         manualinvoice
43         getcharges
44         ModNote
45         getcredits
46         getrefunds
47         ReversePayment
48         recordpayment_selectaccts
49         makepartialpayment
50         WriteOffFee
51         purge_zero_balance_fees )
52 );
53
54 my $schema  = Koha::Database->new->schema;
55 $schema->storage->txn_begin;
56 my $dbh = C4::Context->dbh;
57
58 my $builder = t::lib::TestBuilder->new;
59 my $library = $builder->build( { source => 'Branch' } );
60
61 $dbh->do(q|DELETE FROM accountlines|);
62 $dbh->do(q|DELETE FROM issues|);
63 $dbh->do(q|DELETE FROM borrowers|);
64
65 my $branchcode = $library->{branchcode};
66 my $borrower_number;
67
68 my $context = new Test::MockModule('C4::Context');
69 $context->mock( 'userenv', sub {
70     return {
71         flags  => 1,
72         id     => 'my_userid',
73         branch => $branchcode,
74     };
75 });
76
77 # Testing purge_zero_balance_fees
78
79 # The 3rd value in the insert is 'days ago' --
80 # 0 => today
81 # 1 => yesterday
82 # etc.
83
84 my $sth = $dbh->prepare(
85     "INSERT INTO accountlines (
86          borrowernumber,
87          amountoutstanding,
88          date,
89          description
90      )
91      VALUES ( ?, ?, (select date_sub(CURRENT_DATE, INTERVAL ? DAY) ), ? )"
92 );
93
94 my $days = 5;
95
96 my @test_data = (
97     { amount => 0     , days_ago => 0         , description =>'purge_zero_balance_fees should not delete 0 balance fees with date today'                     , delete => 0 } ,
98     { amount => 0     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete 0 balance fees with date before threshold day'      , delete => 0 } ,
99     { amount => 0     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete 0 balance fees with date on threshold day'          , delete => 0 } ,
100     { amount => 0     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete 0 balance fees with date after threshold day'           , delete => 1 } ,
101     { amount => undef , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete NULL balance fees with date after threshold day'        , delete => 1 } ,
102     { amount => 5     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed before threshold day'  , delete => 0 } ,
103     { amount => 5     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with positive amout owed on threshold day'      , delete => 0 } ,
104     { amount => 5     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed after threshold day'   , delete => 0 } ,
105     { amount => -5    , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed before threshold day' , delete => 0 } ,
106     { amount => -5    , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with negative amout owed on threshold day'     , delete => 0 } ,
107     { amount => -5    , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed after threshold day'  , delete => 0 }
108 );
109
110 my $borrower = Koha::Patron->new( { firstname => 'Test', surname => 'Patron', categorycode => 'PT', branchcode => $branchcode } )->store();
111
112 for my $data ( @test_data ) {
113     $sth->execute($borrower->borrowernumber, $data->{amount}, $data->{days_ago}, $data->{description});
114 }
115
116 purge_zero_balance_fees( $days );
117
118 $sth = $dbh->prepare(
119             "select count(*) = 0 as deleted
120              from accountlines
121              where description = ?"
122        );
123
124 #
125 sub is_delete_correct {
126     my $should_delete = shift;
127     my $description = shift;
128     $sth->execute( $description );
129     my $test = $sth->fetchrow_hashref();
130     is( $test->{deleted}, $should_delete, $description )
131 }
132
133 for my $data  (@test_data) {
134     is_delete_correct( $data->{delete}, $data->{description});
135 }
136
137 $dbh->do(q|DELETE FROM accountlines|);
138
139 subtest "Koha::Account::pay tests" => sub {
140
141     plan tests => 12;
142
143     # Create a borrower
144     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
145     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
146
147     my $borrower = Koha::Patron->new( {
148         cardnumber => '1234567890',
149         surname => 'McFly',
150         firstname => 'Marty',
151     } );
152     $borrower->categorycode( $categorycode );
153     $borrower->branchcode( $branchcode );
154     $borrower->store;
155
156     my $account = Koha::Account->new({ patron_id => $borrower->id });
157
158     my $line1 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 100 })->store();
159     my $line2 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 200 })->store();
160
161     $sth = $dbh->prepare("SELECT count(*) FROM accountlines");
162     $sth->execute;
163     my $count = $sth->fetchrow_array;
164     is($count, 2, 'There is 2 lines as expected');
165
166     # There is $100 in the account
167     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
168     my $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
169     my $amountleft = 0;
170     for my $line ( @$amountoutstanding ) {
171         $amountleft += $line;
172     }
173     is($amountleft, 300, 'The account has 300$ as expected' );
174
175     # We make a $20 payment
176     my $borrowernumber = $borrower->borrowernumber;
177     my $data = '20.00';
178     my $payment_note = '$20.00 payment note';
179     $account->pay( { amount => $data, note => $payment_note } );
180
181     # There is now $280 in the account
182     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
183     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
184     $amountleft = 0;
185     for my $line ( @$amountoutstanding ) {
186         $amountleft += $line;
187     }
188     is($amountleft, 280, 'The account has $280 as expected' );
189
190     # Is the payment note well registered
191     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
192     $sth->execute($borrower->borrowernumber);
193     my $note = $sth->fetchrow_array;
194     is($note,'$20.00 payment note', '$20.00 payment note is registered');
195
196     # We make a -$30 payment (a NEGATIVE payment)
197     $data = '-30.00';
198     $payment_note = '-$30.00 payment note';
199     $account->pay( { amount => $data, note => $payment_note } );
200
201     # There is now $310 in the account
202     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
203     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
204     $amountleft = 0;
205     for my $line ( @$amountoutstanding ) {
206         $amountleft += $line;
207     }
208     is($amountleft, 310, 'The account has $310 as expected' );
209     # Is the payment note well registered
210     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
211     $sth->execute($borrower->borrowernumber);
212     $note = $sth->fetchrow_array;
213     is($note,'-$30.00 payment note', '-$30.00 payment note is registered');
214
215     #We make a $150 payment ( > 1stLine )
216     $data = '150.00';
217     $payment_note = '$150.00 payment note';
218     $account->pay( { amount => $data, note => $payment_note } );
219
220     # There is now $160 in the account
221     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
222     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
223     $amountleft = 0;
224     for my $line ( @$amountoutstanding ) {
225         $amountleft += $line;
226     }
227     is($amountleft, 160, 'The account has $160 as expected' );
228
229     # Is the payment note well registered
230     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
231     $sth->execute($borrower->borrowernumber);
232     $note = $sth->fetchrow_array;
233     is($note,'$150.00 payment note', '$150.00 payment note is registered');
234
235     #We make a $200 payment ( > amountleft )
236     $data = '200.00';
237     $payment_note = '$200.00 payment note';
238     $account->pay( { amount => $data, note => $payment_note } );
239
240     # There is now -$40 in the account
241     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
242     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
243     $amountleft = 0;
244     for my $line ( @$amountoutstanding ) {
245         $amountleft += $line;
246     }
247     is($amountleft, -40, 'The account has -$40 as expected, (credit situation)' );
248
249     # Is the payment note well registered
250     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
251     $sth->execute($borrower->borrowernumber);
252     $note = $sth->fetchrow_array;
253     is($note,'$200.00 payment note', '$200.00 payment note is registered');
254
255     my $line3 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 42, accounttype => 'TEST' })->store();
256     my $payment_id = $account->pay( { lines => [$line3], amount => 42 } );
257     my $payment = Koha::Account::Lines->find( $payment_id );
258     is( $payment->amount(), '-42.000000', "Payment paid the specified fine" );
259     $line3 = Koha::Account::Lines->find( $line3->id );
260     is( $line3->amountoutstanding, '0.000000', "Specified fine is paid" );
261 };
262
263 subtest "Koha::Account::pay particular line tests" => sub {
264
265     plan tests => 5;
266
267     # Create a borrower
268     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
269     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
270
271     my $borrower = Koha::Patron->new( {
272         cardnumber => 'kylemhall',
273         surname => 'Hall',
274         firstname => 'Kyle',
275     } );
276     $borrower->categorycode( $categorycode );
277     $borrower->branchcode( $branchcode );
278     $borrower->store;
279
280     my $account = Koha::Account->new({ patron_id => $borrower->id });
281
282     my $line1 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 1 })->store();
283     my $line2 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 2 })->store();
284     my $line3 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 3 })->store();
285     my $line4 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 4 })->store();
286
287     is( $account->balance(), "10.000000", "Account balance is 10" );
288
289     $account->pay(
290         {
291             lines => [$line2, $line3, $line4],
292             amount => 4,
293         }
294     );
295
296     $_->_result->discard_changes foreach ( $line1, $line2, $line3, $line4 );
297
298     # Line1 is not paid at all, as it was not passed in the lines param
299     is( $line1->amountoutstanding, "1.000000", "Line 1 was not paid" );
300     # Line2 was paid in full, as it was the first in the lines list
301     is( $line2->amountoutstanding, "0.000000", "Line 2 was paid in full" );
302     # Line3 was paid partially, as the remaining balance did not cover it entirely
303     is( $line3->amountoutstanding, "1.000000", "Line 3 was paid to 1.00" );
304     # Line4 was not paid at all, as the payment was all used up by that point
305     is( $line4->amountoutstanding, "4.000000", "Line 4 was not paid" );
306 };
307
308 subtest "makepayment() tests" => sub {
309
310     plan tests => 6;
311
312     # Create a borrower
313     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
314     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
315     $branchcode = $branch;
316     my $borrowernumber = $builder->build({
317         source => 'Borrower',
318         value  => { categorycode => $category,
319                     branchcode   => $branch }
320     })->{ borrowernumber };
321
322     my $amount = 100;
323     my $accountline = $builder->build({ source => 'Accountline',
324         value  => { borrowernumber => $borrowernumber,
325                     amount => $amount,
326                     amountoutstanding => $amount }
327     });
328
329     my $rs = $schema->resultset('Accountline')->search({
330         borrowernumber => $borrowernumber
331     });
332
333     is( $rs->count(), 1, 'Accountline created' );
334
335     # make the full payment
336     makepayment(
337         $accountline->{ accountlines_id }, $borrowernumber,
338         $accountline->{ accountno },       $amount,
339         $borrowernumber, $branch, 'A payment note' );
340
341     # TODO: someone should write actual tests for makepayment()
342
343     my $stat = $schema->resultset('Statistic')->search({
344         branch  => $branch,
345         type    => 'payment'
346     }, { order_by => { -desc => 'datetime' } })->next();
347
348     ok( defined $stat, "There's a payment log that matches the branch" );
349
350     SKIP: {
351         skip "No statistic logged", 4 unless defined $stat;
352
353         is( $stat->type, 'payment', "Correct statistic type" );
354         is( $stat->branch, $branch, "Correct branch logged to statistics" );
355         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
356         is( $stat->value, "$amount" . "\.0000", "Correct amount logged to statistics" );
357     }
358 };
359
360 subtest "makepartialpayment() tests" => sub {
361
362     plan tests => 6;
363
364     # Create a borrower
365     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
366     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
367     $branchcode = $branch;
368     my $borrowernumber = $builder->build({
369         source => 'Borrower',
370         value  => { categorycode => $category,
371                     branchcode   => $branch }
372     })->{ borrowernumber };
373
374     my $amount = 100;
375     my $partialamount = 60;
376     my $accountline = $builder->build({ source => 'Accountline',
377         value  => { borrowernumber => $borrowernumber,
378                     amount => $amount,
379                     amountoutstanding => $amount }
380     });
381
382     my $rs = $schema->resultset('Accountline')->search({
383         borrowernumber => $borrowernumber
384     });
385
386     is( $rs->count(), 1, 'Accountline created' );
387
388     # make the full payment
389     makepartialpayment(
390         $accountline->{ accountlines_id }, $borrowernumber,
391         $accountline->{ accountno },       $partialamount,
392         $borrowernumber, $branch, 'A payment note' );
393
394     # TODO: someone should write actual tests for makepartialpayment()
395
396     my $stat = $schema->resultset('Statistic')->search({
397         branch  => $branch,
398         type    => 'payment'
399     }, { order_by => { -desc => 'datetime' } })->next();
400
401     ok( defined $stat, "There's a payment log that matches the branch" );
402
403     SKIP: {
404         skip "No statistic logged", 4 unless defined $stat;
405
406         is( $stat->type, 'payment', "Correct statistic type" );
407         is( $stat->branch, $branch, "Correct branch logged to statistics" );
408         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
409         is( $stat->value, "$partialamount" . "\.0000", "Correct amount logged to statistics" );
410     }
411 };
412
413 subtest 'balance' => sub {
414     plan tests => 2;
415
416     my $patron = $builder->build({source => 'Borrower'});
417     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
418     my $account = $patron->account;
419     is( $account->balance, 0, 'balance should return 0 if the patron does not have fines' );
420
421     my $accountline_1 = $builder->build(
422         {
423             source => 'Accountline',
424             value  => {
425                 borrowernumber    => $patron->borrowernumber,
426                 amount            => 42,
427                 amountoutstanding => 42
428             }
429         }
430     );
431     my $accountline_2 = $builder->build(
432         {
433             source => 'Accountline',
434             value  => {
435                 borrowernumber    => $patron->borrowernumber,
436                 amount            => -13,
437                 amountoutstanding => -13
438             }
439         }
440     );
441
442     my $balance = $patron->account->balance;
443     is( int($balance), 29, 'balance should return the correct value');
444
445     $patron->delete;
446 };
447
448 1;