import { isCartPage, isProductPage, trackEvent, currencyIsSet, setProductsCurrency, getQuantity, getSelectedVariant, redirectToProductPage, areCustomFieldsEmpty, buildPropertiesFromCustomFields, addDiscountToCart, } from "./helpers.js"; import { checkCartRules, checkPageRules, currentProductPageProductID, doesCartContainOffer, fetchCart, getCartToken, getItemsInCart, isOfferAlreadyAccepted, pageSatisfiesOfferConditions, removeInvalidOffers, setGeoOffers } from "./rules.js"; import { disableCta, updateOfferWithAutopilotData, createContainer, createDismissOffer, createTitle, createCarouselArrows, createPoweredBy, addCSSToPage, showSlides, disableButtonShowSpinner, createSubscriptionElements, createProductImage, createProductLinkWithChildren, createProductInfoElements, createCustomFields, createVariantsWrapper, createSingleVariant, createQuantitySelector, createCtaCSS, } from './domHelpers.js'; (async function () { let theme_data = JSON.parse(icu_theme_app_data_ajax || '{}'); let theme_check = theme_data?.theme_app_extension || {}; let offers = theme_data?.offers || []; let collections = theme_data?.collections || []; let offer = {}; let shopifyDomain = ''; let offerSettings = theme_data?.offer_settings || {}; let abTestVersion = 'a'; let cFields = []; let isAnAjaxCall = false; let page = 1; let product = {}; let offerShown = false; let ajaxOfferShown = false; let offerShownID = -1; let ajaxOfferShownID = -1; let my_offers = []; let currentProductId = -1; const checkoutButton = document.querySelector('.cart__checkout-button') || document.querySelector('[name="checkout"]'); if (checkoutButton) { checkoutButton.addEventListener('click', () => { if (offers.length > 0) { if (Shopify?.shop === 'apptestytest.myshopify.com') { fetch(`${window.Shopify.routes.root}cart.js`, { method: 'GET', headers: { 'Content-Type': 'application/json' }, }) .then(resp => resp.json()) .then((data) => { console.log(data) if (data.item_count > 0 && data.items.some(item => item.properties["_icu"] === "_icu")) { let cartToken = getCartToken(); trackEvent('checkout', offers[0].id, abTestVersion, isAnAjaxCall, cartToken); return true; } else { console.log("Error while fetching cart data", data); return false; } }); } else { trackEvent('checkout', offers[0].id, abTestVersion, isAnAjaxCall); } } }); } const setGlobalVariables = (off, shop) => { offer = off; shopifyDomain = shop; if (off.uses_ab_test) { abTestVersion = Math.floor(Math.random() * 2) === 0 ? 'a' : 'b'; } cFields = [ { name: off.custom_field_name, id: 'icu-pcf1', placeholder: off.custom_field_placeholder, show_field: off.show_custom_field, required: off.custom_field_required }, { name: off.custom_field_2_name, id: 'icu-pcf2', placeholder: off.custom_field_2_placeholder, show_field: off.show_custom_field && off.custom_field_2_name && off.custom_field_2_name !== '', required: off.custom_field_2_required }, { name: off.custom_field_3_name, id: 'icu-pcf3', placeholder: off.custom_field_3_placeholder, show_field: off.show_custom_field && off.custom_field_3_name && off.custom_field_3_name !== '', required: off.custom_field_3_required } ] }; const createSpinner = (off, ctaContainer, addAjax) => { let cartButton; if (off.show_spinner) { cartButton = document.createElement('button'); if (abTestVersion === 'b' && off.uses_ab_test && off?.cta_b !== '') { cartButton.innerHTML = off.cta_b; } else { cartButton.innerHTML = off.cta_a; } } else { cartButton = document.createElement('input'); if (abTestVersion === 'b' && off.uses_ab_test && off?.cta_b !== '') { cartButton.value = off.cta_b; } else { cartButton.value = off.cta_a; } } cartButton.type = 'submit'; cartButton.name = 'add'; cartButton.className = 'bttn product-price'; if (Shopify.designMode) { cartButton.onclick = (e) => e.preventDefault(); } else { cartButton.onclick = async (e) => await addToCart(e, addAjax); } createCtaCSS(cartButton, off); ctaContainer.appendChild(cartButton); } const createAddToCart = (off, addAjax) => { const ctaContainer = document.createElement('form'); ctaContainer.action = off.shop.path_to_cart; ctaContainer.method = 'post'; ctaContainer.id = `${addAjax ? 'ajax-' : ''}product-actions-${product.id}-offer-${off.id}`; if (off.show_custom_field) { if (cFields.length === 0) { cFields = [ { name: off.custom_field_name, id: 'icu-pcf1', placeholder: off.custom_field_placeholder, show_field: off.show_custom_field, required: off.custom_field_required }, { name: off.custom_field_2_name, id: 'icu-pcf2', placeholder: off.custom_field_2_placeholder, show_field: off.show_custom_field && off.custom_field_2_name && off.custom_field_2_name !== '', required: off.custom_field_2_required }, { name: off.custom_field_3_name, id: 'icu-pcf3', placeholder: off.custom_field_3_placeholder, show_field: off.show_custom_field && off.custom_field_3_name && off.custom_field_3_name !== '', required: off.custom_field_3_required } ] } cFields.map(cField => { if (cField.show_field) { ctaContainer.appendChild(createCustomFields(cField.name, cField.placeholder, cField.id, product)); } }) } ctaContainer.appendChild(createVariantsWrapper(addAjax, off, product, offerSettings)); ctaContainer.appendChild(createQuantitySelector(off)); if (off.recharge_subscription_id) { createSubscriptionElements(ctaContainer, off); } createSpinner(off, ctaContainer, addAjax); return ctaContainer; } const createNudgeWrapperWithChildren = (off, variantsContainer, addAjax, prodIndex) => { let parentWrapper; if (off.multi_layout === 'compact') { const nudgeWrapper = document.createElement('div'); nudgeWrapper.className = 'nudge-wrapper'; nudgeWrapper.style.textAlign = 'center'; parentWrapper = nudgeWrapper; } else { const productWrapper = document.createElement('div'); if (prodIndex === 0) { productWrapper.className = 'product-wrapper fade active'; } else { productWrapper.className = 'product-wrapper fade'; } parentWrapper = productWrapper } if (off.show_product_image) { parentWrapper.appendChild(createProductImage(off, product, addAjax)); } if (off.link_to_product) { createProductLinkWithChildren(product, addAjax, off, parentWrapper); } else { createProductInfoElements(parentWrapper, addAjax, off, product); } if (off.multi_layout !== 'compact') { let detailsContainer = parentWrapper.querySelector('.details'); if (detailsContainer) detailsContainer.appendChild(createAddToCart(off, addAjax)) } else { parentWrapper.appendChild(createAddToCart(off, addAjax)); } variantsContainer.appendChild(parentWrapper); } const createVariantsContainerWithChildren = (off, addAjax) => { const variantsContainer = document.createElement('div'); if (off.multi_layout === 'compact') { variantsContainer.className = 'icu-offer-items variants'; } else { variantsContainer.className = 'offer-collection'; } off.offerable_product_details.map((prod, prodIndex) => { product = prod; createNudgeWrapperWithChildren(off, variantsContainer, addAjax, prodIndex); }); return variantsContainer; } const createOffer = async (off, offerSettings) => { const nudgeContainer = createContainer(off); if (off.show_nothanks) { nudgeContainer.appendChild(createDismissOffer()); } let offer_title = createTitle(off, abTestVersion); if (offer_title) nudgeContainer.appendChild(offer_title); nudgeContainer.appendChild(createVariantsContainerWithChildren(off)); addCSSToPage(off, offerSettings); let nudgeOfferList = document.querySelector('#nudge-offer-list'); if (!nudgeOfferList) { nudgeOfferList = document.createElement('div'); nudgeOfferList.id = 'nudge-offer-list'; } let customNudgeParent; if ((isCartPage() && theme_check.cart_block) || (isProductPage() && theme_check.product_block)) { if (block_selector && block_action) { customNudgeParent = document.querySelector(block_selector); if (customNudgeParent) { const icuNotice = document.querySelector('.icu-notice'); if (icuNotice) { nudgeOfferList.replaceChildren(icuNotice, nudgeContainer) } else { nudgeOfferList.replaceChildren(nudgeContainer) } customNudgeParent[block_action](nudgeOfferList) } } } let nudgeParent = document.querySelector('#nudge-offer-listings'); if (!customNudgeParent) { if (nudgeParent) { nudgeOfferList.replaceChildren(nudgeContainer); nudgeParent.replaceChildren(nudgeOfferList); } } if (off.multi_layout === 'carousel') { createCarouselArrows(nudgeContainer, false); showSlides(1); } if (off.show_powered_by) { nudgeContainer.appendChild(createPoweredBy(off)); } } const createAjaxOffer = async (off, offerSettings) => { let ajaxNudgeDrawer = document.querySelector('#nudge-offer-drawer-icu') const ajaxNudgeContainer = createContainer(off, true); if (off.show_nothanks) { ajaxNudgeContainer.appendChild(createDismissOffer(true)); } let offer_title = createTitle(off, abTestVersion); if (offer_title) ajaxNudgeContainer.appendChild(offer_title); ajaxNudgeContainer.appendChild(createVariantsContainerWithChildren(off, true)); addCSSToPage(off, offerSettings); if (off.show_powered_by) { ajaxNudgeContainer.appendChild(createPoweredBy(off)); } const cartForms = document.querySelectorAll('[action="/cart"]:not([id*="product-actions"]):not(main [action="/cart"])'); const prestigeThemes = document.querySelector('.prestige--v4 .Cart.Drawer__Content .Drawer__Main .Drawer__Container'); const mockingBirdThemes = document.querySelector('.cart-drawer__line-items'); const swymReady = document.querySelector('.swym-ready .cart__items'); const yokkoTheme = document.querySelector('.swym-ready .cart-drawer__items'); const miniatureTheme = document.querySelector('.cart-items'); const vetalandThemes = document.querySelector('#drawer-cart .cart__wrapper .cart__items'); const otherCartItems = document.querySelector('#CartDrawer .cart__items'); const magniCover = document.querySelector('#cart-notification-product') const bellaLunaThemes = document.querySelector('.previewCart'); const aiababyThemes = document.querySelector('.mini-cart__line-item'); const hydrateTheme = document.querySelector('#upCart .upcart-products-section'); const freedomResearchTheme = document.querySelector('.t4s-minicart-group-btns'); const happyVibesTheme = document.querySelector('.yv_side_drawer_body .cart-items-wrapper'); const majykTheme = document.querySelectorAll('header .cart-container [action="/cart"]:not([id*="product-actions"]):not(main [action="/cart"])') const silklyTheme = document.querySelector('#CartDrawerForm .drawer__inner .drawer__footer'); const oprimazeTheme = document.querySelector('#cart.mini-cart .mini-cart__inner .mini-cart__footer'); const nameAnderTheme = document.querySelector('#cart-drawer.cart-drawer.drawer .cart-drawer__items'); const nutriliTheme = document.querySelector('#CartDrawer #CartDrawerForm .drawer__scrollable .cart__items'); const psGoodtimes = document.querySelector('#cartSlideoutAside .cart-drawer-form #cartSlideoutWrapper ul.cart-items'); const passengerClothingTheme = document.querySelector('#CartDrawer.cart-drawer .drawer__inner .cart-recommendations') const poppyseedTheme = document.querySelector('#cart-drawer .drawer__body .drawer__items'); const mauliTheme = document.querySelector('.cart-drawer .cart-drawer__content-upper .cart-item-list.cart-drawer__content-item') const caosbrandTheme = document.querySelector('.scd__wrapper .scd__content .scd__body .scd__items') let domain = Shopify.shop if (!ajaxNudgeDrawer && off.in_ajax_cart) { ajaxNudgeDrawer = document.createElement('div'); ajaxNudgeDrawer.id = 'nudge-offer-drawer-icu'; } if (ajaxNudgeDrawer) { if (ajax_selector && ajax_action) { const customNudgeParent = document.querySelector(ajax_selector); if (customNudgeParent) { customNudgeParent[ajax_action](ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } } else if (prestigeThemes) { prestigeThemes.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (mockingBirdThemes) { mockingBirdThemes.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (swymReady) { swymReady.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (yokkoTheme) { yokkoTheme.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (domain === 'minaturewellness.myshopify.com') { miniatureTheme.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (nutriliTheme) { nutriliTheme.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (silklyTheme) { silklyTheme.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (otherCartItems) { otherCartItems.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (magniCover) { magniCover.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (bellaLunaThemes) { bellaLunaThemes.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (vetalandThemes) { vetalandThemes.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (aiababyThemes) { aiababyThemes.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (hydrateTheme) { hydrateTheme.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (freedomResearchTheme) { freedomResearchTheme.before(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (happyVibesTheme) { happyVibesTheme.append(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (majykTheme?.length > 0) { majykTheme.forEach(form => { form.appendChild(ajaxNudgeDrawer); }) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (oprimazeTheme) { oprimazeTheme.append(ajaxNudgeDrawer); ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (nameAnderTheme) { nameAnderTheme.after(ajaxNudgeDrawer); ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (psGoodtimes) { psGoodtimes.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (passengerClothingTheme) { passengerClothingTheme.prepend(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (poppyseedTheme) { poppyseedTheme.appendChild(ajaxNudgeDrawer); ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (mauliTheme) { mauliTheme.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (caosbrandTheme) { caosbrandTheme.after(ajaxNudgeDrawer) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } else if (cartForms?.length > 0) { cartForms.forEach(form => { form.appendChild(ajaxNudgeDrawer); }) ajaxNudgeDrawer.replaceChildren(ajaxNudgeContainer); } } if (off.multi_layout === 'carousel') { createCarouselArrows(ajaxNudgeContainer, true); showSlides(1); } } const checkIfShownOfferIsStillValid = async (offerIdToCheck) => { let offerShown; if (offerIdToCheck !== -1) { offerShown = offers.find(off => off.id === offerIdToCheck) } if (offerShown) { const cartRules = await checkCartRules(offerShown, collections, currentProductId); const pageRules = await checkPageRules(offerShown, collections, currentProductId); const pageSatisfies = await pageSatisfiesOfferConditions(offerShown); if (offerShown.ruleset_type === "or") { if (!((cartRules || pageRules) && pageSatisfies)) { offerIdToCheck = -1 } } else { if (!((cartRules && pageRules) && pageSatisfies)) { offerIdToCheck = -1 } } } return offerIdToCheck } const checkOffersWhenPageUpdates = async () => { if (!offerSettings || Object.keys(offerSettings).length === 0) { const storedOfferSettings = localStorage.getItem(`offerSettings_${Shopify.shop}`); if (storedOfferSettings) { offerSettings = JSON.parse(storedOfferSettings); } } await fetchCart(offerSettings); let offersToRemoveFromCart = []; offerShownID = await checkIfShownOfferIsStillValid(offerShownID) ajaxOfferShownID = await checkIfShownOfferIsStillValid(ajaxOfferShownID) let itemsInCart = getItemsInCart(); let accepted_offers = localStorage.getItem(`accepted_offers_${Shopify.shop}`); if (accepted_offers) { accepted_offers = JSON.parse(accepted_offers); let offersToRemove = []; for (let acceptedOfferID of accepted_offers) { const acceptedOffer = offers.find(off => off.id === parseInt(acceptedOfferID)); if (acceptedOffer) { const products = acceptedOffer.offerable_product_shopify_ids; let productFoundStatus = false; for (let prodID of products) { const productFound = itemsInCart.find(item => item?.productID === prodID && item?.properties._icu); if (productFound) { productFoundStatus = true; } } if (!productFoundStatus && !offersToRemove.includes(acceptedOfferID)) { offersToRemove.push(acceptedOfferID); } } } offersToRemove = new Set(offersToRemove); accepted_offers = accepted_offers.filter(acceptedOffer => !offersToRemove.has(acceptedOffer)); localStorage.setItem(`accepted_offers_${Shopify.shop}`, JSON.stringify(accepted_offers)); } if (isProductPage()) { currentProductId = await currentProductPageProductID(); } for (let off of offers) { const cartRules = await checkCartRules(off, collections, currentProductId); const pageRules = await checkPageRules(off, collections, currentProductId); const pageSatisfies = await pageSatisfiesOfferConditions(off); if (off.ruleset_type === "or") { if ((cartRules || pageRules) && pageSatisfies) { let offerOnPage = document.getElementById(`nudge-offer-${off.id}`); let ajaxOfferOnPage = document.getElementById(`nudge-ajax-nudge-offer-${off.id}`); if (off.offerable_type === 'auto') { // offer is autopilot off.offerable_product_details = updateOfferWithAutopilotData(off); } if (offerSettings.has_shopify_multicurrency) { off.active_currency = currencyIsSet() ? Shopify.currency.active : "USD"; off.offerable_product_details = setProductsCurrency(off); } if (!offerOnPage) { if ( (off.in_product_page && isProductPage()) || (off.in_cart_page && isCartPage() && itemsInCart?.length > 0) ) { if (offerShownID === off.id || offerShownID === -1) { if (offerShownID === -1) offerShownID = off.id offerShown = true await createOffer(off, offerSettings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } } if (off.in_ajax_cart && !ajaxOfferOnPage && itemsInCart?.length > 0) { if (ajaxOfferShownID === off.id || ajaxOfferShownID === -1) { if (ajaxOfferShownID === -1) ajaxOfferShownID = off.id ajaxOfferShown = true await createAjaxOffer(off, offerSettings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } // only on the cart page if (isCartPage() && off.must_accept && (!(await doesCartContainOffer(off)) || !isOfferAlreadyAccepted(off))) { disableCta(); } } else { document.getElementById(`nudge-offer-${off.id}`)?.remove(); if (off.remove_if_no_longer_valid && !(cartRules || pageRules)) { offersToRemoveFromCart.push(off); } } } else { if ((cartRules && pageRules) && pageSatisfies) { let offerOnPage = document.getElementById(`nudge-offer-${off.id}`); let ajaxOfferOnPage = document.getElementById(`nudge-ajax-nudge-offer-${off.id}`); if (off.offerable_type === 'auto') { // offer is autopilot off.offerable_product_details = updateOfferWithAutopilotData(off); } if (offerSettings.has_shopify_multicurrency) { off.active_currency = currencyIsSet() ? Shopify.currency.active : "USD"; off.offerable_product_details = setProductsCurrency(off); } if (!offerOnPage) { if ( (off.in_product_page && isProductPage()) || (off.in_cart_page && isCartPage() && itemsInCart?.length > 0) ) { if (offerShownID === off.id || offerShownID === -1) { if (offerShownID === -1) offerShownID = off.id offerShown = true await createOffer(off, offerSettings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } } if (off.in_ajax_cart && !ajaxOfferOnPage && itemsInCart?.length > 0) { if (ajaxOfferShownID === off.id || ajaxOfferShownID === -1) { if (ajaxOfferShownID === -1) ajaxOfferShownID = off.id ajaxOfferShown = true await createAjaxOffer(off, offerSettings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } // only on the cart page if (isCartPage() && off.must_accept && (!(await doesCartContainOffer(off)) || !isOfferAlreadyAccepted(off))) { disableCta(); } } else { document.getElementById(`nudge-offer-${off.id}`)?.remove(); if (off.remove_if_no_longer_valid && !(cartRules && pageRules)) { offersToRemoveFromCart.push(off); } } } } removeInvalidOffers(offersToRemoveFromCart); if (itemsInCart.length === 0) { if (isCartPage()) { let offersToRemove = document.getElementsByClassName('nudge-offer'); for (let i = 0; i < offersToRemove.length; i++) { offersToRemove[i].remove(); } } else { let offersToRemove = document.getElementsByClassName('nudge-ajax'); for (let i = 0; i < offersToRemove.length; i++) { offersToRemove[i].remove(); } } } }; const listenForCartRequests = () => { if (Shopify?.shop === 'in-rosa.myshopify.com') { document.addEventListener('cartdrawer:opened', async () => { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); }); } if (Shopify?.shop === 'gse-bio.myshopify.com') { document.addEventListener('theme:cart:loaded', async () => { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); }); document.addEventListener('theme:cart:added', async () => { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); }); } else { (function (open) { XMLHttpRequest.prototype.open = function (method, url, async, user, pass) { this.addEventListener("readystatechange", async function () { if (this.readyState === 4 && this.status === 200) { let parser = document.createElement('a'); parser.href = this.responseURL || this._url; let path = parser.pathname; if (path[0] !== "/") { path = "/" + path; } if (Shopify.shop === 'e88e80-b7.myshopify.com' || Shopify.shop === 'kristy-2296.myshopify.com' || Shopify.shop === 'd8bd6b-84.myshopify.com' || Shopify.shop === 'despana-national.myshopify.com' || Shopify.shop === 'disneycouture.myshopify.com') { if ((path.includes('/change') || path.includes('/add')) && parser.search.indexOf("icu") === -1) { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); } } else if (path.includes('/cart') && parser.search.indexOf("icu") === -1) { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); } } }, false); open.call(this, method, url, async, user, pass); }; })(XMLHttpRequest.prototype.open); (function (ns, fetch) { if (typeof fetch !== 'function') return; ns.fetch = function () { let out = fetch.apply(this, arguments); let _args = arguments; out.then(async function (_response) { let parser = document.createElement('a'); parser.href = _args[0]; let path = parser.pathname; if (path[0] !== "/") { path = "/" + path; } const params = new URL(parser.href).searchParams; if (Shopify.shop === 'e88e80-b7.myshopify.com' || Shopify.shop === 'kristy-2296.myshopify.com' || Shopify.shop === 'd8bd6b-84.myshopify.com' || Shopify.shop === 'despana-national.myshopify.com' || Shopify.shop === 'disneycouture.myshopify.com') { if ((path.includes('/change') || path.includes('/add')) && parser.search.indexOf("icu") === -1) { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); } } else if ((path.includes('/cart') && parser.search.indexOf("icu") === -1) || ((Shopify.shop === 'best-honbay.myshopify.com') && params.get('section_id') === 'cart-drawer')) { isAnAjaxCall = true; await checkOffersWhenPageUpdates(); } }); return out; }; }(window, window.fetch)); // Immediately-invoked Function Expression } } const getOffers = async () => { if (isProductPage()) { currentProductId = await currentProductPageProductID(); } if (offers?.length !== 0) { my_offers = offers; let my_offer_settings = offerSettings localStorage.setItem(`offerSettings_${Shopify.shop}`, JSON.stringify(my_offer_settings)); let offersToRemoveFromCart = []; await fetchCart(my_offer_settings); const needsGeoOffers = offers.some(off => { if (off?.rules?.length > 0) { return off.rules.some(rule => rule?.rule_selector?.includes('location')) } return false; }); if (needsGeoOffers) { await setGeoOffers(); } for (let off of offers) { const cartRules = await checkCartRules(off, collections, currentProductId); const pageRules = await checkPageRules(off, collections, currentProductId); const pageSatisfies = await pageSatisfiesOfferConditions(off); if (off.ruleset_type === "or") { if ((cartRules || pageRules) && pageSatisfies) { setGlobalVariables(off, Shopify.shop); if (off.offerable_type === 'auto') { // offer is autopilot off.offerable_product_details = updateOfferWithAutopilotData(off); } if (offerSettings.has_shopify_multicurrency) { off.active_currency = currencyIsSet() ? Shopify.currency.active : "USD"; off.offerable_product_details = setProductsCurrency(off); } if ( (off.in_product_page && isProductPage()) || (off.in_cart_page && isCartPage() && getItemsInCart()?.length > 0) ) { if (!offerShown) { offerShown = true offerShownID = off.id await createOffer(off, my_offer_settings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } if (off.in_ajax_cart && getItemsInCart()?.length > 0) { if (!ajaxOfferShown) { ajaxOfferShown = true ajaxOfferShownID = off.id await createAjaxOffer(off, my_offer_settings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } // only on the cart page if (isCartPage() && off.must_accept && (!(await doesCartContainOffer(off)) || !isOfferAlreadyAccepted(off))) { disableCta(); } } else if (off.remove_if_no_longer_valid && !(cartRules || pageRules)) { offersToRemoveFromCart.push(off); } } else { if ((cartRules && pageRules) && pageSatisfies) { setGlobalVariables(off, Shopify.shop); if (off.offerable_type === 'auto') { // offer is autopilot off.offerable_product_details = updateOfferWithAutopilotData(off); } if (offerSettings.has_shopify_multicurrency) { off.active_currency = currencyIsSet() ? Shopify.currency.active : "USD"; off.offerable_product_details = setProductsCurrency(off); } if ( (off.in_product_page && isProductPage()) || (off.in_cart_page && isCartPage() && getItemsInCart()?.length > 0) ) { if (!offerShown) { offerShown = true offerShownID = off.id await createOffer(off, my_offer_settings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } if (off.in_ajax_cart && getItemsInCart()?.length > 0) { if (!ajaxOfferShown) { ajaxOfferShown = true ajaxOfferShownID = off.id await createAjaxOffer(off, my_offer_settings); if (!Shopify.designMode) { trackEvent('show', off.id, abTestVersion, isAnAjaxCall); } } } // only on the cart page if (isCartPage() && off.must_accept && (!(await doesCartContainOffer(off)) || !isOfferAlreadyAccepted(off))) { disableCta(); } } else if (off.remove_if_no_longer_valid && !(cartRules && pageRules)) { offersToRemoveFromCart.push(off); } } } if (Shopify.designMode) { let offers_for_product_pages = offers.filter(off => off.in_product_page).length; let offers_for_cart_page = offers.filter(off => off.in_cart_page).length; if ((offers_for_product_pages === 0 && isProductPage()) || (offers_for_cart_page === 0 && isCartPage())) { offer = { theme: 'custom', show_product_image: true, multi_layout: 'stack', id: 1, css_options: { main: { color: "#2B3D51", backgroundColor: "#ECF0F1", marginTop: '0px', marginBottom: '0px', borderStyle: 'none', borderWidth: 0, borderRadius: 0, }, text: { fontFamily: "Arial", fontSize: '16px', }, button: { color: "#FFFFFF", backgroundColor: "#2B3D51", fontFamily: "Arial", fontSize: "16px", borderRadius: 0, }, }, show_product_price: true, show_nothanks: false, text_a: 'Would you like to add a Test Product?', link_to_product: false, show_compare_at_price: false, offerable_product_shopify_ids: [], show_quantity_selector: true, show_spinner: false, cta_a: 'Add to Cart', shop: { path_to_cart: '/' }, offerable_product_details: [ { id: 1, title: 'Test Product', medium_image_url: 'https://assets.incartupsell.com/images/billing-ICU-Logo-Small.png', available_json_variants: [ { unparenthesized_price: '$99.99', currencies: [ { label: 'USD', price: '99.99', compare_at_price: '99.99' } ] } ] } ] } await createOffer(offer, my_offer_settings); } } removeInvalidOffers(offersToRemoveFromCart); } else { if (Shopify.designMode) { offer = { theme: 'custom', show_product_image: true, multi_layout: 'stack', id: 1, css_options: { main: { color: "#2B3D51", backgroundColor: "#ECF0F1", marginTop: '0px', marginBottom: '0px', borderStyle: 'none', borderWidth: 0, borderRadius: 0, }, text: { fontFamily: "Arial", fontSize: '16px', }, button: { color: "#FFFFFF", backgroundColor: "#2B3D51", fontFamily: "Arial", fontSize: "16px", borderRadius: 0, }, }, show_product_price: true, show_nothanks: false, text_a: 'Would you like to add a Test Product?', link_to_product: false, show_compare_at_price: false, offerable_product_shopify_ids: [], show_quantity_selector: true, show_spinner: false, cta_a: 'Add to Cart', shop: { path_to_cart: '/' }, offerable_product_details: [ { id: 1, title: 'Test Product', medium_image_url: 'https://assets.incartupsell.com/images/billing-ICU-Logo-Small.png', available_json_variants: [ { unparenthesized_price: '$99.99', currencies: [ { label: 'USD', price: '99.99', compare_at_price: '99.99' } ] } ] } ] } await createOffer(offer, {}); } } } if (theme_check.theme_app_completed && (theme_check.activated === null || theme_check.activated)) { if (Shopify.designMode) { // setInterval(() => { fetch(`/apps/in-cart-upsell/theme_app_check`) .then(response => response.json()) .then(async () => { listenForCartRequests(); await getOffers(); }) // }, 1000); listenForCartRequests(); await getOffers(); console.log('InCartUpsell Loaded Theme Check'); } else { console.log('InCartUpsell Loaded'); listenForCartRequests(); await getOffers(); } } else { if (Shopify.designMode) { console.log('InCartUpsell Loaded Theme Check'); fetch(`/apps/in-cart-upsell/theme_app_check`) .then(response => response.json()) .then(async () => { listenForCartRequests(); await getOffers(); }) } } const addToCart = async (e, addAjax) => { e.preventDefault() let custom_fields = {}; let ctaContainer = e.target.parentElement; if (!ctaContainer || ctaContainer?.id === '') { ctaContainer = e.target.closest('form'); } let quantityToAdd = getQuantity(ctaContainer); let selectedShopifyVariant = getSelectedVariant(ctaContainer); let ctaContainerIDSplit = ctaContainer.id.split('-offer-'); let offerID = ctaContainerIDSplit[1]; if (offerID) { let currentOffer = offers.find(off => off.id === parseInt(offerID)); let redirect = currentOffer?.checkout_after_accepted ? '/checkout' : '/cart'; console.log('Current offer', currentOffer); if (currentOffer?.discount_enabled) { console.log('Creating Offer Discount') const discountResponse = await fetch('/apps/in-cart-upsell/shopify_discounts?' + new URLSearchParams({ shop: Shopify.shop, discount_minimum_condition_value: currentOffer.discount_minimum_condition_value, discount_type: currentOffer.discount_type, discount_value: currentOffer.shopify_discount_value, product_ids: currentOffer.included_variants, combine_product_discounts: currentOffer.combine_product_discounts, combine_orders_discounts: currentOffer.combine_orders_discounts, combine_shipping_discounts: currentOffer.combine_shipping_discounts, discount_applied_once_per_order: currentOffer.discount_applied_once }).toString(), { method: 'GET', headers: { 'Content-Type': 'application/json', } }); const discount = await discountResponse.json(); if (discount) { await addDiscountToCart(discount.discount_code); } } if (currentOffer.redirect_to_product) { e.preventDefault(); redirectToProductPage(currentOffer, selectedShopifyVariant); return false; } else { let cartItems = { items: [{ id: selectedShopifyVariant, quantity: quantityToAdd, properties: {} }] }; if (currentOffer.show_custom_field) { if (areCustomFieldsEmpty(ctaContainer.id, cFields).includes(true)) { return false; } custom_fields = buildPropertiesFromCustomFields(ctaContainer.id, cFields); cartItems.items[0].properties = { ...custom_fields }; } disableButtonShowSpinner(ctaContainer, offerSettings); if (currentOffer.discount_code) { await addDiscountToCart(currentOffer.discount_code); } if (offerSettings.has_recharge && typeof (currentOffer.recharge_subscription_id) !== "undefined") { cartItems.items[0].properties.shipping_interval_frequency = currentOffer.interval_frequency; cartItems.items[0].properties.shipping_interval_unit_type = currentOffer.interval_unit; cartItems.items[0].properties.subscription_id = currentOffer.recharge_subscription_id; } cartItems.items[0].properties._icu = "_icu"; let cartToken = getCartToken(); trackEvent('click', currentOffer.id, abTestVersion, isAnAjaxCall, selectedShopifyVariant, cartToken); fetch( `${window.Shopify.routes.root}cart/add.js?icu=1`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(cartItems), } ) .then(resp => resp.json()) .then(() => { if (currentOffer.show_spinner) { let btn = document.querySelector(`#${ctaContainer.id} .bttn`); if (abTestVersion === 'b') { btn.innerHTML = currentOffer.cta_b; } else { btn.innerHTML = currentOffer.cta_a; } btn.disabled = false; } let acceptedOffers = localStorage.getItem(`accepted_offers_${Shopify.shop}`); if (acceptedOffers) { acceptedOffers = JSON.parse(acceptedOffers); } else { acceptedOffers = []; } if (!acceptedOffers.includes(offerID)) { acceptedOffers.push(offerID); localStorage.setItem(`accepted_offers_${Shopify.shop}`, JSON.stringify(acceptedOffers)); } if (!offerSettings || Object.keys(offerSettings).length === 0) { const storedOfferSettings = localStorage.getItem(`offerSettings_${Shopify.shop}`); if (storedOfferSettings) { offerSettings = JSON.parse(storedOfferSettings); } } if (addAjax && ajax_block_refresh_code) { try { const ajaxCleaned = ajax_block_refresh_code.replace('InCartUpsell.prototype.findOfferWhenReady();', '') eval(ajaxCleaned) } catch (err) { window.location.href = redirect; } } else if (!addAjax && isCartPage() && theme_check.cart_block && cart_block_refresh_code) { try { const cartCleaned = cart_block_refresh_code.replace('InCartUpsell.prototype.findOfferWhenReady();', '') eval(cartCleaned) } catch (err) { window.location.href = redirect; } } else if (!addAjax && isProductPage() && theme_check.product_block && product_block_refresh_code) { try { const productCleaned = product_block_refresh_code.replace('InCartUpsell.prototype.findOfferWhenReady();', '') eval(productCleaned) } catch (err) { window.location.href = redirect; } } else if (offerSettings.ajax_refresh_code?.length > 0 && addAjax) { try { const ajaxCleaned = offerSettings.ajax_refresh_code.replace('InCartUpsell.prototype.findOfferWhenReady();', ''); eval(ajaxCleaned) } catch (err) { window.location.href = redirect; } } else { window.location.href = redirect; } }); } } } })();