Skip to content

Tax calculation after discount

So I have a custom discount applied the following way:

on vendormoduleetcsales.xml

<?xml version="1.0"?>
<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="testdiscount" instance="vendormoduleModelQuoteDiscount" sort_order="500"/>
        </group>
    </section>
</config>

On my vendormoduleModelQuoteDiscount.php

class Discount extends MagentoQuoteModelQuoteAddressTotalAbstractTotal
{
    public function __construct(
        MagentoFrameworkEventManagerInterface $eventManager,
        MagentoStoreModelStoreManagerInterface $storeManager,
        MagentoSalesRuleModelValidator $validator,
        MagentoFrameworkPricingPriceCurrencyInterface $priceCurrency
    ) 
    {
        $this->setCode('testdiscount');
        $this->eventManager  = $eventManager;
        $this->calculator    = $validator;
        $this->storeManager  = $storeManager;
        $this->priceCurrency = $priceCurrency;
    }

    public function collect(
        MagentoQuoteModelQuote $quote,
        MagentoQuoteApiDataShippingAssignmentInterface $shippingAssignment,
        MagentoQuoteModelQuoteAddressTotal $total
    )
    {

    parent::collect($quote, $shippingAssignment, $total);

    $totalDiscount = //Get discount here
    if($totalDiscount > 0)
    {  
        $total->setDiscountAmount(          - $totalDiscount);
        $total->setBaseDiscountAmount(      - $totalDiscount);
        $total->setSubtotalWithDiscount($total->getSubtotal()         - $totalDiscount);
        $total->setBaseSubtotalWithDiscount($total->getBaseSubtotal() - $totalDiscount);

        $total->addTotalAmount($this->getCode(),     - $totalDiscount);
        $total->addBaseTotalAmount($this->getCode(), - $totalDiscount);

    }

    return $this;

    }
}

My problem is that the taxes are being calculated using the total cart value without the discount applied. Any help on how to make the tax prices being applied to the total price including the discount?