Magento 2 collect total adds or deducts the value twice

Magento 2 collect total adds or deducts the value twice

Magento 2 collect total with custom total value gets added or deducted twice
Today we are going to talk about how to stop Magento 2 adding same discount or additional fee twice. We had the similar requirement for our VAT exemption and Surcharge extensions where we wanted to deduct VAT when customer opted in for VAT exemption and charge additional fee when customer pays using specific payment or shipping method respectively.

Magento 2 Collect Total

As you might already now that you have two main functions for collect totals. collect and fetch

For collect function, you just need to make sure you add the following piece of code so that it doesn’t run the same function multiple times -:

 /** * @param Quote $quote * @param ShippingAssignmentInterface $shippingAssignment * @param Total $total * @return $this|bool */ public function collect( Quote $quote, ShippingAssignmentInterface $shippingAssignment, Total $total ) { parent::collect($quote, $shippingAssignment, $total); //code to make sure we don't double deduct or add our value $address = $shippingAssignment->getShipping()->getAddress(); $items = $this->_getAddressItems($address); if (!count($items)) { return $this; } $valueToBeUpdated = $value; $total->setTotalAmount('custom_code', $valueToBeUpdated); $total->setBaseTotalAmount('custom_code', $valueToBeUpdated); return $this; } 

The following piece of code from above code snippet will take care of not adding or deducting value twice

 $address = $shippingAssignment->getShipping()->getAddress(); $items = $this->_getAddressItems($address); if (!count($items)) { return $this; }

We have also noticed quite few developers try to manually calculate total, grand total and other values during the collect total function. Please note there is no need to do do any other calculation other than related to your custom total in the collect function as shown above. Magento will do all the calculation for you automatically to give you running total and grand total.

Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Discover more from WHO WILL CARE eCommerce

Subscribe now to keep reading and get access to the full archive.

Continue reading