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gBlF,M","sources":["webpack://build/../template2/assets/javascripts/components/utilities.js","webpack://build/../template2/assets/javascripts/common/cartDrawer.js","webpack://build/../template2/assets/javascripts/components/store.js","webpack://build/../template2/assets/javascripts/productPurchase.js"],"sourcesContent":["// ===============================================================\n// ADIÇÃO MANUAL DE ASSET\n// ===============================================================\n// Usado para incluir assets no código de forma manual, conforme a necessidade\nexport function addAsset(source, onloadCallback) {\n\n if (!source || source === '') return console.error(`addAsset: caminho não definido.`)\n\n if (source.includes('.js')) {\n const scriptTag = document.createElement('script')\n scriptTag.setAttribute('src', source);\n\n if (onloadCallback && typeof onloadCallback === 'function') {\n scriptTag.onload = onloadCallback\n }\n\n return document.body.appendChild(scriptTag)\n\n } else if (source.includes('.css')) {\n const linkTag = document.createElement('link')\n linkTag.setAttribute('rel', 'stylesheet')\n linkTag.setAttribute('type', 'text/css')\n linkTag.setAttribute('href', source)\n return document.head.appendChild(linkTag)\n\n } else {\n const error = `addAsset: Erro ao criar o asset. Tipo de script não definido, ou não possui tratamento para este tipo de asset.`\n return console.error(error, source)\n }\n}\n\n// ===============================================================\n// BUSCA O CARRINHO ATIVO\n// ===============================================================\nexport async function getCart() {\n try {\n const response = await fetch('/carrinho', {\n headers: {\n 'Accept': 'application/json'\n }\n });\n\n return await response.json()\n\n } catch (error) {\n console.error('Erro ao buscar os dados do carrinho');\n console.error(error);\n return false\n }\n}\n\n// ===============================================================\n// SERIALIZE ARRAY\n// ===============================================================\nexport function serializeArray(form) {\n\n const formData = new FormData(form);\n const data = {};\n\n for (const [name, value] of formData) {\n data[name] = value\n }\n\n const formBody = [];\n\n for (const key in data) {\n const encodeKey = encodeURIComponent(key)\n const encodeValue = encodeURIComponent(data[key])\n formBody.push(`${encodeKey}=${encodeValue}`)\n }\n\n return formBody.join('&')\n \n}\n\n// ===============================================================\n// URL ENCODE FORM DATA\n// ===============================================================\nexport function urlencodeFormData(formData) {\n let string = '';\n\n function encode(s) {\n return encodeURIComponent(s).replace(/%20/g, '+');\n }\n\n for (const pair of formData.entries()) {\n if (typeof pair[1] == 'string') {\n string += (string ? '&' : '') + encode(pair[0]) + '=' + encode(pair[1]);\n }\n }\n return string;\n}\n\n// ===============================================================\n// SLIDE TOGGLE\n// ===============================================================\nexport function slideToggle(contentWrapper, content, duration = 500) {\n let initialHeight = window.getComputedStyle(contentWrapper).height;\n\n if (initialHeight == '0px') {\n return slideDown(contentWrapper, content, duration);\n } else {\n return slideUp(contentWrapper, duration);\n }\n}\n\n// ===============================================================\n// SLIDE UP\n// ===============================================================\nexport function slideUp(contentWrapper, duration = 500) {\n contentWrapper.style.height = '0px';\n contentWrapper.style.transition = `height ${duration} ease`;\n}\n\n// ===============================================================\n// SLIDE DOWN\n// ===============================================================\nexport function slideDown(contentWrapper, content, duration = 500) {\n let innerHeight = content.clientHeight;\n\n contentWrapper.style.height = `${innerHeight}px`;\n contentWrapper.style.transition = `height ${duration} ease`;\n}\n\n// ===============================================================\n// UPDATE DISCOUNT IN PRODUCT BLOCK\n// ===============================================================\nexport function updatePriceBlock() {\n const priceEls = document.querySelectorAll('[data-init-price]');\n\n if (priceEls == null) return;\n\n priceEls.forEach((priceEl) => {\n const discount = priceEl.dataset.discountPercent;\n\n priceEl.dispatchEvent(new Event('change'));\n\n // discount\n if (discount != '0') {\n priceEl.style.setProperty('--discount', `'-${discount}%'`);\n }\n });\n}\n\n// ===============================================================\n// PREÇO POR FETCH\n// ===============================================================\nexport function getPriceProd() {\n const selectors = document.querySelectorAll('[data-update-price]');\n const attr = 'data-update-price';\n\n if (selectors.length > 0) {\n selectors.forEach((selector) => {\n const prodId = selector.getAttribute(attr)\n const url = `/produto/preco/${prodId}`;\n\n if (prodId !== '' && prodId !== null) {\n fetch(url, {\n method: 'GET',\n })\n .then((response) => response.text())\n .then((resp) => {\n selector.innerHTML = resp;\n })\n .catch((error) => {\n console.error(error);\n });\n }\n });\n }\n}\n\n// ===============================================================\n// DEBOUNCE\n// ===============================================================\n/*\n Debounce retorna uma função que enquanto continuar sendo chamada não é executada\n A função só será executada quando para de ser chamada por N milisegundos\n Útil para melhorar a performance de códigos que são executados muitas vezes por segundo, como o $(window).resize()\n\n Ex:\n \n $(window).resize(debounce(function() {\n // código a ser executado\n }, 500))\n \n No exemplo acima a função só será executada 500ms depois do último resize\n Abra o link abaixo e redimensione a janela branca e acompanhe o output do console\n Exemplo codepen: https://codepen.io/valkervieira/pen/oNgqyWY\n\n Um caso comum de uso é em lojas onde a seleção de um filtro na página de tag recarrega automáticamente a página\n Com o debounce o usuário pode escolher vários filtros rapidamente e a página só recarrega quando parar de escolher\n*/\n\nexport function debounce(func, wait, immediate) {\n var timeout;\n immediate || (immediate = true);\n\n return function () {\n var context = this,\n args = arguments;\n\n var later = function () {\n timeout = null;\n if (!immediate) func.apply(context, args);\n };\n\n var callNow = immediate && !timeout;\n\n clearTimeout(timeout);\n\n timeout = setTimeout(later, wait);\n\n if (callNow) func.apply(context, args);\n };\n}\n\n// ===============================================================\n// THROTTLE\n// ===============================================================\n/*\n Throttle diminui a frequencia que uma função é executada\n Enquanto no debounce a função só é executada quando para de ser chamada, no throttle ela\n continua sendo executada só que em um intervalo mínimo de N milisegundos (default = 250)\n\n Ex:\n\n $(window).resize(throttle() {\n // código a ser executado\n }, 500)\n\n No exemplo acima a função resize é chamada várias vezes por segundo mas só é executada 1 vez a cada 500ms\n Abra o link abaixo, redimensione a janela branca e acompanhe o console\n Exemplo codepen: https://codepen.io/valkervieira/pen/yLyKEPW\n\n Um caso comum de uso é checar se o scroll passou de um determinado ponto, para fixar um header ou alterar algum elemento do DOM\n*/\nexport function throttle(fn, threshhold, scope) {\n threshhold || (threshhold = 250);\n var last, deferTimer;\n return function () {\n var context = scope || this;\n\n var now = +new Date(),\n args = arguments;\n if (last && now < last + threshhold) {\n // hold on to it\n clearTimeout(deferTimer);\n deferTimer = setTimeout(function () {\n last = now;\n fn.apply(context, args);\n }, threshhold);\n } else {\n last = now;\n fn.apply(context, args);\n }\n };\n}\n\n// ===============================================================\n// FORMAT MONEY\n// ===============================================================\nexport function formatMoney(value) {\n // FORMATA UM VALOR\n return (\n 'R$ ' +\n value\n .toFixed(2)\n .replace('.', ',')\n .replace(/(\\d)(?=(\\d{3})+\\,)/g, '$1.')\n );\n}\n\n// ===============================================================\n// FORMAT VALUE\n// ===============================================================\n\nexport const formatValue = function (value = '') {\n let parsedValue = value;\n if (typeof value === 'number') {\n parsedValue = value.toFixed(2).toString();\n }\n return parsedValue.replace('.', ',');\n};\n\n// ===============================================================\n// VALIDA QUANTIDADE\n// ===============================================================\nexport function validateQuantity(_val) {\n // VALIDA SE A QUANTIDADE INFORMADA É UM NÚMERO\n if (!isNaN(_val)) {\n if (parseInt(_val) > 0) {\n return true;\n }\n }\n\n return false;\n}\n\n// ===============================================================\n// CLEAR NUMBER\n// ===============================================================\nexport function getClearNumber(_val) {\n // RETORNA UM NÚMERO LIMPO COMO INT\n if (!isNaN(_val)) {\n var clearNumber = parseInt(_val);\n\n return clearNumber;\n }\n\n return false;\n}\n\n// ===============================================================\n// BUSCA\n// ===============================================================\nexport function setSearch() {\n const toggleButton = document.querySelectorAll('[data-toggle-search]');\n const search = document.querySelector('[data-search-container]');\n const input = document.querySelector('[data-search-input]');\n\n toggleButton.length > 0 && toggleButton.forEach(button => {\n button.addEventListener('click', () => {\n\n if (search.classList.contains('open')) {\n search.classList.remove('open');\n\n } else {\n search.classList.add('open');\n setTimeout(() => { input.focus() }, 400);\n }\n })\n })\n}\n\n// ===============================================================\n// BUSCA OS DADOS DO CLIENTE\n// ===============================================================\nexport async function getClient() {\n try {\n const response = await fetch('/conta/cliente', {\n headers: {\n 'accept': 'application/json',\n 'Content-Type': 'application/json',\n 'cache': 'no-store'\n }\n });\n const client = await response.json();\n const access = Object.keys(client).length > 0;\n\n if (access) {\n window.client = client;\n\n return client\n\n } else {\n return null\n }\n\n } catch (error) { console.error(`getClient error`, error) }\n}\n\n// ===============================================================\n// MÁSCARA PARA INPUTS\n// ===============================================================\nexport function formMasks() {\n const\n inputPhones = document.querySelectorAll('[data-phone-mask]'),\n inputCEPs = document.querySelectorAll('[data-cep-mask]'),\n inputCPFs = document.querySelectorAll('[data-cpf-mask]'),\n inputCNPJs = document.querySelectorAll('[data-cnpj-mask]'),\n inputDatesOfBirth = document.querySelectorAll('[data-birth-mask]');\n\n inputPhones.length > 0 && inputPhones.forEach(input => {\n input.addEventListener('input', (e) => {\n //(XX) XXXXX-XXXX\n var phoneValue = e.target.value.replace(/\\D/g, '').match(/(\\d{0,2})(\\d{0,5})(\\d{0,4})/);\n e.target.value = !phoneValue[2] ? phoneValue[1] : '(' + phoneValue[1] + ') ' + phoneValue[2] + (phoneValue[3] ? '-' + phoneValue[3] : '');\n });\n })\n\n inputCEPs.length > 0 && inputCEPs.forEach(input => {\n input.addEventListener('input', (e) => {\n //XXXXX-XX\n var cepValue = e.target.value.replace(/\\D/g, '').match(/(\\d{0,5})(\\d{0,3})/);\n e.target.value = !cepValue[2] ? cepValue[1] : cepValue[1] + '-' + cepValue[2];\n })\n })\n\n inputCPFs.length > 0 && inputCPFs.forEach(input => {\n input.addEventListener('input', (e) => {\n //XXX.XXX.XXX-XX\n var cpfValue = e.target.value.replace(/\\D/g, '').match(/(\\d{0,3})(\\d{0,3})(\\d{0,3})(\\d{0,2})/);\n e.target.value = !cpfValue[2] ? cpfValue[1] : cpfValue[1] + '.' + cpfValue[2] + (cpfValue[3] ? '.' + cpfValue[3] : '') + (cpfValue[4] ? '-' + cpfValue[4] : '');\n })\n })\n\n inputCNPJs.length > 0 && inputCNPJs.forEach(input => {\n input.addEventListener('input', (e) => {\n //XX.XXX.XXX/XXXX-XX\n var cnpjValue = e.target.value.replace(/\\D/g, '').match(/(\\d{0,2})(\\d{0,3})(\\d{0,3})(\\d{0,4})(\\d{0,2})/);\n e.target.value = !cnpjValue[2] ? cnpjValue[1] : cnpjValue[1] + '.' + cnpjValue[2] + (cnpjValue[3] ? '.' + cnpjValue[3] : '') + (cnpjValue[4] ? '/' + cnpjValue[4] : '') + (cnpjValue[5] ? '-' + cnpjValue[5] : '');\n })\n })\n\n inputDatesOfBirth.length > 0 && inputDatesOfBirth.forEach(input => {\n input.addEventListener('input', (e) => {\n // XXXX-XX-XX\n var dateOfBirthValue = e.target.value.replace(/\\D/g, '').match(/(\\d{0,2})(\\d{0,2})(\\d{0,4})/);\n e.target.value = !dateOfBirthValue[2] ? dateOfBirthValue[1] : dateOfBirthValue[1] + '/' + dateOfBirthValue[2] + (dateOfBirthValue[3] ? '/' + dateOfBirthValue[3] : '');\n });\n })\n}","import { addAsset } from '../components/utilities';\n\nconst CartDrawer = {\n root: document.querySelector('#component-cart-drawer-root'),\n buttons: document.querySelectorAll('[data-toggle-cart]'),\n countWrapper: document.querySelector('[data-cart-count]'),\n settings: window.cartDrawerSettings || false,\n\n setCartDrawer: function () {\n const { settings, root } = CartDrawer;\n\n if (!root || !settings) return;\n\n // Define frete grátis\n const freeShipping = settings.freeShippingValue > 1 ? settings.freeShippingValue : 0;\n\n // Inicia o componente\n const componentCartDrawer = new Vnda.Component.CartDrawer({\n anchor: 'right',\n display: 'list',\n startOpen: false,\n titleCart: 'Carrinho de compras',\n titleSuggested: window.cartDrawerSettings.titleSuggested,\n suggestedProductsTag: 'sugestoes-carrinho',\n widthItemSuggested: 25,\n disableShippingCalculation: true,\n freeShipping,\n });\n\n // Renderiza o componente\n componentCartDrawer.render(root);\n\n // Salva instância para acesso global\n window.cartDrawerSettings.instance = componentCartDrawer;\n CartDrawer.settings = window.cartDrawerSettings;\n\n // dispara evento de carregamento, escutado por CartDrawer.show()\n root.dispatchEvent(new Event('vnda:cart-drawer-loaded'));\n },\n\n loadComponent: function () {\n const { settings } = CartDrawer;\n addAsset(settings.script, CartDrawer.setCartDrawer);\n addAsset(settings.styles);\n },\n\n handleCartButton: function (button) {\n // Evita múltiplos cliques caso o carrinho precisa ser instanciado primeiro\n if (button.classList.contains('-loading')) {\n return;\n }\n\n // Abre o cart drawer\n button.classList.add('-loading');\n CartDrawer.show(() => {\n button.classList.remove('-loading');\n });\n },\n\n show: function (callback) {\n const { root } = CartDrawer;\n\n // No mobile, fecha o menu primeiro\n if (window.mmenu) window.mmenu.close();\n\n // Instancia o componente, caso ainda não exista\n if (!CartDrawer.settings.instance) CartDrawer.loadComponent();\n\n // Observa criação da instância inicial, caso não tenha\n if (CartDrawer.settings.instance === false) {\n root.addEventListener('vnda:cart-drawer-loaded', () => {\n CartDrawer.settings.instance.open();\n if (typeof callback === 'function') callback();\n });\n } else {\n // Já possui cart drawer instanciado, retorna abertura\n CartDrawer.settings.instance.open();\n if (typeof callback === 'function') callback();\n }\n },\n\n getCartItens: async function () {\n try {\n const response = await fetch('/carrinho/itens');\n const itens = await response.json();\n return itens;\n } catch (error) {\n console.error('Erro ao buscar a quantidade de produtos do carrinho');\n console.error(error);\n return 0;\n }\n },\n\n updateCartCount: async function (_itemsCount = null) {\n let items = _itemsCount;\n if (_itemsCount == null) items = await CartDrawer.getCartItens();\n\n this.countWrapper.innerHTML = items;\n },\n\n init: function () {\n const _this = this;\n const { buttons } = _this;\n\n // Atualiza o contador de itens do carrinho\n _this.updateCartCount();\n\n if (buttons.length > 0)\n buttons.forEach((button) => {\n button.addEventListener('click', () => {\n _this.handleCartButton(button);\n });\n });\n },\n};\n\nexport default CartDrawer;\n","import CartDrawer from '../common/cartDrawer';\nimport { urlencodeFormData } from './utilities';\n\nconst Store = {\n openCartDrawer: true,\n openCartDrawerMobile: true,\n\n addProduct: function(form, parent, callback) {\n // Se tiver customizações, ajusta campos de texto que não foram preenchidos\n const customizations = form.querySelectorAll('[data-customization]')\n const quantity = Number(form.querySelector('[name=\"quantity\"]').value)\n if (customizations.length > 0) customizations.forEach(custom => {\n const type = custom.getAttribute('type')\n\n if (type !== 'checkbox' || type !== 'radio') {\n if (custom.value === '') {\n custom.setAttribute('disabled', true)\n }\n }\n })\n\n if (customizations.length > 0 && quantity > 1) {\n // Item com personalização e com quantidade alta\n Store.addItemsCustom(form, parent, callback)\n } else {\n // Item com quantidade 1, com ou sem personalização\n Store.addItem(form, parent, callback)\n }\n },\n\n addItemsCustom: async function(form, parent, callback) {\n const _this = this;\n const btnComprar = parent.querySelector('[data-action=\"add-cart\"]');\n const boxResponse = parent.querySelector('[data-form-product] .msg-response:not(.resp-validate)');\n const quantity = Number(form.querySelector('[name=\"quantity\"]').value)\n let hasCustoms = false\n let customs = {}\n\n // Prepara o item e suas personalizações\n let data = { items: [\n {\n sku: form.querySelector('[name=\"sku\"]').value,\n quantity,\n customizations: []\n }\n ]}\n\n const customizations = form.querySelectorAll('[data-customization]')\n if (customizations.length > 0) customizations.forEach(custom => {\n const disabled = custom.getAttribute('disabled')\n const type = custom.getAttribute('type')\n let checked = true;\n if (type !== 'text' && type !== 'textarea') checked = custom.checked\n\n if (checked && disabled !== 'true') {\n hasCustoms = true\n if (type === 'text' || type === 'textarea') {\n customs[custom.getAttribute('data-customization-name')] = custom.value\n } else {\n customs[custom.getAttribute('data-customization-name')] = custom.getAttribute('value') \n }\n }\n })\n\n if (hasCustoms) {\n for (let index = 0; index < quantity; index++) {\n data.items[0].customizations.push(customs)\n }\n }\n\n const json_data = JSON.stringify(data)\n\n console.info('addItemsCustom');\n // console.log(json_data)\n\n // Envia o produto com suas personalizações\n if (!btnComprar.classList.contains('-adding')) {\n btnComprar.classList.add('-adding')\n\n try {\n const response = await fetch('/carrinho/adicionar/kit', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: json_data,\n });\n \n const html = await response.text();\n\n if (response.ok) {\n console.log('addItemsCustom - success');\n if (typeof callback == 'function') {\n callback('produto-adicionado', html, boxResponse, form);\n } else {\n _this.addItemResult('produto-adicionado', html, boxResponse, form);\n }\n\n } else {\n console.log('addItemsCustom - server não reconheceu adição');\n if (typeof callback == 'function') {\n callback('erro-adicionar', error, boxResponse, form);\n } else {\n _this.addItemResult('erro-adicionar', error, boxResponse, form);\n }\n }\n\n } catch (error) {\n console.log('addItemsCustom - error');\n console.error(error);\n\n if (typeof callback == 'function') {\n callback('erro-adicionar', error, boxResponse, form);\n } else {\n _this.addItemResult('erro-adicionar', error, boxResponse, form);\n }\n }\n\n customizations.forEach(custom => {\n custom.removeAttribute('disabled')\n })\n\n btnComprar.classList.remove('-adding');\n }\n },\n\n addItem: async function (form, parent, callback) {\n const _this = this;\n const btnComprar = parent.querySelector('[data-action=\"add-cart\"]');\n const urlAdd = '/carrinho/adicionar';\n const formData = urlencodeFormData(new FormData(form));\n const boxResponse = parent.querySelector('[data-form-product] .msg-response:not(.resp-validate)');\n\n console.info('addItem');\n\n if (!btnComprar.classList.contains('-adding')) {\n btnComprar.classList.add('-adding');\n\n try {\n const response = await fetch(urlAdd, {\n method: 'POST',\n headers: {\n 'Accept': 'application/json, text/javascript, */*; q=0.0',\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n },\n body: formData,\n });\n\n const html = await response.text();\n\n console.log('addItem - success');\n\n if (typeof callback == 'function') {\n callback('produto-adicionado', html, boxResponse, form);\n } else {\n _this.addItemResult('produto-adicionado', html, boxResponse, form);\n }\n } catch (error) {\n console.log('addItem - error');\n console.error(error);\n\n if (typeof callback == 'function') {\n callback('erro-adicionar', error, boxResponse, form);\n } else {\n _this.addItemResult('erro-adicionar', error, boxResponse, form);\n }\n }\n\n btnComprar.classList.remove('-adding');\n }\n },\n\n deleteItem: async function (itemId, item, removeItemResult) {\n const _this = this;\n\n try {\n const body = new URLSearchParams({\n _method: 'DELETE',\n item_id: itemId\n });\n\n const response = await fetch('/carrinho', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n },\n body\n })\n\n console.log('success');\n \n if (window.innerWidth > 768) {\n if (_this.openCartDrawer) {\n CartDrawer.updateCartCount();\n }\n } else {\n if (_this.openCartDrawerMobile) {\n CartDrawer.updateCartCount();\n }\n }\n\n if (typeof removeItemResult == 'function') {\n removeItemResult(item);\n }\n } catch (error) {\n console.log('Erro ao remover item do carrinho');\n console.log(error);\n }\n },\n\n validateFormProduct: function (form) {\n // VALIDA O FORM DE PRODUTO PARA VER SE O PRODUTO PODE SER ADICIONADO\n var btnComprar = form.querySelector('[data-action=\"add-cart\"]');\n var validated = true;\n var errors = [];\n\n if (btnComprar.dataset.available == 'false') {\n validated = false;\n errors.push('');\n } else {\n // verifica se o sku foi selecionado\n if (form.querySelector('[name=\"sku\"]').value == '') {\n validated = false;\n errors.push('Selecione um atributo para o produto');\n }\n\n // verifica se a quantidade é válida\n if (form.querySelector('input[name=\"quantity\"]').value <= 0) {\n validated = false;\n errors.push('Quantidade indisponível');\n }\n }\n\n return { validated, errors };\n },\n\n setRespValidateProduct: function (resp, form, boxResponse) {\n let htmlErrors = '';\n\n if (resp.validated) {\n boxResponse.innerHTML = '';\n } else {\n for (var i = resp.errors.length - 1; i >= 0; i--) {\n htmlErrors += '' + resp.errors[i] + '';\n }\n boxResponse.innerHTML = htmlErrors;\n }\n },\n\n addItemResult: function (typeResult, result, boxResponse, form) {\n const _this = this;\n\n if (typeResult == 'produto-adicionado') {\n const btnComprar = form.querySelector('[data-action=\"add-cart\"]');\n\n if (btnComprar) btnComprar.classList.add('success');\n\n setTimeout(function () {\n if (btnComprar) btnComprar.classList.remove('success');\n if (btnComprar) btnComprar.innerHTML = btnComprar.dataset.textAvailable;\n }, 3500);\n\n // CartDrawer.updateCartCount();\n\n if (window.innerWidth > 768) {\n if (_this.openCartDrawer) {\n CartDrawer.show();\n } else {\n setTimeout(() => {\n window.location.href = urlCart;\n }, 150);\n }\n } else {\n if (_this.openCartDrawerMobile) {\n CartDrawer.show();\n } else {\n setTimeout(() => {\n window.location.href = urlCart;\n }, 150);\n }\n }\n\n // Verifica se há popup de compra rápida ativo. Se tiver, fecha ele\n // Retirar ou comentar se não for utilizado\n const popupQuickview = document.querySelectorAll('[data-popup-quickview]');\n popupQuickview.length > 0 && popupQuickview.forEach(popup => {\n if (popup.classList.contains('-active')) {\n popup.querySelector('[data-close-popup-quickview]').click();\n }\n })\n\n // Remove disabled das personalizações de texto, se existirem\n const customizations = form.querySelectorAll('[data-customization]')\n if (customizations.length > 0) customizations.forEach(custom => {\n const type = custom.getAttribute('type')\n if (type !== 'checkbox' || type !== 'radio') {\n custom.removeAttribute('disabled')\n }\n })\n \n } else if (typeResult == 'erro-adicionar') {\n if (typeof boxResponse != 'undefined' && boxResponse.length > 0) {\n window.scrollTo({\n top: boxResponse.offsetTop,\n behavior: 'smooth',\n });\n\n boxResponse.classList.add('error');\n boxResponse.classList.remove('success');\n boxResponse.querySelector('span').innerHTML =\n 'Ocorreu um erro, tente novamente.';\n }\n }\n },\n};\n\nexport default Store;\n","// \"productVariants\" é inicializado em layout.liquid, e todos os arquivos liquid que montam\n// product_block populam este objeto com as variantes dos produtos em tela\nimport Store from './components/store';\n\nconst ProductPurchase = {\n productVariants,\n products: document.querySelectorAll('[data-product-box]'),\n useLocals: false, // Venda por Locais: alterar para habilitar a funcionalidade - true/false \n\n // Verifica as combinações possíveis entre os atributos, com base no atributo que foi clicado\n checkCombinations: function (currentProduct, selectedAttribute) {\n const productId = currentProduct.getAttribute('data-product-id');\n const selectedAttr = Number(selectedAttribute.getAttribute('data-attribute-index'));\n const variants = ProductPurchase.productVariants[`${productId}`];\n\n // Busca todos os atributos do produto\n const attributes = {\n attr1: [...currentProduct.querySelectorAll('[data-attribute-index=\"1\"]')],\n attr2: [...currentProduct.querySelectorAll('[data-attribute-index=\"2\"]')],\n attr3: [...currentProduct.querySelectorAll('[data-attribute-index=\"3\"]')],\n };\n\n // Busca os atuais atributos selecionados\n const selectedAttributes = {\n attr1: currentProduct.querySelector('[data-attribute=\"1\"] input:checked + label'),\n attr2: currentProduct.querySelector('[data-attribute=\"2\"] input:checked + label'),\n attr3: currentProduct.querySelector('[data-attribute=\"3\"] input:checked + label'),\n };\n\n // Altera o selected para o atributo que foi clicado\n selectedAttributes[`attr${selectedAttr}`] = selectedAttribute;\n\n // Atualiza as classes dos atributos disponíveis/indisponíveis\n // Ao clicar em uma opção de attr1, atualiza os attrs 2 e 3\n switch (selectedAttr) {\n case 1:\n ProductPurchase.markAttributes([...attributes.attr2], 2, variants, selectedAttributes, currentProduct);\n ProductPurchase.markAttributes([...attributes.attr3], 3, variants, selectedAttributes, currentProduct);\n break;\n\n case 2:\n ProductPurchase.markAttributes([...attributes.attr3], 3, variants, selectedAttributes, currentProduct);\n break;\n\n case 3:\n break;\n }\n },\n\n // Marca os atributos como disponiveis/indisponiveis com base nas combinações do checkCombinations\n markAttributes: function (attributes, index, variants, selectedAttributes, currentProduct) {\n if (attributes != null && attributes.length > 0) {\n // Remove os atributos já selecionados que não devem ser analizados,\n // com base no index do atributo que está sendo analizado. Usado para filtrar\n // as variantes e diminuir o número de possíveis combinações que definem como disponível/indisponível\n switch (index) {\n case 1:\n selectedAttributes.attr2 = null;\n selectedAttributes.attr3 = null;\n break;\n\n case 2:\n selectedAttributes.attr3 = null;\n break;\n\n case 3:\n break;\n }\n\n attributes.forEach((attr) => {\n const value = attr.getAttribute('data-attribute-value');\n const property = `property${index}`;\n let available = false;\n\n // Adiciona o atributo iterado nos atributos usados para buscar variantes válidas\n const attrsToCheck = {\n ...selectedAttributes,\n [`attr${index}`]: attr,\n };\n\n // Filtra as variantes para somente as que possuem a combinação de atributos válida\n const validVariants = variants.filter((variant) => {\n const properties = variant.properties;\n let validAttr1 = false;\n let validAttr2 = false;\n let validAttr3 = false;\n\n if (attrsToCheck.attr1 == null) validAttr1 = true;\n if (attrsToCheck.attr2 == null) validAttr2 = true;\n if (attrsToCheck.attr3 == null) validAttr3 = true;\n\n if (properties.property1 == null) validAttr1 = true;\n if (properties.property2 == null) validAttr2 = true;\n if (properties.property3 == null) validAttr3 = true;\n\n if (validAttr1 == false) {\n const valueToCheck = attrsToCheck.attr1.getAttribute('data-attribute-value');\n if (properties.property1.value == valueToCheck) validAttr1 = true;\n }\n\n if (validAttr2 == false) {\n const valueToCheck = attrsToCheck.attr2.getAttribute('data-attribute-value');\n if (properties.property2.value == valueToCheck) validAttr2 = true;\n }\n\n if (validAttr3 == false) {\n const valueToCheck = attrsToCheck.attr3.getAttribute('data-attribute-value');\n if (properties.property3.value == valueToCheck) validAttr3 = true;\n }\n\n if (validAttr1 && validAttr2 && validAttr3) return variant;\n });\n\n attr.classList.remove('-available');\n attr.classList.remove('-unavailable');\n attr.classList.remove('-disabled');\n\n if (validVariants.length > 0) {\n // Encontrou variantes, marca como disponível/indisponível com base nas variantes\n for (const variant of validVariants) {\n if (variant.properties[property]) {\n if (variant.properties[property].value == value) {\n\n // Venda por Locais\n // Busca informações da variante de acordo com o local selecionado\n let variantInventory = null;\n if (window.currentLocal) {\n variantInventory = variant.inventories.find(inventory => {\n return inventory.place && inventory.place.id && inventory.place.id === window.currentLocal.id;\n });\n\n } else if (ProductPurchase.useLocals) {\n // Sem local definido, busca por estoque em algum dos locais\n variantInventory = variant.inventories.find(inventory => {\n return inventory.available;\n });\n }\n\n if ((variantInventory && variantInventory.available) || (!variantInventory && variant.available)) {\n available = true;\n break;\n }\n }\n }\n }\n\n available ? attr.classList.add('-available') : attr.classList.add('-unavailable');\n } else if (validVariants.length === 0) {\n // Não encontrou nenhuma variante, então desabilita a opção.\n // Se esta opção estava selecionada, clica na primeira opção disponível entre os demais\n attr.classList.add('-disabled');\n const value = attr.getAttribute('data-attribute-value');\n const input = currentProduct.querySelector(`[data-attribute=\"${index}\"] input[value=\"${value}\"]`);\n if (input.checked) {\n input.checked = false;\n setTimeout(() => {\n const firstAvailable = currentProduct.querySelector(\n `label[data-attribute-index=\"${index}\"]:not(.-disabled)`\n );\n if (firstAvailable) firstAvailable.click();\n }, 50);\n }\n }\n });\n }\n },\n\n // Procura por SKU válido dentre os atributos escolhidos\n checkSelection: function (currentProduct) {\n const productId = currentProduct.getAttribute('data-product-id');\n const variants = ProductPurchase.productVariants[`${productId}`];\n\n const selectedAttrs = {\n attr1: currentProduct.querySelector('[data-attribute=\"1\"] input:checked'),\n attr2: currentProduct.querySelector('[data-attribute=\"2\"] input:checked'),\n attr3: currentProduct.querySelector('[data-attribute=\"3\"] input:checked'),\n };\n\n let available = false;\n\n for (let index = 0; index < variants.length; index++) {\n const variant = variants[index];\n let attr1 = false;\n let attr2 = false;\n let attr3 = false;\n let attr1Value = null;\n let attr2Value = null;\n let attr3Value = null;\n\n // Venda por Locais\n // Busca informações da variante de acordo com o local selecionado\n let variantInventory = null;\n if (window.currentLocal) {\n variantInventory = variant.inventories.find(inventory => {\n return inventory.place && inventory.place.id && inventory.place.id === window.currentLocal.id;\n });\n }\n\n // Verifica se algum dos atributos é inexistente no cadastro\n if (variant.properties.property1 == null) attr1 = true;\n if (variant.properties.property2 == null) attr2 = true;\n if (variant.properties.property3 == null) attr3 = true;\n\n //Salva o valor de cada um dos atributos/propriedes da própria variante em questão\n if (variant.properties.property1) attr1Value = variant.properties.property1.value;\n if (variant.properties.property2) attr2Value = variant.properties.property2.value;\n if (variant.properties.property3) attr3Value = variant.properties.property3.value;\n\n // Verifica se a variante possui os atributos selecionados\n if (!attr1 && attr1Value != null && selectedAttrs.attr1 != null) {\n if (attr1Value == selectedAttrs.attr1.value) attr1 = true;\n }\n\n if (!attr2 && attr2Value != null && selectedAttrs.attr2 != null) {\n if (attr2Value == selectedAttrs.attr2.value) attr2 = true;\n }\n\n if (!attr3 && attr3Value != null && selectedAttrs.attr3 != null) {\n if (attr3Value == selectedAttrs.attr3.value) attr3 = true;\n }\n\n // Se achou variante compatível com os atributos selecionados, atualiza\n if (attr1 && attr2 && attr3) {\n available = true;\n const event = new CustomEvent('vnda:sku-change', { detail: { sku: variant.sku } });\n const productContainer = currentProduct.closest('[data-product-box]');\n\n currentProduct.querySelector('[name=\"sku\"]').value = variant.sku;\n currentProduct.dispatchEvent(event);\n if (productContainer) productContainer.dispatchEvent(event);\n\n // Reinicializa o input de quantidade para 1\n currentProduct.querySelector('[name=\"quantity\"]').value = 1;\n\n // Remove a mensagem de quantidade máxima quando altera a variante\n if (currentProduct.querySelector('.msg-response .msg-error').classList.contains('-visible')) {\n currentProduct.querySelector('.msg-response .msg-error').innerHTML = '';\n currentProduct.querySelector('.msg-response .msg-error').classList.remove('-visible');\n }\n\n // Quantidade da variante\n let variantQuantity = variant.available_quantity;\n if (variantInventory) {\n variantQuantity = variantInventory.quantity;\n }\n\n // Configura a quantidade máxima do input conforme a variante selecionada\n currentProduct.querySelector('[name=\"quantity\"]').setAttribute('data-available-quantity', variantQuantity);\n\n\n // Configura produto disponível/indisponível\n if (variant.available && !variantInventory) {\n ProductPurchase.setAvailable(currentProduct);\n\n } else if (variant.available && variantInventory && variantInventory.available) {\n ProductPurchase.setAvailable(currentProduct);\n\n } else if (!variant.available && variantInventory && variantInventory.available) {\n ProductPurchase.setAvailable(currentProduct);\n\n } else if (!variant.available && !variantInventory && ProductPurchase.useLocals) {\n \n // Variante indisponível, sem local selecionado, porém com estoque em algum dos locais\n let variantInventory = null;\n variantInventory = variant.inventories.find(inventory => {\n return inventory.available;\n });\n\n if (variantInventory) ProductPurchase.setAvailable(currentProduct);\n\n } else {\n ProductPurchase.setUnavailable(currentProduct, true, variant.sku);\n }\n\n // Atualiza as últimas quantidades disponíveis\n ProductPurchase.setLastUnits(currentProduct, variant, variantInventory);\n\n // Atualiza o preço do componente\n ProductPurchase.updatePrice(currentProduct, variant, variantInventory);\n\n break;\n }\n }\n\n // Quando não encontra variante\n if (!available) ProductPurchase.setUnavailable(currentProduct, false);\n },\n\n // Define produto como disponível pra compra\n setAvailable: function (currentProduct) {\n const addButton = currentProduct.querySelector('[data-action=\"add-cart\"]');\n const currentProductWrapper = currentProduct.closest('[data-product-box]');\n let formNotify = null;\n\n if (currentProductWrapper) {\n formNotify = currentProductWrapper.querySelector('[data-form-notify]');\n }\n\n if (addButton) {\n // addButton.setAttribute('data-available', true);\n addButton.classList.add('-available');\n addButton.classList.remove('-unavailable');\n addButton.innerHTML = addButton.getAttribute('data-text-available');\n }\n\n if (formNotify) formNotify.classList.remove('-active');\n },\n\n // Define produto como indisponível pra compra\n setUnavailable: function (currentProduct, showNotify, sku) {\n const addButton = currentProduct.querySelector('[data-action=\"add-cart\"]');\n const currentProductWrapper = currentProduct.closest('[data-product-box]');\n const showFormNotify = showNotify || false;\n let formNotify = null;\n\n if (currentProductWrapper) {\n formNotify = currentProductWrapper.querySelector('[data-form-notify]');\n }\n\n if (addButton) {\n // addButton.setAttribute('data-available', false);\n addButton.classList.remove('-available');\n addButton.classList.add('-unavailable');\n addButton.innerHTML = addButton.getAttribute('data-text-unavailable');\n }\n\n if (formNotify) {\n if (showFormNotify && sku != undefined && sku != null) {\n formNotify.classList.add('-active');\n formNotify.querySelector('[name=\"sku\"]').value = sku;\n } else {\n formNotify.classList.remove('-active');\n }\n }\n },\n\n // Atualiza o componente de preço do produto\n updatePrice: function (currentProduct, variant, inventory) {\n const productMainContainer = currentProduct.closest('[data-product-box]');\n if (productMainContainer == null) return;\n\n const priceEl = productMainContainer.querySelector('[data-init-price]');\n if (priceEl == null) return;\n\n const groupShop = productMainContainer.getAttribute('data-prod-group-shop');\n\n // Utiliza o preço da variante ou do local selecionado, caso exista\n const variantPrice = inventory ? inventory.price : variant.price;\n const variantSalePrice = inventory ? inventory.sale_price : variant.sale_price;\n\n priceEl.setAttribute('data-sku', variant.sku);\n priceEl.setAttribute('data-price', variantPrice);\n priceEl.dispatchEvent(new Event('change'));\n\n const discount = priceEl.dataset.discountPercent;\n\n // Coloca a porcentagem de desconto no produto\n if (discount != '0') {\n priceEl.style.setProperty('--discount', `'-${discount}%'`);\n }\n\n // atualiza preço final do compre junto se existir\n if (groupShop != null) {\n\n const isAvailable =\n (variant.available && !inventory) ||\n (variant.available && inventory && inventory.available) ||\n (!variant.available && inventory && inventory.available);\n\n productMainContainer.setAttribute('data-price', variantPrice);\n productMainContainer.setAttribute('data-sale-price', variantSalePrice);\n productMainContainer.setAttribute('data-available', isAvailable);\n productMainContainer.dispatchEvent(new Event('vnda:group-shop-price-update'));\n }\n },\n\n // Marca o primeiro atributo como disponível/indisponível, e seleciona os atributos\n // da primeira variante disponível\n markFirstVariant: function (currentProduct) {\n const productId = currentProduct.getAttribute('data-product-id');\n const variants = [...ProductPurchase.productVariants[`${productId}`]];\n\n if (variants.length === 1) {\n\n // Venda por Locais\n let variantInventory = null;\n // Busca informações da variante de acordo com o local selecionado\n if (window.currentLocal) {\n variantInventory = variants[0].inventories.find(inventory => {\n return inventory.place && inventory.place.id && inventory.place.id === window.currentLocal.id;\n });\n\n } else if (!variants[0].available && ProductPurchase.useLocals) {\n // Verifica se o estoque da variante está indisponível\n // Busca disponibilidade em algum dos locais - Se encontrar, habilita o produto\n variantInventory = variants[0].inventories.find(inventory => {\n return inventory.available;\n });\n }\n\n // Possui somente uma variante e não possui atributos,\n // define como disponível/indisponível com base na variante em si\n if (currentProduct.querySelectorAll('.prod-option').length === 0) {\n\n // Quantidade da variante\n let variantQuantity = variants[0].available_quantity;\n if (variantInventory) {\n variantQuantity = variantInventory.quantity;\n }\n\n // Configura a quantidade máxima do input conforme a variante selecionada\n currentProduct\n .querySelector('[name=\"quantity\"]')\n .setAttribute('data-available-quantity', variantQuantity);\n\n // Atualiza o preço do componente\n ProductPurchase.updatePrice(currentProduct, variants[0], variantInventory);\n\n // Atualiza as últimas quantidades disponíveis\n ProductPurchase.setLastUnits(currentProduct, variants[0], variantInventory);\n\n return (\n (variants[0].available && !variantInventory) ||\n (variants[0].available && variantInventory && variantInventory.available) ||\n (!variants[0].available && variantInventory && variantInventory.available)\n ) ? ProductPurchase.setAvailable(currentProduct)\n : ProductPurchase.setUnavailable(currentProduct, true, variants[0].sku);\n\n } else {\n // Possui somente uma variante e possui atributos,\n\n // Atualiza o preço do componente\n ProductPurchase.updatePrice(currentProduct, variants[0], variantInventory);\n\n // Atualiza as últimas quantidades disponíveis\n ProductPurchase.setLastUnits(currentProduct, variants[0], variantInventory);\n }\n\n } else if (variants.length === 0) {\n // Produto não possui variantes, define como indisponível\n return ProductPurchase.setUnavailable(currentProduct);\n }\n\n if (variants.length > 0) {\n const allAttr1 = [...currentProduct.querySelectorAll('[data-attribute=\"1\"] [data-attribute-value]')];\n const allAttr2 = [...currentProduct.querySelectorAll('[data-attribute=\"2\"] [data-attribute-value]')];\n const allAttr3 = [...currentProduct.querySelectorAll('[data-attribute=\"3\"] [data-attribute-value]')];\n\n // Prepara para caso o atributo 1 não esteja em uso, scout por outros\n let attrToCheck = { index: false, options: [] };\n\n if (allAttr3.length > 0) attrToCheck = { index: 'property3', options: allAttr3 };\n if (allAttr2.length > 0) attrToCheck = { index: 'property2', options: allAttr2 };\n if (allAttr1.length > 0) attrToCheck = { index: 'property1', options: allAttr1 };\n\n // Baseado na ordem dos atributos, busca por variantes válidas\n if (attrToCheck.options.length > 0) {\n for (let index = 0; index < attrToCheck.options.length; index++) {\n const attribute = attrToCheck.options[index];\n const value = attribute.getAttribute('data-attribute-value');\n const availableVariants = ProductPurchase.productVariants[`${productId}`].filter((variant) => {\n\n // Venda por Locais\n // Busca informações da variante de acordo com o local selecionado\n let variantInventory = null;\n if (window.currentLocal) {\n variantInventory = variant.inventories.find(inventory => {\n return inventory.place && inventory.place.id && inventory.place.id === window.currentLocal.id;\n });\n } else if (ProductPurchase.useLocals) {\n // Variante com estoque indisponível, sem local selecionado, porém com estoque em algum dos locais\n variantInventory = variant.inventories.find(inventory => {\n return inventory.available;\n });\n }\n\n return variant.properties[attrToCheck.index] &&\n variant.properties[attrToCheck.index].value &&\n variant.properties[attrToCheck.index].value == value &&\n (\n (variant.available && !variantInventory) || // variante disponível sem local\n (variant.available && variantInventory && variantInventory.available) || // variante disponível com local disponível\n (!variant.available && variantInventory && variantInventory.available) // variante indisponível mas com local disponível\n );\n\n });\n\n if (availableVariants.length > 0) {\n attribute.classList.add('-available');\n } else {\n // O produto não tem variantes disponíveis\n attribute.classList.add('-unavailable');\n }\n }\n\n // Marca os atributos da primeira variante disponível,\n //com base na ordem que os atributos se apresentam na tela\n let hasFirstAvailable = false;\n\n for (const attribute of attrToCheck.options) {\n if (attribute.classList.contains('-available')) {\n attribute.click();\n hasFirstAvailable = true;\n\n if (attrToCheck.index == 'property1') {\n for (const attr2 of allAttr2) {\n if (attr2.classList.contains('-available')) {\n attr2.click();\n break;\n }\n }\n\n for (const attr3 of allAttr3) {\n if (attr3.classList.contains('-available')) {\n attr3.click();\n break;\n }\n }\n }\n\n if (attrToCheck.index == 'property2') {\n for (const attr3 of allAttr3) {\n if (attr3.classList.contains('-available')) {\n attr3.click();\n break;\n }\n }\n }\n\n break;\n }\n }\n\n // Quando não há nenhuma first variant com estoque, marca a primeira\n //opção indisponível, para exibir como indisponível\n if (!hasFirstAvailable) {\n attrToCheck.options[0].click();\n if (attrToCheck.index == 'property1') {\n if (allAttr2.length > 0) allAttr2[0].click();\n if (allAttr3.length > 0) allAttr3[0].click();\n }\n\n if (attrToCheck.index == 'property2') {\n if (allAttr3.length > 0) allAttr3[0].click();\n }\n }\n }\n }\n },\n\n // Configura a mesagem de ultimas unidades disponíveis\n setLastUnits: function (currentProduct, variant, inventory) {\n const lastUnitsWrapper = currentProduct.querySelector('.last-units');\n const availableQuantity = inventory ? inventory.available_quantity : variant.available_quantity;\n\n if (availableQuantity <= 5) {\n if (!availableQuantity) {\n lastUnitsWrapper.innerHTML = '';\n lastUnitsWrapper.classList.remove('-visible');\n } else if (availableQuantity > 1) {\n lastUnitsWrapper.innerHTML = `Últimas ${availableQuantity} unidades disponíveis`;\n lastUnitsWrapper.classList.add('-visible');\n } else {\n lastUnitsWrapper.innerHTML = 'Última unidade disponível';\n lastUnitsWrapper.classList.add('-visible');\n }\n } else {\n lastUnitsWrapper.innerHTML = '';\n lastUnitsWrapper.classList.remove('-visible');\n }\n },\n\n // Configura o seletor de quantidade e suas mensagens\n setQuantitySelector: function (currentProduct) {\n const error = currentProduct.querySelector('.msg-response .msg-error');\n const buttonPlus = currentProduct.querySelector('[data-qtd-plus]');\n const buttonMinus = currentProduct.querySelector('[data-qtd-minus]');\n const input = currentProduct.querySelector('[name=\"quantity\"]');\n\n if (buttonPlus != null && buttonMinus != null) {\n buttonPlus.addEventListener('click', () => {\n const current = Number(input.value) + 1;\n const availableQuantity = Number(input.dataset.availableQuantity);\n\n if (!availableQuantity) {\n error.innerHTML = 'Produto em falta no estoque';\n error.classList.add('-visible');\n } else if (current > availableQuantity) {\n // Se o produto atingiu a quantidade máxima em estoque mostra uma mensagem\n error.innerHTML = 'Quantidade máxima em estoque.';\n error.classList.add('-visible');\n } else {\n input.value = current;\n input.setAttribute('value', current);\n }\n });\n\n buttonMinus.addEventListener('click', () => {\n const current = Number(input.value) - 1;\n\n if (current > 0) {\n input.value = current;\n input.setAttribute('value', current);\n\n // Se está mostrando a mensagem de quantidade máxima, remove ela\n if (error.classList.contains('-visible')) {\n error.classList.remove('-visible');\n error.innerHTML = '';\n }\n }\n });\n }\n },\n\n // Trata dos seletores em dropdown para atributos e personalizações\n handleDropdowns: function(currentProduct) {\n const dropdowns = currentProduct.querySelectorAll('.prod-option.-dropdown')\n if (!dropdowns) return\n\n // Configura abre/fecha do dropdown conforme clique nas opções\n return dropdowns.forEach(dropdown => {\n const dropAttrs = dropdown.querySelectorAll('[data-attribute-value], [data-customization] + label');\n dropdown.querySelector('.inner').classList.remove('-choosing')\n\n dropAttrs.forEach(attr => {\n attr.addEventListener('click', () => {\n attr.closest('.inner').classList.toggle('-choosing')\n\n // Garante que os outros dropdowns fechem quando clica em um novo\n dropdowns.forEach(checkDrop => {\n if (checkDrop === dropdown) return\n checkDrop.querySelector('.inner').classList.remove('-choosing')\n })\n });\n });\n })\n },\n\n // Envia o formulário de compra\n submitForm: function (currentProduct) {\n const { useLocals } = ProductPurchase;\n\n currentProduct.addEventListener('submit', (event) => {\n event.preventDefault();\n\n const groupShop = currentProduct.closest('[data-product-box]').getAttribute('data-prod-group-shop');\n\n // Venda por Locais\n if (useLocals && (window.currentLocal == null || !sessionStorage.getItem('local-cep'))) {\n // Caso não tenha local selecionado, abre o popup de inserção do CEP\n const localPopupOpener = document.querySelector('[data-show-locals-popup]');\n localPopupOpener && localPopupOpener.click();\n\n } else if (groupShop == null) {\n // Adição normal de produto - Compre Junto é controlado em outro componente\n const form = currentProduct;\n const parent = form.closest('[data-product-box]');\n\n const respValidated = Store.validateFormProduct(form);\n const boxResponse = parent.querySelector('.msg-response');\n\n if (respValidated.validated) {\n Store.addProduct(form, parent);\n } else {\n //console.info('não foi');\n Store.setRespValidateProduct(respValidated, form, boxResponse);\n }\n }\n });\n },\n\n //Exibe o nome da variante ao lado do nome do atributo\n showAttributeName: function (purchaseForm, attr) {\n const target = purchaseForm.querySelector(`[data-attr-name=\"${attr.dataset.attributeIndex}\"]`);\n let attributeName = attr.dataset.text;\n if (target && attributeName) {\n if (attributeName.includes('|')) {\n attributeName = attributeName.split('|')[0];\n }\n target.innerHTML = attributeName;\n target.classList.add('-visible');\n }\n },\n\n // Funções de controle do formulário de compra\n handlePurchase: function (product) {\n const { checkCombinations, checkSelection, markFirstVariant, submitForm, showAttributeName, setQuantitySelector, handleDropdowns } = ProductPurchase;\n\n const purchaseForm = product.querySelector(\"[data-product-purchase]\");\n\n if (purchaseForm && purchaseForm.getAttribute('data-processed') == 'false') {\n const attrOptions = purchaseForm.querySelectorAll('[data-attribute-value]');\n const attrInputs = purchaseForm.querySelectorAll('[data-prod-option] input');\n\n // Remarca demais atributos ao clicar em uma opção\n attrOptions.forEach((attr) => {\n attr.addEventListener('click', () => {\n checkCombinations(purchaseForm, attr);\n showAttributeName(purchaseForm, attr);\n });\n });\n\n // Verifica variante para combinação de atributos selecionados\n attrInputs.forEach((input) => {\n input.addEventListener('change', () => {\n checkSelection(purchaseForm);\n });\n });\n\n setQuantitySelector(purchaseForm);\n markFirstVariant(purchaseForm);\n submitForm(purchaseForm);\n handleDropdowns(purchaseForm)\n purchaseForm.setAttribute('data-processed', true);\n\n }\n },\n\n // Retorna o HTML necessário para a compra rápida - Popup ou Formulário\n fetchQuickview: async function (id, type) {\n if (!id || !window.ProductPurchase) return\n\n try {\n const baseUrl = window.location.origin;\n const url = new URL(`/produto/quickview/${id}`, baseUrl);\n\n if (type == 'popup') url.searchParams.set('popup_quickview', true);\n if (type == 'group-shop') url.searchParams.set('group_shop', true);\n\n const response = await fetch(url);\n const data = await response.text();\n\n const parser = new DOMParser();\n const doc = parser.parseFromString(data, 'text/html');\n const script = doc.querySelector('[data-product-variants]');\n\n // Popula o array de variantes\n const variants = JSON.parse(script.innerText);\n window.ProductPurchase.productVariants[`${id}`] = variants;\n\n // Retorna o formulário de compra ou o popup de compra rápida\n const purchaseEl = doc.querySelector('body').firstElementChild;\n return purchaseEl;\n\n } catch (error) { console.error(error) }\n },\n\n // Popup de compra rápida\n popupQuickview: {\n // Instancia o popup no DOM\n createPopup: async function (id, type) {\n const { fetchQuickview, handlePurchase, popupQuickview } = ProductPurchase;\n\n try {\n const purchaseEl = await fetchQuickview(id, type);\n\n purchaseEl.setAttribute(\"data-popup-quickview\", id);\n purchaseEl.classList.add('-active');\n document.body.appendChild(purchaseEl);\n\n handlePurchase(purchaseEl);\n\n window.Vnda.Component.Price.update();\n window.lazyLoad && window.lazyLoad.update();\n\n popupQuickview.close(purchaseEl);\n\n } catch (error) {\n console.error('Erro ao processar o popup de compra rápida do produto:', error);\n }\n\n },\n\n // Controla os botões de fechar o popup\n close: function (popup) {\n const closeButtons = popup.querySelectorAll('[data-close-popup-quickview]');\n\n closeButtons.forEach((button) => {\n if (button.getAttribute('data-processed') == 'false') {\n button.addEventListener('click', () => {\n popup.classList.remove('-active');\n });\n button.setAttribute('data-processed', true);\n }\n });\n },\n },\n\n // Popup Quickview - abertura ou criação\n handleQuickviewPopup: function (product, id, type) {\n const { popupQuickview } = ProductPurchase;\n const openPopupPurchaseButton = product.querySelector('[data-open-popup-quickview]');\n\n openPopupPurchaseButton && openPopupPurchaseButton.addEventListener('click', () => {\n if (!openPopupPurchaseButton.classList.contains(\"-searching\")) {\n openPopupPurchaseButton.classList.add('-searching')\n\n const popup = document.querySelector(`[data-popup-quickview='${id}']`);\n\n popup\n ? popup.classList.add(\"-active\")\n : popupQuickview.createPopup(id, type);\n\n setTimeout(() => openPopupPurchaseButton.classList.remove('-searching'), 500)\n }\n\n });\n },\n\n // Formulário Quickview - fetch e inserção do elemento\n handleQuickviewForm: async function (product, id, type) {\n const { fetchQuickview, handlePurchase } = ProductPurchase;\n\n const alreadyProcessed = product.getAttribute(\"data-quickview-processed\");\n if (!alreadyProcessed) {\n\n try {\n const purchaseEl = await fetchQuickview(id, type);\n\n if (!purchaseEl) {\n console.error(\"Erro ao carregar o formulário: purchaseEl vazio\")\n return;\n }\n\n product.appendChild(purchaseEl);\n handlePurchase(product);\n\n product.setAttribute(\"data-quickview-processed\", true);\n\n } catch (error) {\n console.error('Erro ao processar o formulário do produto:', error);\n }\n }\n },\n\n // Define o modelo de compra rápida - Popup / Formulário\n setQuickviewType: async function (product, id) {\n const { handleQuickviewPopup, handleQuickviewForm } = ProductPurchase;\n\n if (!product.hasAttribute(\"data-quickview-type\")) return;\n\n const quickviewType = product.getAttribute(\"data-quickview-type\");\n\n if (quickviewType == \"popup\") {\n handleQuickviewPopup(product, id, quickviewType)\n\n } else if (quickviewType == 'hover' && window.mobile == false) {\n let hoverTimeout;\n\n // Executa o fetch após 250ms no hover\n product.addEventListener(\"mouseenter\", () => {\n hoverTimeout = setTimeout(() => {\n handleQuickviewForm(product, id, quickviewType)\n }, 250);\n })\n\n // Cancela o temporizador ao sair do hover antes do tempo esperado pelo setTimeout\n product.addEventListener(\"mouseleave\", () => {\n clearTimeout(hoverTimeout);\n });\n\n } else if ((quickviewType == 'hover' && window.mobile) || 'group-shop') {\n handleQuickviewForm(product, id, quickviewType)\n }\n\n },\n\n // Observa os produtos em tela\n observeProducts: function (product) {\n const { setQuickviewType } = ProductPurchase;\n\n const observer = new IntersectionObserver(async (entries, observer) => {\n if (entries[0].isIntersecting) {\n const product = entries[0].target;\n const id = product.getAttribute(\"data-product-box\");\n product.setAttribute(\"data-quickview-ready\", true);\n\n setQuickviewType(product, id);\n observer.disconnect();\n }\n });\n\n observer.observe(product);\n },\n\n init: function (update) {\n const triggerUpdate = update || false;\n\n if (triggerUpdate) {\n this.products = document.querySelectorAll('[data-product-box]');\n this.productVariants = productVariants;\n }\n\n window.ProductPurchase = ProductPurchase;\n\n const { products, handlePurchase, observeProducts } = this;\n\n if (products.length > 0)\n products.forEach((product) => {\n\n if (product.querySelector(\"[data-product-purchase]\")) {\n handlePurchase(product);\n } else if (!product.getAttribute('data-quickview-ready')) {\n observeProducts(product);\n }\n\n });\n },\n};\n\nProductPurchase.init()\n"],"names":["addAsset","source","onloadCallback","console","error","includes","scriptTag","document","createElement","setAttribute","onload","body","appendChild","linkTag","head","CartDrawer","root","querySelector","buttons","querySelectorAll","countWrapper","settings","window","cartDrawerSettings","setCartDrawer","freeShipping","freeShippingValue","componentCartDrawer","Vnda","Component","anchor","display","startOpen","titleCart","titleSuggested","suggestedProductsTag","widthItemSuggested","disableShippingCalculation","render","instance","dispatchEvent","Event","loadComponent","script","styles","handleCartButton","button","classList","contains","add","show","remove","callback","mmenu","close","addEventListener","open","getCartItens","async","response","fetch","json","updateCartCount","_itemsCount","items","this","innerHTML","init","_this","length","forEach","Store","openCartDrawer","openCartDrawerMobile","addProduct","form","parent","customizations","quantity","Number","value","custom","type","getAttribute","addItemsCustom","addItem","btnComprar","boxResponse","hasCustoms","customs","data","sku","disabled","checked","index","push","json_data","JSON","stringify","info","method","headers","html","text","ok","log","addItemResult","removeAttribute","formData","string","encode","s","encodeURIComponent","replace","pair","entries","urlencodeFormData","FormData","deleteItem","itemId","item","removeItemResult","URLSearchParams","_method","item_id","innerWidth","validateFormProduct","validated","errors","dataset","available","setRespValidateProduct","resp","htmlErrors","i","typeResult","result","setTimeout","textAvailable","location","href","urlCart","popupQuickview","popup","click","scrollTo","top","offsetTop","behavior","ProductPurchase","productVariants","products","useLocals","checkCombinations","currentProduct","selectedAttribute","productId","selectedAttr","variants","attributes","attr1","attr2","attr3","selectedAttributes","markAttributes","attr","property","attrsToCheck","validVariants","filter","variant","properties","validAttr1","validAttr2","validAttr3","property1","property2","property3","valueToCheck","variantInventory","currentLocal","inventories","find","inventory","place","id","input","firstAvailable","checkSelection","selectedAttrs","attr1Value","attr2Value","attr3Value","event","CustomEvent","detail","productContainer","closest","variantQuantity","available_quantity","setAvailable","setUnavailable","setLastUnits","updatePrice","addButton","currentProductWrapper","formNotify","showNotify","showFormNotify","undefined","productMainContainer","priceEl","groupShop","variantPrice","price","variantSalePrice","sale_price","discount","discountPercent","style","setProperty","isAvailable","markFirstVariant","allAttr1","allAttr2","allAttr3","attrToCheck","options","attribute","hasFirstAvailable","lastUnitsWrapper","availableQuantity","setQuantitySelector","buttonPlus","buttonMinus","current","handleDropdowns","dropdowns","dropdown","dropAttrs","toggle","checkDrop","submitForm","preventDefault","sessionStorage","getItem","respValidated","localPopupOpener","showAttributeName","purchaseForm","target","attributeIndex","attributeName","split","handlePurchase","product","attrOptions","attrInputs","fetchQuickview","baseUrl","origin","url","URL","searchParams","set","doc","DOMParser","parseFromString","parse","innerText","firstElementChild","createPopup","purchaseEl","Price","update","lazyLoad","handleQuickviewPopup","openPopupPurchaseButton","handleQuickviewForm","setQuickviewType","hasAttribute","quickviewType","mobile","hoverTimeout","clearTimeout","observeProducts","observer","IntersectionObserver","isIntersecting","disconnect","observe"],"sourceRoot":""}