I needed product's stock status in the product listing API:
V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=144
So I made a plugin as follows:
<?php
namespace Vendor\StockInfoAPI\Plugin;
use Magento\Catalog\Api\Data\ProductInterface;
class ProductGet{
protected $productExtensionFactory;
protected $productFactory;
public function __construct(
\Magento\Catalog\Api\Data\ProductExtensionFactory $productExtensionFactory,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\CatalogInventory\Api\StockStateInterface $stockItem,
\Psr\Log\LoggerInterface $logger,
\Magento\Store\Model\StoreManagerInterface $storeManager,
\Magento\Catalog\Api\Data\ProductAttributeMediaGalleryEntryInterface $mediaGallery,
\Magento\Eav\Model\Config $eavConfig
)
{
$this->productFactory = $productFactory;
$this->storeManager = $storeManager;
$this->logger = $logger;
$this->stockItem = $stockItem;
$this->productExtensionFactory = $productExtensionFactory;
$this->eavConfig = $eavConfig;
$this->mediaGallery = $mediaGallery;
}
public function afterGet(
\Magento\Catalog\Api\ProductRepositoryInterface $subject,
\Magento\Catalog\Api\Data\ProductInterface $product){
$product = $this->getExtensionAttributesItem($product);
return $product;
}
protected function getExtensionAttributesItem(\Magento\Catalog\Api\Data\ProductInterface $product)
{
$imageUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
if($product->getImage()){
$product->setCustomAttribute("image", $product->getImage());
}
if (!$product->isSaleable()){
$qty = "Out of Stock";
}
else{
$qty = "In-Stock";
}
$extensionattributes = $product->getExtensionAttributes();
$extensionattributes->setQty($qty);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\Product')->loadByAttribute('sku', $product->getSku());
$productPriceBySku = $productCollection->getPrice();
$extensionattributes->setPrice($productPriceBySku);
$product->setExtensionAttributes($extensionattributes);
return $product;
}
/**
* @param \Magento\Catalog\Api\ProductRepositoryInterface $subject
* @param \Magento\Catalog\Model\ResourceModel\Product\Collection $products
* @return \Magento\Catalog\Model\ResourceModel\Product\Collection
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
public function afterGetList(
\Magento\Catalog\Api\ProductRepositoryInterface $subject,
$products
)
{
foreach ($products->getItems() as $product) {
$this->afterGet($subject, $product);
}
return $products;
}
}
As you can see, I am essentially using the same function for fetching the details in product listing API and the product detail API:
V1/products/:SKU
Now the problem is: for some products, I am getting wrong stock status in the listing API.
In the product detail it is working fine.
Any suggestions?