I am trying to import products programmatically into a Magento 2.4.4 installation but I have problem setting the Salable Quantity. I cannot find a viable solution to this issue, please help if you can.
Here is the code I am using to set product Quantity (simplified):
use MagentoCatalogApiProductRepositoryInterface;
use MagentoInventoryApiApiDataSourceItemInterfaceFactory;
use MagentoInventoryApiApiSourceItemsSaveInterface;
public function __construct(
ProductRepositoryInterface $productRepository,
SourceItemInterfaceFactory $sourceItemFactory,
SourceItemsSaveInterface $sourceItemsSave
)
{
$this->productRepository = $productRepository;
$this->sourceItemFactory = $sourceItemFactory;
$this->sourceItemsSave = $sourceItemsSave;
}
private function updateStock($product_id, $qty)
{
$product = $this->productRepository->getById($product_id);
$sourceItem = $this->sourceItemFactory->create();
$sourceItem->setSourceCode('default');
$sourceItem->setSku($product->getSku());
$sourceItem->setQuantity($qty);
$sourceItem->setStatus($qty > 0);
$this->sourceItemsSave->execute([$sourceItem]);
}
After finishing import, I run manually reindex and cache flush:
bin/magento indexer:reindex & bin/magento cache:flush
When displaying the product grid, the product’s Quantity is set correctly but the Salable Quantity is always zero (0). Only after I edit/save the product in admin panel manually, the Salable Quantity is set correctly and equal to Quantity. But this is not a viable solution when having to import thousands of products.
Could you provide an example on how to set the Salable Quantity programmatically?
Thanks