Limit discount

ME2
Shopify Partner
16 1 4

I've got a discount script which applies a discount if a product has a certain tag and another specific product is in the cart. This is my code:

products_needed = [1574879461479,1574879461468]
products_seen = []

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  products_seen << product.id if products_needed.include?(product.id)
end

@percent = Decimal.new(50) / 100.0
Input.cart.line_items.each do |line_item|
product = line_item.variant.product
next unless product.tags.include?('Giftset1-Item')
line_discount = line_item.line_price * @percent
line_item.change_line_price(line_item.line_price - line_discount, message: "bundle")if products_seen.uniq.sort == products_needed.uniq.sort
end

Output.cart = Input.cart

This works well. However, I need to limit the discount to two products, so if a third item is added with the same tag, it shouldn't discount the last item. Any ideas on how to do this?

0 Likes
ME2
Shopify Partner
16 1 4

Got it working like this in case it helps somebody else:

products_needed = [1574879461479,1574879461468]
products_seen = []
discounted_products_count = 0
@percent = Decimal.new(50) / 100.0


Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  products_seen << product.id if products_needed.include?(product.id)
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next unless product.tags.include?('Giftset1-Item')

  if products_seen.uniq.sort == products_needed.uniq.sort and discounted_products_count < 3
    line_discount = line_item.line_price * @percent
    line_item.change_line_price(line_item.line_price - line_discount, message: "bundle")
    discounted_products_count += 1
  end
end


Output.cart = Input.cart

 

0 Likes