const debounce = function(fn, delay) { let timer; return function () { const context = this; const args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; }; class HomeData { constructor() { this.memberDetail = this.getMemberDetail(); this.earnPointsPlan = Promise.resolve({}); this.redeemPlan = Promise.resolve({}); this.getMemberDetailDebounce = debounce( this.getMemberDetail.bind(this), 200 ); } refreshAllData() { this.getMemberDetail(); this.getPointPlans(); this.getRedeemPlans(); this.getPointAndRedeemPlan(); } getMemberDetail() { const memberPromise = fetch( "\/api\/loyalty-server\/member" ).then((response) => { // not login // 用null 和undefined来区分用户状态,因为已经很多地方用!!data.member来判断了,这是最简单的方式。 // null: not member // undefined: not login if (response.status === 401) { return undefined; } else if (response.status === 404) { // not member return null } else if (!response.ok) { return null } return response.json(); }); const tierDetail = fetch( "\/api\/loyalty-server\/tier-details" ).then((response) => response.json()); const fetchPromise = Promise.all([memberPromise, tierDetail]).then(([memberDetail, tierList]) => { const currentTierIndex = tierList.tier_details.findIndex((tier) => tier.id === memberDetail?.tier_id) return { member: memberDetail, current_tier: tierList.tier_details[currentTierIndex === -1 ? 0 : currentTierIndex], next_tier: currentTierIndex === tierList.tier_details.length - 1 ? null : tierList.tier_details[currentTierIndex + 1] } }) this.memberDetail = fetchPromise; return fetchPromise; } getPointPlans() { const fetchPromise = fetch( "\/api\/loyalty-server\/earn-points\/campaigns" ).then((response) => response.json()); this.earnPointsPlan = fetchPromise; return fetchPromise; } getPointsDeduction() { const fetchPromise = fetch( "\/api\/loyalty-server\/points-deduction\/campaign" ).then((response) => response.json()); this.pointsDeduction = fetchPromise; return fetchPromise; } getRedeemPlans() { const fetchPromise = fetch( "\/api\/loyalty-server\/points-redeem\/campaigns" ).then((response) => response.json()); this.redeemPlan = fetchPromise; return fetchPromise; } getPointAndRedeemPlan() { this.pointAndRedeemData = Promise.all([ this.earnPointsPlan, this.redeemPlan, ]).then(([earnPointsPlan, redeemPlan]) => { return { earnPointsPlan, redeemPlan } }); } getCompleteTipStorage() { return Promise.resolve(window.sessionStorage.getItem('loyalty-complete-tip-status')); } saveCompleteTipStorage() { return Promise.resolve(window.sessionStorage.setItem('loyalty-complete-tip-status', 'true')); } } const initData = new HomeData(); exportFunction("memberDetail", () => initData.memberDetail); exportFunction("earnPointData", () => initData.earnPointsPlan); exportFunction("redeemData", () => initData.redeemPlan); exportFunction( "pointAndRedeemData", () => initData.pointAndRedeemData ); exportFunction("refreshAllData", initData.refreshAllData.bind(initData)); exportFunction("refreshMemberDetail", initData.getMemberDetail.bind(initData)); exportFunction("refreshRedeemData", initData.getRedeemPlans.bind(initData)); exportFunction("refreshPointData", initData.getPointPlans.bind(initData)); exportFunction("getCompleteTipStorage", initData.getCompleteTipStorage.bind(initData)); exportFunction("saveCompleteTipStorage", initData.saveCompleteTipStorage.bind(initData)); const getBenefitCardData = () => { return Promise.all([initData.memberDetail, initData.getPointsDeduction()]).then(([memberDetail, pointsDeduction]) => { if(!memberDetail.member) { return initData.getPointPlans().then((pointPlans) => { return { memberDetail, pointPlans, pointsDeduction, } }) } else { return fetch( "\/api\/loyalty-server\/recommend-discount-code\/card-campaigns" ).then((response) => { return response.json(); }).then((coupon_recommendation) => { return { memberDetail, coupon_recommendation, pointsDeduction, } }); } }).catch((error) => { console.log('fetch benefit card data', error) }) } exportFunction("getBenefitCardData", getBenefitCardData);

class SpzCustomLoyaltyModal extends SPZ.BaseElement { constructor(element) { super(element); this.container = document.querySelector( this.element.dataset.container ? this.element.dataset.container : "#loyalty-app__panel .loyalty-app__panel-body" ); } buildCallback() { this.setupAction_(); if (this.moved) return; this.moved = true; const originNode = this.container.querySelector(`:scope > #${this.element.id}`) if (originNode) { this.container.removeChild(originNode); } this.container.appendChild(this.element); } open_() { SPZCore.Dom.toggle(this.element, true); this.lockScroll_(); } lockScroll_() { this.container.classList.add("loyalty-lock-scroll"); } close_() { SPZCore.Dom.toggle(this.element, false); this.unlockScroll_(); } unlockScroll_() { this.container.classList.remove("loyalty-lock-scroll"); } setupAction_() { this.registerAction("open", (invocation) => { const { args } = invocation; this.open_(args); }); this.registerAction("close", () => { this.close_(); }); } isLayoutSupported(layout) { return layout === SPZCore.Layout.CONTAINER; } } SPZ.defineElement("spz-custom-loyalty-modal", SpzCustomLoyaltyModal); class SpzCustomLoyaltyInfoFormModal extends SpzCustomLoyaltyModal { constructor(element) { super(element); this.currentEdit = null; } open_({ type, data, title }) { if (!type) return; super.open_(); this.currentEdit = type; SPZ.whenApiDefined(this.element.querySelector('.loyalty-info-form-modal__render')).then((api) => { api.render({ title, attr: type, init_value: data }, true) }); } isLayoutSupported(layout) { return layout === SPZCore.Layout.CONTAINER; } } SPZ.defineElement( "spz-custom-loyalty-info-form-modal", SpzCustomLoyaltyInfoFormModal ); class SpzCustomLoyaltyEarnModal extends SpzCustomLoyaltyModal { constructor(element) { super(element); } open_({ index }) { SPZ.whenApiDefined(document.getElementById('loyalty-async-get-data')).then((api) => { return api.callFunction('earnPointData'); }).then(({campaigns}) => { SPZ.whenApiDefined(this.element.querySelector('#loyalty-earn-detail-modal__render')).then((api) => { api.render(campaigns[index] || {}, true) super.open_(); }); }); } isLayoutSupported(layout) { return layout === SPZCore.Layout.CONTAINER; } } SPZ.defineElement( "spz-custom-loyalty-earn-modal", SpzCustomLoyaltyEarnModal ); class SpzCustomLoyaltyEvent extends SPZ.BaseElement { constructor(element) { super(element); } buildCallback() { this.setupAction_(); this.action_ = SPZServices.actionServiceForDoc(this.element); this.origin = this.element.dataset.origin; const attributes = this.element.attributes; for (let i = 0; i < attributes.length; i++) { const attributeName = attributes[i].name; if (attributeName.startsWith('@event:')) { const eventName = attributeName.replace('@event:', ''); window.SPZUtils.Event.listen( window, eventName, (data) => { if(data.detail.origin !== this.origin) { this.triggerEvent_(`event:${eventName}`, data); } } ) } } } triggerEvent_(eventName, data) { const event = SPZUtils.Event.create( this.win, `spz-custom-loyalty-event.${eventName}`, data ); this.action_.trigger(this.element, eventName, event); } setupAction_() { this.registerAction("emit", (invocation) => { const { args } = invocation; const {eventName} = args; const e = window.SPZUtils.Event.create( window, eventName, args ); window.dispatchEvent(e); }); } isLayoutSupported(layout) { return layout === SPZCore.Layout.LOGIC; } } SPZ.defineElement("spz-custom-loyalty-event", SpzCustomLoyaltyEvent); class SpzCustomLoyaltyTrack extends SPZ.BaseElement { static observer = new IntersectionObserver(entries => { entries.forEach(entry => { if (entry.isIntersecting) { SPZ.whenApiDefined(entry.target).then((api) => { api.track_(); }) } }); }, { root: null, ratio: 0.6, }); constructor(element) { super(element); this.hasTrack = false; const { trackType, trackEvent_developer, ...dataset } = this.element.dataset; this.trackType = trackType; this.eventDeveloper = trackEvent_developer; const trackEventInfo = {}; Object.keys(dataset).forEach((dataKey) => { if (dataKey.startsWith('track')) { trackEventInfo[dataKey.replace('track', '').toLowerCase()] = dataset[dataKey]; } }) this.trackEventInfo = trackEventInfo; } mountCallback() { if (this.trackType === 'function_expose') { SpzCustomLoyaltyTrack.observer.observe(this.element); } else { this.element.addEventListener("click", () => { this.track_(); }); } } unmountCallback() { if (this.trackType === 'function_expose') { SpzCustomLoyaltyTrack.observer.unobserve(this.element); } else { this.element.removeEventListener("click", () => { this.track_(); }); } } track_() { if (this.hasTrack && this.trackType !== "click") return; SPZ.whenApiDefined(document.querySelector('.loyalty-init-data')).then((api) => { return api.callFunction('memberDetail') }).then((rst) => { // 默认游客 let membership_status = 'guest'; // 未登录时先赋值非会员 if (!!window.SHOPLAZZA.customer.customer_id) membership_status = 'no_member'; // 是会员则上报会员名称 if (rst.member) membership_status = `member_${rst.current_tier.name}`; const {email_id} = window.SPZUtils.Urls.parseQueryString(window.location.search); const eventTypeMap = { 'function_expose': 'expose', 'click': 'click' } window.sa.track(this.trackType, { function_name: 'loyalty', plugin_name: 'loyalty', module_type: 'loyalty', module: 'apps', business_type: 'product_plugin', event_developer: this.eventDeveloper, event_type: eventTypeMap[this.trackType], event_info: JSON.stringify({ ...this.trackEventInfo, membership_status: membership_status, source_channels: email_id ? 'email' : 'Store', email_id: email_id }) }); if (this.trackType !== "click") this.hasTrack = true; }) } isLayoutSupported(layout) { return layout === SPZCore.Layout.CONTAINER || layout === SPZCore.Layout.LOGIC; } } SPZ.defineElement("spz-custom-loyalty-track", SpzCustomLoyaltyTrack); class SpzCustomLoyaltyPoint extends SPZ.BaseElement { constructor(element) { super(element); this.value_ = element.getAttribute('value'); this.init = false; } buildCallback() { if (this.win.__loyalty_settings__) { this.win.__loyalty_settings__.then((settings) => { this.pointName_ = (settings.points_rule && settings.points_rule.points_name) || "Points"; this.render_(); }); } } /** * render dom */ render_() { if (this.init) return; // 清空原有内容 // 解决重复渲染问题 if (this.element.childElementCount > 0) { this.element.innerHTML = ''; } this.init = true; this.container_ = document.createElement("span"); this.container_.classList.add("loyalty-point"); this.container_.innerHTML = `${this.value_ !== null ? `${this.value_} ` : ''}${this.pointName_}`; this.element.appendChild(this.container_); } isLayoutSupported(layout) { return layout === SPZCore.Layout.CONTAINER; } } SPZ.defineElement("spz-custom-loyalty-point", SpzCustomLoyaltyPoint);