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