Skip to content

Instantly share code, notes, and snippets.

@elephantsneverforget
Created September 25, 2023 17:56
Show Gist options
  • Save elephantsneverforget/c3d88c582eee9a664385b4a005c7ec82 to your computer and use it in GitHub Desktop.
Save elephantsneverforget/c3d88c582eee9a664385b4a005c7ec82 to your computer and use it in GitHub Desktop.
Gets discount information in the Web Pixel
getTotalShippingDiscount: function (event) {
const discountApplications = event?.data?.checkout?.discountApplications || [];
const shippingDiscountApplications = discountApplications.filter(
(discountApplication) => discountApplication?.targetType === "SHIPPING_LINE"
);
const shippingDiscountApplicationsPercentBased =
shippingDiscountApplications.filter(
(discountApplication) =>
typeof discountApplication?.value?.percentage !== "undefined"
);
const shippingDiscountApplicationsFixedAmountBased =
shippingDiscountApplications.filter(
(discountApplication) =>
typeof discountApplication?.value?.amount !== "undefined"
);
const percentBasedDiscounts =
shippingDiscountApplicationsPercentBased.reduce(
(acc, shippingDiscountAllocation) => {
const percentDiscount = shippingDiscountAllocation?.value?.percentage;
const totalShippingCost =
event?.data?.checkout?.shippingLine?.price?.amount;
const discount = (percentDiscount / 100) * totalShippingCost;
return acc + Number(discount);
},
0
);
const fixedBasedDiscounts =
shippingDiscountApplicationsFixedAmountBased.reduce(
(acc, shippingDiscountAllocation) => {
return acc + Number(shippingDiscountAllocation?.value?.amount);
},
0
);
return percentBasedDiscounts + fixedBasedDiscounts;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment