Skip to content

Instantly share code, notes, and snippets.

@maxkostinevich
Created June 7, 2018 07:30
Show Gist options
  • Save maxkostinevich/10cf6dd269abf356dc7a9e50ae049768 to your computer and use it in GitHub Desktop.
Save maxkostinevich/10cf6dd269abf356dc7a9e50ae049768 to your computer and use it in GitHub Desktop.
Shopify Script #5 - Buy anything from collection A and get anything from collection B with X% discount
# Buy anything from collection A and get anything from collection B with X% discount,
# if discount code XYZ is applied
# Custom Message
CHECKOUT_MESSAGE = "Get a 50% off"
# Discount code which should me appled
DISCOUNT_CODE = "GET50OFF"
COLLECTION_A = ["BACKPACKS"]
COLLECTION_B = ["SHIRTS"]
# DISCOUNT VALUE (WITHOUT "%")
DISCOUNT_VALUE = 50
# === Do not change anything below ===
cart = Input.cart
discounted_items_qty = 0
discount_percent = Decimal.new(DISCOUNT_VALUE) / 100.0
# Calculate eligible discounted items (X <= ITEMS FROM A COLLECTION)
cart.line_items.each do |line_item|
product = line_item.variant.product
if COLLECTION_A.collect{|el| el.downcase }.include?(product.product_type.downcase)
discounted_items_qty += line_item.quantity
end
end
subtotal = cart.subtotal_price_was
is_free_item_applied = false
if cart.discount_code
if cart.discount_code.code == DISCOUNT_CODE
cart.line_items.each do |line_item|
product = line_item.variant.product
if COLLECTION_B.collect{|el| el.downcase }.include?(product.product_type.downcase) and
discounted_items_qty > 0
if(discounted_items_qty < line_item.quantity)
free_item = line_item.split(take: discounted_items_qty)
cart.line_items.push(free_item)
else
free_item = line_item
end
new_price = line_item.line_price - (line_item.line_price * discount_percent)
free_item.change_line_price(new_price, message: CHECKOUT_MESSAGE)
discounted_items_qty -= free_item.quantity
end
end
end
end
Output.cart = Input.cart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment