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