Refactoring; kleine Erweiterungen für Rechnungsberechnung
[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);
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 $is_sales            = $self->can('customer') && $self->customer;
18   my $is_invoice          = (ref($self) =~ /Invoice/) || $params{invoice};
19
20   my %units_by_name       = map { ( $_->name => $_ ) } @{ SL::DB::Manager::Unit->get_all        };
21   my %price_factors_by_id = map { ( $_->id   => $_ ) } @{ SL::DB::Manager::PriceFactor->get_all };
22   my %taxes_by_chart_id   = ();
23   my %amounts_by_chart_id = ();
24
25   my %data = ( lastcost_total      => 0,
26                invoicediff         => 0,
27                units_by_name       => \%units_by_name,
28                price_factors_by_id => \%price_factors_by_id,
29                taxes_by_chart_id   => \%taxes_by_chart_id,
30                amounts_by_chart_id => \%amounts_by_chart_id,
31                exchangerate        => undef,
32              );
33
34   if (($self->curr || '') ne SL::DB::Default->get_default_currency) {
35     $data{exchangerate}   = $::form->check_exchangerate(\%::myconfig, $self->curr, $self->transdate, $is_sales ? 'buy' : 'sell');
36     $data{exchangerate} ||= $params{exchangerate};
37   }
38   $data{exchangerate} ||= 1;
39
40   $self->netamount(  0);
41   $self->marge_total(0);
42
43   my $idx = 0;
44   foreach my $item ($self->items) {
45     $idx++;
46     _calculate_item($self, $item, $idx, \%data);
47   }
48
49   my $tax_sum = sum map { _round($_, 2) } values %taxes_by_chart_id;
50
51   $self->amount(       _round($self->netamount + $tax_sum, 2));
52   $self->netamount(    _round($self->netamount,            2));
53   $self->marge_percent($self->netamount ? ($self->netamount - $data{lastcost_total}) * 100 / $self->netamount : 0);
54
55   return $self unless wantarray;
56   return ( self    => $self,
57            taxes   => \%taxes_by_chart_id,
58            amounts => \%amounts_by_chart_id,
59          );
60 }
61
62 sub _calculate_item {
63   my ($self, $item, $idx, $data) = @_;
64
65   my $part_unit  = $data->{units_by_name}->{ $item->part->unit };
66   my $item_unit  = $data->{units_by_name}->{ $item->unit       };
67
68   croak("Undefined unit " . $item->part->unit) if !$part_unit;
69   croak("Undefined unit " . $item->unit)       if !$item_unit;
70
71   $item->base_qty($item_unit->convert_to($item->qty, $part_unit));
72
73   my $num_dec   = _num_decimal_places($item->sellprice);
74   my $discount  = _round($item->sellprice * ($item->discount || 0), $num_dec);
75   my $sellprice = _round($item->sellprice - $discount,              $num_dec);
76
77   $item->price_factor(      ! $item->price_factor_obj   ? 1 : ($item->price_factor_obj->factor   || 1));
78   $item->marge_price_factor(! $item->part->price_factor ? 1 : ($item->part->price_factor->factor || 1));
79   my $linetotal = _round($sellprice * $item->qty / $item->price_factor, 2) * $data->{exchangerate};
80   $linetotal    = _round($linetotal,                                    2);
81
82   $data->{invoicediff} += $sellprice * $item->qty * $data->{exchangerate} / $item->price_factor - $linetotal;
83
84   if (!$linetotal) {
85     $item->marge_total(  0);
86     $item->marge_percent(0);
87
88   } else {
89     my $lastcost = ! ($item->lastcost * 1) ? ($item->part->lastcost || 0) : $item->lastcost;
90
91     $item->marge_total(  $linetotal - $lastcost / $item->marge_price_factor);
92     $item->marge_percent($item->marge_total * 100 / $linetotal);
93
94     $self->marge_total(  $self->marge_total + $item->marge_total);
95     $data->{lastcost_total} += $lastcost;
96   }
97
98   my $taxkey     = $item->part->get_taxkey(date => $self->transdate, is_sales => $data->{is_sales}, taxzone => $self->taxzone_id);
99   my $tax_rate   = $taxkey->tax->rate;
100   my $tax_amount = undef;
101
102   if ($self->taxincluded) {
103     $tax_amount = $linetotal * $tax_rate / ($tax_rate + 1);
104     $sellprice  = $sellprice             / ($tax_rate + 1);
105
106   } else {
107     $tax_amount = $linetotal * $tax_rate;
108   }
109
110   $data->{taxes_by_chart_id}->{ $taxkey->chart_id } ||= 0;
111   $data->{taxes_by_chart_id}->{ $taxkey->chart_id }  += $tax_amount;
112
113   $self->netamount($self->netamount + $sellprice * $item->qty / $item->price_factor);
114
115   my $chart = $item->part->get_chart(type => $data->{is_sales} ? 'income' : 'expense', taxzone => $self->taxzone_id);
116   $data->{amounts_by_chart_id}->{$chart->id} += $linetotal;
117
118   if ($data->{is_invoice}) {
119     if ($item->part->is_assembly) {
120       # process_assembly()...
121     } else {
122       # cogs...
123     }
124   }
125
126   $::lxdebug->message(0, "CALCULATE! ${idx} i.qty " . $item->qty . " i.sellprice " . $item->sellprice . " sellprice $sellprice taxamount $tax_amount " .
127                       "i.linetotal $linetotal netamount " . $self->netamount . " marge_total " . $item->marge_total . " marge_percent " . $item->marge_percent);
128 }
129
130 sub _round {
131   return $::form->round_amount(@_);
132 }
133
134 sub _num_decimal_places {
135   return length( (split(/\./, '' . shift, 2))[1] || '' );
136 }
137
138 1;
139 __END__
140
141 =pod
142
143 =encoding utf8
144
145 =head1 NAME
146
147 SL::DB::Helper::PriceTaxCalculator - Mixin for calculating the prices,
148 amounts and taxes of orders, quotations, invoices
149
150 =head1 FUNCTIONS
151
152 =over 4
153
154 =item C<calculate_prices_and_taxes %params>
155
156 Calculates the prices, amounts and taxes for an order, a quotation or
157 an invoice. The function assumes that the mixing package has a certain
158 layout and provides certain functions:
159
160 =over 2
161
162 =item C<transdate>
163
164 The record's date.
165
166 =item C<customer> or C<vendor>
167
168 Determines if the record is a sales or purchase record.
169
170 =item C<items>
171
172 Accessor returning all line items for this record. The line items
173 themselves must again have a certain layout. Instances of
174 L<SL::DB::OrderItem> and L<SL::DB::InvoiceItem> are supported.
175
176 =back
177
178 The following values are calculated and set for C<$self>: C<amount>,
179 C<netamount>, C<marge_percent>, C<marge_total>.
180
181 The following values are calculated and set for each line item:
182 C<base_qty>, C<price_factor>, C<marge_price_factor>, C<marge_total>,
183 C<marge_percent>.
184
185 The objects are not saved.
186
187 Returns C<$self> in scalar context.
188
189 In array context a hash with the following keys is returned:
190
191 =over 2
192
193 =item C<self>
194
195 The object itself.
196
197 =item C<taxes>
198
199 A hash reference with the calculated taxes. The keys are chart IDs,
200 the values the calculated taxes.
201
202 =item C<amounts>
203
204 A hash reference with the calculated amounts. The keys are chart IDs,
205 the values the calculated amounts.
206
207 =back
208
209 =back
210
211 =head1 BUGS
212
213 Nothing here yet.
214
215 =head1 AUTHOR
216
217 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
218
219 =cut