1 package SL::DB::Helper::PriceTaxCalculator;
5 use parent qw(Exporter);
6 our @EXPORT = qw(calculate_prices_and_taxes);
9 use List::Util qw(sum min);
11 use SL::DB::PriceFactor;
14 sub calculate_prices_and_taxes {
15 my ($self, %params) = @_;
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 };
20 my %data = ( lastcost_total => 0,
22 units_by_name => \%units_by_name,
23 price_factors_by_id => \%price_factors_by_id,
28 assembly_items => [ ],
29 exchangerate => undef,
30 is_sales => $self->can('customer') && $self->customer,
31 is_invoice => (ref($self) =~ /Invoice/) || $params{invoice},
34 _get_exchangerate($self, \%data, %params);
37 $self->marge_total(0);
40 foreach my $item ($self->items) {
42 _calculate_item($self, $item, $idx, \%data, %params);
45 my $tax_sum = sum map { _round($_, 2) } values %{ $data{taxes} };
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);
51 _calculate_invoice($self, \%data, %params) if $data{is_invoice};
53 return $self unless wantarray;
55 return map { ($_ => $data{$_}) } qw(taxes amounts amounts_cogs allocated exchangerate assembly_items);
58 sub _get_exchangerate {
59 my ($self, $data, %params) = @_;
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};
65 $data->{exchangerate} ||= 1;
69 my ($self, $item, $idx, $data, %params) = @_;
71 my $part_unit = $data->{units_by_name}->{ $item->part->unit };
72 my $item_unit = $data->{units_by_name}->{ $item->unit };
74 croak("Undefined unit " . $item->part->unit) if !$part_unit;
75 croak("Undefined unit " . $item->unit) if !$item_unit;
77 $item->base_qty($item_unit->convert_to($item->qty, $part_unit));
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);
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);
88 $data->{invoicediff} += $sellprice * $item->qty * $data->{exchangerate} / $item->price_factor - $linetotal;
91 $item->marge_total( 0);
92 $item->marge_percent(0);
95 my $lastcost = ! ($item->lastcost * 1) ? ($item->part->lastcost || 0) : $item->lastcost;
97 $item->marge_total( $linetotal - $lastcost / $item->marge_price_factor);
98 $item->marge_percent($item->marge_total * 100 / $linetotal);
100 $self->marge_total( $self->marge_total + $item->marge_total);
101 $data->{lastcost_total} += $lastcost;
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;
108 if ($self->taxincluded) {
109 $tax_amount = $linetotal * $tax_rate / ($tax_rate + 1);
110 $sellprice = $sellprice / ($tax_rate + 1);
113 $tax_amount = $linetotal * $tax_rate;
116 $data->{taxes}->{ $taxkey->chart_id } ||= 0;
117 $data->{taxes}->{ $taxkey->chart_id } += $tax_amount;
119 $self->netamount($self->netamount + $sellprice * $item->qty / $item->price_factor);
121 my $chart = $item->part->get_chart(type => $data->{is_sales} ? 'income' : 'expense', taxzone => $self->taxzone_id);
122 $data->{amounts}->{$chart->id} += $linetotal;
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)));
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);
131 sub _calculate_invoice {
132 my ($self, $data, %params) = @_;
134 return unless $data->{invoice};
137 sub _calculate_assembly_item {
138 my ($self, $data, $part, $total_qty, $base_factor) = @_;
140 return 0 unless $::eur && $data->{is_invoice};
141 return _calculate_part_service_item($self, $data, $part, $total_qty) unless $part->is_assembly;
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);
152 sub _calculate_part_service_item {
153 my ($self, $data, $part, $total_qty, $base_factor) = @_;
155 $::lxdebug->message(0, "cpsi tq " . $total_qty);
157 return 0 unless $::eur && $data->{is_invoice} && $total_qty;
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);
165 my $iterator = SL::DB::Manager::InvoiceItem->get_all_iterator(query => [ and => [ parts_id => $part->id,
166 \'(base_qty + allocated) < 0' ] ]);
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");
174 my $linetotal = _round(($entry->sellprice * $qty) / $base_factor, 2);
176 $data->{amounts_cogs}->{ $expense_income_chart->id } -= $linetotal;
177 $data->{amounts_cogs}->{ $inventory_chart->id } += $linetotal;
179 $data->{allocated}->{ $part->id } ||= 0;
180 $data->{allocated}->{ $part->id } += $qty;
181 $remaining_qty -= $qty;
186 return $remaining_qty - $total_qty;
190 return $::form->round_amount(@_);
193 sub _num_decimal_places {
194 return length( (split(/\./, '' . shift, 2))[1] || '' );
206 SL::DB::Helper::PriceTaxCalculator - Mixin for calculating the prices,
207 amounts and taxes of orders, quotations, invoices
213 =item C<calculate_prices_and_taxes %params>
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:
225 =item C<customer> or C<vendor>
227 Determines if the record is a sales or purchase record.
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.
237 The following values are calculated and set for C<$self>: C<amount>,
238 C<netamount>, C<marge_percent>, C<marge_total>.
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>,
244 The objects are not saved.
246 Returns C<$self> in scalar context.
248 In array context a hash with the following keys is returned:
258 A hash reference with the calculated taxes. The keys are chart IDs,
259 the values the calculated taxes.
263 A hash reference with the calculated amounts. The keys are chart IDs,
264 the values the calculated amounts.
276 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>