A product is salable or not is determined based on below logic:
- Product should be enabled.
- Product should be marked in-stock.
- qty -(minus) sum of reserved quantity in
inventory_reservation
table should be greater than 0. This is a important check. A product might have main quantity (qty), still it might not be salable.
Requirement: I have an array of configurable product skus and want to check if they are salable. To check a config is salable, assigned simple product should also be checked if they are salable.
<?php
namespace Algolia\CustomAlgolia\Observer;
use Magento\ConfigurableProduct\Api\LinkManagementInterface;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
class ExcludeNotSalableProducts implements ObserverInterface
{
/**
* @var IsProductSalableInterface
*/
private $isProductSalable;
/**
* @var LinkManagementInterface
*/
private $linkManagement;
/**
* @var ProductRepositoryInterface
*/
private $productRepository;
/**
* ExcludeNotSalableProducts constructor.
* @param IsProductSalableInterface $isProductSalable
* @param LinkManagementInterface $linkManagement
* @param ProductRepositoryInterface $productRepository
*/
public function __construct(
LinkManagementInterface $linkManagement,
ProductRepositoryInterface $productRepository
)
{
$this->linkManagement = $linkManagement;
$this->productRepository = $productRepository;
}
/**
* @inheritDoc
*/
public function execute(Observer $observer)
{
$startTime = microtime(true);
$configSkus = ['1001', '1002']; // sku of config products
$parentSkusToExclude = [];
foreach ($configSkus as $configSku) {
echo $configSku . PHP_EOL;
$excludeParent = true;
try {
$childProducts = $this->linkManagement->getChildren($configSku);
foreach ($childProducts as $product) {
$isSalable = $this->productRepository->get($product->getSku())->isSalable();
if ($isSalable) {
$excludeParent = false;
break;
}
}
} catch (\Exception $exception) {
}
if ($excludeParent) {
$parentSkusToExclude[] = $configSku;
}
}
var_dump("done");
var_dump($parentSkusToExclude);
$endTime = microtime(true);
echo 'took ' . ($endTime - $startTime) . ' seconds';
exit;
}
}
Above code takes around 50 second for 100 config products in my local system.
Question: What is the fastest way to determine if a config sku is salable?