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

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