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