Buy X quantity of a product, Get Y% off

Excursionist
46 0 7

I'm using the code below to create a quantity discount when a specific tag is applied to a product, and it works...

DISCOUNTS_BY_QUANTITY = {
  10_000 => 20,
  1_000 => 15,
  100 => 10,
  10 => 5,
}

Input.cart.line_items.each do |line_item|
  next if line_item.variant.product.gift_card?
  if line_item.variant.product.tags.include?('Tiered Pricing')

  quantity, discount = DISCOUNTS_BY_QUANTITY.find do |quantity, _|
    line_item.quantity >= quantity
  end
  next unless discount

  message = "Discount applied! #{discount}% off when buying at least #{quantity}."
  line_item.change_line_price(
    line_item.line_price * (Decimal.new(1) - discount.to_d / 100),
    message: message,
  )
end
end
Output.cart = Input.cart

My question is, how can I modifly the code to be able to do multiple discount groups using different tags? I tried something like this, but could not get it to work...

DISCOUNTS_BY_QUANTITY_GROUP_1 = {
  10_000 => 20,
  1_000 => 15,
  100 => 10,
  10 => 5,
}

DISCOUNTS_BY_QUANTITY_GROUP_2 = {
  200 => 20,
  90 => 15,
  10 => 8,
  5 => 3,
}

Input.cart.line_items.each do |line_item|
  next if line_item.variant.product.gift_card?
  if line_item.variant.product.tags.include?('Tiered Pricing 1')

  quantity, discount = DISCOUNTS_BY_QUANTITY_GROUP_1.find do |quantity, _|
    line_item.quantity >= quantity

  elsif line_item.variant.product.tags.include?('Tiered Pricing 2')

  quantity, discount = DISCOUNTS_BY_QUANTITY_GROUP_2.find do |quantity, _|
    line_item.quantity >= quantity
  end
  next unless discount

  message = "Discount applied! #{discount}% off when buying at least #{quantity}."
  line_item.change_line_price(
    line_item.line_price * (Decimal.new(1) - discount.to_d / 100),
    message: message,
  )
end
end
Output.cart = Input.cart

I'm obvioulsy not getting the syntax right somewhere, but I'm not sure how this should be constructed. Any help?

0 Likes