calculate example

'min' => 1,
            'max' => 3,
            'unit' => 'day',
            'name' => '1-3 days',
        ]);
    }

    public function testCalculateWithEmptyDelivery(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->expects(static::never())->method(static::anything());
        $this->deliveryCalculator->calculate(new CartDataCollection()new Cart('test')new DeliveryCollection()$context);
    }

    public function testCalculateWithAlreadyCalculatedCosts(): void
    {
        $context = $this->createMock(SalesChannelContext::class);
        $context->method('getContext')->willReturn(Context::createDefaultContext());
        $context->method('getItemRounding')->willReturn(new CashRoundingConfig(2, 0.01, true));

        $positions = new DeliveryPositionCollection();
        $positions->add(
            new DeliveryPosition(
                
$salesChannelContext->method('getTaxCalculationType')->willReturn(SalesChannelDefinition::CALCULATION_TYPE_HORIZONTAL);
        $salesChannelContext->method('getItemRounding')->willReturn(new CashRoundingConfig(2, 0.01, true));
        $salesChannelContext->method('getTotalRounding')->willReturn(new CashRoundingConfig(2, 0.01, true));
        $salesChannelContext->method('getTaxState')->willReturn(CartPrice::TAX_STATE_GROSS);

        $calculator = new AmountCalculator(
            new CashRounding(),
            new PercentageTaxRuleBuilder(),
            new TaxCalculator()
        );

        $cartPrice = $calculator->calculate($pricesnew PriceCollection()$salesChannelContext);
        static::assertEquals($expected$cartPrice);
    }

    /** * @dataProvider calculateAmountWithNetPricesProvider */
    public function testCalculateAmountWithNetPrices(CartPrice $expected, PriceCollection $prices): void
    {
        $salesChannelContext = $this->createMock(SalesChannelContext::class);
        $salesChannelContext->method('getSalesChannel')->willReturn(new SalesChannelEntity());

        
$to = $this->splitStringByLines($to);
        } elseif (!is_array($to)) {
            throw new InvalidArgumentException('"to" must be an array or string.');
        }

        [$from$to$start$end] = self::getArrayDiffParted($from$to);

        if ($lcs === null) {
            $lcs = $this->selectLcsImplementation($from$to);
        }

        $common = $lcs->calculate(array_values($from)array_values($to));
        $diff   = [];

        foreach ($start as $token) {
            $diff[] = [$token, self::OLD];
        }

        reset($from);
        reset($to);

        foreach ($common as $token) {
            while (($fromToken = reset($from)) !== $token) {
                
return $children->getPrices()->sum();
        }

        $definition = $lineItem->getPriceDefinition();

        if ($definition instanceof AbsolutePriceDefinition) {
            // reduce line items for provided filter             $prices = $this->filterLineItems($calculated$definition->getFilter()$context)
                ->getPrices();

            return $this->absolutePriceCalculator->calculate($definition->getPrice()$prices$context);
        }

        if ($definition instanceof PercentagePriceDefinition) {
            // reduce line items for provided filter             $prices = $this->filterLineItems($calculated$definition->getFilter()$context)
                ->getPrices();

            return $this->percentagePriceCalculator->calculate($definition->getPercentage()$prices$context);
        }

        if ($definition instanceof QuantityPriceDefinition) {
            
private readonly QuantityPriceCalculator $priceCalculator,
        private readonly PercentageTaxRuleBuilder $percentageTaxRuleBuilder
    ) {
    }

    public function calculate(float $price, PriceCollection $prices, SalesChannelContext $context, int $quantity = 1): CalculatedPrice
    {
        $taxRules = $this->percentageTaxRuleBuilder->buildRules($prices->sum());

        $definition = new QuantityPriceDefinition($price$taxRules$quantity);

        return $this->priceCalculator->calculate($definition$context);
    }
}
public function getDecorated(): AbstractCartOrderRoute
    {
        throw new DecorationPatternException(self::class);
    }

    #[Route(path: '/store-api/checkout/order', name: 'store-api.checkout.cart.order', methods: ['POST'], defaults: ['_loginRequired' => true, '_loginRequiredAllowGuest' => true])]     public function order(Cart $cart, SalesChannelContext $context, RequestDataBag $data): CartOrderRouteResponse
    {
        // we use this state in stock updater class, to prevent duplicate available stock updates         $context->addState('checkout-order-route');

        $calculatedCart = $this->cartCalculator->calculate($cart$context);
        $this->taxProviderProcessor->process($calculatedCart$context);

        $this->addCustomerComment($calculatedCart$data);
        $this->addAffiliateTracking($calculatedCart$data);

        $preOrderPayment = Profiler::trace('checkout-order::pre-payment', fn () => $this->preparedPaymentService->handlePreOrderPayment($calculatedCart$data$context));

        $orderId = Profiler::trace('checkout-order::order-persist', fn () => $this->orderPersister->persist($calculatedCart$context));

        $criteria = new Criteria([$orderId]);
        $criteria->setTitle('order-route::order-loading');
        
 {
    }

    public function adjust(Cart $cart, TaxProviderResult $result, SalesChannelContext $context): void
    {
        $lineItems = $cart->getLineItems();
        $deliveries = $cart->getDeliveries();

        $this->applyLineItemTaxes($lineItems$result->getLineItemTaxes());
        $this->applyDeliveryTaxes($deliveries$result->getDeliveryTaxes());

        $price = $this->amountCalculator->calculate(
            $cart->getLineItems()->getPrices(),
            $cart->getDeliveries()->getShippingCosts(),
            $context
        );

        // either take the price from the tax provider result or take the calculated taxes         $taxes = $price->getCalculatedTaxes()->filter(fn (CalculatedTax $tax) => $tax->getTax() > 0.0);
        $price->setCalculatedTaxes($taxes);

        if ($result->getCartPriceTaxes()) {
            $price = $this->applyCartPriceTaxes($price$result->getCartPriceTaxes()$context);
        }
'cheapestPrice' => $price->resolve($event->getContext()),
                    'cheapestPriceContainer' => $price,
                ]);
            }

            $assigns = [];

            if (($properties = $product->get('properties')) !== null) {
                $assigns['sortedProperties'] = $this->propertyGroupSorter->sort($properties);
            }

            $assigns['calculatedMaxPurchase'] = $this->maxPurchaseCalculator->calculate($product$event->getSalesChannelContext());

            $assigns['isNew'] = $this->isNewDetector->isNew($product$event->getSalesChannelContext());

            $product->assign($assigns);

            $this->setDefaultLayout($product$event->getSalesChannelContext()->getSalesChannelId());

            $this->productVariationBuilder->build($product);
        }

        $this->calculator->calculate($event->getEntities()$event->getSalesChannelContext());
    }
$this->rateLimiter->ensureAccepted(RateLimiter::CART_ADD_LINE_ITEM, $cacheKey);
            }

            $alreadyExists = $cart->has($item->getId());
            $cart->add($item);

            $this->eventDispatcher->dispatch(new BeforeLineItemAddedEvent($item$cart$context$alreadyExists));
        }

        $cart->markModified();

        $cart = $this->cartCalculator->calculate($cart$context);
        $this->cartPersister->save($cart$context);

        $this->eventDispatcher->dispatch(new AfterLineItemAddedEvent($items$cart$context));
        $this->eventDispatcher->dispatch(new CartChangedEvent($cart$context));

        return new CartResponse($cart);
    }
}
public function process(CartDataCollection $data, Cart $original, Cart $toCalculate, SalesChannelContext $context, CartBehavior $behavior): void
    {
        $items = $original->getLineItems()->filterFlatByType(LineItem::CONTAINER_LINE_ITEM);
        foreach ($items as $item) {
            if ($item->getChildren()->count() <= 0) {
                $original->remove($item->getId());
            }
        }

        $items = $original->getLineItems()->filterType(LineItem::CONTAINER_LINE_ITEM);
        foreach ($items as $item) {
            $this->calculate($item$context$toCalculate->getLineItems());
            $toCalculate->add($item);
        }
    }

    private function calculateCollection(LineItemCollection $items, SalesChannelContext $context, \Closure $condition): void
    {
        foreach ($items as $item) {
            $match = $condition($item);

            if (!$match) {
                continue;
            }
$definition = $discount->getPriceDefinition();

        if (!$definition instanceof AbsolutePriceDefinition) {
            throw new InvalidPriceDefinitionException($discount->getLabel()$discount->getCode());
        }

        $affectedPrices = $packages->getAffectedPrices();

        $totalOriginalSum = $affectedPrices->sum()->getTotalPrice();
        $discountValue = -min(abs($definition->getPrice())$totalOriginalSum);

        $price = $this->priceCalculator->calculate(
            $discountValue,
            $affectedPrices,
            $context
        );

        $composition = $this->getCompositionItems(
            $discountValue,
            $packages,
            $totalOriginalSum
        );

        
class GrossPriceCalculatorTest extends TestCase
{
    /** * @dataProvider referencePriceCalculationProvider */
    public function testReferencePriceCalculation(?ReferencePriceDefinition $reference, float $price, ?ReferencePrice $expected): void
    {
        $definition = new QuantityPriceDefinition($pricenew TaxRuleCollection(), 1);
        $definition->setReferencePriceDefinition($reference);

        $calculator = new GrossPriceCalculator(new TaxCalculator()new CashRounding());
        $result = $calculator->calculate($definitionnew CashRoundingConfig(2, 0.01, true));

        static::assertEquals($expected$result->getReferencePrice());
    }

    public static function referencePriceCalculationProvider(): \Generator
    {
        yield 'test calculation without reference price' => [
            null,
            100,
            null,
        ];

        

        );

        $taxCalculator = $this->container->get('shopware.cart.proportional_tax_calculator');
        $hasDifferentTaxes = $taxCalculator->hasDifferentTaxes($positions);

        $basket[CheckoutKey::CURRENCY_ID] = $currency->getId();
        $basket[CheckoutKey::CURRENCY_NAME] = $currency->getCurrency();
        $basket[CheckoutKey::CURRENCY_FACTOR] = $currency->getFactor();

        if ($hasDifferentTaxes && empty($shippingCosts['taxMode']) && $this->get(Shopware_Components_Config::class)->get('proportionalTaxCalculation') && !$this->session->get('taxFree')) {
            $taxProportional = $taxCalculator->calculate($shippingCosts['brutto']$positions, false);

            $basket[CheckoutKey::SHIPPING_COSTS_TAX_PROPORTIONAL] = $taxProportional;

            $shippingNet = 0;

            foreach ($taxProportional as $shippingProportional) {
                $shippingNet += $shippingProportional->getNetPrice();
            }

            $basket[CheckoutKey::SHIPPING_COSTS_WITH_TAX] = $shippingCosts['brutto'];
            $basket[CheckoutKey::SHIPPING_COSTS_NET] = $shippingNet;
            
class NetPriceCalculatorTest extends TestCase
{
    /** * @dataProvider referencePriceCalculationProvider */
    public function testReferencePriceCalculation(?ReferencePriceDefinition $reference, ?ReferencePrice $expected): void
    {
        $definition = new QuantityPriceDefinition(100, new TaxRuleCollection(), 1);
        $definition->setReferencePriceDefinition($reference);

        $calculator = new NetPriceCalculator(new TaxCalculator()new CashRounding());
        $price = $calculator->calculate($definitionnew CashRoundingConfig(2, 0.01, true));

        static::assertEquals($expected$price->getReferencePrice());
    }

    public static function referencePriceCalculationProvider(): \Generator
    {
        yield 'test calculation without reference price' => [
            null,
            null,
        ];

        


                // Stored original edit shipping cost                 $manualShippingCosts = $toCalculate->getExtension(self::MANUAL_SHIPPING_COSTS) ?? $firstDelivery->getShippingCosts();

                $toCalculate->addExtension(self::MANUAL_SHIPPING_COSTS, $manualShippingCosts);

                if ($manualShippingCosts instanceof CalculatedPrice) {
                    $firstDelivery->setShippingCosts($manualShippingCosts);
                }

                $this->deliveryCalculator->calculate($data$toCalculate$deliveries$context);

                $toCalculate->setDeliveries($deliveries);

                return;
            }

            $deliveries = $this->builder->build($toCalculate$data$context$behavior);
            $manualShippingCosts = $original->getExtension(self::MANUAL_SHIPPING_COSTS);

            if ($manualShippingCosts instanceof CalculatedPrice) {
                $deliveries->first()?->setShippingCosts($manualShippingCosts);
            }
Home | Imprint | This part of the site doesn't use cookies.