Skip to content

Instantly share code, notes, and snippets.

@dturton
Forked from HillbergAndBerkIT/Free Gift.rb
Created January 18, 2018 18:07
Show Gist options
  • Save dturton/8b36437abd88387e58a2db4a67f13302 to your computer and use it in GitHub Desktop.
Save dturton/8b36437abd88387e58a2db4a67f13302 to your computer and use it in GitHub Desktop.
Shopify Scripts
# See https://onlygrowth.com/blogs/posts/17-shopify-scripts-to-maximize-conversions for some helpful snippets
class FreeGift
def initialize(variant_id, minTotal, message, quantity = 1)
@variant_id = variant_id
@minTotal = minTotal
@message = message
@giftQuantity = quantity
end
# Get the total of the cart without the variant price being included
def getTotalWithoutGift(cart)
removedGift = false
cartTotalWithoutGift = Money.zero
cart.line_items.each do |item|
# Check to see if the gift has been removed already
# and if the current item is the gift
if item.variant.id == @variant_id && !removedGift
# Ensure that we are only removing the quantity of the gift from the
# free gift item when calculating the total without the gift
if item.quantity > @giftQuantity
i = @giftQuantity
while i < item.quantity do
cartTotalWithoutGift += item.variant.price
i += 1
end
end
# Flag that the gift has now been removed from the total
removedGift = true
next
end
cartTotalWithoutGift += item.line_price_was
end
return cartTotalWithoutGift
end
# Apply the free gift promotion if this gift's conditions are met
def run(cart)
# Flag for whether the gift has been given (price removed from total)
giftMadeFree = false
cartTotal = getTotalWithoutGift(cart)
if cartTotal >= @minTotal
cart.line_items.each do |item|
break if giftMadeFree
if item.variant.id == @variant_id
item.change_line_price(item.line_price - (item.variant.price * @giftQuantity), message: @message)
giftMadeFree = true
end
end
if not giftMadeFree
# We can't actually add products to a customer's cart with the script editor, so we need to
# make sure that we are doing it in JS when the threshold is reached
end
end
end
end
GIFTS = [
# Give the Jewellery Carrier for purchases >=$250
FreeGift.new(
5338912897,
Money.new(cents: 100) * 250,
"Complimentary Deluxe Jewellery Carrier on purchases of $250 or more",
),
]
GIFTS.each do |gift|
gift.run(Input.cart)
end
Output.cart = Input.cart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment