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

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