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

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