Bug 30612: (QA follow-up) Rename accountlines method to account_lines
[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 => 15;
23 use Test::Exception;
24 use Test::MockModule;
25
26 use DateTime;
27
28 use C4::Circulation qw( AddRenewal CanBookBeRenewed LostItem 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 'manager() tests' => sub {
70
71     plan tests => 3;
72
73     $schema->storage->txn_begin;
74
75     my $library = $builder->build( { source => 'Branch' } );
76     my $manager = $builder->build( { source => 'Borrower' } );
77
78     my $line = Koha::Account::Line->new(
79     {
80         manager_id      => $manager->{borrowernumber},
81         debit_type_code => "OVERDUE",
82         status          => "RETURNED",
83         amount          => 10,
84         interface       => 'commandline',
85     })->store;
86
87     my $account_line_manager = $line->manager;
88     is( ref( $account_line_manager ), 'Koha::Patron', 'Koha::Account::Line->manager should return a Koha::Patron' );
89     is( $line->manager_id, $account_line_manager->borrowernumber, 'Koha::Account::Line->manager should return the correct staff' );
90
91     $line->manager_id(undef)->store;
92     is( $line->manager, undef, 'Koha::Account::Line->manager should return undef if no staff linked' );
93
94     $schema->storage->txn_rollback;
95 };
96
97 subtest 'item() tests' => sub {
98
99     plan tests => 3;
100
101     $schema->storage->txn_begin;
102
103     my $library = $builder->build( { source => 'Branch' } );
104     my $patron = $builder->build( { source => 'Borrower' } );
105     my $item = $builder->build_sample_item(
106         {
107             library => $library->{branchcode},
108             barcode => 'some_barcode_12',
109             itype   => 'BK',
110         }
111     );
112
113     my $line = Koha::Account::Line->new(
114     {
115         borrowernumber => $patron->{borrowernumber},
116         itemnumber     => $item->itemnumber,
117         debit_type_code    => "OVERDUE",
118         status         => "RETURNED",
119         amount         => 10,
120         interface      => 'commandline',
121     })->store;
122
123     my $account_line_item = $line->item;
124     is( ref( $account_line_item ), 'Koha::Item', 'Koha::Account::Line->item should return a Koha::Item' );
125     is( $line->itemnumber, $account_line_item->itemnumber, 'Koha::Account::Line->item should return the correct item' );
126
127     $line->itemnumber(undef)->store;
128     is( $line->item, undef, 'Koha::Account::Line->item should return undef if no item linked' );
129
130     $schema->storage->txn_rollback;
131 };
132
133 subtest 'library() tests' => sub {
134
135     plan tests => 4;
136
137     $schema->storage->txn_begin;
138
139     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
140     my $patron  = $builder->build( { source => 'Borrower' } );
141
142     my $line = Koha::Account::Line->new(
143         {
144             borrowernumber  => $patron->{borrowernumber},
145             branchcode      => $library->branchcode,
146             debit_type_code => "OVERDUE",
147             status          => "RETURNED",
148             amount          => 10,
149             interface       => 'commandline',
150         }
151     )->store;
152
153     my $account_line_library = $line->library;
154     is( ref($account_line_library),
155         'Koha::Library',
156         'Koha::Account::Line->library should return a Koha::Library' );
157     is(
158         $line->branchcode,
159         $account_line_library->branchcode,
160         'Koha::Account::Line->library should return the correct library'
161     );
162
163     # Test ON DELETE SET NULL
164     $library->delete;
165     my $found = Koha::Account::Lines->find( $line->accountlines_id );
166     ok( $found, "Koha::Account::Line not deleted when the linked library is deleted" );
167
168     is( $found->library, undef,
169 'Koha::Account::Line->library should return undef if linked library has been deleted'
170     );
171
172     $schema->storage->txn_rollback;
173 };
174
175 subtest 'is_credit() and is_debit() tests' => sub {
176
177     plan tests => 4;
178
179     $schema->storage->txn_begin;
180
181     my $patron  = $builder->build_object({ class => 'Koha::Patrons' });
182     my $account = $patron->account;
183
184     my $credit = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' });
185
186     ok( $credit->is_credit, 'is_credit detects credits' );
187     ok( !$credit->is_debit, 'is_debit detects credits' );
188
189     my $debit = Koha::Account::Line->new(
190     {
191         borrowernumber => $patron->id,
192         debit_type_code    => "OVERDUE",
193         status         => "RETURNED",
194         amount         => 10,
195         interface      => 'commandline',
196     })->store;
197
198     ok( !$debit->is_credit, 'is_credit detects debits' );
199     ok( $debit->is_debit, 'is_debit detects debits');
200
201     $schema->storage->txn_rollback;
202 };
203
204 subtest 'apply() tests' => sub {
205
206     plan tests => 32;
207
208     $schema->storage->txn_begin;
209
210     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
211     my $account = $patron->account;
212
213     my $credit = $account->add_credit( { amount => 100, user_id => $patron->id, interface => 'commandline' } );
214
215     my $debit_1 = Koha::Account::Line->new(
216         {   borrowernumber    => $patron->id,
217             debit_type_code       => "OVERDUE",
218             status            => "RETURNED",
219             amount            => 10,
220             amountoutstanding => 10,
221             interface         => 'commandline',
222         }
223     )->store;
224
225     my $debit_2 = Koha::Account::Line->new(
226         {   borrowernumber    => $patron->id,
227             debit_type_code       => "OVERDUE",
228             status            => "RETURNED",
229             amount            => 100,
230             amountoutstanding => 100,
231             interface         => 'commandline',
232         }
233     )->store;
234
235     $credit->discard_changes;
236     $debit_1->discard_changes;
237
238     my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id });
239     $credit = $credit->apply( { debits => [ $debits->as_list ] } );
240     is( ref($credit), 'Koha::Account::Line', '->apply returns the updated Koha::Account::Line credit object');
241     is( $credit->amountoutstanding * -1, 90, 'Remaining credit is correctly calculated' );
242
243     # re-read debit info
244     $debit_1->discard_changes;
245     is( $debit_1->amountoutstanding * 1, 0, 'Debit has been cancelled' );
246
247     my $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_1->id } );
248     is( $offsets->count, 1, 'Only one offset is generated' );
249     my $THE_offset = $offsets->next;
250     is( $THE_offset->amount * 1, -10, 'Amount was calculated correctly (less than the available credit)' );
251     is( $THE_offset->type, 'APPLY', 'Passed type stored correctly' );
252
253     $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id });
254     $credit = $credit->apply( { debits => [ $debits->as_list ] } );
255     is( $credit->amountoutstanding * 1, 0, 'No remaining credit' );
256     $debit_2->discard_changes;
257     is( $debit_2->amountoutstanding * 1, 10, 'Outstanding amount decremented correctly' );
258
259     $offsets = Koha::Account::Offsets->search( { credit_id => $credit->id, debit_id => $debit_2->id } );
260     is( $offsets->count, 1, 'Only one offset is generated' );
261     $THE_offset = $offsets->next;
262     is( $THE_offset->amount * 1, -90, 'Amount was calculated correctly (less than the available credit)' );
263     is( $THE_offset->type, 'APPLY', 'Defaults to \'APPLY\' offset type' );
264
265     $debits = Koha::Account::Lines->search({ accountlines_id => $debit_1->id });
266     throws_ok
267         { $credit->apply({ debits => [ $debits->as_list ] }); }
268         'Koha::Exceptions::Account::NoAvailableCredit',
269         '->apply() can only be used with outstanding credits';
270
271     $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id });
272     throws_ok
273         { $debit_1->apply({ debits => [ $debits->as_list ] }); }
274         'Koha::Exceptions::Account::IsNotCredit',
275         '->apply() can only be used with credits';
276
277     $debits = Koha::Account::Lines->search({ accountlines_id => $credit->id });
278     my $credit_3 = $account->add_credit({ amount => 1, interface => 'commandline' });
279     throws_ok
280         { $credit_3->apply({ debits => [ $debits->as_list ] }); }
281         'Koha::Exceptions::Account::IsNotDebit',
282         '->apply() can only be applied to credits';
283
284     my $credit_2 = $account->add_credit({ amount => 20, interface => 'commandline' });
285     my $debit_3  = Koha::Account::Line->new(
286         {   borrowernumber    => $patron->id,
287             debit_type_code       => "OVERDUE",
288             status            => "RETURNED",
289             amount            => 100,
290             amountoutstanding => 100,
291             interface         => 'commandline',
292         }
293     )->store;
294
295     $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id, $credit->id ] } });
296     throws_ok {
297         $credit_2->apply( { debits => [ $debits->as_list ] }); }
298         'Koha::Exceptions::Account::IsNotDebit',
299         '->apply() rolls back if any of the passed lines is not a debit';
300
301     is( $debit_1->discard_changes->amountoutstanding * 1,   0, 'No changes to already cancelled debit' );
302     is( $debit_2->discard_changes->amountoutstanding * 1,  10, 'Debit cancelled' );
303     is( $debit_3->discard_changes->amountoutstanding * 1, 100, 'Outstanding amount correctly calculated' );
304     is( $credit_2->discard_changes->amountoutstanding * -1, 20, 'No changes made' );
305
306     $debits = Koha::Account::Lines->search({ accountlines_id => { -in => [ $debit_1->id, $debit_2->id, $debit_3->id ] } });
307     $credit_2 = $credit_2->apply( { debits => [ $debits->as_list ] } );
308
309     is( $debit_1->discard_changes->amountoutstanding * 1,  0, 'No changes to already cancelled debit' );
310     is( $debit_2->discard_changes->amountoutstanding * 1,  0, 'Debit cancelled' );
311     is( $debit_3->discard_changes->amountoutstanding * 1, 90, 'Outstanding amount correctly calculated' );
312     is( $credit_2->amountoutstanding * 1, 0, 'No remaining credit' );
313
314     my $library  = $builder->build_object( { class => 'Koha::Libraries' } );
315     my $biblio = $builder->build_sample_biblio();
316     my $item =
317         $builder->build_sample_item( { biblionumber => $biblio->biblionumber } );
318     my $now = dt_from_string();
319     my $seven_weeks = DateTime::Duration->new(weeks => 7);
320     my $five_weeks = DateTime::Duration->new(weeks => 5);
321     my $seven_weeks_ago = $now - $seven_weeks;
322     my $five_weeks_ago = $now - $five_weeks;
323
324     my $checkout = Koha::Checkout->new(
325         {
326             borrowernumber => $patron->id,
327             itemnumber     => $item->id,
328             date_due       => $five_weeks_ago,
329             branchcode     => $library->id,
330             issuedate      => $seven_weeks_ago
331         }
332     )->store();
333
334     my $accountline = Koha::Account::Line->new(
335         {
336             issue_id       => $checkout->id,
337             borrowernumber => $patron->id,
338             itemnumber     => $item->id,
339             branchcode     => $library->id,
340             date           => \'NOW()',
341             debit_type_code => 'OVERDUE',
342             status         => 'UNRETURNED',
343             interface      => 'cli',
344             amount => '1',
345             amountoutstanding => '1',
346         }
347     )->store();
348
349     my $a = $checkout->account_lines->next;
350     is( $a->id, $accountline->id, "Koha::Checkout::accountlines returns the related acountline" );
351
352     # Enable renewing upon fine payment
353     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
354     my $called = 0;
355     my $module = Test::MockModule->new('C4::Circulation');
356     $module->mock('AddRenewal', sub { $called = 1; });
357     $module->mock('CanBookBeRenewed', sub { return 1; });
358     my $credit_forgive = $account->add_credit(
359         {
360             amount    => 1,
361             user_id   => $patron->id,
362             interface => 'cli',
363             type      => 'FORGIVEN'
364         }
365     );
366     my $debits_renew = Koha::Account::Lines->search({ accountlines_id => $accountline->id })->as_list;
367     $credit_forgive = $credit_forgive->apply( { debits => $debits_renew } );
368     is( $called, 0, 'C4::Circulation::AddRenew NOT called when RenewAccruingItemWhenPaid enabled but credit type is "FORGIVEN"' );
369
370     $accountline = Koha::Account::Line->new(
371         {
372             issue_id       => $checkout->id,
373             borrowernumber => $patron->id,
374             itemnumber     => $item->id,
375             branchcode     => $library->id,
376             date           => \'NOW()',
377             debit_type_code => 'OVERDUE',
378             status         => 'UNRETURNED',
379             interface      => 'cli',
380             amount => '1',
381             amountoutstanding => '1',
382         }
383     )->store();
384     my $credit_renew = $account->add_credit({ amount => 100, user_id => $patron->id, interface => 'commandline' });
385     $debits_renew = Koha::Account::Lines->search({ accountlines_id => $accountline->id })->as_list;
386     $credit_renew = $credit_renew->apply( { debits => $debits_renew } );
387     is( $called, 1, 'RenewAccruingItemWhenPaid causes C4::Circulation::AddRenew to be called when appropriate' );
388
389     my @messages = @{$credit_renew->object_messages};
390     is( $messages[0]->type, 'info', 'Info message added for renewal' );
391     is( $messages[0]->message, 'renewal', 'Message is "renewal"' );
392     is( $messages[0]->payload->{itemnumber}, $item->id, 'itemnumber found in payload' );
393     is( $messages[0]->payload->{due_date}, 1, 'due_date key in payload' );
394     is( $messages[0]->payload->{success}, 1, "'success' key in payload" );
395
396     t::lib::Mocks::mock_preference( 'MarkLostItemsAsReturned', 'onpayment');
397     my $loser  = $builder->build_object( { class => 'Koha::Patrons' } );
398     my $loser_account = $loser->account;
399
400     my $lost_item = $builder->build_sample_item();
401     my $lost_checkout = Koha::Checkout->new(
402         {
403             borrowernumber => $loser->id,
404             itemnumber     => $lost_item->id,
405             date_due       => $five_weeks_ago,
406             branchcode     => $library->id,
407             issuedate      => $seven_weeks_ago
408         }
409     )->store();
410
411     $lost_item->itemlost(1)->store;
412     my $processing_fee = Koha::Account::Line->new(
413         {
414             issue_id       => $lost_checkout->id,
415             borrowernumber => $loser->id,
416             itemnumber     => $lost_item->id,
417             branchcode     => $library->id,
418             date           => \'NOW()',
419             debit_type_code => 'PROCESSING',
420             status         => undef,
421             interface      => 'intranet',
422             amount => '15',
423             amountoutstanding => '15',
424         }
425     )->store();
426     my $lost_fee = Koha::Account::Line->new(
427         {
428             issue_id       => $lost_checkout->id,
429             borrowernumber => $loser->id,
430             itemnumber     => $lost_item->id,
431             branchcode     => $library->id,
432             date           => \'NOW()',
433             debit_type_code => 'LOST',
434             status         => undef,
435             interface      => 'intranet',
436             amount => '12.63',
437             amountoutstanding => '12.63',
438         }
439     )->store();
440     my $pay_lost = $loser_account->add_credit({ amount => 27.630000, user_id => $loser->id, interface => 'intranet' });
441     my $pay_lines = [ $processing_fee, $lost_fee ];
442     $pay_lost->apply( { debits => $pay_lines, offset_type => 'Credit applied' } );
443
444     is( $loser->checkouts->next, undef, "Item has been returned");
445
446
447
448     $schema->storage->txn_rollback;
449 };
450
451 subtest 'Keep account info when related patron, staff, item or cash_register is deleted' => sub {
452
453     plan tests => 4;
454
455     $schema->storage->txn_begin;
456
457     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
458     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
459     my $item = $builder->build_sample_item;
460     my $issue = $builder->build_object(
461         {
462             class => 'Koha::Checkouts',
463             value => { itemnumber => $item->itemnumber }
464         }
465     );
466     my $register = $builder->build_object({ class => 'Koha::Cash::Registers' });
467
468     my $line = Koha::Account::Line->new(
469     {
470         borrowernumber => $patron->borrowernumber,
471         manager_id     => $staff->borrowernumber,
472         itemnumber     => $item->itemnumber,
473         debit_type_code    => "OVERDUE",
474         status         => "RETURNED",
475         amount         => 10,
476         interface      => 'commandline',
477         register_id    => $register->id
478     })->store;
479
480     $issue->delete;
481     $item->delete;
482     $line = $line->get_from_storage;
483     is( $line->itemnumber, undef, "The account line should not be deleted when the related item is delete");
484
485     $staff->delete;
486     $line = $line->get_from_storage;
487     is( $line->manager_id, undef, "The account line should not be deleted when the related staff is delete");
488
489     $patron->delete;
490     $line = $line->get_from_storage;
491     is( $line->borrowernumber, undef, "The account line should not be deleted when the related patron is delete");
492
493     $register->delete;
494     $line = $line->get_from_storage;
495     is( $line->register_id, undef, "The account line should not be deleted when the related cash register is delete");
496
497     $schema->storage->txn_rollback;
498 };
499
500 subtest 'Renewal related tests' => sub {
501
502     plan tests => 8;
503
504     $schema->storage->txn_begin;
505
506     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
507     my $staff = $builder->build_object( { class => 'Koha::Patrons' } );
508     my $item = $builder->build_object({ class => 'Koha::Items' });
509     my $issue = $builder->build_object(
510         {
511             class => 'Koha::Checkouts',
512             value => {
513                 itemnumber      => $item->itemnumber,
514                 onsite_checkout => 0,
515                 renewals_count  => 99,
516                 auto_renew      => 0
517             }
518         }
519     );
520     my $line = Koha::Account::Line->new(
521     {
522         borrowernumber    => $patron->borrowernumber,
523         manager_id        => $staff->borrowernumber,
524         itemnumber        => $item->itemnumber,
525         debit_type_code   => "OVERDUE",
526         status            => "UNRETURNED",
527         amountoutstanding => 0,
528         interface         => 'commandline',
529     })->store;
530
531     is( $line->is_renewable, 1, "Item is returned as renewable when it meets the conditions" );
532     $line->amountoutstanding(5);
533     is( $line->is_renewable, 0, "Item is returned as unrenewable when it has outstanding fine" );
534     $line->amountoutstanding(0);
535     $line->debit_type_code("VOID");
536     is( $line->is_renewable, 0, "Item is returned as unrenewable when it has the wrong account type" );
537     $line->debit_type_code("OVERDUE");
538     $line->status("RETURNED");
539     is( $line->is_renewable, 0, "Item is returned as unrenewable when it has the wrong account status" );
540
541
542     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 0 );
543     is ($line->renew_item({ interface => 'intranet' }), undef, 'Attempt to renew fails when syspref is not set');
544     t::lib::Mocks::mock_preference( 'RenewAccruingItemWhenPaid', 1 );
545     t::lib::Mocks::mock_preference( 'RenewAccruingItemInOpac', 0 );
546     is ($line->renew_item({ interface => 'opac' }), undef, 'Attempt to renew fails when syspref is not set - OPAC');
547     t::lib::Mocks::mock_preference( 'RenewAccruingItemInOpac', 1 );
548     is_deeply(
549         $line->renew_item({ interface => 'intranet' }),
550         {
551             itemnumber => $item->itemnumber,
552             error      => 'too_many',
553             success    => 0
554         },
555         'Attempt to renew fails when CanBookBeRenewed returns false'
556     );
557     $issue->delete;
558     $issue = $builder->build_object(
559         {
560             class => 'Koha::Checkouts',
561             value => {
562                 itemnumber      => $item->itemnumber,
563                 onsite_checkout => 0,
564                 renewals_count  => 0,
565                 auto_renew      => 0
566             }
567         }
568     );
569     my $called = 0;
570     my $module = Test::MockModule->new('C4::Circulation');
571     $module->mock('AddRenewal', sub { $called = 1; });
572     $module->mock('CanBookBeRenewed', sub { return 1; });
573     $line->renew_item;
574     is( $called, 1, 'Attempt to renew succeeds when conditions are met' );
575
576     $schema->storage->txn_rollback;
577 };
578
579 subtest 'adjust() tests' => sub {
580
581     plan tests => 29;
582
583     $schema->storage->txn_begin;
584
585     # count logs before any actions
586     my $action_logs = $schema->resultset('ActionLog')->search()->count;
587
588     # Disable logs
589     t::lib::Mocks::mock_preference( 'FinesLog', 0 );
590
591     my $patron  = $builder->build_object( { class => 'Koha::Patrons' } );
592     my $account = $patron->account;
593
594     my $debit_1 = Koha::Account::Line->new(
595         {   borrowernumber    => $patron->id,
596             debit_type_code       => "OVERDUE",
597             status            => "RETURNED",
598             amount            => 10,
599             amountoutstanding => 10,
600             interface         => 'commandline',
601         }
602     )->store;
603
604     my $debit_2 = Koha::Account::Line->new(
605         {   borrowernumber    => $patron->id,
606             debit_type_code       => "OVERDUE",
607             status            => "UNRETURNED",
608             amount            => 100,
609             amountoutstanding => 100,
610             interface         => 'commandline'
611         }
612     )->store;
613
614     my $credit = $account->add_credit( { amount => 40, user_id => $patron->id, interface => 'commandline' } );
615
616     throws_ok { $debit_1->adjust( { amount => 50, type => 'bad', interface => 'commandline' } ) }
617     qr/Update type not recognised/, 'Exception thrown for unrecognised type';
618
619     throws_ok { $debit_1->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } ) }
620     qr/Update type not allowed on this debit_type/,
621       'Exception thrown for type conflict';
622
623     # Increment an unpaid fine
624     $debit_2->adjust( { amount => 150, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
625
626     is( $debit_2->amount * 1, 150, 'Fine amount was updated in full' );
627     is( $debit_2->amountoutstanding * 1, 150, 'Fine amountoutstanding was update in full' );
628     isnt( $debit_2->date, undef, 'Date has been set' );
629
630     my $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
631     is( $offsets->count, 1, 'An offset is generated for the increment' );
632     my $THIS_offset = $offsets->next;
633     is( $THIS_offset->amount * 1, 50, 'Amount was calculated correctly (increment by 50)' );
634     is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' );
635
636     is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No log was added' );
637
638     # Update fine to partially paid
639     my $debits = Koha::Account::Lines->search({ accountlines_id => $debit_2->id });
640     $credit->apply( { debits => [ $debits->as_list ] } );
641
642     $debit_2->discard_changes;
643     is( $debit_2->amount * 1, 150, 'Fine amount unaffected by partial payment' );
644     is( $debit_2->amountoutstanding * 1, 110, 'Fine amountoutstanding updated by partial payment' );
645
646     # Enable logs
647     t::lib::Mocks::mock_preference( 'FinesLog', 1 );
648
649     # Increment the partially paid fine
650     $debit_2->adjust( { amount => 160, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
651
652     is( $debit_2->amount * 1, 160, 'Fine amount was updated in full' );
653     is( $debit_2->amountoutstanding * 1, 120, 'Fine amountoutstanding was updated by difference' );
654
655     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
656     is( $offsets->count, 3, 'An offset is generated for the increment' );
657     $THIS_offset = $offsets->last;
658     is( $THIS_offset->amount * 1, 10, 'Amount was calculated correctly (increment by 10)' );
659     is( $THIS_offset->type, 'OVERDUE_INCREASE', 'Adjust type stored correctly' );
660
661     is( $schema->resultset('ActionLog')->count(), $action_logs + 1, 'Log was added' );
662
663     # Decrement the partially paid fine, less than what was paid
664     $debit_2->adjust( { amount => 50, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
665
666     is( $debit_2->amount * 1, 50, 'Fine amount was updated in full' );
667     is( $debit_2->amountoutstanding * 1, 10, 'Fine amountoutstanding was updated by difference' );
668
669     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
670     is( $offsets->count, 4, 'An offset is generated for the decrement' );
671     $THIS_offset = $offsets->last;
672     is( $THIS_offset->amount * 1, -110, 'Amount was calculated correctly (decrement by 110)' );
673     is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' );
674
675     # Decrement the partially paid fine, more than what was paid
676     $debit_2->adjust( { amount => 30, type => 'overdue_update', interface => 'commandline' } )->discard_changes;
677     is( $debit_2->amount * 1, 30, 'Fine amount was updated in full' );
678     is( $debit_2->amountoutstanding * 1, 0, 'Fine amountoutstanding was zeroed (payment was 40)' );
679
680     $offsets = Koha::Account::Offsets->search( { debit_id => $debit_2->id } );
681     is( $offsets->count, 5, 'An offset is generated for the decrement' );
682     $THIS_offset = $offsets->last;
683     is( $THIS_offset->amount * 1, -20, 'Amount was calculated correctly (decrement by 20)' );
684     is( $THIS_offset->type, 'OVERDUE_DECREASE', 'Adjust type stored correctly' );
685
686     my $overpayment_refund = $account->lines->last;
687     is( $overpayment_refund->amount * 1, -10, 'A new credit has been added' );
688     is( $overpayment_refund->credit_type_code, 'OVERPAYMENT', 'Credit generated with the expected credit_type_code' );
689
690     $schema->storage->txn_rollback;
691 };
692
693 subtest 'checkout() tests' => sub {
694     plan tests => 6;
695
696     $schema->storage->txn_begin;
697
698     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
699     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
700     my $item = $builder->build_sample_item;
701     my $account = $patron->account;
702
703     t::lib::Mocks::mock_userenv({ branchcode => $library->branchcode });
704     my $checkout = AddIssue( $patron->unblessed, $item->barcode );
705
706     my $line = $account->add_debit({
707         amount    => 10,
708         interface => 'commandline',
709         item_id   => $item->itemnumber,
710         issue_id  => $checkout->issue_id,
711         type      => 'OVERDUE',
712         status    => 'UNRETURNED'
713     });
714
715     my $line_checkout = $line->checkout;
716     is( ref($line_checkout), 'Koha::Checkout', 'Result type is correct' );
717     is( $line_checkout->issue_id, $checkout->issue_id, 'Koha::Account::Line->checkout should return the correct checkout');
718
719     # Prevent re-calculation of fines at check-in for the test; Since bug 8338 the recalculation would result in a '0'
720     # fine which would subsequently be removed by _FixOverduesOnReturn
721     t::lib::Mocks::mock_preference( 'finesMode', 'off' );
722
723     my ( $returned, undef, $old_checkout) = C4::Circulation::AddReturn( $item->barcode, $library->branchcode );
724     is( $returned, 1, 'The item should have been returned' );
725
726     $line = $line->get_from_storage;
727     my $old_line_checkout = $line->checkout;
728     is( ref($old_line_checkout), 'Koha::Old::Checkout', 'Result type is correct' );
729     is( $old_line_checkout->issue_id, $old_checkout->issue_id, 'Koha::Account::Line->checkout should return the correct old_checkout' );
730
731     $line->issue_id(undef)->store;
732     is( $line->checkout, undef, 'Koha::Account::Line->checkout should return undef if no checkout linked' );
733
734     $schema->storage->txn_rollback;
735 };
736
737 subtest 'credits() and debits() tests' => sub {
738     plan tests => 12;
739
740     $schema->storage->txn_begin;
741
742     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
743     my $account = $patron->account;
744
745     my $debit1 = $account->add_debit({
746         amount    => 8,
747         interface => 'commandline',
748         type      => 'ACCOUNT',
749     });
750     my $debit2 = $account->add_debit({
751         amount    => 12,
752         interface => 'commandline',
753         type      => 'ACCOUNT',
754     });
755     my $credit1 = $account->add_credit({
756         amount    => 5,
757         interface => 'commandline',
758         type      => 'CREDIT',
759     });
760     my $credit2 = $account->add_credit({
761         amount    => 10,
762         interface => 'commandline',
763         type      => 'CREDIT',
764     });
765
766     $credit1->apply({ debits => [ $debit1 ] });
767     $credit2->apply({ debits => [ $debit1, $debit2 ] });
768
769     my $credits = $debit1->credits;
770     is($credits->count, 2, '2 Credits applied to debit 1');
771     my $credit = $credits->next;
772     is($credit->amount + 0, -5, 'Correct first credit');
773     $credit = $credits->next;
774     is($credit->amount + 0, -10, 'Correct second credit');
775
776     $credits = $debit2->credits;
777     is($credits->count, 1, '1 Credits applied to debit 2');
778     $credit = $credits->next;
779     is($credit->amount + 0, -10, 'Correct first credit');
780
781     my $debits = $credit1->debits;
782     is($debits->count, 1, 'Credit 1 applied to 1 debit');
783     my $debit = $debits->next;
784     is($debit->amount + 0, 8, 'Correct first debit');
785
786     $debits = $credit2->debits;
787     is($debits->count, 2, 'Credit 2 applied to 2 debits');
788     $debit = $debits->next;
789     is($debit->amount + 0, 8, 'Correct first debit');
790     $debit = $debits->next;
791     is($debit->amount + 0, 12, 'Correct second debit');
792
793     throws_ok
794         { $debit1->debits; }
795         'Koha::Exceptions::Account::IsNotCredit',
796         'Exception is thrown when requesting debits linked to debit';
797
798     throws_ok
799         { $credit1->credits; }
800         'Koha::Exceptions::Account::IsNotDebit',
801         'Exception is thrown when requesting credits linked to credit';
802
803
804     $schema->storage->txn_rollback;
805 };
806
807 subtest "void() tests" => sub {
808
809     plan tests => 23;
810
811     $schema->storage->txn_begin;
812
813     # Create a borrower
814     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
815     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
816
817     my $borrower = Koha::Patron->new( {
818         cardnumber => 'dariahall',
819         surname => 'Hall',
820         firstname => 'Daria',
821     } );
822     $borrower->categorycode( $categorycode );
823     $borrower->branchcode( $branchcode );
824     $borrower->store;
825
826     my $account = Koha::Account->new({ patron_id => $borrower->id });
827
828     my $line1 = Koha::Account::Line->new(
829         {
830             borrowernumber    => $borrower->borrowernumber,
831             amount            => 10,
832             amountoutstanding => 10,
833             interface         => 'commandline',
834             debit_type_code   => 'OVERDUE'
835         }
836     )->store();
837     my $line2 = Koha::Account::Line->new(
838         {
839             borrowernumber    => $borrower->borrowernumber,
840             amount            => 20,
841             amountoutstanding => 20,
842             interface         => 'commandline',
843             debit_type_code   => 'OVERDUE'
844         }
845     )->store();
846
847     is( $account->balance(), 30, "Account balance is 30" );
848     is( $line1->amountoutstanding, 10, 'First fee has amount outstanding of 10' );
849     is( $line2->amountoutstanding, 20, 'Second fee has amount outstanding of 20' );
850
851     my $id = $account->pay(
852         {
853             lines  => [$line1, $line2],
854             amount => 30,
855         }
856     )->{payment_id};
857
858     my $account_payment = Koha::Account::Lines->find( $id );
859
860     is( $account->balance(), 0, "Account balance is 0" );
861
862     $line1->_result->discard_changes();
863     $line2->_result->discard_changes();
864     is( $line1->amountoutstanding+0, 0, 'First fee has amount outstanding of 0' );
865     is( $line2->amountoutstanding+0, 0, 'Second fee has amount outstanding of 0' );
866
867     throws_ok {
868         $line1->void( { interface => 'test' } );
869     }
870     'Koha::Exceptions::Account::IsNotCredit',
871       '->void() can only be used with credits';
872
873     throws_ok {
874         $account_payment->void();
875     }
876     'Koha::Exceptions::MissingParameter',
877       "->void() requires the `interface` parameter is passed";
878
879     throws_ok {
880         $account_payment->void( { interface => 'intranet' } );
881     }
882     'Koha::Exceptions::MissingParameter',
883       "->void() requires the `staff_id` parameter is passed when `interface` equals 'intranet'";
884     throws_ok {
885         $account_payment->void( { interface => 'intranet', staff_id => $borrower->borrowernumber } );
886     }
887     'Koha::Exceptions::MissingParameter',
888       "->void() requires the `branch` parameter is passed when `interface` equals 'intranet'";
889
890     my $void = $account_payment->void({ interface => 'test' });
891
892     is( ref($void), 'Koha::Account::Line', 'Void returns the account line' );
893     is( $void->debit_type_code, 'VOID', 'Void returns the VOID account line' );
894     is( $void->manager_id, undef, 'Void proceeds without manager_id OK if interface is not "intranet"' );
895     is( $void->branchcode, undef, 'Void proceeds without branchcode OK if interface is not "intranet"' );
896     is( $account->balance(), 30, "Account balance is again 30" );
897
898     $account_payment->_result->discard_changes();
899     $line1->_result->discard_changes();
900     $line2->_result->discard_changes();
901
902     is( $account_payment->credit_type_code, 'PAYMENT', 'Voided payment credit_type_code is still PAYMENT' );
903     is( $account_payment->status, 'VOID', 'Voided payment status is VOID' );
904     is( $account_payment->amount+0, -30, 'Voided payment amount is still -30' );
905     is( $account_payment->amountoutstanding+0, 0, 'Voided payment amount outstanding is 0' );
906
907     is( $line1->amountoutstanding+0, 10, 'First fee again has amount outstanding of 10' );
908     is( $line2->amountoutstanding+0, 20, 'Second fee again has amount outstanding of 20' );
909
910     my $credit2 = $account->add_credit( { interface => 'test', amount => 10 } );
911     $void = $credit2->void(
912         {
913             interface => 'intranet',
914             staff_id  => $borrower->borrowernumber,
915             branch    => $branchcode
916         }
917     );
918     is( $void->manager_id, $borrower->borrowernumber, "->void stores the manager_id when it's passed");
919     is( $void->branchcode, $branchcode, "->void stores the branchcode when it's passed");
920
921     $schema->storage->txn_rollback;
922 };
923
924 subtest "payout() tests" => sub {
925
926     plan tests => 18;
927
928     $schema->storage->txn_begin;
929
930     # Create a borrower
931     my $categorycode =
932       $builder->build( { source => 'Category' } )->{categorycode};
933     my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode};
934
935     my $borrower = Koha::Patron->new(
936         {
937             cardnumber => 'dariahall',
938             surname    => 'Hall',
939             firstname  => 'Daria',
940         }
941     );
942     $borrower->categorycode($categorycode);
943     $borrower->branchcode($branchcode);
944     $borrower->store;
945
946     my $staff = Koha::Patron->new(
947         {
948             cardnumber => 'bobby',
949             surname    => 'Bloggs',
950             firstname  => 'Bobby',
951         }
952     );
953     $staff->categorycode($categorycode);
954     $staff->branchcode($branchcode);
955     $staff->store;
956
957     my $account = Koha::Account->new( { patron_id => $borrower->id } );
958
959     my $debit1 = Koha::Account::Line->new(
960         {
961             borrowernumber    => $borrower->borrowernumber,
962             amount            => 10,
963             amountoutstanding => 10,
964             interface         => 'commandline',
965             debit_type_code   => 'OVERDUE'
966         }
967     )->store();
968     my $credit1 = Koha::Account::Line->new(
969         {
970             borrowernumber    => $borrower->borrowernumber,
971             amount            => -20,
972             amountoutstanding => -20,
973             interface         => 'commandline',
974             credit_type_code  => 'CREDIT'
975         }
976     )->store();
977
978     is( $account->balance(), -10, "Account balance is -10" );
979     is( $debit1->amountoutstanding + 0,
980         10, 'Overdue fee has an amount outstanding of 10' );
981     is( $credit1->amountoutstanding + 0,
982         -20, 'Credit has an amount outstanding of -20' );
983
984     my $pay_params = {
985         interface   => 'intranet',
986         staff_id    => $staff->borrowernumber,
987         branch      => $branchcode,
988         payout_type => 'CASH',
989         amount      => 20
990     };
991
992     throws_ok { $debit1->payout($pay_params); }
993     'Koha::Exceptions::Account::IsNotCredit',
994       '->payout() can only be used with credits';
995
996     my @required =
997       ( 'interface', 'staff_id', 'branch', 'payout_type', 'amount' );
998     for my $required (@required) {
999         my $params = {%$pay_params};
1000         delete( $params->{$required} );
1001         throws_ok {
1002             $credit1->payout($params);
1003         }
1004         'Koha::Exceptions::MissingParameter',
1005           "->payout() requires the `$required` parameter is passed";
1006     }
1007
1008     throws_ok {
1009         $credit1->payout(
1010             {
1011                 interface   => 'intranet',
1012                 staff_id    => $staff->borrowernumber,
1013                 branch      => $branchcode,
1014                 payout_type => 'CASH',
1015                 amount      => 25
1016             }
1017         );
1018     }
1019     'Koha::Exceptions::ParameterTooHigh',
1020       '->payout() cannot pay out more than the amountoutstanding';
1021
1022     t::lib::Mocks::mock_preference( 'UseCashRegisters', 1 );
1023     throws_ok {
1024         $credit1->payout(
1025             {
1026                 interface   => 'intranet',
1027                 staff_id    => $staff->borrowernumber,
1028                 branch      => $branchcode,
1029                 payout_type => 'CASH',
1030                 amount      => 10
1031             }
1032         );
1033     }
1034     'Koha::Exceptions::Account::RegisterRequired',
1035       '->payout() requires a cash_register if payout_type is `CASH`';
1036
1037     t::lib::Mocks::mock_preference( 'UseCashRegisters', 0 );
1038     my $payout = $credit1->payout(
1039         {
1040             interface   => 'intranet',
1041             staff_id    => $staff->borrowernumber,
1042             branch      => $branchcode,
1043             payout_type => 'CASH',
1044             amount      => 10
1045         }
1046     );
1047
1048     is( ref($payout), 'Koha::Account::Line',
1049         '->payout() returns a Koha::Account::Line' );
1050     is( $payout->amount() + 0,            10, "Payout amount is 10" );
1051     is( $payout->amountoutstanding() + 0, 0,  "Payout amountoutstanding is 0" );
1052     is( $account->balance() + 0,          0,  "Account balance is 0" );
1053     is( $debit1->amountoutstanding + 0,
1054         10, 'Overdue fee still has an amount outstanding of 10' );
1055     is( $credit1->amountoutstanding + 0,
1056         -10, 'Credit has an new amount outstanding of -10' );
1057     is( $credit1->status(), 'PAID', "Credit has a new status of PAID" );
1058
1059     $schema->storage->txn_rollback;
1060 };
1061
1062 subtest "reduce() tests" => sub {
1063
1064     plan tests => 34;
1065
1066     $schema->storage->txn_begin;
1067
1068     # Create a borrower
1069     my $categorycode =
1070       $builder->build( { source => 'Category' } )->{categorycode};
1071     my $branchcode = $builder->build( { source => 'Branch' } )->{branchcode};
1072
1073     my $borrower = Koha::Patron->new(
1074         {
1075             cardnumber => 'dariahall',
1076             surname    => 'Hall',
1077             firstname  => 'Daria',
1078         }
1079     );
1080     $borrower->categorycode($categorycode);
1081     $borrower->branchcode($branchcode);
1082     $borrower->store;
1083
1084     my $staff = Koha::Patron->new(
1085         {
1086             cardnumber => 'bobby',
1087             surname    => 'Bloggs',
1088             firstname  => 'Bobby',
1089         }
1090     );
1091     $staff->categorycode($categorycode);
1092     $staff->branchcode($branchcode);
1093     $staff->store;
1094
1095     my $account = Koha::Account->new( { patron_id => $borrower->id } );
1096
1097     my $debit1 = Koha::Account::Line->new(
1098         {
1099             borrowernumber    => $borrower->borrowernumber,
1100             amount            => 20,
1101             amountoutstanding => 20,
1102             interface         => 'commandline',
1103             debit_type_code   => 'LOST'
1104         }
1105     )->store();
1106     my $credit1 = Koha::Account::Line->new(
1107         {
1108             borrowernumber    => $borrower->borrowernumber,
1109             amount            => -20,
1110             amountoutstanding => -20,
1111             interface         => 'commandline',
1112             credit_type_code  => 'CREDIT'
1113         }
1114     )->store();
1115
1116     is( $account->balance(), 0, "Account balance is 0" );
1117     is( $debit1->amountoutstanding,
1118         20, 'Overdue fee has an amount outstanding of 20' );
1119     is( $credit1->amountoutstanding,
1120         -20, 'Credit has an amount outstanding of -20' );
1121
1122     my $reduce_params = {
1123         interface      => 'commandline',
1124         reduction_type => 'DISCOUNT',
1125         amount         => 5,
1126         staff_id       => $staff->borrowernumber,
1127         branch         => $branchcode
1128     };
1129
1130     throws_ok { $credit1->reduce($reduce_params); }
1131     'Koha::Exceptions::Account::IsNotDebit',
1132       '->reduce() can only be used with debits';
1133
1134     my @required = ( 'interface', 'reduction_type', 'amount' );
1135     for my $required (@required) {
1136         my $params = {%$reduce_params};
1137         delete( $params->{$required} );
1138         throws_ok {
1139             $debit1->reduce($params);
1140         }
1141         'Koha::Exceptions::MissingParameter',
1142           "->reduce() requires the `$required` parameter is passed";
1143     }
1144
1145     $reduce_params->{interface} = 'intranet';
1146     my @dependant_required = ( 'staff_id', 'branch' );
1147     for my $d (@dependant_required) {
1148         my $params = {%$reduce_params};
1149         delete( $params->{$d} );
1150         throws_ok {
1151             $debit1->reduce($params);
1152         }
1153         'Koha::Exceptions::MissingParameter',
1154 "->reduce() requires the `$d` parameter is passed when interface is intranet";
1155     }
1156
1157     throws_ok {
1158         $debit1->reduce(
1159             {
1160                 interface      => 'intranet',
1161                 staff_id       => $staff->borrowernumber,
1162                 branch         => $branchcode,
1163                 reduction_type => 'REFUND',
1164                 amount         => 25
1165             }
1166         );
1167     }
1168     'Koha::Exceptions::ParameterTooHigh',
1169       '->reduce() cannot reduce more than original amount';
1170
1171     # Partial Reduction
1172     # (Discount 5 on debt of 20)
1173     my $reduction = $debit1->reduce($reduce_params);
1174
1175     is( ref($reduction), 'Koha::Account::Line',
1176         '->reduce() returns a Koha::Account::Line' );
1177     is( $reduction->amount() * 1, -5, "Reduce amount is -5" );
1178     is( $reduction->amountoutstanding() * 1,
1179         0, "Reduce amountoutstanding is 0" );
1180     is( $debit1->amountoutstanding() * 1,
1181         15, "Debit amountoutstanding reduced by 5 to 15" );
1182     is( $debit1->status(), 'DISCOUNTED', "Debit status updated to DISCOUNTED");
1183     is( $account->balance() * 1, -5,        "Account balance is -5" );
1184     is( $reduction->status(),    'APPLIED', "Reduction status is 'APPLIED'" );
1185
1186     my $offsets = Koha::Account::Offsets->search(
1187         { credit_id => $reduction->id } );
1188     is( $offsets->count, 2, 'Two offsets generated' );
1189     my $THE_offset = $offsets->next;
1190     is( $THE_offset->type, 'CREATE', 'CREATE offset added for discount line');
1191     is( $THE_offset->amount * 1,
1192         -5, 'Correct offset amount recorded');
1193     $THE_offset = $offsets->next;
1194     is( $THE_offset->type, 'APPLY', "APPLY offset added for 'DISCOUNT'" );
1195     is( $THE_offset->amount * 1, -5, 'Correct amount offset against debt');
1196     is( $THE_offset->debit_id, $debit1->accountlines_id, 'APPLY offset recorded the correct debit_id');
1197
1198     # Zero offset created when zero outstanding
1199     # (Refund another 5 on paid debt of 20)
1200     $credit1->apply( { debits => [$debit1] } );
1201     is( $debit1->amountoutstanding + 0,
1202         0, 'Debit1 amountoutstanding reduced to 0' );
1203     $reduce_params->{reduction_type} = 'REFUND';
1204     $reduction = $debit1->reduce($reduce_params);
1205     is( $reduction->amount() * 1, -5, "Reduce amount is -5" );
1206     is( $reduction->amountoutstanding() * 1,
1207         -5, "Reduce amountoutstanding is -5" );
1208     is( $debit1->status(), 'REFUNDED', "Debit status updated to REFUNDED");
1209
1210     $offsets = Koha::Account::Offsets->search(
1211         { credit_id => $reduction->id } );
1212     is( $offsets->count, 2, 'Two offsets generated' );
1213     $THE_offset = $offsets->next;
1214     is( $THE_offset->type, 'CREATE', 'CREATE offset added for refund line');
1215     is( $THE_offset->amount * 1,
1216         -5, 'Correct offset amount recorded');
1217     $THE_offset = $offsets->next;
1218     is( $THE_offset->type, 'APPLY', "APPLY offset added for 'REFUND'" );
1219     is( $THE_offset->amount * 1,
1220         0, 'Zero offset created for already paid off debit' );
1221
1222     # Compound reduction should not allow more than original amount
1223     # (Reduction of 5 + 5 + 20 > 20)
1224     $reduce_params->{amount} = 20;
1225     throws_ok {
1226         $debit1->reduce($reduce_params);
1227     }
1228     'Koha::Exceptions::ParameterTooHigh',
1229 '->reduce cannot reduce more than the original amount (combined reductions test)';
1230
1231     # Throw exception if attempting to reduce a payout
1232     my $payout = $reduction->payout(
1233         {
1234             interface   => 'intranet',
1235             staff_id    => $staff->borrowernumber,
1236             branch      => $branchcode,
1237             payout_type => 'CASH',
1238             amount      => 5
1239         }
1240     );
1241     throws_ok {
1242         $payout->reduce($reduce_params);
1243     }
1244     'Koha::Exceptions::Account::IsNotDebit',
1245       '->reduce() cannot be used on a payout debit';
1246
1247     $schema->storage->txn_rollback;
1248 };
1249
1250 subtest "cancel() tests" => sub {
1251     plan tests => 18;
1252
1253     $schema->storage->txn_begin;
1254
1255     my $library = $builder->build_object( { class => 'Koha::Libraries' });
1256     my $patron  = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library->branchcode } });
1257     my $staff   = $builder->build_object({ class => 'Koha::Patrons', value => { branchcode => $library->branchcode } });
1258
1259     t::lib::Mocks::mock_userenv({ patron => $patron });
1260
1261     my $account = Koha::Account->new( { patron_id => $patron->borrowernumber } );
1262
1263     my $debit1 = Koha::Account::Line->new(
1264         {
1265             borrowernumber    => $patron->borrowernumber,
1266             amount            => 10,
1267             amountoutstanding => 10,
1268             interface         => 'commandline',
1269             debit_type_code   => 'OVERDUE',
1270         }
1271     )->store();
1272     my $debit2 = Koha::Account::Line->new(
1273         {
1274             borrowernumber    => $patron->borrowernumber,
1275             amount            => 20,
1276             amountoutstanding => 20,
1277             interface         => 'commandline',
1278             debit_type_code   => 'OVERDUE',
1279         }
1280     )->store();
1281
1282     my $ret = $account->pay(
1283         {
1284             lines  => [$debit2],
1285             amount => 5,
1286         }
1287     );
1288     my $credit = Koha::Account::Lines->find({ accountlines_id => $ret->{payment_id} });
1289
1290     is( $account->balance(), 25, "Account balance is 25" );
1291     is( $debit1->amountoutstanding + 0,
1292         10, 'First fee has amount outstanding of 10' );
1293     is( $debit2->amountoutstanding + 0,
1294         15, 'Second fee has amount outstanding of 15' );
1295     throws_ok {
1296         $credit->cancel(
1297             { staff_id => $staff->borrowernumber, branch => $library->branchcode } );
1298     }
1299     'Koha::Exceptions::Account::IsNotDebit',
1300       '->cancel() can only be used with debits';
1301
1302     throws_ok {
1303         $debit1->reduce( { staff_id => $staff->borrowernumber } );
1304     }
1305     'Koha::Exceptions::MissingParameter',
1306       "->cancel() requires the `branch` parameter is passed";
1307     throws_ok {
1308         $debit1->reduce( { branch => $library->branchcode } );
1309     }
1310     'Koha::Exceptions::MissingParameter',
1311       "->cancel() requires the `staff_id` parameter is passed";
1312
1313     throws_ok {
1314         $debit2->cancel(
1315             { staff_id => $staff->borrowernumber, branch => $library->branchcode } );
1316     }
1317     'Koha::Exceptions::Account',
1318       '->cancel() can only be used with debits that have not been offset';
1319
1320     my $cancellation = $debit1->cancel(
1321         { staff_id => $staff->borrowernumber, branch => $library->branchcode } );
1322     is( ref($cancellation), 'Koha::Account::Line',
1323         'Cancel returns an account line' );
1324     is(
1325         $cancellation->amount() * 1,
1326         $debit1->amount * -1,
1327         "Cancellation amount is " . $debit1->amount
1328     );
1329     is( $cancellation->amountoutstanding() * 1,
1330         0, "Cancellation amountoutstanding is 0" );
1331     is( $debit1->amountoutstanding() * 1,
1332         0, "Debit amountoutstanding reduced to 0" );
1333     is( $debit1->status(), 'CANCELLED', "Debit status updated to CANCELLED" );
1334     is( $account->balance() * 1, 15, "Account balance is 15" );
1335
1336     my $offsets = Koha::Account::Offsets->search(
1337         { credit_id => $cancellation->id } );
1338     is( $offsets->count, 2, 'Two offsets are generated' );
1339     my $THE_offset = $offsets->next;
1340     is( $THE_offset->type, 'CREATE', 'CREATE offset added for cancel line');
1341     is( $THE_offset->amount * 1, -10, 'Correct offset amount recorded' );
1342     $THE_offset = $offsets->next;
1343     is( $THE_offset->type, 'APPLY', "APPLY offset added" );
1344     is( $THE_offset->amount * 1,
1345         -10, 'Correct amount was applied against debit' );
1346
1347     $schema->storage->txn_rollback;
1348 };
1349
1350 1;