${(function(){ const products = data.products; const getDefaultVariant = function(product){ if (product.min_price_variant.available){ return product.min_price_variant; }else { const avail_variants = product.variants.filter(function(variant){ return variant.available; }); if (avail_variants.length) { return avail_variants[0]; } } }; const toQuery = obj => Object.keys(obj) .map(k => Array.isArray(obj[k]) ? obj[k].map(v => `${k}[]=${encodeURIComponent(v)}`).join(‘&’) : `${k}=${encodeURIComponent(obj[k])}` ) .join(‘&’); const getDefaultTrackParams = function(product, index){ const variant = getDefaultVariant(product); const params = { aid: ‘smart_recommend.2.’ + data.id, scm: product.scm || data.scm || ”, spm: data.spmBase + ‘.’ + index, ssp: data.ssp || ”, }; const trackParams = Object.keys(params).map(function(key){ return params[key]; }).join(‘__’); return trackParams; }; const hasMore = (data.products.length – data.target_top_product_num – data.page * data.limit) === 0; return ` `; })()}
${data.originData.data.config.pop_title}
${data.originData.data.rebate_tips || ”}
const zebu_ativity_pop_show_history_key = ‘zebu_ativity_pop_show_history’; class SpzCustomComponent extends SPZ.BaseElement { constructor(element) { super(element); this.templates_ = null; this.container_ = null; this._atcLineItem = {}; this.cart_ = {}; this.top_product_ids_ = []; this.products_ = []; this.activityId_ = null; this.rendered_ = false; this.myInterceptor_ = null; this.i18n_ = {}; this.config_ = {}; this.page_ = 1; this.limit_ = 10; this.loading_ = false; this.activityPopShowHistoryConfig = null; } static deferredMount() { return false; } isLayoutSupported(layout) { return layout == SPZCore.Layout.CONTAINER; } buildCallback() { this.templates_ = SPZServices.templatesForDoc(this.element); this.setAction_(); } generateActivityPopShowHistoryKey(activity_id){ const customer_id = window.C_SETTINGS.customer.customer_id || ‘unlogin’; return customer_id + ‘-‘ + activity_id; } judgeCanShowCartPop(data){ const pop_frequency = data.config.pop_frequency; if (pop_frequency == ‘once’){ return { show: !window.sessionStorage.getItem(‘smart_pop_times’), type: ‘once’ }; } if( pop_frequency == ‘not_limit’ ){ return { show: true, type: ‘not_limit’ }; } const activityPopShowHistory = this.getActivityPopShowHistory(); if( !activityPopShowHistory ){ return { show: true, type: ‘no_history’ }; } const historyKey = this.generateActivityPopShowHistoryKey(data.id); const historyItem = activityPopShowHistory[historyKey]; if( !historyItem ){ return { show: true, type: ‘no_history’ }; } if( pop_frequency == ‘once’ ){ return { show: false, type: ‘once’ }; } const splitArray = pop_frequency.split(‘:’); if( splitArray.length != 3 ){ return { show: true, type: ‘rule_error’ }; } const limitType = splitArray[0]; const limitTypeNum = Number(splitArray[1]); const limitNum = Number(splitArray[2]); const startTime = Number(historyItem[‘startTime’]); const count = Number(historyItem[‘count’]); if( new Date().getTime() >= this.getLimitEndTime( startTime, limitType, limitTypeNum ) ){ return { show: true, type: ‘another_range’ }; } if( limitNum > count ){ return { show: true, type: ‘under_limit’ }; } return { show: false, type: ‘exceed_range’ }; } getActivityPopShowHistory(){ try{ const activityPopShowHistory = JSON.parse(window.localStorage.getItem(zebu_ativity_pop_show_history_key)); if( typeof activityPopShowHistory != ‘object’ ) return null; return activityPopShowHistory; }catch(e){ return null; } } addActivityPopShowHistory(props){ if( !props ) return; const { data, ruleCheckResult } = props; const pop_frequency = data.config.pop_frequency; if( pop_frequency == ‘once’ ){ return window.sessionStorage.setItem(‘smart_pop_times’, Number(window.sessionStorage.getItem(‘smart_pop_times’)) + 1); } const historyKey = this.generateActivityPopShowHistoryKey(data.id); const activityPopShowHistory = this.getActivityPopShowHistory() || {}; const historyItem = activityPopShowHistory[historyKey]; if( ruleCheckResult.type == ‘another_range’ || !historyItem ){ activityPopShowHistory[historyKey] = { startTime: new Date().getTime(), count: 1, }; }else{ activityPopShowHistory[historyKey].count += 1; } return window.localStorage.setItem(zebu_ativity_pop_show_history_key,JSON.stringify(activityPopShowHistory)); } removeActivityPopShowHistory(){ return window.localStorage.removeItem(zebu_ativity_pop_show_history_key); } getLimitEndTime(startTime, rangeType, rangeNum){ if( rangeType == ‘day’ ){ return startTime + 24*60*60*1000 * rangeNum; } if( rangeType == ‘week’ ){ return startTime + 24*60*60*1000 * 7 * rangeNum; } if( rangeType == ‘month’ ){ const date = new Date(startTime); date.setMonth( date.getMonth() + rangeNum ); return date.getTime(); } return startTime; } mountCallback() { this.i18n_ = (window.smartRecommendI18n && window.smartRecommendI18n[document.documentElement.lang] || window.smartRecommendI18n[‘en-US’]) || {}; const cartPopRenderEl = document.getElementById(“smart_cart_pop_render”); const modalEl = document.getElementById(“smart_cart_pop_modal”); const spmBase = `smart_recommend_2`; const extra = { spmBase: spmBase, i18n: this.i18n_, }; const that = this; document.addEventListener(‘dj.addToCart’, (event) => { try { const e = event.detail; console.log(e,’e’); if (e.source === ‘buy_now’ || window.__upsell_block || this.rendered_) return; if (window.C_SETTINGS.meta.page.template_type === 52) return; let navigating = false; const onBeforeUnload = () => { navigating = true; }; window.addEventListener(‘beforeunload’, onBeforeUnload, { once: true }); setTimeout(() => { window.removeEventListener(‘beforeunload’, onBeforeUnload); if (navigating) return; that.fetchActivityData({product_id: e.product_id, variant_id: e.variant_id}).then(data => { if (!data || !data.products || !data.products.length) return; const ruleCheckResult = that.judgeCanShowCartPop(data); if( !ruleCheckResult.show ) return; that.config_ = data.config; const recommendStyle = document.createElement(‘style’); recommendStyle.innerHTML = ` #plugin_recommend_atc_pop { display: none !important; } `; document.head.appendChild(recommendStyle); SPZ.whenApiDefined(cartPopRenderEl).then(function(api){ api.render(Object.assign({}, data, extra), true).then(function() { that.rendered_ = true; if (data.products.length) { const headEl = document.getElementById(“smart_cart_pop_head_render”); if (headEl) { SPZ.whenApiDefined(headEl).then(function(head){ head.render({ data: data }); }); } SPZ.whenApiDefined(modalEl).then(function(api){ that.impressListen(‘#smart_cart_pop_activity’, function(){ that.trackPluginImpression_(data); }); api.open(); that.activityPopShowHistoryConfig = { data, ruleCheckResult }; const intersectionObserver = new IntersectionObserver( function (entries) { if (entries[0].intersectionRatio > 0){ !that.loading_ && (that.products_.length – that.target_top_product_num_) === that.page_ * that.limit_ && that.viewMore(); } }, { threshold: [0.1] } ); if( document.querySelector(‘#smart_cart_pop_view_more_text’) ){ intersectionObserver.observe( document.querySelector(‘#smart_cart_pop_view_more_text’) ); } }); } }) }); }) }, 300); } catch (e) { console.error(e); } }); } unmountCallback() { } viewMore () { const cartPopRenderEl = document.getElementById(“smart_cart_pop_render”); const that = this; const data = {}; SPZ.whenApiDefined(cartPopRenderEl).then(function(api){ that.fetchActivityData({ page: that.page_ + 1, limit: that.limit_ }).then(function(data) { data.products = that.products_; data.target_top_product_num = that.target_top_product_num_; data.i18n = that.i18n_; data.spmBase = `smart_recommend_2`; api.render(data); }) }) } fetchActivityData(data) { const that = this; if (data.product_id) { that._atcLineItem = data; } that.loading_ = true; return that.getCart().then(cart => { that.cart_ = cart.cart; return fetch(window.C_SETTINGS.routes.root + “/api/possum/recommend_activities”, { method: “POST”, headers: { “Content-Type”: “application/json”, “store-id”: window.C_SETTINGS.shop.shop_id, }, body: JSON.stringify({ “show_type”: 2, “line_item”: { “product_id”: that._atcLineItem.product_id, “variant_id”: that._atcLineItem.variant_id, }, line_items: cart.cart.line_items, “page”: data.page || 1, “limit”: data.limit || 10, }) }).then(function(res){ if(res.ok){ return res.json(); } }).then(function(data){ data.cart = cart.cart; if (data.page === 1) { that.target_top_product_num_ = data.target_top_product_num || 0; } that.products_ = that.products_.concat(data.products || []); that.page_ = data.page || 1; that.limit_ = data.limit || 10; return data; }).catch(function(e){ console.log(e); }).finally(function(){ that.loading_ = false; }) }); }; setMatchDrawerHeight_(data) { const modalContent = document.querySelector(“#smart_cart_pop_product_list”); const windowHeight = window.innerHeight; modalContent.style.maxHeight = windowHeight * 0.85 + “px”; } setAction_() { this.registerAction(‘changeBannerColor’, (data) => { if (!data.args.data || !data.args.data.data || !data.args.data.data.data) return false; const config = data.args.data.data.data.config; const bannerBgEl = document.querySelector(‘.smart_cart_pop_banner_bg’); if (bannerBgEl && config) { bannerBgEl.style.background = config.banner_bg_color; bannerBgEl.style.color = config.banner_text_color; } }); this.registerAction(‘handleProductChange’, (data) => { const that = this; const imageEl = document.getElementById(`smart_cart_pop_image_${data.args.data.product_id}`); SPZ.whenApiDefined(imageEl).then(function(api){ api.render({ data: data.args.data, config: that.config_ }); }); const atcTextEl = document.getElementById(`smart_cart_pop_atc_${data.args.data.product_id}`); SPZ.whenApiDefined(atcTextEl).then(function(api){ api.render({ data: data.args.data, defaultText: data.args.defaultText, soldOutText: that.i18n_.sold_out }); }); if (data.args.data.variant.available) { document.getElementById(`smart_cart_pop_atc_btn_${data.args.data.product_id}`).classList.remove(‘zb-pointer-events-none’); } else { document.getElementById(`smart_cart_pop_atc_btn_${data.args.data.product_id}`).classList.add(‘zb-pointer-events-none’); } }); this.registerAction(‘handleProduct’, (detail) => { const that = this; this.renderProductsForm_(detail.args.data.data); }); this.registerAction(‘addATCHook’, (data) => { const params = data.args; this.myInterceptor_ = window.djInterceptors && window.djInterceptors.track.use({ event: ‘dj.addToCart’, params: { aid: ‘smart_recommend.2.’ + params.activity_id, ssp: params.ssp, scm: params.scm, cfb: params.cfb, spm: `..${window.C_SETTINGS.meta.page.template_name}.${params.spm}`, }, once: true }); }); this.registerAction(‘handleAtcSuccess’, (detail) => { detail.args.data.product = detail.args.data.product || {}; detail.args.data.variant = detail.args.data.variant || {}; const defParams = detail.args.product.split(‘__’); const product_id = detail.args.data.product.id; const product_title = detail.args.data.product.title; const variant_id = detail.args.data.variant.id; const price = detail.args.data.variant.price; const aid = defParams[0]; const ifb = detail.args.data.product.ifb; const cfb = detail.args.data.product.cfb; const scm = defParams[1]; const spm = defParams[2]; const ssp = defParams[3]; const params = { id: product_id, product_id: product_id, number: 1, name: product_title, variant_id: variant_id, childrenId: variant_id, item_price: price, source: ‘add_to_cart’, _extra: { aid: aid, ifb: ifb, cfb: cfb, scm: scm, spm: `..${window.C_SETTINGS.meta.page.template_name}.${spm}`, ssp: ssp, } }; const activity_id = `${detail.args.activity_id}`; const target_drive_way = detail.args.target_drive_way; document.getElementById(`smart_cart_pop_loading_${product_id}`).classList.add(‘zb-hidden’); document.getElementById(`smart_cart_pop_added_${product_id}`).classList.remove(‘zb-hidden’); setTimeout(() => { document.getElementById(`smart_cart_pop_added_${product_id}`).classList.add(‘zb-hidden’); document.getElementById(`smart_cart_pop_atc_${product_id}`).classList.remove(‘zb-hidden’); document.getElementById(`smart_cart_pop_atc_btn_${product_id}`).classList.remove(‘zb-pointer-events-none’); }, 1000); this.tranckAddToCart(params); if (target_drive_way === ‘rebate’) { const bannerEl = document.getElementById(`smart_cart_pop_banner`); this.getRecommendInfo(activity_id).then(res => { if (res && res.rebate_tips) { bannerEl.innerHTML = res.rebate_tips; } }) } }); this.registerAction(‘handleCartSummary’, (event) => { const that = this; const checkoutButtonEle = document.getElementById(“smart_cart_pop_checkout_button”); if (checkoutButtonEle) { SPZ.whenApiDefined(checkoutButtonEle).then(function(api){ api.render({ i18n: that.i18n_ }, false); }); } const tipEl = document.getElementById(“smart_cart_pop_tip_info”); const cart = event && event.args && event.args.data && event.args.data.data; if (!tipEl || !cart) return; let total_price = cart.total_price; if (!total_price) { SPZ.whenApiDefined(tipEl).then(function(api){ api.render({ total_price: total_price, i18n: that.i18n_ }, false); }); } else { this.getBindDiscount_(cart.line_items).then(res => { if (res && res.discount_code){ const total = cart.line_price – cart.total_discount – res.bundle_discount_value; if (total > 0) { total_price = total; } else { total_price = 0; } } SPZ.whenApiDefined(tipEl).then(function(api){ api.render({ total_price: total_price, i18n: that.i18n_ }, false); }); }) } }); this.registerAction(‘open’, () => { this.setMatchDrawerHeight_(); this.addActivityPopShowHistory( this.activityPopShowHistoryConfig ); }); this.registerAction(‘close’, () => { this.rendered_ = false; this.products_ = []; window.djInterceptors && window.djInterceptors.track.eject(this.myInterceptor_); }); this.registerAction(‘goToCart’, () => { const routesRoot = window.C_SETTINGS?.routes?.root || ”; window.location.href = routesRoot + ‘/cart’; }); } getCart() { return fetch(`${window.C_SETTINGS.routes.root || ”}/api/cart`, { method: ‘GET’, headers: { ‘Content-Type’: ‘application/json; charset=UTF-8’, }, }).then(res => { if (!res.ok) return { cart: { line_items: [] } }; return res.json(); }).catch(() => ({ cart: { line_items: [] } })); } getRecommendInfo (activity_id) { return this.getCart().then(cart => { this.cart_ = cart.cart; return fetch(`${window.C_SETTINGS.routes.root || ”}/api/possum/recommend_info`, { method: ‘POST’, headers: { ‘Content-Type’: ‘application/json; charset=UTF-8’, }, body: JSON.stringify({ show_type: 2, rule_id: `${activity_id}`, line_items: cart.cart.line_items, line_item: this._atcLineItem, }) }).then(res => res.json()) }) } renderProductsForm_(data) { const products = data.products; const listPopRenderEl = document.getElementById(“smart_cart_pop_render”); if (!listPopRenderEl) return; listPopRenderEl.querySelectorAll(‘.smart_cart_pop_atc_btn_bg’).forEach(function(el){ el.style.color = data.config.add_to_cart_button_text_color; el.style.background = data.config.add_to_cart_button_color; }); products.forEach(function(product){ const productId = product.id; const productFormEls = listPopRenderEl.querySelectorAll(`ljs-product-form[product-id=”${productId}”]`); let variantsEl = listPopRenderEl.querySelectorAll(`ljs-product-form[product-id=”${productId}”] #smart_cart_pop_variant_${productId}_mobile ljs-variants`); if (window.innerWidth > 768) { variantsEl = listPopRenderEl.querySelectorAll(`ljs-product-form[product-id=”${productId}”] #smart_cart_pop_variant_${productId}_pc ljs-variants`); } productFormEls.forEach(function(el){ SPZ.whenApiDefined(el).then(function(api){ api.setProduct(product); }); }); variantsEl.forEach(function(el){ SPZ.whenApiDefined(el).then(function(api){ api.handleRender(product); }); }) }); } tranckAddToCart(detail) { if (window.$) { window.$(document.body).trigger(‘dj.addToCart’, detail); } } trackPluginImpression_(rule){ if (window.sa && window.sa.track) { window.sa.track(“module_impressions”, { aid: `smart_recommend.2.${rule.id}` }); } } getBindDiscount_(carts) { let bundle_sale_ids = []; try { bundle_sale_ids = sessionStorage[‘bundle_sale_ids’] && JSON.parse(sessionStorage[‘bundle_sale_ids’]).filter((item, index, arr) => arr.indexOf(item, 0) === index).slice(-5); } catch (err) { console.error(err); } if (!carts.length) { Promise.resolve(); } return fetch(`${window.C_SETTINGS.routes.root || ”}/api/bundle-sales/cart`, { method: ‘POST’, headers: { ‘Content-Type’: ‘application/json; charset=UTF-8’, ‘store-id’: window.C_SETTINGS.shop.shop_id, }, body: JSON.stringify({ cart: carts, action_type: ‘cart’, bundle_sale_ids }) }).then(res => res.json()) } impressListen(selector, cb) { const el = document.querySelector(selector); const onImpress = (e) => { if (e) { e.stopPropagation(); } cb(); }; if (el && !el.getAttribute(‘imprsd’)) { el.addEventListener(‘impress’, onImpress) } else if (el) { onImpress(); } } } SPZ.defineElement(‘spz-custom-smart’, SpzCustomComponent);
${function(){ return ` ${data.data.rebate_tips || ”}
`; }()}
${function(){ const getImageHeight = function(image){ const width = image.width || 500; const height = image.height || 500; const image_size = data.config.image_size || 0; let ratio = 0; if(image_size == 0){ ratio = (height / width).toFixed(2); }else if(image_size == 1){ ratio = 1.5; } return 132 * ratio; }; const image = data.data.variant.image || data.data.product.image; return ` `; }()}
${(function(){ const product = data.product; const avail_variants = product.variants.filter(function(variant){ return variant.available; }); const selected_variant = product.min_price_variant.available ? product.min_price_variant : avail_variants.length && avail_variants[0]; return `
${option.name} ${ option.values.map(function(value, index){ const checked = selected_variant[“option”+option.position] == value ? “checked”: “”; return `
${value}
` }).join(“”) }
` })()}
${(function(){ const variant = data.variant; return ` ${(function(){ const variant = data.variant; return ` ${ variant.options.map(function(option){ return option.value; }).join(“/”) || ‘Not exist’ }
`; })()}
${(function(){ const variant = data.data && data.data.variant; const defaultText = data.defaultText || ‘Add To Cart’; const text = (!variant || variant.available) ? defaultText: data.soldOutText; return ` ${text}
`; })()}
${(function(){ return ` ${data.i18n.checkout}
`; })()}
Texte d’origine
Évaluez cette traduction
Votre avis nous aidera à améliorer Google Traduction
English