Payment-Helfer: with_transaction() anstelle von do_transaction() nutzen
[kivitendo-erp.git] / SL / DB / Helper / Payment.pm
1 package SL::DB::Helper::Payment;
2
3 use strict;
4
5 use parent qw(Exporter);
6 our @EXPORT = qw(pay_invoice);
7 our @EXPORT_OK = qw(skonto_date skonto_charts amount_less_skonto within_skonto_period percent_skonto reference_account reference_amount open_amount open_percent remaining_skonto_days skonto_amount check_skonto_configuration valid_skonto_amount get_payment_suggestions validate_payment_type open_sepa_transfer_amount get_payment_select_options_for_bank_transaction create_bank_transaction exchangerate forex);
8 our %EXPORT_TAGS = (
9   "ALL" => [@EXPORT, @EXPORT_OK],
10 );
11
12 require SL::DB::Chart;
13 use Data::Dumper;
14 use DateTime;
15 use SL::DATEV qw(:CONSTANTS);
16 use SL::Locale::String qw(t8);
17 use List::Util qw(sum);
18 use SL::DB::Exchangerate;
19 use SL::DB::Currency;
20 use Carp;
21
22 #
23 # Public functions not exported by default
24 #
25
26 sub pay_invoice {
27   my ($self, %params) = @_;
28
29   require SL::DB::Tax;
30
31   my $is_sales = ref($self) eq 'SL::DB::Invoice';
32   my $mult = $is_sales ? 1 : -1;  # multiplier for getting the right sign depending on ar/ap
33
34   my $paid_amount = 0; # the amount that will be later added to $self->paid, should be in default currency
35
36   # default values if not set
37   $params{payment_type} = 'without_skonto' unless $params{payment_type};
38   validate_payment_type($params{payment_type});
39
40   # check for required parameters
41   Common::check_params(\%params, qw(chart_id transdate));
42
43   my $transdate_obj;
44   if (ref($params{transdate} eq 'DateTime')) {
45     $transdate_obj = $params{transdate};
46   } else {
47    $transdate_obj = $::locale->parse_date_to_object($params{transdate});
48   };
49   croak t8('Illegal date') unless ref $transdate_obj;
50
51   # check for closed period
52   my $closedto = $::locale->parse_date_to_object($::instance_conf->get_closedto);
53   if ( ref $closedto && $transdate_obj < $closedto ) {
54     croak t8('Cannot post payment for a closed period!');
55   };
56
57   # check for maximum number of future days
58   if ( $::instance_conf->get_max_future_booking_interval > 0 ) {
59     croak t8('Cannot post transaction above the maximum future booking date!') if $transdate_obj > DateTime->now->add( days => $::instance_conf->get_max_future_booking_interval );
60   };
61
62   # currency is either passed or use the invoice currency if it differs from the default currency
63   my ($exchangerate,$currency);
64   if ($params{currency} || $params{currency_id} || $self->currency_id != $::instance_conf->get_currency_id) {
65     if ($params{currency} || $params{currency_id} ) { # currency was specified
66       $currency = SL::DB::Manager::Currency->find_by(name => $params{currency}) || SL::DB::Manager::Currency->find_by(id => $params{currency_id});
67     } else { # use invoice currency
68       $currency = SL::DB::Manager::Currency->find_by(id => $self->currency_id);
69     };
70     die "no currency" unless $currency;
71     if ($currency->id == $::instance_conf->get_currency_id) {
72       $exchangerate = 1;
73     } else {
74       my $rate = SL::DB::Manager::Exchangerate->find_by(currency_id => $currency->id,
75                                                         transdate   => $transdate_obj,
76                                                        );
77       if ($rate) {
78         $exchangerate = $is_sales ? $rate->buy : $rate->sell;
79       } else {
80         die "No exchange rate for " . $transdate_obj->to_kivitendo;
81       };
82     };
83   } else { # no currency param given or currency is the same as default_currency
84     $exchangerate = 1;
85   };
86
87   # input checks:
88   if ( $params{'payment_type'} eq 'without_skonto' ) {
89     croak "invalid amount for payment_type 'without_skonto': $params{'amount'}\n" unless abs($params{'amount'}) > 0;
90   };
91
92   # options with_skonto_pt and difference_as_skonto don't require the parameter
93   # amount, but if amount is passed, make sure it matches the expected value
94   if ( $params{'payment_type'} eq 'difference_as_skonto' ) {
95     croak "amount $params{amount} doesn't match open amount " . $self->open_amount . ", diff = " . ($params{amount}-$self->open_amount) if $params{amount} && abs($self->open_amount - $params{amount} ) > 0.0000001;
96   } elsif ( $params{'payment_type'} eq 'with_skonto_pt' ) {
97     croak "amount $params{amount} doesn't match amount less skonto: " . $self->open_amount . "\n" if $params{amount} && abs($self->amount_less_skonto - $params{amount} ) > 0.0000001;
98     croak "payment type with_skonto_pt can't be used if payments have already been made" if $self->paid != 0;
99   };
100
101   # absolute skonto amount for invoice, use as reference sum to see if the
102   # calculated skontos add up
103   # only needed for payment_term "with_skonto_pt"
104
105   my $skonto_amount_check = $self->skonto_amount; # variable should be zero after calculating all skonto
106   my $total_open_amount   = $self->open_amount;
107
108   # account where money is paid to/from: bank account or cash
109   my $account_bank = SL::DB::Manager::Chart->find_by(id => $params{chart_id});
110   croak "can't find bank account" unless ref $account_bank;
111
112   my $reference_account = $self->reference_account;
113   croak "can't find reference account (link = AR/AP) for invoice" unless ref $reference_account;
114
115   my $memo   = $params{'memo'}   || '';
116   my $source = $params{'source'} || '';
117
118   my $rounded_params_amount = _round( $params{amount} ); # / $exchangerate);
119   my $fx_gain_loss_amount = 0; # for fx_gain and fx_loss
120
121   my $db = $self->db;
122   $db->with_transaction(sub {
123     my $new_acc_trans;
124
125     # all three payment type create 1 AR/AP booking (the paid part)
126     # difference_as_skonto creates n skonto bookings (1 for each tax type)
127     # with_skonto_pt creates 1 bank booking and n skonto bookings (1 for each tax type)
128     # without_skonto creates 1 bank booking
129
130     # as long as there is no automatic tax, payments are always booked with
131     # taxkey 0
132
133     unless ( $params{payment_type} eq 'difference_as_skonto' ) {
134       # cases with_skonto_pt and without_skonto
135
136       # for case with_skonto_pt we need to know the corrected amount at this
137       # stage if we are going to use $params{amount}
138
139       my $pay_amount = $rounded_params_amount;
140       $pay_amount = $self->amount_less_skonto if $params{payment_type} eq 'with_skonto_pt';
141
142       # bank account and AR/AP
143       $paid_amount += $pay_amount * $exchangerate;
144
145       my $amount = (-1 * $pay_amount) * $mult;
146
147
148       # total amount against bank, do we already know this by now?
149       $new_acc_trans = SL::DB::AccTransaction->new(trans_id   => $self->id,
150                                                    chart_id   => $account_bank->id,
151                                                    chart_link => $account_bank->link,
152                                                    amount     => $amount,
153                                                    transdate  => $transdate_obj,
154                                                    source     => $source,
155                                                    memo       => $memo,
156                                                    project_id => $params{project_id} ? $params{project_id} : undef,
157                                                    taxkey     => 0,
158                                                    tax_id     => SL::DB::Manager::Tax->find_by(taxkey => 0)->id);
159       $new_acc_trans->save;
160
161       # deal with fxtransaction
162       if ( $self->currency_id != $::instance_conf->get_currency_id ) {
163         my $fxamount = _round($amount - ($amount * $exchangerate));
164         $new_acc_trans = SL::DB::AccTransaction->new(trans_id       => $self->id,
165                                                      chart_id       => $account_bank->id,
166                                                      chart_link     => $account_bank->link,
167                                                      amount         => $fxamount * -1,
168                                                      transdate      => $transdate_obj,
169                                                      source         => $source,
170                                                      memo           => $memo,
171                                                      taxkey         => 0,
172                                                      fx_transaction => 1,
173                                                      tax_id         => SL::DB::Manager::Tax->find_by(taxkey => 0)->id);
174         $new_acc_trans->save;
175         # if invoice exchangerate differs from exchangerate of payment
176         # deal with fxloss and fxamount
177         if ($self->exchangerate and $self->exchangerate != 1 and $self->exchangerate != $exchangerate) {
178           my $fxgain_chart = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxgain_accno_id) || die "Can't determine fxgain chart";
179           my $fxloss_chart = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_fxloss_accno_id) || die "Can't determine fxloss chart";
180           my $gain_loss_amount = _round($amount * ($exchangerate - $self->exchangerate ) * -1,2);
181           my $gain_loss_chart = $gain_loss_amount > 0 ? $fxgain_chart : $fxloss_chart;
182           $fx_gain_loss_amount = $gain_loss_amount;
183
184           $new_acc_trans = SL::DB::AccTransaction->new(trans_id       => $self->id,
185                                                        chart_id       => $gain_loss_chart->id,
186                                                        chart_link     => $gain_loss_chart->link,
187                                                        amount         => $gain_loss_amount,
188                                                        transdate      => $transdate_obj,
189                                                        source         => $source,
190                                                        memo           => $memo,
191                                                        taxkey         => 0,
192                                                        fx_transaction => 0,
193                                                        tax_id         => SL::DB::Manager::Tax->find_by(taxkey => 0)->id);
194           $new_acc_trans->save;
195
196         };
197       };
198     };
199
200     if ( $params{payment_type} eq 'difference_as_skonto' or $params{payment_type} eq 'with_skonto_pt' ) {
201
202       my $total_skonto_amount;
203       if ( $params{payment_type} eq 'with_skonto_pt' ) {
204         $total_skonto_amount = $self->skonto_amount;
205       } elsif ( $params{payment_type} eq 'difference_as_skonto' ) {
206         $total_skonto_amount = $self->open_amount;
207       };
208
209       my @skonto_bookings = $self->skonto_charts($total_skonto_amount);
210
211       # error checking:
212       if ( $params{payment_type} eq 'difference_as_skonto' ) {
213         my $calculated_skonto_sum  = sum map { $_->{skonto_amount} } @skonto_bookings;
214         croak "calculated skonto for difference_as_skonto = $calculated_skonto_sum doesn't add up open amount: " . $self->open_amount unless _round($calculated_skonto_sum) == _round($self->open_amount);
215       };
216
217       my $reference_amount = $total_skonto_amount;
218
219       # create an acc_trans entry for each result of $self->skonto_charts
220       foreach my $skonto_booking ( @skonto_bookings ) {
221         next unless $skonto_booking->{'chart_id'};
222         next unless $skonto_booking->{'skonto_amount'} != 0;
223         my $amount = -1 * $skonto_booking->{skonto_amount};
224         $new_acc_trans = SL::DB::AccTransaction->new(trans_id   => $self->id,
225                                                      chart_id   => $skonto_booking->{'chart_id'},
226                                                      chart_link => SL::DB::Manager::Chart->find_by(id => $skonto_booking->{'chart_id'})->link,
227                                                      amount     => $amount * $mult,
228                                                      transdate  => $transdate_obj,
229                                                      source     => $params{source},
230                                                      taxkey     => 0,
231                                                      tax_id     => SL::DB::Manager::Tax->find_by(taxkey => 0)->id);
232
233         # the acc_trans entries are saved individually, not added to $self and then saved all at once
234         $new_acc_trans->save;
235
236         $reference_amount -= abs($amount);
237         $paid_amount      += -1 * $amount * $exchangerate;
238         $skonto_amount_check -= $skonto_booking->{'skonto_amount'};
239       };
240       if ( $params{payment_type} eq 'difference_as_skonto' ) {
241           die "difference_as_skonto calculated incorrectly, sum of calculated payments doesn't add up to open amount $total_open_amount, reference_amount = $reference_amount\n" unless _round($reference_amount) == 0;
242       }
243
244     };
245
246     my $arap_amount = 0;
247
248     if ( $params{payment_type} eq 'difference_as_skonto' ) {
249       $arap_amount = $total_open_amount;
250     } elsif ( $params{payment_type} eq 'without_skonto' ) {
251       $arap_amount = $rounded_params_amount;
252     } elsif ( $params{payment_type} eq 'with_skonto_pt' ) {
253       # this should be amount + sum(amount+skonto), but while we only allow
254       # with_skonto_pt for completely unpaid invoices we just use the value
255       # from the invoice
256       $arap_amount = $total_open_amount;
257     };
258
259     # regardless of payment_type there is always only exactly one arap booking
260     # TODO: compare $arap_amount to running total
261     my $arap_booking= SL::DB::AccTransaction->new(trans_id   => $self->id,
262                                                   chart_id   => $reference_account->id,
263                                                   chart_link => $reference_account->link,
264                                                   amount     => _round($arap_amount * $mult * $exchangerate - $fx_gain_loss_amount),
265                                                   transdate  => $transdate_obj,
266                                                   source     => '', #$params{source},
267                                                   taxkey     => 0,
268                                                   tax_id     => SL::DB::Manager::Tax->find_by(taxkey => 0)->id);
269     $arap_booking->save;
270
271     $fx_gain_loss_amount *= -1 if $self->is_sales;
272     $self->paid($self->paid + _round($paid_amount) + $fx_gain_loss_amount) if $paid_amount;
273     $self->datepaid($transdate_obj);
274     $self->save;
275
276     # make sure transactions will be reloaded the next time $self->transactions
277     # is called, as pay_invoice saves the acc_trans objects individually rather
278     # than adding them to the transaction relation array.
279     $self->forget_related('transactions');
280
281     my $datev_check = 0;
282     if ( $is_sales )  {
283       if ( (  $self->invoice && $::instance_conf->get_datev_check_on_sales_invoice  ) ||
284            ( !$self->invoice && $::instance_conf->get_datev_check_on_ar_transaction )) {
285         $datev_check = 1;
286       }
287     } else {
288       if ( (  $self->invoice && $::instance_conf->get_datev_check_on_purchase_invoice ) ||
289            ( !$self->invoice && $::instance_conf->get_datev_check_on_ap_transaction   )) {
290         $datev_check = 1;
291       }
292     }
293
294     if ( $datev_check ) {
295
296       my $datev = SL::DATEV->new(
297         exporttype => DATEV_ET_BUCHUNGEN,
298         format     => DATEV_FORMAT_KNE,
299         dbh        => $db->dbh,
300         trans_id   => $self->{id},
301       );
302
303       $datev->clean_temporary_directories;
304       $datev->export;
305
306       if ($datev->errors) {
307         # this exception should be caught by with_transaction, which handles the rollback
308         die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
309       }
310     }
311
312     1;
313
314   }) || die t8('error while paying invoice #1 : ', $self->invnumber) . $db->error . "\n";
315
316   return 1;
317 };
318
319 sub skonto_date {
320
321   my $self = shift;
322
323   my $is_sales = ref($self) eq 'SL::DB::Invoice';
324
325   my $skonto_date;
326
327   if ( $is_sales ) {
328     return undef unless ref $self->payment_terms;
329     return undef unless $self->payment_terms->terms_skonto > 0;
330     $skonto_date = DateTime->from_object(object => $self->transdate)->add(days => $self->payment_terms->terms_skonto);
331   } else {
332     return undef unless ref $self->vendor->payment_terms;
333     return undef unless $self->vendor->payment_terms->terms_skonto > 0;
334     $skonto_date = DateTime->from_object(object => $self->transdate)->add(days => $self->vendor->payment_terms->terms_skonto);
335   };
336
337   return $skonto_date;
338 };
339
340 sub reference_account {
341   my $self = shift;
342
343   my $is_sales = ref($self) eq 'SL::DB::Invoice';
344
345   require SL::DB::Manager::AccTransaction;
346
347   my $link_filter = $is_sales ? 'AR' : 'AP';
348
349   my $acc_trans = SL::DB::Manager::AccTransaction->find_by(
350      trans_id   => $self->id,
351      SL::DB::Manager::AccTransaction->chart_link_filter("$link_filter")
352   );
353
354   return undef unless ref $acc_trans;
355
356   my $reference_account = SL::DB::Manager::Chart->find_by(id => $acc_trans->chart_id);
357
358   return $reference_account;
359 };
360
361 sub reference_amount {
362   my $self = shift;
363
364   my $is_sales = ref($self) eq 'SL::DB::Invoice';
365
366   require SL::DB::Manager::AccTransaction;
367
368   my $link_filter = $is_sales ? 'AR' : 'AP';
369
370   my $acc_trans = SL::DB::Manager::AccTransaction->find_by(
371      trans_id   => $self->id,
372      SL::DB::Manager::AccTransaction->chart_link_filter("$link_filter")
373   );
374
375   return undef unless ref $acc_trans;
376
377   # this should be the same as $self->amount
378   return $acc_trans->amount;
379 };
380
381
382 sub open_amount {
383   my $self = shift;
384
385   # in the future maybe calculate this from acc_trans
386
387   # if the difference is 0.01 Cent this may end up as 0.009999999999998
388   # numerically, so round this value when checking for cent threshold >= 0.01
389
390   return $self->amount - $self->paid;
391 };
392
393 sub open_percent {
394   my $self = shift;
395
396   return 0 if $self->amount == 0;
397   my $open_percent;
398   if ( $self->open_amount < 0 ) {
399     # overpaid, currently treated identically
400     $open_percent = $self->open_amount * 100 / $self->amount;
401   } else {
402     $open_percent = $self->open_amount * 100 / $self->amount;
403   };
404
405   return _round($open_percent) || 0;
406 };
407
408 sub skonto_amount {
409   my $self = shift;
410
411   return $self->amount - $self->amount_less_skonto;
412 };
413
414 sub remaining_skonto_days {
415   my $self = shift;
416
417   return undef unless ref $self->skonto_date;
418
419   my $dur = DateTime::Duration->new($self->skonto_date - DateTime->today);
420   return $dur->delta_days();
421
422 };
423
424 sub percent_skonto {
425   my $self = shift;
426
427   my $is_sales = ref($self) eq 'SL::DB::Invoice';
428
429   my $percent_skonto = 0;
430
431   if ( $is_sales ) {
432     return undef unless ref $self->payment_terms;
433     return undef unless $self->payment_terms->percent_skonto > 0;
434     $percent_skonto = $self->payment_terms->percent_skonto;
435   } else {
436     return undef unless ref $self->vendor->payment_terms;
437     return undef unless $self->vendor->payment_terms->terms_skonto > 0;
438     $percent_skonto = $self->vendor->payment_terms->percent_skonto;
439   };
440
441   return $percent_skonto;
442 };
443
444 sub amount_less_skonto {
445   # amount that has to be paid if skonto applies, always return positive rounded values
446   # the result is rounded so we can directly compare it with the user input
447   my $self = shift;
448
449   my $is_sales = ref($self) eq 'SL::DB::Invoice';
450
451   my $percent_skonto = $self->percent_skonto || 0;
452
453   return _round($self->amount - ( $self->amount * $percent_skonto) );
454
455 };
456
457 sub check_skonto_configuration {
458   my $self = shift;
459
460   my $is_sales = ref($self) eq 'SL::DB::Invoice';
461
462   my $skonto_configured = 1; # default is assume skonto works
463
464   # my $transactions = $self->transactions;
465   foreach my $transaction (@{ $self->transactions }) {
466     # find all transactions with an AR_amount or AP_amount link
467     my $tax = SL::DB::Manager::Tax->get_first( where => [taxkey => $transaction->taxkey]);
468     croak "no tax for taxkey " . $transaction->{taxkey} unless ref $tax;
469
470     $transaction->{chartlinks} = { map { $_ => 1 } split(m/:/, $transaction->chart_link) };
471     if ( $is_sales && $transaction->{chartlinks}->{AR_amount} ) {
472       $skonto_configured = 0 unless $tax->skonto_sales_chart_id;
473     } elsif ( !$is_sales && $transaction->{chartlinks}->{AP_amount}) {
474       $skonto_configured = 0 unless $tax->skonto_purchase_chart_id;
475     };
476   };
477
478   return $skonto_configured;
479 };
480
481 sub open_sepa_transfer_amount {
482   my $self = shift;
483
484   my ($vc, $key, $type);
485   if ( ref($self) eq 'SL::DB::Invoice' ) {
486     $vc   = 'customer';
487     $key  = 'ap_id';
488     $type = 'ar';
489   } else {
490     $vc   = 'vendor';
491     $key  = 'ap_id';
492     $type = 'ap';
493   };
494
495   my $sql = qq|SELECT SUM(sei.amount) AS amount FROM sepa_export_items sei | .
496             qq| LEFT JOIN sepa_export se ON (sei.sepa_export_id = se.id)   | .
497             qq| WHERE $key = ? AND NOT se.closed AND (se.vc = '$vc')       |;
498
499   my ($open_sepa_amount) = $self->db->dbh->selectrow_array($sql, undef, $self->id);
500
501   return $open_sepa_amount || 0;
502
503 };
504
505
506 sub skonto_charts {
507   my $self = shift;
508
509   # TODO: use param for amount, may also want to calculate skonto_amounts by
510   # passing percentage in the future
511
512   my $amount = shift || $self->skonto_amount;
513
514   croak "no amount passed to skonto_charts" unless abs(_round($amount)) >= 0.01;
515
516   # TODO: check whether there are negative values in invoice / acc_trans ... credited items
517
518   # don't check whether skonto applies, because user may want to override this
519   # return undef unless $self->percent_skonto;  # for is_sales
520   # return undef unless $self->vendor->payment_terms->percent_skonto;  # for purchase
521
522   my $is_sales = ref($self) eq 'SL::DB::Invoice';
523
524   my $mult = $is_sales ? 1 : -1;  # multiplier for getting the right sign
525
526   my @skonto_charts;  # resulting array with all income/expense accounts that have to be corrected
527
528   # calculate effective skonto (percentage) in difference_as_skonto mode
529   # only works if there are no negative acc_trans values
530   my $effective_skonto_rate = $amount ? $amount / $self->amount : 0;
531
532   # checks:
533   my $total_skonto_amount  = 0;
534   my $total_rounding_error = 0;
535
536   my $reference_ARAP_amount = 0;
537
538   # my $transactions = $self->transactions;
539   foreach my $transaction (@{ $self->transactions }) {
540     # find all transactions with an AR_amount or AP_amount link
541     $transaction->{chartlinks} = { map { $_ => 1 } split(m/:/, $transaction->{chart_link}) };
542     # second condition is that we can determine an automatic Skonto account for each AR_amount entry
543
544     if ( ( $is_sales && $transaction->{chartlinks}->{AR_amount} ) or ( !$is_sales && $transaction->{chartlinks}->{AP_amount}) ) {
545         # $reference_ARAP_amount += $transaction->{amount} * $mult;
546
547         # quick hack that works around problem of non-unique tax keys in SKR04
548         my $tax = SL::DB::Manager::Tax->get_first( where => [taxkey => $transaction->{taxkey}]);
549         croak "no tax for taxkey " . $transaction->{taxkey} unless ref $tax;
550
551         if ( $is_sales ) {
552           die t8('no skonto_chart configured for taxkey #1 : #2 : #3', $transaction->{taxkey} , $tax->taxdescription , $tax->rate*100) unless ref $tax->skonto_sales_chart;
553         } else {
554           die t8('no skonto_chart configured for taxkey #1 : #2 : #3', $transaction->{taxkey} , $tax->taxdescription , $tax->rate*100) unless ref $tax->skonto_purchase_chart;
555         };
556
557         my $skonto_amount_unrounded;
558
559         my $skonto_percent_abs = $self->amount ? abs($transaction->amount * (1 + $tax->rate) * 100 / $self->amount) : 0;
560
561         my $transaction_amount = abs($transaction->{amount} * (1 + $tax->rate));
562         my $transaction_skonto_percent = abs($transaction_amount/$self->amount); # abs($transaction->{amount} * (1 + $tax->rate));
563
564
565         $skonto_amount_unrounded   = abs($amount * $transaction_skonto_percent);
566         my $skonto_amount_rounded  = _round($skonto_amount_unrounded);
567         my $rounding_error         = $skonto_amount_unrounded - $skonto_amount_rounded;
568         my $rounded_rounding_error = _round($rounding_error);
569
570         $total_rounding_error += $rounding_error;
571         $total_skonto_amount  += $skonto_amount_rounded;
572
573         my $rec = {
574           # skonto_percent_abs: relative part of amount + tax to the total invoice amount
575           'skonto_percent_abs'     => $skonto_percent_abs,
576           'chart_id'               => $is_sales ? $tax->skonto_sales_chart->id : $tax->skonto_purchase_chart->id,
577           'skonto_amount'          => $skonto_amount_rounded,
578           # 'rounding_error'         => $rounding_error,
579           # 'rounded_rounding_error' => $rounded_rounding_error,
580         };
581
582         push @skonto_charts, $rec;
583       };
584   };
585
586   # if the rounded sum of all rounding_errors reaches 0.01 this sum is
587   # subtracted from the largest skonto_amount
588   my $rounded_total_rounding_error = abs(_round($total_rounding_error));
589
590   if ( $rounded_total_rounding_error > 0 ) {
591     my $highest_amount_pos = 0;
592     my $highest_amount = 0;
593     my $i = -1;
594     foreach my $ref ( @skonto_charts ) {
595       $i++;
596       if ( $ref->{skonto_amount} > $highest_amount ) {
597         $highest_amount     = $ref->{skonto_amount};
598         $highest_amount_pos = $i;
599       };
600     };
601     $skonto_charts[$i]->{skonto_amount} -= $rounded_total_rounding_error;
602   };
603
604   return @skonto_charts;
605 };
606
607
608 sub within_skonto_period {
609   my $self = shift;
610   my $dateref = shift || DateTime->now->truncate( to => 'day' );
611
612   return undef unless ref $dateref eq 'DateTime';
613   return 0 unless $self->skonto_date;
614
615   # return 1 if requested date (or today) is inside skonto period
616   # this will also return 1 if date is before the invoice date
617   return $dateref <= $self->skonto_date;
618 };
619
620 sub valid_skonto_amount {
621   my $self = shift;
622   my $amount = shift || 0;
623   my $max_skonto_percent = 0.10;
624
625   return 0 unless $amount > 0;
626
627   # does this work for other currencies?
628   return ($self->amount*$max_skonto_percent) > $amount;
629 };
630
631 sub get_payment_select_options_for_bank_transaction {
632   my ($self, $bt_id, %params) = @_;
633
634   my $bt = SL::DB::Manager::BankTransaction->find_by( id => $bt_id );
635   die unless $bt;
636
637   my $open_amount = $self->open_amount;
638
639   my @options;
640   if ( $open_amount &&                   # invoice amount not 0
641        $self->skonto_date &&             # check whether skonto applies
642        abs(abs($self->amount_less_skonto) - abs($bt->amount)) < 0.01 &&
643        $self->check_skonto_configuration) {
644          if ( $self->within_skonto_period($bt->transdate) ) {
645            push(@options, { payment_type => 'without_skonto', display => t8('without skonto') });
646            push(@options, { payment_type => 'with_skonto_pt', display => t8('with skonto acc. to pt'), selected => 1 });
647          } else {
648            push(@options, { payment_type => 'without_skonto', display => t8('without skonto') , selected => 1 });
649            push(@options, { payment_type => 'with_skonto_pt', display => t8('with skonto acc. to pt')});
650          };
651   };
652
653   return @options;
654
655 };
656
657 sub exchangerate {
658   my ($self) = @_;
659
660   return 1 if $self->currency_id == $::instance_conf->get_currency_id;
661
662   die "transdate isn't a DateTime object:" . ref($self->transdate) unless ref($self->transdate) eq 'DateTime';
663   my $rate = SL::DB::Manager::Exchangerate->find_by(currency_id => $self->currency_id,
664                                                     transdate   => $self->transdate,
665                                                    );
666   return undef unless $rate;
667
668   return $self->is_sales ? $rate->buy : $rate->sell; # also undef if not defined
669 };
670
671 sub get_payment_suggestions {
672
673   my ($self, %params) = @_;
674
675   my $open_amount = $self->open_amount;
676   $open_amount   -= $self->open_sepa_transfer_amount if $params{sepa};
677
678   $self->{invoice_amount_suggestion} = $open_amount;
679   undef $self->{payment_select_options};
680   push(@{$self->{payment_select_options}} , { payment_type => 'without_skonto',  display => t8('without skonto') });
681   if ( $self->within_skonto_period ) {
682     # If there have been no payments yet suggest amount_less_skonto, otherwise the open amount
683     if ( $open_amount &&                   # invoice amount not 0
684          $open_amount == $self->amount &&  # no payments yet, or sum of payments and sepa export amounts is zero
685          $self->check_skonto_configuration) {
686       $self->{invoice_amount_suggestion} = $self->amount_less_skonto;
687       push(@{$self->{payment_select_options}} , { payment_type => 'with_skonto_pt',  display => t8('with skonto acc. to pt') , selected => 1 });
688     } else {
689       if ( ( $self->valid_skonto_amount($self->open_amount) || $self->valid_skonto_amount($open_amount) ) and not $params{sepa} ) {
690         $self->{invoice_amount_suggestion} = $open_amount;
691         # only suggest difference_as_skonto if open_amount exactly matches skonto_amount
692         # AND we aren't in SEPA mode
693         my $selected = 0;
694         $selected = 1 if _round($open_amount) == _round($self->skonto_amount);
695         push(@{$self->{payment_select_options}} , { payment_type => 'difference_as_skonto',  display => t8('difference as skonto') , selected => $selected });
696       };
697     };
698   } else {
699     # invoice was configured with skonto, but skonto date has passed, or no skonto available
700     $self->{invoice_amount_suggestion} = $open_amount;
701     # difference_as_skonto doesn't make any sense for SEPA transfer, as this doesn't cause any actual payment
702     if ( $self->valid_skonto_amount($self->open_amount) && not $params{sepa} ) {
703       push(@{$self->{payment_select_options}} , { payment_type => 'difference_as_skonto',  display => t8('difference as skonto') , selected => 0 });
704     };
705   };
706   return 1;
707 };
708
709 sub validate_payment_type {
710   my $payment_type = shift;
711
712   my %allowed_payment_types = map { $_ => 1 } qw(without_skonto with_skonto_pt difference_as_skonto);
713   croak "illegal payment type: $payment_type, must be one of: " . join(' ', keys %allowed_payment_types) unless $allowed_payment_types{ $payment_type };
714
715   return 1;
716 }
717
718 sub create_bank_transaction {
719   my ($self, %params) = @_;
720
721   require SL::DB::Chart;
722   require SL::DB::BankAccount;
723
724   my $bank_chart;
725   if ( $params{chart_id} ) {
726     $bank_chart = SL::DB::Manager::Chart->find_by(chart_id => $params{chart_id}) or die "Can't find bank chart";
727   } elsif ( $::instance_conf->get_ar_paid_accno_id ) {
728     $bank_chart   = SL::DB::Manager::Chart->find_by(id => $::instance_conf->get_ar_paid_accno_id);
729   } else {
730     $bank_chart = SL::DB::Manager::Chart->find_by(description => 'Bank') or die "Can't find bank chart";
731   };
732   my $bank_account = SL::DB::Manager::BankAccount->find_by(chart_id => $bank_chart->id) or die "Can't find bank account for chart";
733
734   my $multiplier = $self->is_sales ? 1 : -1;
735   my $amount = ($params{amount} || $self->amount) * $multiplier;
736
737   my $transdate = $params{transdate} || DateTime->today;
738
739   my $bt = SL::DB::BankTransaction->new(
740     local_bank_account_id => $bank_account->id,
741     remote_bank_code      => $self->customervendor->bank_code,
742     remote_account_number => $self->customervendor->account_number,
743     transdate             => $transdate,
744     valutadate            => $transdate,
745     amount                => $::form->round_amount($amount, 2),
746     currency              => $self->currency->id,
747     remote_name           => $self->customervendor->depositor,
748     purpose               => $params{purpose} || $self->invnumber
749   )->save;
750 };
751
752
753 sub forex {
754   my ($self) = @_;
755   $self->currency_id == $::instance_conf->get_currency_id ? return 0 : return 1;
756 };
757
758 sub _round {
759   my $value = shift;
760   my $num_dec = 2;
761   return $::form->round_amount($value, 2);
762 }
763
764 1;
765
766 __END__
767
768 =pod
769
770 =head1 NAME
771
772 SL::DB::Helper::Payment  Mixin providing helper methods for paying C<Invoice>
773                          and C<PurchaseInvoice> objects and using skonto
774
775 =head1 SYNOPSIS
776
777 In addition to actually causing a payment via pay_invoice this helper contains
778 many methods that help in determining information about the status of the
779 invoice, such as the remaining open amount, whether skonto applies, until which
780 date skonto applies, the skonto amount and relative percentages, what to do
781 with skonto, ...
782
783 To prevent duplicate code this was all added in this mixin rather than directly
784 in SL::DB::Invoice and SL::DB::PurchaseInvoice.
785
786 =over 4
787
788 =item C<pay_invoice %params>
789
790 Create a payment booking for an existing invoice object (type ar/ap/is/ir) via
791 a configured bank account.
792
793 This function deals with all the acc_trans entries and also updates paid and datepaid.
794
795 Example:
796
797   my $ap   = SL::DB::Manager::PurchaseInvoice->find_by( invnumber => '1');
798   my $bank = SL::DB::Manager::BankAccount->find_by( name => 'Bank');
799   $ap->pay_invoice(chart_id      => $bank->chart_id,
800                    amount        => $ap->open_amount,
801                    transdate     => DateTime->now->to_kivitendo,
802                    memo          => 'foobar',
803                    source        => 'barfoo',
804                    payment_type  => 'without_skonto',  # default if not specified
805                    project_id    => 25,
806                   );
807
808 or with skonto:
809   $ap->pay_invoice(chart_id      => $bank->chart_id,
810                    amount        => $ap->amount,       # doesn't need to be specified
811                    transdate     => DateTime->now->to_kivitendo,
812                    memo          => 'foobar',
813                    source        => 'barfoo',
814                    payment_type  => 'with_skonto',
815                   );
816
817 or in a certain currency:
818   $ap->pay_invoice(chart_id      => $bank->chart_id,
819                    amount        => 500,
820                    currency      => 'USD',
821                    transdate     => DateTime->now->to_kivitendo,
822                    memo          => 'foobar',
823                    source        => 'barfoo',
824                    payment_type  => 'with_skonto',
825                   );
826
827 Allowed payment types are:
828   without_skonto with_skonto_pt difference_as_skonto
829
830 The option C<payment_type> allows for a basic skonto mechanism.
831
832 C<without_skonto> is the default mode, "amount" is paid to the account in
833 chart_id. This can also be used for partial payments and corrections via
834 negative amounts.
835
836 C<with_skonto_pt> can't be used for partial payments. When used on unpaid
837 invoices the whole amount is paid, with the skonto part automatically being
838 booked according to the skonto chart configured in the tax settings for each
839 tax key. If an amount is passed it is ignored and the actual configured skonto
840 amount is used.
841
842 C<difference_as_skonto> can only be used after partial payments have been made,
843 the whole specified amount is booked according to the skonto charts configured
844 in the tax settings for each tax key.
845
846 So passing amount doesn't have any effect for the cases C<with_skonto_pt> and
847 C<difference_as_skonto>, as all necessary values are taken from the stored
848 invoice.
849
850 The skonto modes automatically calculate the relative amounts for a mix of
851 taxes, e.g. items with 7% and 19% in one invoice. There is a helper method
852 skonto_charts, which calculates the relative percentages according to the
853 amounts in acc_trans (which are grouped by tax).
854
855 There is currently no way of excluding certain items in an invoice from having
856 skonto applied to them.  If this feature was added to parts the calculation
857 method of relative skonto would have to be completely rewritten using the
858 invoice items rather than acc_trans.
859
860 The skonto modes also still don't automatically correct the tax, this still has
861 to be done manually. Therefore all payments generated by pay_invoice have
862 taxkey 0.
863
864 There is currently no way to directly pay an invoice via this method if the
865 effective skonto differs from the skonto according to the payment terms
866 configured for the invoice/vendor.
867
868 In this case one has to pay in two steps: first the actual paid amount via
869 "without skonto", and then the remainder via "difference_as_skonto". The user
870 has to there actively decide whether to accept the differing skonto.
871
872 Because of the way skonto_charts works the calculation doesn't work if there
873 are negative values in acc_trans. E.g. one invoice with a positive value for
874 19% tax and a negative value for the acc_trans line with 7%
875
876 Skonto doesn't/shouldn't apply if the invoice contains credited items.
877
878 If no amount is given the whole open amout is paid.
879
880 If neither currency or currency_id are given as params, the currency of the
881 invoice is assumed to be the payment currency.
882
883 =item C<reference_account>
884
885 Returns a chart object which is the chart of the invoice with link AR or AP.
886
887 Example (1200 is the AR account for SKR04):
888   my $invoice = invoice(invnumber => '144');
889   $invoice->reference_account->accno
890   # 1200
891
892 =item C<percent_skonto>
893
894 Returns the configured skonto percentage of the payment terms of an invoice,
895 e.g. 0.02 for 2%. Payment terms come from invoice settings for ar, from vendor
896 settings for ap.
897
898 =item C<amount_less_skonto>
899
900 If the invoice has a payment term (via ar for sales, via vendor for purchase),
901 calculate the amount to be paid in the case of skonto.  This doesn't check,
902 whether skonto applies (i.e. skonto doesn't wasn't exceeded), it just subtracts
903 the configured percentage (e.g. 2%) from the total amount.
904
905 The returned value is rounded to two decimals.
906
907 =item C<skonto_date>
908
909 The date up to which skonto may be taken. This is calculated from the invoice
910 date + the number of days configured in the payment terms.
911
912 This method can also be used to determine whether skonto applies for the
913 invoice, as it returns undef if there is no payment term or skonto days is set
914 to 0.
915
916 =item C<within_skonto_period [DATE]>
917
918 Returns 0 or 1.
919
920 Checks whether the invoice has payment terms configured, and whether the date
921 is within the skonto max date. If no date is passed the current date is used.
922
923 You can also pass a dateref object as a parameter to check whether skonto
924 applies for that date rather than the current date.
925
926 =item C<valid_skonto_amount>
927
928 Takes an amount as an argument and checks whether the amount is less than 10%
929 of the total amount of the invoice. The value of 10% is currently hardcoded in
930 the method. This method is currently used to check whether to offer the payment
931 option "difference as skonto".
932
933 Example:
934  if ( $invoice->valid_skonto_amount($invoice->open_amount) ) {
935    # ... do something
936  }
937
938 =item C<skonto_charts [$amount]>
939
940 Returns a list of chart_ids and some calculated numbers that can be used for
941 paying the invoice with skonto. This function will automatically calculate the
942 relative skonto amounts even if the invoice contains several types of taxes
943 (e.g. 7% and 19%).
944
945 Example usage:
946   my $invoice = SL::DB::Manager::Invoice->find_by(invnumber => '211');
947   my @skonto_charts = $invoice->skonto_charts;
948
949 or with the total skonto amount as an argument:
950   my @skonto_charts = $invoice->skonto_charts($invoice->open_amount);
951
952 The following values are generated for each chart:
953
954 =over 2
955
956 =item C<chart_id>
957
958 The chart id of the skonto amount to be booked.
959
960 =item C<skonto_amount>
961
962 The total amount to be paid to the account
963
964 =item C<skonto_percent>
965
966 The relative percentage of that skonto chart. This can be useful if the actual
967 ekonto that is paid deviates from the granted skonto, e.g. customer effectively
968 pays 2.6% skonto instead of 2%, and we accept this. Then we can still calculate
969 the relative skonto amounts for different taxes based on the absolute
970 percentages. Used for case C<difference_as_skonto>.
971
972 =item C<skonto_percent_abs>
973
974 The absolute percentage of that skonto chart in relation to the total amount.
975 Used to calculate skonto_amount for case C<with_skonto_pt>.
976
977 =back
978
979 If the invoice contains several types of taxes then skonto_charts can be used
980 to calculate the relative amounts.
981
982 Example in console of an invoice with 100 Euro at 7% and 100 Euro at 19% with
983 tax not included:
984
985   my $invoice = invoice(invnumber => '144');
986   $invoice->amount
987   226.00000
988   $invoice->payment_terms->percent_skonto
989   0.02
990   $invoice->skonto_charts
991   pp $invoice->skonto_charts
992   #             $VAR1 = {
993   #               'chart_id'       => 128,
994   #               'skonto_amount'  => '2.14',
995   #               'skonto_percent' => '47.3451327433627'
996   #             };
997   #             $VAR2 = {
998   #               'chart_id'       => 130,
999   #               'skonto_amount'  => '2.38',
1000   #               'skonto_percent' => '52.654867256637'
1001   #             };
1002
1003 C<skonto_charts> always returns positive values (abs) for C<skonto_amount> and
1004 C<skonto_percent>.
1005
1006 C<skonto_charts> generates one entry for each acc_trans entry. ar and ap
1007 bookings only have one acc_trans entry for each taxkey (e.g. 7% and 19%).  This
1008 is because all the items are grouped according to the Buchungsgruppen mechanism
1009 and the totals are written to acc_trans.  For is and ir it is possible to have
1010 several acc_trans entries with the same tax. In this case skonto_charts
1011 generates a skonto booking for each acc_trans income/expense entry.
1012
1013 In the future this function may also be used to calculate the corrections for
1014 the income tax.
1015
1016 =item C<open_amount>
1017
1018 Unrounded total open amount of invoice (amount - paid).
1019 Doesn't take into account pending SEPA transfers.
1020
1021 =item C<open_percent>
1022
1023 Percentage of the invoice that is still unpaid, e.g. 100,00 if no payments have
1024 been made yet, 0,00 if fully paid.
1025
1026 =item C<remaining_skonto_days>
1027
1028 How many days skonto can still be taken, calculated from current day. Returns 0
1029 if current day is the max skonto date, and negative number if skonto date has
1030 already passed.
1031
1032 Returns undef if skonto is not configured for that invoice.
1033
1034 =item C<get_payment_suggestions %params>
1035
1036 Creates data intended for an L.select_tag dropdown that can be used in a
1037 template. Depending on the rules it will choose from the options
1038 without_skonto, with_skonto_pt and difference_as_skonto, and select the most
1039 likely one.
1040
1041 If the parameter "sepa" is passed, the SEPA export payments that haven't been
1042 executed yet are considered when determining the open amount of the invoice.
1043
1044 The current rules are:
1045
1046 =over 2
1047
1048 =item * without_skonto is always an option
1049
1050 =item * with_skonto_pt is only offered if there haven't been any payments yet and the current date is within the skonto period.
1051
1052 =item * difference_as_skonto is only offered if there have already been payments made and the open amount is smaller than 10% of the total amount.
1053
1054 with_skonto_pt will only be offered, if all the AR_amount/AP_amount have a
1055 taxkey with a configured skonto chart
1056
1057 =back
1058
1059 It will also fill $self->{invoice_amount_suggestion} with either the open
1060 amount, or if with_skonto_pt is selected, with amount_less_skonto, so the
1061 template can fill the input with the likely amount.
1062
1063 Example in console:
1064   my $ar = invoice( invnumber => '257');
1065   $ar->get_payment_suggestions;
1066   print $ar->{invoice_amount_suggestion} . "\n";
1067   # 97.23
1068   pp $ar->{payment_select_options}
1069   # $VAR1 = [
1070   #         {
1071   #           'display' => 'ohne Skonto',
1072   #           'payment_type' => 'without_skonto'
1073   #         },
1074   #         {
1075   #           'display' => 'mit Skonto nach ZB',
1076   #           'payment_type' => 'with_skonto_pt',
1077   #           'selected' => 1
1078   #         }
1079   #       ];
1080
1081 The resulting array $ar->{payment_select_options} can be used in a template
1082 select_tag using value_key and title_key:
1083
1084 [% L.select_tag('payment_type_' _ loop.count, invoice.payment_select_options, value_key => 'payment_type', title_key => 'display', id => 'payment_type_' _ loop.count) %]
1085
1086 It would probably make sense to have different rules for the pre-selected items
1087 for sales and purchase, and to also make these rules configurable in the
1088 defaults. E.g. when creating a SEPA bank transfer for vendor invoices a company
1089 might always want to pay quickly making use of skonto, while another company
1090 might always want to pay as late as possible.
1091
1092 =item C<get_payment_select_options_for_bank_transaction $banktransaction_id %params>
1093
1094 Make suggestion for a skonto payment type by returning an HTML blob of the options
1095 of a HTML drop-down select with the most likely option preselected.
1096
1097 This is a helper function for BankTransaction/ajax_payment_suggestion.
1098
1099 We are working with an existing payment, so difference_as_skonto never makes sense.
1100
1101 If skonto is possible (skonto_date exists), add two possibilities:
1102 without_skonto and with_skonto_pt if payment date is within skonto_date,
1103 preselect with_skonto_pt, otherwise preselect without skonto.
1104
1105 =item C<create_bank_transaction %params>
1106
1107 Method used for testing purposes, allows you to quickly create bank
1108 transactions from invoices to have something to test payments against.
1109
1110  my $ap = SL::DB::Manager::Invoice->find_by(id => 41);
1111  $ap->create_bank_transaction(amount => $ap->amount/2, transdate => DateTime->today->add(days => 5));
1112
1113 To create a payment for 3 invoices that were all paid together, all with skonto:
1114  my $ar1 = SL::DB::Manager::Invoice->find_by(invnumber=>'20');
1115  my $ar2 = SL::DB::Manager::Invoice->find_by(invnumber=>'21');
1116  my $ar3 = SL::DB::Manager::Invoice->find_by(invnumber=>'22');
1117  $ar1->create_bank_transaction(amount  => ($ar1->amount_less_skonto + $ar2->amount_less_skonto + $ar2->amount_less_skonto),
1118                                purpose => 'Rechnungen 20, 21, 22',
1119                               );
1120
1121 Amount is always relative to the absolute amount of the invoice, use positive
1122 values for sales and purchases.
1123
1124 The following params can be passed to override the defaults:
1125
1126 =over 2
1127
1128 =item * amount
1129
1130 =item * purpose
1131
1132 =item * chart_id (the chart the amount is to be paid to)
1133
1134 =item * transdate
1135
1136 =back
1137
1138 =item C<exchangerate>
1139
1140 Returns 1 immediately if the record uses the default currency.
1141
1142 Returns the exchangerate in database format for the invoice according to that
1143 invoice's transdate, returning 'buy' for sales, 'sell' for purchases.
1144
1145 If no exchangerate can be found for that day undef is returned.
1146
1147 =item C<forex>
1148
1149 Returns 1 if record uses a different currency, 0 if the default currency is used.
1150
1151 =back
1152
1153 =head1 TODO AND CAVEATS
1154
1155 =over 4
1156
1157 =item *
1158
1159 when looking at open amount, maybe consider that there may already be queued
1160 amounts in SEPA Export
1161
1162 =back
1163
1164 =head1 AUTHOR
1165
1166 G. Richardson E<lt>grichardson@kivitendo-premium.de<gt>
1167
1168 =cut