0
votes

I have created an order programatically in Magento 2. I am provided with data:

  • Item value: $10
  • Tax Rate: 20%
  • Discount: $2
  • Grand Total: $10

Now taxes are inclusive product prices, so by default in Magento 2:

  • Item price: $10
  • Item price after discount: $8
  • Tax: 20 % of $8 = $1.6
  • Grand Total : $8 + $1.6 = $9.6.

Grand total is not same as provided. I want to add discount after tax calculation.

2

2 Answers

2
votes

For Tax configuration, there are two ways to fix this. In backend configuration: Apply Customer Tax ->set 'Before Discount'; This should fix your problem I guess.

You can customize the code as well for same : In your di.xml, add as below:

<preference for="Magento\Tax\Model\Sales\Total\Quote\Tax" type="<yournamespace>\<yourModule>\Model\Sales\Total\Quote\Tax"/>

Now create your class file Tax.php and add below code:

namespace <yournamespace>\<yourModule>\Model\Sales\Total\Quote;

class Tax extends \Magento\Tax\Model\Sales\Total\Quote\Tax

{
    /* override code here */
    public function __construct(
        /* add dependency classes here */    ) {
        parent::__construct(
            /* parent class objects here */
        );
    }

    /**
    * Custom Collect tax totals for quote address
    *
    * @param Quote $quote
    * @param ShippingAssignmentInterface $shippingAssignment
    * @param Address\Total $total
    * @return $this
    */
    public function collect(
        \Magento\Quote\Model\Quote $quote,
        \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
        \Magento\Quote\Model\Quote\Address\Total $total
    ) {

       /* your calculation here goes here */
        $total->setTaxAmount($set_your_tax_here);

        return $this;
    }

}

Hope this helps!

0
votes

Yes you can.... You can use default FPT and can modify tax amount as per your need. you can use sales_quote_collect_totals_after event to change product tax amount programmatically.

This answer you can also try inside above overrided Tax model , it works fine.