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