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