Calculate tax programmatically in magento for some customers
-
13-12-2019 - |
Question
my products price are inclusive of 12.5% tax so if my customer has tax excempt then he should not pay 12.5% instead he should pay 2%.
tax excempt:- if my customer produce c form then he is applicable for 2% instead of 12.5%.
Here is my code
i have observer called sales_quote_collect_totals_before
if($customer->getIsTaxExempt() == 1)
{
$items = $observer->getEvent()->getQuote()->getAllVisibleItems();
foreach($items as $item){
$item->getProduct()->setTaxClassId(0); // set product tax class to none
$basePrice = $item->getProduct()->getFinalPrice() / (1+(12.5/100)); // $basePrice is my price exlucive of 12.5%
// here i want $basePrice + 2% of the $basePrice as my finalproduct price inclu of tax
$item->getProduct()->setTaxClassId(12); // set product tax class to 2%
}
}
but this is not working.prices are not changing in the cart.
Note: My code is going into if statement required customers.
Solution
I had done this with myself by adding custom logic in the sales_quote_collect_totals_before observer
public function newTax($observer){
$quote = $observer->getQuote();
foreach ($quote->getAllItems() as $quoteItem) {
if ($quote->getData('customer_cform') === 'true') { // check if customer is b2b customer and selects for the cform option
$product = $quoteItem->getProduct();
$product->setTaxClassId(0); // tax class removed.now the price is with no tax
$basePrice = $product->getFinalPrice() / (1+(12.5/100)); // calcuated 12.5 % of total price and subtracted from the price to get base price
$final_cst_price = $basePrice * (2/100); // added 2% in the base price to get fincal cst price
$finalPrice = $basePrice + $final_cst_price;
$product->setPrice($basePrice);
$product->setTaxClassId(8); // here 8 is a tax rule defined in the magento admin just to show the split of base price and tax (2%) in the cart page and checkout page
}
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange