Quantity-cap Discount Function
A judgment-first walkthrough: when apps fail, how to split overflow to full price, and what to verify before you ship. Illustrative code — not production IP.
SeriesShopify FunctionsLength12:40LevelIntermediateUpdatedJul 2026
Step-by-step
Scaffold the Discount Function
Start from Shopify CLI. Keep the Function tiny — CAP as a constant you can later move to metafields once the mechanic is proven on staging.
JavaScript
1// src/run.js2const CAP = 3;34export function run(input) {5 const lines = input.cart.lines.filter((l) => l.quantity > 0);6 if (lines.length === 0) return { discounts: [] };7 return { discounts: lines.flatMap(capLine) };8}
Split overflow to full price
When quantity exceeds CAP, discount only the capped units. Overflow becomes its own line at full price — the mechanic apps kept getting wrong.
JavaScript
1// src/cap.js2function capLine(line) {3 if (line.quantity <= CAP) {4 return [{ targets: [{ cartLine: { id: line.id } }], value: { percentage: 20 } }];5 }6 // Only the first CAP units are discounted; the rest stay full price.7 return [8 {9 targets: [{ cartLine: { id: line.id, quantity: CAP } }],10 value: { percentage: 20 },11 },12 ];13}
Verify edge cases before staging sign-off
Test mixed carts, gift lines, and CAP changes. If marketing can edit CAP mid-campaign, put it in a metafield — don't redeploy for a number.
qty ≤ CAP→ single discounted lineqty > CAP→ split + full-price overflow- gift / zero-price lines untouched
- B2B company location pricing still resolves
BEYOND THE TUTORIAL
Need this mechanic under NDA for a client?
Watch stays public and judgment-level. Agency overflow gets the production pattern — white-label, IP transfers on payment.