Skip to content

Display the coupon code on the product detail page Magento2.4

 <?php

use MagentoFrameworkApiSearchCriteriaBuilder;
use MagentoSalesRuleApiRuleRepositoryInterface;
use MagentoCatalogApiProductRepositoryInterface;
use MagentoFrameworkRegistry;

class CustomRule
{
    protected $ruleRepository;
    protected $searchCriteriaBuilder;
    protected $productRepository;
    protected $product;

    public function __construct(
        RuleRepositoryInterface $ruleRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        ProductRepositoryInterface $productRepository,
        Registry $registry
    ) {
        $this->ruleRepository = $ruleRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->productRepository = $productRepository;
        $this->product = $registry->registry('current_product');
    }

    /**
     * Ottieni l'oggetto RuleInterface dalle regole di sconto attive
     *
     * @return RuleInterface|null
     */
    public function getList()
    {
        // Costruisci il filtro per recuperare solo le regole attive
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter('is_active', 1)
            ->create();

        // Recupera le regole di sconto attive
        $rules = $this->ruleRepository->getList($searchCriteria)->getItems();

        // Ritorna l'ultimo oggetto RuleInterface
        return end($rules);
    }

    /**
     * Ottieni l'oggetto RuleInterface dalle regole di sconto attive
     *
     * @return RuleInterface|null
     */
    public function getCustomCouponCode()
    {
        $rule = $this->getList();
        if ($rule) {
            return $rule->getDescription();
        } else {
            return null;
        }
    }

    /**
     * Ottieni la percentuale di sconto applicata alla regola attiva
     *
     * @return float|null
     */
    public function getDiscountPercentage()
    {
        $rule = $this->getList();
        if ($rule) {
            return (float) $rule->getDiscountAmount();
        } else {
            return null;
        }
    }


    /**
     * Ottieni l'attributo "manufacturer" del prodotto corrente
     *
     * @return string|null
     */
    public function getProductManufacturer()
    {
        try {
            return $this->product ? $this->product->getAttributeText('manufacturer') : null;
        } catch (Exception $e) {
            return null;
        }
    }
}

I got the manufacturer attribute from the current product and I need to filter my getlist() and search the manufacturer attribute in action for the conditions for which the coupon works what should I do?enter code here