- # calculate individual sellprice
- # discount was already accounted for in db sellprice
- $ar->{sellprice} = $ar->{sellprice} / $ar->{price_factor};
- $ar->{lastcost} = $ar->{lastcost} / $ar->{price_factor};
- $ar->{sellprice_total} = $ar->{qty} * $ar->{sellprice};
- $ar->{lastcost_total} = $ar->{qty} * $ar->{lastcost};
- # marge_percent wird neu berechnet, da Wert in invoice leer ist (Bug)
- $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total}) : 0;
- # marge_total neu berechnen
+
+ # calculate individual sellprice, discount is already accounted for in column sellprice in db
+
+ # The sellprice total can be calculated from sellprice or fxsellprice (the
+ # value that was actually entered in the sellprice field and is always
+ # stored separately). However, for fxsellprice this method only works when
+ # the tax is not included, because otherwise fxsellprice includes the tax
+ # and there is no simple way to extract the tax rate of the article from
+ # the big query.
+ #
+ # Using fxsellprice is potentially more accurate (certainly for tax
+ # included), because we can use the same method as is used while the
+ # invoice is generated.
+ #
+ # sellprice however has already been converted to the net value (but
+ # rounded in the process, which leads to rounding errors when calculating
+ # the linetotal from the rounded sellprice in the report. These rounding
+ # errors can quickly amount to several cents when qty is large)
+ #
+ # For calculating sellprice_total from fxsellprice, you would use:
+ # sellprice_total_including_tax = qty * fxsellprice * (1-discount) / price_factor * exchangerate
+ # $ar->{sellprice_total_including_tax} = $form->round_amount( $ar->{qty} * ( $ar->{fxsellprice} * ( 1 - $ar->{discount} ) ) / $ar->{price_factor}, $form->{"decimalplaces"});
+
+ my $sellprice_orig = $ar->{sellprice};
+ my $qty_orig = $ar->{qty};
+ # adjust sellprice so it reflects the unit sellprice according to price_factor and basefactor
+ $ar->{sellprice} = $ar->{sellprice} / $ar->{price_factor} / $basefactor;
+ # for sellprice_total use the original amounts
+ $ar->{sellprice_total} = $form->round_amount( $qty_orig * $sellprice_orig / $ar->{price_factor}, $form->{"decimalplaces"});
+
+ my $lastcost_orig = $ar->{lastcost};
+ $ar->{lastcost} = $ar->{lastcost} / $ar->{price_factor} / $basefactor;
+ $ar->{lastcost_total} = $form->round_amount( $qty_orig * $lastcost_orig / $ar->{price_factor}, $form->{"decimalplaces"});
+
+ # marge_percent is recalculated, because the value in invoice used to be empty
+ $ar->{marge_percent} = $ar->{sellprice_total} ? (($ar->{sellprice_total}-$ar->{lastcost_total}) / $ar->{sellprice_total} * 100) : 0;
+ # also recalculate marge_total