Magento – n event or plugin spot for when cart rule is no longer valid

event-observermagento2pluginsales-quoteshopping-cart-price-rules

Is there an event or place I can plugin for when a shopping cart price rule is no longer valid (such as when it expires or if you change the quantity of other products where it no longer applies)? I know that it is automatically removed from the cart, but I can't seem to find the place this is happening in the code.

I am writing a module that adds a free product to the cart for a coupon where the subtotal is more than X amount. It is all working except for when reducing the quantity of items in the cart where the subtotal goes below X. The coupon is getting removed, but my product is staying in the cart.

So far I've tapped into the following events to do what I need so far…

salesrule_validator_process
checkout_cart_update_items_after
sales_quote_collect_totals_before

I did find Magento\Quote\Model\CouponManagement which seemed promising since it has set() and remove() methods, but they don't appear to be getting called when the cart is updated.

In the checkout_cart_update_items_after it also seems like a logical place I can check, but it appears the rule is still set according to $cart->getQuote()->getAppliedRuleIds()


UPDATE: I ended up adding an observer for the checkout_cart_save_after event which runs after collectTotals() so knows if the rule is still on the cart or not. Then I basically compare $quote->getAppliedRuleIds() with $quote->getOrigData('applied_rule_ids') to see if the rule has been removed. I feel like there is a better way to do this, but it works for the moment. I still have the issue with coupons that expire though…

Best Answer

I would try to write an around plugin on the function \Magento\SalesRule\Model\Quote\Discount::collect

When the coupon is already set and the total in the cart do show discount amount and the coupon code, it is the totals that drive the content of the cart sidebar.

In this function, the discount description is reset (line 92) and then the discount total is evaluated after this.

We can see clearly the total eventually are update with a discountAmount and a discountDescription.. These 2 are perfect contender for you to trigger you logic that remove your product?

Related Topic