I am trying to add stock quantity dynamically and use the current stock quantity for adding the product to the cart. The stock quantity gets updated successfully, however the ProductRepository keeps returning the outdated stock quantity, therefore I keep getting "out of stock" exception. What's the proper way to achieve this?
if ($stockItem->getQuantity() - $params["qty"] <= 0) { $sourceItem = $this->sourceItemFactory->create(); $sourceItem->setSourceCode('default'); $sourceItem->setSku($product->getSku()); $sourceItem->setQuantity(floatval($params["qty"])+$stockItem->getQuantity()+1); $sourceItem->setStatus(1); $this->sourceItemsSaveInterface->execute([$sourceItem]); // The following part throws an exception (out of stock) // SourceItemRepositoryInterface returns the correct stock and quantity information at this point, however $product (even when retrieved from ProductRepository) has the outdated stock information $this->quote->addProduct($product, $params);
You need to reindex the product before adding and shopping cart, this will help to update the product quantity
protected $indexerRegistry; public function __construct( IndexerRegistry $indexerRegistry ) { $this->indexerRegistry = $indexerRegistry; } public function getVersion() { ......... $this->indexerRegistry->get('catalog_product_category')->reindexRow($product->getId()); ......... }