أطفال التلقائي وضع الدومينو قطار السيارات الكهربائية الدومينو مجموعة الطوب كتل مجموعات ألعاب ألعاب تعليمية للأطفال لتقوم بها بنفسك لعبة الأولاد هدية
المنتج نفس الذي في الفيديو ونعدك بالتوصيل السريع والدفع عند الاستلام وضمان لمدة سنة.
${function() {
const variantData = data.variant || {"id":"5d5f4a41-cb9d-4ca0-8f67-8ade1d93cf4e","product_id":"ef633e94-aca1-4ea8-8128-874339f29de4","title":"A","weight_unit":"kg","inventory_quantity":0,"sku":"MTM000143-1","barcode":"","position":1,"option1":"A","option2":"","option3":"","note":"","image":{"src":"\/\/img.staticdj.com\/3f76f4ccc0b951ddf1209025db87acc0.jpg","path":"3f76f4ccc0b951ddf1209025db87acc0.jpg","width":1000,"height":1000,"alt":"\u0623\u0637\u0641\u0627\u0644 \u0627\u0644\u062a\u0644\u0642\u0627\u0626\u064a \u0648\u0636\u0639 \u0627\u0644\u062f\u0648\u0645\u064a\u0646\u0648 \u0642\u0637\u0627\u0631 \u0627\u0644\u0633\u064a\u0627\u0631\u0627\u062a \u0627\u0644\u0643\u0647\u0631\u0628\u0627\u0626\u064a\u0629 \u0627\u0644\u062f\u0648\u0645\u064a\u0646\u0648 \u0645\u062c\u0645\u0648\u0639\u0629 \u0627\u0644\u0637\u0648\u0628 \u0643\u062a\u0644 \u0645\u062c\u0645\u0648\u0639\u0627\u062a \u0623\u0644\u0639\u0627\u0628 \u0623\u0644\u0639\u0627\u0628 \u062a\u0639\u0644\u064a\u0645\u064a\u0629 \u0644\u0644\u0623\u0637\u0641\u0627\u0644 \u0644\u062a\u0642\u0648\u0645 \u0628\u0647\u0627 \u0628\u0646\u0641\u0633\u0643 \u0644\u0639\u0628\u0629 \u0627\u0644\u0623\u0648\u0644\u0627\u062f \u0647\u062f\u064a\u0629 halantoys","aspect_ratio":1},"wholesale_price":[{"price":184,"min_quantity":1}],"weight":"0.5","compare_at_price":"297","price":"184","retail_price":"297","available":true,"url":"\/products\/huoche?variant=5d5f4a41-cb9d-4ca0-8f67-8ade1d93cf4e","available_quantity":999999999,"options":[{"name":"color","value":"A"}],"off_ratio":38,"flashsale_info":[],"sales":169};
const saveType = "percentage";
const productLabelDiscountOn = false;
return `
-
${saveType == 'percentage'
? `-${variantData.off_ratio}%`
: `-`
}
`;
}()}
${function(){
const tipText = "\u064a\u0631\u062c\u0649 \u062a\u062d\u062f\u064a\u062f {{ name }}".replace(/\{\{\s+name\s+\}\}/g, data);
return `${tipText}
`
}()}
كان المنتج غير متوفر.
المنتج غير متاح.
${function(){
const variantData = data.variant || {"id":"5d5f4a41-cb9d-4ca0-8f67-8ade1d93cf4e","product_id":"ef633e94-aca1-4ea8-8128-874339f29de4","title":"A","weight_unit":"kg","inventory_quantity":0,"sku":"MTM000143-1","barcode":"","position":1,"option1":"A","option2":"","option3":"","note":"","image":{"src":"\/\/img.staticdj.com\/3f76f4ccc0b951ddf1209025db87acc0.jpg","path":"3f76f4ccc0b951ddf1209025db87acc0.jpg","width":1000,"height":1000,"alt":"\u0623\u0637\u0641\u0627\u0644 \u0627\u0644\u062a\u0644\u0642\u0627\u0626\u064a \u0648\u0636\u0639 \u0627\u0644\u062f\u0648\u0645\u064a\u0646\u0648 \u0642\u0637\u0627\u0631 \u0627\u0644\u0633\u064a\u0627\u0631\u0627\u062a \u0627\u0644\u0643\u0647\u0631\u0628\u0627\u0626\u064a\u0629 \u0627\u0644\u062f\u0648\u0645\u064a\u0646\u0648 \u0645\u062c\u0645\u0648\u0639\u0629 \u0627\u0644\u0637\u0648\u0628 \u0643\u062a\u0644 \u0645\u062c\u0645\u0648\u0639\u0627\u062a \u0623\u0644\u0639\u0627\u0628 \u0623\u0644\u0639\u0627\u0628 \u062a\u0639\u0644\u064a\u0645\u064a\u0629 \u0644\u0644\u0623\u0637\u0641\u0627\u0644 \u0644\u062a\u0642\u0648\u0645 \u0628\u0647\u0627 \u0628\u0646\u0641\u0633\u0643 \u0644\u0639\u0628\u0629 \u0627\u0644\u0623\u0648\u0644\u0627\u062f \u0647\u062f\u064a\u0629 halantoys","aspect_ratio":1},"wholesale_price":[{"price":184,"min_quantity":1}],"weight":"0.5","compare_at_price":"297","price":"184","retail_price":"297","available":true,"url":"\/products\/huoche?variant=5d5f4a41-cb9d-4ca0-8f67-8ade1d93cf4e","available_quantity":999999999,"options":[{"name":"color","value":"A"}],"off_ratio":38,"flashsale_info":[],"sales":169};
return `
وزن : ${variantData && variantData.weight}${variantData && variantData.weight_unit}
`
}()}
Enjoy shopping discounts🎁
Support apple pay💵stc-visa
The current produc does not participate any Rebate. Switch the participating product to check the design.
(This prompt will not be displayed on the client-side.)
${function() {
const show = rebate.format_rules.length > data.maxShowCount;
return `
${rule}
${function() {
if(!show) return "";
return `
`;
}()}
`;
}()}
${originData.rebate.format_rules.join(", ")}
if(window.self === window.top) {
(window.disabled_exts ||=[]).push('product_detail_rebate');
}
class SpzRebateComponent extends SPZ.BaseElement {
constructor(element) {
super(element);
}
xhr_ = SPZServices.xhrFor(this.win);
viewport_ = this.getViewport();
action_ = null;
lang = document.documentElement.lang || 'en-US';
i18n = {"ar-SA":{"special_offer":"عرض خاص","close":"إغلاق"},"de-DE":{"special_offer":"Sonderangebot","close":"Schließen"},"en-US":{"special_offer":"SPECIAL OFFER","close":"CLOSE"},"es-ES":{"special_offer":"Oferta especial","close":"Cerrar"},"fr-FR":{"special_offer":"Offre spéciale","close":"Fermer"},"id-ID":{"special_offer":"Penawaran istimewa","close":"Tutup"},"it-IT":{"special_offer":"Offerta speciale","close":"Chiudi"},"ja-JP":{"special_offer":"特別なオファー","close":"閉じる"},"ko-KR":{"special_offer":"특별 메뉴","close":"닫기"},"nl-NL":{"special_offer":"Speciale aanbieding","close":"sluiten"},"pl-PL":{"special_offer":"Oferta specjalna","close":"blisko"},"pt-PT":{"special_offer":"Oferta especial","close":"Fechar"},"ru-RU":{"special_offer":"Специальное предложение","close":"Закрыть"},"th-TH":{"special_offer":"ข้อเสนอพิเศษ","close":"ปิด"},"zh-CN":{"special_offer":"特价","close":"关闭"},"zh-TW":{"special_offer":"特價","close":"關閉"}};
landPage = "\/promotions\/rebate\/";
pageType = 1;
cart = [];
initData = null;
rebateInfo = null;
renderData = null;
footerImage = `${this.win.SHOPLAZZA["image_domain"]}oss/operation/e8ebb03dbb710457ca3b4b6a70898ab2.svg`;
isLayoutSupported(layout) {
return layout == SPZCore.Layout.LOGIC;
}
buildCallback() {
this.initData = this.getProduct();
this.action_ = SPZServices.actionServiceForDoc(this.element);
this.registerAction("triggerGetRenderData", () => {
const event = SPZUtils.Event.create(this.win, "triggerGetRenderData", this.renderData);
this.action_.trigger(this.element, "getRenderData", event);
});
this.registerAction("bindPropagation", () => {
document.querySelector(".product_detail_rebate_list").addEventListener("click", e => {
e.stopPropagation();
this.win.sa &&
this.win.sa.track("plugin_rebate_promotion_click", {
plugin_timestamp: Date.now(),
plugin_location: "info",
product_id: this.initData.product.id,
discount_id: this.rebateInfo.discount_list.map((item) => item.discount_id)[0],
});
});
});
}
async mountCallback() {
document.addEventListener("dj.variantChange", e => {
const data = e.detail;
if (document.querySelector("#product-select-modal.show")) return;
if (this.initData && this.initData.product && data.product && this.initData.product.id === data.product.id) {
this.initData = data;
this.initRebate(this.initData, true);
} else {
this.initData = data;
this.getRebateInfo();
}
});
document.addEventListener("dj.addToCart", e => {
const v = e.detail;
this.rebateInfo &&
this.win.sa &&
this.win.sa.track("plugin_rebate_atc", {
variant_discount_id: this.getVariantDiscountId(v.variant_id).map(item => item.discount_id),
discount_ids: this.rebateInfo.discount_list.map(item => item.discount_id),
variant_id: v.variant_id,
product_id: v.product_id,
price: v.item_price,
number: v.number,
});
});
await this.getRebateInfo();
if (document.querySelector(".plugin-container__bottom-fixed")) {
this.showDiscountPopupsInfoBar();
} else {
this.win.addEventListener("extloaded", () => {
this.showDiscountPopupsInfoBar();
});
}
}
getProduct = (() => {
document.addEventListener("dj.variantChange", e => {
if (!e.detail || !e.detail.product) return;
const productJson = document.querySelector("#product-json");
if (productJson && productJson.textContent && JSON.parse(productJson.textContent)) {
productJson.textContent = JSON.stringify(e.detail);
}
if (this.win.jQuery && this.win.jQuery.fn && this.win.jQuery(document).data("djproduct")) {
this.win.jQuery(document).data("djproduct", e.detail);
}
});
return () => {
let productData = null;
if (this.win.jQuery && this.win.jQuery.fn) {
try {
let product = this.win.jQuery(document).data("djproduct");
if (product) {
productData = JSON.parse(JSON.stringify(product));
} else {
productData = null;
}
} catch (error) {
productData = null;
}
}
if (!productData) {
const productJson = document.querySelector("#product-json");
productData = (productJson && productJson.textContent && JSON.parse(productJson.textContent)) || null;
}
return productData;
};
})();
initRebate = this.win.SPZCore.Types.debounce(
this.win,
((data, variantChange) => {
let discount_list = Object.assign([], this.rebateInfo.discount_list);
/* 按子商品的多少对优惠信息进行排序 */
discount_list &&
discount_list.sort((a, b) => {
return b.variant_ids.length - a.variant_ids.length;
});
/* 选中子商品时 筛选子商品的优惠信息 */
if (data.selected && data.selected.id) {
discount_list = this.getVariantDiscountId(data.selected.id);
}
/* 无满减信息 */
if (!(discount_list && discount_list.length)) {
return;
}
const isSection = !!document.querySelector(
`div[data-section-type^="shoplazza://apps/publicapp/blocks/rebate"] #rebate_custom_component`
);
if (
(this.rebateInfo.rebate_type == "sku" && data && data.selected && data.selected.id) ||
this.rebateInfo.rebate_type == "spu"
) {
if (discount_list[0]) {
this.landPage += discount_list[0].discount_id || "";
}
const info = {
rebate: discount_list[0],
maxShowCount: this.win.innerWidth > 768 ? 3 : 1,
landPage: this.landPage,
modalFooterImg: `url(${`${this.win.SHOPLAZZA["image_domain"]}oss/operation/e8ebb03dbb710457ca3b4b6a70898ab2.svg`})`,
i18n: this.i18n[this.lang]
};
this.renderData = info;
SPZ.whenApiDefined(
document.getElementById(isSection ? "app_rebate_section" : "app_rebate_block")
).then(apis => {
apis.render(info, true);
});
}
this.insertSlideTag(this.rebateInfo.tag, variantChange);
var pluginCurrencyEvent = new CustomEvent("plugin_currency_update");
document.dispatchEvent(pluginCurrencyEvent);
}).bind(this),
10
);
getRebateInfo = async () => {
if (this.initData && this.initData.product && this.initData.product.id) {
var variant_ids = this.initData.product.variants.map(variant => variant.id);
const res = await this.xhr_.fetchJson(
"\/api\/discount-rebate\/product-discount",
{
method: "POST",
body: {
product_id: this.initData.product.id,
product_type: this.initData.product.product_type,
variant_ids: variant_ids,
},
}
);
if (!SPZCore.Types.isEmptyObject(res.rebate_info)) {
res.rebate_info.tag = res.tag;
res.rebate_info.rebate_type = res.rebate_type;
this.rebateInfo = res.rebate_info;
this.initRebate(this.initData);
} else {
if (this.win.top !== this.win.self) {
const noActivity = document.getElementById("no-rebate-activity");
noActivity && (noActivity["style"].display = "block");
}
}
}
};
getVariantDiscountId = (variant_id) => {
if (!variant_id || !this.rebateInfo) return [];
var rebateId = this.rebateInfo.variant_discount_map[variant_id];
return this.rebateInfo.discount_list.filter(item => item.discount_id == rebateId) || [];
};
insertSlideTag = (tag, variantChange) => {
setTimeout(() => {
if (tag) {
var tag_container;
var modal = document.getElementById("product-select-modal");
if (modal && modal.classList.contains("show")) {
if (!variantChange && modal.querySelector(".slider-discount-tag")) return;
if (
variantChange &&
modal.querySelector(".slider-discount-tag:not(.rebate-tag)")
)
return;
tag_container = modal;
} else {
var product_detail_card = document.querySelector(
'.page_container > [data-section-type="product_detail"], .page_container > [data-section-type="product-template"]'
);
if(!product_detail_card) return;
if (!variantChange && product_detail_card.querySelector(".slider-discount-tag")) return;
if (variantChange && product_detail_card.querySelector(".slider-discount-tag:not(.rebate-tag)"))
return;
tag_container = product_detail_card;
}
if (tag_container.matches("#product-select-modal") && this.pageType === 13 && document.documentElement.clientWidth < 768)
return;
const tagDom = `<div class="slider-discount-tag dj_skin_product_title rebate-tag">${tag}</div>`
if (document.querySelector(".sep-loaded-slider")) {
var loadedSlider = tag_container.querySelector(".sep-loaded-slider");
loadedSlider.querySelectorAll(".slider-discount-tag").forEach(function(element) {
element.remove();
});
loadedSlider.insertAdjacentHTML("beforeend", tagDom);
} else {
if (tag_container.querySelector(".support-slick")) {
var supportSlick = tag_container.querySelectorAll(".support-slick, .sep-slider");
supportSlick.forEach((element) => {
element.querySelectorAll(".slider-discount-tag").forEach((element) => {
element.remove();
});
element.insertAdjacentHTML("beforeend",tagDom);
});
} else {
var sepSlider = tag_container.querySelector(".sep-slider");
sepSlider.querySelectorAll(".slider-discount-tag").forEach(function(element) {
element.remove();
});
sepSlider.insertAdjacentHTML("beforeend",tagDom);
}
}
if (document.documentElement.clientWidth < 768) {
const sliderDiscountTagHeight = tag_container.querySelector(".slider-discount-tag").offsetHeight || 0;
document.querySelector(".product-image__swiper_bullets").style.bottom = `${sliderDiscountTagHeight + 15}px`;
}
}
}, 1000);
};
fetchInfoBar = () => {
let discount_ids = [];
if (this.pageType === 1) {
discount_ids = this.rebateInfo && this.rebateInfo.discount_list.map(item => item.discount_id);
} else if (this.pageType === 38) {
discount_ids = [this.win.rebateObj.rebateCollection_id] || [];
}
const productObj = this.getProduct();
return this.xhr_.fetchJson("\/api\/discount-rebate\/global-text", {
method: "POST",
body: {
product_type: productObj && productObj.product && productObj.product.product_type,
line_items: (this.cart.line_items || []).map(item => ({
variant_id: item.variant_id,
product_id: item.product_id,
quantity: item.quantity,
price: item.price,
selected: !item.unchecked,
})),
discount_ids: discount_ids,
},
});
};
renderBottomBanner = res => {
if (!res.tips) return;
if (document.querySelector(".discount__info-bar")) return;
var bar_style = `background:linear-gradient(90deg,${res.config.background_color_start},${res.config.background_color_end}); color:${res.config.color};`;
let data = { tips: res.tips, landPage: this.landPage + res.id, bar_style };
const html = SPZCore.Dom.htmlFor(this.element);
const banner = html([
`<a impr="1" imprevt="1" id="rebate_bottom_bar" href=${data.landPage} class="discount__info-bar text-truncate" data-activity-type="rebate" style="${data.bar_style}">${data.tips}</a>`,
]);
document.querySelector(".plugin-container__bottom-fixed").appendChild(banner);
const pluginCurrencyEvent = new CustomEvent("plugin_currency_update");
document.dispatchEvent(pluginCurrencyEvent);
if (res.id) {
var trackParams = {
page: this.pageType,
discount_id: res.id,
product_id: this.getProduct()?.product.id,
};
banner.addEventListener("click", () => {
this.win.sa &&
this.win.sa.track("plugin_rebate_promotion_click", {
plugin_timestamp: Date.now(),
plugin_location: "bottom_bar",
product_id: trackParams.product_id,
discount_id: trackParams.discount_id,
});
});
this.win.sa && this.win.sa.track("plugin_rebate_banner_pv", trackParams);
}
};
showDiscountPopupsInfoBar = () => {
if ([13, 14, 19, 30, 31].includes(this.pageType)) return;
if (document.querySelector(".plugin-container__bottom-fixed .discount__info-bar")) return;
this.fetchInfoBar().then(this.renderBottomBanner);
document.addEventListener("dj.cartChange", () => {
this.fetchInfoBar().then(this.renderBottomBanner);
});
};
}
SPZ.defineElement("spz-custom-rebate", SpzRebateComponent);
try {
const main = (coreEvent) => {
try {
const {
ecGlobalVarEnums,
getProduct,
getProductFormData,
getOrderFetchParams,
multiply,
removeChildrenDOM,
addChildrenDOM,
loadScript,
getAttributeConfig,
getBlockChannel,
ecEvent,
req,
containerDomId,
channel2ProviderEnums,
showChannelNotOpenTips,
channelEnums,
track,
isPreview,
getExtUrl
} = coreEvent.detail;
window.PaymentEC = {};
let ecConfig;
const shopCurrencyCode = "SAR";
let productDetail = getProduct();
let productPrice = productDetail?.selected?.price
|| 184;
const requiresShipping = productDetail?.product?.requires_shipping;
const expressCheckoutList = {
sdkErrorList: [],
paymentChannelList: [],
disabledChannelList: [],
showChannelList: [],
blockChannelList: [],
extraChannelList: [],
}
const moreButtonConfig = {
firstClick: true,
maxSize: isNaN(1) ? 1 : 1
}
const setBlockChannel = () => {
expressCheckoutList.blockChannelList = getBlockChannel();
track('setBlockChannel', expressCheckoutList);
}
const filterECButton = ({type, domID}) => {
const showChannelList = expressCheckoutList.paymentChannelList.filter((ecName) =>
!expressCheckoutList.sdkErrorList.includes(ecName) && !expressCheckoutList.disabledChannelList.includes(ecName) &&
!expressCheckoutList.extraChannelList.includes(ecName)) || [];
expressCheckoutList.showChannelList = showChannelList.filter((ecName) => ecName !== type) || [];
removeChildrenDOM(domID);
track('filterECButton', expressCheckoutList);
};
const showECButton = () => {
const showChannelList = expressCheckoutList.paymentChannelList.filter((ecName) =>
!expressCheckoutList.sdkErrorList.includes(ecName) && !expressCheckoutList.disabledChannelList.includes(ecName) &&
!expressCheckoutList.extraChannelList.includes(ecName)) || [];
expressCheckoutList.showChannelList = showChannelList;
track('showECButton', expressCheckoutList);
expressCheckoutList.showChannelList.forEach((ecName, index) => {
const disableShow = moreButtonConfig.firstClick && index >= moreButtonConfig.maxSize;
addChildrenDOM(containerDomId[channel2ProviderEnums[ecName]], !disableShow);
showMoreButton();
});
if (expressCheckoutList.showChannelList.length === 0) {
showMoreButton();
}
}
const disabledChannelListEvent = (checkoutData = {}) => {
expressCheckoutList.disabledChannelList = expressCheckoutList.paymentChannelList.filter(ecName => {
let mustDisable = false;
if (!requiresShipping && ecName !== channelEnums.PAYPAL) {
mustDisable = true;
}
if (!productDetail?.selected?.available) {
mustDisable = true;
}
const {payment_due} = checkoutData?.prices;
const paymentDueNum = Number(payment_due || 0) * 100;
const showFlag = paymentDueNum > 0;
if (mustDisable || !showFlag) {
filterECButton({type: ecName, domID: containerDomId[channel2ProviderEnums[ecName]]})
}
return mustDisable || !showFlag;
})
track('disabledChannelListEvent', expressCheckoutList);
}
const showMoreButton = () => {
const dom = document.getElementById('pm-payment-express-more-button-1539149753700-13');
if (!dom) {
return;
}
const showLength = expressCheckoutList.showChannelList.length;
const {firstClick, maxSize} = moreButtonConfig;
dom.style.display = (firstClick && showLength > 0 && showLength > maxSize) ? 'block' : 'none';
dom.onclick = moreButtonEvent;
}
const moreButtonEvent = () => {
const dom = document.getElementById('pm-payment-express-more-button-1539149753700-13');
if (!dom) {
return;
}
dom.style.display = 'none';
moreButtonConfig.firstClick = false;
showECButton();
}
const loadErrorEvent = (type) => {
if (!containerDomId[type]) {
return;
}
filterECButton({type: type, domID: containerDomId[type]});
expressCheckoutList.sdkErrorList.push(type);
showMoreButton();
};
const getECConfig = async () => {
if (window.PaymentEC?.settings) {
return window.PaymentEC?.settings;
}
const result = await req.get('/api/payment/settings');
ecConfig = result?.settings?.express_checkout_config || {};
expressCheckoutList.paymentChannelList = expressCheckoutList.blockChannelList.filter(ecName =>
ecConfig?.express_channels?.includes(ecName)) || [];
window.PaymentEC.settings = {...ecConfig, currencyCode: shopCurrencyCode};
return window.PaymentEC.settings;
}
async function renderEC(data = {}) {
ecConfig = await getECConfig();
track('renderEC', expressCheckoutList);
if (data?.detail?.selected?.price) {
productDetail = data?.detail;
productPrice = data?.detail?.selected?.price;
}
// 初始化时没有事件推送
const formData = getProductFormData(data?.detail || productDetail);
const totalPrice = multiply(productPrice, formData?.[0]?.quantity || 0);
if (ecConfig) {
const checkoutData = {
prices: {payment_due: totalPrice, subtotal_price: totalPrice},
orderParams: getOrderFetchParams(formData),
containerDOMIdEnums: containerDomId,
ecGlobalVarEnums
}
const notOpenChannel = expressCheckoutList.blockChannelList.filter(ecName =>
!expressCheckoutList.paymentChannelList.includes(ecName));
showChannelNotOpenTips(notOpenChannel);
disabledChannelListEvent(checkoutData);
showECButton();
window.PaymentEC.handleEcPluginsLoad = ({
channelInfos = [],
loadedCbFn = () => {
}
}) => {
const expressCheckoutLoadList = [];
channelInfos.map((channelInfo) => {
const {ecGlobalVar, ecName = '', sdkPath = '', datasets} = channelInfo;
if (!document.getElementById(containerDomId[ecName])) {
return;
}
const attributeConfig = getAttributeConfig(channelInfo) || {};
expressCheckoutLoadList.push(
loadScript(() => window[ecGlobalVar], ecGlobalVar, sdkPath, datasets, () => {
loadErrorEvent(ecName);
}, attributeConfig)
);
});
Promise.all(expressCheckoutLoadList).then(() => {
loadedCbFn(checkoutData);
});
};
// 通知外部数据变更
ecEvent.emit('tc_payment_ec_data_change', {
ecGlobalVarEnums,
containerDOMIdEnums: containerDomId
});
}
}
const extraFilterEvent = (e) => {
const {channel, domId, allowShow} = e?.detail || {};
if (channel && domId) {
if (allowShow) {
expressCheckoutList.extraChannelList = expressCheckoutList.extraChannelList.filter(ecName => ecName !== channel);
track('extraFilterEvent_show', expressCheckoutList);
showECButton();
} else {
expressCheckoutList.extraChannelList.push(channel);
filterECButton({type: channel, domID: domId});
track('extraFilterEvent_hide', expressCheckoutList);
showECButton();
}
}
}
const init = () => {
ecEvent.on('shoplazza_express_channels_change', extraFilterEvent, isPreview() ? {once: true} : false);
ecEvent.on('shoplazza_express_channels_change_ready', extraFilterEvent, isPreview() ? {once: true} : false);
document.addEventListener('dj.variantChange', renderEC);
renderEC();
}
const loadFilly = (tag) => {
if (!tag) {
return
}
const script = document.createElement('script');
script.type = 'text/javaScript';
script.src = `//static.staticdj.com/${tag}`;
script.onload = init;
document.getElementsByTagName('head')[0].appendChild(script);
}
const callback = () => {
const fillyTag = getExtUrl('filly');
if (fillyTag) {
setBlockChannel();
loadFilly(fillyTag);
}
}
const delayCallback = () => {
window.requestIdleCallback ? requestIdleCallback(callback, {timeout: 50}) : setTimeout(callback, 50);
}
if (document.readyState === 'complete') {
delayCallback();
return;
}
window.addEventListener('load', delayCallback, false);
} catch (e) {
console.error('payment-sdk-express-checkout:', e)
}
}
const containerDOM = document.getElementById('pm-payment-express-button-container-1539149753700-13');
containerDOM.addEventListener('paymentChannelList', main, false);
} catch (e) {
}
try {
const core = (coreEvent) => {
try {
const {isChrome, isSafari, isPreview, channelEnums} = coreEvent?.detail;
const {getPluginI18nMessages} = window?.payment_plugin_message || {};
/**
* 获取script标签自定义参数
* @param channelInfo 渠道信息
* @return {object|{}}
*/
const getAttributeConfig = (channelInfo) => {
const {ecGlobalVar, ecName} = channelInfo;
const config = {
paypal: {
'data-namespace': ecGlobalVar
}
};
return config[ecName] || {};
};
const getBlockChannel = () => {
const block_googlePay = false &&
"shoplazzagoogle";
const block_applePay = true &&
"shoplazzaapple";
const block_credit = false &&
"paypal";
const blockChannel = {
googlepay: isChrome() && block_googlePay,
applepay: isSafari() && block_applePay,
credit: block_credit
};
const sortList = ['credit', 'googlepay', 'applepay'];
const methodSort = Object.keys(blockChannel).filter(key => blockChannel[key] && key).sort((a, b) => {
const indexA = sortList.indexOf(a);
const indexB = sortList.indexOf(b);
return indexA - indexB;
}).map(key => blockChannel[key]);
return methodSort;
}
const showChannelNotOpenTips = (channelList) => {
const tipsDom = document.getElementById('pm-payment-express-error-tips-1539149753700-13');
if (!isPreview()) {
return;
}
if (!tipsDom) {
return;
}
tipsDom.style.display = channelList.length > 0 ? 'block' : 'none';
const channelName = {
[channelEnums.SHOPLAZZA_GOOGLE]: "ShoplazzaPayments - GooglePay",
[channelEnums.SHOPLAZZA_APPLE]: "ShoplazzaPayments - ApplePay",
[channelEnums.PAYPAL]: "PayPal",
}
channelList.forEach(ecName => {
const id = `pm-payment-express-error-tips-1539149753700-13-${ecName}`;
const hasDom = document.getElementById(id)
if (!hasDom) {
const dom = document.createElement('div');
dom.id = id;
dom.innerHTML = getPluginI18nMessages('ec.not_active_channel', {channelName: channelName[ecName]});
tipsDom.appendChild(dom);
}
})
}
const isAllowTheme = () => {
const allowThemeList = ['Nova 2023', 'Dropshiping', 'Geek', 'Wind', 'Flash'];
const currentTheme = window?.C_SETTINGS?.theme?.merchant_theme_name;
return allowThemeList.includes(currentTheme);
}
const disabledThemTips = () => {
const tipsDom = document.getElementById('pm-payment-express-error-tips-1539149753700-13');
if (!isPreview()) {
return;
}
if (!tipsDom) {
return;
}
tipsDom.style.display = 'block';
const id = 'pm-payment-express-error-tips-1539149753700-13-theme';
const hasDom = document.getElementById(id);
if (!hasDom) {
const dom = document.createElement('div');
dom.id = id;
dom.innerHTML = getPluginI18nMessages('ec.not_support_theme');
tipsDom.appendChild(dom);
}
}
const coreMethod = {
...coreEvent.detail,
getAttributeConfig,
getBlockChannel,
showChannelNotOpenTips,
isAllowTheme,
disabledThemTips
};
if (!isAllowTheme()) {
disabledThemTips();
} else {
const containerDOM = document.getElementById('pm-payment-express-button-container-1539149753700-13');
const moreButtonDOM = document.getElementById('pm-payment-express-more-button-1539149753700-13');
moreButtonDOM.innerHTML = getPluginI18nMessages('ec.more_button');
containerDOM.dispatchEvent(new CustomEvent('paymentChannelList', {detail: coreMethod}));
}
} catch (e) {
}
}
const containerDOM = document.getElementById('pm-payment-express-button-container-1539149753700-13');
containerDOM.addEventListener('Payment_EC_Core_first', core, false);
} catch (e) {
}
try {
const core = () => {
const containerDOM = document.getElementById('pm-payment-express-button-container-1539149753700-13');
if (containerDOM?.getPluginI18nMessages && !window?.payment_plugin_message?.getPluginI18nMessages) {
return;
}
containerDOM.getPluginI18nMessages = window?.payment_plugin_message?.getPluginI18nMessages
try {
const domIDSuffix = '-express-button-container';
const prefix = 'pm-';
const ecGlobalVarEnums = {
paypal: 'pluginPaypalEC'
};
const providerEnums = {
SHOPLAZZA: 'shoplazza',
STRIPE: 'stripe',
PAYPAL: 'paypal'
};
const channelEnums = {
SHOPLAZZA_GOOGLE: 'shoplazzagoogle',
SHOPLAZZA_APPLE: 'shoplazzaapple',
PAYPAL: 'paypal'
}
const containerDomId = {
paypal: `${prefix}${providerEnums.PAYPAL}${domIDSuffix}-1539149753700-13`,
stripe: `${prefix}${providerEnums.STRIPE}${domIDSuffix}-1539149753700-13`,
shoplazza: `${prefix}${providerEnums.SHOPLAZZA}${domIDSuffix}-1539149753700-13`,
};
const channel2ProviderEnums = {
[channelEnums.PAYPAL]: providerEnums.PAYPAL,
[channelEnums.SHOPLAZZA_GOOGLE]: providerEnums.SHOPLAZZA,
[channelEnums.SHOPLAZZA_APPLE]: providerEnums.SHOPLAZZA,
stripegoogle: providerEnums.STRIPE,
stripeapple: providerEnums.STRIPE,
};
const getProduct = () => {
const productJson = document.querySelector('#product-json');
if (productJson?.textContent) {
return JSON.parse(productJson.textContent);
}
if (window.jQuery) {
const $product = window.jQuery?.(document)?.data('djproduct');
const productData = JSON.parse(JSON.stringify($product || {}));
return productData || {};
}
return {};
};
const isChrome = () => {
return navigator?.userAgent?.indexOf('Chrome') > -1 || navigator?.userAgent?.indexOf('CriOS') > -1;
};
const isSafari = () => {
let userAgentString = navigator.userAgent;
let chromeAgent = userAgentString.indexOf('Chrome') > -1 || navigator?.userAgent?.indexOf('CriOS') > -1;
let safariAgent = userAgentString.indexOf('Safari') > -1;
if (chromeAgent && safariAgent) {
safariAgent = false;
}
return safariAgent;
};
const isPreview = () => {
return !!window?.C_EDITING_SETTINGS?.oseid;
}
const getProductFormData = (data) => {
const product_id = data?.product_id || data?.product?.id;
const variant_id = data?.variant_id || data?.variant?.id || data?.selected?.id;
const quantity = data?.quantity || 1;
return [{
product_id,
variant_id,
quantity
}];
}
const getOrderFetchParams = (data) => {
if (!data) {
return {};
}
return {
line_items: data.map((item) => ({
note: '',
quantity: item.quantity || 1,
product_id: item?.product_id,
variant_id: item?.variant_id,
properties: item?.properties,
})),
refer_info: {
source: 'buy_now',
},
customer_note: '',
};
}
const multiply = (a, b) => {
const precision = 2; // 保留两位小数
return Number((a * b).toFixed(precision));
}
/**
* 移除EC节点
* @param id EC容器-div的id
*/
const removeChildrenDOM = (id) => {
if (!id) {
return;
}
const paymentEl = document.querySelector(`#pm-payment-express-button-container-1539149753700-13`);
const childrenEL = document.getElementById(id);
if (paymentEl && childrenEL) {
// childrenEL.remove();
childrenEL.style.display = 'none';
}
};
const addChildrenDOM = (id, allowShow) => {
if (!id) {
return;
}
const paymentEl = document.querySelector(`#pm-payment-express-button-container-1539149753700-13`);
const childrenEL = document.getElementById(id);
if (paymentEl && childrenEL) {
childrenEL.style.display = allowShow ? 'block' : 'none';
return;
}
if (paymentEl && !childrenEL) {
const dom = document.createElement('div');
dom.id = id;
dom.style.display = allowShow ? 'block' : 'none';
paymentEl.appendChild(dom);
}
}
const loadScript = (fnReady, id, src, datasets, onError, attributeConfig = {}) => {
const sdkDomId = id + '-sdk';
if (fnReady() || document.getElementById(sdkDomId)) {
return Promise.resolve({id: true});
}
return new Promise((resolve) => {
const s = document.createElement('script');
s.id = sdkDomId;
s.src = src;
s.defer = true;
if (datasets) {
Object.keys(datasets).map((item) => {
s.dataset[item] = datasets[item];
});
}
s.onload = function () {
window.dispatchEvent(new CustomEvent(`${id}-loaded`));
resolve({id: true});
};
s.onerror = function () {
resolve({id: false});
onError && onError();
};
Object.keys(attributeConfig).forEach((key) => {
s.setAttribute(key, attributeConfig[key]);
});
document.head.appendChild(s);
});
};
const track = (eventName, data) => {
window.sa && window?.sa?.track('pm_' + eventName, data);
}
const eventListeners = {};
const ecEvent = {
on: (eventName, listener, useCapture) => {
eventListeners[eventName] = listener;
window.addEventListener(eventName, listener, useCapture);
},
emit: (eventName, data) => window.dispatchEvent(new CustomEvent(eventName, {detail: data})),
};
const req = {
ROOT_URL: (C_SETTINGS && C_SETTINGS.routes && C_SETTINGS.routes.root) || '',
post: async (url, data = {}) => {
try {
const response = await fetch(req.ROOT_URL + url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
...data,
body: JSON.stringify(data.body),
});
const result = await response.json();
return result
} catch (error) {
throw new Error('post request error' + error);
}
},
get: async (url, data = {}) => {
try {
const response = await fetch(req.ROOT_URL + url);
const result = await response.json();
return result
} catch (error) {
throw new Error('get request error' + error);
}
}
};
const getExtUrl = (name) => {
const url = document.cookie.match(new RegExp('\\b' + name.replace(/_/g, '-') + '-(v[s0-9]+)'));
if (url && url[1]) {
return `${name}.${url[1]}.js`;
} else {
return window?.exts?.filly;
}
}
const coreMethod = {
domIDSuffix,
prefix,
ecGlobalVarEnums,
providerEnums,
channelEnums,
containerDomId,
channel2ProviderEnums,
getProduct,
isChrome,
isSafari,
isPreview,
getProductFormData,
getOrderFetchParams,
multiply,
removeChildrenDOM,
addChildrenDOM,
loadScript,
track,
eventListeners,
ecEvent,
req,
getExtUrl
}
const containerDOM = document.getElementById('pm-payment-express-button-container-1539149753700-13');
if (containerDOM) {
containerDOM.dispatchEvent(new CustomEvent('Payment_EC_Core_first', {detail: coreMethod}));
}
} catch (e) {
}
}
document.addEventListener('payment_plugin_message_reader', core, {once: true});
} catch (e) {
}
const getPluginI18nMessages = (message, replaceObj = {}) => {
const lang = document.documentElement.lang || "en-US";
const [form, key] = message.split('.')
let text = window.payment_plugin_message['en-US'][form][key];
if (window.payment_plugin_message[lang][form].hasOwnProperty(key)) {
text = window.payment_plugin_message[lang][form][key];
}
Object.keys(replaceObj).forEach(key => {
text = text.replace(new RegExp(`\{${key}\}`, 'gi'), replaceObj[key]);
})
return text;
}
const zhCN = {
ec: {
not_active_channel: "请到收款设置中{channelName}或在「快捷支付按钮」设置中选择其他的服务提供方,否则按钮将无法展示",
not_support_theme: "当前主题不支持添加「快捷支付按钮」",
more_button: "更多支付方式",
}
};
const zhTW = {
ec: {
not_active_channel: "请到收款设置中{channelName}或在「快捷支付按钮」设置中选择其他的服务提供方,否则按钮将无法展示",
not_support_theme: "当前主题不支持添加「快捷支付按钮」",
more_button: "更多付款方式",
}
};
const arSA = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "المزيد من خيارات الدفع",
}
};
const deDE = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Weitere Bezahlmöglichkeiten",
}
};
const esES = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Más opciones de pago",
}
};
const frFR = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Plus d'options de paiement",
}
};
const idID = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Opsi pembayaran lainnya",
}
};
const itIT = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Altre opzioni di pagamento",
}
};
const jaJP = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "その他の支払いオプション",
}
};
const koKR = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "더 많은 결제 옵션",
}
};
const enUS = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "More payment options",
}
};
const nlNL = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Meer betalingsmogelijkheden",
}
};
const plPL = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Więcej Opcji Płatności",
}
};
const ptPT = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Mais opções de pagamento",
}
};
const ruRU = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "Другие варианты оплаты",
}
};
const thTH = {
ec: {
not_active_channel: "Please activate {channelName} on B Admin or select another provider in the「Express checkout button」 settings, otherwise it will not display.",
not_support_theme: "This Theme doesn't support adding「Express checkout button」",
more_button: "ตัวเลือกการชำระเงินเพิ่มเติม",
}
};
window.payment_plugin_message = {
getPluginI18nMessages,
"zh-CN": zhCN,
"zh-TW": zhTW,
"ar-SA": arSA,
"de-DE": deDE,
"es-ES": esES,
"fr-FR": frFR,
"id-ID": idID,
"it-IT": itIT,
"ja-JP": jaJP,
"ko-KR": koKR,
"en-US": enUS,
"nl-NL": nlNL,
"pl-PL": plPL,
"pt-PT": ptPT,
"ru-RU": ruRU,
"th-TH": thTH,
}
document.dispatchEvent(new CustomEvent('payment_plugin_message_reader'));
${function() {
const postageFreeAmount = 200;
const custom_text = "Buy {amount} more to enjoy FREE Shipping";
const totalPrice = +data.total_price;
const diffPrice = postageFreeAmount - totalPrice;
const percentDiff = (diffPrice > 0 ? (totalPrice / postageFreeAmount * 100) : 100) + '%';
let tipText = "\u062a\u0648\u0635\u064a\u0644 \u0645\u062c\u0627\u0646\u064a";
if (diffPrice > 0) {
tipText = custom_text.replace('{amount}', `
`);
}
return `
`;
}()}
${function(){
const rules = data.data.rules;
return `
`
}()}
${function(){
const isCart = data.data.isCart;
const isCollection = data.data.isCollection;
const isProduct = data.data.isProduct;
const isIndex = data.data.isIndex;
return `
${isCart ? 'The items in the shopping cart do not participate in any recommendation rule. Add the participating items to your shopping cart to check the design.' : ''}
${isProduct ? 'This product did not participated in any recommendation rule. Switch to another product to check the design.' : ''}
${isCollection ? 'The items in this collection do not participate in any recommendation rule. Switch the participating items to check the design.' : ''}
${isIndex ? 'The home page do not participate in any recommendation rule.' : ''}
(This prompt would not display on client-side)
Recommended Products
`
}()}
${function(){
const rule = data.data;
const getImageHeight = function(image){
const image_size = rule.config.image_size || 0;
const imageWidth = image.width || 600;
const imageHeight = image.height || 800;
let ratio = 0;
if(image_size == 0){
ratio = (imageHeight / imageWidth).toFixed(2);
}else if(image_size == 1){
ratio = 1.5;
}else if(image_size == 2){
ratio = 1;
}else if(image_size == 3){
ratio = 0.75;
}
return imageWidth * ratio;
};
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('&');
return `
`
}()}
class SpzSmartBlockComponent extends SPZ.BaseElement {
constructor(element) {
super(element);
this.templates_ = null;
this.container_ = null;
this.i18n_ = {};
this.config_ = {};
this.show_type_ = 3;
this.product_resource_id_ = '';
this.collection_resource_id_ = '';
this.cart_items_ = [];
this.customer_id_ = '';
this.order_id_ = '';
}
static deferredMount() {
return false;
}
isLayoutSupported(layout) {
return layout == SPZCore.Layout.CONTAINER;
}
buildCallback() {
const template_type = window.SHOPLAZZA.meta.page.template_type;
if (template_type === 1) {
this.show_type_ = 3;
this.product_resource_id_ = window.SHOPLAZZA.meta.page.resource_id;
} else if (template_type === 2) {
this.show_type_ = 4;
this.collection_resource_id_ = window.SHOPLAZZA.meta.page.resource_id;
} else if (template_type === 15){
this.show_type_ = 5;
} else if (template_type === 13){
this.show_type_ = 6;
} else if (template_type === 20){
this.show_type_ = 7;
this.customer_id_ = window.SHOPLAZZA.customer.customer_id;
} else if (template_type === 35){
this.show_type_ = 8;
this.order_id_ = window.location.pathname.split('/').pop();
}
this.templates_ = SPZServices.templatesForDoc(this.element);
this.setAction_();
}
mountCallback() {
console.log('smart mounted');
const that = this;
const themeName = window.SHOPLAZZA.theme.merchant_theme_name;
const isGeek = /Geek/.test(themeName);
this.fetchRules().then((res) => {
if (res && res.rules && res.rules.length) {
const blockEl = document.getElementById('smart_recommend_block');
SPZ.whenApiDefined(blockEl).then((api) => {
api.render({data: res}, true).then(() => {
if (isGeek && that.show_type_ === 6) {
blockEl.querySelector('.plugin_container_wrpper').style.padding = '30px 0';
}
const recommendStyle = document.createElement('style');
recommendStyle.innerHTML = `
.plugin__recommend_container,.app-recommend-card {
display: none !important;
}
`;
document.head.appendChild(recommendStyle);
const fetchList = [];
res.rules.forEach((rule) => {
fetchList.push(this.fetchRuleProductList(rule.id));
});
const fetchAll = Promise.all(fetchList);
fetchAll.then((p_res) => {
res.rules.forEach((rule, index) => {
rule.products = p_res[index] && p_res[index].products;
const ruleEl = document.getElementById('smart_recommend_rule_' + rule.id);
SPZ.whenApiDefined(ruleEl).then((api) => {
api.render({data: rule}, true).then(() => {
that.impressListen(`#smart_recommend_rule_ul_${rule.id}`, function(){
that.trackRuleImpress(rule);
});
const btnElList = document.querySelectorAll(`#smart_recommend_rule_ul_${rule.id} button`);
btnElList.forEach((btnEl) => {
if (btnEl && rule.config && rule.config.quick_shop_button_bg_color && rule.config.quick_shop_button_text_color) {
btnEl.style.backgroundColor = rule.config.quick_shop_button_bg_color;
btnEl.style.color = rule.config.quick_shop_button_text_color;
}
})
});
});
});
});
})
})
} else {
if (window.top !== window.self) {
const template_type = window.SHOPLAZZA.meta.page.template_type;
const holderEl = document.getElementById('smart_recommend_preview_no_data_placeholder');
SPZ.whenApiDefined(holderEl).then((api) => {
api.render({data: { isCart: template_type === 13, isCollection: template_type === 2, isProduct: template_type === 1, isIndex: template_type === 15 }}, true);
});
}
}
});
}
setAction_() {
this.registerAction('quickShop', (data) => {
const that = this;
const product_id = data.args.product_id;
const productIndex = data.args.productIndex;
const rule_id = data.args.rule_id;
const ssp = data.args.ssp;
const scm = data.args.scm;
const cfb = data.args.cfb;
const ifb = data.args.ifb;
const modalRender = document.getElementById('smart_recommend_product_modal_render');
if (product_id) {
this.fetchProductData(product_id).then((res) => {
const product = res.products && res.products.length && res.products[0] || {};
product.cfb = cfb;
product.ifb = ifb;
SPZ.whenApiDefined(modalRender).then((api) => {
api.render({product: product, productIndex: productIndex, rule_id: rule_id, ssp: ssp, scm: scm, show_type: that.show_type_}, true).then(() => {
const modalEl = document.getElementById('smart_recommend_product_modal');
SPZ.whenApiDefined(modalEl).then((modal) => {
that.impressListen('#smart_recommend_product_modal', function(){
that.trackQuickShop({ rule_id: rule_id, product_id: product_id });
});
modal.open();
});
const formEl = document.getElementById('smart_recommend_product_form');
SPZ.whenApiDefined(formEl).then((form) => {
form.setProduct(product);
});
const variantEl = document.getElementById('smart_recommend_product_variants');
SPZ.whenApiDefined(variantEl).then((variant) => {
variant.handleRender(product);
});
});
})
});
}
});
this.registerAction('handleScroll', (data) => {
this.directTo(data.args.rule_id, data.args.direction);
});
this.registerAction('handleProductChange', (data) => {
const variant = data.args.data.variant;
const product = data.args.data.product;
const imageRenderEl = document.getElementById('smart_recommend_product_image');
SPZ.whenApiDefined(imageRenderEl).then((api) => {
api.render({ variant: variant, product: product }, true);
});
});
this.registerAction('handleAtcSuccess', (detail) => {
const data = detail.args;
data.data.product = data.data.product || {};
data.data.variant = data.data.variant || {};
const product_id = data.data.product.id;
const product_title = data.data.product.title;
const variant_id = data.data.variant.id;
const price = data.data.variant.price;
const rule_id = data.rule_id;
const aid = `smart_recommend.${this.show_type_}.${rule_id}`;
const ifb = data.data.product.ifb;
const cfb = data.data.product.cfb;
const ssp = data.ssp;
const scm = data.scm;
const spm = `smart_recommend_${this.show_type_}.${data.spmIndex}`;
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.SHOPLAZZA.meta.page.template_name}.${spm}`,
ssp: ssp,
}
};
this.tranckAddToCart(params);
});
this.registerAction('addATCHook', (data) => {
const params = data.args;
const spm = `smart_recommend_${this.show_type_}.${params.spmIndex}`;
this.myInterceptor_ = window.djInterceptors && window.djInterceptors.track.use({
event: 'dj.addToCart',
params: {
aid: `smart_recommend.${this.show_type_}.` + params.rule_id,
ssp: params.ssp,
scm: params.scm,
cfb: params.cfb,
spm: `..${window.SHOPLAZZA.meta.page.template_name}.${spm}`,
},
once: true
});
});
}
tranckAddToCart(detail) {
if (window.$) {
window.$(document.body).trigger('dj.addToCart', detail);
}
}
fetchRules() {
const payload = {
show_type: this.show_type_,
};
let that = this;
if (this.show_type_ === 6) {
let line_items = [];
return this.fetchCart().then((res) => {
if (res && res.cart && res.cart.line_items) {
line_items = res.cart.line_items.map((item) => {
return { product_id: item.product_id, variant_id: item.variant_id, quantity: item.quantity, price: item.price }
});
}
payload.line_items = line_items;
that.cart_items_ = line_items;
return that.fetchRulesRequest(payload);
});
} else {
if (this.show_type_ === 3) {
payload.line_items = [{ product_id: this.product_resource_id_ }];
} else if (this.show_type_ === 4) {
payload.collection_id = this.collection_resource_id_;
} else if (this.show_type_ === 7) {
payload.customer_id = this.customer_id_;
} else if (this.show_type_ === 8) {
payload.order_id = this.order_id_;
}
return this.fetchRulesRequest(payload);
}
}
fetchRulesRequest(payload) {
return fetch(window.SHOPLAZZA.routes.root + "/api/possum/recommend_query", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
}).then(function(res){
if(res.ok){
return res.json();
}
});
}
fetchCart() {
return fetch(`/api/cart/cart-select?r=${Math.random().toString(36).slice(-4)}`)
.then((res) => {
if (res.ok) {
return res.json();
}
});
}
fetchRuleProductList(rule_id) {
const payload = {
page: 1,
limit: 100,
fields: ["title", "url", "image", "min_price_variant.price", "min_price_variant.compare_at_price"],
rule_id: rule_id,
};
if (this.show_type_ === 3) {
payload.line_items = [{ product_id: this.product_resource_id_ }];
} else if (this.show_type_ === 4) {
payload.collection_id = this.collection_resource_id_;
} else if (this.show_type_ === 6) {
payload.line_items = this.cart_items_;
} else if (this.show_type_ === 7) {
payload.customer_id = this.customer_id_;
} else if (this.show_type_ === 8) {
payload.order_id = this.order_id_;
}
return fetch(window.SHOPLAZZA.routes.root + "/api/possum/recommend_products", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(payload)
}).then(function(res){
if(res.ok){
return res.json();
}
}).catch(function(err){
console.log(err);
});
}
fetchProductData(product_id) {
return fetch(window.SHOPLAZZA.routes.root + "/api/possum/products", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
product_ids: [product_id],
fields: [ "images", "options", "min_price_variant", "variants"]
})
}).then(function(res){
if(res.ok){
return res.json();
}
}).catch(function(err){
console.log(err);
const loadingEl = document.getElementById('smart_recommend_loading');
if (loadingEl) {
loadingEl.style.display = 'none';
}
});
}
getStyle(ele, style) {
if (!ele) return;
if (window.getComputedStyle) {
return window.getComputedStyle(ele)[style];
}
return ele.currentStyle[style];
}
directTo(id, direction) {
const scrollElement = document.getElementById(`smart_recommend_rule_ul_${id}`);
const blockWidth = parseInt(this.getStyle(scrollElement, 'width'));
const scrollLength = (blockWidth * 0.19 - 12) * 5;
const scrollPoint = scrollElement.scrollWidth - scrollElement.clientWidth;
if (!scrollElement) return;
if (direction === 'left') {
if (document.dir === 'rtl') {
scrollElement.scrollTo({
left: Math.abs(scrollElement.scrollLeft) >= scrollPoint - 100 ? 0 : scrollElement.scrollLeft - scrollLength,
behavior: 'smooth'
});
return;
}
scrollElement.scrollTo({
left: Math.max(scrollElement.scrollLeft - scrollLength, 0),
behavior: 'smooth'
});
} else {
if (document.dir === 'rtl') {
scrollElement.scrollTo({
left: Math.abs(scrollElement.scrollLeft) >= scrollPoint + 100 ? 0 : scrollElement.scrollLeft + scrollLength,
behavior: 'smooth'
});
return;
}
scrollElement.scrollTo({
left: scrollElement.scrollLeft >= scrollPoint - 100 ? 0 : scrollElement.scrollLeft + scrollLength,
behavior: 'smooth'
});
}
}
trackRuleImpress(rule) {
if (window.sa && window.sa.track) {
window.sa.track("plugin_common", {
plugin_name: "upsell",
event_type: "impressions",
rule_id: rule.id,
ssp: rule.ssp,
scm: rule.scm,
show_type: this.show_type_,
support_app_block: window.SHOPLAZZA.theme.support_app_block
});
window.sa.track("module_impressions", {
aid: `smart_recommend.${this.show_type_}.${rule.id}`,
support_app_block: window.SHOPLAZZA.theme.support_app_block
});
}
}
trackQuickShop(data) {
window.sa && sa.track && sa.track("plugin_common", {
plugin_name: "upsell",
event_type: "quick_shop",
rule_id: data.rule_id,
product_id: data.product_id,
show_type: this.show_type_,
});
}
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-block', SpzSmartBlockComponent);
${(function(){
const product = data.product;
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('&');
return `
${product.images.map((image) => { return `` }).join('')}
`;
})()}
${(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 `
`
})()}