Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento 2, Magento Development, Customization, Extension Development and Integration, Optimization, SEO and Responsive Design

Magento Add Discount To Product Programmatically

Using this post you can add custom discount to your magento cart total. You can also add discount to cheapest item in cart. Like there are 5 items in your cart and you want to add 30% discount to cheapest item this post will help you. Create new module with following files in your magento. Let's see step by step how this will work.

Download Module

1. Directories and files needed for the module

app/code/local/HK/Customdiscount
app/code/local/HK/Customdiscount/etc
app/code/local/HK/Customdiscount/etc/config.xml
app/code/local/HK/Customdiscount/Model
app/code/local/HK/Customdiscount/Model/Observer.php
app/etc/modules/HK_Customdiscount.xml


2. Content of HK_Customdiscount.xml

<?xml version="1.0"?>
<config>
    <modules>
        <HK_Customdiscount>
            <active>true</active>
            <codePool>local</codePool>
        </HK_Customdiscount>
    </modules>
</config>


3. etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <HK_Customdiscount>
            <version>0.1.0</version>
        </HK_Customdiscount>
    </modules>
    
    <global>
        <events>
            <sales_quote_collect_totals_after>
                <observers>
                    <set_custom_discount>
                        <type>singleton</type>
                        <class>HK_Customdiscount_Model_Observer</class>
                        <method>setDiscount</method>
                    </set_custom_discount>
                </observers>
            </sales_quote_collect_totals_after>
        </events>
    </global>
</config>


4. Model/Observer.php

<?php
class HK_Customdiscount_Model_Observer extends Varien_Object
{
    public function setDiscount($observer)
    {
       $priceArray;
       
       $quote = $observer->getEvent()->getQuote();
       
       /*Enable this code for 30% on cheapest product*/
        /*foreach ($quote->getAllVisibleItems() as $item) {
            $_incl = Mage::helper('checkout')->getPriceInclTax($item);
            $itmQty = $item->getQty()>1?$item->getQty():1;
            for($cnt=1; $cnt <= $itmQty; $cnt++){
                if (Mage::helper('weee')->typeOfDisplay($item, array(0, 1, 4), 'sales') && $item->getWeeeTaxAppliedAmount()){
                    $priceArray[] = $_incl + Mage::helper('weee')->getWeeeTaxInclTax($item);
                }else{
                    $priceArray[] = $_incl-$item->getWeeeTaxDisposition();
                }
            }
        }

        $percentage = 30;
        $discountAmount = ($percentage / 100) * min($priceArray);*/
        
        $discountAmount = 30;
        $quoteid=$quote->getId();           
        if($quoteid) {
            if($discountAmount>0) {
                $total=$quote->getBaseSubtotal();
                $quote->setSubtotal(0);
                $quote->setBaseSubtotal(0);

                $quote->setSubtotalWithDiscount(0);
                $quote->setBaseSubtotalWithDiscount(0);

                $quote->setGrandTotal(0);
                $quote->setBaseGrandTotal(0);

                $canAddItems = $quote->isVirtual()? ('billing') : ('shipping'); 
                foreach ($quote->getAllAddresses() as $address) {
                    $address->setSubtotal(0);
                    $address->setBaseSubtotal(0);

                    $address->setGrandTotal(0);
                    $address->setBaseGrandTotal(0);

                    $address->collectTotals();

                    $quote->setSubtotal((float) $quote->getSubtotal() + $address->getSubtotal());
                    $quote->setBaseSubtotal((float) $quote->getBaseSubtotal() + $address->getBaseSubtotal());

                    $quote->setSubtotalWithDiscount(
                        (float) $quote->getSubtotalWithDiscount() + $address->getSubtotalWithDiscount()
                    );
                    $quote->setBaseSubtotalWithDiscount(
                        (float) $quote->getBaseSubtotalWithDiscount() + $address->getBaseSubtotalWithDiscount()
                    );

                    $quote->setGrandTotal((float) $quote->getGrandTotal() + $address->getGrandTotal());
                    $quote->setBaseGrandTotal((float) $quote->getBaseGrandTotal() + $address->getBaseGrandTotal());

                    $quote ->save(); 

                    $quote->setGrandTotal($quote->getBaseSubtotal()-$discountAmount)
                    ->setBaseGrandTotal($quote->getBaseSubtotal()-$discountAmount)
                    ->setSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
                    ->setBaseSubtotalWithDiscount($quote->getBaseSubtotal()-$discountAmount)
                    ->save(); 


                    if($address->getAddressType()==$canAddItems) {
                    //echo $address->setDiscountAmount; exit;
                     $address->setSubtotalWithDiscount((float) $address->getSubtotalWithDiscount()-$discountAmount);
                     $address->setGrandTotal((float) $address->getGrandTotal()-$discountAmount);
                     $address->setBaseSubtotalWithDiscount((float) $address->getBaseSubtotalWithDiscount()-$discountAmount);
                     $address->setBaseGrandTotal((float) $address->getBaseGrandTotal()-$discountAmount);
                     if($address->getDiscountDescription()){
                     $address->setDiscountAmount(-($address->getDiscountAmount()-$discountAmount));
                     $address->setDiscountDescription($address->getDiscountDescription().', Custom Discount');
                     $address->setBaseDiscountAmount(-($address->getBaseDiscountAmount()-$discountAmount));
                     }else {
                     $address->setDiscountAmount(-($discountAmount));
                     $address->setDiscountDescription('Custom Discount');
                     $address->setBaseDiscountAmount(-($discountAmount));
                     }
                     $address->save();
                    }//end: if
               } //end: foreach
               //echo $quote->getGrandTotal();
                foreach($quote->getAllItems() as $item){
                 //We apply discount amount based on the ratio between the GrandTotal and the RowTotal
                 $rat=$item->getPriceInclTax()/$total;
                 $ratdisc=$discountAmount*$rat;
                 $item->setDiscountAmount(($item->getDiscountAmount()+$ratdisc) * $item->getQty());
                 $item->setBaseDiscountAmount(($item->getBaseDiscountAmount()+$ratdisc) * $item->getQty())->save();

               }    
            }
        }
    }
}


That's it. Hope you are enjoying this post.

Please support us, Like us on Facebook.

  1. Thank you so so much for your module
    I would like to have this custom discount on all the products in checkout besides the ones belonging to category id 7 how could i do it?

    ReplyDelete

 

Copyright @ 2017 HKBlog.