When you add custom discount it will not work with tax. In this article we are going to learn how can we calculate custom discount to tax. Here you can learn how can we add custom discount in Magento 2.
First, we need to confirm the configurations for Tax in Magento 2 Admin Configuration.
Login 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 should be calculate 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. Hope!! It will help you.
Please comment below if any queries.
Happy Coding …:)