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