vendor/shopware/platform/src/Core/Content/Product/DataAbstractionLayer/StockUpdater.php line 172

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