We are currently showing our available qty in stock on the frontend of each product using the following code:
<?php
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$StockState = $objectManager->get('\Magento\CatalogInventory\Api\StockStateInterface');
$qty = $StockState->getStockQty($_product->getId());
?>
But when we enable the new MSI feature in Magento 2 the above code always outputs 0. How are we able to show the total salable qty in the frontend of all inventory sources?
Edit:
I found out that when I enable the Default source and assign it to a product and give it for example 10pcs. The above code outputs 10, so the above code doesnt take all the inventory sources into count. It should show the total salable qty like its showing in the backend.
Edit 2:
Explanation with images.
With the above settings the above code outputs 10. It should output 25.
When Default Source is unassigned the above code outputs 0. It should output 15.
Best Answer
The definition of salable quantity includes the quantity minQty.
Nowadays MSI is the approach. So no other methods, shortcuts, objectmanagers or M1 flashback code. It all has to be an MSI approach that will be compatible with future versions of M2.
So, let's get into it:
This gets your stock id for your website. It might always be the same but you have to look it up.
If on the frontend you want to show a different message for an item on backorder then you can do this:
To determine if the product is in stock and on sale:
If you want to show what is low stock then you can get this from:
Combining these values to show stock availability:
This shows what is readily available with no wait on backorders and no low stock.
If you want to know what is in stock including low stock, change the above to:
To setup your class use the interfaces:
Then, for your constructor: