Discussing Shopify Functions development, deployment, and usage in Shopify apps.
I am building a Shopify app functions which apply different discounts on based of quantity of a product added to the cart.
When 10 or more products of a particular variant is added then 2.5% volume discount must apply and when 25 or more products are added to the cart then 5% volume discount must apply.
The problem is when the second product is added then the discount applied to that product applies on all cart lines irrespective of their quantity .
Below is the code of run.js file of my volume based discount function app.
import { DiscountApplicationStrategy } from "../generated/api"; // Use JSDoc annotations for type safety /** * @typedef {import("../generated/api").RunInput} RunInput * @typedef {import("../generated/api").FunctionRunResult} FunctionRunResult * @typedef {import("../generated/api").Target} Target * @typedef {import("../generated/api").ProductVariant} ProductVariant */ /** * @type {FunctionRunResult} */ const EMPTY_DISCOUNT = { discountApplicationStrategy: DiscountApplicationStrategy.First, discounts: [], }; /** * @param {RunInput} input * @returns {FunctionRunResult} */ export function run(input) { let discountValue = 0; const targets = input.cart.lines .filter((line) => { if(line.merchandise.__typename === "ProductVariant"){ if (line.quantity >= 50) { discountValue = 7.5; return true; } else if (line.quantity >= 25) { discountValue = 5; return true; } else if (line.quantity >= 10) { discountValue = 2.5; return true; } return false; } }) .map((line) => { return { productVariant : { id: line.merchandise.id, } }; }); if (!targets.length) { console.error("No cart lines qualify for volume discount."); return EMPTY_DISCOUNT; } if (discountValue === 2.5) { return { discounts: [ { targets: targets, value: { percentage: { value: "2.5", }, }, message: "2.5% off when buying at least 10", }, ], discountApplicationStrategy: DiscountApplicationStrategy.First, }; } else if(discountValue === 5){ return { discounts: [ { targets, value: { percentage: { value: "5.0", }, }, message: "5% off when buying at least 25", }, ], discountApplicationStrategy: DiscountApplicationStrategy.First, }; } else if(discountValue === 7.5){ return { discounts: [ { targets, value: { percentage: { value: "7.5", }, }, message: "7.5% off when buying at least 50", }, ], discountApplicationStrategy: DiscountApplicationStrategy.First, }; } }
Below is the graphql query :
Help me fix this.
It sounds like there's a significant difference between the code you've written and the actual logic for when you want the discount to apply.
Your code targets every line item with a quantity of 10 or greater and gives them all the same discount.
Also, I recommend using `CartLineTarget` instead of `ProductVariantTarget`.