Bug 19036: (follow-up) Improve test output
[koha.git] / t / db_dependent / Koha / Account.t
1 #!/usr/bin/perl
2
3 # Copyright 2018 Koha Development team
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 Test::More tests => 13;
23 use Test::MockModule;
24 use Test::Exception;
25
26 use DateTime;
27
28 use Koha::Account;
29 use Koha::Account::CreditTypes;
30 use Koha::Account::Lines;
31 use Koha::Account::Offsets;
32 use Koha::DateUtils qw( dt_from_string );
33
34 use t::lib::Mocks;
35 use t::lib::TestBuilder;
36
37 my $schema  = Koha::Database->new->schema;
38 $schema->storage->dbh->{PrintError} = 0;
39 my $builder = t::lib::TestBuilder->new;
40 C4::Context->interface('commandline');
41
42 subtest 'new' => sub {
43
44     plan tests => 2;
45
46     $schema->storage->txn_begin;
47
48     throws_ok { Koha::Account->new(); } qr/No patron id passed in!/, 'Croaked on bad call to new';
49
50     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
51     my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } );
52     is( defined $account, 1, "Account is defined" );
53
54     $schema->storage->txn_rollback;
55 };
56
57 subtest 'outstanding_debits() tests' => sub {
58
59     plan tests => 22;
60
61     $schema->storage->txn_begin;
62
63     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
64     my $account = $patron->account;
65
66     my @generated_lines;
67     push @generated_lines, $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
68     push @generated_lines, $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
69     push @generated_lines, $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
70     push @generated_lines, $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
71
72     my $lines     = $account->outstanding_debits();
73     my @lines_arr = $account->outstanding_debits();
74
75     is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_debits returns a Koha::Account::Lines object' );
76     is( $lines->total_outstanding, 10, 'Outstandig debits total is correctly calculated' );
77
78     my $i = 0;
79     foreach my $line ( @{ $lines->as_list } ) {
80         my $fetched_line = Koha::Account::Lines->find( $generated_lines[$i]->id );
81         is_deeply( $line->unblessed, $fetched_line->unblessed, "Fetched line matches the generated one ($i)" );
82         is_deeply( $lines_arr[$i]->unblessed, $fetched_line->unblessed, "Fetched line matches the generated one ($i)" );
83         is( ref($lines_arr[$i]), 'Koha::Account::Line', 'outstanding_debits returns a list of Koha::Account::Line objects in list context' );
84         $i++;
85     }
86     my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
87     Koha::Account::Line->new(
88         {
89             borrowernumber    => $patron_2->id,
90             amountoutstanding => -2,
91             interface         => 'commandline',
92             credit_type_code  => 'PAYMENT'
93         }
94     )->store;
95     my $just_one = Koha::Account::Line->new(
96         {
97             borrowernumber    => $patron_2->id,
98             amount            => 3,
99             amountoutstanding => 3,
100             interface         => 'commandline',
101             debit_type_code   => 'OVERDUE'
102         }
103     )->store;
104     Koha::Account::Line->new(
105         {
106             borrowernumber    => $patron_2->id,
107             amount            => -6,
108             amountoutstanding => -6,
109             interface         => 'commandline',
110             credit_type_code  => 'PAYMENT'
111         }
112     )->store;
113     $lines = $patron_2->account->outstanding_debits();
114     is( $lines->total_outstanding, 3, "Total if some outstanding debits and some credits is only debits" );
115     is( $lines->count, 1, "With 1 outstanding debits, we get back a Lines object with 1 lines" );
116     my $the_line = Koha::Account::Lines->find( $just_one->id );
117     is_deeply( $the_line->unblessed, $lines->next->unblessed, "We get back the one correct line");
118
119     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
120     my $account_3 = $patron_3->account;
121     $account_3->add_credit( { amount => 2,   interface => 'commandline' } );
122     $account_3->add_credit( { amount => 20,  interface => 'commandline' } );
123     $account_3->add_credit( { amount => 200, interface => 'commandline' } );
124     $lines = $account_3->outstanding_debits();
125     is( $lines->total_outstanding, 0, "Total if no outstanding debits total is 0" );
126     is( $lines->count, 0, "With 0 outstanding debits, we get back a Lines object with 0 lines" );
127
128     my $patron_4  = $builder->build_object({ class => 'Koha::Patrons' });
129     my $account_4 = $patron_4->account;
130     $lines = $account_4->outstanding_debits();
131     is( $lines->total_outstanding, 0, "Total if no outstanding debits is 0" );
132     is( $lines->count, 0, "With no outstanding debits, we get back a Lines object with 0 lines" );
133
134     # create a pathological credit with amountoutstanding > 0 (BZ 14591)
135     Koha::Account::Line->new(
136         {
137             borrowernumber    => $patron_4->id,
138             amount            => -3,
139             amountoutstanding => 3,
140             interface         => 'commandline',
141             credit_type_code  => 'PAYMENT'
142         }
143     )->store();
144     $lines = $account_4->outstanding_debits();
145     is( $lines->count, 0, 'No credits are confused with debits because of the amountoutstanding value' );
146
147     $schema->storage->txn_rollback;
148 };
149
150 subtest 'outstanding_credits() tests' => sub {
151
152     plan tests => 17;
153
154     $schema->storage->txn_begin;
155
156     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
157     my $account = $patron->account;
158
159     my @generated_lines;
160     push @generated_lines, $account->add_credit({ amount => 1, interface => 'commandline' });
161     push @generated_lines, $account->add_credit({ amount => 2, interface => 'commandline' });
162     push @generated_lines, $account->add_credit({ amount => 3, interface => 'commandline' });
163     push @generated_lines, $account->add_credit({ amount => 4, interface => 'commandline' });
164
165     my $lines     = $account->outstanding_credits();
166     my @lines_arr = $account->outstanding_credits();
167
168     is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_credits returns a Koha::Account::Lines object' );
169     is( $lines->total_outstanding, -10, 'Outstandig credits total is correctly calculated' );
170
171     my $i = 0;
172     foreach my $line ( @{ $lines->as_list } ) {
173         my $fetched_line = Koha::Account::Lines->find( $generated_lines[$i]->id );
174         is_deeply( $line->unblessed, $fetched_line->unblessed, "Fetched line matches the generated one ($i)" );
175         is_deeply( $lines_arr[$i]->unblessed, $fetched_line->unblessed, "Fetched line matches the generated one ($i)" );
176         is( ref($lines_arr[$i]), 'Koha::Account::Line', 'outstanding_debits returns a list of Koha::Account::Line objects in list context' );
177         $i++;
178     }
179
180     my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
181     $account  = $patron_2->account;
182     $lines       = $account->outstanding_credits();
183     is( $lines->total_outstanding, 0, "Total if no outstanding credits is 0" );
184     is( $lines->count, 0, "With no outstanding credits, we get back a Lines object with 0 lines" );
185
186     # create a pathological debit with amountoutstanding < 0 (BZ 14591)
187     Koha::Account::Line->new(
188         {
189             borrowernumber    => $patron_2->id,
190             amount            => 2,
191             amountoutstanding => -3,
192             interface         => 'commandline',
193             debit_type_code   => 'OVERDUE'
194         }
195     )->store();
196     $lines = $account->outstanding_credits();
197     is( $lines->count, 0, 'No debits are confused with credits because of the amountoutstanding value' );
198
199     $schema->storage->txn_rollback;
200 };
201
202 subtest 'add_credit() tests' => sub {
203
204     plan tests => 17;
205
206     $schema->storage->txn_begin;
207
208     # delete logs and statistics
209     my $action_logs = $schema->resultset('ActionLog')->search()->count;
210     my $statistics = $schema->resultset('Statistic')->search()->count;
211
212     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
213     my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } );
214
215     is( $account->balance, 0, 'Patron has no balance' );
216
217     # Disable logs
218     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
219
220     throws_ok {
221         $account->add_credit(
222             {   amount      => 25,
223                 description => 'Payment of 25',
224                 library_id  => $patron->branchcode,
225                 note        => 'not really important',
226                 type        => 'PAYMENT',
227                 user_id     => $patron->id
228             }
229         );
230     }
231     'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing';
232
233     my $line_1 = $account->add_credit(
234         {   amount      => 25,
235             description => 'Payment of 25',
236             library_id  => $patron->branchcode,
237             note        => 'not really important',
238             type        => 'PAYMENT',
239             user_id     => $patron->id,
240             interface   => 'commandline'
241         }
242     );
243
244     is( $account->balance, -25, 'Patron has a balance of -25' );
245     is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' );
246     is( $schema->resultset('Statistic')->count(), $statistics + 1, 'Action added to statistics' );
247     is( $line_1->credit_type_code, 'PAYMENT', 'Account type is correctly set' );
248
249     # Enable logs
250     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
251
252     my $line_2 = $account->add_credit(
253         {   amount      => 37,
254             description => 'Payment of 37',
255             library_id  => $patron->branchcode,
256             note        => 'not really important',
257             user_id     => $patron->id,
258             interface   => 'commandline'
259         }
260     );
261
262     is( $account->balance, -62, 'Patron has a balance of -25' );
263     is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' );
264     is( $schema->resultset('Statistic')->count(), $statistics + 2, 'Action added to statistics' );
265     is( $line_2->credit_type_code, 'PAYMENT', 'Account type is correctly set' );
266
267     # offsets have the credit_id set to accountlines_id, and debit_id is undef
268     my $offset_1 = Koha::Account::Offsets->search({ credit_id => $line_1->id })->next;
269     my $offset_2 = Koha::Account::Offsets->search({ credit_id => $line_2->id })->next;
270
271     is( $offset_1->credit_id, $line_1->id, 'No debit_id is set for credits' );
272     is( $offset_1->debit_id, undef, 'No debit_id is set for credits' );
273     is( $offset_2->credit_id, $line_2->id, 'No debit_id is set for credits' );
274     is( $offset_2->debit_id, undef, 'No debit_id is set for credits' );
275
276     my $line_3 = $account->add_credit(
277         {
278             amount      => 20,
279             description => 'Manual credit applied',
280             library_id  => $patron->branchcode,
281             user_id     => $patron->id,
282             type        => 'FORGIVEN',
283             interface   => 'commandline'
284         }
285     );
286
287     is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Log was added' );
288     is( $schema->resultset('Statistic')->count(), $statistics + 2, 'No action added to statistics, because of credit type' );
289
290     # Enable cash registers
291     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
292     throws_ok {
293         $account->add_credit(
294             {
295                 amount       => 20,
296                 description  => 'Cash payment without cash register',
297                 library_id   => $patron->branchcode,
298                 user_id      => $patron->id,
299                 payment_type => 'CASH',
300                 interface    => 'intranet'
301             }
302         );
303     }
304     'Koha::Exceptions::Account::RegisterRequired',
305       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
306
307     # Disable cash registers
308     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
309
310     $schema->storage->txn_rollback;
311 };
312
313 subtest 'add_debit() tests' => sub {
314
315     plan tests => 14;
316
317     $schema->storage->txn_begin;
318
319     # delete logs and statistics
320     my $action_logs = $schema->resultset('ActionLog')->search()->count;
321     my $statistics  = $schema->resultset('Statistic')->search()->count;
322
323     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
324     my $account =
325       Koha::Account->new( { patron_id => $patron->borrowernumber } );
326
327     is( $account->balance, 0, 'Patron has no balance' );
328
329     throws_ok {
330     $account->add_debit(
331         {
332             amount      => -5,
333             description => 'amount validation failure',
334             library_id  => $patron->branchcode,
335             note        => 'this should fail anyway',
336             type        => 'RENT',
337             user_id     => $patron->id,
338             interface   => 'commandline'
339         }
340     ); } 'Koha::Exceptions::Account::AmountNotPositive', 'Expected validation exception thrown (amount)';
341
342     throws_ok {
343     $account->add_debit(
344         {
345             amount      => 5,
346             description => 'type validation failure',
347             library_id  => $patron->branchcode,
348             note        => 'this should fail anyway',
349             type        => 'failure',
350             user_id     => $patron->id,
351             interface   => 'commandline'
352         }
353     ); } 'Koha::Exceptions::Account::UnrecognisedType', 'Expected validation exception thrown (type)';
354
355     throws_ok {
356     $account->add_debit(
357         {
358             amount      => 25,
359             description => 'Rental charge of 25',
360             library_id  => $patron->branchcode,
361             note        => 'not really important',
362             type        => 'RENT',
363             user_id     => $patron->id
364         }
365     ); } 'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing';
366
367     # Disable logs
368     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
369
370     my $line_1 = $account->add_debit(
371         {
372             amount      => 25,
373             description => 'Rental charge of 25',
374             library_id  => $patron->branchcode,
375             note        => 'not really important',
376             type        => 'RENT',
377             user_id     => $patron->id,
378             interface   => 'commandline'
379         }
380     );
381
382     is( $account->balance, 25, 'Patron has a balance of 25' );
383     is(
384         $schema->resultset('ActionLog')->count(),
385         $action_logs + 0,
386         'No log was added'
387     );
388     is(
389         $line_1->debit_type_code,
390         'RENT',
391         'Account type is correctly set'
392     );
393
394     # Enable logs
395     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
396
397     my $line_2   = $account->add_debit(
398         {
399             amount      => 37,
400             description => 'Rental charge of 37',
401             library_id  => $patron->branchcode,
402             note        => 'not really important',
403             type        => 'RENT',
404             user_id     => $patron->id,
405             interface   => 'commandline'
406         }
407     );
408
409     is( $account->balance, 62, 'Patron has a balance of 62' );
410     is(
411         $schema->resultset('ActionLog')->count(),
412         $action_logs + 1,
413         'Log was added'
414     );
415     is(
416         $line_2->debit_type_code,
417         'RENT',
418         'Account type is correctly set'
419     );
420
421     # offsets have the debit_id set to accountlines_id, and credit_id is undef
422     my $offset_1 =
423       Koha::Account::Offsets->search( { debit_id => $line_1->id } )->next;
424     my $offset_2 =
425       Koha::Account::Offsets->search( { debit_id => $line_2->id } )->next;
426
427     is( $offset_1->debit_id,  $line_1->id, 'debit_id is set for debit 1' );
428     is( $offset_1->credit_id, undef,       'credit_id is not set for debit 1' );
429     is( $offset_2->debit_id,  $line_2->id, 'debit_id is set for debit 2' );
430     is( $offset_2->credit_id, undef,       'credit_id is not set for debit 2' );
431
432     $schema->storage->txn_rollback;
433 };
434
435 subtest 'lines() tests' => sub {
436
437     plan tests => 1;
438
439     $schema->storage->txn_begin;
440
441     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
442     my $account = $patron->account;
443
444     # Add Credits
445     $account->add_credit({ amount => 1, interface => 'commandline' });
446     $account->add_credit({ amount => 2, interface => 'commandline' });
447     $account->add_credit({ amount => 3, interface => 'commandline' });
448     $account->add_credit({ amount => 4, interface => 'commandline' });
449
450     # Add Debits
451     $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
452     $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
453     $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
454     $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
455
456     # Paid Off
457     $account->add_credit( { amount => 1, interface => 'commandline' } )
458         ->apply( { debits => [ $account->outstanding_debits->as_list ] } );
459
460     my $lines = $account->lines;
461     is( $lines->_resultset->count, 9, "All accountlines (debits, credits and paid off) were fetched");
462
463     $schema->storage->txn_rollback;
464 };
465
466 subtest 'reconcile_balance' => sub {
467
468     plan tests => 4;
469
470     subtest 'more credit than debit' => sub {
471
472         plan tests => 6;
473
474         $schema->storage->txn_begin;
475
476         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
477         my $account = $patron->account;
478
479         # Add Credits
480         $account->add_credit({ amount => 1, interface => 'commandline' });
481         $account->add_credit({ amount => 2, interface => 'commandline' });
482         $account->add_credit({ amount => 3, interface => 'commandline' });
483         $account->add_credit({ amount => 4, interface => 'commandline' });
484         $account->add_credit({ amount => 5, interface => 'commandline' });
485
486         # Add Debits
487         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
488         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
489         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
490         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
491
492         # Paid Off
493         Koha::Account::Line->new(
494             {
495                 borrowernumber    => $patron->id,
496                 amount            => 1,
497                 amountoutstanding => 0,
498                 interface         => 'commandline',
499                 debit_type_code   => 'OVERDUE'
500             }
501         )->store;
502         Koha::Account::Line->new(
503             {
504                 borrowernumber    => $patron->id,
505                 amount            => 1,
506                 amountoutstanding => 0,
507                 interface         => 'commandline',
508                 debit_type_code   => 'OVERDUE'
509             }
510         )->store;
511
512         is( $account->balance(), -5, "Account balance is -5" );
513         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
514         is( $account->outstanding_credits->total_outstanding, -15, 'Outstanding credits sum -15' );
515
516         $account->reconcile_balance();
517
518         is( $account->balance(), -5, "Account balance is -5" );
519         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
520         is( $account->outstanding_credits->total_outstanding, -5, 'Outstanding credits sum -5' );
521
522         $schema->storage->txn_rollback;
523     };
524
525     subtest 'same debit as credit' => sub {
526
527         plan tests => 6;
528
529         $schema->storage->txn_begin;
530
531         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
532         my $account = $patron->account;
533
534         # Add Credits
535         $account->add_credit({ amount => 1, interface => 'commandline' });
536         $account->add_credit({ amount => 2, interface => 'commandline' });
537         $account->add_credit({ amount => 3, interface => 'commandline' });
538         $account->add_credit({ amount => 4, interface => 'commandline' });
539
540         # Add Debits
541         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
542         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
543         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
544         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
545
546         # Paid Off
547         Koha::Account::Line->new(
548             {
549                 borrowernumber    => $patron->id,
550                 amount            => 1,
551                 amountoutstanding => 0,
552                 interface         => 'commandline',
553                 debit_type_code   => 'OVERDUE'
554             }
555         )->store;
556         Koha::Account::Line->new(
557             {
558                 borrowernumber    => $patron->id,
559                 amount            => 1,
560                 amountoutstanding => 0,
561                 interface         => 'commandline',
562                 debit_type_code   => 'OVERDUE'
563             }
564         )->store;
565
566         is( $account->balance(), 0, "Account balance is 0" );
567         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
568         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
569
570         $account->reconcile_balance();
571
572         is( $account->balance(), 0, "Account balance is 0" );
573         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
574         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
575
576         $schema->storage->txn_rollback;
577     };
578
579     subtest 'more debit than credit' => sub {
580
581         plan tests => 6;
582
583         $schema->storage->txn_begin;
584
585         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
586         my $account = $patron->account;
587
588         # Add Credits
589         $account->add_credit({ amount => 1, interface => 'commandline' });
590         $account->add_credit({ amount => 2, interface => 'commandline' });
591         $account->add_credit({ amount => 3, interface => 'commandline' });
592         $account->add_credit({ amount => 4, interface => 'commandline' });
593
594         # Add Debits
595         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
596         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
597         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
598         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
599         $account->add_debit({ amount => 5, interface => 'commandline', type => 'OVERDUE' });
600
601         # Paid Off
602         Koha::Account::Line->new(
603             {
604                 borrowernumber    => $patron->id,
605                 amount            => 1,
606                 amountoutstanding => 0,
607                 interface         => 'commandline',
608                 debit_type_code   => 'OVERDUE'
609             }
610         )->store;
611         Koha::Account::Line->new(
612             {
613                 borrowernumber    => $patron->id,
614                 amount            => 1,
615                 amountoutstanding => 0,
616                 interface         => 'commandline',
617                 debit_type_code   => 'OVERDUE'
618             }
619         )->store;
620
621         is( $account->balance(), 5, "Account balance is 5" );
622         is( $account->outstanding_debits->total_outstanding, 15, 'Outstanding debits sum 15' );
623         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
624
625         $account->reconcile_balance();
626
627         is( $account->balance(), 5, "Account balance is 5" );
628         is( $account->outstanding_debits->total_outstanding, 5, 'Outstanding debits sum 5' );
629         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
630
631         $schema->storage->txn_rollback;
632     };
633
634     subtest 'credits are applied to older debits first' => sub {
635
636         plan tests => 9;
637
638         $schema->storage->txn_begin;
639
640         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
641         my $account = $patron->account;
642
643         # Add Credits
644         $account->add_credit({ amount => 1, interface => 'commandline' });
645         $account->add_credit({ amount => 3, interface => 'commandline' });
646
647         # Add Debits
648         my $debit_1 = $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
649         my $debit_2 = $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
650         my $debit_3 = $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
651
652         is( $account->balance(), 2, "Account balance is 2" );
653         is( $account->outstanding_debits->total_outstanding, 6, 'Outstanding debits sum 6' );
654         is( $account->outstanding_credits->total_outstanding, -4, 'Outstanding credits sum -4' );
655
656         $account->reconcile_balance();
657
658         is( $account->balance(), 2, "Account balance is 2" );
659         is( $account->outstanding_debits->total_outstanding, 2, 'Outstanding debits sum 2' );
660         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
661
662         $debit_1->discard_changes;
663         is( $debit_1->amountoutstanding + 0, 0, 'Old debit payed' );
664         $debit_2->discard_changes;
665         is( $debit_2->amountoutstanding + 0, 0, 'Old debit payed' );
666         $debit_3->discard_changes;
667         is( $debit_3->amountoutstanding + 0, 2, 'Newest debit only partially payed' );
668
669         $schema->storage->txn_rollback;
670     };
671 };
672
673 subtest 'pay() tests' => sub {
674
675     plan tests => 3;
676
677     $schema->storage->txn_begin;
678
679     # Disable renewing upon fine payment
680     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
681
682     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
683     my $library = $builder->build_object({ class => 'Koha::Libraries' });
684     my $account = $patron->account;
685
686     my $context = Test::MockModule->new('C4::Context');
687     $context->mock( 'userenv', { branch => $library->id } );
688
689     my $credit_1_id = $account->pay({ amount => 200 })->{payment_id};
690     my $credit_1    = Koha::Account::Lines->find( $credit_1_id );
691
692     is( $credit_1->branchcode, undef, 'No branchcode is set if library_id was not passed' );
693
694     my $credit_2_id = $account->pay({ amount => 150, library_id => $library->id })->{payment_id};
695     my $credit_2    = Koha::Account::Lines->find( $credit_2_id );
696
697     is( $credit_2->branchcode, $library->id, 'branchcode set because library_id was passed' );
698
699     # Enable cash registers
700     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
701     throws_ok {
702         $account->pay(
703             {
704                 amount       => 20,
705                 payment_type => 'CASH',
706                 interface    => 'intranet'
707             }
708         );
709     }
710     'Koha::Exceptions::Account::RegisterRequired',
711       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
712
713     # Disable cash registers
714     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
715
716     $schema->storage->txn_rollback;
717 };
718
719 subtest 'pay() handles lost items when paying a specific lost fee' => sub {
720
721     plan tests => 5;
722
723     $schema->storage->txn_begin;
724
725     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
726     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
727     my $account = $patron->account;
728
729     my $context = Test::MockModule->new('C4::Context');
730     $context->mock( 'userenv', { branch => $library->id } );
731
732     my $biblio = $builder->build_sample_biblio();
733     my $item =
734       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
735
736     my $checkout = Koha::Checkout->new(
737         {
738             borrowernumber => $patron->id,
739             itemnumber     => $item->id,
740             date_due       => \'NOW()',
741             branchcode     => $patron->branchcode,
742             issuedate      => \'NOW()',
743         }
744     )->store();
745
746     $item->itemlost('1')->store();
747
748     my $accountline = Koha::Account::Line->new(
749         {
750             issue_id       => $checkout->id,
751             borrowernumber => $patron->id,
752             itemnumber     => $item->id,
753             date           => \'NOW()',
754             debit_type_code    => 'LOST',
755             interface      => 'cli',
756             amount => '1',
757             amountoutstanding => '1',
758         }
759     )->store();
760
761     $account->pay(
762         {
763             amount     => .5,
764             library_id => $library->id,
765             lines      => [$accountline],
766         }
767     );
768
769     $accountline = Koha::Account::Lines->find( $accountline->id );
770     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
771
772     $checkout = Koha::Checkouts->find( $checkout->id );
773     ok( $checkout, 'Item still checked out to patron' );
774
775     $account->pay(
776         {
777             amount     => 0.5,
778             library_id => $library->id,
779             lines      => [$accountline],
780         }
781     );
782
783     $accountline = Koha::Account::Lines->find( $accountline->id );
784     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
785
786     $checkout = Koha::Checkouts->find( $checkout->id );
787     ok( !$checkout, 'Item was removed from patron account' );
788
789     subtest 'item was not checked out to the same patron' => sub {
790         plan tests => 1;
791
792         my $patron_2 = $builder->build_object(
793             {
794                 class => 'Koha::Patrons',
795                 value => { branchcode => $library->branchcode }
796             }
797         );
798         $item->itemlost('1')->store();
799         C4::Accounts::chargelostitem( $patron->borrowernumber, $item->itemnumber, 5, "lost" );
800         my $accountline = Koha::Account::Lines->search(
801             {
802                 borrowernumber  => $patron->borrowernumber,
803                 itemnumber      => $item->itemnumber,
804                 debit_type_code => 'LOST'
805             }
806         )->next;
807         my $checkout = Koha::Checkout->new(
808             {
809                 borrowernumber => $patron_2->borrowernumber,
810                 itemnumber     => $item->itemnumber,
811                 date_due       => \'NOW()',
812                 branchcode     => $patron_2->branchcode,
813                 issuedate      => \'NOW()',
814             }
815         )->store();
816
817         $patron->account->pay(
818             {
819                 amount     => 5,
820                 library_id => $library->branchcode,
821                 lines      => [$accountline],
822             }
823         );
824
825         ok(
826             Koha::Checkouts->find( $checkout->issue_id ),
827             'If the item is checked out to another patron, a lost item should not be returned if lost fee is paid'
828         );
829
830     };
831
832     $schema->storage->txn_rollback;
833 };
834
835 subtest 'pay() handles lost items when paying by amount ( not specifying the lost fee )' => sub {
836
837     plan tests => 4;
838
839     $schema->storage->txn_begin;
840
841     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
842     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
843     my $account = $patron->account;
844
845     my $context = Test::MockModule->new('C4::Context');
846     $context->mock( 'userenv', { branch => $library->id } );
847
848     my $biblio = $builder->build_sample_biblio();
849     my $item =
850       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
851
852     my $checkout = Koha::Checkout->new(
853         {
854             borrowernumber => $patron->id,
855             itemnumber     => $item->id,
856             date_due       => \'NOW()',
857             branchcode     => $patron->branchcode,
858             issuedate      => \'NOW()',
859         }
860     )->store();
861
862     $item->itemlost('1')->store();
863
864     my $accountline = Koha::Account::Line->new(
865         {
866             issue_id       => $checkout->id,
867             borrowernumber => $patron->id,
868             itemnumber     => $item->id,
869             date           => \'NOW()',
870             debit_type_code    => 'LOST',
871             interface      => 'cli',
872             amount => '1',
873             amountoutstanding => '1',
874         }
875     )->store();
876
877     $account->pay(
878         {
879             amount     => .5,
880             library_id => $library->id,
881         }
882     );
883
884     $accountline = Koha::Account::Lines->find( $accountline->id );
885     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
886
887     $checkout = Koha::Checkouts->find( $checkout->id );
888     ok( $checkout, 'Item still checked out to patron' );
889
890     $account->pay(
891         {
892             amount     => .5,,
893             library_id => $library->id,
894         }
895     );
896
897     $accountline = Koha::Account::Lines->find( $accountline->id );
898     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
899
900     $checkout = Koha::Checkouts->find( $checkout->id );
901     ok( !$checkout, 'Item was removed from patron account' );
902
903     $schema->storage->txn_rollback;
904 };
905
906 subtest 'pay() renews items when appropriate' => sub {
907
908     plan tests => 1;
909
910     $schema->storage->txn_begin;
911
912     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
913     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
914     my $account = $patron->account;
915
916     my $context = Test::MockModule->new('C4::Context');
917     $context->mock( 'userenv', { branch => $library->id } );
918
919     my $biblio = $builder->build_sample_biblio();
920     my $item =
921       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
922
923     my $now = dt_from_string();
924     my $seven_weeks = DateTime::Duration->new(weeks => 7);
925     my $five_weeks = DateTime::Duration->new(weeks => 5);
926     my $seven_weeks_ago = $now - $seven_weeks;
927     my $five_weeks_ago = $now - $five_weeks;
928
929     my $checkout = Koha::Checkout->new(
930         {
931             borrowernumber => $patron->id,
932             itemnumber     => $item->id,
933             date_due       => $five_weeks_ago,
934             branchcode     => $patron->branchcode,
935             issuedate      => $seven_weeks_ago
936         }
937     )->store();
938
939     my $accountline = Koha::Account::Line->new(
940         {
941             issue_id       => $checkout->id,
942             borrowernumber => $patron->id,
943             itemnumber     => $item->id,
944             date           => \'NOW()',
945             debit_type_code => 'OVERDUE',
946             status         => 'UNRETURNED',
947             interface      => 'cli',
948             amount => '1',
949             amountoutstanding => '1',
950         }
951     )->store();
952
953     # Enable renewing upon fine payment
954     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
955     my $called = 0;
956     my $module = new Test::MockModule('C4::Circulation');
957     $module->mock('AddRenewal', sub { $called = 1; });
958     $module->mock('CanBookBeRenewed', sub { return 1; });
959     $account->pay(
960         {
961             amount     => '1',
962             library_id => $library->id,
963         }
964     );
965
966     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
967
968     $schema->storage->txn_rollback;
969 };
970
971 subtest 'Koha::Account::Line::apply() handles lost items' => sub {
972
973     plan tests => 4;
974
975     $schema->storage->txn_begin;
976
977     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
978     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
979     my $account = $patron->account;
980
981     my $context = Test::MockModule->new('C4::Context');
982     $context->mock( 'userenv', { branch => $library->id } );
983
984     my $biblio = $builder->build_sample_biblio();
985     my $item =
986       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
987
988     my $checkout = Koha::Checkout->new(
989         {
990             borrowernumber => $patron->id,
991             itemnumber     => $item->id,
992             date_due       => \'NOW()',
993             branchcode     => $patron->branchcode,
994             issuedate      => \'NOW()',
995         }
996     )->store();
997
998     $item->itemlost('1')->store();
999
1000     my $debit = Koha::Account::Line->new(
1001         {
1002             issue_id          => $checkout->id,
1003             borrowernumber    => $patron->id,
1004             itemnumber        => $item->id,
1005             date              => \'NOW()',
1006             debit_type_code       => 'LOST',
1007             interface         => 'cli',
1008             amount            => '1',
1009             amountoutstanding => '1',
1010         }
1011     )->store();
1012
1013     my $credit = Koha::Account::Line->new(
1014         {
1015             borrowernumber    => $patron->id,
1016             date              => '1970-01-01 00:00:01',
1017             amount            => -.5,
1018             amountoutstanding => -.5,
1019             interface         => 'commandline',
1020             credit_type_code  => 'PAYMENT'
1021         }
1022     )->store();
1023     my $debits = $account->outstanding_debits;
1024     $credit->apply({ debits => [ $debits->as_list ] });
1025
1026     $debit = Koha::Account::Lines->find( $debit->id );
1027     is( $debit->amountoutstanding+0, .5, 'Account line was paid down by half' );
1028
1029     $checkout = Koha::Checkouts->find( $checkout->id );
1030     ok( $checkout, 'Item still checked out to patron' );
1031
1032     $credit = Koha::Account::Line->new(
1033         {
1034             borrowernumber    => $patron->id,
1035             date              => '1970-01-01 00:00:01',
1036             amount            => -.5,
1037             amountoutstanding => -.5,
1038             interface         => 'commandline',
1039             credit_type_code  => 'PAYMENT'
1040         }
1041     )->store();
1042     $debits = $account->outstanding_debits;
1043     $credit->apply({ debits => [ $debits->as_list ] });
1044
1045     $debit = Koha::Account::Lines->find( $debit->id );
1046     is( $debit->amountoutstanding+0, 0, 'Account line was paid down by half' );
1047
1048     $checkout = Koha::Checkouts->find( $checkout->id );
1049     ok( !$checkout, 'Item was removed from patron account' );
1050
1051     $schema->storage->txn_rollback;
1052 };
1053
1054 subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->store)' => sub {
1055     plan tests => 38;
1056
1057     $schema->storage->txn_begin;
1058
1059     Koha::Account::Lines->delete();
1060
1061     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1062     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1063     my $account = $patron->account;
1064
1065     #t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1066     my $context = Test::MockModule->new('C4::Context');
1067     $context->mock( 'userenv', { branch => $library->id } );
1068
1069     my $now = dt_from_string;
1070     my $year = $now->year;
1071     my $month = $now->month;
1072     my ($accountlines_id, $accountline);
1073
1074     my $credit_type = Koha::Account::CreditTypes->find('PAYMENT');
1075     $credit_type->credit_number_enabled(1);
1076     $credit_type->store();
1077
1078     t::lib::Mocks::mock_preference('AutoCreditNumber', '');
1079     $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1080     $accountline = Koha::Account::Lines->find($accountlines_id);
1081     is($accountline->credit_number, undef, 'No credit number is generated when syspref is off');
1082
1083     t::lib::Mocks::mock_preference('AutoCreditNumber', 'incremental');
1084     for my $i (1..11) {
1085         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1086         $accountline = Koha::Account::Lines->find($accountlines_id);
1087         is($accountline->credit_number, $i, "Incremental format credit number added for payments: $i");
1088     }
1089     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1090     $accountline = Koha::Account::Lines->find($accountlines_id);
1091     is($accountline->credit_number, undef, "Incremental credit number not added for writeoff");
1092
1093     t::lib::Mocks::mock_preference('AutoCreditNumber', 'annual');
1094     for my $i (1..11) {
1095         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1096         $accountline = Koha::Account::Lines->find($accountlines_id);
1097         is($accountline->credit_number, sprintf('%s-%04d', $year, $i), "Annual format credit number added for payments: " . sprintf('%s-%04d', $year, $i));
1098     }
1099     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1100     $accountline = Koha::Account::Lines->find($accountlines_id);
1101     is($accountline->credit_number, undef, "Annual format credit number not aded for writeoff");
1102
1103     t::lib::Mocks::mock_preference('AutoCreditNumber', 'branchyyyymmincr');
1104     for my $i (1..11) {
1105         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1106         $accountline = Koha::Account::Lines->find($accountlines_id);
1107         is($accountline->credit_number, sprintf('%s%d%02d%04d', $library->id, $year, $month, $i), "branchyyyymmincr format credit number added for payment: " . sprintf('%s%d%02d%04d', $library->id, $year, $month, $i));
1108     }
1109     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1110     $accountline = Koha::Account::Lines->find($accountlines_id);
1111     is($accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff");
1112
1113     throws_ok {
1114         Koha::Account::Line->new(
1115             {
1116                 interface        => 'test',
1117                 amount           => -1,
1118                 credit_type_code => $credit_type->code,
1119                 credit_number    => 42
1120             }
1121         )->store;
1122     }
1123     'Koha::Exceptions::Account',
1124 "Exception thrown when AutoCreditNumber is enabled but credit_number is already defined";
1125
1126     $schema->storage->txn_rollback;
1127 };