I am decorating the "ProductPriceCalculator" as stated in the documentation (https://developer.shopware.com/docs/guides/plugins/plugins/checkout/cart/customize-price-calculation#decorating-the-calculator) and its working fine for the detail productpage. But when I add this product to the cart, the values are multiplied several times. I dont see what I am missing here. This is the code I am using in the decorated calculate method:
public function calculate(iterable $products, SalesChannelContext $context): void
{
/** @var SalesChannelProductEntity $product */
foreach ($products as $product) {
if(array_key_exists('custom_calculation', $product->getCustomFields())
&& $product->getCustomFields()['custom_calculation'] != '') {
$factor = (float)$product->getCustomFields()['custom_calculation'];
$price = $product->getPrice();
$price->first()->setGross($price->first()->getGross() * $factor);
$price->first()->setNet($price->first()->getNet() * $factor);
}
}
$this->getDecorated()->calculate($products, $context);
}
The product gets recalculated several times in the cart process, so you must ensure that your factor gets only multiplied once. You could for example add an extension to your product and skip your factor multiplication when it is present.
public function calculate(iterable $products, SalesChannelContext $context): void
{
/** @var SalesChannelProductEntity $product */
foreach ($products as $product) {
if(array_key_exists('custom_calculation', $product->getCustomFields())
&& $product->getCustomFields()['custom_calculation'] != ''
&& !$product->hasExtension('priceFactorMultiplied')) {
$factor = (float)$product->getCustomFields()['custom_calculation'];
$price = $product->getPrice();
$price->first()->setGross($price->first()->getGross() * $factor);
$price->first()->setNet($price->first()->getNet() * $factor);
$product->addExtension('priceFactorMultiplied', new ArrayStruct([]));
}
}
$this->getDecorated()->calculate($products, $context);
}