Bundle discount quantity limit

Highlighted
Shopify Partner
16 1 2
products_needed = [1574877593703]
products_seen = []
discounted_products_count = 0
discounted_bundle_count = 0
@percent = Decimal.new(100) / 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-Main')
    product2 = line_item.quantity
    discounted_bundle_count += product2
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  product2 = line_item
  next unless product.tags.include?('Giftset1-Item')
  if discounted_bundle_count == 1
  if products_seen.uniq.sort == products_needed.uniq.sort and discounted_products_count < 2  
    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 
end
Output.cart = Input.cart

I've written a discount for a bundled product using product tags. So if a certain product is in the cart and 2 products with a specific tag are added to the cart, those two add on items are discounted/ for free.

Now my issue is that with this, if somebody adds multiple of one add on item, it discounts all of them. So if somebody adds 3 x Add on 1 and 1x Add on 2, the 3 Add on 1s are all discounted, but it should only discount one of them.

So I've tried spliiting the item if the quantity is more than 1. 

      if line_item.quantity > 1

         discounted_item = line_item.split(take: 1)

        discounted_item.change_line_price(discounted_item.line_price - line_discount, message: "bundle")

       else

    line_item.change_line_price(line_item.line_price - line_discount, message: "bundle")

end

However, with this it seems to take on of the 3 out of the card, so it shows only a quantity of 2, and also none of them are discounted. Any ideas how to do this right?

 

0 Likes
Highlighted
Shopify Partner
132 1 18

Hi There,

Just make sure you're reinserting the item back into the cart. The example given in the documentation is

if original_line_item.quantity >= 3
  new_line_item = original_line_item.split(take: 1)
  new_line_item.change_line_price(Money.new(cents: 500), message: "Third hat for 5 dollars")
  cart.line_items << new_line_item
end

note the line before the 'end' that reinserts the item.

More information can be found at https://help.shopify.com/en/manual/apps/apps-by-shopify/script-editor/shopify-scripts#split-example

Cheers,

Elliott

Feeling a bit lost? Contact elliot@mandelbrotian.com for help with theme setup, alterations, custom functionality, and app development.
0 Likes