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