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