How to apply Magento 2 custom discount with tax, we will find out in this dev doc article.
So when you add a custom discount it will not work with tax. But before that, you can also learn about how to add custom discount in Magento 2.
First, we need to confirm the configurations for Tax in Magento 2 Admin Configuration.
Log in to Admin Backend> Stores> Configurations> Sales> Tax.
Tax Calculation Method Based On should be on Total.
Now, get back to our code. Please make sure your totals calculates before calculating tax in Magento 2. You can do this by managing sort_order in your sales.xml file for tax the sort_order is 450 you can define less than 450 see the code snippet below:
<section name="quote"> <group name="totals"> <item name="customdiscount" instance="companyname\module\Model\Quote\Address\Total\CustomDiscount" sort_order="440"/> </group> </section>
Now, Please make changes to your CustomDiscount.php file.
namespace companyname\module\Model\Quote\Address\Total; class CustomDiscount extends \Magento\Quote\Model\Quote\Address\Total\AbstractTotal { /** * @var \Magento\Framework\Pricing\PriceCurrencyInterface */ protected $_priceCurrency; /** * @param \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency [description] */ public function __construct( \Magento\Framework\Pricing\PriceCurrencyInterface $priceCurrency ) { $this->_priceCurrency = $priceCurrency; } 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); $customDiscount = -10; $items = $shippingAssignment->getItems(); foreach ($items as $item) { // in case of configurable product. if ($item->getPrice() <= 0) { continue; } $item->setCalculationPrice($item->getCalculationPrice() - $customDiscount); $item->setBaseCalculationPrice($item->getBaseCalculationPrice() - $customDiscount); } $total->addTotalAmount('customdiscount', $customDiscount); $total->addBaseTotalAmount('customdiscount', $customDiscount); $quote->setCustomDiscount($customDiscount); } return $this; } /** * Assign subtotal amount and label to address object * * @param \Magento\Quote\Model\Quote $quote * @param Address\Total $total * @return array * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function fetch(\Magento\Quote\Model\Quote $quote, \Magento\Quote\Model\Quote\Address\Total $total) { return [ 'code' => 'Custom_Discount', 'title' => $this->getLabel(), 'value' => 10 ]; } /** * get label * @return string */ public function getLabel() { return __('Custom Discount'); } }
That’s it for this dev doc on Magento 2 Custom Discount with Tax. Hope!! It will help you. Please reach out to our team via a support ticket if you have any queries. Happy Coding …:)
You may also check our wide range of Best Magento 2 extensions including coupon builder, coupon listing, product bundle and many more.
Be the first to comment.