//#region Carro Abandonado function BraindwCartAbandoned() { try { console.log("cartAbandoned..."); var skuArray = localStorage.getItem('bdw_cartabandoned').split(','); try{skuArray = skuArray.filter(value => Object.keys(value).length !== 0);} catch{} var bdwQueryString = ''; var itemsArray = skuArray.map(item => { var itemSku = 0; var sellerId = ''; if (item.indexOf('-') > -1 ) { itemSku = item.split('-')[0]; sellerId = item.split('-')[1]; return { id: itemSku, quantity: 1, seller: sellerId } }else{ bdwQueryString += '&fq=productId:' + item; return null; } }).filter(x => x !== null); if(bdwQueryString.length>0) { bdwQueryString = `/api/catalog_system/pub/products/search?${bdwQueryString}`; fetch(bdwQueryString) .then(r => r.json()) .then(function (data) { var bdwOldArray=itemsArray; if (data.length > 0) { itemsArray = data.map(item => { for (var i = 0; i < item.items.length; i++) { if (item.items[i].sellers[0].commertialOffer.AvailableQuantity > 0) { return { id: item.items[i].itemId, quantity: 1, seller: item.items[i].sellers[0].sellerId } } } return { id: item.items[0].itemId, quantity: 1, seller: item.items[0].sellers[0].sellerId } }); } itemsArray = itemsArray.concat(bdwOldArray); console.log('itemarray',itemsArray); if (itemsArray.length > 0) { vtexjs.checkout.getOrderForm().done(function (orderfrom) { vtexjs.checkout.addToCart(itemsArray, null, 1).done(function (orderfrom) { setTimeout(function () { localStorage.removeItem('bdw_cartabandoned'); }, 500); }); }); } }) .catch(error => { $("#braindw_loader").hide(); console.log('BDW CartAbandoned. Error catalog querie' + error); }) } else if (itemsArray.length > 0) { vtexjs.checkout.getOrderForm().done(function (orderfrom) { vtexjs.checkout.addToCart(itemsArray, null, 1).done(function (orderfrom) { setTimeout(function () { localStorage.removeItem('bdw_cartabandoned'); }, 500); }); }); } } catch (e) { console.log(e); } } //#endregion var _HASHBNDW = 'simmonsio_produccion_zagjs'; var _COMPANY = 'simmonsio_produccion'; var _URLBNDW = window.location.protocol + '//s2.braindw.com'; //#region Persistencia var BraindwPersistence = (function () { let storageEmailKey = 'bdw_email'; function GetEmail() { var bdwEmail = ''; if (localStorage.getItem('bdw_user')) { bdwEmail = JSON.parse(localStorage.getItem('bdw_user')).email; } if (localStorage.getItem(storageEmailKey)) { bdwEmail = localStorage.getItem(storageEmailKey); } return bdwEmail; } function GetSucCookie() { let BraindwCa = decodeURIComponent(document.cookie).split(';'); for (let bnwi = 0; bnwi < BraindwCa.length; bnwi++) { if (BraindwCa[bnwi].indexOf("VTEXSC") > -1) { return BraindwCa[bnwi].split('=')[2]; } } return ''; } function GetSessionDate() { let result = null; try { let SalesChannel = GetSucCookie(); result = { SalesChannel: SalesChannel, }; } catch (e) { console.log('GetSessionDate error ', e); } return result; } function GetGuidGuest() { let BraindwCa = decodeURIComponent(document.cookie).split(';'); for (let bnwi = 0; bnwi < BraindwCa.length; bnwi++) { if (BraindwCa[bnwi].indexOf("bdw_session") > -1) { return BraindwCa[bnwi].split('=')[1]; } } return ''; } function SendPersistency(e, url) { let n = { emailguest: GetEmail(), dataset: encodeURI(JSON.stringify(e)), page: "", url: (url) ? url : window.location.href.split("?")[0], urlb: `${_URLBNDW}/Script/braindw/${_HASHBNDW}?hs=Sat Apr 21 2018 10:00:38 GMT-0300 (Hora estándar de Argentina)`, BranchOffice: GetSucCookie(), guidguest: GetGuidGuest() }; fetch('https://p.braindw.com/Api/Data/Capture', { method: "POST", body: JSON.stringify(n), credentials: 'include', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', } }) .then((resp) => resp.json()) .then(function (data) { }) .catch(function (ex) { console.log(ex); }); } function captureProductPersistence() { const d = JSON.parse(localStorage.getItem('bdw_last_products') || '[]'); const productCode = Array.isArray(d) && d.length ? d[0] : null; let e = null; if (productCode) { var s = {}, t = ""; t && (s.sessionDate = t); e = { ProductCode: productCode, Title: "titulo", PriceOnline: 2000, Brand: "marca", Category: "categoria", // here must be the name of the category, whe use the id for now CategoryCode:"codigocategoria", // here must be the code of the category, whe use the id for now UrlImage: "urlimagen", UrlProduct: "urldelproducto", BranchOffice: "", }; s.product = e; SendPersistency(s); } } function GetCartOpened() { let e = null; var items = []; if(typeof vtexjs == "undefined") return e; var data = vtexjs.checkout.orderForm; if(data != undefined){ for (var i = 0; i < data.items.length; i++) { items.push({ ProductTitle: data.items[i].name, ProductCode: data.items[i].productId, ProductUrlImage: data.items[i].imageUrl, ProductQuantity: data.items[i].quantity, ProductQuantityDetails: '', ProductPrice: (data.items[i].sellingPrice / 100).toString(), PriceTotal: (data.items[i].sellingPrice / 100) * data.items[i].quantity, Event: "Load", ProductSku: data.items[i].id, idSeller: data.items[i].seller }) } } e = { CartNumber: '', BranchOffice: GetSucCookie(), Items: items } return e; } function PushInfo(emailGuest) { let e = { sessionDate: GetSessionDate() }; let a = GetCartOpened(); a ? e.cartOpened = a : null; SendPersistency(e); captureProductPersistence(); } return { PushInfo, } })(); //#endregion function bindEvent(element, eventName, eventHandler) { try { if (element.addEventListener) element.addEventListener(eventName, eventHandler, false); else if (element.attachEvent) element.attachEvent('on' + eventName, eventHandler); } catch (e) { } } //#region Captures var BraindwCapture = (function () { let storageEmailKey = 'bdw_email'; function ValidateEmail(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(String(email).toLowerCase()); } function CookiePush(email) { if (ValidateEmail(email)) { console.log('CookiePush'); try { fetch(_URLBNDW + '/tracking/SetCookiesNdway?email=' + email + '&company=' + _COMPANY, { credentials: "include", mode: 'no-cors', method: 'GET', }) .then(function (resp) { return resp.text(); }) .then(function (data) { localStorage.setItem(storageEmailKey, email); console.log("storageEMailkey ", storageEmailKey); BraindwPersistence.PushInfo(email); return false; }) .catch(function (ex) { console.log(ex); }); } catch (e) { } } } function EmailsSite(textBoxSelector) { var email; if(textBoxSelector != undefined || textBoxSelector != null){ email = document.getElementById(textBoxSelector).value; console.log('Email: ',email); if (email == undefined || email == "") return; CookiePush(email); console.log('Email: ',email); } } return { EmailsSite, //CookiePush } })(); //#endregion var BraindwDomReady = function (callback) { document.readyState === "interactive" || document.readyState === "complete" ? callback() : document.addEventListener("DOMContentLoaded", callback); }; BraindwDomReady(function () { var nIntervId; console.log('[braindw_init]'); if(localStorage.getItem('bdw_cartabandoned') !== null && window.location.href.indexOf('checkout/#/cart') > -1){ BraindwCartAbandoned() ; } window.addEventListener("popstate", handleUrlChange); function handleUrlChange() { if (window.location.href.includes("/checkout")) { if(document.getElementById('client-pre-email') != null){ BraindwCapture.EmailsSite('client-pre-email'); }else{ if(document.getElementById('client-email') != null){ BraindwCapture.EmailsSite('client-email'); } } } } }); // Metrics // const BDW_TRACKING_BASE = "https://s2.braindw.com/tracking/track"; const BDW_ABTEST_BASE = "https://abtest.braindw.com"; // Cache for abtest flag status (5 min TTL) let _abtestFlagCache = null; let _abtestFlagCacheTimestamp = 0; const ABTEST_CACHE_TTL = 5 * 60 * 1000; // 5 minutes in ms const _bdwCarouselProductCallers = {}; // Get cookie function getCookie(name) { const regex = new RegExp(`(^|;)\\s*${name}=([^;]*)`); const match = regex.exec(document.cookie); return match ? decodeURIComponent(match[2]) : null; } const vtexCookie = getCookie("bdw_session"); function getLocalStorageValue(key) { try { return localStorage.getItem(key) || ''; } catch (e) { return ''; } } // Get the user email from localStorage. // Tries bdw_email first, then bdw_user (which may be a JSON object). function getBdwEmail() { const email = getLocalStorageValue('bdw_email'); if (email) return email; const userRaw = getLocalStorageValue('bdw_user'); if (userRaw) { try { const userObj = JSON.parse(userRaw); if (userObj && userObj.email) return userObj.email; } catch (e) { // bdw_user might be a plain string if (userRaw.indexOf('@') > -1) return userRaw; } } return ''; } // ----------------------------------------------- // ABTest Flag Status (cached 5 min) // ----------------------------------------------- async function getAbtestFlagStatus() { const now = Date.now(); // Return cached value if still valid if ( _abtestFlagCache !== null && now - _abtestFlagCacheTimestamp < ABTEST_CACHE_TTL ) { return _abtestFlagCache; } try { const url = `${BDW_ABTEST_BASE}/api/abtest/GetFlagStatus?hashclient=${_HASHBNDW}`; const response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json' }, }); if (!response.ok) { console.warn('BDW: ABTest flag status request failed:', response.status); _abtestFlagCache = false; _abtestFlagCacheTimestamp = now; return false; } const data = await response.json(); // Expected shape: // { isSuccess, isFailure, value: { abTestenabled, hashclient }, error } let flag = false; if (typeof data === 'boolean') { flag = data; } else if (data && data.isSuccess === true && data.value) { if (typeof data.value.abTestenabled === 'boolean') { flag = data.value.abTestenabled; } else if (typeof data.value.abtestenabled === 'boolean') { // fallback in case backend casing changes flag = data.value.abtestenabled; } } _abtestFlagCache = flag; _abtestFlagCacheTimestamp = now; return flag; } catch (e) { console.warn('BDW: Error fetching ABTest flag status', e); _abtestFlagCache = false; _abtestFlagCacheTimestamp = now; return false; } } // ----------------------------------------------- // Cart Event Capture (POST to abtest) // ----------------------------------------------- async function captureCartEvent(orderForm) { if (!orderForm) return; try { const abtestEnabled = await getAbtestFlagStatus(); const sessionId = ""; // getCookie("guid"); if (!sessionId) { console.warn("No guid cookie found, skipping cart event"); return; } const email = getBdwEmail(); const guidCartNumber = orderForm.orderFormId || ''; // Build products array from orderForm items // orderForm prices are in centavos (÷100 to get real price) const products = (orderForm.items || []).map(function (item) { const caller = _bdwCarouselProductCallers[item.productId] || null; return { productid: item.productId || '', productname: item.name || item.skuName || '', price: item.sellingPrice ? Math.round(item.sellingPrice / 100) : 0, quantity: item.quantity || 0, caller: caller, }; }); // totalamount from orderForm value (centavos ÷ 100) const totalAmount = orderForm.value ? orderForm.value / 100 : 0; const payload = { eventtype: "cart", abtestenabled: abtestEnabled, bdwsession: !!sessionId, sessionid: sessionId, timestamp: new Date().toISOString(), email: email, guidcartnumber: guidCartNumber, products: products, totalamount: totalAmount, tenant: _HASHBNDW, eventcontextkey: sessionId, }; const url = `${BDW_ABTEST_BASE}/api/events/Capture?hashclient=${_HASHBNDW}`; const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify(payload), }); if (!response.ok) { console.warn('BDW: Cart event capture failed:', response.status); } else { console.log('BDW: Cart event captured successfully'); } } catch (e) { console.error('BDW: Error capturing cart event', e); } } (function () { let _lastFingerprint = null; function onCartChange(orderForm) { const fp = JSON.stringify((orderForm.items || []).map(i => i.productId + ':' + i.quantity )); if (fp === _lastFingerprint) return; _lastFingerprint = fp; console.log('Cart changed:', orderForm.items); captureCartEvent(orderForm); } // Intercept fetch const origFetch = window.fetch; window.fetch = function () { const url = arguments[0]?.url || arguments[0] || ''; return origFetch.apply(this, arguments).then(function (response) { if (typeof url === 'string' && url.includes('/api/checkout/pub/orderForm/')) { response.clone().json().then(function (body) { if (body && body.items) onCartChange(body); }).catch(function () {}); } return response; }); }; // Intercept XMLHttpRequest const origOpen = XMLHttpRequest.prototype.open; const origSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function (method, url) { this._cartUrl = url; return origOpen.apply(this, arguments); }; XMLHttpRequest.prototype.send = function () { this.addEventListener('load', function () { if (this._cartUrl && this._cartUrl.includes('/api/checkout/pub/orderForm/')) { try { const body = JSON.parse(this.responseText); if (body && body.items) onCartChange(body); } catch (e) {} } }); return origSend.apply(this, arguments); }; })(); try{ console.log('[abtest 0] [usertest ]'); } catch(e) {console.log('error load abtest log')}