1import{Component}from"@theme/component";import{morphSection}from"@theme/section-renderer";import{DiscountUpdateEvent}from"@theme/events";import{fetchConfig}from"@theme/utilities";import{cartPerformance}from"@theme/performance";import{addGifts}from"@theme/custom-gwp-gift-add";import{applyGwpDiscount}from"@theme/custom-gwp-discount-guard";class CartDiscount extends Component{requiredRefs=["cartDiscountError","cartDiscountErrorDiscountCode","cartDiscountErrorShipping"];#activeFetch=null;#isApplyingPromotion=!1;connectedCallback(){super.connectedCallback(),this.addEventListener("input",this.#handleInput)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("input",this.#handleInput),this.#activeFetch?.abort()}#handleInput=event=>{const target=event.target;!(target instanceof HTMLInputElement)||target.name!=="discount"||this.#clearCustomFeedback()};#setButtonLoading(isLoading){const button=this.refs.cartDiscountApplyButton??this.querySelector(".cart-discount__button");if(!(button instanceof HTMLButtonElement))return;button.classList.toggle("is-loading",isLoading),button.disabled=isLoading,button.setAttribute("aria-busy",isLoading?"true":"false");const spinner=button.querySelector(".cart-discount__button-spinner");spinner instanceof HTMLElement&&(spinner.hidden=!isLoading)}#showCustomFeedback(type,message){const feedback=this.refs.cartDiscountFeedback;if(!(feedback instanceof HTMLElement))return;this.#hideNativeErrors();const textEl=feedback.querySelector(".cart-discount__feedback-text");textEl instanceof HTMLElement&&(textEl.textContent=message),feedback.classList.remove("hidden","cart-discount__feedback--error","cart-discount__feedback--success","cart-discount__feedback--info"),feedback.classList.add(`cart-discount__feedback--${type}`),feedback.classList.remove("hidden")}#getTranslation(key){const value=(typeof Theme<"u"?Theme:{})?.translations?.[key];return typeof value=="string"?value:""}#clearCustomFeedback(){const feedback=this.refs.cartDiscountFeedback;if(!(feedback instanceof HTMLElement))return;feedback.classList.add("hidden"),feedback.classList.remove("cart-discount__feedback--error","cart-discount__feedback--success","cart-discount__feedback--info");const textEl=feedback.querySelector(".cart-discount__feedback-text");textEl instanceof HTMLElement&&(textEl.textContent="")}#hideNativeErrors(){const{cartDiscountError,cartDiscountErrorDiscountCode,cartDiscountErrorShipping}=this.refs;cartDiscountError?.classList.add("hidden"),cartDiscountErrorDiscountCode?.classList.add("hidden"),cartDiscountErrorShipping?.classList.add("hidden")}#showInfluencerError(key){const{cartDiscountError,cartDiscountErrorDiscountCode}=this.refs,message=this.#getTranslation(key);this.#clearCustomFeedback(),cartDiscountError?.classList.remove("hidden"),cartDiscountErrorDiscountCode?.classList.remove("hidden"),cartDiscountErrorDiscountCode instanceof HTMLElement&&message&&(cartDiscountErrorDiscountCode.textContent=message)}#isInfluencerDiscountApplied(influencer,existingDiscounts){const linkedCodes=[influencer.discountOneTime,influencer.discountSubscription].filter(Boolean).map(c=>String(c).toLowerCase());return linkedCodes.length===0?!1:existingDiscounts.some(existing=>linkedCodes.includes(String(existing).toLowerCase()))}#createAbortController(){this.#activeFetch&&this.#activeFetch.abort();const abortController=new AbortController;return this.#activeFetch=abortController,abortController}applyDiscount=async event=>{event.preventDefault(),event.stopPropagation();const form=event.target;if(!(form instanceof HTMLFormElement))return;const discountCode=form.querySelector('input[name="discount"]');if(!(discountCode instanceof HTMLInputElement)||typeof this.dataset.sectionId!="string")return;const discountCodeValue=discountCode.value.trim();if(!discountCodeValue){this.#showCustomFeedback("error",this.#getTranslation("influencer_code_empty"));return}if(this.#isApplyingPromotion)return;this.#isApplyingPromotion=!0,this.#clearCustomFeedback(),this.#setButtonLoading(!0),this.#showCustomFeedback("info",this.#getTranslation("influencer_code_applying"));const abortController=this.#createAbortController();try{const __offers=window.__influencerOffers||[],influencer=__offers.find?.(o=>o&&typeof o.code=="string"&&o.code.toLowerCase()===discountCodeValue.toLowerCase());if(influencer){this.#hideNativeErrors();const gifts=Array.isArray(influencer.gifts)?influencer.gifts:[],existingDiscounts2=this.#existingDiscounts();if(this.#isInfluencerDiscountApplied(influencer,existingDiscounts2)){discountCode.value="",this.#showCustomFeedback("success",this.#getTranslation("influencer_code_already_applied"));return}try{const cart=await fetch("/cart.js",{headers:{Accept:"application/json"},signal:abortController.signal}).then(r=>r.json()),items=Array.isArray(cart&&cart.items)?cart.items:[];let nonGwpTotal=0;for(let i=0;i<items.length;i++){const it=items[i]||{},props=it.properties||{},requiresShipping=it.requires_shipping!==!1,isLoyaltyProduct=!!(props&&props.__lion_sfp_id);if(!(props&&props._is_gwp==="true")&&requiresShipping&&!isLoyaltyProduct){const lp=Number(it.line_price||0);Number.isNaN(lp)||(nonGwpTotal+=lp)}}try{const threshold=Number(influencer&&influencer.threshold||0)||0;if(threshold>0&&nonGwpTotal<threshold){this.#showInfluencerError("influencer_code_not_eligible_cart_total");return}}catch{}const inCartProductIds=items.map(it=>Number(it&&it.product_id||0)).filter(n=>!Number.isNaN(n)&&n>0),eligProducts=influencer.eligProducts;if(Array.isArray(eligProducts)&&eligProducts.length){const eligSkus=Array.isArray(influencer.eligSkus)&&influencer.eligSkus.length?influencer.eligSkus:[];let ok;if(eligSkus.length>0?ok=items.some(it=>{const pid=Number(it&&it.product_id||0),sku=String(it&&it.sku||"").trim().toUpperCase();return pid>0&&eligProducts.includes(pid)&&sku&&eligSkus.includes(sku)}):ok=eligProducts.some(pid=>inCartProductIds.includes(Number(pid))),!ok){this.#showInfluencerError("influencer_code_not_eligible_items");return}}if(Array.isArray(influencer.eligCollectionProducts)&&influencer.eligCollectionProducts.length&&!influencer.eligCollectionProducts.some(pid=>inCartProductIds.includes(Number(pid)))){this.#showInfluencerError("influencer_code_not_eligible_items");return}if(influencer.scheduleStart||influencer.scheduleEnd){const fmt=new Intl.DateTimeFormat("en-CA",{timeZone:"Europe/London",hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),parts=Object.fromEntries(fmt.formatToParts(new Date).map(p=>[p.type,p.value])),now=`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}`,norm=(s,end2)=>{if(!s)return;const parts2=String(s).trim().replace(" ","T").replace(/Z$/i,"").replace(/[+-]\d{2}:?\d{2}$/i,"").split("T"),date=parts2[0]||"";let time=parts2[1]||(end2?"23:59":"00:00");if(/^\d{2}:\d{2}:\d{2}$/.test(time)&&(time=time.slice(0,5)),!!/^\d{4}-\d{2}-\d{2}$/.test(date)&&/^\d{2}:\d{2}$/.test(time))return`${date}T${time}`},start=norm(influencer.scheduleStart,!1),end=norm(influencer.scheduleEnd,!0);if(start&&now<start||end&&now>end||start&&end&&start>end){this.#showInfluencerError("influencer_code_not_active");return}}}catch{}if(gifts.length>0){let allowStacking=!1;try{const T=typeof Theme<"u"?Theme:{};allowStacking=!!(T&&T.flags&&T.flags.allowGwpInfluencerStacking===!0)}catch{allowStacking=!1}if(!allowStacking)try{const cart=await fetch("/cart.js",{headers:{Accept:"application/json"},signal:abortController.signal}).then(r=>r.json()),items=Array.isArray(cart&&cart.items)?cart.items:[];let hasAnyGift=!1;for(let i=0;i<items.length;i++){const props=(items[i]||{}).properties||{};if(props&&props._is_gwp==="true"){hasAnyGift=!0;break}}if(hasAnyGift){this.#showInfluencerError("influencer_code_one_gift_only");return}}catch{this.#showInfluencerError("influencer_code_one_gift_only");return}const cartBeforeAdd=await fetch("/cart.js",{headers:{Accept:"application/json"},signal:abortController.signal}).then(r=>r.json()),itemsBeforeAdd=Array.isArray(cartBeforeAdd&&cartBeforeAdd.items)?cartBeforeAdd.items:[];if(this.#cartHasInfluencerGift(itemsBeforeAdd,discountCodeValue)){discountCode.value="",this.#showCustomFeedback("success",this.#getTranslation("influencer_code_gift_already_added"));return}const gwpGroup=this.#influencerGwpGroup(discountCodeValue),{added}=await addGifts(gifts.map(id=>({id:Number(id),quantity:1,properties:{_is_gwp:"true",_gwp_group:gwpGroup}})),abortController.signal);if(added.length===0){this.#showInfluencerError("influencer_code_gifts_unavailable");return}let chosenCode="";try{const cart=await fetch("/cart.js",{headers:{Accept:"application/json"},signal:abortController.signal}).then(r=>r.json());chosenCode=(Array.isArray(cart&&cart.items)?cart.items:[]).some(it=>it&&(it.selling_plan_allocation||it.selling_plan_id||it.properties&&(it.properties.selling_plan||it.properties._rc)))?influencer.discountSubscription||influencer.discountOneTime||"":influencer.discountOneTime||""}catch{chosenCode=influencer.discountOneTime||""}const discountOutcome=await applyGwpDiscount(chosenCode,gwpGroup,abortController.signal);if(discountOutcome!=="applied"){discountOutcome==="rejected"?this.#showInfluencerError("influencer_code_not_active"):this.#handleDiscountError("discount_code");return}try{sessionStorage.setItem(`inf-auto-${discountCodeValue.toLowerCase()}`,"1")}
1catch{}discountCode.value="",document.location.reload();return}else{this.#showInfluencerError(influencer.giftsConfigured?"influencer_code_gifts_unavailable":"influencer_code_no_gifts_configured");return}}const existingDiscounts=this.#existingDiscounts();if(existingDiscounts.some(code=>code.toLowerCase()===discountCodeValue.toLowerCase())){discountCode.value="",this.#showCustomFeedback("success",this.#getTranslation("influencer_code_already_applied"));return}this.#hideNativeErrors();const config=fetchConfig("json",{body:JSON.stringify({discount:[...existingDiscounts,discountCodeValue].join(","),sections:[this.dataset.sectionId]})}),data=await(await fetch(Theme.routes.cart_update_url,{...config,signal:abortController.signal})).json();if(data.discount_codes.find(discount=>discount.code===discountCodeValue&&discount.applicable===!1)){discountCode.value="",__offers.length>0?this.#showCustomFeedback("error",this.#getTranslation("influencer_code_not_recognized")):(this.#clearCustomFeedback(),this.#handleDiscountError("discount_code"));return}const newHtml=data.sections[this.dataset.sectionId],section=new DOMParser().parseFromString(newHtml,"text/html").getElementById(`shopify-section-${this.dataset.sectionId}`),discountCodes=section?.querySelectorAll(".cart-discount__pill")||[];if(section){const codes=Array.from(discountCodes).map(element=>element instanceof HTMLLIElement?element.dataset.discountCode:null).filter(Boolean);if(codes.length===existingDiscounts.length&&codes.every(code=>existingDiscounts.includes(code))&&data.discount_codes.find(discount=>discount.code===discountCodeValue&&discount.applicable===!0)){this.#clearCustomFeedback(),this.#handleDiscountError("shipping"),discountCode.value="";return}}this.#clearCustomFeedback(),document.dispatchEvent(new DiscountUpdateEvent(data,this.id)),morphSection(this.dataset.sectionId,newHtml)}catch{}finally{this.#isApplyingPromotion=!1,this.#setButtonLoading(!1),this.#activeFetch=null,cartPerformance.measureFromEvent("discount-update:user-action",event)}};removeDiscount=async event=>{if(event.preventDefault(),event.stopPropagation(),event instanceof KeyboardEvent&&event.key!=="Enter"||!(event instanceof MouseEvent)||!(event.target instanceof HTMLElement)||typeof this.dataset.sectionId!="string")return;const pill=event.target.closest(".cart-discount__pill");if(!(pill instanceof HTMLLIElement))return;const discountCode=pill.dataset.discountCode;if(!discountCode)return;const existingDiscounts=this.#existingDiscounts(),index=existingDiscounts.indexOf(discountCode);if(index===-1)return;existingDiscounts.splice(index,1);const abortController=this.#createAbortController();try{const config=fetchConfig("json",{body:JSON.stringify({discount:existingDiscounts.join(","),sections:[this.dataset.sectionId]})}),data=await(await fetch(Theme.routes.cart_update_url,{...config,signal:abortController.signal})).json();document.dispatchEvent(new DiscountUpdateEvent(data,this.id)),morphSection(this.dataset.sectionId,data.sections[this.dataset.sectionId])}catch{}finally{this.#activeFetch=null}};#handleDiscountError(type){const{cartDiscountError,cartDiscountErrorDiscountCode,cartDiscountErrorShipping}=this.refs,target=type==="discount_code"?cartDiscountErrorDiscountCode:cartDiscountErrorShipping;this.#clearCustomFeedback(),cartDiscountError.classList.remove("hidden"),target.classList.remove("hidden")}#influencerGwpGroup(code){return`influencer:${String(code||"").toLowerCase()}`}#cartHasInfluencerGift(items,code){const group=this.#influencerGwpGroup(code);return items.some(it=>{const props=it&&it.properties||{};return props._is_gwp==="true"&&String(props._gwp_group||"")===group})}#existingDiscounts(){const discountCodes=[],discountPills=this.querySelectorAll(".cart-discount__pill");for(const pill of discountPills)pill instanceof HTMLLIElement&&typeof pill.dataset.discountCode=="string"&&discountCodes.push(pill.dataset.discountCode);return discountCodes}}customElements.get("cart-discount-component")||customElements.define("cart-discount-component",CartDiscount); 2//# sourceMappingURL=/cdn/shop/t/333/assets/cart-discount.js.map?v=169362345987281765501789672938
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.