Have your say in Community Polls: What was/is your greatest motivation to start your own business?

How can I set free gift products to zero and reject discount codes in my cart?

Solved

How can I set free gift products to zero and reject discount codes in my cart?

eballeste1
Excursionist
23 4 17

Im trying to flag certain products as a gift depending on certain situations and want my script to set its price to 0 while also preventing the usage of discount codes if the cart has this gift. I have the following script setup based on disparate codes I have found but for some reason, only the discount rejection is called once I reach the checkout page.

 

 

cart_has_gift = false

Input.cart.line_items.each do |line_item|
  is_gift = line_item.properties["_isGift"]
  if is_gift
    cart_has_deal = true
    item_message = "Gift with Purchase"
    line_item.change_line_price(Money.zero, message: item_message)
  end
end

if cart_has_gift
  Input.cart.discount_code.reject(
    message: "Offers cannot be combined with discount codes."
  )
end

Output.cart = Input.cart

 

 

If I run it without the second conditional, call to discount_code.reject, the product price is set to 0 with the correct gift message showing up.

I have almost no knowledge of Ruby but not sure if this is a Ruby thing or some type of script limitation. Could someone point me in the right direction?

Accepted Solution (1)

eballeste1
Excursionist
23 4 17

This is an accepted solution.

This seemed to work although I have no idea why or how (hopefully someone can explain) but it's working:

cart_has_gift = false

Input.cart.line_items.each do |line_item|
  is_gift = line_item.properties["_isGift"]
  if is_gift
    cart_has_deal = true
    item_message = "Gift with Purchase"
    line_item.change_line_price(Money.zero, message: item_message)
  end
end

# added an additional check in this conditional
if cart_has_gift and Input.cart.discount_code
  Input.cart.discount_code.reject(
    message: "Offers cannot be combined with discount codes."
  )
end

Output.cart = Input.cart

View solution in original post

Replies 2 (2)

eballeste1
Excursionist
23 4 17

This is an accepted solution.

This seemed to work although I have no idea why or how (hopefully someone can explain) but it's working:

cart_has_gift = false

Input.cart.line_items.each do |line_item|
  is_gift = line_item.properties["_isGift"]
  if is_gift
    cart_has_deal = true
    item_message = "Gift with Purchase"
    line_item.change_line_price(Money.zero, message: item_message)
  end
end

# added an additional check in this conditional
if cart_has_gift and Input.cart.discount_code
  Input.cart.discount_code.reject(
    message: "Offers cannot be combined with discount codes."
  )
end

Output.cart = Input.cart
alexsuarez
Shopify Partner
11 0 13

What will be the equavalent if you use shopify function discount product?