I need to reject a discount but I'd also like to apply only to certain product the discounted amount.
As an example: my cart is A,B and I have a order discount of 10%. I don't want product B to be discounted, but I want to discount only A. My approach was this
if cart.discount_code&.percentage
discount = cart.discount_code.percentage / 100.0
discount = 1.0 - discount.to_s.to_f # there's probably a better way to do this... but :)
cart.line_items.each do |line_item|
line_item.change_line_price(line_item.line_price * discount, message: "Applying discount code: " + cart.discount_code.code)
end
cart.discount_code.reject(message: "The discount cannot be applied.")
end
Note that this works on the input test.
The problem is that (from what I've empirically discovered) Shopify removes the discount once it has been rejected. Even though the API offers a rejected?
method. And because removing a discount triggers again the script the second time the if is skipped, because there is no discount anymore.
I have tried to save the discount value in the properties but they are discarded on the next run. There is no way to pass information from one run of the script to the other.
Is it possible to know the discount percentage of a rejected discount?
I don't think you need to reject the discount code at all. You can simply add a condition that controls when the discount is applied, for example:
This way you are avoiding hackish solutions. Instead of checking for skus you can check for tags, title, and so on. The full list can be found here: https://help.shopify.com/en/manual/checkout-settings/script-editor/shopify-scripts#variant
You can also create a null variable, run some for loops in advance and set true/false flag to that variable and use it in your if condition. Either way, the direction of rejection is the wrong way and personally, I have used it only once to prevent customers from abusing a very complex campaign (which was an exception).