Discount Based on Cart Total AFTER Coupon is Applied

New Member
3 0 0

We are running a script to give a specific product for free based on the total amount in the cart. But it calculates the cart total before a coupon code is added. Is there a way to recheck if the total threshold has been met after a coupon has been added?

 

Our current script

FREEBIE_PRODUCT_ID = 1111111111
CART_TOTAL_FOR_DISCOUNT_APPLIED = Money.new(cents: 100) * 125
DISCOUNT_MESSAGE = "FREE Item Name When You Spend Over 125"

freebie_in_cart = false
cart_price_exceeds_discounted_freebie_amount = false
cost_of_freebie = Money.zero

# Test if the freebie is in the cart, also get its cost if it is so we can deduct from the cart total
Input.cart.line_items.select do |line_item|
  product = line_item.variant.product
  if product.id == FREEBIE_PRODUCT_ID
    freebie_in_cart = true
    cost_of_freebie = line_item.line_price
  end
end

# If the freebie exists in the cart, check the subtotal of the other items to see if the freebie should be discounted
if freebie_in_cart
  cart_subtotal_minus_freebie_cost = Input.cart.subtotal_price - cost_of_freebie
  if cart_subtotal_minus_freebie_cost >= CART_TOTAL_FOR_DISCOUNT_APPLIED
    cart_price_exceeds_discounted_freebie_amount = true
  end
end

# Only true if the freebie is in the cart
was_discount_applied = false
if cart_price_exceeds_discounted_freebie_amount
  Input.cart.line_items.each do |item|
    if item.variant.product.id == FREEBIE_PRODUCT_ID && was_discount_applied == false
      if item.quantity > 1
        new_line_item = item.split(take: 1)
        new_line_item.change_line_price(Money.zero, message: DISCOUNT_MESSAGE)
        Input.cart.line_items << new_line_item
        next
      else
        item.change_line_price(Money.zero, message: DISCOUNT_MESSAGE)
      end
    end
  end
end

Output.cart = Input.cart
0 Likes
Shopify Partner
1343 22 204

The .subtotal_price method on Cart object "Returns the subtotal price of the cart after line item discounts are applied but before discount codes are applied."

So in Scripts you do not know what is applied via a coupon.

 

You can hardcode the discount coupons values and make the math but this will be really maintainable can can be error prone

 

https://sections.design tips, tricks & Shopify sections
0 Likes