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

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->getOperation() === EntityWriteResult::OPERATION_INSERT) {
  98.                 continue;
  99.             }
  100.             $changeSet $result->getChangeSet();
  101.             if (!$changeSet) {
  102.                 continue;
  103.             }
  104.             $type $changeSet->getBefore('type');
  105.             if ($type !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  106.                 continue;
  107.             }
  108.             if (!$changeSet->hasChanged('referenced_id') && !$changeSet->hasChanged('quantity')) {
  109.                 continue;
  110.             }
  111.             $ids[] = $changeSet->getBefore('referenced_id');
  112.             $ids[] = $changeSet->getAfter('referenced_id');
  113.         }
  114.         $ids array_filter(array_unique($ids));
  115.         if (empty($ids)) {
  116.             return;
  117.         }
  118.         $this->update($ids$event->getContext());
  119.         $this->clearCache($ids);
  120.     }
  121.     public function stateChanged(StateMachineTransitionEvent $event): void
  122.     {
  123.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  124.             return;
  125.         }
  126.         if ($event->getEntityName() !== 'order') {
  127.             return;
  128.         }
  129.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  130.             $this->decreaseStock($event);
  131.             return;
  132.         }
  133.         if ($event->getFromPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  134.             $this->increaseStock($event);
  135.             return;
  136.         }
  137.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED || $event->getFromPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED) {
  138.             $products $this->getProductsOfOrder($event->getEntityId());
  139.             $ids array_column($products'referenced_id');
  140.             $this->updateAvailableStock($ids$event->getContext());
  141.             $this->updateAvailableFlag($ids$event->getContext());
  142.             $this->clearCache($ids);
  143.             return;
  144.         }
  145.     }
  146.     public function update(array $idsContext $context): void
  147.     {
  148.         if ($context->getVersionId() !== Defaults::LIVE_VERSION) {
  149.             return;
  150.         }
  151.         $this->updateAvailableStock($ids$context);
  152.         $this->updateAvailableFlag($ids$context);
  153.     }
  154.     public function orderPlaced(CheckoutOrderPlacedEvent $event): void
  155.     {
  156.         $ids = [];
  157.         foreach ($event->getOrder()->getLineItems() as $lineItem) {
  158.             if ($lineItem->getType() !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  159.                 continue;
  160.             }
  161.             $ids[] = $lineItem->getReferencedId();
  162.         }
  163.         $this->update($ids$event->getContext());
  164.         $this->clearCache($ids);
  165.     }
  166.     private function increaseStock(StateMachineTransitionEvent $event): void
  167.     {
  168.         $products $this->getProductsOfOrder($event->getEntityId());
  169.         $ids array_column($products'referenced_id');
  170.         $this->updateStock($products, +1);
  171.         $this->updateAvailableStock($ids$event->getContext());
  172.         $this->updateAvailableFlag($ids$event->getContext());
  173.         $this->clearCache($ids);
  174.     }
  175.     private function decreaseStock(StateMachineTransitionEvent $event): void
  176.     {
  177.         $products $this->getProductsOfOrder($event->getEntityId());
  178.         $ids array_column($products'referenced_id');
  179.         $this->updateStock($products, -1);
  180.         $this->updateAvailableStock($ids$event->getContext());
  181.         $this->updateAvailableFlag($ids$event->getContext());
  182.         $this->clearCache($ids);
  183.     }
  184.     private function updateAvailableStock(array $idsContext $context): void
  185.     {
  186.         $ids array_filter(array_keys(array_flip($ids)));
  187.         if (empty($ids)) {
  188.             return;
  189.         }
  190.         $bytes Uuid::fromHexToBytesList($ids);
  191.         $sql '
  192. UPDATE product SET available_stock = stock - (
  193.     SELECT IFNULL(SUM(order_line_item.quantity), 0)
  194.     FROM order_line_item
  195.         INNER JOIN `order`
  196.             ON `order`.id = order_line_item.order_id
  197.             AND `order`.version_id = order_line_item.order_version_id
  198.         INNER JOIN state_machine_state
  199.             ON state_machine_state.id = `order`.state_id
  200.             AND state_machine_state.technical_name NOT IN (:states)
  201.     WHERE LOWER(order_line_item.referenced_id) = LOWER(HEX(product.id))
  202.     AND order_line_item.type = :type
  203.     AND order_line_item.version_id = :version
  204. )
  205. WHERE product.id IN (:ids) AND product.version_id = :version;
  206.         ';
  207.         RetryableQuery::retryable(function () use ($sql$bytes$context): void {
  208.             $this->connection->executeUpdate(
  209.                 $sql,
  210.                 [
  211.                     'type' => LineItem::PRODUCT_LINE_ITEM_TYPE,
  212.                     'version' => Uuid::fromHexToBytes($context->getVersionId()),
  213.                     'states' => [OrderStates::STATE_COMPLETEDOrderStates::STATE_CANCELLED],
  214.                     'ids' => $bytes,
  215.                 ],
  216.                 [
  217.                     'ids' => Connection::PARAM_STR_ARRAY,
  218.                     'states' => Connection::PARAM_STR_ARRAY,
  219.                 ]
  220.             );
  221.         });
  222.     }
  223.     private function updateAvailableFlag(array $idsContext $context): void
  224.     {
  225.         $ids array_filter(array_keys(array_flip($ids)));
  226.         if (empty($ids)) {
  227.             return;
  228.         }
  229.         $bytes Uuid::fromHexToBytesList($ids);
  230.         $sql '
  231.             UPDATE product
  232.             LEFT JOIN product parent
  233.                 ON parent.id = product.parent_id
  234.                 AND parent.version_id = product.version_id
  235.             SET product.available = IFNULL((
  236.                 IFNULL(product.is_closeout, parent.is_closeout) * product.available_stock
  237.                 >=
  238.                 IFNULL(product.is_closeout, parent.is_closeout) * IFNULL(product.min_purchase, parent.min_purchase)
  239.             ), 0)
  240.             WHERE product.id IN (:ids)
  241.             AND product.version_id = :version
  242.         ';
  243.         RetryableQuery::retryable(function () use ($sql$context$bytes): void {
  244.             $this->connection->executeUpdate(
  245.                 $sql,
  246.                 ['ids' => $bytes'version' => Uuid::fromHexToBytes($context->getVersionId())],
  247.                 ['ids' => Connection::PARAM_STR_ARRAY]
  248.             );
  249.         });
  250.     }
  251.     private function updateStock(array $productsint $multiplier): void
  252.     {
  253.         $query = new RetryableQuery(
  254.             $this->connection->prepare('UPDATE product SET stock = stock + :quantity WHERE id = :id AND version_id = :version')
  255.         );
  256.         foreach ($products as $product) {
  257.             $query->execute([
  258.                 'quantity' => (int) $product['quantity'] * $multiplier,
  259.                 'id' => Uuid::fromHexToBytes($product['referenced_id']),
  260.                 'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION),
  261.             ]);
  262.         }
  263.     }
  264.     private function getProductsOfOrder(string $orderId): array
  265.     {
  266.         $query $this->connection->createQueryBuilder();
  267.         $query->select(['referenced_id''quantity']);
  268.         $query->from('order_line_item');
  269.         $query->andWhere('type = :type');
  270.         $query->andWhere('order_id = :id');
  271.         $query->setParameter('id'Uuid::fromHexToBytes($orderId));
  272.         $query->setParameter('type'LineItem::PRODUCT_LINE_ITEM_TYPE);
  273.         return $query->execute()->fetchAll(\PDO::FETCH_ASSOC);
  274.     }
  275.     private function clearCache(array $ids): void
  276.     {
  277.         $tags = [];
  278.         foreach ($ids as $id) {
  279.             $tags[] = $this->cacheKeyGenerator->getEntityTag($id$this->definition->getEntityName());
  280.         }
  281.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'id');
  282.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'available');
  283.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'availableStock');
  284.         $tags[] = $this->cacheKeyGenerator->getFieldTag($this->definition'stock');
  285.         $this->cache->invalidateTags($tags);
  286.     }
  287. }