Bug 22417: Add exec flag on .t file
[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         local *STDERR;
344         open STDERR, '>', '/dev/null';
345         $account->add_debit(
346             {
347                 amount      => 5,
348                 description => 'type validation failure',
349                 library_id  => $patron->branchcode,
350                 note        => 'this should fail anyway',
351                 type        => 'failure',
352                 user_id     => $patron->id,
353                 interface   => 'commandline'
354             }
355         );
356         close STDERR;
357     }
358     'Koha::Exceptions::Account::UnrecognisedType',
359       'Expected validation exception thrown (type)';
360
361     throws_ok {
362     $account->add_debit(
363         {
364             amount      => 25,
365             description => 'Rental charge of 25',
366             library_id  => $patron->branchcode,
367             note        => 'not really important',
368             type        => 'RENT',
369             user_id     => $patron->id
370         }
371     ); } 'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing';
372
373     # Disable logs
374     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
375
376     my $line_1 = $account->add_debit(
377         {
378             amount      => 25,
379             description => 'Rental charge of 25',
380             library_id  => $patron->branchcode,
381             note        => 'not really important',
382             type        => 'RENT',
383             user_id     => $patron->id,
384             interface   => 'commandline'
385         }
386     );
387
388     is( $account->balance, 25, 'Patron has a balance of 25' );
389     is(
390         $schema->resultset('ActionLog')->count(),
391         $action_logs + 0,
392         'No log was added'
393     );
394     is(
395         $line_1->debit_type_code,
396         'RENT',
397         'Account type is correctly set'
398     );
399
400     # Enable logs
401     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
402
403     my $line_2   = $account->add_debit(
404         {
405             amount      => 37,
406             description => 'Rental charge of 37',
407             library_id  => $patron->branchcode,
408             note        => 'not really important',
409             type        => 'RENT',
410             user_id     => $patron->id,
411             interface   => 'commandline'
412         }
413     );
414
415     is( $account->balance, 62, 'Patron has a balance of 62' );
416     is(
417         $schema->resultset('ActionLog')->count(),
418         $action_logs + 1,
419         'Log was added'
420     );
421     is(
422         $line_2->debit_type_code,
423         'RENT',
424         'Account type is correctly set'
425     );
426
427     # offsets have the debit_id set to accountlines_id, and credit_id is undef
428     my $offset_1 =
429       Koha::Account::Offsets->search( { debit_id => $line_1->id } )->next;
430     my $offset_2 =
431       Koha::Account::Offsets->search( { debit_id => $line_2->id } )->next;
432
433     is( $offset_1->debit_id,  $line_1->id, 'debit_id is set for debit 1' );
434     is( $offset_1->credit_id, undef,       'credit_id is not set for debit 1' );
435     is( $offset_2->debit_id,  $line_2->id, 'debit_id is set for debit 2' );
436     is( $offset_2->credit_id, undef,       'credit_id is not set for debit 2' );
437
438     $schema->storage->txn_rollback;
439 };
440
441 subtest 'lines() tests' => sub {
442
443     plan tests => 1;
444
445     $schema->storage->txn_begin;
446
447     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
448     my $account = $patron->account;
449
450     # Add Credits
451     $account->add_credit({ amount => 1, interface => 'commandline' });
452     $account->add_credit({ amount => 2, interface => 'commandline' });
453     $account->add_credit({ amount => 3, interface => 'commandline' });
454     $account->add_credit({ amount => 4, interface => 'commandline' });
455
456     # Add Debits
457     $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
458     $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
459     $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
460     $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
461
462     # Paid Off
463     $account->add_credit( { amount => 1, interface => 'commandline' } )
464         ->apply( { debits => [ $account->outstanding_debits->as_list ] } );
465
466     my $lines = $account->lines;
467     is( $lines->_resultset->count, 9, "All accountlines (debits, credits and paid off) were fetched");
468
469     $schema->storage->txn_rollback;
470 };
471
472 subtest 'reconcile_balance' => sub {
473
474     plan tests => 4;
475
476     subtest 'more credit than debit' => sub {
477
478         plan tests => 6;
479
480         $schema->storage->txn_begin;
481
482         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
483         my $account = $patron->account;
484
485         # Add Credits
486         $account->add_credit({ amount => 1, interface => 'commandline' });
487         $account->add_credit({ amount => 2, interface => 'commandline' });
488         $account->add_credit({ amount => 3, interface => 'commandline' });
489         $account->add_credit({ amount => 4, interface => 'commandline' });
490         $account->add_credit({ amount => 5, interface => 'commandline' });
491
492         # Add Debits
493         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
494         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
495         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
496         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
497
498         # Paid Off
499         Koha::Account::Line->new(
500             {
501                 borrowernumber    => $patron->id,
502                 amount            => 1,
503                 amountoutstanding => 0,
504                 interface         => 'commandline',
505                 debit_type_code   => 'OVERDUE'
506             }
507         )->store;
508         Koha::Account::Line->new(
509             {
510                 borrowernumber    => $patron->id,
511                 amount            => 1,
512                 amountoutstanding => 0,
513                 interface         => 'commandline',
514                 debit_type_code   => 'OVERDUE'
515             }
516         )->store;
517
518         is( $account->balance(), -5, "Account balance is -5" );
519         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
520         is( $account->outstanding_credits->total_outstanding, -15, 'Outstanding credits sum -15' );
521
522         $account->reconcile_balance();
523
524         is( $account->balance(), -5, "Account balance is -5" );
525         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
526         is( $account->outstanding_credits->total_outstanding, -5, 'Outstanding credits sum -5' );
527
528         $schema->storage->txn_rollback;
529     };
530
531     subtest 'same debit as credit' => sub {
532
533         plan tests => 6;
534
535         $schema->storage->txn_begin;
536
537         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
538         my $account = $patron->account;
539
540         # Add Credits
541         $account->add_credit({ amount => 1, interface => 'commandline' });
542         $account->add_credit({ amount => 2, interface => 'commandline' });
543         $account->add_credit({ amount => 3, interface => 'commandline' });
544         $account->add_credit({ amount => 4, interface => 'commandline' });
545
546         # Add Debits
547         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
548         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
549         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
550         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
551
552         # Paid Off
553         Koha::Account::Line->new(
554             {
555                 borrowernumber    => $patron->id,
556                 amount            => 1,
557                 amountoutstanding => 0,
558                 interface         => 'commandline',
559                 debit_type_code   => 'OVERDUE'
560             }
561         )->store;
562         Koha::Account::Line->new(
563             {
564                 borrowernumber    => $patron->id,
565                 amount            => 1,
566                 amountoutstanding => 0,
567                 interface         => 'commandline',
568                 debit_type_code   => 'OVERDUE'
569             }
570         )->store;
571
572         is( $account->balance(), 0, "Account balance is 0" );
573         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
574         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
575
576         $account->reconcile_balance();
577
578         is( $account->balance(), 0, "Account balance is 0" );
579         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
580         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
581
582         $schema->storage->txn_rollback;
583     };
584
585     subtest 'more debit than credit' => sub {
586
587         plan tests => 6;
588
589         $schema->storage->txn_begin;
590
591         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
592         my $account = $patron->account;
593
594         # Add Credits
595         $account->add_credit({ amount => 1, interface => 'commandline' });
596         $account->add_credit({ amount => 2, interface => 'commandline' });
597         $account->add_credit({ amount => 3, interface => 'commandline' });
598         $account->add_credit({ amount => 4, interface => 'commandline' });
599
600         # Add Debits
601         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
602         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
603         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
604         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
605         $account->add_debit({ amount => 5, interface => 'commandline', type => 'OVERDUE' });
606
607         # Paid Off
608         Koha::Account::Line->new(
609             {
610                 borrowernumber    => $patron->id,
611                 amount            => 1,
612                 amountoutstanding => 0,
613                 interface         => 'commandline',
614                 debit_type_code   => 'OVERDUE'
615             }
616         )->store;
617         Koha::Account::Line->new(
618             {
619                 borrowernumber    => $patron->id,
620                 amount            => 1,
621                 amountoutstanding => 0,
622                 interface         => 'commandline',
623                 debit_type_code   => 'OVERDUE'
624             }
625         )->store;
626
627         is( $account->balance(), 5, "Account balance is 5" );
628         is( $account->outstanding_debits->total_outstanding, 15, 'Outstanding debits sum 15' );
629         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
630
631         $account->reconcile_balance();
632
633         is( $account->balance(), 5, "Account balance is 5" );
634         is( $account->outstanding_debits->total_outstanding, 5, 'Outstanding debits sum 5' );
635         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
636
637         $schema->storage->txn_rollback;
638     };
639
640     subtest 'credits are applied to older debits first' => sub {
641
642         plan tests => 9;
643
644         $schema->storage->txn_begin;
645
646         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
647         my $account = $patron->account;
648
649         # Add Credits
650         $account->add_credit({ amount => 1, interface => 'commandline' });
651         $account->add_credit({ amount => 3, interface => 'commandline' });
652
653         # Add Debits
654         my $debit_1 = $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
655         my $debit_2 = $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
656         my $debit_3 = $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
657
658         is( $account->balance(), 2, "Account balance is 2" );
659         is( $account->outstanding_debits->total_outstanding, 6, 'Outstanding debits sum 6' );
660         is( $account->outstanding_credits->total_outstanding, -4, 'Outstanding credits sum -4' );
661
662         $account->reconcile_balance();
663
664         is( $account->balance(), 2, "Account balance is 2" );
665         is( $account->outstanding_debits->total_outstanding, 2, 'Outstanding debits sum 2' );
666         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
667
668         $debit_1->discard_changes;
669         is( $debit_1->amountoutstanding + 0, 0, 'Old debit payed' );
670         $debit_2->discard_changes;
671         is( $debit_2->amountoutstanding + 0, 0, 'Old debit payed' );
672         $debit_3->discard_changes;
673         is( $debit_3->amountoutstanding + 0, 2, 'Newest debit only partially payed' );
674
675         $schema->storage->txn_rollback;
676     };
677 };
678
679 subtest 'pay() tests' => sub {
680
681     plan tests => 3;
682
683     $schema->storage->txn_begin;
684
685     # Disable renewing upon fine payment
686     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
687
688     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
689     my $library = $builder->build_object({ class => 'Koha::Libraries' });
690     my $account = $patron->account;
691
692     my $context = Test::MockModule->new('C4::Context');
693     $context->mock( 'userenv', { branch => $library->id } );
694
695     my $credit_1_id = $account->pay({ amount => 200 })->{payment_id};
696     my $credit_1    = Koha::Account::Lines->find( $credit_1_id );
697
698     is( $credit_1->branchcode, undef, 'No branchcode is set if library_id was not passed' );
699
700     my $credit_2_id = $account->pay({ amount => 150, library_id => $library->id })->{payment_id};
701     my $credit_2    = Koha::Account::Lines->find( $credit_2_id );
702
703     is( $credit_2->branchcode, $library->id, 'branchcode set because library_id was passed' );
704
705     # Enable cash registers
706     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
707     throws_ok {
708         $account->pay(
709             {
710                 amount       => 20,
711                 payment_type => 'CASH',
712                 interface    => 'intranet'
713             }
714         );
715     }
716     'Koha::Exceptions::Account::RegisterRequired',
717       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
718
719     # Disable cash registers
720     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
721
722     $schema->storage->txn_rollback;
723 };
724
725 subtest 'pay() handles lost items when paying a specific lost fee' => sub {
726
727     plan tests => 5;
728
729     $schema->storage->txn_begin;
730
731     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
732     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
733     my $account = $patron->account;
734
735     my $context = Test::MockModule->new('C4::Context');
736     $context->mock( 'userenv', { branch => $library->id } );
737
738     my $biblio = $builder->build_sample_biblio();
739     my $item =
740       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
741
742     my $checkout = Koha::Checkout->new(
743         {
744             borrowernumber => $patron->id,
745             itemnumber     => $item->id,
746             date_due       => \'NOW()',
747             branchcode     => $patron->branchcode,
748             issuedate      => \'NOW()',
749         }
750     )->store();
751
752     $item->itemlost('1')->store();
753
754     my $accountline = Koha::Account::Line->new(
755         {
756             issue_id       => $checkout->id,
757             borrowernumber => $patron->id,
758             itemnumber     => $item->id,
759             date           => \'NOW()',
760             debit_type_code    => 'LOST',
761             interface      => 'cli',
762             amount => '1',
763             amountoutstanding => '1',
764         }
765     )->store();
766
767     $account->pay(
768         {
769             amount     => .5,
770             library_id => $library->id,
771             lines      => [$accountline],
772         }
773     );
774
775     $accountline = Koha::Account::Lines->find( $accountline->id );
776     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
777
778     $checkout = Koha::Checkouts->find( $checkout->id );
779     ok( $checkout, 'Item still checked out to patron' );
780
781     $account->pay(
782         {
783             amount     => 0.5,
784             library_id => $library->id,
785             lines      => [$accountline],
786         }
787     );
788
789     $accountline = Koha::Account::Lines->find( $accountline->id );
790     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
791
792     $checkout = Koha::Checkouts->find( $checkout->id );
793     ok( !$checkout, 'Item was removed from patron account' );
794
795     subtest 'item was not checked out to the same patron' => sub {
796         plan tests => 1;
797
798         my $patron_2 = $builder->build_object(
799             {
800                 class => 'Koha::Patrons',
801                 value => { branchcode => $library->branchcode }
802             }
803         );
804         $item->itemlost('1')->store();
805         C4::Accounts::chargelostitem( $patron->borrowernumber, $item->itemnumber, 5, "lost" );
806         my $accountline = Koha::Account::Lines->search(
807             {
808                 borrowernumber  => $patron->borrowernumber,
809                 itemnumber      => $item->itemnumber,
810                 debit_type_code => 'LOST'
811             }
812         )->next;
813         my $checkout = Koha::Checkout->new(
814             {
815                 borrowernumber => $patron_2->borrowernumber,
816                 itemnumber     => $item->itemnumber,
817                 date_due       => \'NOW()',
818                 branchcode     => $patron_2->branchcode,
819                 issuedate      => \'NOW()',
820             }
821         )->store();
822
823         $patron->account->pay(
824             {
825                 amount     => 5,
826                 library_id => $library->branchcode,
827                 lines      => [$accountline],
828             }
829         );
830
831         ok(
832             Koha::Checkouts->find( $checkout->issue_id ),
833             'If the item is checked out to another patron, a lost item should not be returned if lost fee is paid'
834         );
835
836     };
837
838     $schema->storage->txn_rollback;
839 };
840
841 subtest 'pay() handles lost items when paying by amount ( not specifying the lost fee )' => sub {
842
843     plan tests => 4;
844
845     $schema->storage->txn_begin;
846
847     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
848     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
849     my $account = $patron->account;
850
851     my $context = Test::MockModule->new('C4::Context');
852     $context->mock( 'userenv', { branch => $library->id } );
853
854     my $biblio = $builder->build_sample_biblio();
855     my $item =
856       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
857
858     my $checkout = Koha::Checkout->new(
859         {
860             borrowernumber => $patron->id,
861             itemnumber     => $item->id,
862             date_due       => \'NOW()',
863             branchcode     => $patron->branchcode,
864             issuedate      => \'NOW()',
865         }
866     )->store();
867
868     $item->itemlost('1')->store();
869
870     my $accountline = Koha::Account::Line->new(
871         {
872             issue_id       => $checkout->id,
873             borrowernumber => $patron->id,
874             itemnumber     => $item->id,
875             date           => \'NOW()',
876             debit_type_code    => 'LOST',
877             interface      => 'cli',
878             amount => '1',
879             amountoutstanding => '1',
880         }
881     )->store();
882
883     $account->pay(
884         {
885             amount     => .5,
886             library_id => $library->id,
887         }
888     );
889
890     $accountline = Koha::Account::Lines->find( $accountline->id );
891     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
892
893     $checkout = Koha::Checkouts->find( $checkout->id );
894     ok( $checkout, 'Item still checked out to patron' );
895
896     $account->pay(
897         {
898             amount     => .5,,
899             library_id => $library->id,
900         }
901     );
902
903     $accountline = Koha::Account::Lines->find( $accountline->id );
904     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
905
906     $checkout = Koha::Checkouts->find( $checkout->id );
907     ok( !$checkout, 'Item was removed from patron account' );
908
909     $schema->storage->txn_rollback;
910 };
911
912 subtest 'pay() renews items when appropriate' => sub {
913
914     plan tests => 1;
915
916     $schema->storage->txn_begin;
917
918     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
919     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
920     my $account = $patron->account;
921
922     my $context = Test::MockModule->new('C4::Context');
923     $context->mock( 'userenv', { branch => $library->id } );
924
925     my $biblio = $builder->build_sample_biblio();
926     my $item =
927       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
928
929     my $now = dt_from_string();
930     my $seven_weeks = DateTime::Duration->new(weeks => 7);
931     my $five_weeks = DateTime::Duration->new(weeks => 5);
932     my $seven_weeks_ago = $now - $seven_weeks;
933     my $five_weeks_ago = $now - $five_weeks;
934
935     my $checkout = Koha::Checkout->new(
936         {
937             borrowernumber => $patron->id,
938             itemnumber     => $item->id,
939             date_due       => $five_weeks_ago,
940             branchcode     => $patron->branchcode,
941             issuedate      => $seven_weeks_ago
942         }
943     )->store();
944
945     my $accountline = Koha::Account::Line->new(
946         {
947             issue_id       => $checkout->id,
948             borrowernumber => $patron->id,
949             itemnumber     => $item->id,
950             date           => \'NOW()',
951             debit_type_code => 'OVERDUE',
952             status         => 'UNRETURNED',
953             interface      => 'cli',
954             amount => '1',
955             amountoutstanding => '1',
956         }
957     )->store();
958
959     # Enable renewing upon fine payment
960     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
961     my $called = 0;
962     my $module = new Test::MockModule('C4::Circulation');
963     $module->mock('AddRenewal', sub { $called = 1; });
964     $module->mock('CanBookBeRenewed', sub { return 1; });
965     $account->pay(
966         {
967             amount     => '1',
968             library_id => $library->id,
969         }
970     );
971
972     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
973
974     $schema->storage->txn_rollback;
975 };
976
977 subtest 'Koha::Account::Line::apply() handles lost items' => sub {
978
979     plan tests => 4;
980
981     $schema->storage->txn_begin;
982
983     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
984     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
985     my $account = $patron->account;
986
987     my $context = Test::MockModule->new('C4::Context');
988     $context->mock( 'userenv', { branch => $library->id } );
989
990     my $biblio = $builder->build_sample_biblio();
991     my $item =
992       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
993
994     my $checkout = Koha::Checkout->new(
995         {
996             borrowernumber => $patron->id,
997             itemnumber     => $item->id,
998             date_due       => \'NOW()',
999             branchcode     => $patron->branchcode,
1000             issuedate      => \'NOW()',
1001         }
1002     )->store();
1003
1004     $item->itemlost('1')->store();
1005
1006     my $debit = Koha::Account::Line->new(
1007         {
1008             issue_id          => $checkout->id,
1009             borrowernumber    => $patron->id,
1010             itemnumber        => $item->id,
1011             date              => \'NOW()',
1012             debit_type_code       => 'LOST',
1013             interface         => 'cli',
1014             amount            => '1',
1015             amountoutstanding => '1',
1016         }
1017     )->store();
1018
1019     my $credit = Koha::Account::Line->new(
1020         {
1021             borrowernumber    => $patron->id,
1022             date              => '1970-01-01 00:00:01',
1023             amount            => -.5,
1024             amountoutstanding => -.5,
1025             interface         => 'commandline',
1026             credit_type_code  => 'PAYMENT'
1027         }
1028     )->store();
1029     my $debits = $account->outstanding_debits;
1030     $credit->apply({ debits => [ $debits->as_list ] });
1031
1032     $debit = Koha::Account::Lines->find( $debit->id );
1033     is( $debit->amountoutstanding+0, .5, 'Account line was paid down by half' );
1034
1035     $checkout = Koha::Checkouts->find( $checkout->id );
1036     ok( $checkout, 'Item still checked out to patron' );
1037
1038     $credit = Koha::Account::Line->new(
1039         {
1040             borrowernumber    => $patron->id,
1041             date              => '1970-01-01 00:00:01',
1042             amount            => -.5,
1043             amountoutstanding => -.5,
1044             interface         => 'commandline',
1045             credit_type_code  => 'PAYMENT'
1046         }
1047     )->store();
1048     $debits = $account->outstanding_debits;
1049     $credit->apply({ debits => [ $debits->as_list ] });
1050
1051     $debit = Koha::Account::Lines->find( $debit->id );
1052     is( $debit->amountoutstanding+0, 0, 'Account line was paid down by half' );
1053
1054     $checkout = Koha::Checkouts->find( $checkout->id );
1055     ok( !$checkout, 'Item was removed from patron account' );
1056
1057     $schema->storage->txn_rollback;
1058 };
1059
1060 subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->store)' => sub {
1061     plan tests => 38;
1062
1063     $schema->storage->txn_begin;
1064
1065     Koha::Account::Lines->delete();
1066
1067     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1068     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1069     my $account = $patron->account;
1070
1071     #t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1072     my $context = Test::MockModule->new('C4::Context');
1073     $context->mock( 'userenv', { branch => $library->id } );
1074
1075     my $now = dt_from_string;
1076     my $year = $now->year;
1077     my $month = $now->month;
1078     my ($accountlines_id, $accountline);
1079
1080     my $credit_type = Koha::Account::CreditTypes->find('PAYMENT');
1081     $credit_type->credit_number_enabled(1);
1082     $credit_type->store();
1083
1084     t::lib::Mocks::mock_preference('AutoCreditNumber', '');
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, undef, 'No credit number is generated when syspref is off');
1088
1089     t::lib::Mocks::mock_preference('AutoCreditNumber', 'incremental');
1090     for my $i (1..11) {
1091         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1092         $accountline = Koha::Account::Lines->find($accountlines_id);
1093         is($accountline->credit_number, $i, "Incremental format credit number added for payments: $i");
1094     }
1095     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1096     $accountline = Koha::Account::Lines->find($accountlines_id);
1097     is($accountline->credit_number, undef, "Incremental credit number not added for writeoff");
1098
1099     t::lib::Mocks::mock_preference('AutoCreditNumber', 'annual');
1100     for my $i (1..11) {
1101         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1102         $accountline = Koha::Account::Lines->find($accountlines_id);
1103         is($accountline->credit_number, sprintf('%s-%04d', $year, $i), "Annual format credit number added for payments: " . sprintf('%s-%04d', $year, $i));
1104     }
1105     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1106     $accountline = Koha::Account::Lines->find($accountlines_id);
1107     is($accountline->credit_number, undef, "Annual format credit number not aded for writeoff");
1108
1109     t::lib::Mocks::mock_preference('AutoCreditNumber', 'branchyyyymmincr');
1110     for my $i (1..11) {
1111         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1112         $accountline = Koha::Account::Lines->find($accountlines_id);
1113         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));
1114     }
1115     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1116     $accountline = Koha::Account::Lines->find($accountlines_id);
1117     is($accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff");
1118
1119     throws_ok {
1120         Koha::Account::Line->new(
1121             {
1122                 interface        => 'test',
1123                 amount           => -1,
1124                 credit_type_code => $credit_type->code,
1125                 credit_number    => 42
1126             }
1127         )->store;
1128     }
1129     'Koha::Exceptions::Account',
1130 "Exception thrown when AutoCreditNumber is enabled but credit_number is already defined";
1131
1132     $schema->storage->txn_rollback;
1133 };