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