Check if Cart Price Rule is Active for Product in Magento 2

magento2productshopping-cart-price-rules

I am exploring the possibilities to show active Cart Price rules on a product page. For example, if I have a blue shirt in the category 'shirts' and I create a Cart Price rule for 20% discount on the category 'shirts', is it possible to check this for a product?

I'm trying to fetch all active cart price rules for a product. In the example of the shirt, I want to show 'Get 20% discount on all shirts' on that specific product page.

I explored the sales-rule module but did not find a possible solution. It should be possible right?

Best Answer

I got this fixed by using: \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collection.

I retrieve all rules with:

$rules = $this->collection->create();

You could also filter this collection on Website and store filter.

After you retrieve the collection you can loop through all rules and check if you could apply the rule for the current product:

$product->setProductId($product->getId());

    /** @var \Magento\SalesRule\Model\Rule $rule */
    foreach ($rules as $rule) {
        try {
            if ($rule->getActions()->validate($product)) {
                $activeRules[] = $rule;
            }
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            continue;
        }
    }
Related Topic