Skip to content

Instantly share code, notes, and snippets.

@CodeBrotha
Created November 11, 2021 00:34
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CodeBrotha/c77fc4ff3cea20c26e136e3847cd0332 to your computer and use it in GitHub Desktop.
Save CodeBrotha/c77fc4ff3cea20c26e136e3847cd0332 to your computer and use it in GitHub Desktop.
Shopify Scripts - Line Item Properties Discount
Input.cart.line_items.each do |item|
# ================================================================
# LINE ITEM PROPERTY DISCOUNT
# ================================================================
# Set the line item property in Shopify theme When adding item to cart
#
# line item property is a key/value pair. Example: {"_someCoolPromo": "1"}
#
# In this example:
# "_someCoolPromo" is the key we look for here and must ALWAYS start with an underscore.
# "1" is the value and respresents a value of $1.00 ("1.25" for $1.25, "1.5" for $1.50 etc.)
#
# ================================================================
## Check if line item has the specific line item property and if so apply the relevant discount (if greater than sale discount)
if item.properties.has_key?("_lineItemPropertyKeyHere") && (item.properties["_lineItemPropertyKeyHere"].to_f > 0.00)
line_item_discount_value = Float(item.properties["_lineItemPropertyKeyHere"])
discount_amount = Money.new(cents: 100) * line_item_discount_value
discount_message = "Some Cool Promo"
## Check if line item is currently on sale and if so get the sale discount
if !item.variant.compare_at_price.nil? && item.variant.compare_at_price.cents > 0
## Item has compare_at_price, check if is on sale
if item.variant.compare_at_price > item.variant.price
## Item is on sale, apply bundle item discount based on item.variant.compare_at_price
sale_discount = item.variant.compare_at_price - item.variant.price
if line_item_discount_value > (Float(sale_discount.cents.to_s) / 100)
new_line_price = [item.variant.compare_at_price - (discount_amount * item.quantity), Money.zero].max
item.change_line_price(new_line_price, { message: discount_message })
end
else
## Item is not on sale, apply line item discount based on item.line_price
new_line_price = [item.line_price - (discount_amount * item.quantity), Money.zero].max
item.change_line_price(new_line_price, { message: discount_message })
end
else
## Item does not have compare_at_price, apply line item discount based on item.line_price
new_line_price = [item.line_price - (discount_amount * item.quantity), Money.zero].max
item.change_line_price(new_line_price, { message: discount_message })
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