M1 - How to set different tax class IDs on different instances of the same product in a cart based on custom options

magento.stackexchange https://magento.stackexchange.com/questions/328735

Question

I'm using the latest version of Magento 1.9 and I'm stuck trying to make a change. I checked all the related questions and couldn't find a solution. I figured I should see if someone can help before I start diving deeper into the internals of the framework.

The problem

I have products defined with custom options. Depending on which custom options are selected, the products may or may not need to be zero-rated for tax purposes. This means that based on what custom options are selected, I may or may not have to charge the user tax.

What I have tried

I'm trying to achieve my goal by swapping the tax class ID on the products in the cart. The way I did this is by setting up an Observer on the 'sales_quote_collect_totals_before' event. Inside my observer, I'm doing the following:

$quote = $observer->getQuote();
$cartItems = $quote->getAllVisibleItems();

foreach ($cartItems as $item) {
        $product = $item->getProduct();
        $customOptions = $product->getCustomOptions();

        if (<nasty custom option condition here>) {
                $product->setTaxClassId(2);
        } else {
                $product->setTaxClassId(0);
        }
}

I'm 90% of the way there, but there's one last issue I haven't been able to solve and that is when a customer buys 2 of the same product ID but with different custom options where one would need tax class ID 2 and the other would need tax class ID 0, all products get whatever tax class ID was last set for that product in the loop. That is, it seems that even if I set different class IDs on the different instances of the same product, it just uses the last one set for the general product ID and disregards what was set on the different product instances in the cart.

Does anyone know how to deal with this so that if the same customer adds the same product to their cart with different custom options set I can charge tax on one but not the other?

Any guidance would be greatly appreciated.

Was it helpful?

Solution

I finally figured it out.

When you add an item to your cart it then directs you to /checkout/chart/ and it rebuilds the cart using a query to sales_flat_quote_item. If you have two products with the same product ID, each item in your quote actually will contain a reference to the same product object. This was confusing because when I first added my products to my cart with different custom options, the products were not all references to a single product object.

To solve this, when I iterate over the items in my observer I make clones of the product and assign the copies to each item instead of the same referenced one.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top