0

I need to show all cart/order discounts in the following manner:

Subtotal                              ----------- 100.00

CHRISTMAS10 (Christmas Sale 10 % off) ----------- -10.00
CHDLL1242DK (Coupon Redeemed)         ----------- -20.00

Grand Total                           -----------  70.00

Magento 2 store only the coupon_code and the applied_rule_ids, but not the discount amount for specific rule and discount description.

What would the best way to achieve this? (also if there is any module available, please suggest)

1

You can achieve this by using below code:

namespace Vendor\ModuleName\Controller\Index;

use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;
use Magento\SalesRule\Model\RuleFactory;

class YOURClass extends \Magento\Framework\App\Action\Action
{
     /**
     * @var OrderCollection
     */
    private $orderCollection;
    /**
     * @var RuleFactory
     */
    private $rule;

    public function __construct(
        Context $context,
        CollectionFactory $orderCollection,
        RuleFactory $rule,
        \Psr\Log\LoggerInterface $logger
    )
    {
        parent::__construct($context);
        $this->orderCollection = $orderCollection;
        $this->rule = $rule;
        $this->logger = $logger;
    }


    public function execute()
    {
        $collection = $this->orderCollection->create()
            ->addAttributeToSelect('*')
            ->addFieldToFilter('increment_id', '000000005');

        foreach ($collection->getItems() as $order) {

            foreach($order->getAllItems() as $item) {

                $appliedRule = $item->getAppliedRuleIds();

                if (!empty($appliedRule)) {

                    $appliedRuleArr = explode(",", $appliedRule);

                    foreach ($appliedRuleArr as $ruleId) {

                        $couponCodeData  = $this->rule->create()->load($ruleId);

                        $this->logger->log('600', print_r($couponCodeData->getData(), true));

                    }

                }

            }

        }

    }

}
| improve this answer | |
  • Did the above code work for you? – Bushra Aug 15 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.