Magento – Magento 2 : How to Set custom Discount from controller

discountmagento2

I am developing a module which set discount to total, Whenever customer will press Get Discount.

I can able to reduce Subtotal and GrandTotal in customer quote, Also my quote table is getting updated.

Check my controller below.

public function execute()
{
        echo "<pre>";
    
        $label          = 'My Custom Discount';
        $discountAmount = 10;              
        
        $quoteSession = $this->salesQuote->getQuote()->getData();
        $quoteId = $quoteSession['entity_id'];
        
        $quote = $this->quoteFactory->create()->load($quoteId);
       // print_r($quote->getData()); exit;
       
       
         $quote->setSubtotal($quote->getSubtotal() - $discountAmount);
       $quote->setBaseSubtotal($quote->getBaseSubtotal() - $discountAmount);
       
       $quote->setSubtotalWithDiscount($quote->getSubtotalWithDiscount() - $discountAmount);
       $quote->setBaseSubtotalWithDiscount($quote->getBaseSubtotalWithDiscount() - $discountAmount);
       
       $quote->setGrandTotal(30);
       $quote->setBaseGrandTotal(30);
       
       $quote->save();

But how can I render my Updated Grand Total at Cart Page as well as other further steps like checkout, Invoice, etc etc?

I am stuck here, No idea what is next step !!

Any help would be really great.

Best Answer

First, create new file sales.xml inside etc folder with the following code:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
    <section name="quote">
        <group name="totals">
            <item name="affiliate_discount" instance="Vendor\Module\Model\Total\Quote\CustomTotal" sort_order="420"/>
        </group>
    </section>
</config>

Next, create the file Vendor\Module\Model\Total\Quote\CustomTotal.php with the code below:

<?php
namespace Vendor\Module\Model\Total\Quote;
use Magento\SalesRule\Model\Rule;

class CustomTotal extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal
{
    /**
     * @param \Magento\Quote\Model\Quote $quote
     * @param \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment
     * @param \Magento\Quote\Model\Quote\Address\Total $total
     * @return $this|bool
     */
    public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    )
    {
        parent::collect($quote, $shippingAssignment, $total);
        //Set your custom total here!
        $total->addTotalAmount();
        $total->addBaseTotalAmount();
        $total->setBaseGrandTotal();
        return $this;
    }

}

Hope it help!

Related Topic