Bug 33789: Add unit test
[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 => 6;
695
696     $schema->storage->txn_begin;
697
698     # Disable renewing upon fine payment
699     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
700
701     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
702     my $library = $builder->build_object({ class => 'Koha::Libraries' });
703     my $account = $patron->account;
704
705     my $context = Test::MockModule->new('C4::Context');
706     $context->mock( 'userenv', { branch => $library->id } );
707
708     my $credit_1_id = $account->pay({ amount => 200 })->{payment_id};
709     my $credit_1    = Koha::Account::Lines->find( $credit_1_id );
710
711     is( $credit_1->branchcode, undef, 'No branchcode is set if library_id was not passed' );
712
713     my $credit_2_id = $account->pay({ amount => 150, library_id => $library->id })->{payment_id};
714     my $credit_2    = Koha::Account::Lines->find( $credit_2_id );
715
716     is( $credit_2->branchcode, $library->id, 'branchcode set because library_id was passed' );
717
718     # Enable cash registers
719     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
720     throws_ok {
721         $account->pay(
722             {
723                 amount       => 20,
724                 payment_type => 'CASH',
725                 interface    => 'intranet'
726             }
727         );
728     }
729     'Koha::Exceptions::Account::RegisterRequired',
730       'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
731
732     # Disable cash registers
733     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
734
735     # Undef userenv
736     $context->mock( 'userenv', undef );
737     my $result = $account->pay(
738         {
739             amount => 20,
740             payment_Type => 'CASH',
741             interface => 'intranet'
742         }
743     );
744     ok($result, "Koha::Account->pay functions without a userenv");
745     my $payment = Koha::Account::Lines->find({accountlines_id => $result->{payment_id}});
746     is($payment->manager_id, undef, "manager_id left undefined when no userenv found");
747
748     subtest 'UseEmailReceipts tests' => sub {
749
750         plan tests => 5;
751
752         t::lib::Mocks::mock_preference( 'UseEmailReceipts', 1 );
753
754         my %params;
755
756         my $mocked_letters = Test::MockModule->new('C4::Letters');
757         # we want to test the params
758         $mocked_letters->mock( 'GetPreparedLetter', sub {
759             %params = @_;
760             return 1;
761         });
762         # we don't care about EnqueueLetter for now
763         $mocked_letters->mock( 'EnqueueLetter', sub {
764             return 1;
765         });
766
767         $schema->storage->txn_begin;
768
769         my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
770         my $account = $patron->account;
771
772         my $debit_1 = $account->add_debit( { amount => 5,  interface => 'commandline', type => 'OVERDUE' } );
773         my $debit_2 = $account->add_debit( { amount => 10,  interface => 'commandline', type => 'OVERDUE' } );
774
775         $account->pay({ amount => 6, lines => [ $debit_1, $debit_2 ] });
776         my @offsets = @{$params{substitute}{offsets}};
777
778         is( scalar @offsets, 2, 'Two offsets related to payment' );
779         is( ref($offsets[0]), 'Koha::Account::Offset', 'Type is correct' );
780         is( ref($offsets[1]), 'Koha::Account::Offset', 'Type is correct' );
781         is( $offsets[0]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' );
782         is( $offsets[1]->type, 'APPLY', 'Only APPLY offsets are passed to the notice' );
783
784         $schema->storage->txn_rollback;
785     };
786
787     $schema->storage->txn_rollback;
788 };
789
790 subtest 'pay() handles lost items when paying a specific lost fee' => sub {
791
792     plan tests => 5;
793
794     $schema->storage->txn_begin;
795
796     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
797     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
798     my $account = $patron->account;
799
800     my $context = Test::MockModule->new('C4::Context');
801     $context->mock( 'userenv', { branch => $library->id } );
802
803     my $biblio = $builder->build_sample_biblio();
804     my $item =
805       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
806
807     my $checkout = Koha::Checkout->new(
808         {
809             borrowernumber => $patron->id,
810             itemnumber     => $item->id,
811             date_due       => \'NOW()',
812             branchcode     => $patron->branchcode,
813             issuedate      => \'NOW()',
814         }
815     )->store();
816
817     $item->itemlost('1')->store();
818
819     my $accountline = Koha::Account::Line->new(
820         {
821             issue_id       => $checkout->id,
822             borrowernumber => $patron->id,
823             itemnumber     => $item->id,
824             date           => \'NOW()',
825             debit_type_code    => 'LOST',
826             interface      => 'cli',
827             amount => '1',
828             amountoutstanding => '1',
829         }
830     )->store();
831
832     $account->pay(
833         {
834             amount     => .5,
835             library_id => $library->id,
836             lines      => [$accountline],
837         }
838     );
839
840     $accountline = Koha::Account::Lines->find( $accountline->id );
841     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
842
843     $checkout = Koha::Checkouts->find( $checkout->id );
844     ok( $checkout, 'Item still checked out to patron' );
845
846     $account->pay(
847         {
848             amount     => 0.5,
849             library_id => $library->id,
850             lines      => [$accountline],
851         }
852     );
853
854     $accountline = Koha::Account::Lines->find( $accountline->id );
855     is( $accountline->amountoutstanding+0, 0, 'Account line was paid down by half' );
856
857     $checkout = Koha::Checkouts->find( $checkout->id );
858     ok( !$checkout, 'Item was removed from patron account' );
859
860     subtest 'item was not checked out to the same patron' => sub {
861         plan tests => 1;
862
863         my $patron_2 = $builder->build_object(
864             {
865                 class => 'Koha::Patrons',
866                 value => { branchcode => $library->branchcode }
867             }
868         );
869         $item->itemlost('1')->store();
870         C4::Accounts::chargelostitem( $patron->borrowernumber, $item->itemnumber, 5, "lost" );
871         my $accountline = Koha::Account::Lines->search(
872             {
873                 borrowernumber  => $patron->borrowernumber,
874                 itemnumber      => $item->itemnumber,
875                 debit_type_code => 'LOST'
876             }
877         )->next;
878         my $checkout = Koha::Checkout->new(
879             {
880                 borrowernumber => $patron_2->borrowernumber,
881                 itemnumber     => $item->itemnumber,
882                 date_due       => \'NOW()',
883                 branchcode     => $patron_2->branchcode,
884                 issuedate      => \'NOW()',
885             }
886         )->store();
887
888         $patron->account->pay(
889             {
890                 amount     => 5,
891                 library_id => $library->branchcode,
892                 lines      => [$accountline],
893             }
894         );
895
896         ok(
897             Koha::Checkouts->find( $checkout->issue_id ),
898             'If the item is checked out to another patron, a lost item should not be returned if lost fee is paid'
899         );
900
901     };
902
903     $schema->storage->txn_rollback;
904 };
905
906 subtest 'pay() handles lost items when paying by amount ( not specifying the lost fee )' => sub {
907
908     plan tests => 4;
909
910     $schema->storage->txn_begin;
911
912     # Enable AccountAutoReconcile
913     t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
914
915     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
916     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
917     my $account = $patron->account;
918
919     my $context = Test::MockModule->new('C4::Context');
920     $context->mock( 'userenv', { branch => $library->id } );
921
922     my $biblio = $builder->build_sample_biblio();
923     my $item =
924       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
925
926     my $checkout = Koha::Checkout->new(
927         {
928             borrowernumber => $patron->id,
929             itemnumber     => $item->id,
930             date_due       => \'NOW()',
931             branchcode     => $patron->branchcode,
932             issuedate      => \'NOW()',
933         }
934     )->store();
935
936     $item->itemlost('1')->store();
937
938     my $accountline = Koha::Account::Line->new(
939         {
940             issue_id       => $checkout->id,
941             borrowernumber => $patron->id,
942             itemnumber     => $item->id,
943             date           => \'NOW()',
944             debit_type_code    => 'LOST',
945             interface      => 'cli',
946             amount => '1',
947             amountoutstanding => '1',
948         }
949     )->store();
950
951     $account->pay(
952         {
953             amount     => .5,
954             library_id => $library->id,
955         }
956     );
957
958     $accountline = Koha::Account::Lines->find( $accountline->id );
959     is( $accountline->amountoutstanding+0, .5, 'Account line was paid down by half' );
960
961     $checkout = Koha::Checkouts->find( $checkout->id );
962     ok( $checkout, 'Item still checked out to patron' );
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, 0, 'Account line was paid down by half' );
973
974     $checkout = Koha::Checkouts->find( $checkout->id );
975     ok( !$checkout, 'Item was removed from patron account' );
976
977     $schema->storage->txn_rollback;
978 };
979
980 subtest 'pay() renews items when appropriate' => sub {
981
982     plan tests => 7;
983
984     $schema->storage->txn_begin;
985
986     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
987     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
988     my $account = $patron->account;
989
990     my $context = Test::MockModule->new('C4::Context');
991     $context->mock( 'userenv', { branch => $library->id } );
992
993     my $biblio = $builder->build_sample_biblio();
994     my $item =
995       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
996
997     my $now = dt_from_string();
998     my $seven_weeks = DateTime::Duration->new(weeks => 7);
999     my $five_weeks = DateTime::Duration->new(weeks => 5);
1000     my $seven_weeks_ago = $now - $seven_weeks;
1001     my $five_weeks_ago = $now - $five_weeks;
1002
1003     my $checkout = Koha::Checkout->new(
1004         {
1005             borrowernumber => $patron->id,
1006             itemnumber     => $item->id,
1007             date_due       => $five_weeks_ago,
1008             branchcode     => $patron->branchcode,
1009             issuedate      => $seven_weeks_ago
1010         }
1011     )->store();
1012
1013     my $accountline = Koha::Account::Line->new(
1014         {
1015             issue_id       => $checkout->id,
1016             borrowernumber => $patron->id,
1017             itemnumber     => $item->id,
1018             date           => \'NOW()',
1019             debit_type_code => 'OVERDUE',
1020             status         => 'UNRETURNED',
1021             interface      => 'cli',
1022             amount => '1',
1023             amountoutstanding => '1',
1024         }
1025     )->store();
1026
1027     # Enable renewing upon fine payment
1028     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
1029     my $called = 0;
1030     my $module = Test::MockModule->new('C4::Circulation');
1031     $module->mock('AddRenewal', sub { $called = 1; });
1032     $module->mock('CanBookBeRenewed', sub { return 1; });
1033     my $result = $account->pay(
1034         {
1035             amount     => '1',
1036             library_id => $library->id,
1037         }
1038     );
1039
1040     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
1041     is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" );
1042     is( scalar @{$result->{renew_result}}, 1, "renew_result contains one renewal result" );
1043     is( $result->{renew_result}->[0]->{itemnumber}, $item->id, "renew_result contains itemnumber of renewed item" );
1044
1045     # Reset test by adding a new overdue
1046     Koha::Account::Line->new(
1047         {
1048             issue_id       => $checkout->id,
1049             borrowernumber => $patron->id,
1050             itemnumber     => $item->id,
1051             date           => \'NOW()',
1052             debit_type_code => 'OVERDUE',
1053             status         => 'UNRETURNED',
1054             interface      => 'cli',
1055             amount => '1',
1056             amountoutstanding => '1',
1057         }
1058     )->store();
1059     $called = 0;
1060
1061     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
1062     $result = $account->pay(
1063         {
1064             amount     => '1',
1065             library_id => $library->id,
1066         }
1067     );
1068
1069     is( $called, 0, 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid disabled' );
1070     is(ref($result->{renew_result}), 'ARRAY', "Pay result contains 'renew_result' ARRAY" );
1071     is( scalar @{$result->{renew_result}}, 0, "renew_result contains no renewal results" );
1072
1073     $schema->storage->txn_rollback;
1074 };
1075
1076 subtest 'Koha::Account::Line::apply() handles lost items' => sub {
1077
1078     plan tests => 4;
1079
1080     $schema->storage->txn_begin;
1081
1082     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1083     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1084     my $account = $patron->account;
1085
1086     my $context = Test::MockModule->new('C4::Context');
1087     $context->mock( 'userenv', { branch => $library->id } );
1088
1089     my $biblio = $builder->build_sample_biblio();
1090     my $item =
1091       $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
1092
1093     my $checkout = Koha::Checkout->new(
1094         {
1095             borrowernumber => $patron->id,
1096             itemnumber     => $item->id,
1097             date_due       => \'NOW()',
1098             branchcode     => $patron->branchcode,
1099             issuedate      => \'NOW()',
1100         }
1101     )->store();
1102
1103     $item->itemlost('1')->store();
1104
1105     my $debit = Koha::Account::Line->new(
1106         {
1107             issue_id          => $checkout->id,
1108             borrowernumber    => $patron->id,
1109             itemnumber        => $item->id,
1110             date              => \'NOW()',
1111             debit_type_code       => 'LOST',
1112             interface         => 'cli',
1113             amount            => '1',
1114             amountoutstanding => '1',
1115         }
1116     )->store();
1117
1118     my $credit = Koha::Account::Line->new(
1119         {
1120             borrowernumber    => $patron->id,
1121             date              => '1970-01-01 00:00:01',
1122             amount            => -.5,
1123             amountoutstanding => -.5,
1124             interface         => 'commandline',
1125             credit_type_code  => 'PAYMENT'
1126         }
1127     )->store();
1128     my $debits = $account->outstanding_debits;
1129     $credit->apply({ debits => [ $debits->as_list ] });
1130
1131     $debit = Koha::Account::Lines->find( $debit->id );
1132     is( $debit->amountoutstanding+0, .5, 'Account line was paid down by half' );
1133
1134     $checkout = Koha::Checkouts->find( $checkout->id );
1135     ok( $checkout, 'Item still checked out to patron' );
1136
1137     $credit = Koha::Account::Line->new(
1138         {
1139             borrowernumber    => $patron->id,
1140             date              => '1970-01-01 00:00:01',
1141             amount            => -.5,
1142             amountoutstanding => -.5,
1143             interface         => 'commandline',
1144             credit_type_code  => 'PAYMENT'
1145         }
1146     )->store();
1147     $debits = $account->outstanding_debits;
1148     $credit->apply({ debits => [ $debits->as_list ] });
1149
1150     $debit = Koha::Account::Lines->find( $debit->id );
1151     is( $debit->amountoutstanding+0, 0, 'Account line was paid down by half' );
1152
1153     $checkout = Koha::Checkouts->find( $checkout->id );
1154     ok( !$checkout, 'Item was removed from patron account' );
1155
1156     $schema->storage->txn_rollback;
1157 };
1158
1159 subtest 'Koha::Account::pay() generates credit number (Koha::Account::Line->store)' => sub {
1160     plan tests => 38;
1161
1162     $schema->storage->txn_begin;
1163
1164     Koha::Account::Lines->delete();
1165
1166     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
1167     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1168     my $account = $patron->account;
1169
1170     #t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
1171     my $context = Test::MockModule->new('C4::Context');
1172     $context->mock( 'userenv', { branch => $library->id } );
1173
1174     my $now = dt_from_string;
1175     my $year = $now->year;
1176     my $month = $now->month;
1177     my ($accountlines_id, $accountline);
1178
1179     my $credit_type = Koha::Account::CreditTypes->find('PAYMENT');
1180     $credit_type->credit_number_enabled(1);
1181     $credit_type->store();
1182
1183     t::lib::Mocks::mock_preference('AutoCreditNumber', '');
1184     $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1185     $accountline = Koha::Account::Lines->find($accountlines_id);
1186     is($accountline->credit_number, undef, 'No credit number is generated when syspref is off');
1187
1188     t::lib::Mocks::mock_preference('AutoCreditNumber', 'incremental');
1189     for my $i (1..11) {
1190         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1191         $accountline = Koha::Account::Lines->find($accountlines_id);
1192         is($accountline->credit_number, $i, "Incremental format credit number added for payments: $i");
1193     }
1194     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1195     $accountline = Koha::Account::Lines->find($accountlines_id);
1196     is($accountline->credit_number, undef, "Incremental credit number not added for writeoff");
1197
1198     t::lib::Mocks::mock_preference('AutoCreditNumber', 'annual');
1199     for my $i (1..11) {
1200         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1201         $accountline = Koha::Account::Lines->find($accountlines_id);
1202         is($accountline->credit_number, sprintf('%s-%04d', $year, $i), "Annual format credit number added for payments: " . sprintf('%s-%04d', $year, $i));
1203     }
1204     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1205     $accountline = Koha::Account::Lines->find($accountlines_id);
1206     is($accountline->credit_number, undef, "Annual format credit number not aded for writeoff");
1207
1208     t::lib::Mocks::mock_preference('AutoCreditNumber', 'branchyyyymmincr');
1209     for my $i (1..11) {
1210         $accountlines_id = $account->pay({ amount => '1.00', library_id => $library->id })->{payment_id};
1211         $accountline = Koha::Account::Lines->find($accountlines_id);
1212         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));
1213     }
1214     $accountlines_id = $account->pay({ type => 'WRITEOFF', amount => '1.00', library_id => $library->id })->{payment_id};
1215     $accountline = Koha::Account::Lines->find($accountlines_id);
1216     is($accountline->credit_number, undef, "branchyyyymmincr format credit number not added for writeoff");
1217
1218     throws_ok {
1219         Koha::Account::Line->new(
1220             {
1221                 interface        => 'test',
1222                 amount           => -1,
1223                 credit_type_code => $credit_type->code,
1224                 credit_number    => 42
1225             }
1226         )->store;
1227     }
1228     'Koha::Exceptions::Account',
1229 "Exception thrown when AutoCreditNumber is enabled but credit_number is already defined";
1230
1231     $schema->storage->txn_rollback;
1232 };
1233
1234 subtest 'Koha::Account::payout_amount() tests' => sub {
1235     plan tests => 39;
1236
1237     $schema->storage->txn_begin;
1238
1239     # delete logs and statistics
1240     my $action_logs = $schema->resultset('ActionLog')->search()->count;
1241     my $statistics  = $schema->resultset('Statistic')->search()->count;
1242
1243     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
1244     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1245     my $register =
1246       $builder->build_object( { class => 'Koha::Cash::Registers' } );
1247     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1248     my $account =
1249       Koha::Account->new( { patron_id => $patron->borrowernumber } );
1250
1251     is( $account->balance, 0, 'Test patron has no balance' );
1252
1253     my $payout_params = {
1254         payout_type => 'CASH',
1255         branch      => $library->id,
1256         register_id => $register->id,
1257         staff_id    => $staff->id,
1258         interface   => 'intranet',
1259         amount      => -10,
1260     };
1261
1262     my @required_fields =
1263       ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' );
1264     for my $required_field (@required_fields) {
1265         my $this_payout = { %{$payout_params} };
1266         delete $this_payout->{$required_field};
1267
1268         throws_ok {
1269             $account->payout_amount($this_payout);
1270         }
1271         'Koha::Exceptions::MissingParameter',
1272           "Exception thrown if $required_field parameter missing";
1273     }
1274
1275     throws_ok {
1276         $account->payout_amount($payout_params);
1277     }
1278     'Koha::Exceptions::Account::AmountNotPositive',
1279       'Expected validation exception thrown (amount not positive)';
1280
1281     $payout_params->{amount} = 10;
1282     throws_ok {
1283         $account->payout_amount($payout_params);
1284     }
1285     'Koha::Exceptions::ParameterTooHigh',
1286       'Expected validation exception thrown (amount greater than outstanding)';
1287
1288     # Enable cash registers
1289     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
1290     throws_ok {
1291         $account->payout_amount($payout_params);
1292     }
1293     'Koha::Exceptions::Account::RegisterRequired',
1294 'Exception thrown for UseCashRegisters:1 + payout_type:CASH + cash_register:undef';
1295
1296     # Disable cash registers
1297     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
1298
1299     # Add some outstanding credits
1300     my $credit_1 = $account->add_credit( { amount => 2,  interface => 'commandline' } );
1301     my $credit_2 = $account->add_credit( { amount => 3,  interface => 'commandline' } );
1302     my $credit_3 = $account->add_credit( { amount => 5,  interface => 'commandline' } );
1303     my $credit_4 = $account->add_credit( { amount => 10, interface => 'commandline' } );
1304     my $credits = $account->outstanding_credits();
1305     is( $credits->count, 4, "Found 4 credits with outstanding amounts" );
1306     is( $credits->total_outstanding + 0, -20, "Total -20 outstanding credit" );
1307
1308     my $payout = $account->payout_amount($payout_params);
1309     is(ref($payout), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payout');
1310     is($payout->amount + 0, 10, "Payout amount recorded correctly");
1311     is($payout->amountoutstanding + 0, 0, "Full amount was paid out");
1312     $credits = $account->outstanding_credits();
1313     is($credits->count, 1, "Payout was applied against oldest outstanding credits first");
1314     is($credits->total_outstanding + 0, -10, "Total of 10 outstanding credit remaining");
1315
1316     my $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } );
1317     is( $offsets->count, 4, 'Four offsets generated' );
1318     my $offset = $offsets->next;
1319     is( $offset->type, 'CREATE', 'CREATE offset added for payout line' );
1320     is( $offset->amount * 1, 10, 'Correct offset amount recorded' );
1321     $offset = $offsets->next;
1322     is( $offset->credit_id, $credit_1->id, "Offset added against credit_1");
1323     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1324     is( $offset->amount * 1, -2,      'Correct amount offset against credit_1' );
1325     $offset = $offsets->next;
1326     is( $offset->credit_id, $credit_2->id, "Offset added against credit_2");
1327     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1328     is( $offset->amount * 1, -3,      'Correct amount offset against credit_2' );
1329     $offset = $offsets->next;
1330     is( $offset->credit_id, $credit_3->id, "Offset added against credit_3");
1331     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1332     is( $offset->amount * 1, -5,      'Correct amount offset against credit_3' );
1333
1334     my $credit_5 = $account->add_credit( { amount => 5, interface => 'commandline' } );
1335     $credits = $account->outstanding_credits();
1336     is($credits->count, 2, "New credit added");
1337     $payout_params->{amount} = 2.50;
1338     $payout_params->{credits} = [$credit_5];
1339     $payout = $account->payout_amount($payout_params);
1340
1341     $credits = $account->outstanding_credits();
1342     is($credits->count, 2, "Second credit not fully paid off");
1343     is($credits->total_outstanding + 0, -12.50, "12.50 outstanding credit remaining");
1344     $credit_4->discard_changes;
1345     $credit_5->discard_changes;
1346     is($credit_4->amountoutstanding + 0, -10, "Credit 4 unaffected when credit_5 was passed to payout_amount");
1347     is($credit_5->amountoutstanding + 0, -2.50, "Credit 5 correctly reduced when payout_amount called with credit_5 passed");
1348
1349     $offsets = Koha::Account::Offsets->search( { debit_id => $payout->id } );
1350     is( $offsets->count, 2, 'Two offsets generated' );
1351     $offset = $offsets->next;
1352     is( $offset->type, 'CREATE', 'CREATE offset added for payout line' );
1353     is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' );
1354     $offset = $offsets->next;
1355     is( $offset->credit_id, $credit_5->id, "Offset added against credit_5");
1356     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1357     is( $offset->amount * 1, -2.50,      'Correct amount offset against credit_5' );
1358
1359     $schema->storage->txn_rollback;
1360 };
1361
1362 subtest 'Koha::Account::payin_amount() tests' => sub {
1363     plan tests => 36;
1364
1365     $schema->storage->txn_begin;
1366
1367     # delete logs and statistics
1368     my $action_logs = $schema->resultset('ActionLog')->search()->count;
1369     my $statistics  = $schema->resultset('Statistic')->search()->count;
1370
1371     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
1372     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
1373     my $register =
1374       $builder->build_object( { class => 'Koha::Cash::Registers' } );
1375     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
1376     my $account =
1377       Koha::Account->new( { patron_id => $patron->borrowernumber } );
1378
1379     is( $account->balance, 0, 'Test patron has no balance' );
1380
1381     my $payin_params = {
1382         type  => 'PAYMENT',
1383         payment_type => 'CASH',
1384         branch       => $library->id,
1385         register_id  => $register->id,
1386         staff_id     => $staff->id,
1387         interface    => 'intranet',
1388         amount       => -10,
1389     };
1390
1391     my @required_fields =
1392       ( 'interface', 'amount', 'type' );
1393     for my $required_field (@required_fields) {
1394         my $this_payin = { %{$payin_params} };
1395         delete $this_payin->{$required_field};
1396
1397         throws_ok {
1398             $account->payin_amount($this_payin);
1399         }
1400         'Koha::Exceptions::MissingParameter',
1401           "Exception thrown if $required_field parameter missing";
1402     }
1403
1404     throws_ok {
1405         $account->payin_amount($payin_params);
1406     }
1407     'Koha::Exceptions::Account::AmountNotPositive',
1408       'Expected validation exception thrown (amount not positive)';
1409
1410     $payin_params->{amount} = 10;
1411
1412     # Enable cash registers
1413     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
1414     throws_ok {
1415         $account->payin_amount($payin_params);
1416     }
1417     'Koha::Exceptions::Account::RegisterRequired',
1418 'Exception thrown for UseCashRegisters:1 + payment_type:CASH + cash_register:undef';
1419
1420     # Disable cash registers
1421     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
1422
1423     # Enable AccountAutoReconcile
1424     t::lib::Mocks::mock_preference( 'AccountAutoReconcile', 1 );
1425
1426     # Add some outstanding debits
1427     my $debit_1 = $account->add_debit( { amount => 2,  interface => 'commandline', type => 'OVERDUE' } );
1428     my $debit_2 = $account->add_debit( { amount => 3,  interface => 'commandline', type => 'OVERDUE' } );
1429     my $debit_3 = $account->add_debit( { amount => 5,  interface => 'commandline', type => 'OVERDUE' } );
1430     my $debit_4 = $account->add_debit( { amount => 10, interface => 'commandline', type => 'OVERDUE' } );
1431     my $debits = $account->outstanding_debits();
1432     is( $debits->count, 4, "Found 4 debits with outstanding amounts" );
1433     is( $debits->total_outstanding + 0, 20, "Total 20 outstanding debit" );
1434
1435     my $payin = $account->payin_amount($payin_params);
1436     is(ref($payin), 'Koha::Account::Line', 'Return the Koha::Account::Line object for the payin');
1437     is($payin->amount + 0, -10, "Payin amount recorded correctly");
1438     is($payin->amountoutstanding + 0, 0, "Full amount was used to pay debts");
1439     $debits = $account->outstanding_debits();
1440     is($debits->count, 1, "Payin was applied against oldest outstanding debits first");
1441     is($debits->total_outstanding + 0, 10, "Total of 10 outstanding debit remaining");
1442
1443     my $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } );
1444     is( $offsets->count, 4, 'Four offsets generated' );
1445     my $offset = $offsets->next;
1446     is( $offset->type, 'CREATE', 'CREATE offset added for payin line' );
1447     is( $offset->amount * 1, 10, 'Correct offset amount recorded' );
1448     $offset = $offsets->next;
1449     is( $offset->debit_id, $debit_1->id, "Offset added against debit_1");
1450     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1451     is( $offset->amount * 1, -2,      'Correct amount offset against debit_1' );
1452     $offset = $offsets->next;
1453     is( $offset->debit_id, $debit_2->id, "Offset added against debit_2");
1454     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1455     is( $offset->amount * 1, -3,      'Correct amount offset against debit_2' );
1456     $offset = $offsets->next;
1457     is( $offset->debit_id, $debit_3->id, "Offset added against debit_3");
1458     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1459     is( $offset->amount * 1, -5,      'Correct amount offset against debit_3' );
1460
1461     my $debit_5 = $account->add_debit( { amount => 5, interface => 'commandline', type => 'OVERDUE' } );
1462     $debits = $account->outstanding_debits();
1463     is($debits->count, 2, "New debit added");
1464     $payin_params->{amount} = 2.50;
1465     $payin_params->{debits} = [$debit_5];
1466     $payin = $account->payin_amount($payin_params);
1467
1468     $debits = $account->outstanding_debits();
1469     is($debits->count, 2, "Second debit not fully paid off");
1470     is($debits->total_outstanding + 0, 12.50, "12.50 outstanding debit remaining");
1471     $debit_4->discard_changes;
1472     $debit_5->discard_changes;
1473     is($debit_4->amountoutstanding + 0, 10, "Debit 4 unaffected when debit_5 was passed to payin_amount");
1474     is($debit_5->amountoutstanding + 0, 2.50, "Debit 5 correctly reduced when payin_amount called with debit_5 passed");
1475
1476     $offsets = Koha::Account::Offsets->search( { credit_id => $payin->id } );
1477     is( $offsets->count, 2, 'Two offsets generated' );
1478     $offset = $offsets->next;
1479     is( $offset->type, 'CREATE', 'CREATE offset added for payin line' );
1480     is( $offset->amount * 1, 2.50, 'Correct offset amount recorded' );
1481     $offset = $offsets->next;
1482     is( $offset->debit_id, $debit_5->id, "Offset added against debit_5");
1483     is( $offset->type,       'APPLY', "APPLY used for offset_type" );
1484     is( $offset->amount * 1, -2.50,      'Correct amount offset against debit_5' );
1485
1486     $schema->storage->txn_rollback;
1487 };