function uuidv4() { return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)); } function splitString(stringToSplit, separator) { var arrayOfStrings = stringToSplit.split(separator); } function serialize(obj, prefix) { var str = [], p; for (p in obj) { if (obj.hasOwnProperty(p) && obj[p]) { var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p]; str.push((v !== null && typeof v === "object") ? serialize(v, k) : encodeURIComponent(k) + "=" + encodeURIComponent(v)); } } return str.join("&"); } function setCookie(cname, cvalue, exdays,domain=null) { var d = new Date(); d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/;"+(domain?("domain="+window.location.hostname.replace(window.location.hostname.split(".")[0]+".","")):""); } function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(";"); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == " ") { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function isEmpty(obj) { return obj && Object.keys(obj).length === 0 && Object.getPrototypeOf(obj) === Object.prototype; } if(getCookie("hoopCliente")&&!getCookie("client_deal")){ setCookie("client_deal",getCookie("external_ref"),90,1); } if(!getCookie("hoopCliente")&&getCookie("client_deal")){ setCookie("hoopCliente",1,90); } function sendEvent({status = null, name = null, email = null, phone = null, cep = null, cpf = null, prods = null, prod_name = null, prod_sku = null, prod_img = null, prod_category = null, variation_id = null , prod_id = null, id = null, final_value = null, reference = null,client_id = null, ecommerce = null}) { if (getCookie("external_ref") == "") setCookie("external_ref", uuidv4(), 90); var external_ref = getCookie("external_ref"); var utms={}; var queryString = window.location.search; var urlParams = new URLSearchParams(queryString); urlParams.forEach(function(value, key) { if(key=="campaign_id") key="ad_"+key; utms[key] = value; if(key=="hclid"){ setCookie("hoopCliente", 1, 90); } }); if(!isEmpty(utms)){ utms.url = window.location.href; var utc = new Date().toJSON().slice(0,10).replace(/-/g,"/"); utms.date = utc.split("/")[2] + "/" + utc.split("/")[1] + "/" + utc.split("/")[0]; } function readTextFile(file, callback) { var rawFile = new XMLHttpRequest(); rawFile.overrideMimeType("application/json"); rawFile.open("GET", file, true); rawFile.onreadystatechange = function() { if (rawFile.readyState === 4 && rawFile.status == "200") { callback(rawFile.responseText); } } rawFile.send(null); } if(getCookie("isBot")===""){ readTextFile("https://s3-sa-east-1.amazonaws.com/hoopdecor/static/production/files/user-agents-blocked.json", function(text){ var isBot=text.includes(navigator.userAgent); setCookie("isBot",isBot?1:0,90); }); } const data = { api_token: "867ffc9bd347c2d0a97372237407f72d", company_id: 148134, campaign_id: 872, topic_id: 1273, ecommerce: ecommerce, crosClient:getCookie("client_deal"), status: status, external_ref: external_ref, name: name, email: email, phone: phone, cep: cep, cpf: cpf, prods: prods, final_value:final_value, utms: utms, prod_sku: prod_sku, prod_id: prod_id, prod_name: prod_name, prod_img: prod_img, prod_category: prod_category, variation_id: variation_id, reference: reference, url: window.location.href, id: id, client_id:client_id, } if(getCookie("isBot")!=="1") fetch("https://hoopdecor.com/api/external/ecommerces?"+serialize(data)) .then(response => response.json()) .then(response => { var oldActions=JSON.parse(getCookie("hoop_actions")?getCookie("hoop_actions"):"[]"); var newActions=oldActions.concat(response); var newValue=[]; try{ newValue=JSON.stringify(newActions); if(newValue.length>1600){ newValue.shift(); } }catch (e) { newValue=[]; } setCookie("hoop_actions",newValue, 10); if(response.length) window.verifyCupons(0); }); } (()=>{ var myAppJavaScript = function(){ function HoopTrackModel() { this.plataform = "tray"; this.selectedBuy = null; this.data = { name: null, email: null, phone: null, cep: null, cpf: null, cart: [], prod_name: null, prod_sku: null, prod_id: null, prod_ref: null, prod_img: [], id: null, final_value: null, prod_category:[], client_id:null, } this.functions = { getCartSession(){ return document.querySelector("html").dataset.session || null; }, getAjax(e, t, a, r){ var request = new XMLHttpRequest(); var params = a; params="?" + Object .keys(params) .map(function(key){ return key+"="+encodeURIComponent(params[key]) }) .join("&"); var url =t + params; request.onreadystatechange = function (){ if (request.readyState == 4 && typeof JSON.parse(request.response).causes =="undefined"){ console.log("get Cart"); console.log(request.response); r(JSON.parse(request.response)); } }; request.open(e,url); request.send(); }, getCart:()=>{ const cartSession = this.functions.getCartSession(); if (cartSession) { this.data.cart = []; var e = "/web_api/cart/" + cartSession; this.functions.getAjax("GET", e, {}, (e)=> { console.log(e); e.forEach((item)=>{ const div = document.createElement("div"); div.innerHTML = item.Cart.product_name; const name = div.textContent || div.innerText || ""; this.data.cart.push({"name": name, "variation_id": item.Cart.variant_id == "0"?item.Cart.product_id:item.Cart.variant_id, "quantity": item.Cart.quantity, "value": item.Cart.price, "img": [item.Cart.product_image.https], "sku": item.Cart.variant_id !== "0"?`${item.Cart.product_id}-${item.Cart.variant_id}`:null}); this.data.client_id=item.Cart.customer_id; }); this.events.shopping_cart(); }); } }, getCategory(){ var array = []; dataLayer[0].breadcrumbDetails.forEach(function(value){ array.push(value.name); }); return array; }, getPage(){ if ( dataLayer&&dataLayer[0]&&dataLayer[0].nameProduct) { return "product"; } else if(location.pathname == "/checkout/cart"){ return "cart"; } else if(location.pathname == "/checkout" || location.pathname == "/checkout/"){ return "checkout"; } } } this.triggers = { buy:()=>{ document.querySelector("#form_comprar").addEventListener("submit",()=> { setTimeout(()=>{this.functions.getCart()},1000); }); }, productOpen:()=>{ this.data.prod_name = dataLayer[0].nameProduct; this.data.prod_id = dataLayer[0].listSku.length? dataLayer[0].listSku[0].idSku.split("-")[1]:dataLayer[0].idProduct; this.data.prod_img = [dataLayer[0].urlImage]; this.data.prod_sku = dataLayer[0].listSku.length? dataLayer[0].listSku[0].idSku:null; this.data.prod_ref = dataLayer[0].reference; if(this.data.prod_ref&&!this.data.prod_sku){ this.data.prod_sku=this.data.prod_ref; } this.events.product_open(); }, checkout:()=>{ const info = globalCart.data.cart.customer; this.data.email = info.email; this.data.name = info.name; this.data.cep = info.address.zipCode; this.data.phone = info.cellphone; this.data.client_id = info.id; if(!this.data.email.includes("*")) this.events.checkout(); }, order:()=>{ this.data.id = globalCart.data.cart.orderId; this.data.final_value = globalCart.data.cart.total; this.events.purchase(); }, cart:()=>{ this.data.cart = []; _this.model.cart.products().forEach((item)=>{ this.data.cart.push({"name":item.name(),"sku": item.variant_id() == "0"?null:item.sku_ga(), "variation_id": item.variant_id() == "0"?item.id():item.variant_id(), "quantity": item.quantity(), "value": parseFloat(item.price()), "img": [item.images.large()], "reference": item.variant_id() == "0"? item.reference():null}); }); this.events.shopping_cart(); } } this.observers = { watchCheckout:()=>{ let aux = 1; new MutationObserver(() => { if (globalCart.data.cart.customer?.id && globalCart.data.cart.customer.address && aux) { aux = 0; this.triggers.checkout(globalCart.data.cart.customer); } }).observe(document, {subtree: true, childList: true}); }, watchCart:()=>{ let lastTotal = _this.model.total(); new MutationObserver(() => { let total = _this.model.total(); if (lastTotal != total) { lastTotal = total; this.triggers.cart(); } console.log(lastTotal); }).observe(document.querySelector("[data-cart-template='products']"), {subtree: true, childList: true}); }, watchOrder:()=>{ let aux = 1; new MutationObserver(() => { if (globalCart.data.cart.orderId && aux) { aux = 0; this.triggers.order(); } }).observe(document, {subtree: true, childList: true}); }, watchCopy(){ let copy=document.querySelector('h1[itemprop="name"],h1[class="product-name"]'); if(!copy){ copy=document.querySelector('h2[itemprop="name"],h3[itemprop="name"]'); } if(copy) copy.oncopy=function(){ window.hoopTrack.events.copy(); }; } } this.events = { shopping_cart:()=>{ window.sendEvent({status : "shopping_cart", prods : this.data.cart.length?this.data.cart:"empty",client_id:this.data.client_id, ecommerce: "tray"}); }, product_open:()=>{ window.sendEvent({status : "product_open", prod_name : this.data.prod_name, prod_sku : this.data.prod_sku, prod_img : this.data.prod_img, prod_category : this.data.prod_category, variation_id : this.data.prod_id, reference : this.data.prod_ref, ecommerce: "tray"}); }, checkout:()=>{ window.sendEvent({status : "checkout", name : this.data.name, email : this.data.email, phone : this.data.phone, cep : this.data.cep, prods : this.data.products,client_id:this.data.client_id, ecommerce: "tray"}); }, purchase:()=>{ window.sendEvent({status : "purchase",id : this.data.id, final_value : this.data.final_value, ecommerce: "tray"}); }, clear:()=>{ window.sendEvent({}); }, copy:()=>{ window.sendEvent({status : "copy", prod_name : this.data.prod_name, prod_sku : this.data.prod_sku, prod_img : this.data.prod_img, prod_category : this.data.prod_category, variation_id : this.data.prod_id, reference : this.data.prod_ref, ecommerce: "tray"}); }, } this.init = function(){ let page = this.functions.getPage(); switch (page){ case "product": this.triggers.productOpen(); this.observers.watchCopy(); this.triggers.buy(); setTimeout(this.functions.getCart.bind(this.functions), 1500); break; case "checkout": this.events.checkout(); this.observers.watchCheckout(); this.observers.watchOrder(); break; case "cart": this.observers.watchCart(); break; case "purchase": this.triggers.order(); break; default: this.events.clear(); setTimeout(this.functions.getCart(), 1500); break; } } } window.hoopTrack = new HoopTrackModel(); window.hoopTrack.init(); } myAppJavaScript(); })()