Creating a discount based on customer and variant tags

Hello,

I am working on an automatic discount function for our store. I want to be able to apply cart line level discounts based on both the customer’s tags and the product variant’s tags. I have managed to get checking the customer tags correct but am having trouble getting from cartline.merchandise to the product variant information. This is my first attempt at a shopify function as we migrate off of scripts and I had thought just checking tags would be easy but it seems like it is not.

GraphQL:

query RunInput {
  cart {
    buyerIdentity {
      customer {
        hasTags(tags: ["employee"]) {
          tag
          hasTag
        }
      }
    }
    lines {
      id
      merchandise {__typename
        ...on ProductVariant {
          sku
          product {
            hasTags(tags: ["DiscountEligible","Sterling Jewelry","Final Sale"]) {
              tag
              hasTag
            }
          }
        }
      }
    }
  }
}

Javascript:

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

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

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

/**
 * @param {RunInput} input
 * @returns {FunctionRunResult}
 */
export function run(input) {
  const lines = input.cart.lines
  const customer = input.cart.buyerIdentity?.customer
  customer?.hasTags.some((t) => (t.tag.toLowerCase() === "employee" && t.hasTag === true))
  {
    var finalDiscount = {discounts: []}
    for(var i = 0; i< lines.length; i++)
      {
        if(lines[i].merchandise.product )// how do I go from merchandise to product? all that is available is lines[i].merchandise.__typename
          {
            
          }
      }
  }

  return EMPTY_DISCOUNT;
};
1 Like

Is there a chance that the merchandise is of type CustomProduct rather than ProductVariant? Can you try adding this to your input as well?

...on CustomProduct {
title
}

Hello I tried adding that to my graphql query and updating the typegen. However that did not help the problem in the run.js. I have not attempted to actually run the function yet as I do not even know how to get the data I need so there is no error or customproduct being checked as the function is not running. Thank you for trying though!