I am writing a Shipping Discount Shopify function. If a customer buy two items which are from different locations, e.g. item A from location X and item B from location Y, I want to give 50% discount on shipping fee.
But how to detect if the cart’s items are from multiple locations?
I am using input.cart.deliveryGroups.length.
It seems not correct as it always returns one.
Can anyone help?
Here is my code (run.js):
const EMPTY_DISCOUNT = {
discounts: [],
};
export function run(input) {
const deliveryGroupCount = input.cart.deliveryGroups.length;
if (deliveryGroupCount === 1) {
return EMPTY_DISCOUNT;
}
const discountPercentage = 100 / deliveryGroupCount;
const deliveryOptions = [];
for(const deliveryGroup of input.cart.deliveryGroups) {
for (const option of deliveryGroup.deliveryOptions) {
deliveryOptions.push({
deliveryOption: {
handle: option.handle
}
})
}
}
return {
discounts: [
{
targets: deliveryOptions,
value: {
percentage: {
value: discountPercentage
}
}
}
]
}
};
Here is run.graphql
query RunInput {
cart {
deliveryGroups {
deliveryOptions {
title
handle
}
}
}
}