How to Set Quantity to Product on MSI Magento 2.3

magento2.3msiproductquantitystock

In my custom module, I'm using StockRegistryInterface to set qty and save my product. But on Magento 2.3 I started facing the issue of having 0 salable qty right after saving the product.

Default stock 0

After digging a bit, I saw that StockRegistryInterface is deprecated and it was replaced with Multi Source Inventory. How should I save the qty of my product now?

Here is the piece of code where I do it with StockRegistryInterface:

        /* @var ProductInterface $product */
        $stockItem = $this->stock->getStockItemBySku($product->getSku());
        $stockItem->setQty($this->estoque_disponivel);
        $stockItem->setIsInStock(true);
        $this->stock->updateStockItemBySku($product->getSku(), $stockItem);

Best Answer

Here you go!

/**
 * @var Magento\InventoryApi\Api\SourceItemsSaveInterface
 */
protected $sourceItemsSave;

/**
 * @var Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory
 */
protected $sourceItemFactory;

/**
 * @param SourceItemsSaveInterface $sourceItemsSave
 * @param SourceItemInterfaceFactory $sourceItemFactory
 */
public function __construct(
    Magento\InventoryApi\Api\SourceItemsSaveInterface $sourceItemsSave,
    Magento\InventoryApi\Api\Data\SourceItemInterfaceFactory $sourceItemFactory,
) {
    $this->sourceItemsSave = $sourceItemsSave;
    $this->sourceItemFactory = $sourceItemFactory;
}

/**
 * @param $sku
 * @param $qty
 * @param $source
 */
public function setQtyToProduct($sku, $qty, $source)
{
    $sourceItem = $this->sourceItemFactory->create();
    $sourceItem->setSourceCode($source);
    $sourceItem->setSku($sku);
    $sourceItem->setQuantity($qty);
    $sourceItem->setStatus(1);

    $this->sourceItemsSave->execute([$sourceItem]);
}