vendor/shopware/core/Content/Product/DataAbstractionLayer/StockUpdater.php line 76

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Product\DataAbstractionLayer;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
  5. use Shopware\Core\Checkout\Cart\LineItem\LineItem;
  6. use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemDefinition;
  7. use Shopware\Core\Checkout\Order\OrderEvents;
  8. use Shopware\Core\Checkout\Order\OrderStates;
  9. use Shopware\Core\Content\Product\ProductDefinition;
  10. use Shopware\Core\Defaults;
  11. use Shopware\Core\Framework\Adapter\Cache\CacheClearer;
  12. use Shopware\Core\Framework\Context;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Cache\EntityCacheKeyGenerator;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\RetryableQuery;
  15. use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\ChangeSetAware;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\DeleteCommand;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\InsertCommand;
  20. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\UpdateCommand;
  21. use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
  22. use Shopware\Core\Framework\Uuid\Uuid;
  23. use Shopware\Core\System\StateMachine\Event\StateMachineTransitionEvent;
  24. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  25. class StockUpdater implements EventSubscriberInterface
  26. {
  27.     /**
  28.      * @var Connection
  29.      */
  30.     private $connection;
  31.     /**
  32.      * @var ProductDefinition
  33.      */
  34.     private $definition;
  35.     /**
  36.      * @var CacheClearer
  37.      */
  38.     private $cache;
  39.     /**
  40.      * @var EntityCacheKeyGenerator
  41.      */
  42.     private $cacheKeyGenerator;
  43.     public function __construct(
  44.         Connection $connection,
  45.         ProductDefinition $definition,
  46.         CacheClearer $cache,
  47.         EntityCacheKeyGenerator $cacheKeyGenerator
  48.     ) {
  49.         $this->connection $connection;
  50.         $this->definition $definition;
  51.         $this->cache $cache;
  52.         $this->cacheKeyGenerator $cacheKeyGenerator;
  53.     }
  54.     /**
  55.      * Returns a list of custom business events to listen where the product maybe changed
  56.      */
  57.     public static function getSubscribedEvents()
  58.     {
  59.         return [
  60.             CheckoutOrderPlacedEvent::class => 'orderPlaced',
  61.             StateMachineTransitionEvent::class => 'stateChanged',
  62.             PreWriteValidationEvent::class => 'triggerChangeSet',
  63.             OrderEvents::ORDER_LINE_ITEM_WRITTEN_EVENT => 'lineItemWritten',
  64.             OrderEvents::ORDER_LINE_ITEM_DELETED_EVENT => 'lineItemWritten',
  65.         ];
  66.     }
  67.     public function triggerChangeSet(PreWriteValidationEvent $event): void
  68.     {
  69.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  70.             return;
  71.         }
  72.         foreach ($event->getCommands() as $command) {
  73.             if (!$command instanceof ChangeSetAware) {
  74.                 continue;
  75.             }
  76.             /** @var ChangeSetAware|InsertCommand|UpdateCommand $command */
  77.             if ($command->getDefinition()->getEntityName() !== OrderLineItemDefinition::ENTITY_NAME) {
  78.                 continue;
  79.             }
  80.             if ($command instanceof DeleteCommand) {
  81.                 $command->requestChangeSet();
  82.                 continue;
  83.             }
  84.             if ($command->hasField('referenced_id') || $command->hasField('product_id') || $command->hasField('quantity')) {
  85.                 $command->requestChangeSet();
  86.                 continue;
  87.             }
  88.         }
  89.     }
  90.     /**
  91.      * If the product of an order item changed, the stocks of the old product and the new product must be updated.
  92.      */
  93.     public function lineItemWritten(EntityWrittenEvent $event): void
  94.     {
  95.         $ids = [];
  96.         foreach ($event->getWriteResults() as $result) {
  97.             if ($result->hasPayload('referencedId') && $result->getProperty('type') === LineItem::PRODUCT_LINE_ITEM_TYPE) {
  98.                 $ids[] = $result->getProperty('referencedId');
  99.             }
  100.             if ($result->getOperation() === EntityWriteResult::OPERATION_INSERT) {
  101.                 continue;
  102.             }
  103.             $changeSet $result->getChangeSet();
  104.             if (!$changeSet) {
  105.                 continue;
  106.             }
  107.             $type $changeSet->getBefore('type');
  108.             if ($type !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  109.                 continue;
  110.             }
  111.             if (!$changeSet->hasChanged('referenced_id') && !$changeSet->hasChanged('quantity')) {
  112.                 continue;
  113.             }
  114.             $ids[] = $changeSet->getBefore('referenced_id');
  115.             $ids[] = $changeSet->getAfter('referenced_id');
  116.         }
  117.         $ids array_filter(array_unique($ids));
  118.         if (empty($ids)) {
  119.             return;
  120.         }
  121.         $this->update($ids$event->getContext());
  122.         $this->clearCache($ids);
  123.     }
  124.     public function stateChanged(StateMachineTransitionEvent $event): void
  125.     {
  126.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  127.             return;
  128.         }
  129.         if ($event->getEntityName() !== 'order') {
  130.             return;
  131.         }
  132.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  133.             $this->decreaseStock($event);
  134.             return;
  135.         }
  136.         if ($event->getFromPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  137.             $this->increaseStock($event);
  138.             return;
  139.         }
  140.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED || $event->getFromPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED) {
  141.             $products $this->getProductsOfOrder($event->getEntityId());
  142.             $ids array_column($products'referenced_id');
  143.             $this->updateAvailableStock($ids$event->getContext());
  144.             $this->updateAvailableFlag($ids$event->getContext());
  145.             $this->clearCache($ids);
  146.             return;
  147.         }
  148.     }
  149.     public function update(array $idsContext $context): void
  150.     {
  151.         if ($context->getVersionId() !== Defaults::LIVE_VERSION) {
  152.             return;
  153.         }
  154.         $this->updateAvailableStock($ids$context);
  155.         $this->updateAvailableFlag($ids$context);
  156.     }
  157.     public function orderPlaced(CheckoutOrderPlacedEvent $event): void
  158.     {
  159.         $ids = [];
  160.         foreach ($event->getOrder()->getLineItems() as $lineItem) {
  161.             if ($lineItem->getType() !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  162.                 continue;
  163.             }
  164.             $ids[] = $lineItem->getReferencedId();
  165.         }
  166.         $this->update($ids$event->getContext());
  167.         $this->clearCache($ids);
  168.     }
  169.     private function increaseStock(StateMachineTransitionEvent $event): void
  170.     {
  171.         $products $this->getProductsOfOrder($event->getEntityId());
  172.         $ids array_column($products'referenced_id');
  173.         $this->updateStock($products, +1);
  174.         $this->updateAvailableStock($ids$event->getContext());
  175.         $this->updateAvailableFlag($ids$event->getContext());
  176.         $this->clearCache($ids);
  177.     }
  178.     private function decreaseStock(StateMachineTransitionEvent $event): void
  179.     {
  180.         $products $this->getProductsOfOrder($event->getEntityId());
  181.         $ids array_column($products'referenced_id');
  182.         $this->updateStock($products, -1);
  183.         $this->updateAvailableStock($ids$event->getContext());
  184.         $this->updateAvailableFlag($ids$event->getContext());
  185.         $this->clearCache($ids);
  186.     }
  187.     private function updateAvailableStock(array $idsContext $context): void
  188.     {
  189.         $ids array_filter(array_keys(array_flip($ids)));
  190.         if (empty($ids)) {
  191.             return;
  192.         }
  193.         $bytes Uuid::fromHexToBytesList($ids);
  194.         $sql '
  195. UPDATE product SET available_stock = stock - (
  196.     SELECT IFNULL(SUM(order_line_item.quantity), 0)
  197.     FROM order_line_item
  198.         INNER JOIN `order`
  199.             ON `order`.id = order_line_item.order_id
  200.             AND `order`.version_id = order_line_item.order_version_id
  201.         INNER JOIN state_machine_state
  202.             ON state_machine_state.id = `order`.state_id
  203.             AND state_machine_state.technical_name NOT IN (:states)
  204.     WHERE LOWER(order_line_item.referenced_id) = LOWER(HEX(product.id))
  205.     AND order_line_item.type = :type
  206.     AND order_line_item.version_id = :version
  207. )
  208. WHERE product.id IN (:ids) AND product.version_id = :version;
  209.         ';
  210.         RetryableQuery::retryable(function () use ($sql$bytes$context): void {
  211.             $this->connection->executeUpdate(
  212.                 $sql,
  213.                 [
  214.                     'type' => LineItem::PRODUCT_LINE_ITEM_TYPE,
  215.                     'version' => Uuid::fromHexToBytes($context->getVersionId()),
  216.                     'states' => [OrderStates::STATE_COMPLETEDOrderStates::STATE_CANCELLED],
  217.                     'ids' => $bytes,
  218.                 ],
  219.                 [
  220.                     'ids' => Connection::PARAM_STR_ARRAY,
  221.                     'states' => Connection::PARAM_STR_ARRAY,
  222.                 ]
  223.             );
  224.         });
  225.     }
  226.     private function updateAvailableFlag(array $idsContext $context): void
  227.     {
  228.         $ids array_filter(array_keys(array_flip($ids)));
  229.         if (empty($ids)) {
  230.             return;
  231.         }
  232.         $bytes Uuid::fromHexToBytesList($ids);
  233.         $sql '
  234.             UPDATE product
  235.             LEFT JOIN product parent
  236.                 ON parent.id = product.parent_id
  237.                 AND parent.version_id = product.version_id
  238.             SET product.available = IFNULL((
  239.                 IFNULL(product.is_closeout, parent.is_closeout) * product.available_stock
  240.                 >=
  241.                 IFNULL(product.is_closeout, parent.is_closeout) * IFNULL(product.min_purchase, parent.min_purchase)
  242.             ), 0)
  243.             WHERE product.id IN (:ids)
  244.             AND product.version_id = :version
  245.         ';
  246.         RetryableQuery::retryable(function () use ($sql$context$bytes): void {
  247.             $this->connection->executeUpdate(
  248.                 $sql,
  249.                 ['ids' => $bytes'version' => Uuid::fromHexToBytes($context->getVersionId())],
  250.                 ['ids' => Connection::PARAM_STR_ARRAY]
  251.             );
  252.         });
  253.     }
  254.     private function updateStock(array $productsint $multiplier): void
  255.     {
  256.         $query = new RetryableQuery(
  257.             $this->connection->prepare('UPDATE product SET stock = stock + :quantity WHERE id = :id AND version_id = :version')
  258.         );
  259.         foreach ($products as $product) {
  260.             $query->execute([
  261.                 'quantity' => (int) $product['quantity'] * $multiplier,
  262.                 'id' => Uuid::fromHexToBytes($product['referenced_id']),
  263.                 'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION),
  264.             ]);
  265.         }
  266.     }
  267.     private function getProductsOfOrder(string $orderId): array
  268.     {
  269.         $query $this->connection->createQueryBuilder();
  270.         $query->select(['referenced_id''quantity']);
  271.         $query->from('order_line_item');
  272.         $query->andWhere('type = :type');
  273.         $query->andWhere('order_id = :id');
  274.         $query->andWhere('version_id = :version');
  275.         $query->setParameter('id'Uuid::fromHexToBytes($orderId));
  276.         $query->setParameter('version'Uuid::fromHexToBytes(Defaults::LIVE_VERSION));
  277.         $query->setParameter('type'LineItem::PRODUCT_LINE_ITEM_TYPE);
  278.         return $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
  279.     }
  280.     private function clearCache(array $ids): void
  281.     {
  282.         $tags = [];
  283.         foreach ($ids as $id) {
  284.             $tags[] = $this->cacheKeyGenerator->getEntityTag($id$this->definition->getEntityName());
  285.         }
  286.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'id');
  287.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'available');
  288.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'availableStock');
  289.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'stock');
  290.         $this->cache->invalidateTags($tags);
  291.     }
  292. }