Skip to content
Scripts examples

Migrating a script that limited how many units were discounted

The cap is not the trap. The trap is a single sort line: with it the CHEAPEST units are discounted, without it the FIRST ones are, and both files are dense with the same split call that also makes them look like a BOGO.

Rebuilt
What the Script did

It discounted only the first few matching units and left the rest at full price.

Merchants wrote this 3 different ways, and they do not all mean the same thing. Each spelling is below with its own cart and its own numbers.

Run it against your own store

Paste it into Scripts rescue and watch what it rebuilds

  1. Copy the Ruby with the button beside any Script on this page.
  2. In your Shopify admin, open Stackable, then Tools, then Scripts rescue.
  3. Paste it there, read what the tool says it will build, and compare that with the settings on this page.

Scripts rescue is on the Pro plan. Nothing is published until you tell it what your old Script charged and the two figures match to the cent.

Quantity limit first n discounted (D5)

Rebuilt

Danger pair D5. This file and its partner look almost identical and behave differently, so read both before you decide which one you have.

The original Ruby

# GENERATED BY THE SHOPIFY SCRIPT CREATOR APP

class ConditionalDiscount < Campaign
  def initialize(condition, customer_qualifier, cart_qualifier, line_item_selector, discount, max_discounts)
    super(condition, customer_qualifier, cart_qualifier, line_item_selector)
    @discount = discount
    @items_to_discount = max_discounts == 0 ? nil : max_discounts
  end

  def run(cart)
    return unless qualifies?(cart)
    applicable_items = cart.line_items.select { |item| @line_item_selector.nil? || @line_item_selector.match?(item) }
    applicable_items.each do |item|
      break if @items_to_discount == 0
      if !@items_to_discount.nil? && (item.quantity > @items_to_discount)
        new_item = item.split({ take: @items_to_discount })
        @discount.apply(new_item)
        position = cart.line_items.find_index(item)
        cart.line_items.insert(position + 1, new_item)
        @items_to_discount = 0
      else
        @discount.apply(item)
        @items_to_discount -= item.quantity unless @items_to_discount.nil?
      end
    end
  end
end

CAMPAIGNS = [
  ConditionalDiscount.new(
    :all, nil, nil,
    ProductTypeSelector.new(:does, ["Sale"]),
    PercentageDiscount.new(30, "30% off first 2"),
    2
  ),
].freeze

CAMPAIGNS.each do |campaign|
  campaign.run(Input.cart)
end

Output.cart = Input.cart
What it becomes

Recognised as Discount on the first few units and rebuilt as a bxgy offer. These are the real configuration keys the offer is saved with, so you can check your own rebuild against them field by field.

Every setting, spelled out
SettingValueConfig key
Offer typebxgytype
Countingper_variantcounting
Recurrenceoncerecurrence
Tier 1min qty 1 -> free itemtiers[0]
Buy quantity1bxgy.buyQty
Get quantity2bxgy.getQty
Get selectionsame_itembxgy.getSelection
Reward on the get units30% offbxgy.getDiscountPct
Free units are additionalfalsebxgy.freeUnitsAreAdditional
Target scopeproduct_typestarget.scope
Target includesSaletarget.includeIds
MethodautomaticdiscountMethod
Allocationstandardstacking.allocation
Combines with other discountsnostacking
You will be asked to confirm
  • Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect.
You will be told
  • The unit limit counts per matching group, not per cart line, so a cart with two separate lines can reach the limit twice.
The cart that proves it

Built on our public demo store, Meridian Goods, so every price here can be reproduced rather than taken on trust. The discount below is what the same engine that runs at checkout computes for this exact cart.

  • No Meridian Goods product carries the type Sale. Set it on Aria Wireless Earbuds in Shopify before you build the cart, and on nothing else.
The cart that triggers this offer, and what it costs
ItemQtyUnit price
Aria Wireless Earbuds1$79.00
Subtotal$79.00
Discount-$23.70
Total$55.30

Signed out, or signed in as a customer with no tags.

The figure the tool checks you against

Before publishing, the tool asks what your old Script did to a cart you already have. Set it to 1 of Aria Wireless Earbuds at $79.00 and the answer is fixed.

The discount is $23.70. The total the shopper paid is $55.30.

The comparison is exact, down to the smallest unit of your currency. One cent out and publishing stays shut, which is the whole point of the step.

The cart that must produce nothing
  • swap the cart for a single Braided USB-C Cable
The cart that must not trigger this offer
ItemQtyUnit price
Braided USB-C Cable1$14.00
Subtotal$14.00
Total$14.00

Signed out, or signed in as a customer with no tags.

Quantity limit cheapest n (D5)

Rebuilt

Danger pair D5. This file and its partner look almost identical and behave differently, so read both before you decide which one you have.

The original Ruby

# GENERATED BY THE SHOPIFY SCRIPT CREATOR APP

class ConditionalDiscount < Campaign
  def initialize(condition, customer_qualifier, cart_qualifier, line_item_selector, discount, max_discounts)
    super(condition, customer_qualifier, cart_qualifier, line_item_selector)
    @discount = discount
    @items_to_discount = max_discounts == 0 ? nil : max_discounts
  end

  def run(cart)
    return unless qualifies?(cart)
    applicable_items = cart.line_items.select { |item| @line_item_selector.nil? || @line_item_selector.match?(item) }
    applicable_items = applicable_items.sort_by { |item| item.variant.price }
    applicable_items.each do |item|
      break if @items_to_discount == 0
      if !@items_to_discount.nil? && (item.quantity > @items_to_discount)
        new_item = item.split({ take: @items_to_discount })
        @discount.apply(new_item)
        position = cart.line_items.find_index(item)
        cart.line_items.insert(position + 1, new_item)
        @items_to_discount = 0
      else
        @discount.apply(item)
        @items_to_discount -= item.quantity unless @items_to_discount.nil?
      end
    end
  end
end

CAMPAIGNS = [
  ConditionalDiscount.new(
    :all, nil, nil,
    ProductTypeSelector.new(:does, ["Sale"]),
    PercentageDiscount.new(30, "30% off your 2 cheapest"),
    2
  ),
].freeze

CAMPAIGNS.each do |campaign|
  campaign.run(Input.cart)
end

Output.cart = Input.cart
What it becomes

Recognised as Discount on the first few units and rebuilt as a bxgy offer. These are the real configuration keys the offer is saved with, so you can check your own rebuild against them field by field.

Every setting, spelled out
SettingValueConfig key
Offer typebxgytype
Countingper_groupcounting
Recurrenceoncerecurrence
Tier 1min qty 1 -> free itemtiers[0]
Buy quantity1bxgy.buyQty
Get quantity2bxgy.getQty
Get selectioncheapest_eligiblebxgy.getSelection
Reward on the get units30% offbxgy.getDiscountPct
Free units are additionalfalsebxgy.freeUnitsAreAdditional
Target scopeproduct_typestarget.scope
Target includesSaletarget.includeIds
MethodautomaticdiscountMethod
Allocationstandardstacking.allocation
Combines with other discountsnostacking
You will be asked to confirm
  • Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect.
You will be told
  • The unit limit counts per matching group, not per cart line, so a cart with two separate lines can reach the limit twice.
The cart that proves it

Built on our public demo store, Meridian Goods, so every price here can be reproduced rather than taken on trust. The discount below is what the same engine that runs at checkout computes for this exact cart.

  • No Meridian Goods product carries the type Sale. Set it on Aria Wireless Earbuds and Impact Phone Case in Shopify before you build the cart, and on nothing else.
The cart that triggers this offer, and what it costs
ItemQtyUnit price
Impact Phone Case1$24.00
Aria Wireless Earbuds1$79.00
Subtotal$103.00
Discount-$30.90
Total$72.10

Signed out, or signed in as a customer with no tags.

The figure the tool checks you against

Before publishing, the tool asks what your old Script did to a cart you already have. Set it to 1 of Impact Phone Case at $24.00 and the answer is fixed.

The discount is $7.20. The total the shopper paid is $16.80.

The comparison is exact, down to the smallest unit of your currency. One cent out and publishing stays shut, which is the whole point of the step.

The cart that must produce nothing
  • swap the cart for a single Braided USB-C Cable
The cart that must not trigger this offer
ItemQtyUnit price
Braided USB-C Cable1$14.00
Subtotal$14.00
Total$14.00

Signed out, or signed in as a customer with no tags.

Quantity limit first n discounted (D6)

Rebuilt

Danger pair D6. This file and its partner look almost identical and behave differently, so read both before you decide which one you have.

The original Ruby

DISCOUNT_PERCENTAGE = 30
MAX_UNITS = 2

num_to_discount = MAX_UNITS

Input.cart.line_items.each_with_index do |line_item, position|
  break if num_to_discount <= 0
  next unless line_item.variant.product.tags.include?("limited")

  if line_item.quantity > num_to_discount
    split_line_item = line_item.split(take: num_to_discount)
    Input.cart.line_items.insert(position + 1, split_line_item)
    line_item = split_line_item
  end

  line_item.change_line_price(
    line_item.line_price * (1.0 - (DISCOUNT_PERCENTAGE / 100.0)),
    message: "30% off your first 2"
  )
  num_to_discount -= line_item.quantity
end

Output.cart = Input.cart
What it becomes

Recognised as Discount on the first few units and rebuilt as a bxgy offer. These are the real configuration keys the offer is saved with, so you can check your own rebuild against them field by field.

Every setting, spelled out
SettingValueConfig key
Offer typebxgytype
Countingper_variantcounting
Recurrenceoncerecurrence
Tier 1min qty 1 -> free itemtiers[0]
Buy quantity1bxgy.buyQty
Get quantity2bxgy.getQty
Get selectionsame_itembxgy.getSelection
Reward on the get units30% offbxgy.getDiscountPct
Free units are additionalfalsebxgy.freeUnitsAreAdditional
Target scopetagstarget.scope
Target includeslimitedtarget.includeIds
MethodautomaticdiscountMethod
Allocationstandardstacking.allocation
Combines with other discountsnostacking
You will be asked to confirm
  • Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect.
You will be told
  • The unit limit counts per matching group, not per cart line, so a cart with two separate lines can reach the limit twice.
The cart that proves it

Built on our public demo store, Meridian Goods, so every price here can be reproduced rather than taken on trust. The discount below is what the same engine that runs at checkout computes for this exact cart.

  • No Meridian Goods product carries the tag limited. Set it on Aria Wireless Earbuds in Shopify before you build the cart, and on nothing else.
The cart that triggers this offer, and what it costs
ItemQtyUnit price
Aria Wireless Earbuds1$79.00
Subtotal$79.00
Discount-$23.70
Total$55.30

Signed out, or signed in as a customer with no tags.

The figure the tool checks you against

Before publishing, the tool asks what your old Script did to a cart you already have. Set it to 1 of Aria Wireless Earbuds at $79.00 and the answer is fixed.

The discount is $23.70. The total the shopper paid is $55.30.

The comparison is exact, down to the smallest unit of your currency. One cent out and publishing stays shut, which is the whole point of the step.

The cart that must produce nothing
  • swap the cart for a single Braided USB-C Cable
The cart that must not trigger this offer
ItemQtyUnit price
Braided USB-C Cable1$14.00
Subtotal$14.00
Total$14.00

Signed out, or signed in as a customer with no tags.

Two files that look the same

Each pair below is one Script shape written two ways. They differ by a line or two and they do different things, so read both before deciding which one you have.

Danger pair D5

Quantity limit first n discounted (D5)

Rebuilt

Rebuilt as a bxgy offer.

Discount on its own cart: $23.70

Lines that differ
    PercentageDiscount.new(30, "30% off first 2"),
Read Limit the discounted units

Quantity limit cheapest n (D5)

Rebuilt

Rebuilt as a bxgy offer.

Discount on its own cart: $30.90

Lines that differ
    applicable_items = applicable_items.sort_by { |item| item.variant.price }
    PercentageDiscount.new(30, "30% off your 2 cheapest"),
Read Limit the discounted units

Danger pair D6

Quantity limit first n discounted (D6)

Rebuilt

Rebuilt as a bxgy offer.

Discount on its own cart: $23.70

Lines that differ
DISCOUNT_PERCENTAGE = 30
MAX_UNITS = 2
num_to_discount = MAX_UNITS
Input.cart.line_items.each_with_index do |line_item, position|
  break if num_to_discount <= 0
  next unless line_item.variant.product.tags.include?("limited")

And 9 more differing lines, on its own page.

Read Limit the discounted units

Quantity limit purchase cap (D6)

Different Shopify API

Not rebuilt. This needs a different kind of Shopify app

Lines that differ
# GENERATED BY THE SHOPIFY SCRIPT CREATOR APP
class QuantityLimit < Campaign
  def initialize(condition, customer_qualifier, cart_qualifier, line_item_selector, limit_by, limit)
    super(condition, customer_qualifier, cart_qualifier, line_item_selector)
    @limit_by = limit_by
    @limit = limit

And 26 more differing lines, on its own page.

Read Purchase quantity limit

Common questions

Will Stackable rebuild this script?
Yes. Every spelling on this page is rebuilt today as a bxgy offer, and the cart above is the one that proves it.
What cart proves it works?
1 x Aria Wireless Earbuds at $79.00. The engine takes $23.70 off, and checkout charges $55.30.
What will I have to check before publishing?
Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect. The unit limit counts per matching group, not per cart line, so a cart with two separate lines can reach the limit twice.

Related Script shapes

Purchase quantity limit

A cap on how many units a shopper could buy, enforced by trimming the cart.

Buy one get one free

A set of paid units earns an extra unit at no charge.

Buy X get Y, inclusive

The same buy-and-get offer, counted so the reward sits inside each set rather than beside it.

Paste your Script and see it rebuilt

The rebuild is checked against the money your old Script charged before you can publish it.

We use essential cookies to run this site, and, only with your permission, analytics cookies to understand traffic. Read our Cookie Policy.