92f9362e64648ca9e67d3a6e2b907e0d2ff551ec
[kivitendo-erp.git] / t / bank / bank_transactions.t
1 use Test::More tests => 293;
2
3 use strict;
4
5 use lib 't';
6 use utf8;
7
8 use Carp;
9 use Support::TestSetup;
10 use Test::Exception;
11 use List::Util qw(sum);
12
13 use SL::DB::AccTransaction;
14 use SL::DB::BankTransactionAccTrans;
15 use SL::DB::Buchungsgruppe;
16 use SL::DB::Currency;
17 use SL::DB::Customer;
18 use SL::DB::Default;
19 use SL::DB::Vendor;
20 use SL::DB::Invoice;
21 use SL::DB::Unit;
22 use SL::DB::Part;
23 use SL::DB::TaxZone;
24 use SL::DB::BankAccount;
25 use SL::DB::PaymentTerm;
26 use SL::DB::PurchaseInvoice;
27 use SL::DB::BankTransaction;
28 use SL::Controller::BankTransaction;
29 use SL::Controller::Reconciliation;
30 use SL::Dev::ALL qw(:ALL);
31 use Data::Dumper;
32
33 my ($customer, $vendor, $currency_id, $unit, $tax, $tax0, $tax7, $tax_9, $payment_terms, $bank_account);
34 my ($currency);
35 my ($ar_chart,$bank,$ar_amount_chart, $ap_chart, $ap_amount_chart);
36 my ($ar_transaction, $ap_transaction);
37 my ($dt, $dt_5, $dt_10, $year);
38
39 sub clear_up {
40
41   SL::DB::Manager::BankTransactionAccTrans->delete_all(all => 1);
42   SL::DB::Manager::BankTransaction->delete_all(all => 1);
43   SL::DB::Manager::InvoiceItem->delete_all(all => 1);
44   SL::DB::Manager::InvoiceItem->delete_all(all => 1);
45   SL::DB::Manager::Invoice->delete_all(all => 1);
46   SL::DB::Manager::PurchaseInvoice->delete_all(all => 1);
47   SL::DB::Manager::Part->delete_all(all => 1);
48   SL::DB::Manager::Customer->delete_all(all => 1);
49   SL::DB::Manager::Vendor->delete_all(all => 1);
50   SL::DB::Manager::SepaExportItem->delete_all(all => 1);
51   SL::DB::Manager::SepaExport->delete_all(all => 1);
52   SL::DB::Manager::BankAccount->delete_all(all => 1);
53   SL::DB::Manager::PaymentTerm->delete_all(all => 1);
54   SL::DB::Manager::Currency->delete_all(where => [ name => 'CUR' ]);
55   # SL::DB::Manager::Default->delete_all(all => 1);
56 };
57
58 my $bt_controller;
59
60 sub save_btcontroller_to_string {
61   my $output;
62   open(my $outputFH, '>', \$output) or die;
63   my $oldFH = select $outputFH;
64
65   $bt_controller = SL::Controller::BankTransaction->new;
66   $bt_controller->action_save_invoices;
67
68   select $oldFH;
69   close $outputFH;
70   return $output;
71 }
72
73 # starting test:
74 Support::TestSetup::login();
75
76 clear_up();
77 reset_state(); # initialise customers/vendors/bank/currency/...
78
79 test1();
80
81 test_overpayment_with_partialpayment();
82 test_overpayment();
83 reset_state();
84 test_skonto_exact();
85 test_two_invoices();
86 test_partial_payment();
87 test_credit_note();
88 test_ap_transaction();
89 test_neg_ap_transaction(invoice => 0);
90 test_neg_ap_transaction(invoice => 1);
91 test_ap_payment_transaction();
92 test_ap_payment_part_transaction();
93 test_neg_sales_invoice();
94 test_two_neg_ap_transaction();
95 test_one_inv_and_two_invoices_with_skonto_exact();
96 test_bt_error();
97 test_full_workflow_ar_multiple_inv_skonto_reconciliate_and_undo();
98 reset_state();
99 test_sepa_export();
100
101 reset_state();
102 test_bt_rule1();
103 reset_state();
104 test_two_banktransactions();
105 # remove all created data at end of test
106 test_closedto();
107 clear_up();
108
109 done_testing();
110
111 ###### functions for setting up data
112
113 sub reset_state {
114   my %params = @_;
115
116   $params{$_} ||= {} for qw(unit customer tax vendor);
117
118   clear_up();
119
120   $year  = DateTime->today_local->year;
121   $year  = 2019 if $year == 2020; # use year 2019 in 2020, because of tax rate change in Germany
122   $dt    = DateTime->new(year => $year, month => 1, day => 12);
123   $dt_5  = $dt->clone->add(days => 5);
124   $dt_10 = $dt->clone->add(days => 10);
125
126   $tax             = SL::DB::Manager::Tax->find_by(taxkey => 3, rate => 0.19, %{ $params{tax} }) || croak "No tax";
127   $tax7            = SL::DB::Manager::Tax->find_by(taxkey => 2, rate => 0.07)                    || croak "No tax for 7\%";
128   $tax_9           = SL::DB::Manager::Tax->find_by(taxkey => 9, rate => 0.19, %{ $params{tax} }) || croak "No tax for 19\%";
129   $tax0            = SL::DB::Manager::Tax->find_by(taxkey => 0, rate => 0.0)                     || croak "No tax for 0\%";
130
131   $currency_id     = $::instance_conf->get_currency_id;
132
133   $bank_account     =  SL::DB::BankAccount->new(
134     account_number  => '123',
135     bank_code       => '123',
136     iban            => '123',
137     bic             => '123',
138     bank            => '123',
139     chart_id        => SL::DB::Manager::Chart->find_by(description => 'Bank')->id,
140     name            => SL::DB::Manager::Chart->find_by(description => 'Bank')->description,
141   )->save;
142
143   $customer = new_customer(
144     name                      => 'Test Customer OLÉ S.L. Årdbärg AB',
145     iban                      => 'DE12500105170648489890',
146     bic                       => 'TESTBIC',
147     account_number            => '648489890',
148     mandate_date_of_signature => $dt,
149     mandator_id               => 'foobar',
150     bank                      => 'Geizkasse',
151     bank_code                 => 'G1235',
152     depositor                 => 'Test Customer',
153     customernumber            => 'CUST1704',
154   )->save;
155
156   $payment_terms = create_payment_terms();
157
158   $vendor = new_vendor(
159     name           => 'Test Vendor',
160     payment_id     => $payment_terms->id,
161     iban           => 'DE12500105170648489890',
162     bic            => 'TESTBIC',
163     account_number => '648489890',
164     bank           => 'Geizkasse',
165     bank_code      => 'G1235',
166     depositor      => 'Test Vendor',
167     vendornumber   => 'VEND1704',
168   )->save;
169
170   $ar_chart        = SL::DB::Manager::Chart->find_by( accno => '1400' ); # Forderungen
171   $ap_chart        = SL::DB::Manager::Chart->find_by( accno => '1600' ); # Verbindlichkeiten
172   $bank            = SL::DB::Manager::Chart->find_by( accno => '1200' ); # Bank
173   $ar_amount_chart = SL::DB::Manager::Chart->find_by( accno => '8400' ); # Erlöse
174   $ap_amount_chart = SL::DB::Manager::Chart->find_by( accno => '3400' ); # Wareneingang 19%
175
176 }
177
178 sub test_ar_transaction {
179   my (%params) = @_;
180   my $netamount = $::form->round_amount($params{amount}, 2) || 100;
181   my $amount    = $::form->round_amount($netamount * 1.19,2);
182   my $invoice   = SL::DB::Invoice->new(
183       invoice      => 0,
184       invnumber    => $params{invnumber} || undef, # let it use its own invnumber
185       amount       => $amount,
186       netamount    => $netamount,
187       transdate    => $dt,
188       taxincluded  => $params{taxincluded } || 0,
189       customer_id  => $customer->id,
190       taxzone_id   => $customer->taxzone_id,
191       currency_id  => $currency_id,
192       transactions => [],
193       payment_id   => $params{payment_id} || undef,
194       notes        => 'test_ar_transaction',
195   );
196   $invoice->add_ar_amount_row(
197     amount => $invoice->netamount,
198     chart  => $ar_amount_chart,
199     tax_id => $params{tax_id} || $tax->id,
200   );
201
202   $invoice->create_ar_row(chart => $ar_chart);
203   $invoice->save;
204
205   is($invoice->currency_id , $currency_id , 'currency_id has been saved');
206   is($invoice->netamount   , $netamount   , 'ar amount has been converted');
207   is($invoice->amount      , $amount      , 'ar amount has been converted');
208   is($invoice->taxincluded , 0            , 'ar transaction doesn\'t have taxincluded');
209
210   if ( $netamount == 100 ) {
211     is(SL::DB::Manager::AccTransaction->find_by(chart_id => $ar_amount_chart->id , trans_id => $invoice->id)->amount , '100.00000'  , $ar_amount_chart->accno . ': has been converted for currency');
212     is(SL::DB::Manager::AccTransaction->find_by(chart_id => $ar_chart->id        , trans_id => $invoice->id)->amount , '-119.00000' , $ar_chart->accno . ': has been converted for currency');
213   }
214   return $invoice;
215 };
216
217 sub test_ap_transaction {
218   my (%params) = @_;
219   my $testname = 'test_ap_transaction';
220
221   my $netamount = 100;
222   my $amount    = $::form->round_amount($netamount * 1.19,2);
223   my $invoice   = SL::DB::PurchaseInvoice->new(
224     invoice      => 0,
225     invnumber    => $params{invnumber} || $testname,
226     amount       => $amount,
227     netamount    => $netamount,
228     transdate    => $dt,
229     taxincluded  => 0,
230     vendor_id    => $vendor->id,
231     taxzone_id   => $vendor->taxzone_id,
232     currency_id  => $currency_id,
233     transactions => [],
234     notes        => 'test_ap_transaction',
235   );
236   $invoice->add_ap_amount_row(
237     amount     => $invoice->netamount,
238     chart      => $ap_amount_chart,
239     tax_id     => $params{tax_id} || $tax_9->id,
240   );
241
242   $invoice->create_ap_row(chart => $ap_chart);
243   $invoice->save;
244
245   is($invoice->currency_id , $currency_id , "$testname: currency_id has been saved");
246   is($invoice->netamount   , 100          , "$testname: ap amount has been converted");
247   is($invoice->amount      , 119          , "$testname: ap amount has been converted");
248   is($invoice->taxincluded , 0            , "$testname: ap transaction doesn\'t have taxincluded");
249
250   is(SL::DB::Manager::AccTransaction->find_by(chart_id => $ap_amount_chart->id , trans_id => $invoice->id)->amount , '-100.00000' , $ap_amount_chart->accno . ': has been converted for currency');
251   is(SL::DB::Manager::AccTransaction->find_by(chart_id => $ap_chart->id        , trans_id => $invoice->id)->amount , '119.00000'  , $ap_chart->accno . ': has been converted for currency');
252
253   return $invoice;
254 };
255
256 ###### test cases
257
258 sub test1 {
259
260   my $testname = 'test1';
261
262   $ar_transaction = test_ar_transaction(invnumber => 'salesinv1');
263
264   my $bt = create_bank_transaction(record      => $ar_transaction,
265                                    transdate   => $dt,
266                                    valutadate  => $dt) or die "Couldn't create bank_transaction";
267
268   $::form->{invoice_ids} = {
269     $bt->id => [ $ar_transaction->id ]
270   };
271
272   save_btcontroller_to_string();
273
274   $ar_transaction->load;
275   $bt->load;
276   is($ar_transaction->paid   , '119.00000' , "$testname: salesinv1 was paid");
277   is($ar_transaction->closed , 1           , "$testname: salesinv1 is closed");
278   is($bt->invoice_amount     , '119.00000' , "$testname: bt invoice amount was assigned");
279
280 };
281
282 sub test_skonto_exact {
283
284   my $testname = 'test_skonto_exact';
285
286   $ar_transaction = test_ar_transaction(invnumber => 'salesinv skonto',
287                                         payment_id => $payment_terms->id,
288                                        );
289
290   my $bt = create_bank_transaction(record        => $ar_transaction,
291                                    bank_chart_id => $bank->id,
292                                    transdate     => $dt,
293                                    valutadate    => $dt,
294                                    amount        => $ar_transaction->amount_less_skonto
295                                   ) or die "Couldn't create bank_transaction";
296
297   $::form->{invoice_ids} = {
298     $bt->id => [ $ar_transaction->id ]
299   };
300   $::form->{invoice_skontos} = {
301     $bt->id => [ 'with_skonto_pt' ]
302   };
303
304   save_btcontroller_to_string();
305
306   $ar_transaction->load;
307   $bt->load;
308   is($ar_transaction->paid   , '119.00000' , "$testname: salesinv skonto was paid");
309   is($ar_transaction->closed , 1           , "$testname: salesinv skonto is closed");
310   is($bt->invoice_amount     , '113.05000' , "$testname: bt invoice amount was assigned");
311
312 };
313
314 sub test_bt_error {
315
316   my $testname = 'test_rollback_error';
317   # without type with_free_skonto the helper function (Payment.pm) looks ugly but not
318   # breakable
319
320   $ar_transaction = test_ar_transaction(invnumber   => 'salesinv skonto',
321                                         payment_id  => $payment_terms->id,
322                                         taxincluded => 0,
323                                         amount      => 168.58 / 1.19,
324                                        );
325
326   my $bt = create_bank_transaction(record        => $ar_transaction,
327                                    bank_chart_id => $bank->id,
328                                    transdate   => $dt,
329                                    valutadate  => $dt,
330                                    amount        => 160.15,
331                                   ) or die "Couldn't create bank_transaction";
332   $::form->{invoice_ids} = {
333     $bt->id => [ $ar_transaction->id ]
334   };
335   $::form->{invoice_skontos} = {
336     $bt->id => [ 'with_skonto_pt' ]
337   };
338   is($ar_transaction->netamount, $::form->round_amount(168.58/1.19, 2), "$testname: Net Amount assigned");
339   is($ar_transaction->amount, 168.58, "$testname: Amount assigned");
340   is($ar_transaction->paid   , '0' , "$testname: salesinv is not paid");
341
342   # generate an error for testing rollback mechanism
343   my $saved_skonto_sales_chart_id = $tax->skonto_sales_chart_id;
344   $tax->skonto_sales_chart_id(undef);
345   $tax->save;
346
347   save_btcontroller_to_string();
348   my @bt_errors = @{ $bt_controller->problems };
349   is(substr($bt_errors[0]->{message},0,38), 'Kein Skontokonto für Steuerschlüssel 3', "$testname: Fehlermeldung ok");
350   # set original value
351   $tax->skonto_sales_chart_id($saved_skonto_sales_chart_id);
352   $tax->save;
353
354   $ar_transaction->load;
355   $bt->load;
356   is($ar_transaction->paid   , '0.00000' , "$testname: salesinv was not paid");
357   is($bt->invoice_amount     , '0.00000' , "$testname: bt invoice amount was not assigned");
358
359 };
360
361 sub test_two_invoices {
362
363   my $testname = 'test_two_invoices';
364
365   my $ar_transaction_1 = test_ar_transaction(invnumber => 'salesinv_1');
366   my $ar_transaction_2 = test_ar_transaction(invnumber => 'salesinv_2');
367
368   my $bt = create_bank_transaction(record        => $ar_transaction_1,
369                                    amount        => ($ar_transaction_1->amount + $ar_transaction_2->amount),
370                                    purpose       => "Rechnungen " . $ar_transaction_1->invnumber . " und " . $ar_transaction_2->invnumber,
371                                    transdate     => $dt,
372                                    valutadate    => $dt,
373                                    bank_chart_id => $bank->id,
374                                   ) or die "Couldn't create bank_transaction";
375
376   my ($agreement, $rule_matches) = $bt->get_agreement_with_invoice($ar_transaction_1);
377   is($agreement, 16, "points for ar_transaction_1 in test_two_invoices ok");
378
379   $::form->{invoice_ids} = {
380     $bt->id => [ $ar_transaction_1->id, $ar_transaction_2->id ]
381   };
382
383   save_btcontroller_to_string();
384
385   $ar_transaction_1->load;
386   $ar_transaction_2->load;
387   $bt->load;
388
389   is($ar_transaction_1->paid   , '119.00000' , "$testname: salesinv_1 wcsv_import_reportsas paid");
390   is($ar_transaction_1->closed , 1           , "$testname: salesinv_1 is closed");
391   is($ar_transaction_2->paid   , '119.00000' , "$testname: salesinv_2 was paid");
392   is($ar_transaction_2->closed , 1           , "$testname: salesinv_2 is closed");
393   is($bt->invoice_amount       , '238.00000' , "$testname: bt invoice amount was assigned");
394
395 }
396
397 sub test_one_inv_and_two_invoices_with_skonto_exact {
398
399   my $testname = 'test_two_invoices_with_skonto_exact';
400
401   my $ar_transaction_1 = test_ar_transaction(invnumber => 'salesinv 1 skonto',
402                                              payment_id => $payment_terms->id,
403                                             );
404   my $ar_transaction_2 = test_ar_transaction(invnumber => 'salesinv 2 skonto',
405                                              payment_id => $payment_terms->id,
406                                             );
407   my $ar_transaction_3 = test_ar_transaction(invnumber => 'salesinv 3 no skonto');
408
409
410
411   my $bt = create_bank_transaction(record        => $ar_transaction_1,
412                                    bank_chart_id => $bank->id,
413                                    transdate     => $dt,
414                                    valutadate    => $dt,
415                                    amount        => $ar_transaction_1->amount_less_skonto * 2 + $ar_transaction_3->amount
416                                   ) or die "Couldn't create bank_transaction";
417
418   $::form->{invoice_ids} = {
419     $bt->id => [ $ar_transaction_1->id, $ar_transaction_3->id, $ar_transaction_2->id]
420   };
421   $::form->{invoice_skontos} = {
422     $bt->id => [ 'with_skonto_pt', 'without_skonto', 'with_skonto_pt' ]
423   };
424
425   save_btcontroller_to_string();
426
427   $ar_transaction_1->load;
428   $ar_transaction_2->load;
429   $ar_transaction_3->load;
430   my $skonto_1 = SL::DB::Manager::AccTransaction->find_by(trans_id => $ar_transaction_1->id, chart_id => 162);
431   my $skonto_2 = SL::DB::Manager::AccTransaction->find_by(trans_id => $ar_transaction_2->id, chart_id => 162);
432   $bt->load;
433   is($skonto_1->amount   , '-5.95000' , "$testname: salesinv 1 skonto was booked");
434   is($skonto_2->amount   , '-5.95000' , "$testname: salesinv 2 skonto was booked");
435   is($ar_transaction_1->paid   , '119.00000' , "$testname: salesinv 1 was paid");
436   is($ar_transaction_2->paid   , '119.00000' , "$testname: salesinv 2 was paid");
437   is($ar_transaction_3->paid   , '119.00000' , "$testname: salesinv 3 was paid");
438   is($ar_transaction_1->closed , 1           , "$testname: salesinv 1 skonto is closed");
439   is($ar_transaction_2->closed , 1           , "$testname: salesinv 2 skonto is closed");
440   is($ar_transaction_3->closed , 1           , "$testname: salesinv 2 skonto is closed");
441   is($bt->invoice_amount     , '345.10000' , "$testname: bt invoice amount was assigned");
442
443 }
444
445 sub test_overpayment {
446
447   my $testname = 'test_overpayment';
448
449   $ar_transaction = test_ar_transaction(invnumber => 'salesinv overpaid');
450
451   # amount 135 > 119
452   my $bt = create_bank_transaction(record        => $ar_transaction,
453                                    bank_chart_id => $bank->id,
454                                    transdate   => $dt,
455                                    valutadate  => $dt,
456                                    amount        => 135
457                                   ) or die "Couldn't create bank_transaction";
458
459   $::form->{invoice_ids} = {
460     $bt->id => [ $ar_transaction->id ]
461   };
462
463   save_btcontroller_to_string();
464
465   $ar_transaction->load;
466   $bt->load;
467
468   is($ar_transaction->paid                     , '119.00000' , "$testname: 'salesinv overpaid' was not overpaid");
469   is($bt->invoice_amount                       , '119.00000' , "$testname: bt invoice amount was not fully assigned with the overpaid amount");
470 { local $TODO = 'this currently fails because closed ignores over-payments, see commit d90966c7';
471   is($ar_transaction->closed                   , 0           , "$testname: 'salesinv overpaid' is open (via 'closed' method')");
472 }
473   is($ar_transaction->open_amount == 0 ? 1 : 0 , 1           , "$testname: 'salesinv overpaid is closed (via amount-paid)");
474
475 };
476
477 sub test_overpayment_with_partialpayment {
478
479   # two payments on different days, 10 and 119. If there is only one invoice we
480   # don't want it to be overpaid.
481   my $testname = 'test_overpayment_with_partialpayment';
482
483   $ar_transaction = test_ar_transaction(invnumber => 'salesinv overpaid partial');
484
485   my $bt_1 = create_bank_transaction(record        => $ar_transaction,
486                                      bank_chart_id => $bank->id,
487                                      transdate   => $dt,
488                                      valutadate  => $dt,
489                                      amount        =>  10
490                                     ) or die "Couldn't create bank_transaction";
491   my $bt_2 = create_bank_transaction(record        => $ar_transaction,
492                                      amount        => 119,
493                                      transdate     => $dt_5,
494                                      valutadate    => $dt_5,
495                                      bank_chart_id => $bank->id,
496                                     ) or die "Couldn't create bank_transaction";
497
498   $::form->{invoice_ids} = {
499     $bt_1->id => [ $ar_transaction->id ]
500   };
501   save_btcontroller_to_string();
502
503   $bt_1->load;
504   is($bt_1->invoice_amount ,  '10.00000' , "$testname: bt_1 invoice amount was fully assigned");
505   $::form->{invoice_ids} = {
506     $bt_2->id => [ $ar_transaction->id ]
507   };
508   save_btcontroller_to_string();
509
510   $ar_transaction->load;
511   $bt_2->load;
512
513   is($bt_1->invoice_amount ,  '10.00000' , "$testname: bt_1 invoice amount was fully assigned");
514   is($ar_transaction->paid , '119.00000' , "$testname: 'salesinv overpaid partial' was not overpaid");
515   is($bt_2->invoice_amount , '109.00000' , "$testname: bt_2 invoice amount was partly assigned");
516
517 };
518
519 sub test_partial_payment {
520
521   my $testname = 'test_partial_payment';
522
523   $ar_transaction = test_ar_transaction(invnumber => 'salesinv partial payment');
524
525   # amount 100 < 119
526   my $bt = create_bank_transaction(record        => $ar_transaction,
527                                    bank_chart_id => $bank->id,
528                                    transdate     => $dt,
529                                    valutadate    => $dt,
530                                    amount        => 100
531                                   ) or die "Couldn't create bank_transaction";
532
533   $::form->{invoice_ids} = {
534     $bt->id => [ $ar_transaction->id ]
535   };
536
537   save_btcontroller_to_string();
538
539   $ar_transaction->load;
540   $bt->load;
541
542   is($ar_transaction->paid , '100.00000' , "$testname: 'salesinv partial payment' was partially paid");
543   is($bt->invoice_amount   , '100.00000' , "$testname: bt invoice amount was assigned partially paid amount");
544
545   # addon test partial payment full point match
546   my $bt2 = create_bank_transaction(record        => $ar_transaction,
547                                     bank_chart_id => $bank->id,
548                                     transdate     => $dt,
549                                     valutadate    => $dt,
550                                     amount        => 19
551                                    ) or die "Couldn't create bank_transaction";
552
553   my ($agreement, $rule_matches) = $bt2->get_agreement_with_invoice($ar_transaction);
554   is($agreement, 15, "points for exact partial payment ok");
555   is($rule_matches, 'remote_account_number(3) exact_open_amount(4) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus0(3) ', "rules_matches for exact partial payment ok");
556 };
557
558 sub test_full_workflow_ar_multiple_inv_skonto_reconciliate_and_undo {
559
560   my $testname = 'test_partial_payment';
561
562   $ar_transaction = test_ar_transaction(invnumber => 'salesinv partial payment two');
563   my $ar_transaction_2 = test_ar_transaction(invnumber => 'salesinv 2 22d2', amount => 22);
564
565   # amount 299.29 > 119
566   my $bt = create_bank_transaction(record        => $ar_transaction,
567                                    bank_chart_id => $bank->id,
568                                    amount        => 299.29
569                                   ) or die "Couldn't create bank_transaction";
570
571   $::form->{invoice_ids} = {
572     $bt->id => [ $ar_transaction->id ]
573   };
574
575   save_btcontroller_to_string();
576
577   $ar_transaction->load;
578   $bt->load;
579
580   is($ar_transaction->paid , '119.00000' , "$testname: 'salesinv partial payment' was fully paid");
581   is($bt->invoice_amount   , '119.00000' , "$testname: bt invoice amount was assigned partially paid amount");
582   is($bt->amount           , '299.29000' , "$testname: bt amount is stil there");
583   # next invoice, same bank transaction
584   $::form->{invoice_ids} = {
585     $bt->id => [ $ar_transaction_2->id ]
586   };
587
588   save_btcontroller_to_string();
589
590   $ar_transaction_2->load;
591   $bt->load;
592   is($ar_transaction_2->paid , '26.18000' , "$testname: 'salesinv partial payment' was fully paid");
593   is($bt->invoice_amount   , '145.18000' , "$testname: bt invoice amount was assigned partially paid amount");
594   is($bt->amount           , '299.29000' , "$testname: bt amount is stil there");
595   is(scalar @{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [bank_transaction_id => $bt->id ] )}, 4, "$testname 4 acc_trans entries created");
596
597   #  now check all 4 entries done so far and save paid acc_trans_ids for later use with reconcile
598   foreach my $acc_trans_id_entry (@{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [bank_transaction_id => $bt->id ] )}) {
599     isnt($acc_trans_id_entry->ar_id, undef, "$testname: bt linked with acc_trans and trans_id set");
600     my $rl = SL::DB::Manager::RecordLink->get_all(where => [ from_id => $bt->id, from_table => 'bank_transactions', to_id => $acc_trans_id_entry->ar_id ]);
601     is (ref $rl->[0], 'SL::DB::RecordLink', "$testname record link created");
602     my $acc_trans = SL::DB::Manager::AccTransaction->get_all(where => [acc_trans_id => $acc_trans_id_entry->acc_trans_id]);
603     foreach my $entry (@{ $acc_trans }) {
604       like(abs($entry->amount), qr/(119|26.18)/, "$testname: abs amount correct");
605       like($entry->chart_link, qr/(paid|AR)/, "$testname chart_link correct");
606       push @{ $::form->{bb_ids} }, $entry->acc_trans_id if $entry->chart_link =~ m/paid/;
607     }
608   }
609   # great we need one last booking to clear the whole bank transaction - we include skonto
610   my $ar_transaction_skonto = test_ar_transaction(invnumber  => 'salesinv skonto last case',
611                                                   payment_id => $payment_terms->id,
612                                                   amount     => 136.32,
613                                                  );
614
615   $::form->{invoice_ids} = {
616     $bt->id => [ $ar_transaction_skonto->id ]
617   };
618   $::form->{invoice_skontos} = {
619     $bt->id => [ 'with_skonto_pt' ]
620   };
621
622   save_btcontroller_to_string();
623
624   $ar_transaction_skonto->load;
625   $bt->load;
626   is($ar_transaction_skonto->paid , '162.22000' , "$testname: 'salesinv skonto fully paid");
627   is($bt->invoice_amount   , '299.29000' , "$testname: bt invoice amount was assigned partially paid amount");
628   is($bt->amount           , '299.29000' , "$testname: bt amount is stil there");
629   is(scalar @{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [bank_transaction_id => $bt->id ] )},
630        9, "$testname 9 acc_trans entries created");
631
632   # same loop as above, but only for the 3rd ar_id
633   foreach my $acc_trans_id_entry (@{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [ar_id => $ar_transaction_skonto->id ] )}) {
634     isnt($acc_trans_id_entry->ar_id, '', "$testname: bt linked with acc_trans and trans_id set");
635     my $rl = SL::DB::Manager::RecordLink->get_all(where => [ from_id => $bt->id, from_table => 'bank_transactions', to_id => $acc_trans_id_entry->ar_id ]);
636     is (ref $rl->[0], 'SL::DB::RecordLink', "$testname record link created");
637     my $acc_trans = SL::DB::Manager::AccTransaction->get_all(where => [acc_trans_id => $acc_trans_id_entry->acc_trans_id]);
638     foreach my $entry (@{ $acc_trans }) {
639       like($entry->chart_link, qr/(paid|AR)/, "$testname chart_link correct");
640       is ($entry->amount, '162.22000', "$testname full amont") if $entry->chart_link eq 'AR'; # full amount
641       like(abs($entry->amount), qr/(154.11|8.11)/, "$testname: abs amount correct") if $entry->chart_link =~ m/paid/;
642       push @{ $::form->{bb_ids} }, $entry->acc_trans_id if ($entry->chart_link =~ m/paid/ && $entry->amount == -154.11);
643     }
644   }
645   # done, now reconciliate all bookings
646   $::form->{bt_ids} = [ $bt->id ];
647   my $rec_controller = SL::Controller::Reconciliation->new;
648   my @errors = $rec_controller->_get_elements_and_validate;
649
650   is (scalar @errors, 0, "$testname unsuccesfull reconciliation with error: " . Dumper(@errors));
651   $rec_controller->_reconcile;
652   $bt->load;
653
654   # and check the cleared state of bt and the acc_transactions
655   is($bt->cleared, '1' , "$testname: bt cleared");
656   foreach (@{ $::form->{bb_ids} }) {
657     my $acc_trans = SL::DB::Manager::AccTransaction->find_by(acc_trans_id => $_);
658     is($acc_trans->cleared, '1' , "$testname: acc_trans entry cleared");
659   }
660   # now, this was a really bad idea and in general a major mistake. better undo and redo the whole bank transactions
661
662   $::form->{ids} = [ $bt->id ];
663   $bt_controller = SL::Controller::BankTransaction->new;
664   $bt_controller->action_unlink_bank_transaction('testcase' => 1);
665
666   $bt->load;
667
668   # and check the cleared state of bt and the acc_transactions
669   is($bt->cleared, '0' , "$testname: bt undo cleared");
670   is($bt->invoice_amount, '0.00000' , "$testname: bt undo invoice amount");
671   foreach (@{ $::form->{bb_ids} }) {
672     my $acc_trans = SL::DB::Manager::AccTransaction->find_by(acc_trans_id => $_);
673     is($acc_trans, undef , "$testname: cleared acc_trans entry completely removed");
674   }
675   # this was for data integrity for reconcile, now all the other options
676   is(scalar @{ SL::DB::Manager::BankTransactionAccTrans->get_all(where => [bank_transaction_id => $bt->id ] )},
677        0, "$testname 7 acc_trans entries deleted");
678   my $rl = SL::DB::Manager::RecordLink->get_all(where => [ from_id => $bt->id, from_table => 'bank_transactions' ]);
679   is (ref $rl->[0], '', "$testname record link removed");
680   # double safety and check ar.paid
681   # load all three invoices and check for paid-link via acc_trans and paid in general
682
683   $ar_transaction->load;
684   $ar_transaction_2->load;
685   $ar_transaction_skonto->load;
686
687   is(scalar @{ SL::DB::Manager::AccTransaction->get_all(
688      where => [ trans_id => $ar_transaction->id, chart_link => { like => '%paid%' } ])},
689      0, "$testname no more paid entries in acc_trans for ar_transaction");
690   is(scalar @{ SL::DB::Manager::AccTransaction->get_all(
691      where => [ trans_id => $ar_transaction_2->id, chart_link => { like => '%paid%' } ])},
692      0, "$testname no more paid entries in acc_trans for ar_transaction_2");
693   is(scalar @{ SL::DB::Manager::AccTransaction->get_all(
694      where => [ trans_id => $ar_transaction_skonto->id, chart_link => { like => '%paid%' } ])},
695      0, "$testname no more paid entries in acc_trans for ar_transaction_skonto");
696
697   is($ar_transaction->paid , '0.00000' , "$testname: 'salesinv fully unpaid");
698   is($ar_transaction_2->paid , '0.00000' , "$testname: 'salesinv 2 fully unpaid");
699   is($ar_transaction_skonto->paid , '0.00000' , "$testname: 'salesinv skonto fully unpaid");
700
701   # whew. w(h)a(n)t a whole lotta test
702 }
703
704
705 sub test_credit_note {
706
707   my $testname = 'test_credit_note';
708
709   my $part1 = new_part(   partnumber => 'T4254')->save;
710   my $part2 = new_service(partnumber => 'Serv1')->save;
711   my $credit_note = create_credit_note(
712     invnumber    => 'cn 1',
713     customer     => $customer,
714     transdate    => $dt,
715     taxincluded  => 0,
716     invoiceitems => [ create_invoice_item(part => $part1, qty =>  3, sellprice => 70),
717                       create_invoice_item(part => $part2, qty => 10, sellprice => 50),
718                     ]
719   );
720   my $bt            = create_bank_transaction(record        => $credit_note,
721                                                                 amount        => $credit_note->amount,
722                                                                 bank_chart_id => $bank->id,
723                                                                 transdate     => $dt_10,
724                                                                );
725   my ($agreement, $rule_matches) = $bt->get_agreement_with_invoice($credit_note);
726   is($agreement, 14, "points for credit note ok");
727   is($rule_matches, 'remote_account_number(3) exact_amount(4) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus14(2) ', "rules_matches for credit note ok");
728
729   $::form->{invoice_ids} = {
730     $bt->id => [ $credit_note->id ]
731   };
732
733   save_btcontroller_to_string();
734
735   $credit_note->load;
736   $bt->load;
737   is($credit_note->amount   , '-844.90000', "$testname: amount ok");
738   is($credit_note->netamount, '-710.00000', "$testname: netamount ok");
739   is($credit_note->paid     , '-844.90000', "$testname: paid ok");
740 }
741
742 sub test_neg_ap_transaction {
743   my (%params) = @_;
744   my $testname = 'test_neg_ap_transaction' . $params{invoice} ? ' invoice booking' : ' credit booking';
745   my $netamount = -20;
746   my $amount    = $::form->round_amount($netamount * 1.19,2);
747   my $invoice   = SL::DB::PurchaseInvoice->new(
748     invoice      => $params{invoice} // 0,
749     invnumber    => $params{invnumber} || 'test_neg_ap_transaction',
750     amount       => $amount,
751     netamount    => $netamount,
752     transdate    => $dt,
753     taxincluded  => 0,
754     vendor_id    => $vendor->id,
755     taxzone_id   => $vendor->taxzone_id,
756     currency_id  => $currency_id,
757     transactions => [],
758     notes        => 'test_neg_ap_transaction',
759   );
760   $invoice->add_ap_amount_row(
761     amount     => $invoice->netamount,
762     chart      => $ap_amount_chart,
763     tax_id     => $tax_9->id,
764   );
765
766   $invoice->create_ap_row(chart => $ap_chart);
767   $invoice->save;
768
769   is($invoice->netamount, -20  , "$testname: netamount ok");
770   is($invoice->amount   , -23.8, "$testname: amount ok");
771
772   my $bt            = create_bank_transaction(record        => $invoice,
773                                               amount        => $invoice->amount,
774                                               bank_chart_id => $bank->id,
775                                               transdate     => $dt_10,
776                                                                );
777
778   my ($agreement, $rule_matches) = $bt->get_agreement_with_invoice($invoice);
779   is($agreement, 16, "points for negative ap transaction ok");
780
781   $::form->{invoice_ids} = {
782     $bt->id => [ $invoice->id ]
783   };
784
785   save_btcontroller_to_string();
786
787   $invoice->load;
788   $bt->load;
789
790   is($invoice->amount   , '-23.80000', "$testname: amount ok");
791   is($invoice->netamount, '-20.00000', "$testname: netamount ok");
792   is($invoice->paid     , '-23.80000', "$testname: paid ok");
793   is($bt->invoice_amount, '23.80000', "$testname: bt invoice amount for ap was assigned");
794   is($bt->amount,         '23.80000', "$testname: bt  amount for ap was assigned");
795
796   return $invoice;
797 };
798 sub test_two_neg_ap_transaction {
799   my $testname='test_two_neg_ap_transaction';
800   my $netamount = -20;
801   my $amount    = $::form->round_amount($netamount * 1.19,2);
802   my $invoice   = SL::DB::PurchaseInvoice->new(
803     invoice      =>  0,
804     invnumber    => 'test_neg_ap_transaction',
805     amount       => $amount,
806     netamount    => $netamount,
807     transdate    => $dt,
808     taxincluded  => 0,
809     vendor_id    => $vendor->id,
810     taxzone_id   => $vendor->taxzone_id,
811     currency_id  => $currency_id,
812     transactions => [],
813     notes        => 'test_neg_ap_transaction',
814   );
815   $invoice->add_ap_amount_row(
816     amount     => $invoice->netamount,
817     chart      => $ap_amount_chart,
818     tax_id     => $tax_9->id,
819   );
820
821   $invoice->create_ap_row(chart => $ap_chart);
822   $invoice->save;
823
824   is($invoice->netamount, -20  , "$testname: netamount ok");
825   is($invoice->amount   , -23.8, "$testname: amount ok");
826
827   my $netamount_two = -1.14;
828   my $amount_two    = $::form->round_amount($netamount_two * 1.19,2);
829   my $invoice_two   = SL::DB::PurchaseInvoice->new(
830     invoice      => 0,
831     invnumber    => 'test_neg_ap_transaction_two',
832     amount       => $amount_two,
833     netamount    => $netamount_two,
834     transdate    => $dt,
835     taxincluded  => 0,
836     vendor_id    => $vendor->id,
837     taxzone_id   => $vendor->taxzone_id,
838     currency_id  => $currency_id,
839     transactions => [],
840     notes        => 'test_neg_ap_transaction_two',
841   );
842   $invoice_two->add_ap_amount_row(
843     amount     => $invoice_two->netamount,
844     chart      => $ap_amount_chart,
845     tax_id     => $tax_9->id,
846   );
847
848   $invoice_two->create_ap_row(chart => $ap_chart);
849   $invoice_two->save;
850
851   is($invoice_two->netamount, -1.14  , "$testname: netamount ok");
852   is($invoice_two->amount   , -1.36, "$testname: amount ok");
853
854
855   my $bt            = create_bank_transaction(record        => $invoice_two,
856                                               amount        => $invoice_two->amount + $invoice->amount,
857                                               bank_chart_id => $bank->id,
858                                               transdate     => $dt_10,
859                                                                );
860   # my ($agreement, $rule_matches) = $bt->get_agreement_with_invoice($invoice_two);
861   # is($agreement, 15, "points for negative ap transaction ok");
862
863   $::form->{invoice_ids} = {
864     $bt->id => [ $invoice->id, $invoice_two->id ]
865   };
866
867   save_btcontroller_to_string();
868
869   $invoice->load;
870   $invoice_two->load;
871   $bt->load;
872
873   is($invoice->amount   , '-23.80000', "$testname: first inv amount ok");
874   is($invoice->netamount, '-20.00000', "$testname: first inv netamount ok");
875   is($invoice->paid     , '-23.80000', "$testname: first inv paid ok");
876   is($invoice_two->amount   , '-1.36000', "$testname: second inv amount ok");
877   is($invoice_two->netamount, '-1.14000', "$testname: second inv netamount ok");
878   is($invoice_two->paid     , '-1.36000', "$testname: second inv paid ok");
879   is($bt->invoice_amount, '25.16000', "$testname: bt invoice amount for both invoices were assigned");
880
881
882   return ($invoice, $invoice_two);
883 };
884
885 sub test_ap_payment_transaction {
886   my (%params) = @_;
887   my $testname = 'test_ap_payment_transaction';
888   my $netamount = 115;
889   my $amount    = $::form->round_amount($netamount * 1.19,2);
890   my $invoice   = SL::DB::PurchaseInvoice->new(
891     invoice      => 0,
892     invnumber    => $params{invnumber} || $testname,
893     amount       => $amount,
894     netamount    => $netamount,
895     transdate    => $dt,
896     taxincluded  => 0,
897     vendor_id    => $vendor->id,
898     taxzone_id   => $vendor->taxzone_id,
899     currency_id  => $currency_id,
900     transactions => [],
901     notes        => $testname,
902   );
903   $invoice->add_ap_amount_row(
904     amount     => $invoice->netamount,
905     chart      => $ap_amount_chart,
906     tax_id     => $tax_9->id,
907   );
908
909   $invoice->create_ap_row(chart => $ap_chart);
910   $invoice->save;
911
912   is($invoice->netamount, 115  , "$testname: netamount ok");
913   is($invoice->amount   , 136.85, "$testname: amount ok");
914
915   my $bt            = create_bank_transaction(record        => $invoice,
916                                               amount        => $invoice->amount,
917                                               bank_chart_id => $bank->id,
918                                               transdate     => $dt_10,
919                                              );
920   $::form->{invoice_ids} = {
921     $bt->id => [ $invoice->id ]
922   };
923
924   save_btcontroller_to_string();
925
926   $invoice->load;
927   $bt->load;
928
929   is($invoice->amount   , '136.85000', "$testname: amount ok");
930   is($invoice->netamount, '115.00000', "$testname: netamount ok");
931   is($bt->amount,         '-136.85000', "$testname: bt amount ok");
932   is($invoice->paid     , '136.85000', "$testname: paid ok");
933   is($bt->invoice_amount, '-136.85000', "$testname: bt invoice amount for ap was assigned");
934
935   return $invoice;
936 };
937
938 sub test_ap_payment_part_transaction {
939   my (%params) = @_;
940   my $testname = 'test_ap_payment_p_transaction';
941   my $netamount = 115;
942   my $amount    = $::form->round_amount($netamount * 1.19,2);
943   my $invoice   = SL::DB::PurchaseInvoice->new(
944     invoice      => 0,
945     invnumber    => $params{invnumber} || $testname,
946     amount       => $amount,
947     netamount    => $netamount,
948     transdate    => $dt,
949     taxincluded  => 0,
950     vendor_id    => $vendor->id,
951     taxzone_id   => $vendor->taxzone_id,
952     currency_id  => $currency_id,
953     transactions => [],
954     notes        => $testname,
955   );
956   $invoice->add_ap_amount_row(
957     amount     => $invoice->netamount,
958     chart      => $ap_amount_chart,
959     tax_id     => $tax_9->id,
960   );
961
962   $invoice->create_ap_row(chart => $ap_chart);
963   $invoice->save;
964
965   is($invoice->netamount, 115  , "$testname: netamount ok");
966   is($invoice->amount   , 136.85, "$testname: amount ok");
967
968   my $bt            = create_bank_transaction(record        => $invoice,
969                                               amount        => $invoice->amount-100,
970                                               bank_chart_id => $bank->id,
971                                               transdate     => $dt_10,
972                                              );
973   $::form->{invoice_ids} = {
974     $bt->id => [ $invoice->id ]
975   };
976
977   save_btcontroller_to_string();
978
979   $invoice->load;
980   $bt->load;
981
982   is($invoice->amount   , '136.85000', "$testname: amount ok");
983   is($invoice->netamount, '115.00000', "$testname: netamount ok");
984   is($bt->amount,         '-36.85000', "$testname: bt amount ok");
985   is($invoice->paid     ,  '36.85000', "$testname: paid ok");
986   is($bt->invoice_amount, '-36.85000', "$testname: bt invoice amount for ap was assigned");
987
988   my $bt2           = create_bank_transaction(record        => $invoice,
989                                               amount        => 100,
990                                               bank_chart_id => $bank->id,
991                                               transdate     => $dt_10,
992                                              );
993   $::form->{invoice_ids} = {
994     $bt2->id => [ $invoice->id ]
995   };
996
997   save_btcontroller_to_string();
998   $invoice->load;
999   $bt2->load;
1000
1001   is($invoice->amount   , '136.85000', "$testname: amount ok");
1002   is($invoice->netamount, '115.00000', "$testname: netamount ok");
1003   is($bt2->amount,        '-100.00000',"$testname: bt amount ok");
1004   is($invoice->paid     , '136.85000', "$testname: paid ok");
1005   is($bt2->invoice_amount,'-100.00000', "$testname: bt invoice amount for ap was assigned");
1006
1007   return $invoice;
1008 };
1009
1010 sub test_neg_sales_invoice {
1011
1012   my $testname = 'test_neg_sales_invoice';
1013
1014   my $part1 = new_part(   partnumber => 'Funkenhaube öhm')->save;
1015   my $part2 = new_service(partnumber => 'Service-Pauschale Pasch!')->save;
1016
1017   my $neg_sales_inv = create_sales_invoice(
1018     invnumber    => '20172201',
1019     customer     => $customer,
1020     taxincluded  => 0,
1021     transdate     => $dt,
1022     invoiceitems => [ create_invoice_item(part => $part1, qty =>  3, sellprice => 70),
1023                       create_invoice_item(part => $part2, qty => 10, sellprice => -50),
1024                     ]
1025   );
1026   my $bt            = create_bank_transaction(record        => $neg_sales_inv,
1027                                                                 amount        => $neg_sales_inv->amount,
1028                                                                 bank_chart_id => $bank->id,
1029                                                                 transdate     => $dt,
1030                                                                 valutadate    => $dt,
1031                                                                );
1032   $::form->{invoice_ids} = {
1033     $bt->id => [ $neg_sales_inv->id ]
1034   };
1035
1036   save_btcontroller_to_string();
1037
1038   $neg_sales_inv->load;
1039   $bt->load;
1040   is($neg_sales_inv->amount   , '-345.10000', "$testname: amount ok");
1041   is($neg_sales_inv->netamount, '-290.00000', "$testname: netamount ok");
1042   is($neg_sales_inv->paid     , '-345.10000', "$testname: paid ok");
1043   is($bt->amount              , '-345.10000', "$testname: bt amount ok");
1044   is($bt->invoice_amount      , '-345.10000', "$testname: bt invoice_amount ok");
1045 }
1046
1047 sub test_bt_rule1 {
1048
1049   my $testname = 'test_bt_rule1';
1050
1051   $ar_transaction = test_ar_transaction(invnumber => 'bt_rule1', transdate => $dt);
1052
1053   my $bt = create_bank_transaction(record => $ar_transaction, transdate => $dt) or die "Couldn't create bank_transaction";
1054
1055   $ar_transaction->load;
1056   $bt->load;
1057   is($ar_transaction->paid   , '0.00000' , "$testname: not paid");
1058   is($bt->invoice_amount     , '0.00000' , "$testname: bt invoice amount was not assigned");
1059
1060   my $bt_controller = SL::Controller::BankTransaction->new;
1061   my ( $bt_transactions, $proposals ) = $bt_controller->gather_bank_transactions_and_proposals(bank_account => $bank_account);
1062
1063   is(scalar(@$bt_transactions)         , 1  , "$testname: one bank_transaction");
1064   is($bt_transactions->[0]->{agreement}, 20 , "$testname: agreement == 20");
1065   my $match = join ( ' ',@{$bt_transactions->[0]->{rule_matches}});
1066   #print "rule_matches='".$match."'\n";
1067   is($match,
1068      "remote_account_number(3) exact_amount(4) own_invoice_in_purpose(5) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus0(3) ",
1069      "$testname: rule_matches ok");
1070   $bt->invoice_amount($bt->amount);
1071   $bt->save;
1072   is($bt->invoice_amount     , '119.00000' , "$testname: bt invoice amount now set");
1073 };
1074
1075 sub test_sepa_export {
1076
1077   my $testname = 'test_sepa_export';
1078
1079   $ar_transaction = test_ar_transaction(invnumber => 'sepa1', transdate => $dt);
1080
1081   my $bt  = create_bank_transaction(record => $ar_transaction, transdate => $dt) or die "Couldn't create bank_transaction";
1082   my $se  = create_sepa_export();
1083   my $sei = create_sepa_export_item(
1084     chart_id       => $bank->id,
1085     ar_id          => $ar_transaction->id,
1086     sepa_export_id => $se->id,
1087     vc_iban        => $customer->iban,
1088     vc_bic         => $customer->bic,
1089     vc_mandator_id => $customer->mandator_id,
1090     vc_depositor   => $customer->depositor,
1091     amount         => $ar_transaction->amount,
1092   );
1093   require SL::SEPA::XML;
1094   my $sepa_xml   = SL::SEPA::XML->new('company'     => $customer->name,
1095                                       'creditor_id' => "id",
1096                                       'src_charset' => 'UTF-8',
1097                                       'message_id'  => "test",
1098                                       'grouped'     => 1,
1099                                       'collection'  => 1,
1100                                      );
1101   is($sepa_xml->{company}    , 'Test Customer OLE S.L. Ardbaerg AB');
1102
1103   $ar_transaction->load;
1104   $bt->load;
1105   $sei->load;
1106   is($ar_transaction->paid   , '0.00000' , "$testname: sepa1 not paid");
1107   is($bt->invoice_amount     , '0.00000' , "$testname: bt invoice amount was not assigned");
1108   is($bt->amount             , '119.00000' , "$testname: bt amount ok");
1109   is($sei->amount            , '119.00000' , "$testname: sepa export amount ok");
1110
1111   my $bt_controller = SL::Controller::BankTransaction->new;
1112   my ( $bt_transactions, $proposals ) = $bt_controller->gather_bank_transactions_and_proposals(bank_account => $bank_account);
1113
1114   is(scalar(@$bt_transactions)         , 1  , "$testname: one bank_transaction");
1115   is($bt_transactions->[0]->{agreement}, 25 , "$testname: agreement == 25");
1116   my $match = join ( ' ',@{$bt_transactions->[0]->{rule_matches}});
1117   is($match,
1118      "remote_account_number(3) exact_amount(4) own_invoice_in_purpose(5) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus0(3) sepa_export_item(5) ",
1119      "$testname: rule_matches ok");
1120 };
1121
1122 sub test_two_banktransactions {
1123
1124   my $testname = 'two_banktransactions';
1125
1126   my $ar_transaction_1 = test_ar_transaction(invnumber => 'salesinv10000' , amount => 2912.00 );
1127   my $bt1 = create_bank_transaction(record        => $ar_transaction_1,
1128                                     amount        => $ar_transaction_1->amount,
1129                                     purpose       => "Rechnung10000 beinahe",
1130                                     transdate     => $dt,
1131                                     bank_chart_id => $bank->id,
1132                                   ) or die "Couldn't create bank_transaction";
1133
1134   my $bt2 = create_bank_transaction(record        => $ar_transaction_1,
1135                                     amount        => $ar_transaction_1->amount + 0.01,
1136                                     purpose       => "sicher salesinv20000 vielleicht",
1137                                     transdate     => $dt,
1138                                     bank_chart_id => $bank->id,
1139                                   ) or die "Couldn't create bank_transaction";
1140
1141   my ($agreement1, $rule_matches1) = $bt1->get_agreement_with_invoice($ar_transaction_1);
1142   is($agreement1, 19, "bt1 19 points for ar_transaction_1 in $testname ok");
1143   #print "rule_matches1=".$rule_matches1."\n";
1144   is($rule_matches1,
1145      "remote_account_number(3) exact_amount(4) own_invnumber_in_purpose(4) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus0(3) ",
1146      "$testname: rule_matches ok");
1147   my ($agreement2, $rule_matches2) = $bt2->get_agreement_with_invoice($ar_transaction_1);
1148   is($agreement2, 11, "bt2 11 points for ar_transaction_1 in $testname ok");
1149   is($rule_matches2,
1150      "remote_account_number(3) depositor_matches(2) remote_name(2) payment_within_30_days(1) datebonus0(3) ",
1151      "$testname: rule_matches ok");
1152
1153   my $ar_transaction_2 = test_ar_transaction(invnumber => 'salesinv20000' , amount => 2912.01 );
1154   my $ar_transaction_3 = test_ar_transaction(invnumber => 'zweitemit10000', amount => 2912.00 );
1155      ($agreement1, $rule_matches1) = $bt1->get_agreement_with_invoice($ar_transaction_2);
1156
1157   is($agreement1, 11, "bt1 11 points for ar_transaction_2 in $testname ok");
1158
1159      ($agreement2, $rule_matches2) = $bt2->get_agreement_with_invoice($ar_transaction_2);
1160   is($agreement2, 20, "bt2 20 points for ar_transaction_2 in $testname ok");
1161
1162      ($agreement2, $rule_matches2) = $bt2->get_agreement_with_invoice($ar_transaction_1);
1163   is($agreement2, 11, "bt2 11 points for ar_transaction_1 in $testname ok");
1164
1165   my $bt3 = create_bank_transaction(record        => $ar_transaction_3,
1166                                     amount        => $ar_transaction_3->amount,
1167                                     purpose       => "sicher Rechnung10000 vielleicht",
1168                                     transdate     => $dt,
1169                                     bank_chart_id => $bank->id,
1170                                   ) or die "Couldn't create bank_transaction";
1171
1172   my ($agreement3, $rule_matches3) = $bt3->get_agreement_with_invoice($ar_transaction_3);
1173   is($agreement3, 19, "bt3 19 points for ar_transaction_3 in $testname ok");
1174
1175   $bt2->delete;
1176   $ar_transaction_2->delete;
1177
1178   #nun sollten zwei gleichwertige Rechnungen $ar_transaction_1 und $ar_transaction_3 für $bt1 gefunden werden
1179   #aber es darf keine Proposals geben mit mehreren Rechnungen
1180   my $bt_controller = SL::Controller::BankTransaction->new;
1181   my ( $bt_transactions, $proposals ) = $bt_controller->gather_bank_transactions_and_proposals(bank_account => $bank_account);
1182
1183   is(scalar(@$bt_transactions)   , 2  , "$testname: two bank_transaction");
1184   is(scalar(@$proposals)         , 0  , "$testname: no proposals");
1185
1186   $ar_transaction_3->delete;
1187
1188   # Jetzt gibt es zwei Kontobewegungen mit gleichen Punkten für eine Rechnung.
1189   # hier darf es auch keine Proposals geben
1190
1191   ( $bt_transactions, $proposals ) = $bt_controller->gather_bank_transactions_and_proposals(bank_account => $bank_account);
1192
1193   is(scalar(@$bt_transactions)   , 2  , "$testname: two bank_transaction");
1194   # odyn testfall - anforderungen so (noch) nicht in kivi
1195   # is(scalar(@$proposals)         , 0  , "$testname: no proposals");
1196
1197   # Jetzt gibt es zwei Kontobewegungen für eine Rechnung.
1198   # eine Bewegung bekommt mehr Punkte
1199   # hier darf es auch keine Proposals geben
1200   $bt3->update_attributes( purpose => "fuer Rechnung salesinv10000");
1201
1202   ( $bt_transactions, $proposals ) = $bt_controller->gather_bank_transactions_and_proposals(bank_account => $bank_account);
1203
1204   is(scalar(@$bt_transactions)   , 2  , "$testname: two bank_transaction");
1205   # odyn testfall - anforderungen so (noch) nicht in kivi
1206   # is(scalar(@$proposals)         , 1  , "$testname: one proposal");
1207
1208 };
1209 sub test_closedto {
1210
1211   my $testname = 'closedto';
1212
1213   my $ar_transaction_1 = test_ar_transaction(invnumber => 'salesinv10000' , amount => 2912.00 );
1214   my $bt1 = create_bank_transaction(record        => $ar_transaction_1,
1215                                     amount        => $ar_transaction_1->amount,
1216                                     purpose       => "Rechnung10000 beinahe",
1217                                     bank_chart_id => $bank->id,
1218                                   ) or die "Couldn't create bank_transaction";
1219
1220   $bt1->valutadate(DateTime->new(year => 2019, month => 12, day => 30));
1221   $bt1->save();
1222
1223   is($bt1->closed_period, 0, "$testname undefined closedto");
1224
1225   my $defaults = SL::DB::Manager::Default->get_all(limit => 1)->[0];
1226   $defaults->closedto(DateTime->new(year => 2019, month => 12, day => 31));
1227   $defaults->save();
1228   $::instance_conf->reload->data;
1229   $bt1->load();
1230   is($bt1->closed_period, 1, "$testname defined and next date closedto");
1231
1232   $bt1->valutadate(DateTime->new(year => 2020, month => 1, day => 1));
1233   $bt1->save();
1234   $bt1->load();
1235
1236   is($bt1->closed_period, 0, "$testname defined closedto and next date valuta");
1237   $defaults->closedto(undef);
1238   $defaults->save();
1239
1240 }
1241
1242 sub test_skonto_exact_ap_transaction {
1243
1244   my $testname = 'test_skonto_exact_ap_transaction';
1245
1246   $ap_transaction = test_ap_transaction(invnumber => 'ap transaction skonto',
1247                                         payment_id => $payment_terms->id,
1248                                        );
1249
1250   my $bt = create_bank_transaction(record        => $ap_transaction,
1251                                    bank_chart_id => $bank->id,
1252                                    transdate     => $dt,
1253                                    valutadate    => $dt,
1254                                    amount        => $ap_transaction->amount_less_skonto
1255                                   ) or die "Couldn't create bank_transaction";
1256
1257   $::form->{invoice_ids} = {
1258     $bt->id => [ $ap_transaction->id ]
1259   };
1260   $::form->{invoice_skontos} = {
1261     $bt->id => [ 'with_skonto_pt' ]
1262   };
1263
1264   save_btcontroller_to_string();
1265
1266   $ap_transaction->load;
1267   $bt->load;
1268   is($ap_transaction->paid   , '119.00000' , "$testname: ap transaction skonto was paid");
1269   is($ap_transaction->closed , 1           , "$testname: ap transaction skonto is closed");
1270   is($bt->invoice_amount     , '113.05000' , "$testname: bt invoice amount was assigned");
1271
1272 };
1273
1274 1;