I'm creating a product programmatically and trying to update its stock quantity (XXX) afterwards, but the products grid always shows Quantity: XXX, Default Stock: 0.
I'm using Magento 2.4.4 [which uses MultiSource Inventory by default], with only the default source and default stock.
Here's what I've tried:
/** @var \Magento\Catalog\Model\Product $product */
$product = $this->productFactory->create();
$product
->setTypeId(Type::TYPE_SIMPLE)
->setSku('test');
(...)
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $this->productRepository */
$product = $this->productRepository->save($product)
Later I try to update the stock with:
1: works but it is deprecated
/** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem
->setIsInStock(true)
->setQty(XXX)
->setStockStatusChangedAuto(true);
$product = $this->productRepository->save($product)
2: works but it is deprecated
$product->setQuantityAndStockStatus(['qty' => XXX, 'is_in_stock' => 1]);
$product = $this->productRepository->save($product)
3: updates product quantity but doesn't update its salable quantity. The table inventory_stock_1
is filled with zero quantity and is_salable
= 0
/** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */
$stockItem = $product->getExtensionAttributes()->getStockItem();
$stockItem
->setIsInStock(true)
->setQty(XXX)
->setStockStatusChangedAuto(true);
/** @var \Magento\InventoryApi\Api\GetSourceItemsBySkuInterface $this->getSourceItemsBySku */
$stockItems = $this->getSourceItemsBySku->execute($product->getSku());
reset($stockItems)->setQuantity(XXX);
reset($stockItems)->setStatus(SourceItemInterface::STATUS_IN_STOCK);
/** @var \Magento\InventoryApi\Api\SourceItemsSaveInterface $this->sourceItemsSave */
$this->sourceItemsSave->execute($stockItems);
Am I missing any additional steps so the Inventory API method works correctly?