99d0d738933bc8fe4f2a3de2f93a5db5d1c23ac1
[koha.git] / t / db_dependent / Koha / Account / Line.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 => 11;
23 use Test::Exception;
24 use Test::MockModule;
25
26 use DateTime;
27
28 use C4::Circulation qw/AddIssue AddReturn/;
29 use Koha::Account;
30 use Koha::Account::Lines;
31 use Koha::Account::Offsets;
32 use Koha::Items;
33 use Koha::DateUtils qw( dt_from_string );
34
35 use t::lib::Mocks;
36 use t::lib::TestBuilder;
37
38 my $schema = Koha::Database->new->schema;
39 my $builder = t::lib::TestBuilder->new;
40
41 subtest 'patron() tests' => sub {
42
43     plan tests => 3;
44
45     $schema->storage->txn_begin;
46
47     my $library = $builder->build( { source => 'Branch' } );
48     my $patron = $builder->build( { source => 'Borrower' } );
49
50     my $line = Koha::Account::Line->new(
51     {
52         borrowernumber => $patron->{borrowernumber},
53         debit_type_code    => "OVERDUE",
54         status         => "RETURNED",
55         amount         => 10,
56         interface      => 'commandline',
57     })->store;
58
59     my $account_line_patron = $line->patron;
60     is( ref( $account_line_patron ), 'Koha::Patron', 'Koha::Account::Line->patron should return a Koha::Patron' );
61     is( $line->borrowernumber, $account_line_patron->borrowernumber, 'Koha::Account::Line->patron should return the correct borrower' );
62
63     $line->borrowernumber(undef)->store;
64     is( $line->patron, undef, 'Koha::Account::Line->patron should return undef if no patron linked' );
65
66     $schema->storage->txn_rollback;
67 };
68
69 subtest 'item() tests' => sub {
70
71     plan tests => 3;
72
73     $schema->storage->txn_begin;
74
75     my $library = $builder->build( { source => 'Branch' } );
76     my $biblioitem = $builder->build( { source => 'Biblioitem' } );
77     my $patron = $builder->build( { source => 'Borrower' } );
78     my $item = Koha::Item->new(
79     {
80         biblionumber     => $biblioitem->{biblionumber},
81         biblioitemnumber => $biblioitem->{biblioitemnumber},
82         homebranch       => $library->{branchcode},
83         holdingbranch    => $library->{branchcode},
84         barcode          => 'some_barcode_12',
85         itype            => 'BK',
86     })->store;
87
88     my $line = Koha::Account::Line->new(
89     {
90         borrowernumber => $patron->{borrowernumber},
91         itemnumber     => $item->itemnumber,
92         debit_type_code    => "OVERDUE",
93         status         => "RETURNED",
94         amount         => 10,
95         interface      => 'commandline',
96     })->store;
97
98     my $account_line_item = $line->item;
99     is( ref( $account_line_item ), 'Koha::Item', 'Koha::Account::Line->item should return a Koha::Item' );
100     is( $line->itemnumber, $account_line_item->itemnumber, 'Koha::Account::Line->item should return the correct item' );
101
102     $line->itemnumber(undef)->store;
103     is( $line->item, undef, 'Koha::Account::Line->item should return undef if no item linked' );
104
105     $schema->storage->txn_rollback;
106 };
107
108 subtest 'is_credit() and is_debit() tests' => sub {
109
110     plan tests => 4;
111
112     $schema->storage->txn_begin;
113
114     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
115     my $account = $patron->account;
116
117     my $credit = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' });
118
119     ok( $credit->is_credit, 'is_credit detects credits' );
120     ok( !$credit->is_debit, 'is_debit detects credits' );
121
122     my $debit = Koha::Account::Line->new(
123     {
124         borrowernumber => $patron->id,
125         debit_type_code    => "OVERDUE",
126         status         => "RETURNED",
127         amount         => 10,
128         interface      => 'commandline',
129     })->store;
130
131     ok( !$debit->is_credit, 'is_credit detects debits' );
132     ok( $debit->is_debit, 'is_debit detects debits');
133
134     $schema->storage->txn_rollback;
135 };
136
137 subtest 'apply() tests' => sub {
138
139     plan tests => 25;
140
141     $schema->storage->txn_begin;
142
143     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
144     my $account = $patron->account;
145
146     my $credit = $account->add_credit( { amount => 100, user_id => $patron->id, interface => 'commandline' } );
147
148     my $debit_1 = Koha::Account::Line->new(
149         {   borrowernumber    => $patron->id,
150             debit_type_code       => "OVERDUE",
151             status            => "RETURNED",
152             amount            => 10,
153             amountoutstanding => 10,
154             interface         => 'commandline',
155         }
156     )->store;
157
158     my $debit_2 = Koha::Account::Line->new(
159         {   borrowernumber    => $patron->id,
160             debit_type_code       => "OVERDUE",
161             status            => "RETURNED",
162             amount            => 100,
163             amountoutstanding => 100,
164             interface         => 'commandline',
165         }
166     )->store;
167
168     $credit->discard_changes;
169     $debit_1->discard_changes;
170
171     my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id });
172     my $remaining_credit = $credit->apply( { debits => [ $debits->as_list ], offset_type => 'Manual Credit' } );
173     is( $remaining_credit * 1, 90, 'Remaining credit is correctly calculated' );
174     $credit->discard_changes;
175     is( $credit->amountoutstanding * -1, $remaining_credit, 'Remaining credit correctly stored' );
176
177     # re-read debit info
178     $debit_1->discard_changes;
179     is( $debit_1->amountoutstanding * 1, 0, 'Debit has been cancelled' );
180
181     my $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_1->id } );
182     is( $offsets->count, 1, 'Only one offset is generated' );
183     my $THE_offset = $offsets->next;
184     is( $THE_offset->amount * 1, -10, 'Amount was calculated correctly (less than the available credit)' );
185     is( $THE_offset->type, 'Manual Credit', 'Passed type stored correctly' );
186
187     $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id });
188     $remaining_credit = $credit->apply( { debits => [ $debits->as_list ] } );
189     is( $remaining_credit, 0, 'No remaining credit left' );
190     $credit->discard_changes;
191     is( $credit->amountoutstanding * 1, 0, 'No outstanding credit' );
192     $debit_2->discard_changes;
193     is( $debit_2->amountoutstanding * 1, 10, 'Outstanding amount decremented correctly' );
194
195     $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_2->id } );
196     is( $offsets->count, 1, 'Only one offset is generated' );
197     $THE_offset = $offsets->next;
198     is( $THE_offset->amount * 1, -90, 'Amount was calculated correctly (less than the available credit)' );
199     is( $THE_offset->type, 'Credit Applied', 'Defaults to \'Credit Applied\' offset type' );
200
201     $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id });
202     throws_ok
203         { $credit->apply({ debits => [ $debits->as_list ] }); }
204         'Koha::Exceptions::Account::NoAvailableCredit',
205         '->apply() can only be used with outstanding credits';
206
207     $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id });
208     throws_ok
209         { $debit_1->apply({ debits => [ $debits->as_list ] }); }
210         'Koha::Exceptions::Account::IsNotCredit',
211         '->apply() can only be used with credits';
212
213     $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id });
214     my $credit_3 = $account->add_credit({ amount => 1, interface => 'commandline' });
215     throws_ok
216         { $credit_3->apply({ debits => [ $debits->as_list ] }); }
217         'Koha::Exceptions::Account::IsNotDebit',
218         '->apply() can only be applied to credits';
219
220     my $credit_2 = $account->add_credit({ amount => 20, interface => 'commandline' });
221     my $debit_3  = Koha::Account::Line->new(
222         {   borrowernumber    => $patron->id,
223             debit_type_code       => "OVERDUE",
224             status            => "RETURNED",
225             amount            => 100,
226             amountoutstanding => 100,
227             interface         => 'commandline',
228         }
229     )->store;
230
231     $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id, $credit->id ] } });
232     throws_ok {
233         $credit_2->apply( { debits => [ $debits->as_list ], offset_type => 'Manual Credit' } ); }
234         'Koha::Exceptions::Account::IsNotDebit',
235         '->apply() rolls back if any of the passed lines is not a debit';
236
237     is( $debit_1->discard_changes->amountoutstanding * 1,   0, 'No changes to already cancelled debit' );
238     is( $debit_2->discard_changes->amountoutstanding * 1,  10, 'Debit cancelled' );
239     is( $debit_3->discard_changes->amountoutstanding * 1, 100, 'Outstanding amount correctly calculated' );
240     is( $credit_2->discard_changes->amountoutstanding * -1, 20, 'No changes made' );
241
242     $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id ] } });
243     $remaining_credit = $credit_2->apply( { debits => [ $debits->as_list ], offset_type => 'Manual Credit' } );
244
245     is( $debit_1->discard_changes->amountoutstanding * 1,  0, 'No changes to already cancelled debit' );
246     is( $debit_2->discard_changes->amountoutstanding * 1,  0, 'Debit cancelled' );
247     is( $debit_3->discard_changes->amountoutstanding * 1, 90, 'Outstanding amount correctly calculated' );
248     is( $credit_2->discard_changes->amountoutstanding * 1, 0, 'No remaining credit' );
249
250     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
251     my $biblio = $builder->build_sample_biblio();
252     my $item =
253         $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
254     my $now = dt_from_string();
255     my $seven_weeks = DateTime::Duration->new(weeks => 7);
256     my $five_weeks = DateTime::Duration->new(weeks => 5);
257     my $seven_weeks_ago = $now - $seven_weeks;
258     my $five_weeks_ago = $now - $five_weeks;
259
260     my $checkout = Koha::Checkout->new(
261         {
262             borrowernumber => $patron->id,
263             itemnumber     => $item->id,
264             date_due       => $five_weeks_ago,
265             branchcode     => $library->id,
266             issuedate      => $seven_weeks_ago
267         }
268     )->store();
269
270     my $accountline = Koha::Account::Line->new(
271         {
272             issue_id       => $checkout->id,
273             borrowernumber => $patron->id,
274             itemnumber     => $item->id,
275             branchcode     => $library->id,
276             date           => \'NOW()',
277             accounttype    => 'OVERDUE',
278             status         => 'UNRETURNED',
279             interface      => 'cli',
280             amount => '1',
281             amountoutstanding => '1',
282         }
283     )->store();
284
285     # Enable renewing upon fine payment
286     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
287     my $called = 0;
288     my $module = new Test::MockModule('C4::Circulation');
289     $module->mock('AddRenewal', sub { $called = 1; });
290     my $credit_renew = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' });
291     my $debits_renew = Koha::Account::Lines->search({ accountlines_id => $accountline->id });
292     $credit_renew->apply( { debits => $debits_renew, offset_type => 'Manual Credit' } );
293
294     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
295
296     $schema->storage->txn_rollback;
297 };
298
299 subtest 'Keep account info when related patron, staff, item or cash_register is deleted' => sub {
300
301     plan tests => 4;
302
303     $schema->storage->txn_begin;
304
305     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
306     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
307     my $item = $builder->build_object({ class => 'Koha::Items' });
308     my $issue = $builder->build_object(
309         {
310             class => 'Koha::Checkouts',
311             value => { itemnumber => $item->itemnumber }
312         }
313     );
314     my $register = $builder->build_object({ class => 'Koha::Cash::Registers' });
315
316     my $line = Koha::Account::Line->new(
317     {
318         borrowernumber => $patron->borrowernumber,
319         manager_id     => $staff->borrowernumber,
320         itemnumber     => $item->itemnumber,
321         debit_type_code    => "OVERDUE",
322         status         => "RETURNED",
323         amount         => 10,
324         interface      => 'commandline',
325         register_id    => $register->id
326     })->store;
327
328     $issue->delete;
329     $item->delete;
330     $line = $line->get_from_storage;
331     is( $line->itemnumber, undef, "The account line should not be deleted when the related item is delete");
332
333     $staff->delete;
334     $line = $line->get_from_storage;
335     is( $line->manager_id, undef, "The account line should not be deleted when the related staff is delete");
336
337     $patron->delete;
338     $line = $line->get_from_storage;
339     is( $line->borro1wernumber, undef, "The account line should not be deleted when the related patron is delete");
340
341     $register->delete;
342     $line = $line->get_from_storage;
343     is( $line->register_id, undef, "The account line should not be deleted when the related cash register is delete");
344
345     $schema->storage->txn_rollback;
346 };
347
348 subtest 'adjust() tests' => sub {
349
350     plan tests => 29;
351
352     $schema->storage->txn_begin;
353
354     # count logs before any actions
355     my $action_logs = $schema->resultset('ActionLog')->search()->count;
356
357     # Disable logs
358     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
359
360     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
361     my $account = $patron->account;
362
363     my $debit_1 = Koha::Account::Line->new(
364         {   borrowernumber    => $patron->id,
365             debit_type_code       => "OVERDUE",
366             status            => "RETURNED",
367             amount            => 10,
368             amountoutstanding => 10,
369             interface         => 'commandline',
370         }
371     )->store;
372
373     my $debit_2 = Koha::Account::Line->new(
374         {   borrowernumber    => $patron->id,
375             debit_type_code       => "OVERDUE",
376             status            => "UNRETURNED",
377             amount            => 100,
378             amountoutstanding => 100,
379             interface         => 'commandline'
380         }
381     )->store;
382
383     my $credit = $account->add_credit( { amount => 40, user_id => $patron->id, interface => 'commandline' } );
384
385     throws_ok { $debit_1->adjust( { amount => 50, type => 'bad', interface => 'commandline' } ) }
386     qr/Update type not recognised/, 'Exception thrown for unrecognised type';
387
388     throws_ok { $debit_1->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } ) }
389     qr/Update type not allowed on this debit_type/,
390       'Exception thrown for type conflict';
391
392     # Increment an unpaid fine
393     $debit_2->adjust( { amount => 150, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
394
395     is( $debit_2->amount * 1, 150, 'Fine amount was updated in full' );
396     is( $debit_2->amountoutstanding * 1, 150, 'Fine amountoutstanding was update in full' );
397     isnt( $debit_2->date, undef, 'Date has been set' );
398
399     my $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
400     is( $offsets->count, 1, 'An offset is generated for the increment' );
401     my $THIS_offset = $offsets->next;
402     is( $THIS_offset->amount * 1, 50, 'Amount was calculated correctly (increment by 50)' );
403     is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' );
404
405     is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' );
406
407     # Update fine to partially paid
408     my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id });
409     $credit->apply( { debits => [ $debits->as_list ], offset_type => 'Manual Credit' } );
410
411     $debit_2->discard_changes;
412     is( $debit_2->amount * 1, 150, 'Fine amount unaffected by partial payment' );
413     is( $debit_2->amountoutstanding * 1, 110, 'Fine amountoutstanding updated by partial payment' );
414
415     # Enable logs
416     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
417
418     # Increment the partially paid fine
419     $debit_2->adjust( { amount => 160, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
420
421     is( $debit_2->amount * 1, 160, 'Fine amount was updated in full' );
422     is( $debit_2->amountoutstanding * 1, 120, 'Fine amountoutstanding was updated by difference' );
423
424     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
425     is( $offsets->count, 3, 'An offset is generated for the increment' );
426     $THIS_offset = $offsets->last;
427     is( $THIS_offset->amount * 1, 10, 'Amount was calculated correctly (increment by 10)' );
428     is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' );
429
430     is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' );
431
432     # Decrement the partially paid fine, less than what was paid
433     $debit_2->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
434
435     is( $debit_2->amount * 1, 50, 'Fine amount was updated in full' );
436     is( $debit_2->amountoutstanding * 1, 10, 'Fine amountoutstanding was updated by difference' );
437
438     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
439     is( $offsets->count, 4, 'An offset is generated for the decrement' );
440     $THIS_offset = $offsets->last;
441     is( $THIS_offset->amount * 1, -110, 'Amount was calculated correctly (decrement by 110)' );
442     is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' );
443
444     # Decrement the partially paid fine, more than what was paid
445     $debit_2->adjust( { amount => 30, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
446     is( $debit_2->amount * 1, 30, 'Fine amount was updated in full' );
447     is( $debit_2->amountoutstanding * 1, 0, 'Fine amountoutstanding was zeroed (payment was 40)' );
448
449     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
450     is( $offsets->count, 5, 'An offset is generated for the decrement' );
451     $THIS_offset = $offsets->last;
452     is( $THIS_offset->amount * 1, -20, 'Amount was calculated correctly (decrement by 20)' );
453     is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' );
454
455     my $overpayment_refund = $account->lines->last;
456     is( $overpayment_refund->amount * 1, -10, 'A new credit has been added' );
457     is( $overpayment_refund->description, 'Overpayment refund', 'Credit generated with the expected description' );
458
459     $schema->storage->txn_rollback;
460 };
461
462 subtest 'checkout() tests' => sub {
463     plan tests => 6;
464
465     $schema->storage->txn_begin;
466
467     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
468     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
469     my $item = $builder->build_sample_item;
470     my $account = $patron->account;
471
472     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
473     my $checkout = AddIssue( $patron->unblessed, $item->barcode );
474
475     my $line = $account->add_debit({
476         amount    => 10,
477         interface => 'commandline',
478         item_id   => $item->itemnumber,
479         issue_id  => $checkout->issue_id,
480         type      => 'OVERDUE',
481     });
482
483     my $line_checkout = $line->checkout;
484     is( ref($line_checkout), 'Koha::Checkout', 'Result type is correct' );
485     is( $line_checkout->issue_id, $checkout->issue_id, 'Koha::Account::Line->checkout should return the correct checkout');
486
487     my ( $returned, undef, $old_checkout) = C4::Circulation::AddReturn( $item->barcode, $library->branchcode );
488     is( $returned, 1, 'The item should have been returned' );
489
490     $line = $line->get_from_storage;
491     my $old_line_checkout = $line->checkout;
492     is( ref($old_line_checkout), 'Koha::Old::Checkout', 'Result type is correct' );
493     is( $old_line_checkout->issue_id, $old_checkout->issue_id, 'Koha::Account::Line->checkout should return the correct old_checkout' );
494
495     $line->issue_id(undef)->store;
496     is( $line->checkout, undef, 'Koha::Account::Line->checkout should return undef if no checkout linked' );
497
498     $schema->storage->txn_rollback;
499 };
500
501 subtest 'credits() and debits() tests' => sub {
502     plan tests => 10;
503
504     $schema->storage->txn_begin;
505
506     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
507     my $account = $patron->account;
508
509     my $debit1 = $account->add_debit({
510         amount    => 8,
511         interface => 'commandline',
512         type      => 'ACCOUNT',
513     });
514     my $debit2 = $account->add_debit({
515         amount    => 12,
516         interface => 'commandline',
517         type      => 'ACCOUNT',
518     });
519     my $credit1 = $account->add_credit({
520         amount    => 5,
521         interface => 'commandline',
522         type      => 'CREDIT',
523     });
524     my $credit2 = $account->add_credit({
525         amount    => 10,
526         interface => 'commandline',
527         type      => 'CREDIT',
528     });
529
530     $credit1->apply({ debits => [ $debit1 ] });
531     $credit2->apply({ debits => [ $debit1, $debit2 ] });
532
533     my $credits = $debit1->credits;
534     is($credits->count, 2, '2 Credits applied to debit 1');
535     my $credit = $credits->next;
536     is($credit->amount + 0, -5, 'Correct first credit');
537     $credit = $credits->next;
538     is($credit->amount + 0, -10, 'Correct second credit');
539
540     $credits = $debit2->credits;
541     is($credits->count, 1, '1 Credits applied to debit 2');
542     $credit = $credits->next;
543     is($credit->amount + 0, -10, 'Correct first credit');
544
545     my $debits = $credit1->debits;
546     is($debits->count, 1, 'Credit 1 applied to 1 debit');
547     my $debit = $debits->next;
548     is($debit->amount + 0, 8, 'Correct first debit');
549
550     $debits = $credit2->debits;
551     is($debits->count, 2, 'Credit 2 applied to 2 debits');
552     $debit = $debits->next;
553     is($debit->amount + 0, 8, 'Correct first debit');
554     $debit = $debits->next;
555     is($debit->amount + 0, 12, 'Correct second debit');
556
557     $schema->storage->txn_rollback;
558 };
559
560 subtest "void() tests" => sub {
561
562     plan tests => 16;
563
564     $schema->storage->txn_begin;
565
566     # Create a borrower
567     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
568     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
569
570     my $borrower = Koha::Patron->new( {
571         cardnumber => 'dariahall',
572         surname => 'Hall',
573         firstname => 'Daria',
574     } );
575     $borrower->categorycode( $categorycode );
576     $borrower->branchcode( $branchcode );
577     $borrower->store;
578
579     my $account = Koha::Account->new({ patron_id => $borrower->id });
580
581     my $line1 = Koha::Account::Line->new(
582         {
583             borrowernumber    => $borrower->borrowernumber,
584             amount            => 10,
585             amountoutstanding => 10,
586             interface         => 'commandline',
587             debit_type_code   => 'OVERDUE'
588         }
589     )->store();
590     my $line2 = Koha::Account::Line->new(
591         {
592             borrowernumber    => $borrower->borrowernumber,
593             amount            => 20,
594             amountoutstanding => 20,
595             interface         => 'commandline',
596             debit_type_code   => 'OVERDUE'
597         }
598     )->store();
599
600     is( $account->balance(), 30, "Account balance is 30" );
601     is( $line1->amountoutstanding, 10, 'First fee has amount outstanding of 10' );
602     is( $line2->amountoutstanding, 20, 'Second fee has amount outstanding of 20' );
603
604     my $id = $account->pay(
605         {
606             lines  => [$line1, $line2],
607             amount => 30,
608         }
609     );
610
611     my $account_payment = Koha::Account::Lines->find( $id );
612
613     is( $account->balance(), 0, "Account balance is 0" );
614
615     $line1->_result->discard_changes();
616     $line2->_result->discard_changes();
617     is( $line1->amountoutstanding+0, 0, 'First fee has amount outstanding of 0' );
618     is( $line2->amountoutstanding+0, 0, 'Second fee has amount outstanding of 0' );
619
620     my $ret = $account_payment->void();
621
622     is( ref($ret), 'Koha::Account::Line', 'Void returns the account line' );
623     is( $account->balance(), 30, "Account balance is again 30" );
624
625     $account_payment->_result->discard_changes();
626     $line1->_result->discard_changes();
627     $line2->_result->discard_changes();
628
629     is( $account_payment->credit_type_code, 'PAYMENT', 'Voided payment credit_type_code is still PAYMENT' );
630     is( $account_payment->status, 'VOID', 'Voided payment status is VOID' );
631     is( $account_payment->amount+0, 0, 'Voided payment amount is 0' );
632     is( $account_payment->amountoutstanding+0, 0, 'Voided payment amount outstanding is 0' );
633
634     is( $line1->amountoutstanding+0, 10, 'First fee again has amount outstanding of 10' );
635     is( $line2->amountoutstanding+0, 20, 'Second fee again has amount outstanding of 20' );
636
637     # Accountlines that are not credits should be un-voidable
638     my $line1_pre = $line1->unblessed();
639     $ret = $line1->void();
640     $line1->_result->discard_changes();
641     my $line1_post = $line1->unblessed();
642     is( $ret, undef, 'Attempted void on non-credit returns undef' );
643     is_deeply( $line1_pre, $line1_post, 'Non-credit account line cannot be voided' );
644
645     $schema->storage->txn_rollback;
646 };
647
648 subtest "payout() tests" => sub {
649
650     plan tests => 18;
651
652     $schema->storage->txn_begin;
653
654     # Create a borrower
655     my $categorycode =
656       $builder->build( { source => 'Category' } )->{categorycode};
657     my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode};
658
659     my $borrower = Koha::Patron->new(
660         {
661             cardnumber => 'dariahall',
662             surname    => 'Hall',
663             firstname  => 'Daria',
664         }
665     );
666     $borrower->categorycode($categorycode);
667     $borrower->branchcode($branchcode);
668     $borrower->store;
669
670     my $staff = Koha::Patron->new(
671         {
672             cardnumber => 'bobby',
673             surname    => 'Bloggs',
674             firstname  => 'Bobby',
675         }
676     );
677     $staff->categorycode($categorycode);
678     $staff->branchcode($branchcode);
679     $staff->store;
680
681     my $account = Koha::Account->new( { patron_id => $borrower->id } );
682
683     my $debit1 = Koha::Account::Line->new(
684         {
685             borrowernumber    => $borrower->borrowernumber,
686             amount            => 10,
687             amountoutstanding => 10,
688             interface         => 'commandline',
689             debit_type_code   => 'OVERDUE'
690         }
691     )->store();
692     my $credit1 = Koha::Account::Line->new(
693         {
694             borrowernumber    => $borrower->borrowernumber,
695             amount            => -20,
696             amountoutstanding => -20,
697             interface         => 'commandline',
698             credit_type_code  => 'CREDIT'
699         }
700     )->store();
701
702     is( $account->balance(), -10, "Account balance is -10" );
703     is( $debit1->amountoutstanding + 0,
704         10, 'Overdue fee has an amount outstanding of 10' );
705     is( $credit1->amountoutstanding + 0,
706         -20, 'Credit has an amount outstanding of -20' );
707
708     my $pay_params = {
709         interface   => 'intranet',
710         staff_id    => $staff->borrowernumber,
711         branch      => $branchcode,
712         payout_type => 'CASH',
713         amount      => 20
714     };
715
716     throws_ok { $debit1->payout($pay_params); }
717     'Koha::Exceptions::Account::IsNotCredit',
718       '->payout() can only be used with credits';
719
720     my @required =
721       ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' );
722     for my $required (@required) {
723         my $params = {%$pay_params};
724         delete( $params->{$required} );
725         throws_ok {
726             $credit1->payout($params);
727         }
728         'Koha::Exceptions::MissingParameter',
729           "->payout() requires the `$required` parameter is passed";
730     }
731
732     throws_ok {
733         $credit1->payout(
734             {
735                 interface   => 'intranet',
736                 staff_id    => $staff->borrowernumber,
737                 branch      => $branchcode,
738                 payout_type => 'CASH',
739                 amount      => 25
740             }
741         );
742     }
743     'Koha::Exceptions::ParameterTooHigh',
744       '->payout() cannot pay out more than the amountoutstanding';
745
746     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
747     throws_ok {
748         $credit1->payout(
749             {
750                 interface   => 'intranet',
751                 staff_id    => $staff->borrowernumber,
752                 branch      => $branchcode,
753                 payout_type => 'CASH',
754                 amount      => 10
755             }
756         );
757     }
758     'Koha::Exceptions::Account::RegisterRequired',
759       '->payout() requires a cash_register if payout_type is `CASH`';
760
761     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
762     my $payout = $credit1->payout(
763         {
764             interface   => 'intranet',
765             staff_id    => $staff->borrowernumber,
766             branch      => $branchcode,
767             payout_type => 'CASH',
768             amount      => 10
769         }
770     );
771
772     is( ref($payout), 'Koha::Account::Line',
773         '->payout() returns a Koha::Account::Line' );
774     is( $payout->amount() + 0,            10, "Payout amount is 10" );
775     is( $payout->amountoutstanding() + 0, 0,  "Payout amountoutstanding is 0" );
776     is( $account->balance() + 0,          0,  "Account balance is 0" );
777     is( $debit1->amountoutstanding + 0,
778         10, 'Overdue fee still has an amount outstanding of 10' );
779     is( $credit1->amountoutstanding + 0,
780         -10, 'Credit has an new amount outstanding of -10' );
781     is( $credit1->status(), 'PAID', "Credit has a new status of PAID" );
782
783     $schema->storage->txn_rollback;
784 };
785
786 subtest "reduce() tests" => sub {
787
788     plan tests => 27;
789
790     $schema->storage->txn_begin;
791
792     # Create a borrower
793     my $categorycode =
794       $builder->build( { source => 'Category' } )->{categorycode};
795     my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode};
796
797     my $borrower = Koha::Patron->new(
798         {
799             cardnumber => 'dariahall',
800             surname    => 'Hall',
801             firstname  => 'Daria',
802         }
803     );
804     $borrower->categorycode($categorycode);
805     $borrower->branchcode($branchcode);
806     $borrower->store;
807
808     my $staff = Koha::Patron->new(
809         {
810             cardnumber => 'bobby',
811             surname    => 'Bloggs',
812             firstname  => 'Bobby',
813         }
814     );
815     $staff->categorycode($categorycode);
816     $staff->branchcode($branchcode);
817     $staff->store;
818
819     my $account = Koha::Account->new( { patron_id => $borrower->id } );
820
821     my $debit1 = Koha::Account::Line->new(
822         {
823             borrowernumber    => $borrower->borrowernumber,
824             amount            => 20,
825             amountoutstanding => 20,
826             interface         => 'commandline',
827             debit_type_code   => 'LOST'
828         }
829     )->store();
830     my $credit1 = Koha::Account::Line->new(
831         {
832             borrowernumber    => $borrower->borrowernumber,
833             amount            => -20,
834             amountoutstanding => -20,
835             interface         => 'commandline',
836             credit_type_code  => 'CREDIT'
837         }
838     )->store();
839
840     is( $account->balance(), 0, "Account balance is 0" );
841     is( $debit1->amountoutstanding,
842         20, 'Overdue fee has an amount outstanding of 20' );
843     is( $credit1->amountoutstanding,
844         -20, 'Credit has an amount outstanding of -20' );
845
846     my $reduce_params = {
847         interface      => 'commandline',
848         reduction_type => 'REFUND',
849         amount         => 5,
850         staff_id       => $staff->borrowernumber,
851         branch         => $branchcode
852     };
853
854     throws_ok { $credit1->reduce($reduce_params); }
855     'Koha::Exceptions::Account::IsNotDebit',
856       '->reduce() can only be used with debits';
857
858     my @required = ( 'interface', 'reduction_type', 'amount' );
859     for my $required (@required) {
860         my $params = {%$reduce_params};
861         delete( $params->{$required} );
862         throws_ok {
863             $debit1->reduce($params);
864         }
865         'Koha::Exceptions::MissingParameter',
866           "->reduce() requires the `$required` parameter is passed";
867     }
868
869     $reduce_params->{interface} = 'intranet';
870     my @dependant_required = ( 'staff_id', 'branch' );
871     for my $d (@dependant_required) {
872         my $params = {%$reduce_params};
873         delete( $params->{$d} );
874         throws_ok {
875             $debit1->reduce($params);
876         }
877         'Koha::Exceptions::MissingParameter',
878 "->reduce() requires the `$d` parameter is passed when interface is intranet";
879     }
880
881     throws_ok {
882         $debit1->reduce(
883             {
884                 interface      => 'intranet',
885                 staff_id       => $staff->borrowernumber,
886                 branch         => $branchcode,
887                 reduction_type => 'REFUND',
888                 amount         => 25
889             }
890         );
891     }
892     'Koha::Exceptions::ParameterTooHigh',
893       '->reduce() cannot reduce more than original amount';
894
895     # Partial Reduction
896     # (Refund 5 on debt of 20)
897     my $reduction = $debit1->reduce($reduce_params);
898
899     is( ref($reduction), 'Koha::Account::Line',
900         '->reduce() returns a Koha::Account::Line' );
901     is( $reduction->amount() * 1, -5, "Reduce amount is -5" );
902     is( $reduction->amountoutstanding() * 1,
903         0, "Reduce amountoutstanding is 0" );
904     is( $debit1->amountoutstanding() * 1,
905         15, "Debit amountoutstanding reduced by 5 to 15" );
906     is( $account->balance() * 1, -5,        "Account balance is -5" );
907     is( $reduction->status(),    'APPLIED', "Reduction status is 'APPLIED'" );
908
909     my $offsets = Koha::Account::Offsets->search(
910         { credit_id => $reduction->id, debit_id => $debit1->id } );
911     is( $offsets->count, 1, 'Only one offset is generated' );
912     my $THE_offset = $offsets->next;
913     is( $THE_offset->amount * 1,
914         -5, 'Correct amount was applied against debit' );
915     is( $THE_offset->type, 'REFUND', "Offset type set to 'REFUND'" );
916
917     # Zero offset created when zero outstanding
918     # (Refund another 5 on paid debt of 20)
919     $credit1->apply( { debits => [$debit1] } );
920     is( $debit1->amountoutstanding + 0,
921         0, 'Debit1 amountoutstanding reduced to 0' );
922     $reduction = $debit1->reduce($reduce_params);
923     is( $reduction->amount() * 1, -5, "Reduce amount is -5" );
924     is( $reduction->amountoutstanding() * 1,
925         -5, "Reduce amountoutstanding is -5" );
926
927     $offsets = Koha::Account::Offsets->search(
928         { credit_id => $reduction->id, debit_id => $debit1->id } );
929     is( $offsets->count, 1, 'Only one new offset is generated' );
930     $THE_offset = $offsets->next;
931     is( $THE_offset->amount * 1,
932         0, 'Zero offset created for already paid off debit' );
933     is( $THE_offset->type, 'REFUND', "Offset type set to 'REFUND'" );
934
935     # Compound reduction should not allow more than original amount
936     # (Reduction of 5 + 5 + 20 > 20)
937     $reduce_params->{amount} = 20;
938     throws_ok {
939         $debit1->reduce($reduce_params);
940     }
941     'Koha::Exceptions::ParameterTooHigh',
942 '->reduce cannot reduce more than the original amount (combined reductions test)';
943
944     # Throw exception if attempting to reduce a payout
945     my $payout = $reduction->payout(
946         {
947             interface   => 'intranet',
948             staff_id    => $staff->borrowernumber,
949             branch      => $branchcode,
950             payout_type => 'CASH',
951             amount      => 5
952         }
953     );
954     throws_ok {
955         $payout->reduce($reduce_params);
956     }
957     'Koha::Exceptions::Account::IsNotDebit',
958       '->reduce() cannot be used on a payout debit';
959
960     $schema->storage->txn_rollback;
961 };
962
963 1;