Bug 23049: Update existing code to use debit_type
[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 => 33;
22 use Test::MockModule;
23 use Test::Warn;
24
25 use t::lib::TestBuilder;
26 use t::lib::Mocks;
27
28 use Koha::Account;
29 use Koha::Account::DebitTypes;
30 use Koha::Account::Lines;
31 use Koha::Account::Offsets;
32 use Koha::Notice::Messages;
33 use Koha::Notice::Templates;
34 use Koha::DateUtils qw( dt_from_string );
35
36 use C4::Circulation qw( MarkIssueReturned );
37
38 BEGIN {
39     use_ok('C4::Accounts');
40     use_ok('Koha::Object');
41     use_ok('Koha::Patron');
42     use_ok('Data::Dumper');
43 }
44
45 can_ok( 'C4::Accounts',
46     qw(
47         chargelostitem
48         manualinvoice
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 $dbh->do(q|DELETE FROM accountlines|);
60 $dbh->do(q|DELETE FROM issues|);
61 $dbh->do(q|DELETE FROM borrowers|);
62
63 my $branchcode = $library->{branchcode};
64 my $borrower_number;
65
66 my $context = new Test::MockModule('C4::Context');
67 $context->mock( 'userenv', sub {
68     return {
69         flags  => 1,
70         id     => 'my_userid',
71         branch => $branchcode,
72     };
73 });
74 $context->mock( 'interface', sub { return "commandline" } );
75 my $userenv_branchcode = $branchcode;
76
77 # Test manualinvoice
78 my $itemtype = $builder->build( { source => 'Itemtype' } );
79 my $item   = $builder->build( { source => 'Item', value => { itype => $itemtype->{itemtype} } } );
80 my $patron = $builder->build( { source => 'Borrower' } );
81 my $amount = '5.000000';
82 my $description = "Test fee!";
83 my $type = 'LOST';
84 my $note = 'Test note!';
85 warning_like {
86     C4::Accounts::manualinvoice( $patron->{borrowernumber},
87         $item->{itemnumber}, $description, $type, $amount, $note )
88 }
89 qr/C4::Accounts::manualinvoice is deprecated in favor of Koha::Account->add_debit/,
90   "deprecation warning received for manualinvoice";
91 my ($accountline) = Koha::Account::Lines->search(
92     {
93         borrowernumber => $patron->{borrowernumber}
94     }
95 );
96 is( $accountline->debit_type_code, $type, 'Debit type set correctly for manualinvoice' );
97 is( $accountline->amount, $amount, 'Accountline amount set correctly for manualinvoice' );
98 ok( $accountline->description =~ /^$description/, 'Accountline description set correctly for manualinvoice' );
99 is( $accountline->note, $note, 'Accountline note set correctly for manualinvoice' );
100 is( $accountline->branchcode, $branchcode, 'Accountline branchcode set correctly for manualinvoice' );
101
102 $dbh->do(q|DELETE FROM accountlines|);
103
104 # Testing purge_zero_balance_fees
105
106 # The 3rd value in the insert is 'days ago' --
107 # 0 => today
108 # 1 => yesterday
109 # etc.
110
111 my $sth = $dbh->prepare(
112     "INSERT INTO accountlines (
113          borrowernumber,
114          amountoutstanding,
115          date,
116          description,
117          interface
118      )
119      VALUES ( ?, ?, (select date_sub(CURRENT_DATE, INTERVAL ? DAY) ), ?, ? )"
120 );
121
122 my $days = 5;
123
124 my @test_data = (
125     { amount => 0     , days_ago => 0         , description =>'purge_zero_balance_fees should not delete 0 balance fees with date today'                     , delete => 0 } ,
126     { amount => 0     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete 0 balance fees with date before threshold day'      , delete => 0 } ,
127     { amount => 0     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete 0 balance fees with date on threshold day'          , delete => 0 } ,
128     { amount => 0     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete 0 balance fees with date after threshold day'           , delete => 1 } ,
129     { amount => undef , days_ago => $days + 1 , description =>'purge_zero_balance_fees should delete NULL balance fees with date after threshold day'        , delete => 1 } ,
130     { amount => 5     , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed before threshold day'  , delete => 0 } ,
131     { amount => 5     , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with positive amout owed on threshold day'      , delete => 0 } ,
132     { amount => 5     , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with positive amout owed after threshold day'   , delete => 0 } ,
133     { amount => -5    , days_ago => $days - 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed before threshold day' , delete => 0 } ,
134     { amount => -5    , days_ago => $days     , description =>'purge_zero_balance_fees should not delete fees with negative amout owed on threshold day'     , delete => 0 } ,
135     { amount => -5    , days_ago => $days + 1 , description =>'purge_zero_balance_fees should not delete fees with negative amout owed after threshold day'  , delete => 0 }
136 );
137 my $categorycode = $builder->build({ source => 'Category' })->{categorycode};
138 my $borrower = Koha::Patron->new( { firstname => 'Test', surname => 'Patron', categorycode => $categorycode, branchcode => $branchcode } )->store();
139
140 for my $data ( @test_data ) {
141     $sth->execute($borrower->borrowernumber, $data->{amount}, $data->{days_ago}, $data->{description}, 'commandline');
142 }
143
144 purge_zero_balance_fees( $days );
145
146 $sth = $dbh->prepare(
147             "select count(*) = 0 as deleted
148              from accountlines
149              where description = ?"
150        );
151
152 #
153 sub is_delete_correct {
154     my $should_delete = shift;
155     my $description = shift;
156     $sth->execute( $description );
157     my $test = $sth->fetchrow_hashref();
158     is( $test->{deleted}, $should_delete, $description )
159 }
160
161 for my $data  (@test_data) {
162     is_delete_correct( $data->{delete}, $data->{description});
163 }
164
165 $dbh->do(q|DELETE FROM accountlines|);
166
167 subtest "Koha::Account::pay tests" => sub {
168
169     plan tests => 14;
170
171     # Create a borrower
172     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
173     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
174
175     my $borrower = Koha::Patron->new( {
176         cardnumber => '1234567890',
177         surname => 'McFly',
178         firstname => 'Marty',
179     } );
180     $borrower->categorycode( $categorycode );
181     $borrower->branchcode( $branchcode );
182     $borrower->store;
183
184     my $account = Koha::Account->new({ patron_id => $borrower->id });
185
186     my $line1 = $account->add_debit({ type => 'account', amount => 100, interface => 'commandline' });
187     my $line2 = $account->add_debit({ type => 'account', amount => 200, interface => 'commandline' });
188
189     $sth = $dbh->prepare("SELECT count(*) FROM accountlines");
190     $sth->execute;
191     my $count = $sth->fetchrow_array;
192     is($count, 2, 'There is 2 lines as expected');
193
194     # There is $100 in the account
195     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
196     my $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
197     my $amountleft = 0;
198     for my $line ( @$amountoutstanding ) {
199         $amountleft += $line;
200     }
201     is($amountleft, 300, 'The account has 300$ as expected' );
202
203     # We make a $20 payment
204     my $borrowernumber = $borrower->borrowernumber;
205     my $data = '20.00';
206     my $payment_note = '$20.00 payment note';
207     my $id = $account->pay( { amount => $data, note => $payment_note, payment_type => "TEST_TYPE" } );
208
209     my $accountline = Koha::Account::Lines->find( $id );
210     is( $accountline->payment_type, "TEST_TYPE", "Payment type passed into pay is set in account line correctly" );
211
212     # There is now $280 in the account
213     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
214     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
215     $amountleft = 0;
216     for my $line ( @$amountoutstanding ) {
217         $amountleft += $line;
218     }
219     is($amountleft, 280, 'The account has $280 as expected' );
220
221     # Is the payment note well registered
222     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
223     $sth->execute($borrower->borrowernumber);
224     my $note = $sth->fetchrow_array;
225     is($note,'$20.00 payment note', '$20.00 payment note is registered');
226
227     # We make a -$30 payment (a NEGATIVE payment)
228     $data = '-30.00';
229     $payment_note = '-$30.00 payment note';
230     $account->pay( { amount => $data, note => $payment_note } );
231
232     # There is now $310 in the account
233     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
234     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
235     $amountleft = 0;
236     for my $line ( @$amountoutstanding ) {
237         $amountleft += $line;
238     }
239     is($amountleft, 310, 'The account has $310 as expected' );
240     # Is the payment note well registered
241     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
242     $sth->execute($borrower->borrowernumber);
243     $note = $sth->fetchrow_array;
244     is($note,'-$30.00 payment note', '-$30.00 payment note is registered');
245
246     #We make a $150 payment ( > 1stLine )
247     $data = '150.00';
248     $payment_note = '$150.00 payment note';
249     $account->pay( { amount => $data, note => $payment_note } );
250
251     # There is now $160 in the account
252     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
253     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
254     $amountleft = 0;
255     for my $line ( @$amountoutstanding ) {
256         $amountleft += $line;
257     }
258     is($amountleft, 160, 'The account has $160 as expected' );
259
260     # Is the payment note well registered
261     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
262     $sth->execute($borrower->borrowernumber);
263     $note = $sth->fetchrow_array;
264     is($note,'$150.00 payment note', '$150.00 payment note is registered');
265
266     #We make a $200 payment ( > amountleft )
267     $data = '200.00';
268     $payment_note = '$200.00 payment note';
269     $account->pay( { amount => $data, note => $payment_note } );
270
271     # There is now -$40 in the account
272     $sth = $dbh->prepare("SELECT amountoutstanding FROM accountlines WHERE borrowernumber=?");
273     $amountoutstanding = $dbh->selectcol_arrayref($sth, {}, $borrower->borrowernumber);
274     $amountleft = 0;
275     for my $line ( @$amountoutstanding ) {
276         $amountleft += $line;
277     }
278     is($amountleft, -40, 'The account has -$40 as expected, (credit situation)' );
279
280     # Is the payment note well registered
281     $sth = $dbh->prepare("SELECT note FROM accountlines WHERE borrowernumber=? ORDER BY accountlines_id DESC LIMIT 1");
282     $sth->execute($borrower->borrowernumber);
283     $note = $sth->fetchrow_array;
284     is($note,'$200.00 payment note', '$200.00 payment note is registered');
285
286     my $line3 = $account->add_debit({ type => 'account', amount => 42, interface => 'commandline' });
287     my $payment_id = $account->pay( { lines => [$line3], amount => 42 } );
288     my $payment = Koha::Account::Lines->find( $payment_id );
289     is( $payment->amount(), '-42.000000', "Payment paid the specified fine" );
290     $line3 = Koha::Account::Lines->find( $line3->id );
291     is( $line3->amountoutstanding, '0.000000', "Specified fine is paid" );
292     is( $payment->branchcode, undef, 'branchcode passed, then undef' );
293 };
294
295 subtest "Koha::Account::pay particular line tests" => sub {
296
297     plan tests => 5;
298
299     # Create a borrower
300     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
301     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
302
303     my $borrower = Koha::Patron->new( {
304         cardnumber => 'kylemhall',
305         surname => 'Hall',
306         firstname => 'Kyle',
307     } );
308     $borrower->categorycode( $categorycode );
309     $borrower->branchcode( $branchcode );
310     $borrower->store;
311
312     my $account = Koha::Account->new({ patron_id => $borrower->id });
313
314     my $line1 = $account->add_debit({ type => 'account', amount => 1, interface => 'commandline' });
315     my $line2 = $account->add_debit({ type => 'account', amount => 2, interface => 'commandline' });
316     my $line3 = $account->add_debit({ type => 'account', amount => 3, interface => 'commandline' });
317     my $line4 = $account->add_debit({ type => 'account', amount => 4, interface => 'commandline' });
318
319     is( $account->balance(), 10, "Account balance is 10" );
320
321     $account->pay(
322         {
323             lines => [$line2, $line3, $line4],
324             amount => 4,
325         }
326     );
327
328     $_->_result->discard_changes foreach ( $line1, $line2, $line3, $line4 );
329
330     # Line1 is not paid at all, as it was not passed in the lines param
331     is( $line1->amountoutstanding, "1.000000", "Line 1 was not paid" );
332     # Line2 was paid in full, as it was the first in the lines list
333     is( $line2->amountoutstanding, "0.000000", "Line 2 was paid in full" );
334     # Line3 was paid partially, as the remaining balance did not cover it entirely
335     is( $line3->amountoutstanding, "1.000000", "Line 3 was paid to 1.00" );
336     # Line4 was not paid at all, as the payment was all used up by that point
337     is( $line4->amountoutstanding, "4.000000", "Line 4 was not paid" );
338 };
339
340 subtest "Koha::Account::pay writeoff tests" => sub {
341
342     plan tests => 5;
343
344     # Create a borrower
345     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
346     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
347
348     my $borrower = Koha::Patron->new( {
349         cardnumber => 'chelseahall',
350         surname => 'Hall',
351         firstname => 'Chelsea',
352     } );
353     $borrower->categorycode( $categorycode );
354     $borrower->branchcode( $branchcode );
355     $borrower->store;
356
357     my $account = Koha::Account->new({ patron_id => $borrower->id });
358
359     my $line = $account->add_debit({ type => 'account', amount => 42, interface => 'commandline' });
360
361     is( $account->balance(), 42, "Account balance is 42" );
362
363     my $id = $account->pay(
364         {
365             lines  => [$line],
366             amount => 42,
367             type   => 'writeoff',
368         }
369     );
370
371     $line->_result->discard_changes();
372
373     is( $line->amountoutstanding, "0.000000", "Line was written off" );
374
375     my $writeoff = Koha::Account::Lines->find( $id );
376
377     is( $writeoff->accounttype, 'W', 'Type is correct for writeoff' );
378     is( $writeoff->description, 'Writeoff', 'Description is correct' );
379     is( $writeoff->amount, '-42.000000', 'Amount is correct' );
380 };
381
382 subtest "More Koha::Account::pay tests" => sub {
383
384     plan tests => 8;
385
386     # Create a borrower
387     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
388     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
389     $branchcode = $branch;
390     my $borrowernumber = $builder->build({
391         source => 'Borrower',
392         value  => { categorycode => $category,
393                     branchcode   => $branch }
394     })->{ borrowernumber };
395
396     my $amount = 100;
397     my $accountline = $builder->build({ source => 'Accountline',
398         value  => { borrowernumber => $borrowernumber,
399                     amount => $amount,
400                     amountoutstanding => $amount }
401     });
402
403     my $rs = $schema->resultset('Accountline')->search({
404         borrowernumber => $borrowernumber
405     });
406
407     is( $rs->count(), 1, 'Accountline created' );
408
409     my $account = Koha::Account->new( { patron_id => $borrowernumber } );
410     my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } );
411     # make the full payment
412     $account->pay({ lines => [$line], amount => $amount, library_id => $branch, note => 'A payment note' });
413
414     my $offset = Koha::Account::Offsets->search({ debit_id => $accountline->{accountlines_id} })->next();
415     is( $offset->amount(), '-100.000000', 'Offset amount is -100.00' );
416     is( $offset->type(), 'Payment', 'Offset type is Payment' );
417
418     my $stat = $schema->resultset('Statistic')->search({
419         branch  => $branch,
420         type    => 'payment'
421     }, { order_by => { -desc => 'datetime' } })->next();
422
423     ok( defined $stat, "There's a payment log that matches the branch" );
424
425     SKIP: {
426         skip "No statistic logged", 4 unless defined $stat;
427
428         is( $stat->type, 'payment', "Correct statistic type" );
429         is( $stat->branch, $branch, "Correct branch logged to statistics" );
430         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
431         is( $stat->value+0, $amount, "Correct amount logged to statistics" );
432     }
433 };
434
435 subtest "Even more Koha::Account::pay tests" => sub {
436
437     plan tests => 8;
438
439     # Create a borrower
440     my $category   = $builder->build({ source => 'Category' })->{ categorycode };
441     my $branch     = $builder->build({ source => 'Branch' })->{ branchcode };
442     $branchcode = $branch;
443     my $borrowernumber = $builder->build({
444         source => 'Borrower',
445         value  => { categorycode => $category,
446                     branchcode   => $branch }
447     })->{ borrowernumber };
448
449     my $amount = 100;
450     my $partialamount = 60;
451     my $accountline = $builder->build({ source => 'Accountline',
452         value  => { borrowernumber => $borrowernumber,
453                     amount => $amount,
454                     amountoutstanding => $amount }
455     });
456
457     my $rs = $schema->resultset('Accountline')->search({
458         borrowernumber => $borrowernumber
459     });
460
461     is( $rs->count(), 1, 'Accountline created' );
462
463     my $account = Koha::Account->new( { patron_id => $borrowernumber } );
464     my $line = Koha::Account::Lines->find( $accountline->{ accountlines_id } );
465     # make the full payment
466     $account->pay({ lines => [$line], amount => $partialamount, library_id => $branch, note => 'A payment note' });
467
468     my $offset = Koha::Account::Offsets->search( { debit_id => $accountline->{ accountlines_id } } )->next();
469     is( $offset->amount, '-60.000000', 'Offset amount is -60.00' );
470     is( $offset->type, 'Payment', 'Offset type is payment' );
471
472     my $stat = $schema->resultset('Statistic')->search({
473         branch  => $branch,
474         type    => 'payment'
475     }, { order_by => { -desc => 'datetime' } })->next();
476
477     ok( defined $stat, "There's a payment log that matches the branch" );
478
479     SKIP: {
480         skip "No statistic logged", 4 unless defined $stat;
481
482         is( $stat->type, 'payment', "Correct statistic type" );
483         is( $stat->branch, $branch, "Correct branch logged to statistics" );
484         is( $stat->borrowernumber, $borrowernumber, "Correct borrowernumber logged to statistics" );
485         is( $stat->value+0, $partialamount, "Correct amount logged to statistics" );
486     }
487 };
488
489 subtest 'balance' => sub {
490     plan tests => 2;
491
492     my $patron = $builder->build({source => 'Borrower'});
493     $patron = Koha::Patrons->find( $patron->{borrowernumber} );
494     my $account = $patron->account;
495     is( $account->balance, 0, 'balance should return 0 if the patron does not have fines' );
496
497     my $accountline_1 = $builder->build(
498         {
499             source => 'Accountline',
500             value  => {
501                 borrowernumber    => $patron->borrowernumber,
502                 amount            => 42,
503                 amountoutstanding => 42
504             }
505         }
506     );
507     my $accountline_2 = $builder->build(
508         {
509             source => 'Accountline',
510             value  => {
511                 borrowernumber    => $patron->borrowernumber,
512                 amount            => -13,
513                 amountoutstanding => -13
514             }
515         }
516     );
517
518     my $balance = $patron->account->balance;
519     is( int($balance), 29, 'balance should return the correct value');
520
521     $patron->delete;
522 };
523
524 subtest "C4::Accounts::chargelostitem tests" => sub {
525     plan tests => 3;
526
527     my $branch = $builder->build( { source => 'Branch' } );
528     my $branchcode = $branch->{branchcode};
529
530     my $staff = $builder->build( { source => 'Borrower' } );
531     my $staff_id = $staff->{borrowernumber};
532
533     my $module = Test::MockModule->new('C4::Context');
534     $module->mock(
535         'userenv',
536         sub {
537             return {
538                 flags  => 1,
539                 number => $staff_id,
540                 branch => $branchcode,
541             };
542         }
543     );
544
545     my $itype_no_replace_no_fee = $builder->build({ source => 'Itemtype', value => {
546             rentalcharge => 0,
547             defaultreplacecost => undef,
548             processfee => undef,
549     }});
550     my $itype_replace_no_fee = $builder->build({ source => 'Itemtype', value => {
551             rentalcharge => 0,
552             defaultreplacecost => 16.32,
553             processfee => undef,
554     }});
555     my $itype_no_replace_fee = $builder->build({ source => 'Itemtype', value => {
556             rentalcharge => 0,
557             defaultreplacecost => undef,
558             processfee => 8.16,
559     }});
560     my $itype_replace_fee = $builder->build({ source => 'Itemtype', value => {
561             rentalcharge => 0,
562             defaultreplacecost => 4.08,
563             processfee => 2.04,
564     }});
565     my $cli_borrowernumber = $builder->build({ source => 'Borrower' })->{'borrowernumber'};
566     my $cli_itemnumber1 = $builder->build({ source => 'Item', value => { itype => $itype_no_replace_no_fee->{itemtype} } })->{'itemnumber'};
567     my $cli_itemnumber2 = $builder->build({ source => 'Item', value => { itype => $itype_replace_no_fee->{itemtype} } })->{'itemnumber'};
568     my $cli_itemnumber3 = $builder->build({ source => 'Item', value => { itype => $itype_no_replace_fee->{itemtype} } })->{'itemnumber'};
569     my $cli_itemnumber4 = $builder->build({ source => 'Item', value => { itype => $itype_replace_fee->{itemtype} } })->{'itemnumber'};
570
571     my $cli_issue_id_1 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1 } })->{issue_id};
572     my $cli_issue_id_2 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2 } })->{issue_id};
573     my $cli_issue_id_3 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3 } })->{issue_id};
574     my $cli_issue_id_4 = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id};
575     my $cli_issue_id_4X = undef;
576
577     my $lostfine;
578     my $procfee;
579
580     subtest "fee application tests" => sub {
581         plan tests => 44;
582
583         t::lib::Mocks::mock_preference('item-level_itypes', '1');
584         t::lib::Mocks::mock_preference('useDefaultReplacementCost', '0');
585
586         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor");
587         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
588         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PF' });
589         ok( !$lostfine, "No lost fine if no replacementcost or default when pref off");
590         ok( !$procfee,  "No processing fee if no processing fee");
591         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor");
592         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
593         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PF' });
594         ok( $lostfine->amount == 6.12, "Lost fine equals replacementcost when pref off and no default set");
595         ok( !$procfee,  "No processing fee if no processing fee");
596         $lostfine->delete();
597
598         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor");
599         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
600         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PF' });
601         ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off");
602         ok( !$procfee,  "No processing fee if no processing fee");
603         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor");
604         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
605         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PF' });
606         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set");
607         ok( !$procfee,  "No processing fee if no processing fee");
608         $lostfine->delete();
609
610         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor");
611         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
612         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PF' });
613         ok( !$lostfine, "No lost fine if no replacementcost and no default set when pref off");
614         ok( $procfee->amount == 8.16,  "Processing fee if processing fee");
615         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
616         $procfee->delete();
617         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor");
618         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
619         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PF' });
620         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and no default set");
621         ok( $procfee->amount == 8.16,  "Processing fee if processing fee");
622         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
623         $lostfine->delete();
624         $procfee->delete();
625
626         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
627         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
628         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
629         ok( !$lostfine, "No lost fine if no replacementcost but default set when pref off");
630         ok( $procfee->amount == 2.04,  "Processing fee if processing fee");
631         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
632         $procfee->delete();
633         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
634         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
635         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
636         ok( $lostfine->amount == 6.12 , "Lost fine equals replacementcost when pref off and default set");
637         ok( $procfee->amount == 2.04,  "Processing fee if processing fee");
638         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
639         $lostfine->delete();
640         $procfee->delete();
641
642         t::lib::Mocks::mock_preference('useDefaultReplacementCost', '1');
643
644         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 0, "Perdedor");
645         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
646         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PF' });
647         ok( !$lostfine, "No lost fine if no replacementcost or default when pref on");
648         ok( !$procfee,  "No processing fee if no processing fee");
649         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber1, 6.12, "Perdedor");
650         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'LOST' });
651         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber1, debit_type_code => 'PF' });
652         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set");
653         ok( !$procfee,  "No processing fee if no processing fee");
654
655         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 0, "Perdedor");
656         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
657         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PF' });
658         is( $lostfine->amount(), "16.320000", "Lost fine is default if no replacementcost but default set when pref on");
659         ok( !$procfee,  "No processing fee if no processing fee");
660         $lostfine->delete();
661         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber2, 6.12, "Perdedor");
662         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'LOST' });
663         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber2, debit_type_code => 'PF' });
664         is( $lostfine->amount, "6.120000" , "Lost fine equals replacementcost when pref on and default set");
665         ok( !$procfee,  "No processing fee if no processing fee");
666
667         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 0, "Perdedor");
668         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
669         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PF' });
670         ok( !$lostfine, "No lost fine if no replacementcost and default not set when pref on");
671         is( $procfee->amount, "8.160000",  "Processing fee if processing fee");
672         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
673         $procfee->delete();
674         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber3, 6.12, "Perdedor");
675         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'LOST' });
676         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber3, debit_type_code => 'PF' });
677         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and no default set");
678         is( $procfee->amount, "8.160000",  "Processing fee if processing fee");
679         is( $procfee->issue_id, $cli_issue_id_3, "Processing fee issue id is correct" );
680
681         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "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 => 'PF' });
684         is( $lostfine->amount, "4.080000", "Lost fine is default if no replacementcost but default set when pref on");
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         $lostfine->delete();
688         $procfee->delete();
689         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
690         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
691         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
692         is( $lostfine->amount, "6.120000", "Lost fine equals replacementcost when pref on and default set");
693         is( $procfee->amount, "2.040000",  "Processing fee if processing fee");
694         is( $procfee->issue_id, $cli_issue_id_4, "Processing fee issue id is correct" );
695         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
696         my $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
697         my $procfees  = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
698         ok( $lostfines->count == 1 , "Lost fine cannot be double charged for the same issue_id");
699         ok( $procfees->count == 1,  "Processing fee cannot be double charged for the same issue_id");
700         MarkIssueReturned($cli_borrowernumber, $cli_itemnumber4);
701         $cli_issue_id_4X = $builder->build({ source => 'Issue', value => { borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4 } })->{issue_id};
702         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 6.12, "Perdedor");
703         $lostfines = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
704         $procfees  = Koha::Account::Lines->search({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
705         ok( $lostfines->count == 2 , "Lost fine can be charged twice for the same item if they are distinct issue_id's");
706         ok( $procfees->count == 2,  "Processing fee can be charged twice for the same item if they are distinct issue_id's");
707         $lostfines->delete();
708         $procfees->delete();
709     };
710
711     subtest "basic fields tests" => sub {
712         plan tests => 12;
713
714         t::lib::Mocks::mock_preference('ProcessingFeeNote', 'Test Note');
715         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, '1.99', "Perdedor");
716
717         # Lost Item Fee
718         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
719         ok($lostfine, "Lost fine created");
720         is($lostfine->manager_id, $staff_id, "Lost fine manager_id set correctly");
721         is($lostfine->issue_id, $cli_issue_id_4X, "Lost fine issue_id set correctly");
722         is($lostfine->description, "Perdedor", "Lost fine issue_id set correctly");
723         is($lostfine->note, '', "Lost fine does not contain a note");
724         is($lostfine->branchcode, $branchcode, "Lost fine branchcode set correctly");
725
726         # Processing Fee
727         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
728         ok($procfee, "Processing fee created");
729         is($procfee->manager_id, $staff_id, "Processing fee manager_id set correctly");
730         is($procfee->issue_id, $cli_issue_id_4X, "Processing fee issue_id set correctly");
731         is($procfee->description, "Perdedor", "Processing fee issue_id set correctly");
732         is($procfee->note, C4::Context->preference("ProcessingFeeNote"), "Processing fee contains note matching ProcessingFeeNote");
733         is($procfee->branchcode, $branchcode, "Processing fee branchcode set correctly");
734         $lostfine->delete();
735         $procfee->delete();
736     };
737
738     subtest "FinesLog tests" => sub {
739         plan tests => 2;
740
741         my $action_logs = $schema->resultset('ActionLog')->search()->count;
742
743         t::lib::Mocks::mock_preference( 'FinesLog', 0 );
744         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
745         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
746         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
747         is( $schema->resultset('ActionLog')->count(), $action_logs + 0, 'No logs were added' );
748         $lostfine->delete();
749         $procfee->delete();
750
751         t::lib::Mocks::mock_preference( 'FinesLog', 1 );
752         C4::Accounts::chargelostitem( $cli_borrowernumber, $cli_itemnumber4, 0, "Perdedor");
753         $lostfine = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'LOST' });
754         $procfee  = Koha::Account::Lines->find({ borrowernumber => $cli_borrowernumber, itemnumber => $cli_itemnumber4, debit_type_code => 'PF' });
755         is( $schema->resultset('ActionLog')->count(), $action_logs + 2, 'Logs were added' );
756         $lostfine->delete();
757         $procfee->delete();
758     };
759
760     # Cleanup - this must be replaced with a transaction per subtest
761     Koha::Patrons->find($cli_borrowernumber)->checkouts->delete;
762 };
763
764 subtest "Koha::Account::non_issues_charges tests" => sub {
765     plan tests => 21;
766
767     my $patron = $builder->build_object( { class => 'Koha::Patrons' } );
768     my $account = $patron->account;
769
770     my $today  = dt_from_string;
771     my $res    = 3;
772     my $rent   = 5;
773     my $manual = 7;
774     $account->add_debit(
775         {
776             description => 'a Res fee',
777             type        => 'reserve',
778             amount      => $res,
779             interface   => 'commandline'
780         }
781     );
782     $account->add_debit(
783         {
784             description => 'a Rental fee',
785             type        => 'rent',
786             amount      => $rent,
787             interface   => 'commandline'
788         }
789     );
790     Koha::Account::DebitTypes->find_or_create(
791         {
792             code        => 'Copie',
793             description => 'Fee for copie',
794             is_system   => 0
795         }
796     )->store;
797     Koha::Account::Line->new(
798         {
799             borrowernumber    => $patron->borrowernumber,
800             date              => $today,
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({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => 0, interface => 'commandline' })->store();
946     my $credit = Koha::Account::Line->new({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => -5, interface => 'commandline' })->store();
947     my $offset = Koha::Account::Offset->new({ credit_id => $credit->id, debit_id => $debit->id, type => 'Payment', amount => 0 })->store();
948     purge_zero_balance_fees( 1 );
949     my $debit_2 = Koha::Account::Lines->find( $debit->id );
950     my $credit_2 = Koha::Account::Lines->find( $credit->id );
951     ok( $debit_2, 'Debit was correctly not deleted when credit has balance' );
952     ok( $credit_2, 'Credit was correctly not deleted when credit has balance' );
953     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2, "The 2 account lines still exists" );
954
955     $debit = Koha::Account::Line->new({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => 5, interface => 'commanline' })->store();
956     $credit = Koha::Account::Line->new({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => 0, interface => 'commandline' })->store();
957     $offset = Koha::Account::Offset->new({ credit_id => $credit->id, debit_id => $debit->id, type => 'Payment', amount => 0 })->store();
958     purge_zero_balance_fees( 1 );
959     $debit_2 = $credit_2 = undef;
960     $debit_2 = Koha::Account::Lines->find( $debit->id );
961     $credit_2 = Koha::Account::Lines->find( $credit->id );
962     ok( $debit_2, 'Debit was correctly not deleted when debit has balance' );
963     ok( $credit_2, 'Credit was correctly not deleted when debit has balance' );
964     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists" );
965
966     $debit = Koha::Account::Line->new({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => 0, interface => 'commandline' })->store();
967     $credit = Koha::Account::Line->new({ borrowernumber => $patron->id, date => '1900-01-01', amountoutstanding => 0, interface => 'commandline' })->store();
968     $offset = Koha::Account::Offset->new({ credit_id => $credit->id, debit_id => $debit->id, type => 'Payment', amount => 0 })->store();
969     purge_zero_balance_fees( 1 );
970     $debit_2 = Koha::Account::Lines->find( $debit->id );
971     $credit_2 = Koha::Account::Lines->find( $credit->id );
972     ok( !$debit_2, 'Debit was correctly deleted' );
973     ok( !$credit_2, 'Credit was correctly deleted' );
974     is( Koha::Account::Lines->count({ borrowernumber => $patron->id }), 2 + 2, "The 2 + 2 account lines still exists, the last 2 have been deleted ok" );
975 };
976
977
978 subtest "Koha::Account::Offset credit & debit tests" => sub {
979
980     plan tests => 4;
981
982     # Create a borrower
983     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
984     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
985
986     my $borrower = Koha::Patron->new( {
987         cardnumber => 'kyliehall',
988         surname => 'Hall',
989         firstname => 'Kylie',
990     } );
991     $borrower->categorycode( $categorycode );
992     $borrower->branchcode( $branchcode );
993     $borrower->store;
994
995     my $account = Koha::Account->new({ patron_id => $borrower->id });
996
997     my $line1 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amount => 10, amountoutstanding => 10, interface => 'commandline' })->store();
998     my $line2 = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amount => 20, amountoutstanding => 20, interface => 'commandline' })->store();
999
1000     my $id = $account->pay(
1001         {
1002             lines  => [$line1, $line2],
1003             amount => 30,
1004         }
1005     );
1006
1007     # Test debit and credit methods for Koha::Account::Offset
1008     my $account_offset = Koha::Account::Offsets->find( { credit_id => $id, debit_id => $line1->id } );
1009     is( $account_offset->debit->id, $line1->id, "Koha::Account::Offset->debit gets correct accountline" );
1010     is( $account_offset->credit->id, $id, "Koha::Account::Offset->credit gets correct accountline" );
1011
1012     $account_offset = Koha::Account::Offset->new(
1013         {
1014             credit_id => undef,
1015             debit_id  => undef,
1016             type      => 'Payment',
1017             amount    => 0,
1018         }
1019     )->store();
1020
1021     is( $account_offset->debit, undef, "Koha::Account::Offset->debit returns undef if no associated debit" );
1022     is( $account_offset->credit, undef, "Koha::Account::Offset->credit returns undef if no associated credit" );
1023 };
1024
1025 subtest "Payment notice tests" => sub {
1026
1027     plan tests => 8;
1028
1029     Koha::Account::Lines->delete();
1030     Koha::Patrons->delete();
1031     Koha::Notice::Messages->delete();
1032     # Create a borrower
1033     my $categorycode = $builder->build({ source => 'Category' })->{ categorycode };
1034     my $branchcode   = $builder->build({ source => 'Branch' })->{ branchcode };
1035
1036     my $borrower = Koha::Patron->new(
1037         {
1038             cardnumber   => 'chelseahall',
1039             surname      => 'Hall',
1040             firstname    => 'Chelsea',
1041             email        => 'chelsea@example.com',
1042             categorycode => $categorycode,
1043             branchcode   => $branchcode,
1044         }
1045     )->store();
1046
1047     my $manager = $builder->build_object({ class => "Koha::Patrons" });
1048     my $context = new Test::MockModule('C4::Context');
1049     $context->mock( 'userenv', sub {
1050         return {
1051             number     => $manager->borrowernumber,
1052             branch     => $manager->branchcode,
1053         };
1054     });
1055     my $account = Koha::Account->new({ patron_id => $borrower->id });
1056
1057     my $line = Koha::Account::Line->new({ borrowernumber => $borrower->borrowernumber, amountoutstanding => 27, interface => 'commandline' })->store();
1058
1059     my $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_PAYMENT' } );
1060     $letter->content('[%- USE Price -%]A payment of [% credit.amount * -1 | $Price %] has been applied to your account.');
1061     $letter->store();
1062
1063     t::lib::Mocks::mock_preference('UseEmailReceipts', '0');
1064     my $id = $account->pay( { amount => 1 } );
1065     is( Koha::Notice::Messages->search()->count(), 0, 'Notice for payment not sent if UseEmailReceipts is disabled' );
1066
1067     $id = $account->pay( { amount => 1, type => 'writeoff' } );
1068     is( Koha::Notice::Messages->search()->count(), 0, 'Notice for writeoff not sent if UseEmailReceipts is disabled' );
1069
1070     t::lib::Mocks::mock_preference('UseEmailReceipts', '1');
1071
1072     $id = $account->pay( { amount => 12 } );
1073     my $notice = Koha::Notice::Messages->search()->next();
1074     is( $notice->subject, 'Account payment', 'Notice subject is correct for payment' );
1075     is( $notice->letter_code, 'ACCOUNT_PAYMENT', 'Notice letter code is correct for payment' );
1076     is( $notice->content, 'A payment of 12.00 has been applied to your account.', 'Notice content is correct for payment' );
1077     $notice->delete();
1078
1079     $letter = Koha::Notice::Templates->find( { code => 'ACCOUNT_WRITEOFF' } );
1080     $letter->content('[%- USE Price -%]A writeoff of [% credit.amount * -1 | $Price %] has been applied to your account.');
1081     $letter->store();
1082
1083     $id = $account->pay( { amount => 13, type => 'writeoff' } );
1084     $notice = Koha::Notice::Messages->search()->next();
1085     is( $notice->subject, 'Account writeoff', 'Notice subject is correct for payment' );
1086     is( $notice->letter_code, 'ACCOUNT_WRITEOFF', 'Notice letter code is correct for writeoff' );
1087     is( $notice->content, 'A writeoff of 13.00 has been applied to your account.', 'Notice content is correct for writeoff' );
1088 };
1089
1090 1;