Issue on using product tags in Functions

Issue on using product tags in Functions

nyashamadzokere
Shopify Partner
7 0 1

I am trying to apply for discounts on product tag with  "2FOR200", "2FOR300", "3FOR500". I am having an error on my run.js line 25 and 34.The accessing the product.hasAnyTag

//run.graphql

query RunInput($tags: [String!]) {
  cart {
    lines {
      id
      quantity
      merchandise {
        ... on ProductVariant {
          id
          product {
            hasAnyTag(tags: ["2FOR200", "2FOR300", "3FOR500"])
          }
        }
      }
    }
  }
}

my run.js 

// @ts-check
import { DiscountApplicationStrategy } from "../generated/api";

/**
 * @typedef {import("../generated/api").RunInput} RunInput
 * @typedef {import("../generated/api").FunctionRunResult} FunctionRunResult
 * @typedef {import("../generated/api").Target} Target
 */

/**
 * @type {FunctionRunResult}
 */
const EMPTY_DISCOUNT = {
  discountApplicationStrategy: DiscountApplicationStrategy.First,
  discounts: [],
};

/**
 * @param {RunInput} input
 * @returns {FunctionRunResult}
 */
export function run(input) {
  const targets = input.cart.lines
    // Only include cart lines with at least one pair of items (quantity >= 2)
    .filter((line) => line.quantity >= 2 && line.merchandise.product.hasAnyTag)
    .map((line) => {
      const tagDiscountMapping = {
        "2FOR200": 10.0, // 10% discount
        "2FOR300": 30.0, // 30% discount
        "3FOR500": 20.0, // 20% discount
      };

      const tag = ["2FOR200", "2FOR300", "3FOR500"].find((t) =>
        line.merchandise.product.hasAnyTg.includes(t)
      );

      // Calculate eligible discount based on quantity and tag
      const discountValue = tagDiscountMapping[tag];
      const eligibleGroups = tag === "3FOR500" ? Math.floor(line.quantity / 3) : Math.floor(line.quantity / 2);

      // Generate discount targets for each eligible group
      return Array.from({ length: eligibleGroups }, () => ({
        cartLine: { id: line.id },
      }));
    })
    .flat();

  if (!targets.length) {
    console.error("No cart lines qualify for the discount.");
    return EMPTY_DISCOUNT;
  }

  return {
    discounts: [
      {
        targets,
        value: {
          percentage: {
            value: discountValue.toString(),
          },
        },
      },
    ],
    discountApplicationStrategy: DiscountApplicationStrategy.First,
  };
}
Replies 0 (0)