DEV Community

Mathanagopal Sankarasubramanian
Mathanagopal Sankarasubramanian

Posted on

Magento 2 product saleable quantity

Hiya fellow devs, this is my first post here. Please bear with me.

Stock Management in Magento 2 is usually not that difficult before they deprecated the StockRegistryInterface.

This post explains how to get the saleable quantity of a product in Magento 2.

To get this you need product SKU (Stock Keeping unit) and website code of the website you need the saleable quantity for. So now lets get down to code.

First inject the Magento\InventorySalesApi\Api\StockResolverInterface and Magento\InventorySalesApi\Api\GetProductSalableQtyInterface into the constructor of the class.

public function __construct(
\Magento\InventorySalesApi\Api\StockResolverInterface $stockResolver,
   $this->stockResolver = $stockResolver;
   $this->getProductSaleableQty = $getProductSaleableQty;
Enter fullscreen mode Exit fullscreen mode

You have guessed it correctly, we are going to use GetProductSalableQtyInterface to get the saleable quantity of the product.

Then all that is left is to write the logic. You have to retrieve the stock ID of the stock that is appointed to the website. Then you have to pass the SKU and stock ID to get the saleable quantity. Here stock ID is important and to get that we need to use the StockResolverInterface. These terminologies come from MSI feature of Magento.

public function getProductSaleableQty($productSku, $websiteCode){
   $stockId = $this->stockResolver->execute(SalesChannelInterface::TYPE_WEBSITE, $websiteCode)->getStockId();
      $qty = $this->getProductSalableQty->execute($productSku, $stockId);
   } catch(Exception $exception){
      $qty = 0;
   return $qty;
Enter fullscreen mode Exit fullscreen mode

Here SalesChannelInterface is from Magento\InventorySalesApi\Api\Data\SalesChannelInterface.

Just by this stock ID you can get the following details related to stock in Magento 2:

  1. Retrieve sources related to current stock ordered by priority. - GetSourcesAssignedToStockOrderedByPriorityInterface
  2. Use it in StockRepositoryInterface to get the details of the stock.
  3. Check if product is assigned to stock - IsProductAssignedToStockInterface
  4. Check whether products are saleable for given stock - AreProductsSalableInterface.
  5. Check whether a given products quantities are saleable for a given stock. Meaning, whether you can sell specific quantity of a product in your website - AreProductsSalableForRequestedQtyInterface

Hope this helps for someone.

Discussion (0)