"; source = ((CCRZ.getCookie("handlebars") != "") ? preSource : "") + data; } }); } } else { preSource = "" + id + "
"; source = ((CCRZ.getCookie("handlebars") != "") ? preSource : "") + source; } return Handlebars.compile(source); } }); /* //////////////////////////////////////////////////////// //////////////// GLOBAL AUXILIAR FUNCTIONS //////////////// */ ///////////////////////////////////////////////////////// // CLONE ANY OBJECT function cloneObject(objectToClone) { return JSON.parse(JSON.stringify(objectToClone)); } //Asigna a un un texto de error //Parametros: //elem: $("#elemento") o $(".clase") etc //message: "mensaje de error" function setMessageErrorInElement(elem, message) { elem.html(message).css("color", "#ff0000"); } //Limpia el de error //Parametros: //elem: $("#elemento") o $(".clase") etc //millisecond: 3000 o la cantidad de milisegundos que desee function hideMessageErrorInElement(elem, millisecond) { setTimeout(() => { elem.html(''); }, millisecond); } //Deshabilita los input de un form //Parametros: //elem: $("#elemento") o $(".clase") etc //excludeInput: string de input que desea excluir separados por coma(,). Ejm: "#txtInput1,.txtClassBtn,#txtArea" function disabledForm(elem, excludeInput) { if (excludeInput != undefined) { elem.not(excludeInput).prop('disabled', true); } else { elem.prop('disabled', true); } } //Habilita los input de un form //Parametros: //elem: $("#elemento") o $(".clase") etc function enabledForm(elem) { elem.prop('disabled', false); } //Valida si es visita o no function IsGuest() { if (CCRZ.currentUser.UserType == 'Guest') { return true; } else { return false; } } //Retorna el nombre del día de la semana function getDayName(dayNumber) { let weekday = new Array(7); weekday[0] = "Global_DayName1"; weekday[1] = "Global_DayName2"; weekday[2] = "Global_DayName3"; weekday[3] = "Global_DayName4"; weekday[4] = "Global_DayName5"; weekday[5] = "Global_DayName6"; weekday[6] = "Global_DayName7"; return weekday[dayNumber]; } //Habilita los popovers de un form //Parametros: //elem: $("#elemento") o $(".clase") etc function showMessageTypePopover(elem, title, content, timeClose) { if(CCRZ.getPageConfig('pd.enablepopuppl')){ if($(elem).data('isavailableurl')){ elem.attr('data-html', true); let brandTitle=CCRZ.productDetailModel.attributes.product.prodBean.brandName; let labelBrand=CCRZ.pagevars.pageLabels.seeMoreProductsByBrand?CCRZ.pagevars.pageLabels.seeMoreProductsByBrand:''; let writter=''; let store=CCRZ.pagevars.storefrontName; writter+=''+content+'
'; writter+=''+' '+labelBrand+' '+ brandTitle+' '; content=writter; title=''+title+'
'; } let timeToSet=(CCRZ.getPageConfig('pd.settimepopup')?CCRZ.getPageConfig('pd.settimepopup'):30000); timeClose=parseInt(timeToSet); } elem.attr('title', title); elem.attr('data-content', content); elem.attr('data-trigger', 'focus'); elem.attr('data-toggle', 'popover'); elem.attr('data-container', 'body'); elem.attr('data-placement', 'top'); elem.popover("show"); setTimeout(() => { elem.popover("hide"); elem.popover("destroy"); }, timeClose); } function getJsonToAddCart(idProd, qty, typeProduct) { let data = []; // ----- FIX FOR COMPARE PRODUCTS let viewState = $("#viewState").val() == undefined? "ListView":$("#viewState").val() if (viewState == "ListView") { data.push({ prodId: idProd, qty: qty }); } else if (viewState == "DetailView") { if (typeProduct == "Dynamic Kit") { let prods = CCRZ.dynamicKitView.selView.dataSet.selList.toJSON(); for (p of prods) { data.push({ prodId: p.id, qty: p.quantity }); } } else { data.push({ prodId: idProd, qty: qty }); } } return data; } function percentagesOfDiscount(price, basePrice){ let percent = 100, result = 0; result = ((percent - (percent * price) / basePrice)).toFixed(); return result + '%'; } //-------------------------------------------------------------------------------- // ------------------ FORMATO DE NUMERO SEPARADO POR COMAS ----------------------- //-------------------------------------------------------------------------------- var formatNumber = { separador: ",", // separador para los miles sepDecimal: '.', // separador para los decimales formatear:function (num){ num +=''; var splitStr = num.split('.'); var splitLeft = splitStr[0]; var splitRight = splitStr.length > 1 ? this.sepDecimal + splitStr[1] : ''; var regx = /(\d+)(\d{3})/; while (regx.test(splitLeft)) { splitLeft = splitLeft.replace(regx, '$1' + this.separador + '$2'); } return this.simbol + splitLeft + splitRight; }, new:function(num, simbol){ this.simbol = simbol ||''; return this.formatear(num); } } function cartItemsHasSelectSubscrip(){ if(CCRZ.cartCheckoutModel.attributes.cartItems){ let found = CCRZ.cartCheckoutModel.attributes.cartItems.find(x => x.hasOwnProperty("subProdterm")); if(found){ return true; }else{ return false; } }else{ return false; } } function getPrefixStore() { return CCRZ.pagevars.storefrontName.toLowerCase().indexOf("cochez") > 0 ? 'C' : 'N'; } function getPrefixStore2() { return CCRZ.pagevars.storefrontName.toLowerCase().indexOf("cochez") > 0 ? 'CO' : 'NO'; } function getPrefixStore3(){ return CCRZ.pagevars.storefrontName.toLowerCase().indexOf("cochez") > 0 ? 'Chz' : 'Nvy'; } function getCodeCompany() { return CCRZ.pagevars.storefrontName.toLowerCase().indexOf("cochez") > 0 ? '01' : '03'; } function getNameCompany(){ return CCRZ.pagevars.storefrontName.toLowerCase().indexOf("cochez") > 0 ? 'Cochez' : 'Novey'; } function getGeneralNameCategories() { return['Root: CochezB2C', 'Root: NoveyB2C', 'Root: NoveyB2C2','Root: CochezB2B']; } //-------------------------------------------------------------------------------- function updateMiniCartFields(){ // subtotal, tax, shipping let subtotal; if(CCRZ.pagevars.storefrontName.includes('B2B')){ subtotal = (CCRZ.LLIPaymentModel.attributes.cartData.subtotalAmount != undefined)? parseFloat(CCRZ.LLIPaymentModel.attributes.cartData.subtotalAmount) : 0, tax = (CCRZ.LLIPaymentModel.attributes.cartData.taxAmount != undefined)? parseFloat(CCRZ.LLIPaymentModel.attributes.cartData.taxAmount) : 0, shipping = (CCRZ.LLIPaymentModel.attributes.cartData.shipAmount != undefined)? parseFloat(CCRZ.LLIPaymentModel.attributes.cartData.shipAmount) : 0. itbmsString = parseFloat(tax).toFixed(2), itbms = parseFloat(itbmsString) }else{ subtotal = (CCRZ.cartCheckoutView.model.attributes.subtotalAmount != undefined)? parseFloat(CCRZ.cartCheckoutView.model.attributes.subtotalAmount) : 0, tax = (CCRZ.cartCheckoutView.model.attributes.tax != undefined)? parseFloat(CCRZ.cartCheckoutView.model.attributes.tax) : 0, shipping= (CCRZ.cartCheckoutView.model.attributes.shippingCharge != undefined)? parseFloat(CCRZ.cartCheckoutView.model.attributes.shippingCharge) : 0. itbmsString = parseFloat(tax).toFixed(2), itbms = parseFloat(itbmsString) } // totalAmount = (subtotal + itbms + shippingCharge).toFixed(2) console.log('subtotal',subtotal, 'tac',tax, 'shipping',shipping ) subtotal = parseFloat(subtotal) tax = parseFloat(tax) shipping = parseFloat(shipping) itbmsString=parseFloat(tax).toFixed(2); itbms=parseFloat(itbmsString); suma=subtotal + itbms + shipping; var total=suma.toFixed(2); // console.log("totsum",sumaTot); // total = parseFloat((subtotal + tax + shipping)).toFixed(2) // console.log('total',total); $("#writerTax").empty(); $("#writertotalAmount").empty(); $("#writerShip").empty(); $("#writerTax").append(formatNumber.new(itbms, "$")); $("#writertotalAmount").append(formatNumber.new( total, "$") ); $("#writerShip").append(formatNumber.new( shipping, "$") ); //writeExtData(); $(".plusInfo").attr("style","display:block"); $(".plusInfoTot").attr("style","display:block"); $(".plusInfoEnv").attr("style","display:block"); } function writeExtData(){ $("#writerExtDataComprador").empty(); var writer=""; console.log('check type',CCRZ.CheckoutPayload.DeliveryType); if(CCRZ.CheckoutPayload.DeliveryType=='DOM'){ writer+=""; if(CCRZ.pagevars.storefrontName=='B2CNovey'){ writer+="
Información de envío "; } else if(CCRZ.pagevars.storefrontName=='B2CCochez'){ writer+="
Información de envío "; } writer+="
"+CCRZ.processPageLabelMap('AddressInMap_Country') +': '+CCRZ.CheckoutPayload.Country+"
"; writer+="
"+CCRZ.processPageLabelMap('Checkout_ship_description') +': '+CCRZ.CheckoutPayload.addressDescription+"
"; // writer+="
"+CCRZ.processPageLabelMap('Checkout_ChooseDeliveryDate') +': '+CCRZ.CheckoutPayload.liMainDelivery+"
"; writer+="
"+CCRZ.processPageLabelMap('Checkout_ChooseDeliveryDate') +': '+CCRZ.CheckoutPayload.DeliveryDate+"
"; writer+="
"; }else if(CCRZ.CheckoutPayload.DeliveryType=='SUC'){ writer+=""; if(CCRZ.pagevars.storefrontName=='B2CNovey'){ writer+="
Información de retiro "; } else if(CCRZ.pagevars.storefrontName=='B2CCochez'){ writer+="
Información de retiro "; } writer+="
"+CCRZ.processPageLabelMap('Checkout_suc_description') +': '+CCRZ.CheckoutPayload.DeliveryTypeDesc+"
"; writer+="
"+CCRZ.processPageLabelMap('Checkout_suc_select') +': '+CCRZ.CheckoutPayload.Store+"
"; writer+="
"; } $("#writerExtDataComprador").append(writer); } function writerData( name,ape,email){ $("#writerDataComprador").empty(); // var ape=CCRZ.cartCheckoutView.model.attributes.buyerLastName; // var email=CCRZ.cartCheckoutView.model.attributes.buyerEmail; var writer=""; writer+=""; if(CCRZ.pagevars.storefrontName=='B2CNovey'){ writer+="
" + CCRZ.processPageLabelMap('Component_MiniCart_BuyerInformation') + "
"; } else if(CCRZ.pagevars.storefrontName=='B2CCochez'){ writer+="
" + CCRZ.processPageLabelMap('Component_MiniCart_BuyerInformation') + "
"; } writer+="
"; writer+=""; if(CCRZ.pagevars.storefrontName=='B2CNovey'){ writer+="
" + CCRZ.processPageLabelMap('Name') + ":
"; writer+="
"+name+" "+ape+"
"; }else if(CCRZ.pagevars.storefrontName=='B2CCochez'){ writer+="
" + CCRZ.processPageLabelMap('Name') + ": "+name+" "+ape+"
"; // writer+="
"+name+" "+ape+"
"; } writer+="
"; writer+=""; if(CCRZ.pagevars.storefrontName=='B2CNovey'){ writer+="
" + CCRZ.processPageLabelMap('EMail') + "
"; writer+="
"+email+"
"; }else if(CCRZ.pagevars.storefrontName=='B2CCochez'){ writer+="
" + CCRZ.processPageLabelMap('EMail') + ": "+email+"
"; } writer+="
"; $("#writerDataComprador").append(writer); } function paintCustomerData(){ if(CCRZ.pagevars.isGuest){ var nameP=CCRZ.cartCheckoutView.model.attributes.buyerFirstName; var apeP=CCRZ.cartCheckoutView.model.attributes.buyerLastName; var emailP=CCRZ.cartCheckoutView.model.attributes.buyerEmail; writerData(nameP, apeP,emailP); }else{ var nameP=CCRZ.currentUser.FirstName; var apeP=CCRZ.currentUser.LastName; var emailP=CCRZ.currentUser.Email; writerData(nameP, apeP,emailP); } } function clearAmuntAndDelivaryData(){ $("#writerTax").empty(); $("#writertotalAmount").empty(); $("#writerShip").empty(); $("#writerExtDataComprador").empty(); $(".plusInfo").attr("style","display:none"); $(".plusInfoTot").attr("style","display:none"); $(".plusInfoEnv").attr("style","display:none"); } function updateInfo(){ CCRZ.LoadTaxMiniCart=null; if(CCRZ.pagevars.currentPageName == "ccrz__CheckoutNew"){ if(CCRZ.pagevars.isGuest){ CCRZ.LoadTaxMiniCart =setInterval(function() { if(!(typeof CCRZ.cartCheckoutView.model.attributes.buyerFirstName == "undefined")){ // var nameP=CCRZ.cartCheckoutView.model.attributes.buyerFirstName; // var apeP=CCRZ.cartCheckoutView.model.attributes.buyerLastName; // var emailP=CCRZ.cartCheckoutView.model.attributes.buyerEmail; // writerData(nameP, apeP,emailP); paintCustomerData() if(CCRZ.CheckoutPayload!=undefined){ writeExtData(); } updateMiniCartFields(); clearInterval(CCRZ.LoadTaxMiniCart); } }, 1000); }else{ CCRZ.LoadTaxMiniCart =setInterval(function() { console.log('pregunta') if(!(typeof CCRZ.currentUser === "undefined")){ console.log( 'curr:-',CCRZ.currentUser); // var nameP=CCRZ.currentUser.FirstName; // var apeP=CCRZ.currentUser.LastName; // var emailP=CCRZ.currentUser.Email; // writerData(nameP, apeP,emailP); paintCustomerData() if(CCRZ.CheckoutPayload!=undefined){ writeExtData(); } updateMiniCartFields(); clearInterval(CCRZ.LoadTaxMiniCart); } }, 1000); } } } function is_MC_Pixel_Active() { let isActive = false if(typeof _etmc !== "undefined" && CCRZ.getPageConfig('sfmc.mcp_enable',false)){ isActive = true } return isActive } function getCategoryNameFromFilterDataProp(paramObj) { //DATALAYER AJX //se obtiene la categoría del producto try { let catFilter = ''; catFilter = paramObj .split('|') .filter(x => x.includes('CategoryName')) .find(x => !x.includes('SubCategory')) .split('=')[1]; return catFilter; } catch (error) { // console.log( error ); return ''; } } function getCategoryNameFromLocalStorage(sku) { //DATALAYER AJX //se obtiene la categoría del producto try { let catName = ''; catName = JSON.parse(localStorage.getItem( "DatalayerCategoryProduct" )) .find(x => x.prod == sku).cat; return catName; } catch (error) { // console.log( error ); return ''; } } function setLocalStorageDatalayerCategoryProduct(objProdCat, deleteStorage) { try { if(deleteStorage){ localStorage.removeItem('DatalayerCategoryProduct'); return } let prodCatObj = []; let getStorage = localStorage.getItem('DatalayerCategoryProduct'); if(getStorage){ prodCatObj = JSON.parse(getStorage); prodCatObj.push(objProdCat); localStorage.setItem('DatalayerCategoryProduct', JSON.stringify(prodCatObj)); } else{ prodCatObj.push(objProdCat); localStorage.setItem('DatalayerCategoryProduct', JSON.stringify(prodCatObj)); } } catch (error) { } } function linkHawkSend(e){ let hawkKey=CCRZ.pagevars.storefrontName=='B2CCochez'? '3f3063fb0b584d43b6c91421aede6c03' : '49842e22915f43fcbcc5c5bcd8280800'; HawkSearch.link(e,hawkKey,1, e.target.dataset.productsfid,0) ; //e.stopImmediatePropagation(); } ////////////////////////////////////////////////////////////////////////////////////////// // PREPARE DATA TO USE IN PRODUCT CLICK DATALAYER ////////////////////////////////////////////////////////////////////////////////////////// function callProductClick_DataLayer(e) { let dataProduct = JSON.parse(e.currentTarget.getAttribute("data-product")), // productUrl = e.toElement.href productUrl =e.currentTarget.href // console.log('dataProduct event ----> ',dataProduct) dataProduct.productUrl = productUrl let viewState = new URLSearchParams(window.location.search).getAll('viewState')[0], operation = new URLSearchParams(window.location.search).getAll('operation')[0], isCategory = CCRZ.productListPageModel == undefined? false : CCRZ.productListPageModel.attributes.isCategory if(dataProduct.typeProduct == "Spotlight" || dataProduct.typeProduct == "Featured"){ viewState = "ListView" dataProduct.category = dataProduct.typeProduct == "Spotlight"? "Destacados" : "Recomendados" } if (viewState == "ListView" || operation == "quickSearch") { dataProduct.listType = (viewState == "ListView"? viewState:operation) } if(isCategory){ if(CCRZ.productListPageModel.attributes.category.sfdcName == "Root: CochezB2C"){ dataProduct.category = "Ofertas" }else{ dataProduct.category = CCRZ.productListPageModel.attributes.category.sfdcName } } CCRZ.pubSub.trigger('productClick', dataProduct); } function callCategoryLinkClick_DataLayer(e) { let dataPromo = JSON.parse(e.currentTarget.getAttribute("data-category")) if(dataPromo != null || dataPromo != undefined){ CCRZ.pubSub.trigger('promoClick', dataPromo) }else{ console.log('vacio') } } // --------------------- PROTOTYPE ------------------------ String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } // ---------------- REMOTE INVOKE ACTION ----------------- // Utilizar para cuando el método del controlador recive un JSON como parámetro //----- // Parámetros // remoteCallObj: el objeto con contexto del controlador que se va utilizar. // remoteActionName: nombre del metodo o action a ejecutar en el controlador // data: parametros(objeto) en formato string function callCtrlRemoteAction(remoteCallObj, remoteActionName, data) { // console.log(arguments); return new Promise(function(resolve, reject) { remoteCallObj.invokeContainerLoadingCtx($('.deskLayout'), remoteActionName, data, function(res, err) { if (res != null) { resolve(res); } else if (err.message != "") { resolve(err); } }, { nmsp: false }); }); } //####################################################################################################################// // * * * * * * * * * * * * * * * * * * * * GOOGLE TAG MANAGER * * * * * * * * * * * * * * * * * * * * * * * * * *// // * * * * * * * * * * * * * * * * * * * * * * * DATALAYER * * * * * * * * * * * * * * * * * * * * * * * * * * * *// //####################################################################################################################// //-------------------------------------------------------------------------------- // --------------- EVENTO: IMPRESSIONS ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("productPrint", function(productList) { // console.log('productPrint ', productList) if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_ProductPrint(productList) } }); //---------- Format data function setDataLayer_ProductPrint(productList) { // console.log('setDataLayer_ProductPrint ', productList) let data = { 'ecommerce': { 'currencyCode': CCRZ.pagevars.currencyData.currencyName, 'impressions': [] } } // console.log('data ----> ', data) let productIndex = 0, viewState = new URLSearchParams(window.location.search).getAll('viewState')[0], operation = new URLSearchParams(window.location.search).getAll('operation')[0], listType = "", isCategory = CCRZ.productListPageModel !== undefined? CCRZ.productListPageModel.attributes.isCategory : "", categoryName = "" if(isCategory){ if(CCRZ.productListPageModel.attributes.category.sfdcName == "Root: CochezB2C"){ categoryName = "Ofertas" }else{ categoryName = CCRZ.productListPageModel.attributes.category.sfdcName } } // CCRZ.productListPageModel.attributes.category.sfdcName == "Root: CochezB2C"? "Ofertas" : product.model.attributes.category.sfdcName) : "" if (viewState == "ListView" || operation == "quickSearch") { listType = (viewState == "ListView"? viewState:operation) // console.log('listType -> ', listType) } for(product of productList){ // console.log('product solo -> ', product.model.attributes) data.ecommerce.impressions.push({ name: product.model.attributes.sfdcName, id: product.model.attributes.SKU, price: product.model.attributes.price, brand: product.model.attributes.brandName == undefined? "": product.model.attributes.brandName, category: isCategory? categoryName : "", variant: '', 'list': listType, 'position': (productIndex + 1) }); productIndex++ // console.log('productIndex ', data) } pushDataLayer(data) }; //-------------------------------------------------------------------------------- // --------------- EVENTO: RELATED PRODUCT IMPRESSIONS ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("relatedProductPrint", function(productList, sectionName) { // console.log('productPrint ', productList) if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_RelatedProductPrint(productList, sectionName) } }); //---------- Format data function setDataLayer_RelatedProductPrint(productList, sectionName) { // console.log('setDataLayer_ProductPrint ', productList) let data = { 'ecommerce': { 'currencyCode': CCRZ.pagevars.currencyData.currencyName, 'impressions': [] } } // console.log('data ----> ', data) let productIndex = 0 for(product of productList){ // console.log('product solo -> ', product.model.attributes) if(sectionName =="Cart_CrossSell"){ data.ecommerce.impressions.push({ name: product.mockProduct.sfdcName, id: product.mockProduct.sku, price: product.price, brand: product.mockProduct.brandName == undefined? "": product.mockProduct.brandName, category: "", variant: '', list: sectionName + ' carousel', position: (productIndex + 1) }); }else{ data.ecommerce.impressions.push({ name: product.prodBean.sfdcName, id: product.prodBean.sku, price: product.price, brand: product.prodBean.brandName == undefined? "": product.prodBean.brandName, category: "", variant: '', list: 'Product Detail - ' + sectionName + ' carousel', position: (productIndex + 1) }); } productIndex++ // console.log('productIndex ', data) } pushDataLayer(data) }; //-------------------------------------------------------------------------------- // --------------- EVENTO: PRODUCT DETAIL IMPRESSION ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("productDetailPrint", function(productList) { // console.log('productPrint ', productList) if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_ProductDetailPrint(productList) } // * * * UPDATE CART ITEMS MARKETING CLOUD PIXEL * * * if(is_MC_Pixel_Active() && (CCRZ.getPageConfig('sfmc.acc_id', '') !== '' && CCRZ.getPageConfig('sfmc.acc_id', '') !== 'Empty') ){ setTimeout(() => { if(CCRZ.getPageConfig('env.isprod',false)){ _etmc.push(["setOrgId", CCRZ.getPageConfig('sfmc.acc_id', '')]); _etmc.push(["trackPageView", { "item" : productList.SKU}]); }else{ console.log("Product SKU => ", productList[0].SKU) } }, 500); } }); //---------- Format data function setDataLayer_ProductDetailPrint(productList) { // console.log('setDataLayer_ProductPrint ', productList) let data = { 'ecommerce': { 'detail': { 'actionField': {'list': ''}, 'products': [] } } } // console.log('data ----> ', data) let productIndex = 0, viewState = new URLSearchParams(window.location.search).getAll('viewState')[0], operation = new URLSearchParams(window.location.search).getAll('operation')[0], listType = "", isCategory = CCRZ.productListPageModel !== undefined? CCRZ.productListPageModel.attributes.isCategory : "", categoryName = "" if(isCategory){ if(CCRZ.productListPageModel.attributes.category.sfdcName == "Root: CochezB2C"){ categoryName = "Ofertas" }else{ categoryName = CCRZ.productListPageModel.attributes.category.sfdcName } } // CCRZ.productListPageModel.attributes.category.sfdcName == "Root: CochezB2C"? "Ofertas" : product.model.attributes.category.sfdcName) : "" if (viewState == "ListView" || operation == "quickSearch") { listType = (viewState == "ListView"? viewState:operation) // console.log('listType -> ', listType) } for(product of productList){ // console.log('product solo -> ', product.model.attributes) data.ecommerce.detail.products.push({ name: product.sfdcName, id: product.SKU, price: product.price, brand: product.brandName == undefined? "": product.brandName, category: getCategoryNameFromFilterDataProp(product.filterData), variant: '' }); productIndex++ } pushDataLayer(data) }; //-------------------------------------------------------------------------------- // --------------- EVENTO: CART ITEMS IMPRESSION -------------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("cartItemsPrint", function(items) { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_CartItemsPrint(items) } }) //---------- Format data function setDataLayer_CartItemsPrint(items){ let data = { 'ecommerce': { 'currencyCode': CCRZ.pagevars.currencyData.currencyName, 'impressions': [] } } let productIndex = 0 for(item of items){ data.ecommerce.impressions.push({ name: item.attributes.product.sfdcName, id: item.attributes.product.SKU, price: item.attributes.price, brand: item.attributes.product.brandName == undefined? "": item.attributes.product.brandName, category: "", variant: '', list: 'Cart Items', position: (productIndex + 1), quantity: item.attributes.quantity }); productIndex++ } pushDataLayer(data) } //-------------------------------------------------------------------------------- // --------------- EVENTO: CLICK PRODUCTO ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("productClick", function(productList) { // console.log('productClick ', productList) if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_ProductClick(productList) } }); //---------- Format data function setDataLayer_ProductClick(productList) { // console.log('setDataLayer_ProductPrint ', productList) let data = { 'event': 'productClick', 'ecommerce': { 'click': { 'actionField': {'list': productList.listType}, // Optional list property. 'products': [ { 'name': productList.name, // Name or ID is required. 'id': productList.SKU, 'price': productList.price, 'brand': productList.brand == undefined? "":productList.brand, 'category': productList.category == undefined? "":productList.category, 'variant': productList.variant, 'position': productList.position } ] } } // , // 'eventCallback': function() { // document.location = productList.productUrl // } } // console.log('data ----> ', data) pushDataLayer(data) }; //-------------------------------------------------------------------------------- // --------------- EVENTO: ADD TO CART ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("addToCartSuccess", function(qty, typeProduct, dataProduct) { if(CCRZ.getPageConfig('hsm.enable_hs')){ hawkDataTrackCynx(qty, typeProduct, dataProduct);//gs code hawkSearch } if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_AddCart(qty, typeProduct, dataProduct) } // * * * UPDATE CART ITEMS MARKETING CLOUD PIXEL * * * if(is_MC_Pixel_Active()){ setTimeout(() => { set_MC_Pixel_Tracking_CartItems() }, 1500); } }); CCRZ.pubSub.on("chargeFooter", function() { // function hawkLoadEvent(){ if(CCRZ.getPageConfig('hsm.enable_hs')){ if(CCRZ.pagevars.currentPageName=="ccrz__HomePage"){ HawkSearch.Tracking.track('pageload',{pageType: "landing"}); } if(CCRZ.pagevars.currentPageName=="ccrz__Cart"){ HawkSearch.Tracking.track('pageload',{pageType: "cart"}); } if(CCRZ.pagevars.currentPageName=="ccrz__MyAccount"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__CheckoutNew"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__ProductList"){ HawkSearch.Tracking.track('pageload',{pageType: "custom"}); } if(CCRZ.pagevars.currentPageName=="ccrz__ProductList"){ } if(CCRZ.pagevars.currentPageName=="ccrz__ProductDetails"){ // setTimeout(() => { HawkSearch.Context.add("uniqueid", CCRZ.productDetailModel.attributes.product.prodBean.id) // }, 1000); HawkSearch.Tracking.track('pageload',{pageType: "item"}); } } }); function hawkDataTrackCynx(qty, typeProduct, dataProduct){ console.log('datos '+ dataProduct.sfidProd); console.log('datos2 '+ dataProduct.id); sfidHawk=dataProduct.sfidProd?dataProduct.sfidProd:dataProduct.id; sendEventHawkTrackAdd2Cart(sfidHawk,dataProduct.price,qty) } function sendEventHawkTrackAdd2Cart(sfidHawk,price,qty){ console.log('hawkEventSend => '+ sfidHawk); HawkSearch.Tracking.track('add2cart',{ uniqueId: sfidHawk, price: parseFloat(price), quantity: parseInt(qty), currency: 'USD' }); } function hawkDataTrackOrderConfirmation(dataPurchase){ let oItems=[]; if(dataPurchase.orderItems){ for(item of dataPurchase.orderItems ){ if(item.product && item.price && item.quantity){ oItems.push({ uniqueid: item.product, itemPrice: item.price, quantity: item.quantity }) } } HawkSearch.Tracking.track('sale', { orderNo: dataPurchase.orderName, itemList: oItems, total: dataPurchase.totalAmount, subTotal: dataPurchase.subTotal, tax: dataPurchase.tax, currency: 'USD' }); } // HawkSearch.Tracking.track('sale', { // orderNo: dataPurchase.orderName, // itemList: dataPurchase.orderItems, // total: dataPurchase.totalAmount, // subTotal: dataPurchase.subTotal, // tax: dataPurchase.tax, // currency: 'USD' // }); } //---------- Format data function setDataLayer_AddCart(qty, typeProduct, dataProduct) { let data = { 'event': 'addToCart', 'ecommerce': { 'currencyCode': CCRZ.pagevars.currencyData.currencyName, 'add': { 'products': [] } } }; let viewState = new URLSearchParams(window.location.search).getAll('viewState')[0]; let operation = new URLSearchParams(window.location.search).getAll('operation')[0]; if( viewState === undefined && (typeProduct !== "Spotlight" && typeProduct !== "Featured") ){ viewState = "DetailView" } if(typeProduct == "Spotlight" || typeProduct == "Featured"){ viewState = "ListView" dataProduct.category = typeProduct == "Spotlight"? "Destacados" : "Recomendados" } if (viewState == "ListView" || operation == "quickSearch" || window.location.pathname.includes('ccrz__ProductList')) { let catName = ''; if(typeProduct == "Spotlight"){ catName = getCategoryNameFromFilterDataProp(CCRZ.productsPromosView.data.Spotlight.find(x => x.mockProduct.SKU == dataProduct.sku).mockProduct.filterData); } else if(typeProduct == "Featured"){ try { catName = getCategoryNameFromFilterDataProp(CCRZ.views.featuredProduct1View.model.attributes.Featured.find(x => x.mockProduct.SKU == dataProduct.sku).mockProduct.filterData); } catch (error) { catName = ''; } } else{ catName = getCategoryNameFromFilterDataProp(CCRZ.productListPageView.productItemsView.collection.models.find(x => x.attributes.SKU == dataProduct.sku).attributes.filterData); } data.ecommerce.add.products.push({ name: dataProduct.name, id: dataProduct.sku, price: dataProduct.price, brand: dataProduct.brandName == undefined? "": dataProduct.brandName, category: catName, variant: '', qty: qty }); setLocalStorageDatalayerCategoryProduct({prod: dataProduct.sku, cat: catName }, false); } else if (viewState == "DetailView") { if (typeProduct == "Dynamic Kit") { let prods = CCRZ.dynamicKitView.selView.dataSet.selList.toJSON(); for (p of prods) { data.ecommerce.add.products.push({ name: p.name, id: p.sku, price: p.price, brand: p.brandName == undefined? "": p.brandName, category: p.category == undefined? "": p.category, variant: '', qty: p.qty }); } } else { data.ecommerce.add.products.push({ name: dataProduct.name, id: dataProduct.sku, price: dataProduct.price, brand: dataProduct.brandName == undefined? "": dataProduct.brandName, category: dataProduct.category == undefined ? getCategoryNameFromFilterDataProp(CCRZ.productDetailModel.attributes.product.prodBean.filterData) : dataProduct.category, variant: '', qty: qty }); setLocalStorageDatalayerCategoryProduct({prod: dataProduct.sku, cat: getCategoryNameFromFilterDataProp(CCRZ.productDetailModel.attributes.product.prodBean.filterData) }, false); } } pushDataLayer(data) } //-------------------------------------------------------------------------------- // --------------- EVENTO: UPDATE ITEM FROM CART ----------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("updateItemFromCart", function(dataProduct) { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_UpdateItemCart(dataProduct) } // * * * UPDATE CART ITEMS MARKETING CLOUD PIXEL * * * if(is_MC_Pixel_Active()){ setTimeout(() => { set_MC_Pixel_Tracking_CartItems() }, 1500); } }); //---------- Format data function setDataLayer_UpdateItemCart(dataProduct) { let isRem, isAdd = false let dataRem = { 'event': 'removeFromCart', 'ecommerce': { 'remove': { 'products': [] } } }; let dataAdd = { 'event': 'addToCart', 'ecommerce': { 'currencyCode': CCRZ.pagevars.currencyData.currencyName, 'add': { 'products': [] } } }; for(products of dataProduct){ if(products.attributes.quantity != products.attributes.originalQuantity){ if(products.attributes.quantity < products.attributes.originalQuantity){ isRem = true dataRem.ecommerce.remove.products.push({ name: products.attributes.product.sfdcName, id: products.attributes.product.SKU, price: products.attributes.price, brand: products.attributes.product.brandName == undefined? "": products.attributes.product.brandName, category: '', variant: '', qty: (products.attributes.originalQuantity - products.attributes.quantity) }); } else if (products.attributes.quantity > products.attributes.originalQuantity){ isAdd = true dataAdd.ecommerce.add.products.push({ name: products.attributes.product.sfdcName, id: products.attributes.product.SKU, price: products.attributes.price, brand: products.attributes.product.brandName == undefined? "": products.attributes.product.brandName, category: '', variant: '', qty: (products.attributes.quantity - products.attributes.originalQuantity) }); } } } if(isRem){ pushDataLayer(dataRem) } if(isAdd){ pushDataLayer(dataAdd) } } //-------------------------------------------------------------------------------- // --------------- EVENTO: REMOVE FROM CART ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("removeItemFromCart", function(prodRem) { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_RemoveItemCart(prodRem) } }); //---------- Format data function setDataLayer_RemoveItemCart(prodRem) { let dataRem = { 'event': 'removeFromCart', 'ecommerce': { 'remove': { 'products': [] } } }; dataRem.ecommerce.remove.products.push({ name: prodRem.product.sfdcName, id: prodRem.product.SKU, price: prodRem.product.price, brand: prodRem.product.brandName == undefined ? "" : prodRem.product.brandName, category: '', variant: '', qty: prodRem.quantity }); pushDataLayer(dataRem) } //-------------------------------------------------------------------------------- // --------------- EVENTO: PROMOVIEWS (IMPRESIONES DE PROMOS) ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("promoPrint", function(promoView) { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_PromoPrint(promoView) } }); //---------- Format data function setDataLayer_PromoPrint(promoView) { var promoList = promoView let data = { 'ecommerce': { 'promoView': { 'promotions': [] } } }; for(promos of promoList){ data.ecommerce.promoView.promotions.push({ id: promos.sfid, name: promos.name, creative: '', position: promos.pageLocation + ' ' + promos.locationType + ' ' + promos.sequence, }); } pushDataLayer(data) } //-------------------------------------------------------------------------------- // --------------- EVENTO: PROMOCLICK (CLICKS DE PROMOS) ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("promoClick", function(promoClick) { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_PromoClick(promoClick) } }); //---------- Format data function setDataLayer_PromoClick(promoClick) { let data = { 'event': 'promotionClick', 'ecommerce': { 'promoClick': { 'promotions': [ { 'id': promoClick.sfid, 'name': promoClick.name, 'creative': '', 'position': promoClick.pageLocation + ' ' + promoClick.locationType + ' ' + promoClick.sequence } ] } } // , // 'eventCallback': function() { // document.location = productList.productUrl // } } pushDataLayer(data) }; //-------------------------------------------------------------------------------- // --------------- EVENTO: PURCHASE PROCCESS ---------------- //-------------------------------------------------------------------------------- //---------- Listeners CCRZ.pubSub.on("Datalayer_onCheckout", function(co_step, co_option, co_productsList) { // console.log('ejecuta pubsub checkout datalayer') if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_onCheckoutStep( co_step, co_option, co_productsList ) } }); CCRZ.pubSub.on("view:PaymentsCCView:refresh", function() { if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_onCheckoutStep( 2, 'Payments', CCRZ.miniCartCheckoutModel.attributes ) } }) //---------- Format data function setDataLayer_onCheckoutStep(co_step, co_option, co_productsList) { let data = { 'event': 'checkout', 'ecommerce': { 'checkout': { 'actionField': {'step': co_step, 'option': co_option}, 'products': [] } } } // console.log('co_productsList ->',co_productsList) let productList = co_productsList.cartItems for(product of productList){ item = product.mockProduct !== undefined? product.mockProduct:product.product data.ecommerce.checkout.products.push({ name: item.name !== undefined? item.name:item.sfdcName, id: item.sku !== undefined? item.sku:item.SKU, price: product.price, brand: item.brandName == undefined? "": item.brandName, category: item.category == undefined ? getCategoryNameFromLocalStorage(item.sku) : item.category, variant: '', qty: product.quantity }); } pushDataLayer(data) } //-------------------------------------------------------------------------------- // --------------- EVENTO: PURCHASE PROCCESS ---------------- //-------------------------------------------------------------------------------- //---------- Listener CCRZ.pubSub.on("purchaseSuccess", function(dataPurchase) { if(CCRZ.getPageConfig('debug.show_dcl', false)){ console.log('ejecuta pubsub purchase datalayer', dataPurchase) } if(CCRZ.getPageConfig('gtm.enable_dl',false)){ setDataLayer_PurchaseSuccess( dataPurchase ) } if(is_MC_Pixel_Active()){ set_MC_Pixel_PurchaseSuccess(dataPurchase) } //Activa traking para hawkSearch if(CCRZ.getPageConfig('hsm.enable_hs')){ hawkDataTrackOrderConfirmation(dataPurchase) } }); //---------- Format data google tag manager function setDataLayer_PurchaseSuccess(dataPurchase) { let data = { 'ecommerce': { 'purchase': { 'actionField': { 'id': dataPurchase.sfdcName, // Transaction ID. Required for purchases and refunds <----- ORDER NUMBER ON SALESFORCE. 'affiliation': 'Online Store', 'revenue': dataPurchase.totalAmount, // Total transaction value (incl. tax and shipping) 'tax': dataPurchase.tax, 'shipping': dataPurchase.shippingCharge, 'coupon': dataPurchase.couponName }, 'products': [] // <------ PRODUCTS LIST HERE } } }; let productList = dataPurchase.orderItems for(product of productList){ data.ecommerce.purchase.products.push({ name: product.mockProduct.name, id: product.mockProduct.sku, price: product.price, brand: product.mockProduct.brandName == undefined? "": product.mockProduct.brandName, category: product.mockProduct.category == undefined ? getCategoryNameFromLocalStorage(product.mockProduct.sku) : product.mockProduct.category, variant: '', qty: product.quantity }); } pushDataLayer(data); //borra el localstorage //setLocalStorageDatalayerCategoryProduct({}, true); } function setDataLayer_ThanksYouPage(dataCustomEvent) { let data = { 'event': 'thanksyoupage', 'ecommerce': { 'purchase': { 'actionField': { 'id': dataCustomEvent.sfdcName, 'affiliation': 'Online Store', 'revenue': dataCustomEvent.totalAmount, 'tax': dataCustomEvent.tax, 'shipping': dataCustomEvent.shippingCharge, 'coupon': dataCustomEvent.couponName }, 'products': [] // <------ PRODUCTS LIST HERE } } }; let productList = dataCustomEvent.orderItems for(product of productList){ data.ecommerce.purchase.products.push({ name: product.mockProduct.name, id: product.mockProduct.sku, price: product.price, brand: product.mockProduct.brandName == undefined? "": product.mockProduct.brandName, category: product.mockProduct.category == undefined ? getCategoryNameFromLocalStorage(product.mockProduct.sku) : product.mockProduct.category, variant: '', qty: product.quantity }); } //CCRZ.pagevars.pageConfig["env.isprod"] = 'TRUE' pushDataLayer(data); //borra el localstorage setLocalStorageDatalayerCategoryProduct({}, true); } //---------- Format data MC PIXEL function set_MC_Pixel_PurchaseSuccess(dataPurchase) { let data = { 'cart': [], 'order_number': dataPurchase.sfdcName, // Transaction ID. Required for purchases and refunds <----- ORDER NUMBER ON SALESFORCE. 'discount': '', 'shipping': dataPurchase.shippingCharge, // Shipping value) 'details': { 'originatedCart' : dataPurchase.originatedCart, 'buyerEmail': dataPurchase.buyerEmail, 'buyerFirstName': dataPurchase.buyerFirstName, 'buyerLastName': dataPurchase.buyerLastName, 'buyerMobilePhone': dataPurchase.buyerMobilePhone, 'contactId': dataPurchase.contact, 'shippingCharge': dataPurchase.shippingCharge, 'subTotal': dataPurchase.subTotal, 'tax': dataPurchase.tax, 'taxSubTotalAmount': dataPurchase.taxSubTotalAmount, 'totalAmount': dataPurchase.totalAmount } } let productList = dataPurchase.orderItems for(product of productList){ data.cart.push({ item: product.mockProduct.name, quantity: product.quantity, price: product.price, unique_id: product.mockProduct.sku }); } if(CCRZ.getPageConfig('env.isprod',false)){ _etmc.push(["trackConversion", data]) }else{ console.log("data compra MC Pixel => ",data) } } //-------------------------------------------------------------------------------- // --------------- PUSH DATA IN TO DATALAYER ---------------- //-------------------------------------------------------------------------------- function pushDataLayer(data) { if(!CCRZ.getPageConfig('env.isprod',false)){ console.log('DATALAYER = ', data); }else{ dataLayer.push(data); } } //-------------------------------------------------------------------------------- // --------------- FUNCTION DRAG SCROLL FOR PAINT PALETTE ---------------- //-------------------------------------------------------------------------------- function setDragScroll( elemName ) { const ele = document.getElementById( elemName ); ele.style.cursor = 'grab'; let pos = { top: 0, left: 0, x: 0, y: 0 }; const mouseDownHandler = function(e) { ele.style.cursor = 'grabbing'; ele.style.userSelect = 'none'; pos = { left: ele.scrollLeft, top: ele.scrollTop, // Get the current mouse position x: e.clientX, y: e.clientY, }; document.addEventListener('mousemove', mouseMoveHandler); document.addEventListener('mouseup', mouseUpHandler); }; const mouseMoveHandler = function(e) { // How far the mouse has been moved const dx = e.clientX - pos.x; const dy = e.clientY - pos.y; // Scroll the element ele.scrollTop = pos.top - dy; ele.scrollLeft = pos.left - dx; }; const mouseUpHandler = function() { ele.style.cursor = 'grab'; ele.style.removeProperty('user-select'); document.removeEventListener('mousemove', mouseMoveHandler); document.removeEventListener('mouseup', mouseUpHandler); }; // Attach the handler ele.addEventListener('mousedown', mouseDownHandler); } function ifApplyExpressDelivery(){ if(CCRZ.getPageConfig('exdev.stl')){ let availableExpressList = CCRZ.getPageConfig('exdev.stl').split(','); let sucursalFilter; if(localStorage.getItem('locStor'+getPrefixStore3())){ sucursalFilter = getCodeCompany()+(JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo); if( availableExpressList.find(x=>((x.trim())==sucursalFilter)) ){ //let dateToday = moment().format('YYYY-MM-DD'); //const applyStoreBySpecialHour = ifApplyStoreBySpecialHour(dateToday, getCodeCompany(), (JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo)); //console.log( "VALIDATE SPECIAL HOUR: " + applyStoreBySpecialHour ); // validamos si para la cia y sucursal existe horario especial por día feriado // if( ifApplyStoreBySpecialHour(dateToday, getCodeCompany(), (JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo)) == true){ // $('.expressDeliveryStyle').hide() // }else{ // validamos si el horario de la sucursal está habilitado para el horario de Delivery Express ( ifApplyExpressDeliveryByTime() == true ) ? $('.expressDeliveryStyle').show() : $('.expressDeliveryStyle').hide(); // } //$('.expressDeliveryStyle').show() }else{ $('.expressDeliveryStyle').hide() } } } } function ifApplyExpressDeliveryByTime(){ let date = new Date(); // Creamos y asignamos una fecha / hora para validar horarios // fuera del delivery express //let date2 = new Date().toISOString().split('T')[0]; //date2 = date2 + ' 03:30:00 PM'; // Get current hour with timezone. Require moment-timezone library const currentHour = moment(date, 'YYYY-MM-DD H:mm:ss a').tz('America/Panama').format('HH:mm:ss'); const openHour = date.toISOString().split('T')[0] + ' ' + CCRZ.getPageConfig('exdev.enableexpressdelivery'); const openHourDeliveryExpress = moment(openHour, 'YYYY-MM-DD H:mm:ss a').format('HH:mm:ss'); const closeHour = date.toISOString().split('T')[0] + ' ' + CCRZ.getPageConfig('exdev.disableexpressdelivery'); const closeHourDeliveryExpress = moment(closeHour, 'YYYY-MM-DD H:mm:ss a').format('HH:mm:ss'); return ( ( currentHour >= openHourDeliveryExpress) == true && (currentHour <= closeHourDeliveryExpress) == true ) ? true : false; } // Obtenemos los datos para validación si existe sucursal con horario especial o feriado /*function ifApplyStoreBySpecialHour(specialDate, ciaCode, ciaStore){ let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('getStoreBySpecialHour', specialDate, ciaCode, ciaStore, function(response, event) { //console.log("AJX RESPONSE :: ==> " + response); let applyResponseSH; if(!response.data.length == 0){ const HoraInicioStore = response.data[0].Hora_Inicio__c; const HoraFinStore = response.data[0].Hora_Fin__c; if( HoraInicioStore == "cerrado" && HoraFinStore == "cerrado"){ applyResponseSH = true; }else{ applyResponseSH = false; } }else{ applyResponseSH = false; } return applyResponseSH; }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); }*/ /* function ifApplyStoreBySpecialHour( specialDate, ciaCode, ciaStore ) { return new Promise((resolve, reject) => { let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('getStoreBySpecialHour', specialDate, ciaCode, ciaStore, function(response, event) { let applyResponseSH; //console.log("AJX RESPONSE :: ==> " + response); if(!response.data.length == 0){ const HoraInicioStore = response.data[0].Hora_Inicio__c; const HoraFinStore = response.data[0].Hora_Fin__c; if( HoraInicioStore == "cerrado" && HoraFinStore == "cerrado"){ applyResponseSH = true; }else{ applyResponseSH = false; } }else{ applyResponseSH = false; } return applyResponseSH; }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); }); } */ function enabledBrandForInk(){ let brandName = CCRZ.prodDetailView.model.attributes.product.prodBean.brandName if(brandName != null){ let brandEnables = CCRZ.getPageConfig('paint.brands_enable').split(',') return brandEnables.includes(brandName.toLowerCase().capitalize()) } else { return false } } // id: a1F5C000000kRcWUAU // qty: 1 function addToCartSFAsync( id, qty ) { console.log("JMC ================> entro"); return new Promise((resolve, reject) => { //Valida el inventario let data=[{ prodId: id, qty: qty.toString() }]; let remoteCall = _.extend(CCRZ.RemoteInvocation, { className: 'AddToCartRemoteValidator' }); remoteCall.invokeContainerLoadingCtx($('.deskLayout'), 'itemQuantityValidationRemoteAction', JSON.stringify(data), function (res, err) { if (res != null) { if (res.success) { //Agrega al carrito el producto let remoteCall2 = _.extend(CCRZ.RemoteInvocation, { className: 'ccrz.cc_RemoteActionController' }); remoteCall2.invokeContainerLoadingCtx($('.deskLayout'), 'addItem', id, qty, null, null, "", null, function (res, err) { if (res.success) { resolve(res); CCRZ.pubSub.trigger('cartChange', res.data); } }, { nmsp: false }); } else { reject(res); } } else if (err.message != "") { reject(res); } }, { nmsp: false }); }); } CCRZ.pubSub.on("view:PaymentProcessorView:refresh", function() { updateInfo(); setTimeout(() => { $("#overlay").remove() }, 2000); }) function momentFormatLLLL(date){ let dateLLLL = '' if(date != ''){ let arrDates = moment(date).format('LLLL').split(' ') arrDates[0] = arrDates[0].toLowerCase().capitalize() arrDates.splice(arrDates.length-1) dateLLLL = arrDates.join(' ') } else { dateLLLL = 'Fecha invalida' } return dateLLLL } function obtenerValorParametroBase(sParametroNombre,url) { var sPaginaURL = url; var sURLVariables = sPaginaURL.split('&'); for (var i = 0; i < sURLVariables.length; i++) { var sParametro = sURLVariables[i].split('='); if (sParametro[0] == sParametroNombre) { return sParametro[1]; } } return null; } //Funcion que retorna la distancia en kilometros entre dos conjuntos de coordenadas function getDistanceByTwoCoordinates(lat1, lon1, lat2, lon2){ rad = function(x){ return x * Math.PI/180; } //Radio de la tierra en km let R = 6371; let dLat = rad( lat2 - lat1 ); let dLong = rad( lon2 - lon1 ); let a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLong/2) * Math.sin(dLong/2); let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); let d = R * c; return d.toFixed(2); } //Funcion que ordena por alguna propiedad del JSON function jsonSortOrder(prop) { return function(a, b) { if (a[prop] > b[prop]) { return 1; } else if (a[prop] < b[prop]) { return -1; } return 0; } } //Funcion que seteara la tienda y la actualiza en el widget componente del header selector de tiendas function setLocStore(storeCode){ let cia = getCodeCompany() let stores = JSON.parse(localStorage.getItem('stores'+getPrefixStore3())) let storeSelected = stores.find( x => (cia+x.centro == storeCode) ) let jsonStore = JSON.stringify({ codigo:storeSelected.centro, tienda:storeSelected.nombre, direccion:storeSelected.direccion, horarioLV:storeSelected.horarioLunesViernes, horarioS:storeSelected.horarioSabado, horarioD:storeSelected.horarioDomingo, coordenadas: storeSelected.coordenadas }) localStorage.setItem('locStor'+getPrefixStore3(), jsonStore) //Actualiza el componente widget de tiendas en el header locationSelected() } function loaderPayment(text1, text2){ let customLoader = `` return customLoader } /* GIFT CARD */ //variable global var processCount = 0; var addItemSuccessCount = 0; // CCRZ.pubSub.on('view:cartView:refresh', function(){ // if((JSON.parse(sessionStorage.getItem('giftcard')) != null) && (CCRZ.pagevars.queryParams.pagekey != 'GiftCard') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ // if(JSON.parse(sessionStorage.getItem('savedCartItems')) != null){ // checkCartToRemoveGiftCard(false); // sessionStorage.removeItem('giftcard'); // let savedItems = JSON.parse(sessionStorage.getItem('savedCartItems')); // let parseItem; // let itemsQty = savedItems.length; // //let response = false; // savedItems.forEach(element => { // parseItem = JSON.parse(element); // addSavedCartItems(parseItem.idProduct, parseItem.quantity, itemsQty); // }); // //CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.sfid); // }else{ // checkCartToRemoveGiftCard(true); // sessionStorage.removeItem('giftcard'); // } // } // }); //NEW DEV LOCAL STORAGE ANDRES GARCIA CCRZ.pubSub.on('view:cartView:refresh', function(){ if((JSON.parse(localStorage.getItem('giftcard')) != null) && (CCRZ.pagevars.queryParams.pagekey != 'GiftCard') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ if(JSON.parse(localStorage.getItem('savedCartItems')) != null){ checkCartToRemoveGiftCard(false); localStorage.removeItem('giftcard'); let savedItems = JSON.parse(localStorage.getItem('savedCartItems')); let parseItem; let itemsQty = savedItems.length; //let response = false; savedItems.forEach(element => { parseItem = JSON.parse(element); addSavedCartItems(parseItem.idProduct, parseItem.quantity, itemsQty); }); //CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.sfid); }else{ checkCartToRemoveGiftCard(true); localStorage.removeItem('giftcard'); } } // valida el contexto de PG Promocionales //validatePgPromoContext(); }); // CCRZ.pubSub.on('view:CartDetailView:refresh',function(){ // validatePgPromoContext(); // }); function checkCartToRemoveGiftCard(cartChangeFlag){ const ccFlag = cartChangeFlag; if(processCount == 0){ let gcSKU = CCRZ.getPageConfig('GC.gcsku', 'GCSKU'); //let gcSessionStorage = JSON.parse(sessionStorage.getItem('giftcard')); if(CCRZ.cartView.cartmodel.attributes.cartItems != undefined){ if(CCRZ.cartView.cartmodel.attributes.cartItems[0].mockProduct.sku.includes(gcSKU)){ removeGCFromCart(CCRZ.cartView.cartmodel.attributes.sfid, ccFlag); } } processCount++; } } function removeGCFromCart(cartSfid,cartChangeFlag) { const ccFlag = cartChangeFlag; let processCount = 0; let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); remoteCall.invokeCtx('removeItemsFromCart',cartSfid,(res,err)=>{ if(res.success && ccFlag){ CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.encryptedId); } },{nmsp: false, escape: false, buffer: false} ); } //NEW DEV SAVE CART ITEMS GIFTCARD // function getCartItems(cartSfid) { // //let processCount = 0; // let items; // let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); // remoteCall.invokeCtx('getCartItems',cartSfid,(res,err)=>{ // if(res.success){ // items = JSON.stringify(res.data.cartItems); // sessionStorage.setItem('savedCartItems',items); // } // },{nmsp: false, escape: false, buffer: false} // ); // } //NEW DEV SAVE CART ITEMS GIFTCARD // function addSavedCartItems(idProd, qty, itemsQty){ // let remoteCall = _.extend(CCRZ.RemoteInvocation, { className: 'ccrz.cc_RemoteActionController' }); // remoteCall.invokeContainerLoadingCtx($('.deskLayout'), 'addItem', idProd, qty, null, null, "", null, function (res, err) { // if (res.success) { // console.log('Se logro introducir items al carrito desde el session storage'); // addItemSuccessCount++; // if(addItemSuccessCount == itemsQty){ // CCRZ.pubSub.trigger('cartChange', res.data); // } // } // }, // { nmsp: false }); // } // PUNTOS GRODOS PROMOCIONALES ---------------- // isPromo: true or false function setLocalIsCartPgPromoContext(isPromo){ isPromo ? localStorage.setItem('isPgPromoContext', 'true') : localStorage.removeItem('isPgPromo'); } // function validatePgPromoContext(){ // if((localStorage.getItem('isPgPromoContext') == 'true') && (CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__CheckoutNew') && CCRZ.pagevars.remoteContext.currentPageName != 'ccrz__OrderConfirmation'){ // const cartID = CCRZ.cartView != undefined ? CCRZ.cartView.cartmodel.attributes.sfid : CCRZ.cartDetailView.model.attributes.sfid; // const cartEncId = CCRZ.pagevars.currentCartID; // let remoteCall = _.extend(CCRZ.RemoteInvocation,{ className: 'AddToCartRemoteValidator'}); // remoteCall.invokeCtx('removePGCartItems',cartID, true, function(response, event) { // if(response.success){ // localStorage.removeItem('isPgPromoContext'); // remoteCall.invokeCtx('removeFlagIsPgPromo',cartEncID, function(response, event) { // if(response.success){ // console.log('AJX :: removeFlagIsPgPromo ==> ', response); // //Refresco la pagina si estoy en el cart Detail // if(CCRZ.pagevars.remoteContext.currentPageName == 'ccrz__Cart'){ // location.reload(); // } // } // }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); // CCRZ.pubSub.trigger('cartChange', CCRZ.cartView.cartmodel.attributes.encryptedId); // } // }, { nmsp: false, escape: false, timeout: 10000, buffer: false }); // } // } // function checkCartToRemoveGiftCard(cartChangeFlag){ // const ccFlag = cartChangeFlag; // if(processCount == 0){ // let gcSKU = CCRZ.getPageConfig('GC.gcsku', 'GCSKU'); // //let gcSessionStorage = JSON.parse(sessionStorage.getItem('giftcard')); // if(CCRZ.cartView.cartmodel.attributes.cartItems != undefined){ // if(CCRZ.cartView.cartmodel.attributes.cartItems[0].mockProduct.sku.includes(gcSKU)){ // removeGCFromCart(CCRZ.cartView.cartmodel.attributes.sfid, ccFlag); // } // } // processCount++; // } // }
'; } } return wrapper; }); // INSERTA ROW SEGUN PARAMETROS ESTABLECIDOS EN LA FUNCION Handlebars.registerHelper('gridWrapCustom', function(index, isLast, isOpenning, customCol, clases) { var wrapper = "", perRow = customCol, clases = (clases == undefined) ? '' : clases; if (isOpenning) { if (index == 0 || index % perRow == 0) { wrapper += '
'; } } else { if ((index + 1) % perRow == 0 || isLast) { wrapper += '
'; } } return wrapper; }); Handlebars.registerHelper('hlpPercentagesOfDiscount', function(price, basePrice, options) { return percentagesOfDiscount(price, basePrice); }); Handlebars.registerHelper("hlpGetStorefrontname", function(options) { return CCRZ.pagevars.storefrontName; }); Handlebars.registerHelper("hlpGetCurrSiteURL", function(options) { return CCRZ.pagevars.currSiteURL; }); Handlebars.registerHelper("hlpGetCartId", function(options) { return CCRZ.pagevars.currentCartID; }); Handlebars.registerHelper("hlpGetCurrUserLocale", function(options) { return CCRZ.pagevars.userLocale; }); // DISPLAY FONT AWESOME ICON BY SIZE OPTIONS => '' (ORIGINAL) | 'fa-lg' (33% increase) | 'fa-2x' | 'fa-3x' | 'fa-4x' | 'fa-5x' Handlebars.registerHelper('displayIconBySize', function(iconName, size, options) { return new Handlebars.SafeString(" "); }); // DISPLAY CATEGORY BAR IMAGES Handlebars.registerHelper('categoriesBarLink', function(category, styleClass, options) { var tmpCategory = _.clone(category); if (tmpCategory && tmpCategory.shortDesc) { delete tmpCategory.shortDesc; } if (tmpCategory && tmpCategory.longDesc) { delete tmpCategory.longDesc; } var categoryJSON = _.escape(JSON.stringify(tmpCategory)); var content, image = ''; if (tmpCategory && tmpCategory.name) { content = _.escape(tmpCategory.name); } else if (tmpCategory && tmpCategory.category && tmpCategory.category.name) { content = _.escape(tmpCategory.category.name); } if (options && options.hash['icon']){ image = options.hash['icon']; } if (options && options.hash['image']){ image = options.hash['image']; } var href = CCRZ.goToPLP(null, category); if(styleClass.indexOf('categoryBar') == -1){ if (category.openInNewWindow || category.isNewWindow) { return new Handlebars.SafeString("
" + image + "" + content + " "); } else { return new Handlebars.SafeString("
" + image + "" + content + " "); } }else{ if (category.openInNewWindow || category.isNewWindow) { return new Handlebars.SafeString("
" + image + "" + content + " "); } else { return new Handlebars.SafeString("
" + image + "" + content + " "); } } }); //DISPLAY SVG IMAGES WITH URL Handlebars.registerHelper('displaySVG_IMG', function(obj, styleClass, options) { var imgSrc = CCRZ.processImageURL(obj, styleClass, options); var width = ''; var height = ''; if (options && options.hash['width']) width = "width='" + options.hash['width'] + "'"; if (options && options.hash['height']) height = "height='" + options.hash['height'] + "'"; if (options && options.hash.hasOwnProperty('noUrl') ) imgSrc = CCRZ.pagevars.themeBaseURL + "images/" + obj if (imgSrc.length > 0) return new Handlebars.SafeString(" "); else return new Handlebars.SafeString(""); }); Handlebars.registerHelper("hlpGetUrlCatalogo", function(pageName, options) { if(CCRZ.getPageConfig('env.isprod', true)){ return CCRZ.pagevars.storeSettings.Site_Secure_Domain__c + '/ccrz__CCPage?pagekey=' + pageName +'&cartId=' + CCRZ.pagevars.currentCartID + getCSRQueryString(); }else{ return CCRZ.pagevars.storeSettings.Site_Secure_Domain__c + '/' + CCRZ.pagevars.storefrontName.toLocaleLowerCase() + '/ccrz__CCPage?pagekey=' + pageName +'&cartId=' + CCRZ.pagevars.currentCartID + getCSRQueryString(); } }); Handlebars.registerHelper("getPageConfig", function(configName, options) { if(CCRZ.getPageConfig(configName) !== undefined){ return CCRZ.getPageConfig(configName) } }); Handlebars.registerHelper("activeDefaultPaymentType", function(configName, keyName, activeClass, options) { if(CCRZ.getPageConfig(configName) !== undefined){ if(CCRZ.getPageConfig(configName, 'cc') == keyName){ return new Handlebars.SafeString(activeClass) } } }); //Para extraer en porcentaje de ahorro Handlebars.registerHelper('hlpPercentagesOfDiscount', function(price, basePrice, options) { return percentagesOfDiscount(price, basePrice); }); //Para verificar URL HomePage Handlebars.registerHelper('hlphomePageLink', function() { const href = CCRZ.pagevars.currSiteURL; return new Handlebars.SafeString(``) }); // DISPLAY PRODUCT NAME AND PREPARE DATA TO USE IN GOOGLE TAG MANAGER DATALAYER Handlebars.registerHelper('productLinkPDP', function(product, productType, styleClass, options) { let SKU = ''; let price = 0 if (!_.isUndefined(product)) { if (product.linkURL) { SKU = product.linkURL; } else if (product.sku) { SKU = product.sku; } else if (product.SKU) { SKU = product.SKU; } else if (product.productSKU) { SKU = product.productSKU; } let filterData = CCRZ.productDetailModel == undefined ? "" : CCRZ.productDetailModel.attributes.product.prodBean.filterData; var linkObj = { 'name': product.alternateName !== undefined? product.alternateName : product.sfdcName, 'SKU': SKU, 'price': product.price == undefined? "":product.price, 'brand': product.brandName, 'category': getCategoryNameFromFilterDataProp(filterData), 'variant': '', 'list': '', 'position': '', 'productUrl': '', 'typeProduct': productType, 'openInNewWindow': product.openInNewWindow, 'friendlyUrl': product.friendlyUrl }; var productJSON = _.escape(JSON.stringify(linkObj)); } var content = ''; if (product & product.name) { content = _.escape(product.name); } if (options & options.hash['image']) content = options.hash['image']; if (options & options.hash['text']) { content = _.escape(_.unescape(options.hash['text'])); } var href = CCRZ.goToPDP(null,product); //var href = GoToPDP_test(null, product); if(CCRZ.getPageConfig('hsm.enable_hs')){// si tengo activado el HawkSearchTracking if (product.openInNewWindow || product.isNewWindow) { // return new Handlebars.SafeString(" " + content + " ") return new Handlebars.SafeString("" + content + " ") } else { return new Handlebars.SafeString("" + content + " "); // return new Handlebars.SafeString("" + content + " "); } }else{ if (product.openInNewWindow || product.isNewWindow) { return new Handlebars.SafeString("" + content + " ") } else { return new Handlebars.SafeString("" + content + " "); // return new Handlebars.SafeString("" + content + " "); } } }); /*GoToPDP_test = function(objLink) { var product = null; if (objLink !== null) { product = $(objLink).data("product"); } if (product === null) { product = arguments[1]; } var productSku; if (product.linkURL) { productSku = product.linkURL; } else if (product.sku) { productSku = product.sku; } else if (product.SKU) { productSku = product.SKU; } else if (product.productSKU) { productSku = product.productSKU; } var productUrl = CCRZ.pageUrls.productDetails + buildQueryString_test("?sku=" + encodeURIComponent(productSku)); if (CCRZ.pagevars.useFriendlyUrls && !_.isUndefined(product.friendlyUrl)) { if (product.friendlyUrl.startsWith('/') && CCRZ.pagevars.currSiteURL.endsWith('/')) { product.friendlyUrl = product.friendlyUrl.substring(1); } productUrl = CCRZ.pagevars.currSiteURL + product.friendlyUrl + buildQueryString_test(''); } return productUrl; }; buildQueryString_test = function(inputQueryString) { var queryString = inputQueryString; if (inputQueryString.toLowerCase().indexOf("portaluser") === -1 && CCRZ.pagevars.portalUserId) { queryString ? queryString += '&' : queryString += '?'; queryString += 'portalUser=' + CCRZ.pagevars.portalUserId; } if (inputQueryString.toLowerCase().indexOf("store") === -1 && CCRZ.pagevars.storeName) { queryString ? queryString += '&' : queryString += '?'; queryString += 'store=' + CCRZ.pagevars.storeName; } if (inputQueryString.toLowerCase().indexOf("effectiveaccount") === -1 && CCRZ.pagevars.effAccountId) { queryString ? queryString += '&' : queryString += '?'; queryString += 'effectiveAccount=' + CCRZ.pagevars.effAccountId; } if (inputQueryString.toLowerCase().indexOf("grid") === -1 && CCRZ.pagevars.priceGroupId) { queryString ? queryString += '&' : queryString += '?'; queryString += 'grid=' + CCRZ.pagevars.priceGroupId; } if (inputQueryString.toLowerCase().indexOf("cclcl") === -1 && CCRZ.pagevars.userLocale) { queryString ? queryString += '&' : queryString += '?'; queryString += 'cclcl=' + CCRZ.pagevars.userLocale; } return queryString; }; openPDP_test = function(e) { if (!e) e = window.event; var target = e.target || e.srcElement; if (CCRZ.ga) { CCRZ.ga.handleProductDetails(e); } var link = GoToPDP_test(e); if (target === "_blank") { if (windowObjectReference == null || windowObjectReference.closed) { windowObjectReference = window.open(link); } else { windowObjectReference.focus(); } } else { window.location = link; } return false; };*/ Handlebars.registerHelper('displayImageCustom', function(obj, styleClass, options) { if (options && options.hash['src']) { var imgSrc = _.escape(options.hash['src']); } else { var imgSrc = CCRZ.processImageURL(obj, styleClass, options); } //TODAS LAS PROPIEDADES QUE DESEES COLOCAR PARA EL TAG AQUI let alt = ""; if (options && options.hash['alt']) alt = _.escape(options.hash['alt']); /*var dataId = ""; if (options && options.hash['dataId']) dataId = _.escape(options.hash['dataId']);*/ let loading = '' if(options && options.hash['loading']) loading = _.escape(options.hash['loading']); if (imgSrc.length > 0) return new Handlebars.SafeString(" "); else return new Handlebars.SafeString(" "); }); Handlebars.registerHelper('CategoryLinkCustom', function(category, styleClass, options) { var tmpCategory = _.clone(category); if (tmpCategory && tmpCategory.shortDesc) { delete tmpCategory.shortDesc; } if (tmpCategory && tmpCategory.longDesc) { delete tmpCategory.longDesc; } var categoryJSON = _.escape(JSON.stringify(tmpCategory)); var content = ''; var promo = ''; if (tmpCategory && tmpCategory.name) { content = _.escape(tmpCategory.name); } else if (tmpCategory && tmpCategory.category && tmpCategory.category.name) { content = _.escape(tmpCategory.category.name); } if (options && options.hash['image']) content = options.hash['image']; if (options && options.hash['text']) { content = _.escape(options.hash['text']); } if (options && options.hash['promo']) promo = options.hash['promo']; var href = CCRZ.goToPLP(null, category); if (category.openInNewWindow || category.isNewWindow) { return new Handlebars.SafeString("" + content + " "); } else { return new Handlebars.SafeString("" + content + " "); } }); //RETURNS THE REAL INDEX NUMBER OF LIST Handlebars.registerHelper('printIndex', function(value, options) { return parseInt(value) + 1; }); //RETURNS THE URI OF CREDIT CARD LOGO Handlebars.registerHelper('getCCLogo', function(paymentType, options) { return CCRZ.pagevars.storeSettings.Site_Secure_Domain__c + CCRZ.pagevars.themeBaseURL + 'images/'+ paymentType + '.svg' }); //RETURNS THE CREDIT CARD NUMBER FORMAT Handlebars.registerHelper('formatCCNumber', function(cardNumber, paymentType, options) { let number = "", num = [] for (var i = 0, len = cardNumber.length; i < len; i += 1) { num.push(cardNumber[i]); } if(paymentType == "Amex"){ // number = cardNumber.replace(/\b(\d{4})(\d{6})(\d{5})\b/, '$1 $2 $3'); for(var i=0; i < 4; i++) { number = number.concat(num[i]) } number = number + " " for(i; i < 10; i++) { number = number.concat(num[i]) } number = number + " " for(i; i < 16; i++) { number = number.concat(num[i]) } }else{ // number = cardNumber.replace(/(\{A-Z 0-9}(?!\s))/g, "$1 ") for(var i=0; i < num.length; i++) { if(i%4 == 0 && i > 0) number = number.concat(' ') number = number.concat(num[i]) } } return number }); //RETURNS THE URI OF CREDIT CARD LOGO Handlebars.registerHelper('setDateFormat', function(month, year, options) { let dateFormat = month + "/"+ year if(month <= 9){ dateFormat = "0" + month + "/"+ year } return dateFormat }); //RETURNS THE URI OF CREDIT CARD LOGO Handlebars.registerHelper('showDebugComments',function(logName, logContent) { if(CCRZ.getPageConfig('debug.show_dcl', false)){ console.log(logName, logContent) } }); // RETURN COUNT DOWN FOR SPLASH PROMOTIONS Handlebars.registerHelper('printCountDown', function(id, dateValue, size, fontsize, positionX, PositionY, options) { // *** UPDATE COUNT EVERY 1 SECOND *** var x = setInterval(function() { // *** APPLY STYLES BY PARAMETERS *** let cdParameters = "splash-cd-size-" + size + " splash-cd-fontsize-" + fontsize + " splash-cd-position-x-" + positionX + " splash-cd-position-y-" + PositionY; $("." + id).addClass(cdParameters); $("." + id + "-mobile").addClass(cdParameters); // *** GET TODAY VALUE *** var now = new Date().getTime(); // *** CALCULATE DIFFERENCE BETWEEN NOW AND COUNTDOWN DATE *** var distance = dateValue - now; if(distance > 0){ // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // *** DISPLAY RESULT IN THE CONTAINER BY ID *** for (let index = 0; index < $("." + id + "-Days").length; index++) { $("." + id + "-Days")[index].innerHTML = days + "d"; $("." + id + "-Hours")[index].innerHTML = hours + "h"; $("." + id + "-Minutes")[index].innerHTML = minutes + "m"; $("." + id + "-Seconds")[index].innerHTML = seconds + "s"; } }else{ // *** STOP THE INTERVAL & SET TO 0 AL CONTAINERS BY ID *** clearInterval(x); for (let index = 0; index < $("." + id + "-Days").length; index++) { $("." + id + "-Days")[0].innerHTML = "0d"; $("." + id + "-Hours")[0].innerHTML = "0h"; $("." + id + "-Minutes")[0].innerHTML = "0m"; $("." + id + "-Seconds")[0].innerHTML = "0s"; } } }, 1000); }); // RETURN COUNT DOWN FOR SPLASH PROMOTIONS Handlebars.registerHelper('printCountDown-Header', function(id, options) { // *** UPDATE COUNT EVERY 1 SECOND *** var x = setInterval(function() { // *** GET TODAY VALUE *** var now = new Date().getTime(); // *** CALCULATE DIFFERENCE BETWEEN NOW AND COUNTDOWN DATE *** let dateValue = new Date().getTime(); if(CCRZ.getPageConfig('pm_u.cd_enddate', false) !== false){ dateValue = new Date(CCRZ.getPageConfig('pm_u.cd_enddate', false)).getTime(); } var distance = dateValue - now; if(distance > 0){ // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // *** DISPLAY RESULT IN THE CONTAINER BY ID *** $("." + id)[0].innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s"; }else{ // *** STOP THE INTERVAL & SET TO 0 AL CONTAINERS BY ID *** clearInterval(x); $("." + id)[0].innerHTML.innerHTML = "0d 0h 0m 0s"; } }, 1000); }); Handlebars.registerHelper('ifApplyExpressDelivery', function(expressDelivery, options) { if(CCRZ.pagevars.currentPageName=="ccrz__ProductList")expressDelivery=true; if(expressDelivery){ if(CCRZ.getPageConfig('exdev.stl')){ let availableExpressList = CCRZ.getPageConfig('exdev.stl').split(','); let sucursalFilter = ''; if(localStorage.getItem('locStor'+getPrefixStore3())){ sucursalFilter = getCodeCompany()+(JSON.parse(localStorage.getItem('locStor'+getPrefixStore3())).codigo); } else { return options.inverse(this); } if(availableExpressList.find(x=>((x.trim())==sucursalFilter))){ return options.fn(this); } else { return options.inverse(this); } } else { return options.inverse(this); } } else { return options.inverse(this); } }); //-------------------------------------------------------------------------------- //------------------- HANDLEBAR QUE UTILIZAMOS PARA GARANTIAS EXTENDIDA ---------- //-------------------------------------------------------------------------------- Handlebars.registerHelper('splitExtSKUWarranty', function(extSku, options) { return extSku.split(" -- ")[2]; }); Handlebars.registerHelper('isWarranty', function(extSku, options) { if(extSku != undefined){ let skuLabel = 'GARANTIA-EXT' return extSku.includes(skuLabel) ? options.inverse(this) : options.fn(this); } else { return options.fn(this); } }); Handlebars.registerHelper('haveWarranty', function(sku, options) { let prodWhitExtSku = CCRZ.currentCart.attributes.ECartItemsS.models.filter(x => (x.attributes.hasOwnProperty("extSKU") && x.attributes.hasOwnProperty("extName"))); let haveWarranty = prodWhitExtSku.find(x => x.attributes.extSKU.includes(sku) || x.attributes.extName.includes(sku)); return haveWarranty ? 'style="pointer-events: none;background: #eaeaea;"' : ""; }); //-------------------------------------------------------------------------------- //--------------------- HANDLEBARS QUE UTILIZAMOS EN EL CARRITO ------------------ //-------------------------------------------------------------------------------- Handlebars.registerHelper('haveProductMaxQty', function(max_qty,qty,sfid, options) { if(max_qty){ if(qty>max_qty){ CCRZ.cartDetailView.updateItemQty(event,sfid,max_qty); CCRZ.indicadorMaxQty=1; return options.fn(this); }else{ return options.inverse(this); } }else{ return options.inverse(this); } }); Handlebars.registerHelper('configurationEval', function(config,options) { if(CCRZ.getPageConfig('C.mq')){ return options.fn(this); }else{ return options.inverse(this); } }); //-------------------------------------------------------------------------------- //--------------------- HANDLEBARS LINK URL CATEGORIAS UPPER MENU ---------------- //-------------------------------------------------------------------------------- Handlebars.registerHelper('hlpSetCartId', function(url,options) { let parametro=obtenerValorParametroBase('cartId',url) if(CCRZ.pagevars.currentCartID!=''&& parametro==''){ partesUrl=url.split('cartId=') return partesUrl[0]+'cartId='+CCRZ.pagevars.currentCartID+partesUrl[1] }else{ return url } }); //-------------------------------------------------------------------------------- //--------------------- HANDLEBARS QUE UTILIZAMOS EN EL CHECKOUT ----------------- //-------------------------------------------------------------------------------- Handlebars.registerHelper('hlpBtnSaveAddress', function(options) { let btn = ''; return btn; }); Handlebars.registerHelper('hlpProvinceList', function(options) { let html = "", ubigeos = getUbigeos(); for(item of ubigeos.pais.provincia){ html += '
' + item.descripcion + ' '; } return html; }) //Handlebars.registerHelper('getCardAddressAccount', function(options) { // CCRZ.CheckoutCustomDataAddressSelect = undefined; // getAddressByAccountId(); //}); //-------------------------------------------------------------------------------- //--------------------- HANDLEBARS QUE UTILIZAMOS EN EL MINI CART ---------------- //-------------------------------------------------------------------------------- //Handlebars.registerHelper('updateData', function( options) { // if(CCRZ.cartCheckoutView.currStep!=0){ // updateInfo() // console.log('paso1') // clearAmuntAndDelivaryData() // } //}); Handlebars.registerHelper('momentFormatLLLL', function(date, options) { let dateLLLL = '' // if(CCRZ.pagevars.currentPageName == 'ccrz__OrderConfirmation' || (!CCRZ.getPageConfig('env.isProd'))){ // date = date.split("/").reverse().join("/") // } date=moment(date).add(12, 'hours').format("YYYY-MM-DD"); if(date != ''){ let arrDates = moment(date).format('LLLL').split(' ') arrDates[0] = arrDates[0].toLowerCase().capitalize() arrDates.splice(arrDates.length-1) dateLLLL = arrDates.join(' ') } else { dateLLLL = 'Fecha invalida' } return dateLLLL }) //-------------------------------------------------------------------------------- //--------------------- GET PAYMENT TYPE SVG ICON URL BY KEY -------------------- //-------------------------------------------------------------------------------- Handlebars.registerHelper("getPaymentTypeSVG", function(key, options) { let URL = CCRZ.processPageLabelMap('svg_payment_method_' + key); return URL }); Handlebars.registerHelper("getLastCardNumber", function(number, options) { let cardNumber = number.substring(number.length - 4) return cardNumber }) Handlebars.registerHelper("maskAsteriskNumber", function(number, card, options) { let cardNumber = card === 'Amex' ? number.replace('XXXXXXXXXXX','**** ****** *') : number.replace('XXXXXXXXXXXX','**** **** **** ') return cardNumber }) Handlebars.registerHelper("loadQuoteOnce", function(options){ /*if(CCRZ.cartDetailView.model.attributes.quoteId){ return options.inverse(this); } else { return options.fn(this); }*/ if(CCRZ.cartDetailModel.attributes.quoteId){ let acum = 0, haveItems = CCRZ.cartDetailModel.attributes.ECartItemsS ? true : false if(haveItems){ let cartItems = CCRZ.cartDetailModel.attributes.ECartItemsS.models for(let a = 0; a < cartItems.length; a++){ if(cartItems[a].attributes.comesfromquote){ acum = acum + 1 } } if(acum > 0){ return options.inverse(this); } else { return options.fn(this); } } else { return options.fn(this); } } else { return options.fn(this); } })