Question

I was trying to validate the cart rule using plugin, but not able to do this, here I am explaining my approach in form of code files, please let me know how to do this.

app\code\Vendor\Module\Plugin\Condition\Product.php

<?php

namespace Vendor\Module\Plugin\Condition;

use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Additional attr for validator.
 */
class Product
{
    /**
     * @var \Magento\Catalog\Api\ProductRepositoryInterface
     */
    private $productRepository;     

    private $stockItem;

    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\CatalogInventory\Api\StockStateInterface $stockItem
    ) {
        $this->productRepository = $productRepository;
        $this->stockItem = $stockItem;
    }

    /**
     * @param \Magento\Rule\Model\Condition\Product\AbstractProduct $subject
     * @param \Magento\Framework\Model\AbstractModel $object
     */
    public function beforeValidate(
        \Magento\Rule\Model\Condition\Product\AbstractProduct $subject,
        \Magento\Framework\Model\AbstractModel $object
    ) {
        if ($object->getProduct() instanceof \Magento\Catalog\Model\Product) {
            /** @var \Magento\Catalog\Model\Product $product */
            $product = $object->getProduct();
        } else {
            try {
                $product = $this->productRepository->getById($object->getProductId());
            } catch (NoSuchEntityException $e) {
                $product = null;
            }
        }

        $qty = $this->stockItem->getStockQty($product->getId(), $product->getStore()->getWebsiteId());

        $logger = \Magento\Framework\App\ObjectManager::getInstance()->get('\Psr\Log\LoggerInterface');
        $logger->debug($qty."<= plugin working =>".$product->getProductId());


        $object->setData('product_qty', $qty);
        //return parent::validate($object);
    }
}

di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">    
    <type name="Magento\SalesRule\Model\Rule\Condition\Product">
        <plugin name="Custom_Rules::Condition_Product" type="Vendor\Module\Plugin\Condition\Product" />
    </type>
</config>

My cart rule condition is as below:- enter image description here

If product qty condition is true then rule will apply for that product in cart.

Any help would be much appreciated.

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top