src/Core/Checkout/Cart/CartRuleLoader.php line 78

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Checkout\Cart;
  3. use Doctrine\DBAL\Connection;
  4. use Psr\Log\LoggerInterface;
  5. use Shopware\Core\Checkout\Cart\Event\CartCreatedEvent;
  6. use Shopware\Core\Checkout\Cart\Exception\CartTokenNotFoundException;
  7. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  8. use Shopware\Core\Checkout\Cart\Price\Struct\CartPrice;
  9. use Shopware\Core\Checkout\Cart\Tax\TaxDetector;
  10. use Shopware\Core\Content\Rule\RuleCollection;
  11. use Shopware\Core\Defaults;
  12. use Shopware\Core\Framework\Context;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Exception\EntityNotFoundException;
  14. use Shopware\Core\Framework\Log\Package;
  15. use Shopware\Core\Framework\Util\FloatComparator;
  16. use Shopware\Core\Framework\Uuid\Uuid;
  17. use Shopware\Core\Profiling\Profiler;
  18. use Shopware\Core\System\Country\CountryDefinition;
  19. use Shopware\Core\System\Country\CountryEntity;
  20. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  21. use Symfony\Contracts\Cache\CacheInterface;
  22. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  23. use Symfony\Contracts\Service\ResetInterface;
  24. #[Package('checkout')]
  25. class CartRuleLoader implements ResetInterface
  26. {
  27.     private const MAX_ITERATION 7;
  28.     private ?RuleCollection $rules null;
  29.     /**
  30.      * @var array<string, float>
  31.      */
  32.     private array $currencyFactor = [];
  33.     /**
  34.      * @internal
  35.      */
  36.     public function __construct(private readonly AbstractCartPersister $cartPersister, private readonly Processor $processor, private readonly LoggerInterface $logger, private readonly CacheInterface $cache, private readonly AbstractRuleLoader $ruleLoader, private readonly TaxDetector $taxDetector, private readonly Connection $connection, private readonly EventDispatcherInterface $dispatcher)
  37.     {
  38.     }
  39.     public function loadByToken(SalesChannelContext $contextstring $cartToken): RuleLoaderResult
  40.     {
  41.         try {
  42.             $cart $this->cartPersister->load($cartToken$context);
  43.             return $this->load($context$cart, new CartBehavior($context->getPermissions()), false);
  44.         } catch (CartTokenNotFoundException) {
  45.             $cart = new Cart($cartToken);
  46.             $this->dispatcher->dispatch(new CartCreatedEvent($cart));
  47.             return $this->load($context$cart, new CartBehavior($context->getPermissions()), true);
  48.         }
  49.     }
  50.     public function loadByCart(SalesChannelContext $contextCart $cartCartBehavior $behaviorContextbool $isNew false): RuleLoaderResult
  51.     {
  52.         return $this->load($context$cart$behaviorContext$isNew);
  53.     }
  54.     public function reset(): void
  55.     {
  56.         $this->rules null;
  57.     }
  58.     public function invalidate(): void
  59.     {
  60.         $this->reset();
  61.         $this->cache->delete(CachedRuleLoader::CACHE_KEY);
  62.     }
  63.     private function load(SalesChannelContext $contextCart $cartCartBehavior $behaviorContextbool $new): RuleLoaderResult
  64.     {
  65.         return Profiler::trace('cart-rule-loader', function () use ($context$cart$behaviorContext$new) {
  66.             $rules $this->loadRules($context->getContext());
  67.             // save all rules for later usage
  68.             $all $rules;
  69.             $ids $new $rules->getIds() : $cart->getRuleIds();
  70.             // update rules in current context
  71.             $context->setRuleIds($ids);
  72.             $iteration 1;
  73.             $timestamps $cart->getLineItems()->fmap(function (LineItem $lineItem) {
  74.                 if ($lineItem->getDataTimestamp() === null) {
  75.                     return null;
  76.                 }
  77.                 return $lineItem->getDataTimestamp()->format(Defaults::STORAGE_DATE_TIME_FORMAT);
  78.             });
  79.             // start first cart calculation to have all objects enriched
  80.             $cart $this->processor->process($cart$context$behaviorContext);
  81.             do {
  82.                 $compare $cart;
  83.                 if ($iteration self::MAX_ITERATION) {
  84.                     break;
  85.                 }
  86.                 // filter rules which matches to current scope
  87.                 $rules $rules->filterMatchingRules($cart$context);
  88.                 // update matching rules in context
  89.                 $context->setRuleIds($rules->getIds());
  90.                 // calculate cart again
  91.                 $cart $this->processor->process($cart$context$behaviorContext);
  92.                 // check if the cart changed, in this case we have to recalculate the cart again
  93.                 $recalculate $this->cartChanged($cart$compare);
  94.                 // check if rules changed for the last calculated cart, in this case we have to recalculate
  95.                 $ruleCompare $all->filterMatchingRules($cart$context);
  96.                 if (!$rules->equals($ruleCompare)) {
  97.                     $recalculate true;
  98.                     $rules $ruleCompare;
  99.                 }
  100.                 ++$iteration;
  101.             } while ($recalculate);
  102.             $cart $this->validateTaxFree($context$cart$behaviorContext);
  103.             $index 0;
  104.             foreach ($rules as $rule) {
  105.                 ++$index;
  106.                 $this->logger->info(
  107.                     sprintf('#%s Rule detection: %s with priority %s (id: %s)'$index$rule->getName(), $rule->getPriority(), $rule->getId())
  108.                 );
  109.             }
  110.             $context->setRuleIds($rules->getIds());
  111.             $context->setAreaRuleIds($rules->getIdsByArea());
  112.             // save the cart if errors exist, so the errors get persisted
  113.             if ($cart->getErrors()->count() > || $this->updated($cart$timestamps)) {
  114.                 $this->cartPersister->save($cart$context);
  115.             }
  116.             return new RuleLoaderResult($cart$rules);
  117.         });
  118.     }
  119.     private function loadRules(Context $context): RuleCollection
  120.     {
  121.         if ($this->rules !== null) {
  122.             return $this->rules;
  123.         }
  124.         return $this->rules $this->ruleLoader->load($context)->filterForContext();
  125.     }
  126.     private function cartChanged(Cart $previousCart $current): bool
  127.     {
  128.         $previousLineItems $previous->getLineItems();
  129.         $currentLineItems $current->getLineItems();
  130.         return $previousLineItems->count() !== $currentLineItems->count()
  131.             || $previous->getPrice()->getTotalPrice() !== $current->getPrice()->getTotalPrice()
  132.             || $previousLineItems->getKeys() !== $currentLineItems->getKeys()
  133.             || $previousLineItems->getTypes() !== $currentLineItems->getTypes()
  134.         ;
  135.     }
  136.     private function detectTaxType(SalesChannelContext $contextfloat $cartNetAmount 0): string
  137.     {
  138.         $currency $context->getCurrency();
  139.         $currencyTaxFreeAmount $currency->getTaxFreeFrom();
  140.         $isReachedCurrencyTaxFreeAmount $currencyTaxFreeAmount && $cartNetAmount >= $currencyTaxFreeAmount;
  141.         if ($isReachedCurrencyTaxFreeAmount) {
  142.             return CartPrice::TAX_STATE_FREE;
  143.         }
  144.         $country $context->getShippingLocation()->getCountry();
  145.         $isReachedCustomerTaxFreeAmount $country->getCustomerTax()->getEnabled() && $this->isReachedCountryTaxFreeAmount($context$country$cartNetAmount);
  146.         $isReachedCompanyTaxFreeAmount $this->taxDetector->isCompanyTaxFree($context$country) && $this->isReachedCountryTaxFreeAmount($context$country$cartNetAmountCountryDefinition::TYPE_COMPANY_TAX_FREE);
  147.         if ($isReachedCustomerTaxFreeAmount || $isReachedCompanyTaxFreeAmount) {
  148.             return CartPrice::TAX_STATE_FREE;
  149.         }
  150.         if ($this->taxDetector->useGross($context)) {
  151.             return CartPrice::TAX_STATE_GROSS;
  152.         }
  153.         return CartPrice::TAX_STATE_NET;
  154.     }
  155.     /**
  156.      * @param array<string, string> $timestamps
  157.      */
  158.     private function updated(Cart $cart, array $timestamps): bool
  159.     {
  160.         foreach ($cart->getLineItems() as $lineItem) {
  161.             if (!isset($timestamps[$lineItem->getId()])) {
  162.                 return true;
  163.             }
  164.             $original $timestamps[$lineItem->getId()];
  165.             $timestamp $lineItem->getDataTimestamp() !== null $lineItem->getDataTimestamp()->format(Defaults::STORAGE_DATE_TIME_FORMAT) : null;
  166.             if ($original !== $timestamp) {
  167.                 return true;
  168.             }
  169.         }
  170.         return \count($timestamps) !== $cart->getLineItems()->count();
  171.     }
  172.     private function isReachedCountryTaxFreeAmount(
  173.         SalesChannelContext $context,
  174.         CountryEntity $country,
  175.         float $cartNetAmount 0,
  176.         string $taxFreeType CountryDefinition::TYPE_CUSTOMER_TAX_FREE
  177.     ): bool {
  178.         $countryTaxFreeLimit $taxFreeType === CountryDefinition::TYPE_CUSTOMER_TAX_FREE $country->getCustomerTax() : $country->getCompanyTax();
  179.         if (!$countryTaxFreeLimit->getEnabled()) {
  180.             return false;
  181.         }
  182.         $countryTaxFreeLimitAmount $countryTaxFreeLimit->getAmount() / $this->fetchCurrencyFactor($countryTaxFreeLimit->getCurrencyId(), $context);
  183.         $currency $context->getCurrency();
  184.         $cartNetAmount /= $this->fetchCurrencyFactor($currency->getId(), $context);
  185.         // currency taxFreeAmount === 0.0 mean currency taxFreeFrom is disabled
  186.         return $currency->getTaxFreeFrom() === 0.0 && FloatComparator::greaterThanOrEquals($cartNetAmount$countryTaxFreeLimitAmount);
  187.     }
  188.     private function fetchCurrencyFactor(string $currencyIdSalesChannelContext $context): float
  189.     {
  190.         if ($currencyId === Defaults::CURRENCY) {
  191.             return 1;
  192.         }
  193.         $currency $context->getCurrency();
  194.         if ($currencyId === $currency->getId()) {
  195.             return $currency->getFactor();
  196.         }
  197.         if (\array_key_exists($currencyId$this->currencyFactor)) {
  198.             return $this->currencyFactor[$currencyId];
  199.         }
  200.         $currencyFactor $this->connection->fetchOne(
  201.             'SELECT `factor` FROM `currency` WHERE `id` = :currencyId',
  202.             ['currencyId' => Uuid::fromHexToBytes($currencyId)]
  203.         );
  204.         if (!$currencyFactor) {
  205.             throw new EntityNotFoundException('currency'$currencyId);
  206.         }
  207.         return $this->currencyFactor[$currencyId] = (float) $currencyFactor;
  208.     }
  209.     private function validateTaxFree(SalesChannelContext $contextCart $cartCartBehavior $behaviorContext): Cart
  210.     {
  211.         $totalCartNetAmount $cart->getPrice()->getPositionPrice();
  212.         if ($context->getTaxState() === CartPrice::TAX_STATE_GROSS) {
  213.             $totalCartNetAmount $totalCartNetAmount $cart->getLineItems()->getPrices()->getCalculatedTaxes()->getAmount();
  214.         }
  215.         $taxState $this->detectTaxType($context$totalCartNetAmount);
  216.         $previous $context->getTaxState();
  217.         if ($taxState === $previous) {
  218.             return $cart;
  219.         }
  220.         $context->setTaxState($taxState);
  221.         $cart->setData(null);
  222.         $cart $this->processor->process($cart$context$behaviorContext);
  223.         if ($previous !== CartPrice::TAX_STATE_FREE) {
  224.             $context->setTaxState($previous);
  225.         }
  226.         return $cart;
  227.     }
  228. }