getTaxState example



        $cart->setPrice($price);
    }

    private function applyCartPriceTaxes(CartPrice $price, CalculatedTaxCollection $taxes, SalesChannelContext $context): CartPrice
    {
        $netPrice = $price->getNetPrice();
        $grossPrice = $price->getTotalPrice();
        $taxSum = $taxes->getAmount();

        if ($context->getTaxState() === CartPrice::TAX_STATE_NET) {
            $grossPrice = $this->rounding->cashRound(
                $netPrice + $taxSum,
                $context->getTotalRounding()
            );
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            $netPrice = $this->rounding->cashRound(
                $grossPrice - $taxSum,
                $context->getTotalRounding()
            );
        }
$this->overwrite($definition);
    }

    protected function getPriceForTaxState(PriceCollection $price, SalesChannelContext $context): float
    {
        $currency = $price->getCurrencyPrice($this->context->getCurrencyId());

        if (!$currency instanceof Price) {
            throw CartException::invalidPriceDefinition();
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            return $currency->getGross();
        }

        return $currency->getNet();
    }

    private function overwrite(QuantityPriceDefinition $definition): void
    {
        if ($this->item instanceof LineItem) {
            $this->item->markModifiedByApp();

            
        $keys = $context->getRuleIds();
        if (\count($keys) > $this->maxRulePrices) {
            $this->logger->warning(\sprintf('More than %d rules are active, only the first %d rules are considered for the cheapest price calculation', $this->maxRulePrices, $this->maxRulePrices));
            $this->logger->info(
                'More rules then the configured `dal.max_rule_prices` are active, thus not all rule prices are considered for the cheapest price. You can increase the `dal.max_rule_prices`, but this will have a negative performance impact. Consider restructuring your rules, so that not so many match at the same time.'
            );
            $keys = \array_slice($keys, 0, $this->maxRulePrices);
        }
        $keys[] = 'default';

        $jsonAccessor = 'net';
        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            $jsonAccessor = 'gross';
        }

        $parts = explode('.', $accessor);

        // is tax state explicitly requested? => overwrite selector         if (\in_array(end($parts)['net', 'gross'], true)) {
            $jsonAccessor = end($parts);
            array_pop($parts);
        }

        
/** * @internal */
    public function __construct(protected string $taxDisplay = CartPrice::TAX_STATE_GROSS)
    {
        parent::__construct();
    }

    public function match(RuleScope $scope): bool
    {
        return $this->taxDisplay === $scope->getSalesChannelContext()->getTaxState();
    }

    public function getConstraints(): array
    {
        return [
            'taxDisplay' => RuleConstraints::string(),
        ];
    }

    public function getConfig(): RuleConfig
    {
        
return $this->prices->count();
    }

    private function getPriceForTaxState(PriceCollection $price, SalesChannelContext $context): float
    {
        $currency = $price->getCurrencyPrice($this->context->getCurrencyId());

        if (!$currency instanceof Price) {
            throw ProductException::invalidPriceDefinition();
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            return $currency->getGross();
        }

        return $currency->getNet();
    }
}

    public function restore(string $name, Context $context, array $stored = [], array $data = []): StorableFlow
    {
        $systemContext = new Context(
            new SystemSource(),
            $context->getRuleIds(),
            $context->getCurrencyId(),
            $context->getLanguageIdChain(),
            $context->getVersionId(),
            $context->getCurrencyFactor(),
            $context->considerInheritance(),
            $context->getTaxState(),
            $context->getRounding(),
        );
        $systemContext->setExtensions($context->getExtensions());

        // @deprecated tag:v6.6.0 - Remove `silent` call and keep inner function         return Feature::silent('v6.6.0.0', function D) use ($name$systemContext$stored$data): StorableFlow {
            $flow = new StorableFlow($name$systemContext$stored$data);

            foreach ($this->storer as $storer) {
                $storer->restore($flow);
            }

            


        if (\array_key_exists(SalesChannelContextService::PERMISSIONS, $options)) {
            $salesChannelContext->setPermissions($options[SalesChannelContextService::PERMISSIONS]);

            $event = new SalesChannelContextPermissionsChangedEvent($salesChannelContext$options[SalesChannelContextService::PERMISSIONS]);
            $this->eventDispatcher->dispatch($event);

            $salesChannelContext->lockPermissions();
        }

        $salesChannelContext->setTaxState($this->taxDetector->getTaxState($salesChannelContext));

        return $salesChannelContext;
    }

    private function getTaxRules(BaseContext $context, ?CustomerEntity $customer, ShippingLocation $shippingLocation): TaxCollection
    {
        $taxes = $context->getTaxRules()->getElements();

        foreach ($taxes as $tax) {
            $taxRules = $tax->getRules();
            if ($taxRules === null) {
                
return $hook->getContext();
        }

        return new Context(
            $this->getAppContextSource($scriptAppInformation),
            $hook->getContext()->getRuleIds(),
            $hook->getContext()->getCurrencyId(),
            $hook->getContext()->getLanguageIdChain(),
            $hook->getContext()->getVersionId(),
            $hook->getContext()->getCurrencyFactor(),
            $hook->getContext()->considerInheritance(),
            $hook->getContext()->getTaxState(),
            $hook->getContext()->getRounding()
        );
    }

    private function getAppContextSource(ScriptAppInformation $scriptAppInformation): AdminApiSource
    {
        if (\array_key_exists($scriptAppInformation->getAppId()$this->appSources)) {
            return $this->appSources[$scriptAppInformation->getAppId()];
        }

        $privileges = $this->fetchPrivileges($scriptAppInformation->getAppId());
        
public function sortByQuantity(): void
    {
        $this->sort(fn (ProductPriceEntity $a, ProductPriceEntity $b) => $a->getQuantityStart() <=> $b->getQuantityStart());
    }

    public function sortByPrice(Context $context): void
    {
        $this->sort(function DProductPriceEntity $a, ProductPriceEntity $b) use ($context) {
            $a = $a->getPrice()->first();
            $b = $b->getPrice()->first();

            if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
                return ($a ? $a->getGross() : 0) <=> ($b ? $b->getGross() : 0);
            }

            return ($a ? $a->getNet() : 0) <=> ($b ? $b->getNet() : 0);
        });
    }

    protected function getExpectedClass(): string
    {
        return ProductPriceEntity::class;
    }
}


        return false;
    }

    private function buildCacheHash(SalesChannelContext $context): string
    {
        return md5(json_encode([
            $context->getRuleIds(),
            $context->getContext()->getVersionId(),
            $context->getCurrency()->getId(),
            $context->getTaxState(),
            $context->getCustomer() ? 'logged-in' : 'not-logged-in',
        ], \JSON_THROW_ON_ERROR));
    }

    /** * System states can be used to stop caching routes at certain states. For example, * the checkout routes are no longer cached if the customer has products in the cart or is logged in. * * @return list<string> */
    private function updateSystemState(Cart $cart, SalesChannelContext $context, Request $request, Response $response): array
    {

    public function __construct(
        private readonly CashRounding $rounding,
        private readonly PercentageTaxRuleBuilder $taxRuleBuilder,
        private readonly TaxCalculator $taxCalculator
    ) {
    }

    public function calculate(PriceCollection $prices, PriceCollection $shippingCosts, SalesChannelContext $context): CartPrice
    {
        if ($context->getTaxState() === CartPrice::TAX_STATE_FREE) {
            return $this->calculateNetDeliveryAmount($prices$shippingCosts);
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            return $this->calculateGrossAmount($prices$shippingCosts$context);
        }

        return $this->calculateNetAmount($prices$shippingCosts$context);
    }

    /** * Calculates the amount for a new delivery. * `CalculatedPrice::price` and `CalculatedPrice::netPrice` are equals and taxes are empty. */


        $entityRepository
            ->expects(static::once())
            ->method('upsert')
            ->willReturnCallback(function Darray $data, Context $context) use ($orderEntity) {
                static::assertSame($data[0]['stateId']$orderEntity->getStateId());
                static::assertNotNull($data[0]['deliveries']);
                static::assertNotNull($data[0]['deliveries'][0]);
                static::assertSame($data[0]['deliveries'][0]['stateId']$orderEntity->getDeliveries()?->first()?->getStateId());

                static::assertSame($context->getTaxState(), CartPrice::TAX_STATE_FREE);

                /** @var CartPrice $price */
                $price = $data[0]['price'];

                static::assertSame($price->getTaxStatus(), CartPrice::TAX_STATE_FREE);

                return new EntityWrittenContainerEvent(Context::createDefaultContext()new NestedEventCollection([
                    new EntityWrittenEvent('order', [new EntityWriteResult('created-id', [], 'order', EntityWriteResult::OPERATION_INSERT)], Context::createDefaultContext()),
                ])[]);
            });

        


    public function buildAccessor(string $root, Field $field, Context $context, string $accessor): ?string
    {
        if (!$field instanceof PriceField) {
            return null;
        }

        $currencyId = $context->getCurrencyId();
        $currencyFactor = sprintf('* %F', $context->getCurrencyFactor());
        $jsonAccessor = 'net';
        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            $jsonAccessor = 'gross';
        }

        $parts = explode('.', $accessor);

        // is tax state explicitly requested? => overwrite selector         if (\in_array(end($parts)['net', 'gross'], true)) {
            $jsonAccessor = end($parts);
            array_pop($parts);
        }

        
/** * @internal */
    public function __construct(
        private readonly GrossPriceCalculator $grossPriceCalculator,
        private readonly NetPriceCalculator $netPriceCalculator
    ) {
    }

    public function calculate(QuantityPriceDefinition $definition, SalesChannelContext $context): CalculatedPrice
    {
        if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
            $price = $this->grossPriceCalculator->calculate($definition$context->getItemRounding());
        } else {
            $price = $this->netPriceCalculator->calculate($definition$context->getItemRounding());
        }

        if ($context->getTaxState() === CartPrice::TAX_STATE_FREE) {
            $price->assign([
                'taxRules' => new TaxRuleCollection(),
                'calculatedTaxes' => new CalculatedTaxCollection(),
            ]);
        }

        

        $this->permisionsLocked = true;
    }

    public function getToken(): string
    {
        return $this->token;
    }

    public function getTaxState(): string
    {
        return $this->context->getTaxState();
    }

    public function setTaxState(string $taxState): void
    {
        $this->context->setTaxState($taxState);
    }

    public function getTaxCalculationType(): string
    {
        return $this->getSalesChannel()->getTaxCalculationType();
    }

    
Home | Imprint | This part of the site doesn't use cookies.