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