Bug 27636: (QA follow-up) Fix tests and validate
[koha-ffzg.git] / t / db_dependent / Accounts.t
1 #!/usr/bin/perl
2
3 # Copyright 2015 BibLibre
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 3 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, see <http://www.gnu.org/licenses>.
18
19 use Modern::Perl;
20
21 use Test::More tests => 27;
22 use Test::MockModule;
23 use Test::Exception;
24 use Test::Warn;
25
26 use t::lib::TestBuilder;
27 use t::lib::Mocks;
28
29 use Koha::Account;
30 use Koha::Account::DebitTypes;
31 use Koha::Account::Lines;
32 use Koha::Account::Offsets;
33 use Koha::Notice::Messages;
34 use Koha::Notice::Templates;
35 use Koha::DateUtils qw( dt_from_string );
36
37 use C4::Circulation qw( MarkIssueReturned );
38
39 BEGIN {
40     use_ok('C4::Accounts');
41     use_ok('Koha::Object');
42     use_ok('Koha::Patron');
43     use_ok('Data::Dumper');
44 }
45
46 can_ok( 'C4::Accounts',
47     qw(
48         chargelostitem
49         purge_zero_balance_fees )
50 );
51
52 my $schema  = Koha::Database->new->schema;
53 $schema->storage->txn_begin;
54 my $dbh = C4::Context->dbh;
55
56 my $builder = t::lib::TestBuilder->new;
57 my $library = $builder->build( { source => 'Branch' } );
58
59 my $branchcode = $library->{branchcode};
60
61 my $context = Test::MockModule->new('C4::Context');
62 $context->mock( 'userenv', sub {
63     return {
64         flags  => 1,
65         id     => 'my_userid',
66         branch => $branchcode,
67     };
68 });
69 $context->mock( 'interface', sub { return "commandline" } );
70 my $userenv_branchcode = $branchcode;
71
72 # Testing purge_zero_balance_fees
73
74 # The 3rd value in the insert is 'days ago' --
75 # 0 => today
76 # 1 => yesterday
77 # etc.
78
79 my $sth = $dbh->prepare(
80     "INSERT INTO accountlines (
81          borrowernumber,
82          amountoutstanding,
83          date,
84          description,
85          interface,
86          credit_type_code,
87          debit_type_code
88      )
89      VALUES ( ?, ?, (select date_sub(CURRENT_DATE, INTERVAL ? DAY) ), ?, ?, ?, ? )"
90 );
91
92 my $days = 5;
93
94 my @test_data = (
95     { amount => 0     , days_ago => 0         , description =>'purge_zero_balance_fees should not delete 0 balance fees with date today'                     , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
96     { amount => 0     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete 0 balance fees with date before threshold day'      , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
97     { amount => 0     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete 0 balance fees with date on threshold day'          , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
98     { amount => 0     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete 0 balance fees with date after threshold day'           , delete => 1, credit_type => undef, debit_type => 'OVERDUE' } ,
99     { amount => undef , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete NULL balance fees with date after threshold day'        , delete => 1, credit_type => undef, debit_type => 'OVERDUE' } ,
100     { amount => 5     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed before threshold day' , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
101     { amount => 5     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with positive amout owed on threshold day'     , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
102     { amount => 5     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed after threshold day'  , delete => 0, credit_type => undef, debit_type => 'OVERDUE' } ,
103     { amount => -5    , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed before threshold day' , delete => 0, credit_type => 'PAYMENT', debit_type => undef } ,
104     { amount => -5    , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with negative amout owed on threshold day'     , delete => 0, credit_type => 'PAYMENT', debit_type => undef } ,
105     { amount => -5    , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed after threshold day'  , delete => 0, credit_type => 'PAYMENT', debit_type => undef }
106 );
107 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
108 my $borrower = Koha::Patron->new( { firstname => 'Test', surname => 'Patron', categorycode => $categorycode, branchcode => $branchcode } )->store();
109
110 for my $data ( @test_data ) {
111     $sth->execute(
112         $borrower->borrowernumber,
113         $data->{amount},
114         $data->{days_ago},
115         $data->{description},
116         'commandline',
117         $data->{credit_type},
118         $data->{debit_type}
119     );
120 }
121
122 purge_zero_balance_fees( $days );
123
124 $sth = $dbh->prepare(
125             "select count(*) = 0 as deleted
126              from accountlines
127              where description = ?"
128        );
129
130 #
131 sub is_delete_correct {
132     my $should_delete = shift;
133     my $description = shift;
134     $sth->execute( $description );
135     my $test = $sth->fetchrow_hashref();
136     is( $test->{deleted}, $should_delete, $description )
137 }
138
139 for my $data  (@test_data) {
140     is_delete_correct( $data->{delete}, $data->{description});
141 }
142
143 $dbh->do(q|DELETE FROM accountlines|);
144
145 subtest "Koha::Account::pay tests" => sub {
146
147     plan tests => 13;
148
149     # Create a borrower
150     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
151     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
152
153     my $borrower = Koha::Patron->new( {
154         cardnumber => '1234567890',
155         surname => 'McFly',
156         firstname => 'Marty',
157     } );
158     $borrower->categorycode( $categorycode );
159     $borrower->branchcode( $branchcode );
160     $borrower->store;
161
162     my $account = Koha::Account->new({ patron_id => $borrower->id });
163
164     my $line1 = $account->add_debit({ type => 'ACCOUNT', amount => 100, interface => 'commandline' });
165     my $line2 = $account->add_debit({ type => 'ACCOUNT', amount => 200, interface => 'commandline' });
166
167     $sth = $dbh->prepare("SELECT count(*) FROM accountlines");
168     $sth->execute;
169     my $count = $sth->fetchrow_array;
170     is($count, 2, 'There is 2 lines as expected');
171
172     # There is $100 in the account
173     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
174     my $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
175     my $amountleft = 0;
176     for my $line ( @$amountoutstanding ) {
177         $amountleft += $line;
178     }
179     is($amountleft, 300, 'The account has 300$ as expected' );
180
181     # We make a $20 payment
182     my $borrowernumber = $borrower->borrowernumber;
183     my $data = '20.00';
184     my $payment_note = '$20.00 payment note';
185     my $id = $account->pay( { amount => $data, note => $payment_note, payment_type => "TEST_TYPE" } )->{payment_id};
186
187     my $accountline = Koha::Account::Lines->find( $id );
188     is( $accountline->payment_type, "TEST_TYPE", "Payment type passed into pay is set in account line correctly" );
189
190     # There is now $280 in the account
191     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
192     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
193     $amountleft = 0;
194     for my $line ( @$amountoutstanding ) {
195         $amountleft += $line;
196     }
197     is($amountleft, 280, 'The account has $280 as expected' );
198
199     # Is the payment note well registered
200     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
201     $sth->execute($borrower->borrowernumber);
202     my $note = $sth->fetchrow_array;
203     is($note,'$20.00 payment note', '$20.00 payment note is registered');
204
205     # We attempt to make a -$30 payment (a NEGATIVE payment)
206     $data = '-30.00';
207     $payment_note = '-$30.00 payment note';
208     throws_ok { $account->pay( { amount => $data, note => $payment_note } ) } qr//, 'Croaked on call to pay with negative amount';
209
210     #We make a $150 payment ( > 1stLine )
211     $data = '150.00';
212     $payment_note = '$150.00 payment note';
213     $account->pay( { amount => $data, note => $payment_note } );
214
215     # There is now $130 in the account
216     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
217     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
218     $amountleft = 0;
219     for my $line ( @$amountoutstanding ) {
220         $amountleft += $line;
221     }
222     is($amountleft, 130, 'The account has $130 as expected' );
223
224     # Is the payment note well registered
225     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
226     $sth->execute($borrower->borrowernumber);
227     $note = $sth->fetchrow_array;
228     is($note,'$150.00 payment note', '$150.00 payment note is registered');
229
230     #We make a $200 payment ( > amountleft )
231     $data = '200.00';
232     $payment_note = '$200.00 payment note';
233     $account->pay( { amount => $data, note => $payment_note } );
234
235     # There is now -$70 in the account
236     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
237     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
238     $amountleft = 0;
239     for my $line ( @$amountoutstanding ) {
240         $amountleft += $line;
241     }
242     is($amountleft, -70, 'The account has -$70 as expected, (credit situation)' );
243
244     # Is the payment note well registered
245     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
246     $sth->execute($borrower->borrowernumber);
247     $note = $sth->fetchrow_array;
248     is($note,'$200.00 payment note', '$200.00 payment note is registered');
249
250     my $line3 = $account->add_debit({ type => 'ACCOUNT', amount => 42, interface => 'commandline' });
251     my $payment_id = $account->pay( { lines => [$line3], amount => 42 } )->{payment_id};
252     my $payment = Koha::Account::Lines->find( $payment_id );
253     is( $payment->amount()+0, -42, "Payment paid the specified fine" );
254     $line3 = Koha::Account::Lines->find( $line3->id );
255     is( $line3->amountoutstanding+0, 0, "Specified fine is paid" );
256     is( $payment->branchcode, undef, 'branchcode passed, then undef' );
257 };
258
259 subtest "Koha::Account::pay particular line tests" => sub {
260
261     plan tests => 5;
262
263     # Create a borrower
264     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
265     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
266
267     my $borrower = Koha::Patron->new( {
268         cardnumber => 'kylemhall',
269         surname => 'Hall',
270         firstname => 'Kyle',
271     } );
272     $borrower->categorycode( $categorycode );
273     $borrower->branchcode( $branchcode );
274     $borrower->store;
275
276     my $account = Koha::Account->new({ patron_id => $borrower->id });
277
278     my $line1 = $account->add_debit({ type => 'ACCOUNT', amount => 1, interface => 'commandline' });
279     my $line2 = $account->add_debit({ type => 'ACCOUNT', amount => 2, interface => 'commandline' });
280     my $line3 = $account->add_debit({ type => 'ACCOUNT', amount => 3, interface => 'commandline' });
281     my $line4 = $account->add_debit({ type => 'ACCOUNT', amount => 4, interface => 'commandline' });
282
283     is( $account->balance(), 10, "Account balance is 10" );
284
285     $account->pay(
286         {
287             lines => [$line2, $line3, $line4],
288             amount => 4,
289         }
290     );
291
292     $_->_result->discard_changes foreach ( $line1, $line2, $line3, $line4 );
293
294     # Line1 is not paid at all, as it was not passed in the lines param
295     is( $line1->amountoutstanding+0, 1, "Line 1 was not paid" );
296     # Line2 was paid in full, as it was the first in the lines list
297     is( $line2->amountoutstanding+0, 0, "Line 2 was paid in full" );
298     # Line3 was paid partially, as the remaining balance did not cover it entirely
299     is( $line3->amountoutstanding+0, 1, "Line 3 was paid to 1.00" );
300     # Line4 was not paid at all, as the payment was all used up by that point
301     is( $line4->amountoutstanding+0, 4, "Line 4 was not paid" );
302 };
303
304 subtest "Koha::Account::pay writeoff tests" => sub {
305
306     plan tests => 5;
307
308     # Create a borrower
309     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
310     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
311
312     my $borrower = Koha::Patron->new( {
313         cardnumber => 'chelseahall',
314         surname => 'Hall',
315         firstname => 'Chelsea',
316     } );
317     $borrower->categorycode( $categorycode );
318     $borrower->branchcode( $branchcode );
319     $borrower->store;
320
321     my $account = Koha::Account->new({ patron_id => $borrower->id });
322
323     my $line = $account->add_debit({ type => 'ACCOUNT', amount => 42, interface => 'commandline' });
324
325     is( $account->balance(), 42, "Account balance is 42" );
326
327     my $id = $account->pay(
328         {
329             lines  => [$line],
330             amount => 42,
331             type   => 'WRITEOFF',
332         }
333     )->{payment_id};
334
335     $line->_result->discard_changes();
336
337     is( $line->amountoutstanding+0, 0, "Line was written off" );
338
339     my $writeoff = Koha::Account::Lines->find( $id );
340
341     is( $writeoff->credit_type_code, 'WRITEOFF', 'Type is correct for WRITEOFF' );
342     is( $writeoff->description, '', 'Description is correct' );
343     is( $writeoff->amount+0, -42, 'Amount is correct' );
344 };
345
346 subtest "More Koha::Account::pay tests" => sub {
347
348     plan tests => 8;
349
350     # Create a borrower
351     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
352     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
353     $branchcode = $branch;
354     my $borrowernumber = $builder->build({
355         source => 'Borrower',
356         value  => { categorycode => $category,
357                     branchcode   => $branch }
358     })->{ borrowernumber };
359
360     my $amount = 100;
361     my $accountline = $builder->build(
362         {
363             source => 'Accountline',
364             value  => {
365                 borrowernumber    => $borrowernumber,
366                 amount            => $amount,
367                 amountoutstanding => $amount,
368                 credit_type_code  => undef,
369             }
370         }
371     );
372
373     my $rs = $schema->resultset('Accountline')->search({
374         borrowernumber => $borrowernumber
375     });
376
377     is( $rs->count(), 1, 'Accountline created' );
378
379     my $account = Koha::Account->new( { patron_id => $borrowernumber } );
380     my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } );
381     # make the full payment
382     $account->pay({ lines => [$line], amount => $amount, library_id => $branch, note => 'A payment note' });
383
384     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->{accountlines_id} })->next();
385     is( $offset->amount+0, -100, 'Offset amount is -100.00' );
386     is( $offset->type(), 'Payment', 'Offset type is Payment' );
387
388     my $stat = $schema->resultset('Statistic')->search({
389         branch  => $branch,
390         type    => 'PAYMENT'
391     }, { order_by => { -desc => 'datetime' } })->next();
392
393     ok( defined $stat, "There's a payment log that matches the branch" );
394
395     SKIP: {
396         skip "No statistic logged", 4 unless defined $stat;
397
398         is( $stat->type, 'payment', "Correct statistic type" );
399         is( $stat->branch, $branch, "Correct branch logged to statistics" );
400         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
401         is( $stat->value+0, -$amount, "Correct amount logged to statistics" );
402     }
403 };
404
405 subtest "Even more Koha::Account::pay tests" => sub {
406
407     plan tests => 8;
408
409     # Create a borrower
410     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
411     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
412     $branchcode = $branch;
413     my $borrowernumber = $builder->build({
414         source => 'Borrower',
415         value  => { categorycode => $category,
416                     branchcode   => $branch }
417     })->{ borrowernumber };
418
419     my $amount = 100;
420     my $partialamount = 60;
421     my $accountline = $builder->build(
422         {
423             source => 'Accountline',
424             value  => {
425                 borrowernumber    => $borrowernumber,
426                 amount            => $amount,
427                 amountoutstanding => $amount,
428                 credit_type_code  => undef,
429             }
430         }
431     );
432
433     my $rs = $schema->resultset('Accountline')->search({
434         borrowernumber => $borrowernumber
435     });
436
437     is( $rs->count(), 1, 'Accountline created' );
438
439     my $account = Koha::Account->new( { patron_id => $borrowernumber } );
440     my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } );
441     # make the full payment
442     $account->pay({ lines => [$line], amount => $partialamount, library_id => $branch, note => 'A payment note' });
443
444     my $offset = Koha::Account::Offsets->search( { debit_id => $accountline->{ accountlines_id } } )->next();
445     is( $offset->amount+0, -60, 'Offset amount is -60.00' );
446     is( $offset->type, 'Payment', 'Offset type is payment' );
447
448     my $stat = $schema->resultset('Statistic')->search({
449         branch  => $branch,
450         type    => 'PAYMENT'
451     }, { order_by => { -desc => 'datetime' } })->next();
452
453     ok( defined $stat, "There's a payment log that matches the branch" );
454
455     SKIP: {
456         skip "No statistic logged", 4 unless defined $stat;
457
458         is( $stat->type, 'payment', "Correct statistic type" );
459         is( $stat->branch, $branch, "Correct branch logged to statistics" );
460         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
461         is( $stat->value+0, -$partialamount, "Correct amount logged to statistics" );
462     }
463 };
464
465 subtest 'balance' => sub {
466     plan tests => 2;
467
468     my $patron = $builder->build({source => 'Borrower'});
469     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
470     my $account = $patron->account;
471     is( $account->balance, 0, 'balance should return 0 if the patron does not have fines' );
472
473     my $accountline_1 = $builder->build(
474         {
475             source => 'Accountline',
476             value  => {
477                 borrowernumber    => $patron->borrowernumber,
478                 amount            => 42,
479                 amountoutstanding => 42,
480                 credit_type_code  => undef,
481             }
482         }
483     );
484     my $accountline_2 = $builder->build(
485         {
486             source => 'Accountline',
487             value  => {
488                 borrowernumber    => $patron->borrowernumber,
489                 amount            => -13,
490                 amountoutstanding => -13,
491                 debit_type_code   => undef,
492             }
493         }
494     );
495
496     my $balance = $patron->account->balance;
497     is( int($balance), 29, 'balance should return the correct value');
498
499     $patron->delete;
500 };
501
502 subtest "C4::Accounts::chargelostitem tests" => sub {
503     plan tests => 3;
504
505     my $branch = $builder->build( { source => 'Branch' } );
506     my $branchcode = $branch->{branchcode};
507
508     my $staff = $builder->build( { source => 'Borrower' } );
509     my $staff_id = $staff->{borrowernumber};
510
511     my $module = Test::MockModule->new('C4::Context');
512     $module->mock(
513         'userenv',
514         sub {
515             return {
516                 flags  => 1,
517                 number => $staff_id,
518                 branch => $branchcode,
519             };
520         }
521     );
522
523     my $itype_no_replace_no_fee = $builder->build({ source => 'Itemtype', value => {
524             rentalcharge => 0,
525             defaultreplacecost => undef,
526             processfee => undef,
527     }});
528     my $itype_replace_no_fee = $builder->build({ source => 'Itemtype', value => {
529             rentalcharge => 0,
530             defaultreplacecost => 16.32,
531             processfee => undef,
532     }});
533     my $itype_no_replace_fee = $builder->build({ source => 'Itemtype', value => {
534             rentalcharge => 0,
535             defaultreplacecost => undef,
536             processfee => 8.16,
537     }});
538     my $itype_replace_fee = $builder->build({ source => 'Itemtype', value => {
539             rentalcharge => 0,
540             defaultreplacecost => 4.08,
541             processfee => 2.04,
542     }});
543     my $cli_borrowernumber = $builder->build({ source => 'Borrower' })->{'borrowernumber'};
544     my $cli_itemnumber1 = $builder->build_sample_item({ itype => $itype_no_replace_no_fee->{itemtype} })->itemnumber;
545     my $cli_itemnumber2 = $builder->build_sample_item({ itype => $itype_replace_no_fee->{itemtype} })->itemnumber;
546     my $cli_itemnumber3 = $builder->build_sample_item({ itype => $itype_no_replace_fee->{itemtype} })->itemnumber;
547     my $cli_itemnumber4 = $builder->build_sample_item({ itype => $itype_replace_fee->{itemtype} })->itemnumber;
548
549     my $cli_issue_id_1 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1 } })->{issue_id};
550     my $cli_issue_id_2 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2 } })->{issue_id};
551     my $cli_issue_id_3 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3 } })->{issue_id};
552     my $cli_issue_id_4 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id};
553     my $cli_issue_id_4X = undef;
554
555     my $lostfine;
556     my $procfee;
557
558     subtest "fee application tests" => sub {
559         plan tests => 44;
560
561         t::lib::Mocks::mock_preference('item-level_itypes', '1');
562         t::lib::Mocks::mock_preference('useDefaultReplacementCost', '0');
563
564         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor");
565         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
566         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' });
567         ok( !$lostfine, "No lost fine if no replacementcost or default when pref off");
568         ok( !$procfee,  "No processing fee if no processing fee");
569         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor");
570         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
571         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' });
572         ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and no default set");
573         ok( !$procfee,  "No processing fee if no processing fee");
574         $lostfine->delete();
575
576         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor");
577         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
578         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' });
579         ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off");
580         ok( !$procfee,  "No processing fee if no processing fee");
581         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor");
582         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
583         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' });
584         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set");
585         ok( !$procfee,  "No processing fee if no processing fee");
586         $lostfine->delete();
587
588         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor");
589         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
590         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' });
591         ok( !$lostfine, "No lost fine if no replacementcost and no default set when pref off");
592         ok( $procfee->amount == 8.16,  "Processing fee if processing fee");
593         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
594         $procfee->delete();
595         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor");
596         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
597         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' });
598         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and no default set");
599         ok( $procfee->amount == 8.16,  "Processing fee if processing fee");
600         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
601         $lostfine->delete();
602         $procfee->delete();
603
604         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
605         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
606         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
607         ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off");
608         ok( $procfee->amount == 2.04,  "Processing fee if processing fee");
609         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
610         $procfee->delete();
611         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
612         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
613         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
614         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set");
615         ok( $procfee->amount == 2.04,  "Processing fee if processing fee");
616         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
617         $lostfine->delete();
618         $procfee->delete();
619
620         t::lib::Mocks::mock_preference('useDefaultReplacementCost', '1');
621
622         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor");
623         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
624         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' });
625         ok( !$lostfine, "No lost fine if no replacementcost or default when pref on");
626         ok( !$procfee,  "No processing fee if no processing fee");
627         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor");
628         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
629         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PROCESSING' });
630         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set");
631         ok( !$procfee,  "No processing fee if no processing fee");
632
633         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor");
634         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
635         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' });
636         is( $lostfine->amount(), "16.320000", "Lost fine is default if no replacementcost but default set when pref on");
637         ok( !$procfee,  "No processing fee if no processing fee");
638         $lostfine->delete();
639         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor");
640         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
641         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PROCESSING' });
642         is( $lostfine->amount, "6.120000" , "Lost fine equals replacementcost when pref on and default set");
643         ok( !$procfee,  "No processing fee if no processing fee");
644
645         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor");
646         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
647         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' });
648         ok( !$lostfine, "No lost fine if no replacementcost and default not set when pref on");
649         is( $procfee->amount, "8.160000",  "Processing fee if processing fee");
650         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
651         $procfee->delete();
652         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor");
653         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
654         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PROCESSING' });
655         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set");
656         is( $procfee->amount, "8.160000",  "Processing fee if processing fee");
657         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
658
659         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
660         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
661         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
662         is( $lostfine->amount, "4.080000", "Lost fine is default if no replacementcost but default set when pref on");
663         is( $procfee->amount, "2.040000",  "Processing fee if processing fee");
664         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
665         $lostfine->delete();
666         $procfee->delete();
667         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
668         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
669         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
670         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set");
671         is( $procfee->amount, "2.040000",  "Processing fee if processing fee");
672         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
673         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
674         my $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
675         my $procfees  = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
676         ok( $lostfines->count == 1 , "Lost fine cannot be double charged for the same issue_id");
677         ok( $procfees->count == 1,  "Processing fee cannot be double charged for the same issue_id");
678         MarkIssueReturned($cli_borrowernumber, $cli_itemnumber4);
679         $cli_issue_id_4X = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id};
680         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
681         $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
682         $procfees  = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
683         ok( $lostfines->count == 2 , "Lost fine can be charged twice for the same item if they are distinct issue_id's");
684         ok( $procfees->count == 2,  "Processing fee can be charged twice for the same item if they are distinct issue_id's");
685         $lostfines->delete();
686         $procfees->delete();
687     };
688
689     subtest "basic fields tests" => sub {
690         plan tests => 12;
691
692         t::lib::Mocks::mock_preference('ProcessingFeeNote', 'Test Note');
693         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, '1.99', "Perdedor");
694
695         # Lost Item Fee
696         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
697         ok($lostfine, "Lost fine created");
698         is($lostfine->manager_id, $staff_id, "Lost fine manager_id set correctly");
699         is($lostfine->issue_id, $cli_issue_id_4X, "Lost fine issue_id set correctly");
700         is($lostfine->description, "Perdedor", "Lost fine issue_id set correctly");
701         is($lostfine->note, '', "Lost fine does not contain a note");
702         is($lostfine->branchcode, $branchcode, "Lost fine branchcode set correctly");
703
704         # Processing Fee
705         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
706         ok($procfee, "Processing fee created");
707         is($procfee->manager_id, $staff_id, "Processing fee manager_id set correctly");
708         is($procfee->issue_id, $cli_issue_id_4X, "Processing fee issue_id set correctly");
709         is($procfee->description, "Perdedor", "Processing fee issue_id set correctly");
710         is($procfee->note, C4::Context->preference("ProcessingFeeNote"), "Processing fee contains note matching ProcessingFeeNote");
711         is($procfee->branchcode, $branchcode, "Processing fee branchcode set correctly");
712         $lostfine->delete();
713         $procfee->delete();
714     };
715
716     subtest "FinesLog tests" => sub {
717         plan tests => 2;
718
719         my $action_logs = $schema->resultset('ActionLog')->search()->count;
720
721         t::lib::Mocks::mock_preference( 'FinesLog', 0 );
722         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
723         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
724         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
725         is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No logs were added' );
726         $lostfine->delete();
727         $procfee->delete();
728
729         t::lib::Mocks::mock_preference( 'FinesLog', 1 );
730         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
731         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
732         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PROCESSING' });
733         is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Logs were added' );
734         $lostfine->delete();
735         $procfee->delete();
736     };
737
738     # Cleanup - this must be replaced with a transaction per subtest
739     Koha::Patrons->find($cli_borrowernumber)->checkouts->delete;
740 };
741
742 subtest "Koha::Account::non_issues_charges tests" => sub {
743     plan tests => 21;
744
745     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
746     my $account = $patron->account;
747
748     my $res    = 3;
749     my $rent   = 5;
750     my $manual = 7;
751     $account->add_debit(
752         {
753             description => 'a Res fee',
754             type        => 'RESERVE',
755             amount      => $res,
756             interface   => 'commandline'
757         }
758     );
759     $account->add_debit(
760         {
761             description => 'a Rental fee',
762             type        => 'RENT',
763             amount      => $rent,
764             interface   => 'commandline'
765         }
766     );
767     Koha::Account::DebitTypes->find_or_create(
768         {
769             code        => 'Copie',
770             description => 'Fee for copie',
771             is_system   => 0
772         }
773     )->store;
774     Koha::Account::Line->new(
775         {
776             borrowernumber    => $patron->borrowernumber,
777             description       => 'a Manual invoice fee',
778             debit_type_code   => 'Copie',
779             amountoutstanding => $manual,
780             interface         => 'commandline'
781         }
782     )->store;
783
784
785     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   0 );
786     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 0 );
787     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  0 );
788     my ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
789     my $other_charges = $total - $non_issues_charges;
790     is(
791         $account->balance,
792         $res + $rent + $manual,
793         'Total charges should be Res + Rent + Manual'
794     );
795     is( $non_issues_charges, 0,
796         'If 0|0|0 there should not have non issues charges' );
797     is( $other_charges, 15, 'If 0|0|0 there should only have other charges' );
798
799     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   0 );
800     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 0 );
801     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  1 );
802     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
803     $other_charges = $total - $non_issues_charges;
804     is(
805         $total,
806         $res + $rent + $manual,
807         'Total charges should be Res + Rent + Manual'
808     );
809     is( $non_issues_charges, $manual,
810         'If 0|0|1 Only Manual should be a non issue charge' );
811     is(
812         $other_charges,
813         $res + $rent,
814         'If 0|0|1 Res + Rent should be other charges'
815     );
816
817     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   0 );
818     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 1 );
819     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  0 );
820     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
821     $other_charges = $total - $non_issues_charges;
822     is(
823         $total,
824         $res + $rent + $manual,
825         'Total charges should be Res + Rent + Manual'
826     );
827     is( $non_issues_charges, $rent,
828         'If 0|1|0 Only Rental should be a non issue charge' );
829     is(
830         $other_charges,
831         $res + $manual,
832         'If 0|1|0 Rent + Manual should be other charges'
833     );
834
835     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   0 );
836     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 1 );
837     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  1 );
838     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
839     $other_charges = $total - $non_issues_charges;
840     is(
841         $total,
842         $res + $rent + $manual,
843         'Total charges should be Res + Rent + Manual'
844     );
845     is(
846         $non_issues_charges,
847         $rent + $manual,
848         'If 0|1|1 Rent + Manual should be non issues charges'
849     );
850     is( $other_charges, $res, 'If 0|1|1 there should only have other charges' );
851
852     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   1 );
853     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 0 );
854     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  0 );
855     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
856     $other_charges = $total - $non_issues_charges;
857     is(
858         $total,
859         $res + $rent + $manual,
860         'Total charges should be Res + Rent + Manual'
861     );
862     is( $non_issues_charges, $res,
863         'If 1|0|0 Only Res should be non issues charges' );
864     is(
865         $other_charges,
866         $rent + $manual,
867         'If 1|0|0 Rent + Manual should be other charges'
868     );
869
870     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   1 );
871     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 1 );
872     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  0 );
873     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
874     $other_charges = $total - $non_issues_charges;
875     is(
876         $total,
877         $res + $rent + $manual,
878         'Total charges should be Res + Rent + Manual'
879     );
880     is(
881         $non_issues_charges,
882         $res + $rent,
883         'If 1|1|0 Res + Rent should be non issues charges'
884     );
885     is( $other_charges, $manual,
886         'If 1|1|0 Only Manual should be other charges' );
887
888     t::lib::Mocks::mock_preference( 'HoldsInNoissuesCharge',   1 );
889     t::lib::Mocks::mock_preference( 'RentalsInNoissuesCharge', 1 );
890     t::lib::Mocks::mock_preference( 'ManInvInNoissuesCharge',  1 );
891     ( $total, $non_issues_charges ) = ( $account->balance, $account->non_issues_charges );
892     $other_charges = $total - $non_issues_charges;
893     is(
894         $total,
895         $res + $rent + $manual,
896         'Total charges should be Res + Rent + Manual'
897     );
898     is(
899         $non_issues_charges,
900         $res + $rent + $manual,
901         'If 1|1|1 Res + Rent + Manual should be non issues charges'
902     );
903     is( $other_charges, 0, 'If 1|1|1 there should not have any other charges' );
904 };
905
906 subtest "Koha::Account::non_issues_charges tests" => sub {
907     plan tests => 9;
908
909     my $patron = $builder->build_object(
910         {
911             class => "Koha::Patrons",
912             value => {
913                 firstname    => 'Test',
914                 surname      => 'Patron',
915                 categorycode => $categorycode,
916                 branchcode   => $branchcode
917             }
918         }
919     );
920
921     my $debit = Koha::Account::Line->new(
922         {
923             borrowernumber    => $patron->id,
924             date              => '1970-01-01 00:00:01',
925             amountoutstanding => 0,
926             interface         => 'commandline',
927             debit_type_code   => 'LOST'
928         }
929     )->store();
930     my $credit = Koha::Account::Line->new(
931         {
932             borrowernumber    => $patron->id,
933             date              => '1970-01-01 00:00:01',
934             amountoutstanding => -5,
935             interface         => 'commandline',
936             credit_type_code  => 'PAYMENT'
937         }
938     )->store();
939     my $offset = Koha::Account::Offset->new(
940         {
941             credit_id => $credit->id,
942             debit_id  => $debit->id,
943             type      => 'Payment',
944             amount    => 0
945         }
946     )->store();
947     purge_zero_balance_fees( 1 );
948     my $debit_2 = Koha::Account::Lines->find( $debit->id );
949     my $credit_2 = Koha::Account::Lines->find( $credit->id );
950     ok( $debit_2, 'Debit was correctly not deleted when credit has balance' );
951     ok( $credit_2, 'Credit was correctly not deleted when credit has balance' );
952     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2, "The 2 account lines still exists" );
953
954     $debit = Koha::Account::Line->new(
955         {
956             borrowernumber    => $patron->id,
957             date              => '1970-01-01 00:00:01',
958             amountoutstanding => 5,
959             interface         => 'commanline',
960             debit_type_code   => 'LOST'
961         }
962     )->store();
963     $credit = Koha::Account::Line->new(
964         {
965             borrowernumber    => $patron->id,
966             date              => '1970-01-01 00:00:01',
967             amountoutstanding => 0,
968             interface         => 'commandline',
969             credit_type_code  => 'PAYMENT'
970         }
971     )->store();
972     $offset = Koha::Account::Offset->new(
973         {
974             credit_id => $credit->id,
975             debit_id  => $debit->id,
976             type      => 'Payment',
977             amount    => 0
978         }
979     )->store();
980     purge_zero_balance_fees( 1 );
981     $debit_2 = $credit_2 = undef;
982     $debit_2 = Koha::Account::Lines->find( $debit->id );
983     $credit_2 = Koha::Account::Lines->find( $credit->id );
984     ok( $debit_2, 'Debit was correctly not deleted when debit has balance' );
985     ok( $credit_2, 'Credit was correctly not deleted when debit has balance' );
986     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists" );
987
988     $debit = Koha::Account::Line->new(
989         {
990             borrowernumber    => $patron->id,
991             date              => '1970-01-01 00:00:01',
992             amountoutstanding => 0,
993             interface         => 'commandline',
994             debit_type_code   => 'LOST'
995         }
996     )->store();
997     $credit = Koha::Account::Line->new(
998         {
999             borrowernumber    => $patron->id,
1000             date              => '1970-01-01 00:00:01',
1001             amountoutstanding => 0,
1002             interface         => 'commandline',
1003             credit_type_code  => 'PAYMENT'
1004         }
1005     )->store();
1006     $offset = Koha::Account::Offset->new(
1007         {
1008             credit_id => $credit->id,
1009             debit_id  => $debit->id,
1010             type      => 'Payment',
1011             amount    => 0
1012         }
1013     )->store();
1014     purge_zero_balance_fees( 1 );
1015     $debit_2 = Koha::Account::Lines->find( $debit->id );
1016     $credit_2 = Koha::Account::Lines->find( $credit->id );
1017     ok( !$debit_2, 'Debit was correctly deleted' );
1018     ok( !$credit_2, 'Credit was correctly deleted' );
1019     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists, the last 2 have been deleted ok" );
1020 };
1021
1022
1023 subtest "Koha::Account::Offset credit & debit tests" => sub {
1024
1025     plan tests => 4;
1026
1027     # Create a borrower
1028     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
1029     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
1030
1031     my $borrower = Koha::Patron->new( {
1032         cardnumber => 'kyliehall',
1033         surname => 'Hall',
1034         firstname => 'Kylie',
1035     } );
1036     $borrower->categorycode( $categorycode );
1037     $borrower->branchcode( $branchcode );
1038     $borrower->store;
1039
1040     my $account = Koha::Account->new({ patron_id => $borrower->id });
1041
1042     my $line1 = Koha::Account::Line->new(
1043         {
1044             borrowernumber    => $borrower->borrowernumber,
1045             amount            => 10,
1046             amountoutstanding => 10,
1047             interface         => 'commandline',
1048             debit_type_code   => 'LOST'
1049         }
1050     )->store();
1051     my $line2 = Koha::Account::Line->new(
1052         {
1053             borrowernumber    => $borrower->borrowernumber,
1054             amount            => 20,
1055             amountoutstanding => 20,
1056             interface         => 'commandline',
1057             debit_type_code   => 'LOST'
1058         }
1059     )->store();
1060
1061     my $id = $account->pay(
1062         {
1063             lines  => [$line1, $line2],
1064             amount => 30,
1065         }
1066     )->{payment_id};
1067
1068     # Test debit and credit methods for Koha::Account::Offset
1069     my $account_offset = Koha::Account::Offsets->find( { credit_id => $id, debit_id => $line1->id } );
1070     is( $account_offset->debit->id, $line1->id, "Koha::Account::Offset->debit gets correct accountline" );
1071     is( $account_offset->credit->id, $id, "Koha::Account::Offset->credit gets correct accountline" );
1072
1073     $account_offset = Koha::Account::Offset->new(
1074         {
1075             credit_id => undef,
1076             debit_id  => undef,
1077             type      => 'Payment',
1078             amount    => 0,
1079         }
1080     )->store();
1081
1082     is( $account_offset->debit, undef, "Koha::Account::Offset->debit returns undef if no associated debit" );
1083     is( $account_offset->credit, undef, "Koha::Account::Offset->credit returns undef if no associated credit" );
1084 };
1085
1086 subtest "Payment notice tests" => sub {
1087
1088     plan tests => 8;
1089
1090     Koha::Notice::Messages->delete();
1091     # Create a patron
1092     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
1093
1094     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1095     my $context = Test::MockModule->new('C4::Context');
1096     $context->mock( 'userenv', sub {
1097         return {
1098             number     => $manager->borrowernumber,
1099             branch     => $manager->branchcode,
1100         };
1101     });
1102     my $account = Koha::Account->new({ patron_id => $patron->borrowernumber });
1103
1104     my $line = Koha::Account::Line->new(
1105         {
1106             borrowernumber    => $patron->borrowernumber,
1107             amountoutstanding => 27,
1108             interface         => 'commandline',
1109             debit_type_code   => 'LOST'
1110         }
1111     )->store();
1112
1113     my $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_PAYMENT' } );
1114     $letter->content('[%- USE Price -%]A payment of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]');
1115     $letter->store();
1116
1117     t::lib::Mocks::mock_preference('UseEmailReceipts', '0');
1118     my $id = $account->pay( { amount => 1 } )->{payment_id};
1119     is( Koha::Notice::Messages->search()->count(), 0, 'Notice for payment not sent if UseEmailReceipts is disabled' );
1120
1121     $id = $account->pay( { amount => 1, type => 'WRITEOFF' } )->{payment_id};
1122     is( Koha::Notice::Messages->search()->count(), 0, 'Notice for writeoff not sent if UseEmailReceipts is disabled' );
1123
1124     t::lib::Mocks::mock_preference('UseEmailReceipts', '1');
1125
1126     $id = $account->pay( { amount => 12, library_id => $branchcode } )->{payment_id};
1127     my $notice = Koha::Notice::Messages->search()->next();
1128     is( $notice->subject, 'Account payment', 'Notice subject is correct for payment' );
1129     is( $notice->letter_code, 'ACCOUNT_PAYMENT', 'Notice letter code is correct for payment' );
1130     is( $notice->content, "A payment of 12.00 has been applied to your account. Your $branchcode", 'Notice content is correct for payment' );
1131     $notice->delete();
1132
1133     $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_WRITEOFF' } );
1134     $letter->content('[%- USE Price -%]A writeoff of [% credit.amount * -1 | $Price %] has been applied to your account. Your [% branch.branchcode %]');
1135     $letter->store();
1136
1137     $id = $account->pay( { amount => 13, type => 'WRITEOFF', library_id => $branchcode  } )->{payment_id};
1138     $notice = Koha::Notice::Messages->search()->next();
1139     is( $notice->subject, 'Account writeoff', 'Notice subject is correct for payment' );
1140     is( $notice->letter_code, 'ACCOUNT_WRITEOFF', 'Notice letter code is correct for writeoff' );
1141     is( $notice->content, "A writeoff of 13.00 has been applied to your account. Your $branchcode", 'Notice content is correct for writeoff' );
1142 };
1143
1144 1;