Bug 33176: Handle RequirePaymentType
[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 => 15;
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 => 10;
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
74     is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_debits returns a Koha::Account::Lines object' );
75     is( $lines->total_outstanding, 10, 'Outstandig debits total is correctly calculated' );
76
77     my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
78     Koha::Account::Line->new(
79         {
80             borrowernumber    => $patron_2->id,
81             amountoutstanding => -2,
82             interface         => 'commandline',
83             credit_type_code  => 'PAYMENT'
84         }
85     )->store;
86     my $just_one = Koha::Account::Line->new(
87         {
88             borrowernumber    => $patron_2->id,
89             amount            => 3,
90             amountoutstanding => 3,
91             interface         => 'commandline',
92             debit_type_code   => 'OVERDUE'
93         }
94     )->store;
95     Koha::Account::Line->new(
96         {
97             borrowernumber    => $patron_2->id,
98             amount            => -6,
99             amountoutstanding => -6,
100             interface         => 'commandline',
101             credit_type_code  => 'PAYMENT'
102         }
103     )->store;
104     $lines = $patron_2->account->outstanding_debits();
105     is( $lines->total_outstanding, 3, "Total if some outstanding debits and some credits is only debits" );
106     is( $lines->count, 1, "With 1 outstanding debits, we get back a Lines object with 1 lines" );
107     my $the_line = Koha::Account::Lines->find( $just_one->id );
108     is_deeply( $the_line->unblessed, $lines->next->unblessed, "We get back the one correct line");
109
110     my $patron_3  = $builder->build_object({ class => 'Koha::Patrons' });
111     my $account_3 = $patron_3->account;
112     $account_3->add_credit( { amount => 2,   interface => 'commandline' } );
113     $account_3->add_credit( { amount => 20,  interface => 'commandline' } );
114     $account_3->add_credit( { amount => 200, interface => 'commandline' } );
115     $lines = $account_3->outstanding_debits();
116     is( $lines->total_outstanding, 0, "Total if no outstanding debits total is 0" );
117     is( $lines->count, 0, "With 0 outstanding debits, we get back a Lines object with 0 lines" );
118
119     my $patron_4  = $builder->build_object({ class => 'Koha::Patrons' });
120     my $account_4 = $patron_4->account;
121     $lines = $account_4->outstanding_debits();
122     is( $lines->total_outstanding, 0, "Total if no outstanding debits is 0" );
123     is( $lines->count, 0, "With no outstanding debits, we get back a Lines object with 0 lines" );
124
125     # create a pathological credit with amountoutstanding > 0 (BZ 14591)
126     Koha::Account::Line->new(
127         {
128             borrowernumber    => $patron_4->id,
129             amount            => -3,
130             amountoutstanding => 3,
131             interface         => 'commandline',
132             credit_type_code  => 'PAYMENT'
133         }
134     )->store();
135     $lines = $account_4->outstanding_debits();
136     is( $lines->count, 0, 'No credits are confused with debits because of the amountoutstanding value' );
137
138     $schema->storage->txn_rollback;
139 };
140
141 subtest 'outstanding_credits() tests' => sub {
142
143     plan tests => 5;
144
145     $schema->storage->txn_begin;
146
147     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
148     my $account = $patron->account;
149
150     my @generated_lines;
151     push @generated_lines, $account->add_credit({ amount => 1, interface => 'commandline' });
152     push @generated_lines, $account->add_credit({ amount => 2, interface => 'commandline' });
153     push @generated_lines, $account->add_credit({ amount => 3, interface => 'commandline' });
154     push @generated_lines, $account->add_credit({ amount => 4, interface => 'commandline' });
155
156     my $lines     = $account->outstanding_credits();
157
158     is( ref($lines), 'Koha::Account::Lines', 'Called in scalar context, outstanding_credits returns a Koha::Account::Lines object' );
159     is( $lines->total_outstanding, -10, 'Outstandig credits total is correctly calculated' );
160
161     my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
162     $account  = $patron_2->account;
163     $lines       = $account->outstanding_credits();
164     is( $lines->total_outstanding, 0, "Total if no outstanding credits is 0" );
165     is( $lines->count, 0, "With no outstanding credits, we get back a Lines object with 0 lines" );
166
167     # create a pathological debit with amountoutstanding < 0 (BZ 14591)
168     Koha::Account::Line->new(
169         {
170             borrowernumber    => $patron_2->id,
171             amount            => 2,
172             amountoutstanding => -3,
173             interface         => 'commandline',
174             debit_type_code   => 'OVERDUE'
175         }
176     )->store();
177     $lines = $account->outstanding_credits();
178     is( $lines->count, 0, 'No debits are confused with credits because of the amountoutstanding value' );
179
180     $schema->storage->txn_rollback;
181 };
182
183 subtest 'add_credit() tests' => sub {
184
185     plan tests => 22;
186
187     $schema->storage->txn_begin;
188
189     # delete logs and statistics
190     my $action_logs = $schema->resultset('ActionLog')->search()->count;
191     my $statistics = $schema->resultset('Statistic')->search()->count;
192
193     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
194     my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } );
195
196     is( $account->balance, 0, 'Patron has no balance' );
197
198     # Disable logs
199     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
200
201     throws_ok {
202         $account->add_credit(
203             {
204                 amount      => 25,
205                 description => 'Payment of 25',
206                 library_id  => $patron->branchcode,
207                 note        => 'not really important',
208                 type        => 'PAYMENT',
209                 user_id     => $patron->id
210             }
211         );
212     }
213     'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing';
214
215     my $line_1 = $account->add_credit(
216         {
217             amount      => 25,
218             description => 'Payment of 25',
219             library_id  => $patron->branchcode,
220             note        => 'not really important',
221             type        => 'PAYMENT',
222             user_id     => $patron->id,
223             interface   => 'commandline'
224         }
225     );
226
227     is( $account->balance, -25, 'Patron has a balance of -25' );
228     is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' );
229     is( $schema->resultset('Statistic')->count(), $statistics + 1, 'Action added to statistics' );
230     is( $line_1->credit_type_code, 'PAYMENT', 'Account type is correctly set' );
231     ok( $line_1->amount < 0, 'Credit amount is stored as a negative' );
232
233     # Enable logs
234     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
235
236     my $line_2 = $account->add_credit(
237         {   amount      => 37,
238             description => 'Payment of 37',
239             library_id  => $patron->branchcode,
240             note        => 'not really important',
241             user_id     => $patron->id,
242             interface   => 'commandline'
243         }
244     );
245
246     is( $account->balance, -62, 'Patron has a balance of -25' );
247     is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' );
248     is( $schema->resultset('Statistic')->count(), $statistics + 2, 'Action added to statistics' );
249     is( $line_2->credit_type_code, 'PAYMENT', 'Account type is correctly set' );
250     ok( $line_1->amount < 0, 'Credit amount is stored as a negative' );
251
252     # offsets have the credit_id set to accountlines_id, and debit_id is undef
253     my $offset_1 = Koha::Account::Offsets->search({ credit_id => $line_1->id })->next;
254     my $offset_2 = Koha::Account::Offsets->search({ credit_id => $line_2->id })->next;
255
256     is( $offset_1->credit_id, $line_1->id, 'No debit_id is set for credits' );
257     is( $offset_1->debit_id, undef, 'No debit_id is set for credits' );
258     ok( $offset_1->amount > 0, 'Credit creation offset is a positive' );
259     is( $offset_2->credit_id, $line_2->id, 'No debit_id is set for credits' );
260     is( $offset_2->debit_id, undef, 'No debit_id is set for credits' );
261     ok( $offset_2->amount > 0, 'Credit creation offset is a positive' );
262
263     my $line_3 = $account->add_credit(
264         {
265             amount      => 20,
266             description => 'Manual credit applied',
267             library_id  => $patron->branchcode,
268             user_id     => $patron->id,
269             type        => 'FORGIVEN',
270             interface   => 'commandline'
271         }
272     );
273
274     is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Log was added' );
275     is( $schema->resultset('Statistic')->count(), $statistics + 2, 'No action added to statistics, because of credit type' );
276
277     # Enable cash registers
278     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
279     throws_ok {
280         $account->add_credit(
281             {
282                 amount       => 20,
283                 description  => 'Cash payment without cash register',
284                 library_id   => $patron->branchcode,
285                 user_id      => $patron->id,
286                 payment_type => 'CASH',
287                 interface    => 'intranet'
288             }
289         );
290     }
291     'Koha::Exceptions::Account::RegisterRequired',
292       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
293
294     # Disable cash registers
295     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
296
297     my $item = $builder->build_sample_item;
298
299     my $checkout = Koha::Checkout->new(
300         {
301             borrowernumber => $patron->id,
302             itemnumber     => $item->id,
303             date_due       => \'NOW()',
304             branchcode     => $patron->branchcode,
305             issuedate      => \'NOW()',
306         }
307     )->store();
308
309     my $line_4 = $account->add_credit(
310         {
311             amount      => 20,
312             description => 'Manual credit applied',
313             library_id  => $patron->branchcode,
314             user_id     => $patron->id,
315             type        => 'FORGIVEN',
316             interface   => 'commandline',
317             issue_id    => $checkout->id
318         }
319     );
320
321     is( $line_4->issue_id, $checkout->id, 'The issue ID matches the checkout ID' );
322
323     $schema->storage->txn_rollback;
324 };
325
326 subtest 'add_debit() tests' => sub {
327
328     plan tests => 14;
329
330     $schema->storage->txn_begin;
331
332     # delete logs and statistics
333     my $action_logs = $schema->resultset('ActionLog')->search()->count;
334     my $statistics  = $schema->resultset('Statistic')->search()->count;
335
336     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
337     my $account =
338       Koha::Account->new( { patron_id => $patron->borrowernumber } );
339
340     is( $account->balance, 0, 'Patron has no balance' );
341
342     throws_ok {
343     $account->add_debit(
344         {
345             amount      => -5,
346             description => 'amount validation failure',
347             library_id  => $patron->branchcode,
348             note        => 'this should fail anyway',
349             type        => 'RENT',
350             user_id     => $patron->id,
351             interface   => 'commandline'
352         }
353     ); } 'Koha::Exceptions::Account::AmountNotPositive', 'Expected validation exception thrown (amount)';
354
355     throws_ok {
356         local *STDERR;
357         open STDERR, '>', '/dev/null';
358         $account->add_debit(
359             {
360                 amount      => 5,
361                 description => 'type validation failure',
362                 library_id  => $patron->branchcode,
363                 note        => 'this should fail anyway',
364                 type        => 'failure',
365                 user_id     => $patron->id,
366                 interface   => 'commandline'
367             }
368         );
369         close STDERR;
370     }
371     'Koha::Exceptions::Account::UnrecognisedType',
372       'Expected validation exception thrown (type)';
373
374     throws_ok {
375     $account->add_debit(
376         {
377             amount      => 25,
378             description => 'Rental charge of 25',
379             library_id  => $patron->branchcode,
380             note        => 'not really important',
381             type        => 'RENT',
382             user_id     => $patron->id
383         }
384     ); } 'Koha::Exceptions::MissingParameter', 'Exception thrown if interface parameter missing';
385
386     # Disable logs
387     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
388
389     my $line_1 = $account->add_debit(
390         {
391             amount      => 25,
392             description => 'Rental charge of 25',
393             library_id  => $patron->branchcode,
394             note        => 'not really important',
395             type        => 'RENT',
396             user_id     => $patron->id,
397             interface   => 'commandline'
398         }
399     );
400
401     is( $account->balance, 25, 'Patron has a balance of 25' );
402     is(
403         $schema->resultset('ActionLog')->count(),
404         $action_logs + 0,
405         'No log was added'
406     );
407     is(
408         $line_1->debit_type_code,
409         'RENT',
410         'Account type is correctly set'
411     );
412
413     # Enable logs
414     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
415
416     my $line_2   = $account->add_debit(
417         {
418             amount      => 37,
419             description => 'Rental charge of 37',
420             library_id  => $patron->branchcode,
421             note        => 'not really important',
422             type        => 'RENT',
423             user_id     => $patron->id,
424             interface   => 'commandline'
425         }
426     );
427
428     is( $account->balance, 62, 'Patron has a balance of 62' );
429     is(
430         $schema->resultset('ActionLog')->count(),
431         $action_logs + 1,
432         'Log was added'
433     );
434     is(
435         $line_2->debit_type_code,
436         'RENT',
437         'Account type is correctly set'
438     );
439
440     # offsets have the debit_id set to accountlines_id, and credit_id is undef
441     my $offset_1 =
442       Koha::Account::Offsets->search( { debit_id => $line_1->id } )->next;
443     my $offset_2 =
444       Koha::Account::Offsets->search( { debit_id => $line_2->id } )->next;
445
446     is( $offset_1->debit_id,  $line_1->id, 'debit_id is set for debit 1' );
447     is( $offset_1->credit_id, undef,       'credit_id is not set for debit 1' );
448     is( $offset_2->debit_id,  $line_2->id, 'debit_id is set for debit 2' );
449     is( $offset_2->credit_id, undef,       'credit_id is not set for debit 2' );
450
451     $schema->storage->txn_rollback;
452 };
453
454 subtest 'lines() tests' => sub {
455
456     plan tests => 1;
457
458     $schema->storage->txn_begin;
459
460     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
461     my $account = $patron->account;
462
463     # Add Credits
464     $account->add_credit({ amount => 1, interface => 'commandline' });
465     $account->add_credit({ amount => 2, interface => 'commandline' });
466     $account->add_credit({ amount => 3, interface => 'commandline' });
467     $account->add_credit({ amount => 4, interface => 'commandline' });
468
469     # Add Debits
470     $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
471     $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
472     $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
473     $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
474
475     # Paid Off
476     $account->add_credit( { amount => 1, interface => 'commandline' } )
477         ->apply( { debits => [ $account->outstanding_debits->as_list ] } );
478
479     my $lines = $account->lines;
480     is( $lines->_resultset->count, 9, "All accountlines (debits, credits and paid off) were fetched");
481
482     $schema->storage->txn_rollback;
483 };
484
485 subtest 'reconcile_balance' => sub {
486
487     plan tests => 4;
488
489     subtest 'more credit than debit' => sub {
490
491         plan tests => 6;
492
493         $schema->storage->txn_begin;
494
495         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
496         my $account = $patron->account;
497
498         # Add Credits
499         $account->add_credit({ amount => 1, interface => 'commandline' });
500         $account->add_credit({ amount => 2, interface => 'commandline' });
501         $account->add_credit({ amount => 3, interface => 'commandline' });
502         $account->add_credit({ amount => 4, interface => 'commandline' });
503         $account->add_credit({ amount => 5, interface => 'commandline' });
504
505         # Add Debits
506         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
507         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
508         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
509         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
510
511         # Paid Off
512         Koha::Account::Line->new(
513             {
514                 borrowernumber    => $patron->id,
515                 amount            => 1,
516                 amountoutstanding => 0,
517                 interface         => 'commandline',
518                 debit_type_code   => 'OVERDUE'
519             }
520         )->store;
521         Koha::Account::Line->new(
522             {
523                 borrowernumber    => $patron->id,
524                 amount            => 1,
525                 amountoutstanding => 0,
526                 interface         => 'commandline',
527                 debit_type_code   => 'OVERDUE'
528             }
529         )->store;
530
531         is( $account->balance(), -5, "Account balance is -5" );
532         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
533         is( $account->outstanding_credits->total_outstanding, -15, 'Outstanding credits sum -15' );
534
535         $account->reconcile_balance();
536
537         is( $account->balance(), -5, "Account balance is -5" );
538         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
539         is( $account->outstanding_credits->total_outstanding, -5, 'Outstanding credits sum -5' );
540
541         $schema->storage->txn_rollback;
542     };
543
544     subtest 'same debit as credit' => sub {
545
546         plan tests => 6;
547
548         $schema->storage->txn_begin;
549
550         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
551         my $account = $patron->account;
552
553         # Add Credits
554         $account->add_credit({ amount => 1, interface => 'commandline' });
555         $account->add_credit({ amount => 2, interface => 'commandline' });
556         $account->add_credit({ amount => 3, interface => 'commandline' });
557         $account->add_credit({ amount => 4, interface => 'commandline' });
558
559         # Add Debits
560         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
561         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
562         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
563         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
564
565         # Paid Off
566         Koha::Account::Line->new(
567             {
568                 borrowernumber    => $patron->id,
569                 amount            => 1,
570                 amountoutstanding => 0,
571                 interface         => 'commandline',
572                 debit_type_code   => 'OVERDUE'
573             }
574         )->store;
575         Koha::Account::Line->new(
576             {
577                 borrowernumber    => $patron->id,
578                 amount            => 1,
579                 amountoutstanding => 0,
580                 interface         => 'commandline',
581                 debit_type_code   => 'OVERDUE'
582             }
583         )->store;
584
585         is( $account->balance(), 0, "Account balance is 0" );
586         is( $account->outstanding_debits->total_outstanding, 10, 'Outstanding debits sum 10' );
587         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
588
589         $account->reconcile_balance();
590
591         is( $account->balance(), 0, "Account balance is 0" );
592         is( $account->outstanding_debits->total_outstanding, 0, 'No outstanding debits' );
593         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
594
595         $schema->storage->txn_rollback;
596     };
597
598     subtest 'more debit than credit' => sub {
599
600         plan tests => 6;
601
602         $schema->storage->txn_begin;
603
604         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
605         my $account = $patron->account;
606
607         # Add Credits
608         $account->add_credit({ amount => 1, interface => 'commandline' });
609         $account->add_credit({ amount => 2, interface => 'commandline' });
610         $account->add_credit({ amount => 3, interface => 'commandline' });
611         $account->add_credit({ amount => 4, interface => 'commandline' });
612
613         # Add Debits
614         $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
615         $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
616         $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
617         $account->add_debit({ amount => 4, interface => 'commandline', type => 'OVERDUE' });
618         $account->add_debit({ amount => 5, interface => 'commandline', type => 'OVERDUE' });
619
620         # Paid Off
621         Koha::Account::Line->new(
622             {
623                 borrowernumber    => $patron->id,
624                 amount            => 1,
625                 amountoutstanding => 0,
626                 interface         => 'commandline',
627                 debit_type_code   => 'OVERDUE'
628             }
629         )->store;
630         Koha::Account::Line->new(
631             {
632                 borrowernumber    => $patron->id,
633                 amount            => 1,
634                 amountoutstanding => 0,
635                 interface         => 'commandline',
636                 debit_type_code   => 'OVERDUE'
637             }
638         )->store;
639
640         is( $account->balance(), 5, "Account balance is 5" );
641         is( $account->outstanding_debits->total_outstanding, 15, 'Outstanding debits sum 15' );
642         is( $account->outstanding_credits->total_outstanding, -10, 'Outstanding credits sum -10' );
643
644         $account->reconcile_balance();
645
646         is( $account->balance(), 5, "Account balance is 5" );
647         is( $account->outstanding_debits->total_outstanding, 5, 'Outstanding debits sum 5' );
648         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
649
650         $schema->storage->txn_rollback;
651     };
652
653     subtest 'credits are applied to older debits first' => sub {
654
655         plan tests => 9;
656
657         $schema->storage->txn_begin;
658
659         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
660         my $account = $patron->account;
661
662         # Add Credits
663         $account->add_credit({ amount => 1, interface => 'commandline' });
664         $account->add_credit({ amount => 3, interface => 'commandline' });
665
666         # Add Debits
667         my $debit_1 = $account->add_debit({ amount => 1, interface => 'commandline', type => 'OVERDUE' });
668         my $debit_2 = $account->add_debit({ amount => 2, interface => 'commandline', type => 'OVERDUE' });
669         my $debit_3 = $account->add_debit({ amount => 3, interface => 'commandline', type => 'OVERDUE' });
670
671         is( $account->balance(), 2, "Account balance is 2" );
672         is( $account->outstanding_debits->total_outstanding, 6, 'Outstanding debits sum 6' );
673         is( $account->outstanding_credits->total_outstanding, -4, 'Outstanding credits sum -4' );
674
675         $account->reconcile_balance();
676
677         is( $account->balance(), 2, "Account balance is 2" );
678         is( $account->outstanding_debits->total_outstanding, 2, 'Outstanding debits sum 2' );
679         is( $account->outstanding_credits->total_outstanding, 0, 'Outstanding credits sum 0' );
680
681         $debit_1->discard_changes;
682         is( $debit_1->amountoutstanding + 0, 0, 'Old debit payed' );
683         $debit_2->discard_changes;
684         is( $debit_2->amountoutstanding + 0, 0, 'Old debit payed' );
685         $debit_3->discard_changes;
686         is( $debit_3->amountoutstanding + 0, 2, 'Newest debit only partially payed' );
687
688         $schema->storage->txn_rollback;
689     };
690 };
691
692 subtest 'pay() tests' => sub {
693
694     plan tests => 7;
695
696     $schema->storage->txn_begin;
697
698     # Disable renewing upon fine payment
699     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
700
701
702     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
703     my $library = $builder->build_object({ class => 'Koha::Libraries' });
704     my $account = $patron->account;
705
706     t::lib::Mocks::mock_preference( 'RequirePaymentType', 1 );
707     throws_ok {
708         $account->pay(
709             {
710                 amount       => 5,
711                 interface    => 'intranet'
712             }
713         );
714     }
715     'Koha::Exceptions::Account::PaymentTypeRequired',
716       'Exception thrown for RequirePaymentType:1 + payment_type:undef';
717
718     t::lib::Mocks::mock_preference( 'RequirePaymentType', 0 );
719     my $context = Test::MockModule->new('C4::Context');
720     $context->mock( 'userenv', { branch => $library->id } );
721
722     my $credit_1_id = $account->pay({ amount => 200 })->{payment_id};
723     my $credit_1    = Koha::Account::Lines->find( $credit_1_id );
724
725     is( $credit_1->branchcode, undef, 'No branchcode is set if library_id was not passed' );
726
727     my $credit_2_id = $account->pay({ amount => 150, library_id => $library->id })->{payment_id};
728     my $credit_2    = Koha::Account::Lines->find( $credit_2_id );
729
730     is( $credit_2->branchcode, $library->id, 'branchcode set because library_id was passed' );
731     # Enable cash registers
732     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
733     throws_ok {
734         $account->pay(
735             {
736                 amount       => 20,
737                 payment_type => 'CASH',
738                 interface    => 'intranet'
739             }
740         );
741     }
742     'Koha::Exceptions::Account::RegisterRequired',
743       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
744
745     # Disable cash registers
746     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
747
748     # Undef userenv
749     $context->mock( 'userenv', undef );
750     my $result = $account->pay(
751         {
752             amount => 20,
753             payment_Type => 'CASH',
754             interface => 'intranet'
755         }
756     );
757     ok($result, "Koha::Account->pay functions without a userenv");
758     my $payment = Koha::Account::Lines->find({accountlines_id => $result->{payment_id}});
759     is($payment->manager_id, undef, "manager_id left undefined when no userenv found");
760
761     subtest 'UseEmailReceipts tests' => sub {
762
763         plan tests => 5;
764
765         t::lib::Mocks::mock_preference( 'UseEmailReceipts', 1 );
766
767         my %params;
768
769         my $mocked_letters = Test::MockModule->new('C4::Letters');
770         # we want to test the params
771         $mocked_letters->mock( 'GetPreparedLetter', sub {
772             %params = @_;
773             return 1;
774         });
775         # we don't care about EnqueueLetter for now
776         $mocked_letters->mock( 'EnqueueLetter', sub {
777             return 1;
778         });
779
780         $schema->storage->txn_begin;
781
782         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
783         my $account = $patron->account;
784
785         my $debit_1 = $account->add_debit( { amount => 5,  interface => 'commandline', type => 'OVERDUE' } );
786         my $debit_2 = $account->add_debit( { amount => 10,  interface => 'commandline', type => 'OVERDUE' } );
787
788         $account->pay({ amount => 6, lines => [ $debit_1, $debit_2 ] });
789         my @offsets = @{$params{substitute}{offsets}};
790
791         is( scalar @offsets, 2, 'Two offsets related to payment' );
792         is( ref($offsets[0]), 'Koha::Account::Offset', 'Type is correct' );
793         is( ref($offsets[1]), 'Koha::Account::Offset', 'Type is correct' );
794         is( $offsets[0]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' );
795         is( $offsets[1]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' );
796
797         $schema->storage->txn_rollback;
798     };
799
800     $schema->storage->txn_rollback;
801 };
802
803 subtest 'pay() handles lost items when paying a specific lost fee' => sub {
804
805     plan tests => 5;
806
807     $schema->storage->txn_begin;
808
809     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
810     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
811     my $account = $patron->account;
812
813     my $context = Test::MockModule->new('C4::Context');
814     $context->mock( 'userenv', { branch => $library->id } );
815
816     my $biblio = $builder->build_sample_biblio();
817     my $item =
818       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
819
820     my $checkout = Koha::Checkout->new(
821         {
822             borrowernumber => $patron->id,
823             itemnumber     => $item->id,
824             date_due       => \'NOW()',
825             branchcode     => $patron->branchcode,
826             issuedate      => \'NOW()',
827         }
828     )->store();
829
830     $item->itemlost('1')->store();
831
832     my $accountline = Koha::Account::Line->new(
833         {
834             issue_id       => $checkout->id,
835             borrowernumber => $patron->id,
836             itemnumber     => $item->id,
837             date           => \'NOW()',
838             debit_type_code    => 'LOST',
839             interface      => 'cli',
840             amount => '1',
841             amountoutstanding => '1',
842         }
843     )->store();
844
845     $account->pay(
846         {
847             amount     => .5,
848             library_id => $library->id,
849             lines      => [$accountline],
850         }
851     );
852
853     $accountline = Koha::Account::Lines->find( $accountline->id );
854     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
855
856     $checkout = Koha::Checkouts->find( $checkout->id );
857     ok( $checkout, 'Item still checked out to patron' );
858
859     $account->pay(
860         {
861             amount     => 0.5,
862             library_id => $library->id,
863             lines      => [$accountline],
864         }
865     );
866
867     $accountline = Koha::Account::Lines->find( $accountline->id );
868     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
869
870     $checkout = Koha::Checkouts->find( $checkout->id );
871     ok( !$checkout, 'Item was removed from patron account' );
872
873     subtest 'item was not checked out to the same patron' => sub {
874         plan tests => 1;
875
876         my $patron_2 = $builder->build_object(
877             {
878                 class => 'Koha::Patrons',
879                 value => { branchcode => $library->branchcode }
880             }
881         );
882         $item->itemlost('1')->store();
883         C4::Accounts::chargelostitem( $patron->borrowernumber, $item->itemnumber, 5, "lost" );
884         my $accountline = Koha::Account::Lines->search(
885             {
886                 borrowernumber  => $patron->borrowernumber,
887                 itemnumber      => $item->itemnumber,
888                 debit_type_code => 'LOST'
889             }
890         )->next;
891         my $checkout = Koha::Checkout->new(
892             {
893                 borrowernumber => $patron_2->borrowernumber,
894                 itemnumber     => $item->itemnumber,
895                 date_due       => \'NOW()',
896                 branchcode     => $patron_2->branchcode,
897                 issuedate      => \'NOW()',
898             }
899         )->store();
900
901         $patron->account->pay(
902             {
903                 amount     => 5,
904                 library_id => $library->branchcode,
905                 lines      => [$accountline],
906             }
907         );
908
909         ok(
910             Koha::Checkouts->find( $checkout->issue_id ),
911             'If the item is checked out to another patron, a lost item should not be returned if lost fee is paid'
912         );
913
914     };
915
916     $schema->storage->txn_rollback;
917 };
918
919 subtest 'pay() handles lost items when paying by amount ( not specifying the lost fee )' => sub {
920
921     plan tests => 4;
922
923     $schema->storage->txn_begin;
924
925     # Enable AccountAutoReconcile
926     t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
927
928     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
929     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
930     my $account = $patron->account;
931
932     my $context = Test::MockModule->new('C4::Context');
933     $context->mock( 'userenv', { branch => $library->id } );
934
935     my $biblio = $builder->build_sample_biblio();
936     my $item =
937       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
938
939     my $checkout = Koha::Checkout->new(
940         {
941             borrowernumber => $patron->id,
942             itemnumber     => $item->id,
943             date_due       => \'NOW()',
944             branchcode     => $patron->branchcode,
945             issuedate      => \'NOW()',
946         }
947     )->store();
948
949     $item->itemlost('1')->store();
950
951     my $accountline = Koha::Account::Line->new(
952         {
953             issue_id       => $checkout->id,
954             borrowernumber => $patron->id,
955             itemnumber     => $item->id,
956             date           => \'NOW()',
957             debit_type_code    => 'LOST',
958             interface      => 'cli',
959             amount => '1',
960             amountoutstanding => '1',
961         }
962     )->store();
963
964     $account->pay(
965         {
966             amount     => .5,
967             library_id => $library->id,
968         }
969     );
970
971     $accountline = Koha::Account::Lines->find( $accountline->id );
972     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
973
974     $checkout = Koha::Checkouts->find( $checkout->id );
975     ok( $checkout, 'Item still checked out to patron' );
976
977     $account->pay(
978         {
979             amount     => .5,,
980             library_id => $library->id,
981         }
982     );
983
984     $accountline = Koha::Account::Lines->find( $accountline->id );
985     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
986
987     $checkout = Koha::Checkouts->find( $checkout->id );
988     ok( !$checkout, 'Item was removed from patron account' );
989
990     $schema->storage->txn_rollback;
991 };
992
993 subtest 'pay() renews items when appropriate' => sub {
994
995     plan tests => 7;
996
997     $schema->storage->txn_begin;
998
999     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1000     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1001     my $account = $patron->account;
1002
1003     my $context = Test::MockModule->new('C4::Context');
1004     $context->mock( 'userenv', { branch => $library->id } );
1005
1006     my $biblio = $builder->build_sample_biblio();
1007     my $item =
1008       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
1009
1010     my $now = dt_from_string();
1011     my $seven_weeks = DateTime::Duration->new(weeks => 7);
1012     my $five_weeks = DateTime::Duration->new(weeks => 5);
1013     my $seven_weeks_ago = $now - $seven_weeks;
1014     my $five_weeks_ago = $now - $five_weeks;
1015
1016     my $checkout = Koha::Checkout->new(
1017         {
1018             borrowernumber => $patron->id,
1019             itemnumber     => $item->id,
1020             date_due       => $five_weeks_ago,
1021             branchcode     => $patron->branchcode,
1022             issuedate      => $seven_weeks_ago
1023         }
1024     )->store();
1025
1026     my $accountline = Koha::Account::Line->new(
1027         {
1028             issue_id       => $checkout->id,
1029             borrowernumber => $patron->id,
1030             itemnumber     => $item->id,
1031             date           => \'NOW()',
1032             debit_type_code => 'OVERDUE',
1033             status         => 'UNRETURNED',
1034             interface      => 'cli',
1035             amount => '1',
1036             amountoutstanding => '1',
1037         }
1038     )->store();
1039
1040     # Enable renewing upon fine payment
1041     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
1042     my $called = 0;
1043     my $module = Test::MockModule->new('C4::Circulation');
1044     $module->mock('AddRenewal', sub { $called = 1; });
1045     $module->mock('CanBookBeRenewed', sub { return 1; });
1046     my $result = $account->pay(
1047         {
1048             amount     => '1',
1049             library_id => $library->id,
1050         }
1051     );
1052
1053     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
1054     is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" );
1055     is( scalar @{$result->{renew_result}}, 1, "renew_result contains one renewal result" );
1056     is( $result->{renew_result}->[0]->{itemnumber}, $item->id, "renew_result contains itemnumber of renewed item" );
1057
1058     # Reset test by adding a new overdue
1059     Koha::Account::Line->new(
1060         {
1061             issue_id       => $checkout->id,
1062             borrowernumber => $patron->id,
1063             itemnumber     => $item->id,
1064             date           => \'NOW()',
1065             debit_type_code => 'OVERDUE',
1066             status         => 'UNRETURNED',
1067             interface      => 'cli',
1068             amount => '1',
1069             amountoutstanding => '1',
1070         }
1071     )->store();
1072     $called = 0;
1073
1074     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
1075     $result = $account->pay(
1076         {
1077             amount     => '1',
1078             library_id => $library->id,
1079         }
1080     );
1081
1082     is( $called, 0, 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid disabled' );
1083     is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" );
1084     is( scalar @{$result->{renew_result}}, 0, "renew_result contains no renewal results" );
1085
1086     $schema->storage->txn_rollback;
1087 };
1088
1089 subtest 'Koha::Account::Line::apply() handles lost items' => sub {
1090
1091     plan tests => 4;
1092
1093     $schema->storage->txn_begin;
1094
1095     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1096     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1097     my $account = $patron->account;
1098
1099     my $context = Test::MockModule->new('C4::Context');
1100     $context->mock( 'userenv', { branch => $library->id } );
1101
1102     my $biblio = $builder->build_sample_biblio();
1103     my $item =
1104       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
1105
1106     my $checkout = Koha::Checkout->new(
1107         {
1108             borrowernumber => $patron->id,
1109             itemnumber     => $item->id,
1110             date_due       => \'NOW()',
1111             branchcode     => $patron->branchcode,
1112             issuedate      => \'NOW()',
1113         }
1114     )->store();
1115
1116     $item->itemlost('1')->store();
1117
1118     my $debit = Koha::Account::Line->new(
1119         {
1120             issue_id          => $checkout->id,
1121             borrowernumber    => $patron->id,
1122             itemnumber        => $item->id,
1123             date              => \'NOW()',
1124             debit_type_code       => 'LOST',
1125             interface         => 'cli',
1126             amount            => '1',
1127             amountoutstanding => '1',
1128         }
1129     )->store();
1130
1131     my $credit = Koha::Account::Line->new(
1132         {
1133             borrowernumber    => $patron->id,
1134             date              => '1970-01-01 00:00:01',
1135             amount            => -.5,
1136             amountoutstanding => -.5,
1137             interface         => 'commandline',
1138             credit_type_code  => 'PAYMENT'
1139         }
1140     )->store();
1141     my $debits = $account->outstanding_debits;
1142     $credit->apply({ debits => [ $debits->as_list ] });
1143
1144     $debit = Koha::Account::Lines->find( $debit->id );
1145     is( $debit->amountoutstanding+0, .5, 'Account line was paid down by half' );
1146
1147     $checkout = Koha::Checkouts->find( $checkout->id );
1148     ok( $checkout, 'Item still checked out to patron' );
1149
1150     $credit = Koha::Account::Line->new(
1151         {
1152             borrowernumber    => $patron->id,
1153             date              => '1970-01-01 00:00:01',
1154             amount            => -.5,
1155             amountoutstanding => -.5,
1156             interface         => 'commandline',
1157             credit_type_code  => 'PAYMENT'
1158         }
1159     )->store();
1160     $debits = $account->outstanding_debits;
1161     $credit->apply({ debits => [ $debits->as_list ] });
1162
1163     $debit = Koha::Account::Lines->find( $debit->id );
1164     is( $debit->amountoutstanding+0, 0, 'Account line was paid down by half' );
1165
1166     $checkout = Koha::Checkouts->find( $checkout->id );
1167     ok( !$checkout, 'Item was removed from patron account' );
1168
1169     $schema->storage->txn_rollback;
1170 };
1171
1172 subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->store)' => sub {
1173     plan tests => 38;
1174
1175     $schema->storage->txn_begin;
1176
1177     Koha::Account::Lines->delete();
1178
1179     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1180     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1181     my $account = $patron->account;
1182
1183     #t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1184     my $context = Test::MockModule->new('C4::Context');
1185     $context->mock( 'userenv', { branch => $library->id } );
1186
1187     my $now = dt_from_string;
1188     my $year = $now->year;
1189     my $month = $now->month;
1190     my ($accountlines_id, $accountline);
1191
1192     my $credit_type = Koha::Account::CreditTypes->find('PAYMENT');
1193     $credit_type->credit_number_enabled(1);
1194     $credit_type->store();
1195
1196     t::lib::Mocks::mock_preference('AutoCreditNumber', '');
1197     $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1198     $accountline = Koha::Account::Lines->find($accountlines_id);
1199     is($accountline->credit_number, undef, 'No credit number is generated when syspref is off');
1200
1201     t::lib::Mocks::mock_preference('AutoCreditNumber', 'incremental');
1202     for my $i (1..11) {
1203         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1204         $accountline = Koha::Account::Lines->find($accountlines_id);
1205         is($accountline->credit_number, $i, "Incremental format credit number added for payments: $i");
1206     }
1207     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1208     $accountline = Koha::Account::Lines->find($accountlines_id);
1209     is($accountline->credit_number, undef, "Incremental credit number not added for writeoff");
1210
1211     t::lib::Mocks::mock_preference('AutoCreditNumber', 'annual');
1212     for my $i (1..11) {
1213         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1214         $accountline = Koha::Account::Lines->find($accountlines_id);
1215         is($accountline->credit_number, sprintf('%s-%04d', $year, $i), "Annual format credit number added for payments: " . sprintf('%s-%04d', $year, $i));
1216     }
1217     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1218     $accountline = Koha::Account::Lines->find($accountlines_id);
1219     is($accountline->credit_number, undef, "Annual format credit number not aded for writeoff");
1220
1221     t::lib::Mocks::mock_preference('AutoCreditNumber', 'branchyyyymmincr');
1222     for my $i (1..11) {
1223         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1224         $accountline = Koha::Account::Lines->find($accountlines_id);
1225         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));
1226     }
1227     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1228     $accountline = Koha::Account::Lines->find($accountlines_id);
1229     is($accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff");
1230
1231     throws_ok {
1232         Koha::Account::Line->new(
1233             {
1234                 interface        => 'test',
1235                 amount           => -1,
1236                 credit_type_code => $credit_type->code,
1237                 credit_number    => 42
1238             }
1239         )->store;
1240     }
1241     'Koha::Exceptions::Account',
1242 "Exception thrown when AutoCreditNumber is enabled but credit_number is already defined";
1243
1244     $schema->storage->txn_rollback;
1245 };
1246
1247 subtest 'Koha::Account::payout_amount() tests' => sub {
1248     plan tests => 39;
1249
1250     $schema->storage->txn_begin;
1251
1252     # delete logs and statistics
1253     my $action_logs = $schema->resultset('ActionLog')->search()->count;
1254     my $statistics  = $schema->resultset('Statistic')->search()->count;
1255
1256     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
1257     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1258     my $register =
1259       $builder->build_object( { class => 'Koha::Cash::Registers' } );
1260     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1261     my $account =
1262       Koha::Account->new( { patron_id => $patron->borrowernumber } );
1263
1264     is( $account->balance, 0, 'Test patron has no balance' );
1265
1266     my $payout_params = {
1267         payout_type => 'CASH',
1268         branch      => $library->id,
1269         register_id => $register->id,
1270         staff_id    => $staff->id,
1271         interface   => 'intranet',
1272         amount      => -10,
1273     };
1274
1275     my @required_fields =
1276       ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' );
1277     for my $required_field (@required_fields) {
1278         my $this_payout = { %{$payout_params} };
1279         delete $this_payout->{$required_field};
1280
1281         throws_ok {
1282             $account->payout_amount($this_payout);
1283         }
1284         'Koha::Exceptions::MissingParameter',
1285           "Exception thrown if $required_field parameter missing";
1286     }
1287
1288     throws_ok {
1289         $account->payout_amount($payout_params);
1290     }
1291     'Koha::Exceptions::Account::AmountNotPositive',
1292       'Expected validation exception thrown (amount not positive)';
1293
1294     $payout_params->{amount} = 10;
1295     throws_ok {
1296         $account->payout_amount($payout_params);
1297     }
1298     'Koha::Exceptions::ParameterTooHigh',
1299       'Expected validation exception thrown (amount greater than outstanding)';
1300
1301     # Enable cash registers
1302     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
1303     throws_ok {
1304         $account->payout_amount($payout_params);
1305     }
1306     'Koha::Exceptions::Account::RegisterRequired',
1307 'Exception thrown for UseCashRegisters:1 + payout_type:CASH + cash_register:undef';
1308
1309     # Disable cash registers
1310     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
1311
1312     # Add some outstanding credits
1313     my $credit_1 = $account->add_credit( { amount => 2,  interface => 'commandline' } );
1314     my $credit_2 = $account->add_credit( { amount => 3,  interface => 'commandline' } );
1315     my $credit_3 = $account->add_credit( { amount => 5,  interface => 'commandline' } );
1316     my $credit_4 = $account->add_credit( { amount => 10, interface => 'commandline' } );
1317     my $credits = $account->outstanding_credits();
1318     is( $credits->count, 4, "Found 4 credits with outstanding amounts" );
1319     is( $credits->total_outstanding + 0, -20, "Total -20 outstanding credit" );
1320
1321     my $payout = $account->payout_amount($payout_params);
1322     is(ref($payout), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payout');
1323     is($payout->amount + 0, 10, "Payout amount recorded correctly");
1324     is($payout->amountoutstanding + 0, 0, "Full amount was paid out");
1325     $credits = $account->outstanding_credits();
1326     is($credits->count, 1, "Payout was applied against oldest outstanding credits first");
1327     is($credits->total_outstanding + 0, -10, "Total of 10 outstanding credit remaining");
1328
1329     my $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } );
1330     is( $offsets->count, 4, 'Four offsets generated' );
1331     my $offset = $offsets->next;
1332     is( $offset->type, 'CREATE', 'CREATE offset added for payout line' );
1333     is( $offset->amount * 1, 10, 'Correct offset amount recorded' );
1334     $offset = $offsets->next;
1335     is( $offset->credit_id, $credit_1->id, "Offset added against credit_1");
1336     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1337     is( $offset->amount * 1, -2,      'Correct amount offset against credit_1' );
1338     $offset = $offsets->next;
1339     is( $offset->credit_id, $credit_2->id, "Offset added against credit_2");
1340     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1341     is( $offset->amount * 1, -3,      'Correct amount offset against credit_2' );
1342     $offset = $offsets->next;
1343     is( $offset->credit_id, $credit_3->id, "Offset added against credit_3");
1344     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1345     is( $offset->amount * 1, -5,      'Correct amount offset against credit_3' );
1346
1347     my $credit_5 = $account->add_credit( { amount => 5, interface => 'commandline' } );
1348     $credits = $account->outstanding_credits();
1349     is($credits->count, 2, "New credit added");
1350     $payout_params->{amount} = 2.50;
1351     $payout_params->{credits} = [$credit_5];
1352     $payout = $account->payout_amount($payout_params);
1353
1354     $credits = $account->outstanding_credits();
1355     is($credits->count, 2, "Second credit not fully paid off");
1356     is($credits->total_outstanding + 0, -12.50, "12.50 outstanding credit remaining");
1357     $credit_4->discard_changes;
1358     $credit_5->discard_changes;
1359     is($credit_4->amountoutstanding + 0, -10, "Credit 4 unaffected when credit_5 was passed to payout_amount");
1360     is($credit_5->amountoutstanding + 0, -2.50, "Credit 5 correctly reduced when payout_amount called with credit_5 passed");
1361
1362     $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } );
1363     is( $offsets->count, 2, 'Two offsets generated' );
1364     $offset = $offsets->next;
1365     is( $offset->type, 'CREATE', 'CREATE offset added for payout line' );
1366     is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' );
1367     $offset = $offsets->next;
1368     is( $offset->credit_id, $credit_5->id, "Offset added against credit_5");
1369     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1370     is( $offset->amount * 1, -2.50,      'Correct amount offset against credit_5' );
1371
1372     $schema->storage->txn_rollback;
1373 };
1374
1375 subtest 'Koha::Account::payin_amount() tests' => sub {
1376     plan tests => 36;
1377
1378     $schema->storage->txn_begin;
1379
1380     # delete logs and statistics
1381     my $action_logs = $schema->resultset('ActionLog')->search()->count;
1382     my $statistics  = $schema->resultset('Statistic')->search()->count;
1383
1384     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
1385     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1386     my $register =
1387       $builder->build_object( { class => 'Koha::Cash::Registers' } );
1388     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1389     my $account =
1390       Koha::Account->new( { patron_id => $patron->borrowernumber } );
1391
1392     is( $account->balance, 0, 'Test patron has no balance' );
1393
1394     my $payin_params = {
1395         type  => 'PAYMENT',
1396         payment_type => 'CASH',
1397         branch       => $library->id,
1398         register_id  => $register->id,
1399         staff_id     => $staff->id,
1400         interface    => 'intranet',
1401         amount       => -10,
1402     };
1403
1404     my @required_fields =
1405       ( 'interface', 'amount', 'type' );
1406     for my $required_field (@required_fields) {
1407         my $this_payin = { %{$payin_params} };
1408         delete $this_payin->{$required_field};
1409
1410         throws_ok {
1411             $account->payin_amount($this_payin);
1412         }
1413         'Koha::Exceptions::MissingParameter',
1414           "Exception thrown if $required_field parameter missing";
1415     }
1416
1417     throws_ok {
1418         $account->payin_amount($payin_params);
1419     }
1420     'Koha::Exceptions::Account::AmountNotPositive',
1421       'Expected validation exception thrown (amount not positive)';
1422
1423     $payin_params->{amount} = 10;
1424
1425     # Enable cash registers
1426     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
1427     throws_ok {
1428         $account->payin_amount($payin_params);
1429     }
1430     'Koha::Exceptions::Account::RegisterRequired',
1431 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
1432
1433     # Disable cash registers
1434     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
1435
1436     # Enable AccountAutoReconcile
1437     t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
1438
1439     # Add some outstanding debits
1440     my $debit_1 = $account->add_debit( { amount => 2,  interface => 'commandline', type => 'OVERDUE' } );
1441     my $debit_2 = $account->add_debit( { amount => 3,  interface => 'commandline', type => 'OVERDUE' } );
1442     my $debit_3 = $account->add_debit( { amount => 5,  interface => 'commandline', type => 'OVERDUE' } );
1443     my $debit_4 = $account->add_debit( { amount => 10, interface => 'commandline', type => 'OVERDUE' } );
1444     my $debits = $account->outstanding_debits();
1445     is( $debits->count, 4, "Found 4 debits with outstanding amounts" );
1446     is( $debits->total_outstanding + 0, 20, "Total 20 outstanding debit" );
1447
1448     my $payin = $account->payin_amount($payin_params);
1449     is(ref($payin), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payin');
1450     is($payin->amount + 0, -10, "Payin amount recorded correctly");
1451     is($payin->amountoutstanding + 0, 0, "Full amount was used to pay debts");
1452     $debits = $account->outstanding_debits();
1453     is($debits->count, 1, "Payin was applied against oldest outstanding debits first");
1454     is($debits->total_outstanding + 0, 10, "Total of 10 outstanding debit remaining");
1455
1456     my $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } );
1457     is( $offsets->count, 4, 'Four offsets generated' );
1458     my $offset = $offsets->next;
1459     is( $offset->type, 'CREATE', 'CREATE offset added for payin line' );
1460     is( $offset->amount * 1, 10, 'Correct offset amount recorded' );
1461     $offset = $offsets->next;
1462     is( $offset->debit_id, $debit_1->id, "Offset added against debit_1");
1463     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1464     is( $offset->amount * 1, -2,      'Correct amount offset against debit_1' );
1465     $offset = $offsets->next;
1466     is( $offset->debit_id, $debit_2->id, "Offset added against debit_2");
1467     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1468     is( $offset->amount * 1, -3,      'Correct amount offset against debit_2' );
1469     $offset = $offsets->next;
1470     is( $offset->debit_id, $debit_3->id, "Offset added against debit_3");
1471     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1472     is( $offset->amount * 1, -5,      'Correct amount offset against debit_3' );
1473
1474     my $debit_5 = $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } );
1475     $debits = $account->outstanding_debits();
1476     is($debits->count, 2, "New debit added");
1477     $payin_params->{amount} = 2.50;
1478     $payin_params->{debits} = [$debit_5];
1479     $payin = $account->payin_amount($payin_params);
1480
1481     $debits = $account->outstanding_debits();
1482     is($debits->count, 2, "Second debit not fully paid off");
1483     is($debits->total_outstanding + 0, 12.50, "12.50 outstanding debit remaining");
1484     $debit_4->discard_changes;
1485     $debit_5->discard_changes;
1486     is($debit_4->amountoutstanding + 0, 10, "Debit 4 unaffected when debit_5 was passed to payin_amount");
1487     is($debit_5->amountoutstanding + 0, 2.50, "Debit 5 correctly reduced when payin_amount called with debit_5 passed");
1488
1489     $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } );
1490     is( $offsets->count, 2, 'Two offsets generated' );
1491     $offset = $offsets->next;
1492     is( $offset->type, 'CREATE', 'CREATE offset added for payin line' );
1493     is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' );
1494     $offset = $offsets->next;
1495     is( $offset->debit_id, $debit_5->id, "Offset added against debit_5");
1496     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1497     is( $offset->amount * 1, -2.50,      'Correct amount offset against debit_5' );
1498
1499     $schema->storage->txn_rollback;
1500 };