Hi,
I’m currently trying to build a Shopify Discount Function that will target products based off a tag. If I hardcode the tag value into the input query the function works however I would like this to be dynamic, along with the percentage off. I followed along with the using input variable documentation and my input query currently looks like this:
query RunInput ($tags: [String!]) {
cart {
lines {
quantity
merchandise {
__typename
...on ProductVariant {
id
product {
hasAnyTag(tags: $tags),
}
}
}
}
}
discountNode {
metafield(namespace: "$app:product-discount", key: "function-configuration"){
value
}
}
}
I also have updated my shopify.extension.toml to include the input variable and the function-configuration metafield, however after I use the Shopify GraphQL app to create my discount using the function id and passing through the json data for the metafield, upon running the function the product is not discounted even if it is tagged correctly and the value field in my discountNode show as null. Here is the log for further context:
{
"cart": {
"lines": [
{
"quantity": 1,
"merchandise": {
"__typename": "ProductVariant",
"id": "gid://shopify/ProductVariant/47070228152616",
"product": {
"hasAnyTag": false
}
}
}
]
},
"discountNode": {
"metafield": null
}
}
Any insight into what the issue with my code may be or what I may be missing would be beyond appreciated.
Thank you!
PS: Here is the run function as well
* {RunInput} input
* @returns {FunctionRunResult}
*/
export function run(input) {
/**
* @type {{
* percentage: number
* }}
*/
const configuration = JSON.parse(
input?.discountNode?.metafield?.value ?? "{}"
);
if(!configuration.percentage){
return EMPTY_DISCOUNT;
}
const targets = input.cart.lines
// Only include cart lines with a quantity of two or more
// and a targetable product variant
.filter(line =>
line.merchandise.__typename == "ProductVariant" && line.merchandise.product.hasAnyTag)
.map(line => {
const variant = /** @type {ProductVariant} */ (line.merchandise);
return /** @type {Target} */ ({
// Use the variant ID to create a discount target
productVariant: {
id: variant.id
}
});
});
if (!targets.length) {
// You can use STDERR for debug logs in your function
console.error("No cart lines qualify for product discount.");
return EMPTY_DISCOUNT;
}
// The /shopify_function package applies JSON.stringify() to your function result
// and writes it to STDOUT
return {
discounts: [
{
// Apply the discount to the collected targets
targets,
// Define a percentage-based discount
value: {
percentage: {
value: configuration.percentage.toString()
}
}
}
],
discountApplicationStrategy: DiscountApplicationStrategy.First
};
};