vendor/shopware/core/Checkout/Cart/CartRuleLoader.php line 76

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