src/Core/Content/Product/DataAbstractionLayer/StockUpdater.php line 87

  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\DataAbstractionLayer\StockUpdate\StockUpdateFilterProvider;
  10. use Shopware\Core\Content\Product\Events\ProductNoLongerAvailableEvent;
  11. use Shopware\Core\Defaults;
  12. use Shopware\Core\Framework\Context;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\RetryableQuery;
  14. use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\ChangeSetAware;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\DeleteCommand;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Write\Command\WriteCommand;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Write\Validation\PreWriteValidationEvent;
  20. use Shopware\Core\Framework\Log\Package;
  21. use Shopware\Core\Framework\Uuid\Uuid;
  22. use Shopware\Core\Profiling\Profiler;
  23. use Shopware\Core\System\StateMachine\Event\StateMachineTransitionEvent;
  24. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  25. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  26. /**
  27.  * @internal
  28.  */
  29. #[Package('core')]
  30. class StockUpdater implements EventSubscriberInterface
  31. {
  32.     /**
  33.      * @internal
  34.      */
  35.     public function __construct(
  36.         private readonly Connection $connection,
  37.         private readonly EventDispatcherInterface $dispatcher,
  38.         private readonly StockUpdateFilterProvider $stockUpdateFilter
  39.     ) {
  40.     }
  41.     /**
  42.      * Returns a list of custom business events to listen where the product maybe changed
  43.      *
  44.      * @return array<string, string|array{0: string, 1: int}|list<array{0: string, 1?: int}>>
  45.      */
  46.     public static function getSubscribedEvents(): array
  47.     {
  48.         return [
  49.             CheckoutOrderPlacedEvent::class => 'orderPlaced',
  50.             StateMachineTransitionEvent::class => 'stateChanged',
  51.             PreWriteValidationEvent::class => 'triggerChangeSet',
  52.             OrderEvents::ORDER_LINE_ITEM_WRITTEN_EVENT => 'lineItemWritten',
  53.             OrderEvents::ORDER_LINE_ITEM_DELETED_EVENT => 'lineItemWritten',
  54.         ];
  55.     }
  56.     public function triggerChangeSet(PreWriteValidationEvent $event): void
  57.     {
  58.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  59.             return;
  60.         }
  61.         foreach ($event->getCommands() as $command) {
  62.             if (!$command instanceof ChangeSetAware) {
  63.                 continue;
  64.             }
  65.             /** @var ChangeSetAware&WriteCommand $command */
  66.             if ($command->getDefinition()->getEntityName() !== OrderLineItemDefinition::ENTITY_NAME) {
  67.                 continue;
  68.             }
  69.             if ($command instanceof DeleteCommand) {
  70.                 $command->requestChangeSet();
  71.                 continue;
  72.             }
  73.             /** @var WriteCommand&ChangeSetAware $command */
  74.             if ($command->hasField('referenced_id') || $command->hasField('product_id') || $command->hasField('quantity')) {
  75.                 $command->requestChangeSet();
  76.             }
  77.         }
  78.     }
  79.     public function orderPlaced(CheckoutOrderPlacedEvent $event): void
  80.     {
  81.         $ids = [];
  82.         foreach ($event->getOrder()->getLineItems() ?? [] as $lineItem) {
  83.             if ($lineItem->getType() !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  84.                 continue;
  85.             }
  86.             $referencedId $lineItem->getReferencedId();
  87.             if (!$referencedId) {
  88.                 continue;
  89.             }
  90.             if (!\array_key_exists($referencedId$ids)) {
  91.                 $ids[$referencedId] = 0;
  92.             }
  93.             $ids[$referencedId] += $lineItem->getQuantity();
  94.         }
  95.         $filteredIds $this->stockUpdateFilter->filterProductIdsForStockUpdates(\array_keys($ids), $event->getContext());
  96.         $ids \array_filter($ids, static fn (string $id) => \in_array($id$filteredIdstrue), \ARRAY_FILTER_USE_KEY);
  97.         // order placed event is a high load event. Because of the high load, we simply reduce the quantity here instead of executing the high costs `update` function
  98.         $query = new RetryableQuery(
  99.             $this->connection,
  100.             $this->connection->prepare('UPDATE product SET available_stock = available_stock - :quantity WHERE id = :id')
  101.         );
  102.         Profiler::trace('order::update-stock', static function () use ($query$ids): void {
  103.             foreach ($ids as $id => $quantity) {
  104.                 $query->execute(['id' => Uuid::fromHexToBytes((string) $id), 'quantity' => $quantity]);
  105.             }
  106.         });
  107.         Profiler::trace('order::update-flag', function () use ($ids$event): void {
  108.             $this->updateAvailableFlag(\array_keys($ids), $event->getContext());
  109.         });
  110.     }
  111.     /**
  112.      * If the product of an order item changed, the stocks of the old product and the new product must be updated.
  113.      */
  114.     public function lineItemWritten(EntityWrittenEvent $event): void
  115.     {
  116.         $ids = [];
  117.         // we don't want to trigger to `update` method when we are inside the order process
  118.         if ($event->getContext()->hasState('checkout-order-route')) {
  119.             return;
  120.         }
  121.         foreach ($event->getWriteResults() as $result) {
  122.             if ($result->hasPayload('referencedId') && $result->getProperty('type') === LineItem::PRODUCT_LINE_ITEM_TYPE) {
  123.                 $ids[] = $result->getProperty('referencedId');
  124.             }
  125.             if ($result->getOperation() === EntityWriteResult::OPERATION_INSERT) {
  126.                 continue;
  127.             }
  128.             $changeSet $result->getChangeSet();
  129.             if (!$changeSet) {
  130.                 continue;
  131.             }
  132.             $type $changeSet->getBefore('type');
  133.             if ($type !== LineItem::PRODUCT_LINE_ITEM_TYPE) {
  134.                 continue;
  135.             }
  136.             if (!$changeSet->hasChanged('referenced_id') && !$changeSet->hasChanged('quantity')) {
  137.                 continue;
  138.             }
  139.             $ids[] = $changeSet->getBefore('referenced_id');
  140.             $ids[] = $changeSet->getAfter('referenced_id');
  141.         }
  142.         $ids array_filter(array_unique($ids));
  143.         if (empty($ids)) {
  144.             return;
  145.         }
  146.         $this->update($ids$event->getContext());
  147.     }
  148.     public function stateChanged(StateMachineTransitionEvent $event): void
  149.     {
  150.         if ($event->getContext()->getVersionId() !== Defaults::LIVE_VERSION) {
  151.             return;
  152.         }
  153.         if ($event->getEntityName() !== 'order') {
  154.             return;
  155.         }
  156.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  157.             $products $this->getProductsOfOrder($event->getEntityId(), $event->getContext());
  158.             $this->updateStockAndSales($products, -1);
  159.             return;
  160.         }
  161.         if ($event->getFromPlace()->getTechnicalName() === OrderStates::STATE_COMPLETED) {
  162.             $products $this->getProductsOfOrder($event->getEntityId(), $event->getContext());
  163.             $this->updateStockAndSales($products, +1);
  164.             return;
  165.         }
  166.         if ($event->getToPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED || $event->getFromPlace()->getTechnicalName() === OrderStates::STATE_CANCELLED) {
  167.             $products $this->getProductsOfOrder($event->getEntityId(), $event->getContext());
  168.             $ids array_column($products'referenced_id');
  169.             $this->updateAvailableStockAndSales($ids$event->getContext());
  170.             $this->updateAvailableFlag($ids$event->getContext());
  171.         }
  172.     }
  173.     /**
  174.      * @param list<string> $ids
  175.      */
  176.     public function update(array $idsContext $context): void
  177.     {
  178.         if ($context->getVersionId() !== Defaults::LIVE_VERSION) {
  179.             return;
  180.         }
  181.         $ids $this->stockUpdateFilter->filterProductIdsForStockUpdates($ids$context);
  182.         $this->updateAvailableStockAndSales($ids$context);
  183.         $this->updateAvailableFlag($ids$context);
  184.     }
  185.     /**
  186.      * @param list<string> $ids
  187.      */
  188.     private function updateAvailableStockAndSales(array $idsContext $context): void
  189.     {
  190.         $ids array_filter(array_keys(array_flip($ids)));
  191.         if (empty($ids)) {
  192.             return;
  193.         }
  194.         $sql '
  195. SELECT LOWER(HEX(order_line_item.product_id)) as product_id,
  196.     IFNULL(
  197.         SUM(IF(state_machine_state.technical_name = :completed_state, 0, order_line_item.quantity)),
  198.         0
  199.     ) as open_quantity,
  200.     IFNULL(
  201.         SUM(IF(state_machine_state.technical_name = :completed_state, order_line_item.quantity, 0)),
  202.         0
  203.     ) as sales_quantity
  204. FROM order_line_item
  205.     INNER JOIN `order`
  206.         ON `order`.id = order_line_item.order_id
  207.         AND `order`.version_id = order_line_item.order_version_id
  208.     INNER JOIN state_machine_state
  209.         ON state_machine_state.id = `order`.state_id
  210.         AND state_machine_state.technical_name <> :cancelled_state
  211. WHERE order_line_item.product_id IN (:ids)
  212.     AND order_line_item.type = :type
  213.     AND order_line_item.version_id = :version
  214.     AND order_line_item.product_id IS NOT NULL
  215. GROUP BY product_id;
  216.         ';
  217.         $rows $this->connection->fetchAllAssociative(
  218.             $sql,
  219.             [
  220.                 'type' => LineItem::PRODUCT_LINE_ITEM_TYPE,
  221.                 'version' => Uuid::fromHexToBytes($context->getVersionId()),
  222.                 'completed_state' => OrderStates::STATE_COMPLETED,
  223.                 'cancelled_state' => OrderStates::STATE_CANCELLED,
  224.                 'ids' => Uuid::fromHexToBytesList($ids),
  225.             ],
  226.             [
  227.                 'ids' => Connection::PARAM_STR_ARRAY,
  228.             ]
  229.         );
  230.         $fallback array_column($rows'product_id');
  231.         $fallback array_diff($ids$fallback);
  232.         $update = new RetryableQuery(
  233.             $this->connection,
  234.             $this->connection->prepare('UPDATE product SET available_stock = stock - :open_quantity, sales = :sales_quantity, updated_at = :now WHERE id = :id')
  235.         );
  236.         foreach ($fallback as $id) {
  237.             $update->execute([
  238.                 'id' => Uuid::fromHexToBytes((string) $id),
  239.                 'open_quantity' => 0,
  240.                 'sales_quantity' => 0,
  241.                 'now' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
  242.             ]);
  243.         }
  244.         foreach ($rows as $row) {
  245.             $update->execute([
  246.                 'id' => Uuid::fromHexToBytes($row['product_id']),
  247.                 'open_quantity' => $row['open_quantity'],
  248.                 'sales_quantity' => $row['sales_quantity'],
  249.                 'now' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
  250.             ]);
  251.         }
  252.     }
  253.     /**
  254.      * @param list<string> $ids
  255.      */
  256.     private function updateAvailableFlag(array $idsContext $context): void
  257.     {
  258.         $ids array_filter(array_unique($ids));
  259.         if (empty($ids)) {
  260.             return;
  261.         }
  262.         $bytes Uuid::fromHexToBytesList($ids);
  263.         $sql '
  264.             UPDATE product
  265.             LEFT JOIN product parent
  266.                 ON parent.id = product.parent_id
  267.                 AND parent.version_id = product.version_id
  268.             SET product.available = IFNULL((
  269.                 IFNULL(product.is_closeout, parent.is_closeout) * product.available_stock
  270.                 >=
  271.                 IFNULL(product.is_closeout, parent.is_closeout) * IFNULL(product.min_purchase, parent.min_purchase)
  272.             ), 0)
  273.             WHERE product.id IN (:ids)
  274.             AND product.version_id = :version
  275.         ';
  276.         RetryableQuery::retryable($this->connection, function () use ($sql$context$bytes): void {
  277.             $this->connection->executeStatement(
  278.                 $sql,
  279.                 ['ids' => $bytes'version' => Uuid::fromHexToBytes($context->getVersionId())],
  280.                 ['ids' => Connection::PARAM_STR_ARRAY]
  281.             );
  282.         });
  283.         $updated $this->connection->fetchFirstColumn(
  284.             'SELECT LOWER(HEX(id)) FROM product WHERE available = 0 AND id IN (:ids) AND product.version_id = :version',
  285.             ['ids' => $bytes'version' => Uuid::fromHexToBytes($context->getVersionId())],
  286.             ['ids' => Connection::PARAM_STR_ARRAY]
  287.         );
  288.         if (!empty($updated)) {
  289.             $this->dispatcher->dispatch(new ProductNoLongerAvailableEvent($updated$context));
  290.         }
  291.     }
  292.     /**
  293.      * @param list<array{referenced_id: string, quantity: string}> $products
  294.      */
  295.     private function updateStockAndSales(array $productsint $stockMultiplier): void
  296.     {
  297.         $query = new RetryableQuery(
  298.             $this->connection,
  299.             $this->connection->prepare('UPDATE product SET stock = stock + :quantity, sales = sales - :quantity WHERE id = :id AND version_id = :version')
  300.         );
  301.         foreach ($products as $product) {
  302.             $query->execute([
  303.                 'quantity' => (int) $product['quantity'] * $stockMultiplier,
  304.                 'id' => Uuid::fromHexToBytes($product['referenced_id']),
  305.                 'version' => Uuid::fromHexToBytes(Defaults::LIVE_VERSION),
  306.             ]);
  307.         }
  308.     }
  309.     /**
  310.      * @return list<array{referenced_id: string, quantity: string}>
  311.      */
  312.     private function getProductsOfOrder(string $orderIdContext $context): array
  313.     {
  314.         $query $this->connection->createQueryBuilder();
  315.         $query->select(['referenced_id''quantity']);
  316.         $query->from('order_line_item');
  317.         $query->andWhere('type = :type');
  318.         $query->andWhere('order_id = :id');
  319.         $query->andWhere('version_id = :version');
  320.         $query->setParameter('id'Uuid::fromHexToBytes($orderId));
  321.         $query->setParameter('version'Uuid::fromHexToBytes(Defaults::LIVE_VERSION));
  322.         $query->setParameter('type'LineItem::PRODUCT_LINE_ITEM_TYPE);
  323.         /** @var list<array{referenced_id: string, quantity: string}> $result */
  324.         $result $query->executeQuery()->fetchAllAssociative();
  325.         $filteredIds $this->stockUpdateFilter->filterProductIdsForStockUpdates(\array_column($result'referenced_id'), $context);
  326.         return \array_filter($result, static fn (array $item) => \in_array($item['referenced_id'], $filteredIdstrue));
  327.     }
  328. }