Weitere Berechnungen für Rechnungen
[kivitendo-erp.git] / SL / DB / Helper / PriceTaxCalculator.pm
1 package SL::DB::Helper::PriceTaxCalculator;
2
3 use strict;
4
5 use parent qw(Exporter);
6 our @EXPORT = qw(calculate_prices_and_taxes);
7
8 use Carp;
9 use List::Util qw(sum min);
10 use SL::DB::Default;
11 use SL::DB::PriceFactor;
12 use SL::DB::Unit;
13
14 sub calculate_prices_and_taxes {
15   my ($self, %params) = @_;
16
17   my %units_by_name       = map { ( $_->name => $_ ) } @{ SL::DB::Manager::Unit->get_all        };
18   my %price_factors_by_id = map { ( $_->id   => $_ ) } @{ SL::DB::Manager::PriceFactor->get_all };
19
20   my %data = ( lastcost_total      => 0,
21                invoicediff         => 0,
22                units_by_name       => \%units_by_name,
23                price_factors_by_id => \%price_factors_by_id,
24                taxes               => { },
25                amounts             => { },
26                amounts_cogs        => { },
27                allocated           => { },
28                assembly_items      => [ ],
29                exchangerate        => undef,
30                is_sales            => $self->can('customer') && $self->customer,
31                is_invoice          => (ref($self) =~ /Invoice/) || $params{invoice},
32              );
33
34   _get_exchangerate($self, \%data, %params);
35
36   $self->netamount(  0);
37   $self->marge_total(0);
38
39   my $idx = 0;
40   foreach my $item ($self->items) {
41     $idx++;
42     _calculate_item($self, $item, $idx, \%data, %params);
43   }
44
45   my $tax_sum = sum map { _round($_, 2) } values %{ $data{taxes} };
46
47   $self->amount(       _round($self->netamount + $tax_sum, 2));
48   $self->netamount(    _round($self->netamount,            2));
49   $self->marge_percent($self->netamount ? ($self->netamount - $data{lastcost_total}) * 100 / $self->netamount : 0);
50
51   _calculate_invoice($self, \%data, %params) if $data{is_invoice};
52
53   return $self unless wantarray;
54
55   return map { ($_ => $data{$_}) } qw(taxes amounts amounts_cogs allocated exchangerate assembly_items);
56 }
57
58 sub _get_exchangerate {
59   my ($self, $data, %params) = @_;
60
61   if (($self->curr || '') ne SL::DB::Default->get_default_currency) {
62     $data->{exchangerate}   = $::form->check_exchangerate(\%::myconfig, $self->curr, $self->transdate, $data->{is_sales} ? 'buy' : 'sell');
63     $data->{exchangerate} ||= $params{exchangerate};
64   }
65   $data->{exchangerate} ||= 1;
66 }
67
68 sub _calculate_item {
69   my ($self, $item, $idx, $data, %params) = @_;
70
71   my $part_unit  = $data->{units_by_name}->{ $item->part->unit };
72   my $item_unit  = $data->{units_by_name}->{ $item->unit       };
73
74   croak("Undefined unit " . $item->part->unit) if !$part_unit;
75   croak("Undefined unit " . $item->unit)       if !$item_unit;
76
77   $item->base_qty($item_unit->convert_to($item->qty, $part_unit));
78
79   my $num_dec   = _num_decimal_places($item->sellprice);
80   my $discount  = _round($item->sellprice * ($item->discount || 0), $num_dec);
81   my $sellprice = _round($item->sellprice - $discount,              $num_dec);
82
83   $item->price_factor(      ! $item->price_factor_obj   ? 1 : ($item->price_factor_obj->factor   || 1));
84   $item->marge_price_factor(! $item->part->price_factor ? 1 : ($item->part->price_factor->factor || 1));
85   my $linetotal = _round($sellprice * $item->qty / $item->price_factor, 2) * $data->{exchangerate};
86   $linetotal    = _round($linetotal,                                    2);
87
88   $data->{invoicediff} += $sellprice * $item->qty * $data->{exchangerate} / $item->price_factor - $linetotal;
89
90   if (!$linetotal) {
91     $item->marge_total(  0);
92     $item->marge_percent(0);
93
94   } else {
95     my $lastcost = ! ($item->lastcost * 1) ? ($item->part->lastcost || 0) : $item->lastcost;
96
97     $item->marge_total(  $linetotal - $lastcost / $item->marge_price_factor);
98     $item->marge_percent($item->marge_total * 100 / $linetotal);
99
100     $self->marge_total(  $self->marge_total + $item->marge_total);
101     $data->{lastcost_total} += $lastcost;
102   }
103
104   my $taxkey     = $item->part->get_taxkey(date => $self->transdate, is_sales => $data->{is_sales}, taxzone => $self->taxzone_id);
105   my $tax_rate   = $taxkey->tax->rate;
106   my $tax_amount = undef;
107
108   if ($self->taxincluded) {
109     $tax_amount = $linetotal * $tax_rate / ($tax_rate + 1);
110     $sellprice  = $sellprice             / ($tax_rate + 1);
111
112   } else {
113     $tax_amount = $linetotal * $tax_rate;
114   }
115
116   $data->{taxes}->{ $taxkey->chart_id } ||= 0;
117   $data->{taxes}->{ $taxkey->chart_id }  += $tax_amount;
118
119   $self->netamount($self->netamount + $sellprice * $item->qty / $item->price_factor);
120
121   my $chart = $item->part->get_chart(type => $data->{is_sales} ? 'income' : 'expense', taxzone => $self->taxzone_id);
122   $data->{amounts}->{$chart->id} += $linetotal;
123
124   push @{ $data->{assembly_items} }, [];
125   $item->allocated(_calculate_assembly_item($self, $data, $item->part, $item->base_qty, $item->unit_obj->convert_to(1, $item->part->unit_obj)));
126
127   $::lxdebug->message(0, "CALCULATE! ${idx} i.qty " . $item->qty . " i.sellprice " . $item->sellprice . " sellprice $sellprice taxamount $tax_amount " .
128                       "i.linetotal $linetotal netamount " . $self->netamount . " marge_total " . $item->marge_total . " marge_percent " . $item->marge_percent);
129 }
130
131 sub _calculate_invoice {
132   my ($self, $data, %params) = @_;
133
134   return unless $data->{invoice};
135 }
136
137 sub _calculate_assembly_item {
138   my ($self, $data, $part, $total_qty, $base_factor) = @_;
139
140   return 0 unless $::eur && $data->{is_invoice};
141   return _calculate_part_service_item($self, $data, $part, $total_qty) unless $part->is_assembly;
142
143   my $allocated = 0;
144   foreach my $assembly_entry (@{ $part->assemblies }) {
145     push @{ $data->{assembly_items}->[-1] }, { part => $assembly_entry->part, qty => $total_qty * $assembly_entry->qty };
146     $allocated += _calculate_assembly_item($self, $data, $assembly_entry->part, $total_qty * $assembly_entry->qty);
147   }
148
149   return $allocated;
150 }
151
152 sub _calculate_part_service_item {
153   my ($self, $data, $part, $total_qty, $base_factor) = @_;
154
155   $::lxdebug->message(0, "cpsi tq " . $total_qty);
156
157   return 0 unless $::eur && $data->{is_invoice} && $total_qty;
158
159   my ($entry);
160   $base_factor           ||= 1;
161   my $remaining_qty        = $total_qty;
162   my $expense_income_chart = $part->get_chart(type => $data->{is_sales} ? 'expense' : 'income', taxzone => $self->taxzone_id);
163   my $inventory_chart      = $part->get_chart(type => 'inventory',                              taxzone => $self->taxzone_id);
164
165   my $iterator             = SL::DB::Manager::InvoiceItem->get_all_iterator(query => [ and => [ parts_id => $part->id,
166                                                                                                 \'(base_qty + allocated) < 0' ] ]);
167
168   while (($remaining_qty > 0) && ($entry = $iterator->next)) {
169     my $qty = min($remaining_qty, $entry->base_qty * -1 - $entry->allocated - $data->{allocated}->{$part->id});
170     $::lxdebug->message(0, "qty $qty");
171
172     next unless $qty;
173
174     my $linetotal = _round(($entry->sellprice * $qty) / $base_factor, 2);
175
176     $data->{amounts_cogs}->{ $expense_income_chart->id } -= $linetotal;
177     $data->{amounts_cogs}->{ $inventory_chart->id      } += $linetotal;
178
179     $data->{allocated}->{ $part->id } ||= 0;
180     $data->{allocated}->{ $part->id }  += $qty;
181     $remaining_qty                     -= $qty;
182   }
183
184   $iterator->finish;
185
186   return $remaining_qty - $total_qty;
187 }
188
189 sub _round {
190   return $::form->round_amount(@_);
191 }
192
193 sub _num_decimal_places {
194   return length( (split(/\./, '' . shift, 2))[1] || '' );
195 }
196
197 1;
198 __END__
199
200 =pod
201
202 =encoding utf8
203
204 =head1 NAME
205
206 SL::DB::Helper::PriceTaxCalculator - Mixin for calculating the prices,
207 amounts and taxes of orders, quotations, invoices
208
209 =head1 FUNCTIONS
210
211 =over 4
212
213 =item C<calculate_prices_and_taxes %params>
214
215 Calculates the prices, amounts and taxes for an order, a quotation or
216 an invoice. The function assumes that the mixing package has a certain
217 layout and provides certain functions:
218
219 =over 2
220
221 =item C<transdate>
222
223 The record's date.
224
225 =item C<customer> or C<vendor>
226
227 Determines if the record is a sales or purchase record.
228
229 =item C<items>
230
231 Accessor returning all line items for this record. The line items
232 themselves must again have a certain layout. Instances of
233 L<SL::DB::OrderItem> and L<SL::DB::InvoiceItem> are supported.
234
235 =back
236
237 The following values are calculated and set for C<$self>: C<amount>,
238 C<netamount>, C<marge_percent>, C<marge_total>.
239
240 The following values are calculated and set for each line item:
241 C<base_qty>, C<price_factor>, C<marge_price_factor>, C<marge_total>,
242 C<marge_percent>.
243
244 The objects are not saved.
245
246 Returns C<$self> in scalar context.
247
248 In array context a hash with the following keys is returned:
249
250 =over 2
251
252 =item C<self>
253
254 The object itself.
255
256 =item C<taxes>
257
258 A hash reference with the calculated taxes. The keys are chart IDs,
259 the values the calculated taxes.
260
261 =item C<amounts>
262
263 A hash reference with the calculated amounts. The keys are chart IDs,
264 the values the calculated amounts.
265
266 =back
267
268 =back
269
270 =head1 BUGS
271
272 Nothing here yet.
273
274 =head1 AUTHOR
275
276 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
277
278 =cut