window._ABConfig.getProductDiscountedPricing = ({ variantId, amount, quantity, sellingPlanId }) => {
const disableAppFunctionality = window?._ABConfig?.['disableAppFunctionality'] || false;
if (!variantId || disableAppFunctionality) {
console.error('Please provide a current variant id');
return [];
}
//helper functions
const isDiscountUsageLimitExceed = (customerDiscountUsage, bundle) => {
if (customerDiscountUsage && customerDiscountUsage.length) {
const targetDiscountUsage = customerDiscountUsage.find(
(discountUsage) => discountUsage?.uniqueRef === bundle?.uniqueRef
);
return targetDiscountUsage && targetDiscountUsage?.usageCount >= bundle?.limitToUsePerCustomer;
}
return false;
};
const isBundleRestrictedCustomerByTagsByDiscount = (item, customerTags) => {
if (!item?.restrictTags) return false;
const restrictTags = item?.restrictTags?.split(',');
return customerTags && customerTags.length > 0 && customerTags.some((tag) => restrictTags?.includes(tag));
};
const isBundleAllowedByCustomersTagByDiscount = (item, customerTags) => {
if (!item?.allowedTags) return true;
const allowedCustomersOnly = item?.allowedTags?.split(',');
return (
customerTags &&
customerTags.length > 0 &&
customerTags.some((tag) => allowedCustomersOnly?.includes(tag))
);
};
const isBundleRestrictedByDiscount = (item, customerTags) => {
return isBundleRestrictedCustomerByTagsByDiscount(item, customerTags) || !isBundleAllowedByCustomersTagByDiscount(item, customerTags);
};
const processBundleRules = (bundles, type, fields) =>
bundles
.filter((bundle) => bundle?.bundleType === type)
.map((rule) => {
const parsedRule = { ...rule };
fields.forEach((field) => {
try {
parsedRule[field] = JSON.parse(rule[field] || '[]');
} catch (e) {
console.error('Failed to parse field:', field, e);
parsedRule[field] = [];
}
});
return parsedRule;
});
const getBestDiscount = (applicableDiscounts, lineItem, discountKey = 'discount') => {
return applicableDiscounts.reduce((greater, current) => {
const greaterDiscount = greater?.[discountKey];
const currentDiscount = current?.[discountKey];
if ((greater?.discountType === "PERCENTAGE" && current?.discountType === "PERCENTAGE") ||
(greater?.discountType === "FIXED_AMOUNT" && current?.discountType === "FIXED_AMOUNT")) {
return currentDiscount > greaterDiscount ? current : greater;
} else if (current?.discountType === "FIXED_AMOUNT" && greater?.discountType === "PERCENTAGE") {
return currentDiscount > ((greaterDiscount / 100) * lineItem?.totalAmount) ? current : greater;
} else if (current?.discountType === "PERCENTAGE" && greater?.discountType === "FIXED_AMOUNT") {
return ((currentDiscount / 100) * lineItem?.totalAmount) > greaterDiscount ? current : greater;
}
return currentDiscount > greaterDiscount ? current : greater;
});
};
const getApplicableTieredDiscount = (volumeDiscountBundles, lineItem) => {
let applicableDiscount = null;
const updatedVolumeDiscountBundles = volumeDiscountBundles.map(bundle => {
const updatedTieredDiscount = bundle?.tieredDiscount.map(discount => {
return {
...discount,
appliesOn: bundle?.appliesOn
};
})
return {
...bundle,
tieredDiscount: updatedTieredDiscount
}
});
const volumeDiscountBundlesTieredDiscount = updatedVolumeDiscountBundles.reduce((acc, item) => {
return acc.concat(item?.tieredDiscount);
}, []);
let applicableQuantityBasedDiscount = volumeDiscountBundlesTieredDiscount
.filter(tieredDiscount => tieredDiscount?.discountBasedOn === "QUANTITY")
.filter(tieredDiscount => lineItem?.quantity >= tieredDiscount?.value);
applicableQuantityBasedDiscount = applicableQuantityBasedDiscount.length > 0 ? getBestDiscount(applicableQuantityBasedDiscount, lineItem) : null;
let applicableSpendAmountBasedDiscount = volumeDiscountBundlesTieredDiscount
.filter(tieredDiscount => tieredDiscount?.discountBasedOn === "AMOUNT")
.filter(tieredDiscount => lineItem?.totalAmount >= tieredDiscount?.value);
applicableSpendAmountBasedDiscount = applicableSpendAmountBasedDiscount.length > 0 ? getBestDiscount(applicableSpendAmountBasedDiscount, lineItem, ) : null;
if (applicableQuantityBasedDiscount && applicableSpendAmountBasedDiscount) {
if ((applicableQuantityBasedDiscount?.discountType === "PERCENTAGE" && applicableSpendAmountBasedDiscount?.discountType === "PERCENTAGE") || (applicableQuantityBasedDiscount?.discountType === "FIXED_AMOUNT" && applicableSpendAmountBasedDiscount?.discountType === "FIXED_AMOUNT")) {
if (applicableQuantityBasedDiscount?.discount > applicableSpendAmountBasedDiscount?.discount) {
applicableDiscount = applicableQuantityBasedDiscount;
} else {
applicableDiscount = applicableSpendAmountBasedDiscount;
}
}else if(applicableQuantityBasedDiscount?.discountType === "PERCENTAGE" && applicableSpendAmountBasedDiscount?.discountType === "FIXED_AMOUNT"){
if (((applicableQuantityBasedDiscount?.discount / 100) * lineItem?.totalAmount) > applicableSpendAmountBasedDiscount?.discount) {
applicableDiscount = applicableQuantityBasedDiscount;
} else {
applicableDiscount = applicableSpendAmountBasedDiscount;
}
}else if(applicableQuantityBasedDiscount?.discountType === "FIXED_AMOUNT" && applicableSpendAmountBasedDiscount?.discountType === "PERCENTAGE"){
if (applicableQuantityBasedDiscount?.discount > ((applicableSpendAmountBasedDiscount?.discount / 100) * lineItem?.totalAmount)) {
applicableDiscount = applicableQuantityBasedDiscount;
} else {
applicableDiscount = applicableSpendAmountBasedDiscount;
}
}
} else if (applicableQuantityBasedDiscount) {
applicableDiscount = applicableQuantityBasedDiscount;
} else if (applicableSpendAmountBasedDiscount) {
applicableDiscount = applicableSpendAmountBasedDiscount;
}
return applicableDiscount;
}
const getApplicablePercentOrFixedDiscount = (discountedPricingBundles, lineItem) => {
let applicableDiscount = null;
let applicableQuantityBasedDiscount = discountedPricingBundles
.map(bundle => {
return {
...bundle,
minProductCount: bundle?.minProductCount || 0,
maxProductCount: bundle?.maxProductCount || 0,
minOrderAmount: bundle?.minOrderAmount || 0
};
})
.filter(bundle => {
const minCount = bundle.minProductCount;
const maxCount = bundle.maxProductCount;
const minAmount = bundle.minOrderAmount;
if (minCount > 0 && lineItem.quantity < minCount) return false;
if (maxCount > 0 && lineItem.quantity > maxCount) return false;
if (minAmount > 0 && lineItem.amount < minAmount) return false;
return true;
});
applicableDiscount = applicableQuantityBasedDiscount.length > 0 ? getBestDiscount(applicableQuantityBasedDiscount, lineItem, 'discountValue') : null;
if(applicableDiscount){
applicableDiscount = {
discountBasedOn: applicableDiscount?.minOrderAmount > 0 && applicableDiscount?.minProductCount === 0 ? "AMOUNT" : "QUANTITY",
value: applicableDiscount?.minOrderAmount > 0 && applicableDiscount?.minProductCount === 0 ? lineItem?.totalAmount : lineItem?.quantity,
discount: applicableDiscount?.discountValue,
discountType: applicableDiscount?.discountType,
appliesOn: applicableDiscount?.appliesOn
}
}
return applicableDiscount;
}
const collections = _ABConfig?.product?.collections || [];
const discountBundles = [{"id":12174,"shop":"conquest-maps.myshopify.com","name":"15% Off Everything for Compass Club Members!","description":"15% Off Everything for Compass Club Members!","status":"ACTIVE","customerIncludeTags":null,"discountType":"PERCENTAGE","discountValue":15.0,"products":"null","variants":"null","sequenceNo":null,"bundleType":"DISCOUNTED_PRICING","settings":"{\"excludeSubscriptionPlans\":\"\",\"showUnitPrice\":false,\"sequentialProductsPerBatch\":50,\"includedSubscriptionPlans\":\"\"}","bundleProductId":null,"bundleVariantId":null,"productHandle":null,"discountId":null,"price":null,"numberOfProducts":0,"subscriptionBundlingEnabled":false,"subscriptionId":null,"minProductCount":null,"maxProductCount":null,"uniqueRef":"GOoBr6pXjJ","bundleRedirect":"CART","customRedirectURL":null,"minOrderAmount":null,"tieredDiscount":null,"productViewStyle":"QUICK_ADD","singleProductSettings":"null","trackInventory":false,"sellingPlanType":"BUNDLE_LEVEL","clearCart":"ENABLED","minPrice":null,"maxPrice":null,"externalBuildABoxId":null,"variantVisibilityType":"SHOW_VARIANTS_AS_INDIVIDUAL","subTitle":null,"freeShipping":false,"themeType":"THEME_TWO","showBundleInProductPage":true,"combinedWithProductDiscount":true,"combinedWithShippingDiscount":true,"combinedWithOrderDiscount":true,"allowedTags":"compass-club,compass-club-renew,compass-club-monthly-founding-member-intro,compass-club-monthly-founding-member-permanent,Compass Club Admin,compass-club-monthly-membership,compass-club-annual-membership,compass-club-annual-founding-membership","restrictTags":null,"selectionType":"FLEXIBLE","bundleHtml":"null","discountedVariants":"null","allowedCountries":null,"appliesOn":"ONE_TIME","purchaseRequirement":"NO_REQUIREMENT","productDiscountType":"EACH_PRODUCT","countrySelectionType":"ALL_COUNTRY","discountApplyApproach":"SHOPIFY_DISCOUNT_FUNCTION","discountedProductChooseType":"CHOOSE_ALL","internalName":"Compass Club Member 15% Off","sections":"[]","limitToUsePerCustomer":null,"discountedVariantSelectionLimit":null,"hideOneTimePurchase":false,"hideSubscriptionPurchase":false,"maxOrderAmount":null,"collectionData":"[{\"id\":263153090663,\"title\":\"Products not on Sale\",\"handle\":\"products-not-on-sale\",\"image\":null},{\"id\":265735012455,\"title\":\"Products on Sale\",\"handle\":\"products-on-sale\",\"image\":null}]","productSelectionType":"COLLECTION","tag":"Compass-Club-15-Off","productChooseType":null,"variantSelectionLimit":null,"discountTargetType":"VARIANT","enableSubscription":null,"subscriptionWidgetPosition":null,"subscribeTitle":null,"subscribeSubtitle":null,"subscriptionPreselected":null,"getYAppliesOn":null,"announcementBarMessage":null,"automaticDiscountNodeId":"gid://shopify/DiscountAutomaticNode/1709498335598","recurringCycleLimit":0,"automaticShippingDiscountNodeId":null,"scheduledBundleRule":null,"bundleActiveFrom":null,"bundleActiveTo":null,"bundleSubType":null,"discountAppliesOn":null,"layoutType":null,"style":"{\"buttonBackgroundColor\":\"#000000\",\"headingTextColor\":\"#000000\",\"primaryTextColor\":\"#000000\",\"secondaryTextColor\":\"#ffffff\"}","labels":"{\"volumeDiscountSaveRewardsLabel\":\"Save {{discount}}{{discount_type}}!\",\"volumeDiscountQuantityRewardsLabel\":\"Buy {{quantity}} quantity and get {{discount}}{{discount_type}} discount!\",\"volumeDiscountSpentAmountRewardsLabel\":\"Spend {{currency}}{{spent_amount}} and get {{discount}}{{discount_type}} discount!\",\"volumeAmountDiscountSpentAmountRewardsLabel\":\"Spend {{currency}}{{spent_amount}} and get {{currency}}{{discount}} discount!\",\"volumeAmountDiscountQuantityRewardsLabel\":\"Buy {{quantity}} quantity and get {{currency}}{{discount}} discount!\",\"volumeAmountDiscountSaveRewardsLabel\":\"Save {{currency}}{{discount}}!\"}","upsells":null,"enableVolumeDiscountUpsell":false,"combos":"[]","progressiveGift":null,"enableProgressiveGifts":false,"discountName":null,"shippingDiscountType":null},{"id":26416,"shop":"conquest-maps.myshopify.com","name":null,"description":null,"status":"ACTIVE","customerIncludeTags":null,"discountType":"PERCENTAGE","discountValue":100.0,"products":"null","variants":"[]","sequenceNo":null,"bundleType":"SHIPPING_DISCOUNT","settings":"{\"enableAnnouncementBar\":false}","bundleProductId":null,"bundleVariantId":null,"productHandle":null,"discountId":null,"price":null,"numberOfProducts":0,"subscriptionBundlingEnabled":false,"subscriptionId":null,"minProductCount":null,"maxProductCount":null,"uniqueRef":"dq5grkmrg7","bundleRedirect":"CART","customRedirectURL":null,"minOrderAmount":null,"tieredDiscount":null,"productViewStyle":"QUICK_ADD","singleProductSettings":"null","trackInventory":false,"sellingPlanType":"BUNDLE_LEVEL","clearCart":"ENABLED","minPrice":null,"maxPrice":null,"externalBuildABoxId":null,"variantVisibilityType":"SHOW_VARIANTS_AS_INDIVIDUAL","subTitle":null,"freeShipping":false,"themeType":"THEME_TWO","showBundleInProductPage":true,"combinedWithProductDiscount":true,"combinedWithShippingDiscount":true,"combinedWithOrderDiscount":true,"allowedTags":"Employee-Pickup","restrictTags":null,"selectionType":"FLEXIBLE","bundleHtml":"null","discountedVariants":"null","allowedCountries":null,"appliesOn":"BOTH","purchaseRequirement":"NO_REQUIREMENT","productDiscountType":"EACH_PRODUCT","countrySelectionType":"ALL_COUNTRY","discountApplyApproach":"SHOPIFY_DISCOUNT_FUNCTION","discountedProductChooseType":"CHOOSE_ALL","internalName":"Employee Pickup","sections":"[{\"id\":1,\"name\":\"\",\"description\":\"\",\"minProductCount\":0,\"maxProductCount\":0,\"variants\":[]}]","limitToUsePerCustomer":null,"discountedVariantSelectionLimit":null,"hideOneTimePurchase":false,"hideSubscriptionPurchase":false,"maxOrderAmount":null,"collectionData":null,"productSelectionType":"PRODUCT","tag":"appstle_bundles","productChooseType":"CHOOSE_ALL","variantSelectionLimit":null,"discountTargetType":"PRODUCT","enableSubscription":false,"subscriptionWidgetPosition":"BELOW","subscribeTitle":"Subscribe and Save","subscribeSubtitle":"Delivered Monthly","subscriptionPreselected":true,"getYAppliesOn":"BOTH","announcementBarMessage":null,"automaticDiscountNodeId":null,"recurringCycleLimit":0,"automaticShippingDiscountNodeId":"gid://shopify/DiscountAutomaticNode/1712141468014","scheduledBundleRule":null,"bundleActiveFrom":null,"bundleActiveTo":null,"bundleSubType":null,"discountAppliesOn":null,"layoutType":null,"style":"{\"productCardBackgroundColor\":\"#ffffff\",\"disabledTextColor\":\"#6B7280\",\"buttonBackgroundColor\":\"#363636\",\"bundlePageBackgroundColor\":\"#FAFAF9\",\"headingTextColor\":\"#363636\",\"primaryHoverColor\":\"#363636\",\"primaryTextColor\":\"#363636\",\"primaryColor\":\"#363636\",\"primaryDisabledColor\":\"#333333\",\"primaryDisabledTextColor\":\"#ffffff\",\"secondaryTextColor\":\"#ffffff\",\"fieldDisabledBackgroundColor\":\"#D1D5DB\"}","labels":"{}","upsells":null,"enableVolumeDiscountUpsell":false,"combos":null,"progressiveGift":null,"enableProgressiveGifts":false,"discountName":null,"shippingDiscountType":null},{"id":36639,"shop":"conquest-maps.myshopify.com","name":"Compass Club Free Shipping","description":null,"status":"ACTIVE","customerIncludeTags":null,"discountType":"PERCENTAGE","discountValue":100.0,"products":"[]","variants":"[]","sequenceNo":null,"bundleType":"SHIPPING_DISCOUNT","settings":"{\"cardGap\":16,\"sequentialProductsPerBatch\":50,\"showUnitPrice\":false,\"showPricesWithoutDecimal\":false,\"includedSubscriptionPlans\":\"\",\"excludeSubscriptionPlans\":\"\",\"perRowItem\":\"THREE\",\"enableAnnouncementBar\":false,\"borderRadius\":8,\"showClassicBundleWidgetInChildProduct\":false,\"enableSequentialProductLoading\":false,\"showPriceWithSubscriptionPrice\":true,\"showPriceOfChosenProductsOnly\":false}","bundleProductId":null,"bundleVariantId":null,"productHandle":null,"discountId":null,"price":null,"numberOfProducts":0,"subscriptionBundlingEnabled":false,"subscriptionId":null,"minProductCount":null,"maxProductCount":null,"uniqueRef":"chxqrrsncd","bundleRedirect":"CART","customRedirectURL":null,"minOrderAmount":null,"tieredDiscount":null,"productViewStyle":"QUICK_ADD","singleProductSettings":"[]","trackInventory":false,"sellingPlanType":"BUNDLE_LEVEL","clearCart":"ENABLED","minPrice":null,"maxPrice":null,"externalBuildABoxId":null,"variantVisibilityType":"SHOW_VARIANTS_AS_INDIVIDUAL","subTitle":null,"freeShipping":false,"themeType":"THEME_TWO","showBundleInProductPage":true,"combinedWithProductDiscount":true,"combinedWithShippingDiscount":true,"combinedWithOrderDiscount":true,"allowedTags":"compass-club","restrictTags":null,"selectionType":"FLEXIBLE","bundleHtml":null,"discountedVariants":"[]","allowedCountries":null,"appliesOn":"BOTH","purchaseRequirement":"NO_REQUIREMENT","productDiscountType":"EACH_PRODUCT","countrySelectionType":"ALL_COUNTRY","discountApplyApproach":"SHOPIFY_DISCOUNT_FUNCTION","discountedProductChooseType":"CHOOSE_ALL","internalName":"Compass Club Free Shipping","sections":"[]","limitToUsePerCustomer":null,"discountedVariantSelectionLimit":null,"hideOneTimePurchase":false,"hideSubscriptionPurchase":false,"maxOrderAmount":null,"collectionData":null,"productSelectionType":"PRODUCT","tag":"CC-Returning","productChooseType":"CHOOSE_ALL","variantSelectionLimit":null,"discountTargetType":"VARIANT","enableSubscription":false,"subscriptionWidgetPosition":"BELOW","subscribeTitle":"Subscribe and Save","subscribeSubtitle":"Delivered Monthly","subscriptionPreselected":false,"getYAppliesOn":"BOTH","announcementBarMessage":null,"automaticDiscountNodeId":null,"recurringCycleLimit":0,"automaticShippingDiscountNodeId":"gid://shopify/DiscountAutomaticNode/1725788717422","scheduledBundleRule":false,"bundleActiveFrom":null,"bundleActiveTo":null,"bundleSubType":null,"discountAppliesOn":"PER_ORDER","layoutType":"LAYOUT_ONE","style":"{\"tierFullPriceColor\":\"#1e293b\",\"tierFreeGiftTitleFontSize\":13,\"tierUpsellTitleFontSize\":13,\"primaryColor\":\"#000000\",\"tierSubTitleFontSize\":13,\"otherProductsModalFullPriceColor\":\"#555555\",\"primaryDisabledColor\":\"#333333\",\"cardHoverColor\":\"#f8fafc\",\"otherProductsModalPriceColor\":\"#000000\",\"otherProductsModalButtonTextColor\":\"#ffffff\",\"otherProductsButtonBackgroundColor\":\"#374151\",\"tierPriceFontSize\":20,\"tierUpsellSubTitleFontSize\":12,\"headingTextColor\":\"#000000\",\"badgesTextColor\":\"#ffffff\",\"blockTitleFontStyle\":\"BOLD\",\"tierTitleFontSize\":20,\"otherProductsProductTitleColor\":\"#374151\",\"subscriptionTitleTextColor\":\"#1e293b\",\"subscriptionSubTitleFontSize\":13,\"otherProductsImageSize\":40,\"saveBadgeBackgroundColor\":\"#d1fae5\",\"tierFreeGiftBackgroundColor\":\"#f1f5f9\",\"cardGap\":16,\"tierPriceFontStyle\":\"BOLD\",\"otherProductsModalOverlayColor\":\"#6b7280\",\"tierPriceColor\":\"#1e293b\",\"tierFreeGiftPriceFontSize\":14,\"otherProductsButtonTextColor\":\"#ffffff\",\"tierTitleFontStyle\":\"BOLD\",\"ruleUpsellSubTitleFontSize\":13,\"tierUnitLabelFontSize\":14,\"blockTitleFontSize\":14,\"otherProductsProductTitleSize\":16,\"productCardBackgroundColor\":\"#ffffff\",\"cardBackgroundColor\":\"#ffffff\",\"buttonBackgroundColor\":\"#000000\",\"bundlePageBackgroundColor\":\"#FAFAF9\",\"borderRadius\":8,\"tierUpsellBackgroundColor\":\"#e2e8f0\",\"ruleUpsellTitleTextColor\":\"#1e293b\",\"ruleUpsellSubTitleTextColor\":\"#1e293b\",\"tierUpsellSubTitleTextColor\":\"#1e293b\",\"primaryDisabledTextColor\":\"#ffffff\",\"otherProductsModalProductTitleTextSize\":14,\"otherProductsModalProductTitleColor\":\"#000000\",\"fieldDisabledBackgroundColor\":\"#D1D5DB\",\"otherProductsModalImageSize\":80,\"disabledTextColor\":\"#6B7280\",\"primaryHoverColor\":\"#000000\",\"saveBadgeTextColor\":\"#065f46\",\"tierUnitLabelFontStyle\":\"REGULAR\",\"cardBorderColor\":\"#cbd5e1\",\"ruleUpsellTitleFontSize\":15,\"selectedCardBackgroundColor\":\"#eff6ff\",\"tierFullPriceFontSize\":14,\"subscriptionSubTitleTextColor\":\"#1e293b\",\"selectedCardBorderColor\":\"#3b82f6\",\"tierTitleColor\":\"#1e293b\",\"tierFullPriceFontStyle\":\"REGULAR\",\"tierSubTitleFontStyle\":\"REGULAR\",\"secondaryTextColor\":\"#ffffff\",\"blockTitleColor\":\"#1e293b\",\"tierSubTitleColor\":\"#475569\",\"saveBadgeFontSize\":12,\"primaryTextColor\":\"#000000\",\"tierFreeGiftTextColor\":\"#1e293b\",\"tierFreeGiftTitleFontStyle\":\"BOLD\",\"tierUpsellTitleTextColor\":\"#1e293b\",\"tierFreeGiftPriceFontStyle\":\"REGULAR\",\"perRowItem\":\"THREE\",\"badgesBackgroundColor\":\"#ea580c\",\"otherProductsModalHeadingLabelColor\":\"#000000\",\"otherProductsModalButtonBackgroundColor\":\"#374151\",\"dedicatedSubscriptionLayout\":\"LAYOUT_ONE\",\"saveBadgeFontStyle\":\"REGULAR\",\"subscriptionTitleFontSize\":15,\"otherProductsModalProductPriceTextSize\":14}","labels":"{\"oneTimeTitle\":\"One Time Purchase\",\"otherProductsModalSubtitleLabel\":\"\",\"oneTimeSubtitle\":\"No Subscription\"}","upsells":null,"enableVolumeDiscountUpsell":false,"combos":null,"progressiveGift":null,"enableProgressiveGifts":false,"discountName":null,"shippingDiscountType":null}];
const customerTags = null;
let customerDiscountUsage = [];
let isLoggedIn = false;
const filteredDiscountBundles = Array.isArray(discountBundles) && discountBundles.length > 0 && discountBundles?.filter((bundle) => {
if (bundle?.status !== 'ACTIVE' || bundle?.bundleSubType === 'BUY_X_GET_Y') {
return false;
}
if ((bundle?.allowedTags || bundle?.restrictTags || bundle?.limitToUsePerCustomer > 0) && !isLoggedIn) {
return false;
}
if ((bundle?.allowedTags || bundle?.restrictTags) && isLoggedIn && isBundleRestrictedByDiscount(bundle, customerTags)) {
return false;
}
if (bundle?.limitToUsePerCustomer > 0 && isDiscountUsageLimitExceed(customerDiscountUsage, bundle)) {
return false;
}
if (bundle?.appliesOn === "ONE_TIME" && sellingPlanId != null) {
return false;
}
if (bundle?.appliesOn === "SUBSCRIPTION" && sellingPlanId === null) {
return false;
}
try {
const variantsString = bundle?.variants || '[]';
const variants = typeof variantsString === 'string' ? JSON.parse(variantsString) : variantsString;
const bundleCollections = JSON.parse(bundle?.collectionData || '[]');
return (Array.isArray(variants) && variants.some((variant) => variant && parseInt(variant?.variantId) === parseInt(variantId))) ||
(Array.isArray(bundleCollections) &&
bundleCollections?.length > 0 &&
bundleCollections.some(bundleCollection => collections.some(collection => collection?.id === bundleCollection?.id)))
} catch (e) {
console.error('Failed to parse JSON:', e);
return false;
}
}) || [];
const totalAmount = amount * quantity;
const lineItem = {variantId, quantity, amount, totalAmount };
const volumeDiscountBundles = processBundleRules(filteredDiscountBundles, 'VOLUME_DISCOUNT', ["variants", "tieredDiscount"]);
const discountedPricingBundles = processBundleRules(filteredDiscountBundles, 'DISCOUNTED_PRICING', ["variants"]);
let applicableDiscount = null;
const volumeDiscount = getApplicableTieredDiscount(volumeDiscountBundles, lineItem);
const pricingDiscount = getApplicablePercentOrFixedDiscount(discountedPricingBundles, lineItem);
if (volumeDiscount && pricingDiscount) {
applicableDiscount = getBestDiscount([volumeDiscount, pricingDiscount], lineItem);
} else {
applicableDiscount = volumeDiscount || pricingDiscount;
}
const discountAmount = applicableDiscount?.discountType === "PERCENTAGE" ? (totalAmount * applicableDiscount?.discount) / 100 : applicableDiscount?.discount;
const discountedPrice = applicableDiscount?.discountType === "PERCENTAGE" ? (totalAmount - discountAmount) : ( totalAmount - applicableDiscount?.discount);
return {
variantId,
quantity,
amount,
totalAmount,
discountType: applicableDiscount?.discountType,
discountValue: applicableDiscount?.discount,
discountAmount,
discountedPrice: !isNaN(discountedPrice) ? discountedPrice : undefined,
discountConfigure: applicableDiscount?.appliesOn
};
};
if (_ABConfig?.bundle_setting?.enableGa4CrossDomainTracking === true) {
(function () {
const params = new URLSearchParams(window.location.search);
const gl = params.get('_gl');
if (gl) {
sessionStorage.setItem('_ab_ga4_gl', gl);
}
const saved = sessionStorage.getItem('_ab_ga4_gl');
document.addEventListener('DOMContentLoaded', function () {
const links = document.querySelectorAll('a[href*="/apps/bundles/bb/"]');
links.forEach(function (link) {
const url = new URL(link.href);
if (saved) url.searchParams.set('_gl', saved);
link.href = url.toString();
});
});
})();
}