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