link whatsapp
Contador de visitas

Relaxe ao Navegar!

Relaxe ao Navegar!

Clique para Interagir

Clique para Interagir

Florais

Florais

Nossa Localização

Seu carrinho

Subtotal:

Desconto: - Total: Enviar pedido Chamar garçom Fechar comanda
foto do usuário do google
Florais

", "price": null, "link": null, "description": null, "image": null, "created_at": "2022-07-14 00:12:43", "updated_at": "2022-12-06 22:39:35", "text_color": "#fff", "background_color": "rgba(255,255,255,0)", "button_text": "Comprar", "image_size": "large", "image_position": "center", "button_color": "#fff", "position": 1, "card_wrapper_id": null, "font_family": "[object Object]", "title_font_size": 40, "price_font_size": 1, "description_font_size": 26, "title_position": "left", "description_position": "center", "show_link_button": true, "where_open_link": "_self", "image_button": null, "category_name": null, "button_text_color": "#ffffff", "disable_cart": false, "product_complements_qty": null, "disable_product": false, "title_in_editor": true, "description_in_editor": false, "image_height_fixed": true, "price_position": "center", "price_color": "rgba(0,0,0,0)", "product_complements_mandatory": false, "package_weight": null, "package_length": null, "package_width": null, "package_height": null, "package_diameter": null, "product_complements_min_qty": null, "complement_label": null, "button_font_size": 20, "supply_control": null, "supply": null, "code": null, "sanitized_title": "florais", "show_images": true, "product_category_id": null, "image_url": null, "image_button_url": null, "complementSteps": [], "productImages": [ { "id": 551009, "card_product_id": 1053512, "position": 1, "path": "https://files.nextgocard.com.br/products/XWlAyNgrWOYyRaP5-1.png", "image": "https://files.nextgocard.com.br/products/XWlAyNgrWOYyRaP5-1.png" }, { "id": 551011, "card_product_id": 1053512, "position": 2, "path": "https://files.nextgocard.com.br/products/CODg7U9JN4b3B2zA-2.png", "image": "https://files.nextgocard.com.br/products/CODg7U9JN4b3B2zA-2.png" }, { "id": 551012, "card_product_id": 1053512, "position": 3, "path": "https://files.nextgocard.com.br/products/yB18WvQOZnCk6rZY-3.png", "image": "https://files.nextgocard.com.br/products/yB18WvQOZnCk6rZY-3.png" } ], "categories": [], "priceConverted": "R$ 0,00" } ] const cartTranslation = { "cartModalTitle": "Seu carrinho", "cartModalFinishButtonText": "Enviar pedido", "cartModalFinishLoadingButtonText": "Enviando pedido", "cartFinishModalTitle": "Informações do carrinho", "cardNameInputLabel": "Nome:", "cardPhoneInputLabel": "Telefone: ", "cardPaymentTypeInputLabel": "Forma de Pagamento:", "cardExtraInfoInputLabel": "Observações:", "cardDeliveryTypeInputLabel": "Forma de Entrega:", "cardDeliveryTotalPriceLabel": "Valor da Entrega", "cardDeliveryPriceMessageLabel": "Entrega", "cardDeliveryAddressOptionInputLabel": "Endereço", "cardDeliveryPlaceOptionInputLabel": "No local", "cardDeliveryPlaceInformationInputLabel": "Informação da mesa", "cardZipCodeInputLabel": "CEP:", "cardSearchZipCodeButtonText": "Pesquisar", "cardCouponCodeInputLabel": "Código de Desconto:", "cardSearchCouponCodeButtonText": "Aplicar", "cardSuccessCouponLabel": "Desconto de $$ aplicado a compra.", "cardDateErrorCouponLabel": "Esse cupom expirou em $$", "cardAmountErrorCouponLabel": "Esse cupom só é válido pra compras a partir de $$ em produtos cadastrados", "cardProductsErrorCouponLabel": "Esse cupom não é válido para o(s) produto(s) no seu carrinho", "cardInvalidErrorCouponLabel": "Cupom inválido.", "cardStreetInputLabel": "Logradouro:", "cardStreetNumberInputLabel": "Número:", "cardStreetComplementInputLabel": "Complemento:", "cardDistrictInputLabel": "Bairro:", "cardStateInputLabel": "Estado:", "cardCityInputLabel": "Cidade:", "cardCalculateDeliveryPriceButtonText": "Calcular Entrega", "cardMaxComplements": "Atingiu a quantidade máxima de complementos.", "cardFinishButtonText": "Enviar pedido", "extraInfoDefault": "Nenhuma", "noInformation": "Não informado", "complementTitle": "Complementos", "complementContinueAction": "Continuar compra", "openingHoursTitle": "Horário de funcionamento", "onlinepayment": "Pagamento on-line", "localPaymentTypeLabel": "Forma de Pagamento na Entrega", "moneyLocalPaymentType": "Dinheiro", "creditCardLocalPaymentType": "Cartão de crédito", "debitCardLocalPaymentType": "Cartão de débito", "moneyChangeLabel": "Troco para:", "withoutMoneyChangeLabel": "Não preciso de troco", "wppMessageCreditCardLocalPayment": "Pagamento na entrega via cartão de crédito", "wppMessageDebitCardLocalPayment": "Pagamento na entrega via cartão de débito", "wppMessageMoneyLocalPaymentWithoutChange": "Pagamento na entrega via dinheiro. Não preciso de troco", "wppMessageMoneyLocalPaymentWithChange": "Pagamento na entrega via dinheiro. Troco para: ", "hoursConnective": "às ", "cardName": "Nome:", "cardComplement": "Complemento:", "cardAmount": "Quantidade:", "cardPrice": "Valor:", "cardDesk": "Mesa: ", "cardOrder": "Pedido", "checkoutMethodsModalTitle": "Escolha o método de compra", "checkoutMethodsDeliveryLabel": "Delivery", "checkoutMethodsGetLocallyLabel": "Retirar no local", "checkoutMethodsBillLabel": "Comanda", "checkoutMethodsOnlineSellLabel": "Venda On-line", "checkoutMethodsLocallyConsumptionLabel": "Consumo no local", "useBillIdentification": "Usar comanda já existente", "billIdentificationLabel": "ID da comanda", "closeBillButtonLabel": "Fechar comanda", "callWaiterButton": "Chamar garçom", "callingWaiterButton": "Chamando garçom", "calledWaiterButton": "Garçom chamado", "alreadyHasBillOpenText": "Encontramos uma comanda em aberta", "billCartModalTitle": "Sua comanda", "billIdentificationNotFound": "Comanda não encontrada", "billLinkMessage": "Resumo da comanda", "billNextgoPayMessage": "Pagar online", "loadingText": "Carregando...", "productCode": "Código: ", "shareLocationLink": "Localização: ", "invalidPhoneError": "Telefone inválido", "categorySectionTitle": "Categorias", "categoryGroupSectionBack": "voltar", "categorySectionBack": "voltar", "freightCalculationError": "Não foi possível calcular o frete.", "freeFreight": "Frete grátis", "language": "pt-br" } const cardRender = { "id": 14820, "language": "pt-br", "currency": "R$", "cart": { "id": 6678, "card_render_id": 14820, "nextgo_orders_id": null, "cnpj": null, "created_at": "2022-04-21 13:57:58", "updated_at": "2022-04-21 13:57:58", "cart_title": null, "label_name": null, "label_purchase_method": null, "label_observation": null, "label_shipping_method": null, "label_table_info": null, "label_phone": null, "label_send_button": null, "active_name": false, "active_observation": false, "active_address": false, "nextgo_orders_active": null, "active_delivery_type": true, "nextgo_orders_email": null, "label_address_freight_option": null, "label_locally_freight_option": null, "online_payment_label": null, "pop_up_subtotal_label": null, "pop_up_discount_label": null, "pop_up_total_label": null, "pop_up_finish_button_label": null, "pop_up_title_label": null, "complement_chosen_label": null, "wpp_order_label": null, "wpp_product_name_label": null, "wpp_product_quantity_label": null, "wpp_product_price_label": null, "wpp_complement_quantity_label": null, "wpp_complement_price_label": null, "wpp_delivery_title_label": null, "wpp_orders_link_label": null, "sending_order_label": null, "with_get_locally": true, "with_delivery": false, "with_bill": false, "checkout_method_modal_bg_color": "#BDC3C7", "checkout_method_text_color": "#000000", "checkout_method_option_bg_color": "#FFFFFF", "checkout_method_option_border_color": "#000000", "bill_finish_thanks_message": "Obrigado por consumir, seu pedido está sendo finalizado", "with_online_sell": false, "with_locally_consumption": false, "hide_status_url": false, "use_nextgo_orders_v2": false, "use_nextgo_pay": false, "use_nextgo_pay_in_bill": false, "nextgo_orders_nextgo_id": null, "metadata": {}, "hide_observations": false, "hide_product_out_of_stock": false, "hide_complement_out_of_stock": false }, "event": null } const useNextGoOrdersV2 = cardRender.cart && cardRender.cart.use_nextgo_orders_v2; const productsWrappers = [] const productsInWrappers = []; productsWrappers.forEach(el => productsInWrappers.push(...el.products.flat())) const products = [...productsOfCard,...productsInWrappers] const coupons = [] const freights = "" if(freights.type == "fixed" && freights.active == true) { let text = ''; if (freights.freight_value_label || cartTranslation.cardDeliveryTotalPriceLabel) { text = (freights.freight_value_label || cartTranslation.cardDeliveryTotalPriceLabel); } const freightsPriceEl = document.getElementById('freights-price') if (freightsPriceEl) freightsPriceEl.innerText = text + ': ' + convertToCurrency(freights.price); } const wppCartPhone = null let wppCart = []; let totalPrice = 0; let discount = 0; let ticketId = ''; let lastTotalPrice = 0; let lastDiscount = 0; let oldAmountComplement = 0; let oldAmountComplementArray = []; let currentPlusCode function generateId() { return parseInt(new Date().getTime() / 100, 10); } function minimizeWppCart() { document.getElementById('wpp-cart').classList.remove('show'); document.getElementById('wpp-cart-minimized').classList.add('show'); } function increaseWppCart() { document.getElementById('wpp-cart').classList.add('show'); document.getElementById('wpp-cart-minimized').classList.remove('show'); } function hasSupply({ product }) { if (!product) return true; if (!product.supply_control) return true; return product.supply > 0; } function decreaseSupply({ product }) { if (!product.supply_control) return; const productIndex = products.findIndex(p => p.id === product.id); const foundProduct = products[productIndex]; products[productIndex] = { ...foundProduct, supply: foundProduct.supply - 1, } } function increaseSupply({ cartProductId }) { const cartProduct = wppCart.find(wppCartItem => wppCartItem.id === cartProductId) const productIndex = products.findIndex(product => product.id === cartProduct.productId); if (cartProduct.choosedProductComplements) { cartProduct.choosedProductComplements.forEach((complement) => { const hasComplementSupplyStore = complementsSupplyStore.get(complement.id); if (hasComplementSupplyStore) complementsSupplyStore.set(complement.id, 0) }) } const foundProduct = products[productIndex]; if (!foundProduct || !foundProduct.supply_control) return; products[productIndex] = { ...foundProduct, supply: foundProduct.supply + 1, } } function productComplementHasSupply({ productComplement }) { if (!productComplement) return true; if (!productComplement.supply_control) return true; return productComplement.supply > 0; } function decreaseProductComplementSupply({ productId, productComplementId }) { const productIndex = products.findIndex(product => product.id === productId); const foundProduct = products[productIndex]; const updatedProductComplements = foundProduct.productComplements.map(productComplement => { if (productComplement.id !== productComplementId) return productComplement; if (!productComplement.supply_control) return productComplement; return { ...productComplement, supply: productComplement.supply - 1, } }) products[productIndex] = { ...foundProduct, productComplements: updatedProductComplements } } function increaseProductComplementSupply({ productId, productComplementId }) { const productIndex = products.findIndex(product => product.id === productId); const foundProduct = products[productIndex]; const updatedProductComplements = foundProduct.productComplements.map(productComplement => { if (productComplement.id !== productComplementId) return productComplement; if (!productComplement.supply_control) return productComplement; return { ...productComplement, supply: productComplement.supply + 1, } }) products[productIndex] = { ...foundProduct, productComplements: updatedProductComplements } } function addToWppCart(productId, { observations } = {}) { if (!openingHours.isOpen || openingHours.force_close) { showOpeningHours({ evtFromProduct: true }); return; } const cartItemId = generateId(); const product = products.find(product => product.id === productId); const productHasSupply = hasSupply({ product }); if (!productHasSupply) { showSnackbar({ message: 'Produto sem estoque' }) return; } totalPrice += product.price ? parseFloat(product.price.replace(/,/g, '.')) : 0 const productIndexInCart = product.complementSteps.length > 0 ? wppCart.findIndex(product => product.id === productId) : wppCart.findIndex(product => product.productId === productId); if (productIndexInCart !== -1 && (!cartConfig.metadata || !cartConfig.metadata.ignoreProductGroup)) { const wppCartContent = { ...wppCart[productIndexInCart] } wppCart[productIndexInCart] = { ...wppCartContent, price: parseFloat(product.price), amount: wppCartContent.amount + 1, observations, } } else { const newCartItem = { ...product, productId: product.id, id: cartItemId, amount: 1, observations, } wppCart.push({ ...newCartItem, price: product.price > 0 ? product.price : 0, }) } decreaseSupply({ product }); if (wppCart.length === 1) { document.getElementById('wpp-cart').classList.add('show') } renderWppCart(); if (checkoutMethod === 'bill') { document.getElementById('bill-add-btn').classList.remove('d-none'); } return cartItemId } function removeToWppCart(productId) { const productIndexInCart = wppCart.findIndex(product => product.id === productId); wppCart[productIndexInCart].price = typeof wppCart[productIndexInCart].price === 'string' ? parseFloat(wppCart[productIndexInCart].price.replace(/,/g, '.')) : parseFloat(wppCart[productIndexInCart].price) totalPrice -= wppCart[productIndexInCart].price ? wppCart[productIndexInCart].price : 0 discount = 0; if (wppCart[productIndexInCart].choosedProductComplements) { wppCart[productIndexInCart].choosedProductComplements.forEach(productComplement => { if (!productComplement.price) totalPrice -= 0; else { if (typeof productComplement.price === 'number') { totalPrice -= productComplement.price * productComplement.amount; } else { totalPrice -= parseFloat(productComplement.price.replace(/,/g, '.')) * productComplement.amount; } } }) } increaseSupply({ cartProductId: productId }); if (wppCart[productIndexInCart].amount > 1) { wppCart[productIndexInCart] = { ...wppCart[productIndexInCart], amount: wppCart[productIndexInCart].amount - 1 } } else { wppCart = wppCart.filter(el => el.id !== productId); } if (wppCart.length === 0) { if (checkoutMethod === 'bill') { document.querySelector('.wpp-cart-finish-btn').classList.add('d-none'); document.querySelector('.bill-add-btn').classList.add('d-none'); } else { document.getElementById('wpp-cart').classList.remove('show'); } } renderWppCart(); } function validateInputValue(productComplementId) { const productComplementInputElement = document.getElementById('productComplement' + productComplementId); if (typeof productComplementInputElement.value !== 'number' && productComplementInputElement.value === '' ) { productComplementInputElement.value = 0; } } function isValidateInputValue(productComplementId) { const productComplementInputElement = document.getElementById('productComplement' + productComplementId); if (typeof productComplementInputElement.value !== 'number' && productComplementInputElement.value === '' ) { return false; } return true; } function getTotalComplements() { const complementInputs = document.querySelectorAll(".complement-wrapper input"); let totalComplements = 0; complementInputs.forEach(input => (totalComplements += parseInt(input.value || 0, 10))) return totalComplements; } function checkMinComplements({ product, totalComplements }) { const minComplMessage = document.querySelector("p.minComplementos"); const minComplMessageCount = document.querySelector("p.minComplementos span"); const minComplementsQuantity = product.product_complements_min_qty; const shouldShowMessage = minComplementsQuantity !== null && totalComplements < minComplementsQuantity minComplMessage.style.display = shouldShowMessage ? 'block' : 'none'; minComplMessageCount.innerText = shouldShowMessage ? minComplementsQuantity : '-'; return shouldShowMessage; } function addProductComplementToWppCart(cartItemId, productId, productComplementId, complementAmountInput) { if (!openingHours.isOpen || openingHours.force_close) return; const product = products.find(product => product.id === productId); const productComplementWithSupply = productComplementHasSupply({ productComplement: product.productComplements .find(productComplement => productComplement.id === productComplementId) }); if (!productComplementWithSupply) { showSnackbar({ message: 'Complemento sem estoque' }) return; } if(getWppQuantiy(product, complementAmountInput)) { const productComplement = product.productComplements.find(productComplement => productComplement.id === productComplementId) if (!isValidateInputValue(productComplement.id)) return; if(wppCart.findIndex(product => product.productId === productId && product.id === cartItemId) === -1){ cartItemId = addToWppCart(productId) } const cartItemIndex = wppCart.findIndex(item => item.id === cartItemId); const alreadyHasThisProductComplement = wppCart[cartItemIndex].choosedProductComplements && wppCart[cartItemIndex].choosedProductComplements.map(el => el.id).includes(productComplement.id) if (alreadyHasThisProductComplement) { const updatedChoosedProductComplements = wppCart[cartItemIndex].choosedProductComplements.map(productComplement => { if (productComplement.id === productComplementId) { complementAmountValue = complementAmountInput == true ? document.getElementById("productComplement"+productComplement.id).value : parseInt(productComplement.amount) + 1; return { ...productComplement, amount: complementAmountValue, }; } return productComplement; }) document.getElementById("productComplement"+productComplement.id).value = updatedChoosedProductComplements.find(x => x.id === productComplement.id).amount; wppCart[cartItemIndex] = { ...wppCart[cartItemIndex], choosedProductComplements: updatedChoosedProductComplements, } } else { if(!wppCart[cartItemIndex].choosedProductComplements){ oldAmountComplementArray = []; } const itemCartContent = { ...wppCart[cartItemIndex] } complementAmountValue = complementAmountInput == true ? document.getElementById("productComplement"+productComplement.id).value : 1; document.getElementById("productComplement"+productComplement.id).value = complementAmountValue; wppCart[cartItemIndex] = { ...itemCartContent, choosedProductComplements: itemCartContent.choosedProductComplements ? [...itemCartContent.choosedProductComplements, { ...productComplement, amount: complementAmountValue }] : [{ ...productComplement, amount: complementAmountValue }], } } if(complementAmountValue){ let find = alreadyHasThisProductComplement != null ? oldAmountComplementArray.find(x => x.id === productComplementId) : null; oldAmountComplement = find ? find.amount : 0; nm = productComplement.price ? parseFloat(productComplement.price.replace(/,/g, '.')) * complementAmountValue : 0 if(oldAmountComplement > nm && oldAmountComplement != 0){ totalPrice -= oldAmountComplement; totalPrice += nm; //totalPrice -= oldAmountComplement - nm; newAmount = nm oldAmountComplement = 0; } else { newAmount = nm; totalPrice -= oldAmountComplement; totalPrice += newAmount; oldAmountComplement = 0; } oldAmountComplement+=newAmount; if(!find){ oldAmountComplementArray.push({amount: oldAmountComplement, id: productComplementId}); } else { find.amount = oldAmountComplement; } } else { totalPrice += productComplement.price ? parseFloat(productComplement.price.replace(/,/g, '.')) : 0 } decreaseProductComplementSupply({ productId: product.id, productComplementId }); renderWppCart(); } const totalComplements = getTotalComplements(); checkMinComplements({ product, totalComplements }); } function decProductComplementToWppCart(cartItemId, productId, productComplementId) { const product = products.find(product => product.id === productId); const productComplement = product.productComplements.find(productComplement => productComplement.id === productComplementId) const cartItemIndex = wppCart.findIndex(item => item.id === cartItemId); const complMessage = document.querySelector("p.maxComplementos"); complMessage.style.display = "none"; const alreadyHasThisProductComplement = wppCart[cartItemIndex].choosedProductComplements && wppCart[cartItemIndex].choosedProductComplements.map(el => el.id).includes(productComplement.id) let find = oldAmountComplementArray.find(x => x.id === productComplementId); if (alreadyHasThisProductComplement) { if(document.getElementById("productComplement"+productComplementId).value > 1){ find.amount -= productComplement.price; const updatedChoosedProductComplements = wppCart[cartItemIndex].choosedProductComplements.map(productComplement => { if (productComplement.id === productComplementId) { return { ...productComplement, amount: productComplement.amount - 1, }; } return productComplement; }); document.getElementById("productComplement"+productComplement.id).value = document.getElementById("productComplement"+productComplement.id).value = updatedChoosedProductComplements.find(x => x.id === productComplement.id).amount; wppCart[cartItemIndex] = { ...wppCart[cartItemIndex], choosedProductComplements: updatedChoosedProductComplements, } } else { document.getElementById("productComplement"+productComplement.id).value = 0; find.amount = 0; removeProductComplementToWppCart(cartItemId, productComplementId) } } if(document.getElementById("productComplement"+productComplement.id).value > 0) { totalPrice -= productComplement.price ? parseFloat(productComplement.price.replace(/,/g, '.')) : 0 renderWppCart(); } const totalComplements = getTotalComplements(); checkMinComplements({ product, totalComplements }); } function getWppQuantiy(product, eventByKeyUpManually) { const productProduct = product; let sumComplementsSelected = 0; let maxComplementOfProduct = productProduct.product_complements_qty; let itensCount = document.querySelectorAll(".complement-wrapper input"); let complMessage = document.querySelector("p.maxComplementos"); itensCount.forEach(index => { sumComplementsSelected += parseInt(index.value); }); if (eventByKeyUpManually && sumComplementsSelected === 0) { return false; } if (maxComplementOfProduct !== null && (maxComplementOfProduct <= sumComplementsSelected) && !eventByKeyUpManually ) { complMessage.style.display = "block"; return false; } complMessage.style.display = "none"; return true; } function removeProductComplementToWppCart(cartItemId, productComplementId) { const cartItemIndex = wppCart.findIndex(product => product.id === cartItemId); const productComplementToRemove = wppCart[cartItemIndex] .productComplements .find(productComplement => productComplement.id === productComplementId); wppCart[cartItemIndex] = { ...wppCart[cartItemIndex], choosedProductComplements: wppCart[cartItemIndex].choosedProductComplements.map(el => { if (el.id === productComplementId) { if (el.amount > 1) { return { ...el, amount: el.amount - 1, } } return null; } return el; }).filter(el => el) } if(productComplementToRemove.price != null){ totalPrice -= parseFloat(productComplementToRemove.price.replace(/,/g, '.')) } increaseProductComplementSupply({ productId: wppCart[cartItemIndex].productId, productComplementId, }) renderWppCart(); } async function openProductComplements(productId) { if (!openingHours.isOpen || openingHours.force_close) { showOpeningHours({ evtFromProduct: true }); return; } const product = await products.find(product => product.id === productId); const cartItemId = product.product_complements_mandatory? generateId(): addToWppCart(productId); const complMessage = document.querySelector("p.maxComplementos"); const minComplMessage = document.querySelector("p.minComplementos"); complMessage.style.display = "none"; minComplMessage.style.display = "none"; openComplementsModal({ cartItemId, productComplements: product.productComplements, complementLabel: product.complement_label, }); } function getProductTitleLength(product) { let productAmount = product.price !== 0 || !product.choosedProductComplements || product.choosedProductComplements.length === 0 ? product.amount + 'x ' : '' if (!product.title) return productAmount + 'Produto sem titulo' const title = product.title.replace(/(<([^>]+)>)/ig, ''); if (title.length > 25) { return productAmount + title.substring(0, 25) + '...'; } return productAmount + title; } function createCartItem({ cartItem }) { const titleElement = document.createElement('p'); const titleText = document.createTextNode(getProductTitleLength(cartItem)); titleElement.appendChild(titleText); const xElement = document.createElement('a'); const xText = document.createTextNode('x'); xElement.appendChild(xText); xElement.href = 'javascript:void(removeToWppCart(' + cartItem.id + '));'; const infoDiv = document.createElement('div'); infoDiv.append(titleElement); if (cartItem.choosedProductComplements) { cartItem.choosedProductComplements.forEach(productComplement => { const complementsInfoDiv = document.createElement('div'); complementsInfoDiv.classList.add('product-complements-in-cart'); const complementTitle = document.createElement('p'); complementTitle.innerText = getProductTitleLength(productComplement); complementsInfoDiv.append(complementTitle); if (!cartItem.isFixed) { const xComplementElement = document.createElement('a'); xComplementElement.innerText = 'x'; xComplementElement.href = 'javascript:void(removeProductComplementToWppCart(' + cartItem.id + ',' + productComplement.id + '));'; complementsInfoDiv.append(xComplementElement); } infoDiv.append(complementsInfoDiv); }); } const divElement = document.createElement('div'); divElement.appendChild(infoDiv) divElement.appendChild(xElement) divElement.classList.add('product-in-cart') document.getElementById('wpp-cart-products').appendChild(divElement); } function createTotalElement() { document.querySelector('#cart-total span').innerHTML = convertToCurrency(totalPrice); document.querySelector('#cart-discount span').innerHTML = convertToCurrency(discount); document.querySelector('#total span').innerHTML = convertToCurrency(Math.max(totalPrice - discount, 0)); } function renderWppCart({ mode, billIdentification, localIdentification } = {}) { document.getElementById('wpp-cart-products').innerHTML = ''; wppCart.forEach(cartItem => createCartItem({ cartItem })) createTotalElement() if (mode === 'bill' && billIdentification) { const billIdentificationLabel = document.getElementById('bill-identification-label'); billIdentificationLabel.innerText = 'Id: ' + billIdentification billIdentificationLabel.classList.remove('d-none'); const billLocalIdentificationLabel = document.getElementById('bill-local-identification-label'); billLocalIdentificationLabel.innerText = cartTranslation.cardDesk + localIdentification billLocalIdentificationLabel.classList.remove('d-none'); document.querySelector('.wpp-cart-title h2').innerText = cartTranslation.billCartModalTitle; document.querySelector('.bill-close-btn').classList.remove('d-none'); document.querySelector('.wpp-cart-finish-btn').classList.add('d-none'); document.getElementById('bill-add-btn').classList.add('d-none'); document.getElementById('wpp-cart').classList.add('show') if (cardRender.cart && cardRender.cart.metadata && cardRender.cart.metadata.showCallWaiterButton) { document.querySelector('.call-waiter-btn').classList.remove('d-none') } } } function openModal() { document.getElementById('wpp-cart').classList.toggle('show') document.getElementById('cart-info-modal-bg').classList.toggle('show') document.documentElement.style.overflow = 'hidden'; } function closeModal() { if (!document.getElementById('wpp-cart').classList.contains('show')) { document.getElementById('wpp-cart').classList.add('show') } document.getElementById('cart-info-modal-bg').classList.toggle('show') if (document.getElementById('use-bill-identification').parentElement.classList.contains('show')) { document.getElementById('fidelity-wrapper').classList.remove('hide'); } if (!document.getElementById('local-payment-type-wrapper').classList.contains('d-none')) { document.getElementById('local-payment-type-wrapper').classList.add('d-none'); } if (!document.getElementById('money-change-wrapper').classList.contains('d-none')) { document.getElementById('money-change-wrapper').classList.add('d-none'); } document.getElementById('use-bill-identification').parentElement.classList.remove('show') document.documentElement.style.overflow = 'auto'; if (freights && freights.active == true && ['correios', 'melhor_envio', 'advanced_distance', 'distance'].includes(freights.type)) { totalPrice -= valueFreight; valueFreight = 0; wppCart = wppCart.filter(item => item.title !== (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); // if (correiosFreightDiv) { // correiosFreightDiv.innerHTML = ""; // } valueFreightVerify = undefined; } const { billIdentification } = getOpenedBill(); if (billIdentification == null) { checkoutMethod = null; } } function createComplementElement({ cartItemId, productComplement }) { const complementWrapperDiv = document.createElement('div'); complementWrapperDiv.classList.add('complement-wrapper'); const complementInfoDiv = document.createElement('div'); const complementInfoTitleP = document.createElement('p'); complementInfoTitleP.innerText = productComplement.title; const complementInfoDescriptionP = document.createElement('p'); complementInfoDescriptionP.innerText = productComplement.description; const complementInfoPriceP = document.createElement('p'); complementInfoPriceP.innerText = convertToCurrency(productComplement.price); complementInfoDiv.append(complementInfoTitleP); complementInfoDiv.append(complementInfoDescriptionP); complementInfoDiv.append(complementInfoPriceP); complementWrapperDiv.append(complementInfoDiv); const complementRemove = document.createElement('a'); complementRemove.setAttribute("class", "minusComplement"); complementRemove.innerHTML = '-' complementRemove.href = 'javascript:void(decProductComplementToWppCart('+ cartItemId + ',' + productComplement.product_id + ',' + productComplement.id + '))'; const complementAmount = document.createElement("INPUT"); complementAmount.setAttribute("type", "text"); complementAmount.setAttribute("id", "productComplement" + productComplement.id); complementAmount.value = 0; complementAmount.onclick = function () { complementAmount.setAttribute('onkeyup','addProductComplementToWppCart('+ cartItemId + ',' + productComplement.product_id + ',' + productComplement.id + ',' + true + ')'); complementAmount.setAttribute('onfocusout','validateInputValue('+productComplement.id+')'); }; complementAmount.onblur = function () { const product = products.find(product => product.id === productComplement.product_id); const maxComplementOfProduct = product.product_complements_qty; ifResetQuantityOfComplements(product, maxComplementOfProduct, complementAmount); }; complementAmount.oninput = function () { const product = products.find(product => product.id === productComplement.product_id); const maxComplementOfProduct = product.product_complements_qty; ifResetQuantityOfComplements(product, maxComplementOfProduct, complementAmount); }; const complementAddA = document.createElement('a'); complementAddA.setAttribute("class", "plusComplement"); complementAddA.innerHTML = '+' complementAddA.href = 'javascript:void(addProductComplementToWppCart('+ cartItemId + ',' + productComplement.product_id + ',' + productComplement.id + '))'; complementWrapperDiv.append(complementRemove); complementWrapperDiv.append(complementAmount); complementWrapperDiv.append(complementAddA); document.querySelector('.complements').append(complementWrapperDiv); } function ifResetQuantityOfComplements(product, max, compl) { const productProduct = product; let sumComplementsSelected = 0; let maxComplementOfProduct = max; let itensCount = document.querySelectorAll(".complement-wrapper input"); let complMessage = document.querySelector("p.maxComplementos"); itensCount.forEach(index => { sumComplementsSelected += parseInt(index.value); }); sessionStorage.setItem('complId', compl.id); sessionStorage.setItem('complVal', compl.value); if(sumComplementsSelected > maxComplementOfProduct) { const idComplement = document.getElementById(compl.id); idComplement.value = 0; complMessage.style.display = "block"; } } function convertToCurrency(value) { let code, lang; switch (cardRender.currency) { case "R$": lang = 'pt-BR'; code = 'BRL'; break; case "$": lang = 'en-US'; code = 'USD'; break; case "€": lang = 'en-US'; code = 'EUR'; break; case "¥": lang = 'ja-jn'; code = 'JPY'; break; case "MT": lang = 'pt-MZ'; code = 'MZN'; break; default: lang = cardRender.language; code = cardRender.currency; }; let conversion = new Intl .NumberFormat(lang, {style: 'currency', currency: code }) .format(value); return conversion; } let currentProductIdAtComplementsModal; function openComplementsModal({ cartItemId, productComplements, complementLabel }) { // Clear all child of complements document.querySelector('.complements').innerHTML = ''; // Create all complements productComplements.forEach(productComplement => createComplementElement({ cartItemId, productComplement, })) if (complementLabel) document.getElementById('product-complement-title').innerText = complementLabel document.getElementById('product-complements-modal-bg').classList.toggle('show') document.documentElement.style.overflow = 'hidden'; currentProductIdAtComplementsModal = cartItemId; } function closeComplementsModal() { document.getElementById('product-complements-modal-bg').classList.toggle('show') document.documentElement.style.overflow = 'auto'; const currentProduct = wppCart.find(product => product.id === currentProductIdAtComplementsModal) if (!currentProduct) return; const totalComplements = currentProduct.choosedProductComplements ? currentProduct.choosedProductComplements.reduce((total, { amount }) => total + amount, 0) : 0; if ( currentProduct.product_complements_mandatory && currentProduct.product_complements_min_qty != null && currentProduct.product_complements_min_qty > totalComplements ) { removeToWppCart(currentProductIdAtComplementsModal); return; } const productWithoutPrice = !currentProduct.price || currentProduct.price === 0; const hasSelectedComplement = !!(currentProduct.choosedProductComplements && currentProduct.choosedProductComplements.length !== 0) if (productWithoutPrice && !hasSelectedComplement) { removeToWppCart(currentProductIdAtComplementsModal) } } const inputZipCodeElement = document.getElementById('zipCode'); const streetElement = document.getElementById('street'); const streetNumberElement = document.getElementById('street-number'); const streetComplementElement = document.getElementById('street-complement'); const districtElement = document.getElementById('district'); const cityElement = document.getElementById('city'); const stateElement = document.getElementById('state'); function getProductComplementText({ itemCart }) { if (!itemCart.choosedProductComplements) return ''; let productComplementText = ''; itemCart.choosedProductComplements.forEach(productComplement => { const parsedFloat = parseFloat(productComplement.price || 0) const totalProductComplementPrice = productComplement.amount * parsedFloat; productComplementText += ' ' + ((translation.cart && translation.cart.complement && translation.cart.complement.wppComplementLabel) || cartTranslation.cardComplement) + ' *' + productComplement.title+ '*%0a' + ' ' + (cartConfig.wpp_complement_quantity_label || cartTranslation.cardAmount) + ' *' + productComplement.amount + '*%0a' + ' ' + (cartConfig.wpp_complement_price_label || cartTranslation.cardPrice) + ' *' + convertToCurrency(totalProductComplementPrice) + '*%0a%0a'; }); return productComplementText; } function getOrderText() { let orderText = ''; wppCart.forEach((itemCart) => { console.log(itemCart); if(itemCart.price > 0) { if(!itemCart.deliveryType) { orderText += (cartConfig.wpp_product_name_label || cartTranslation.cardName) + ' *' + ((itemCart.title && itemCart.title.replace(/(<([^>]+)>)/ig, '')) || 'Produto sem título') + '*%0a' if (itemCart.code) orderText += cartTranslation.productCode + '*' + itemCart.code.replace(/#/g, '%23') + '*%0a' if (itemCart.price !== 0 || !itemCart.choosedProductComplements) { orderText += (cartConfig.wpp_product_quantity_label || cartTranslation.cardAmount) + ' *' + itemCart.amount + '*%0a' } let productObservation = itemCart.observations ? 'Obs do produto: ' + itemCart.observations + '%0a%0a' : ''; orderText += (cartConfig.wpp_product_price_label || cartTranslation.cardPrice) + ' *' + convertToCurrency(itemCart.price) + '*%0a%0a' + getProductComplementText({ itemCart }) + productObservation; } else { orderText += (cartConfig.wpp_product_name_label || cartTranslation.cardName) + ' *' + (itemCart.title && itemCart.title.replace(/(<([^>]+)>)/ig, '')) + ' tipo '+itemCart.deliveryType+'*%0a' if (itemCart.code) orderText += cartTranslation.productCode + '*' + itemCart.code.replace(/#/g, '%23') + '*%0a' if (itemCart.price !== 0 || !itemCart.choosedProductComplements) { orderText += (cartConfig.wpp_product_quantity_label || cartTranslation.cardAmount) + ' *' + itemCart.amount + '*%0a' } orderText += (cartConfig.wpp_product_price_label || cartTranslation.cardPrice) + ' *' + convertToCurrency(itemCart.price) + '*%0a%0a' } } else { orderText += (cartConfig.wpp_product_name_label || cartTranslation.cardName) + ' *' + ((itemCart.title && itemCart.title.replace(/(<([^>]+)>)/ig, '')) || 'Produto sem título') + '*%0a' if (itemCart.code) orderText += cartTranslation.productCode + '*' + itemCart.code.replace(/#/g, '%23') + '*%0a' if (itemCart.price !== 0 || !itemCart.choosedProductComplements) { orderText += (cartConfig.wpp_product_quantity_label || cartTranslation.cardAmount) + ' *' + itemCart.amount + '*%0a%0a' } let productObservation = itemCart.observations ? 'Obs do produto: ' + itemCart.observations + '%0a%0a' : ''; orderText += getProductComplementText({ itemCart }) + productObservation; } }) return orderText; } let deliveryTypeElement = document.getElementById('deliveryType'); const deliveryLocalDivElement = document.getElementById('delivery-local-div'); const deliveryAddressDivElement = document.getElementById('delivery-address-div'); const deliveryLocalInputElement = document.getElementById('delivery-local'); const customFreightDiv = document.getElementById('custom-freight-div'); const freightCustomFields = document.getElementById('custom-freight'); const calculateFreightDiv = document.getElementById('calculate-freight-div'); if (deliveryTypeElement) { deliveryTypeElement.addEventListener('change', (evt) => { if ([cartConfig.label_address_freight_option, 'Endereço'].includes(evt.target.value)) { deliveryAddressDivElement.classList.remove('d-none'); deliveryLocalDivElement.classList.add('d-none'); calculateFreightDiv && calculateFreightDiv.classList.remove('d-none'); deliveryLocalInputElement.value = null; deliveryLocalInputElement.removeAttribute('required'); inputZipCodeElement.setAttribute('required', true); streetElement.setAttribute('required', true); streetNumberElement.setAttribute('required', true); districtElement.setAttribute('required', true); if (cityElement) cityElement.setAttribute('required', true); if (stateElement) stateElement.setAttribute('required', true); if (customFreightDiv) { deliveryLocalDivElement.classList.add('d-none'); customFreightDiv.classList.remove('d-none') freightCustomFields.required = true; } } else { deliveryLocalInputElement.setAttribute('required', true) deliveryAddressDivElement.classList.add('d-none'); deliveryLocalDivElement.classList.remove('d-none'); calculateFreightDiv && calculateFreightDiv.classList.add('d-none'); inputZipCodeElement.value = null; inputZipCodeElement.removeAttribute('required'); streetElement.value = null; streetElement.removeAttribute('required'); streetNumberElement.value = null; streetNumberElement.removeAttribute('required'); if (streetComplementElement) { streetComplementElement.value = null; } districtElement.value = null; districtElement.removeAttribute('required'); if (cityElement) { cityElement.value = null; cityElement.removeAttribute('required'); } if (stateElement) { stateElement.value = null; stateElement.removeAttribute('required'); } if (customFreightDiv) { deliveryLocalDivElement.classList.remove('d-none'); customFreightDiv.classList.add('d-none') freightCustomFields.required = false; const freight = wppCart.find(el => el.title === (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); if (freight) { totalPrice -= freight.price; wppCart = wppCart.filter(el => el.title !== (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); } } } }) } if (freightCustomFields) { freightCustomFields.addEventListener('change', (evt) => { const selectedCustomField = freights.customFreights .find(customFreight => customFreight.id === parseInt(evt.target.value, 10)); document.getElementById('custom-freight-price').innerText = (freights.freight_value_label || cartTranslation.cardDeliveryTotalPriceLabel) + ': ' + convertToCurrency(selectedCustomField.price); const newCartItem = { title: cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel, amount: 1, price: parseFloat(selectedCustomField.price), customFreightFieldName: selectedCustomField.name } const lastFreight = wppCart.find(el => el.title === (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); if (lastFreight) { totalPrice -= lastFreight.price; wppCart = wppCart.filter(el => el.title !== (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); } totalPrice += parseFloat(selectedCustomField.price); wppCart.push(newCartItem) }) } function getCompleteDeliveryInfo() { const { zipCodeInput, streetInput, streetNumberInput, streetComplementInput, districtInput, cityInput, stateInput, } = getFormInputs(); if (['onlineSell', 'locally'].includes(checkoutMethod)) return ''; if (checkoutMethod === 'locallyConsumption' || (deliveryTypeElement && [cartConfig.label_locally_freight_option, 'No Local'].includes(deliveryTypeElement.value))) { return (cartConfig.label_table_info || 'Mesa') + ': *' + ((document.getElementById('delivery-local') && document.getElementById('delivery-local').value) || cartTranslation.noInformation ) + '*%0a%0a'; } let customFreight = ''; if (freights.type === 'custom') { const freightInfo = wppCart.find(el => el.title === (cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel)); customFreight = (freights.freight_label || 'Frete') + ': *' + freightInfo.customFreightFieldName + '*%0a%0a'; } let cardStreetInputLabel = freights.lable_public_place || cartTranslation.cardStreetInputLabel, cardStreetNumberInputLabel = freights.lable_number || cartTranslation.cardStreetNumberInputLabel, cardStreetComplementInputLabel = freights.lable_complement || cartTranslation.cardStreetComplementInputLabel, cardDistrictInputLabel = freights.lable_neighborhood || cartTranslation.cardDistrictInputLabel, cardCityInputLabel = freights.lable_city || cartTranslation.cardCityInputLabel, cardStateInputLabel = freights.lable_state || cartTranslation.cardStateInputLabel customFreight += ((freights && freights.zip_code_label) || cartTranslation.cardZipCodeInputLabel) + ' *' + ((zipCodeInput && zipCodeInput.value) || cartTranslation.noInformation) + '*%0a%0a' + cardStreetInputLabel + ' *' + (streetInput.value || cartTranslation.noInformation) + '*%0a%0a' + cardStreetNumberInputLabel + ' *' + (streetNumberInput.value || cartTranslation.noInformation) + '*%0a%0a'; if (!freights || !freights.metadata || !freights.metadata.hideStreetComplement) { customFreight += cardStreetComplementInputLabel + ' *' + ((streetComplementInput && streetComplementInput.value) || cartTranslation.noInformation) + '*%0a%0a' } customFreight += cardDistrictInputLabel + ' *' + (districtInput.value || cartTranslation.noInformation) + '*%0a%0a' if (!freights || !freights.metadata || !freights.metadata.hideCity) { customFreight += cardCityInputLabel + ' *' + ((cityInput && cityInput.value) || cartTranslation.noInformation) + '*%0a%0a' } if (!freights || !freights.metadata || !freights.metadata.hideState) { customFreight += cardStateInputLabel + ' *' + ((stateInput && stateInput.value) || cartTranslation.noInformation) + '*%0a%0a' } return customFreight } function getPaymentType() { const paymentTypeElement = document.getElementById("paymentType"); const paymentTypeChosen = paymentTypeElement ? paymentTypeElement.value : ''; const isLocalPayment = paymentTypeChosen.toLowerCase().includes('entrega') if (!isLocalPayment) { return paymentTypeChosen || cartTranslation.noInformation } const localPaymentTypeChosen = document.getElementById("local-payment-type").value; if (localPaymentTypeChosen === 'creditCard') { return cartTranslation.wppMessageCreditCardLocalPayment } if (localPaymentTypeChosen === 'debitCard') { return cartTranslation.wppMessageDebitCardLocalPayment } const withoutMoneyChange = document.getElementById("without-money-change").checked const moneyChangeValue = Number(document.getElementById("money-change").value) if (withoutMoneyChange || moneyChangeValue === 0) { return cartTranslation.wppMessageMoneyLocalPaymentWithoutChange } return cartTranslation.wppMessageMoneyLocalPaymentWithChange + convertToCurrency(moneyChangeValue) } function getFormInputs() { const zipCodeInput = document.getElementById('zipCode'); const streetInput = document.getElementById('street'); const streetNumberInput = document.getElementById('street-number'); const streetComplementInput = document.getElementById('street-complement'); const districtInput = document.getElementById('district'); const cityInput = document.getElementById('city'); const stateInput = document.getElementById('state'); const deliveryLocalInput = document.getElementById('delivery-local'); return { zipCodeInput, streetInput, streetNumberInput, streetComplementInput, districtInput, cityInput, stateInput, deliveryLocalInput, } } function resetInput({ inputId }) { const inputElement = document.getElementById(inputId); if (inputElement) inputElement.value = null; } function resetElement({ inputId }) { const htmlElement = document.getElementById(inputId); if (htmlElement) htmlElement.innerHTML = null; } function resetSite() { resetInput({ inputId: 'wpp-cart-form-name' }); resetInput({ inputId: 'wpp-cart-form-phone' }); resetInput({ inputId: 'extraInfo' }); resetInput({ inputId: 'discountCode' }); if (checkoutMethod === 'delivery') { resetInput({ inputId: 'zipCode' }); resetInput({ inputId: 'street' }); resetInput({ inputId: 'street-number' }); resetInput({ inputId: 'street-complement' }); resetInput({ inputId: 'district' }); resetInput({ inputId: 'state' }); resetInput({ inputId: 'city' }); resetElement({ inputId: 'freights-price' }); } if (checkoutMethod === 'bill') { document.querySelector('#cart-info-modal-bg').classList.remove('show') document.querySelector('#wpp-cart').classList.remove('show') document.querySelector('.wpp-cart-title h2').innerText = cartConfig.pop_up_title_label || cartTranslation.cartModalTitle document.querySelector('#bill-identification-label').classList.add('d-none') document.querySelector('#bill-local-identification-label').classList.add('d-none') document.querySelector('.call-waiter-btn').classList.add('d-none') document.querySelector('.bill-close-btn').classList.add('d-none') document.querySelector('.bill-add-btn').classList.add('d-none') document.querySelector('.wpp-cart-finish-btn').classList.remove('d-none') } wppCart = []; totalPrice = 0; valueFreight = 0; discount = 0; const couponAlert = document.getElementById('coupon-alert'); if (couponAlert) couponAlert.innerHTML = '' valueFreightVerify = undefined; renderWppCart(); if (checkoutMethod !== 'bill') { closeModal(); } document.getElementById('wpp-cart').classList.remove('show'); document.getElementById('send-order').innerText = cartTranslation.cardFinishButtonText document.getElementById('send-order').disabled = false; // money change document.getElementById('local-payment-type-wrapper').classList.add('d-none'); document.getElementById('money-change-wrapper').classList.add('d-none'); document.getElementById('money-change-field').classList.add('d-none'); document.getElementById('paymentType').value = document.getElementById('paymentType').options[0].value checkoutMethod = null setLoading({ isLoading: false }); } async function createClient(data) { const userLogged = JSON.parse(localStorage.getItem('user')); if (!userLogged) { const { success, error } = await login(data); if (error) { await signUp(data); } } } async function revalidateSupply() { const wppCartInitialLength = wppCart.length; wppCart.map(item => { if (hasSupply({ product: item })) { if ((item.selectedComplementSteps ?? []).length === 0) { return item; } if (item.selectedComplementSteps?.every(item => productComplementHasSupply({ productComplement: item }))) { return item; } else { showSnackbar('O complemento do produto ' + item.sanitized_title + ', não tem mais estoque!'); removeToWppCart(item.id); } } else { showSnackbar('O produto ' + item.sanitized_title + ', não tem mais estoque!'); removeToWppCart(item.id); } }) return wppCartInitialLength === wppCart.length; } var valueFreightVerify; async function redirectToWpp(evt) { if (!revalidateSupply()) { return; } const wppCartPhoneInput = document.getElementById('wpp-cart-form-phone'); if (wppCartPhoneInput.required) { const phoneIsValid = isValidPhone(wppCartPhoneInput) if (!phoneIsValid) { document.getElementById("error-phone").style.display = "block"; return; } else { document.getElementById("error-phone").style.display = "none"; } } let redirectMethod; let redirectUrl; evt.submitter.disabled = true deliveryTypeElement = document.getElementById('deliveryType'); setLoading({ isLoading: true }); const finishButton = document.getElementById('send-order') .innerText = cartConfig.sending_order_label || cartTranslation.cartModalFinishLoadingButtonText if (freights == "" || ['fixed', 'free', 'custom'].includes(freights.type) || freights.active == false || (deliveryTypeElement && [cartConfig.label_locally_freight_option, 'No Local', 'On-line'].includes(deliveryTypeElement.value)) || (freights != "" && valueFreightVerify != undefined) ) { const nameElement = document.getElementById('wpp-cart-form-name'); const name = nameElement && nameElement.value; const phone = document.getElementById('wpp-cart-form-phone').value; const password = document.getElementById('wpp-cart-form-password').value; const dataToClient = { photoURL: localStorage.getItem('photoURL') ?? null, phone: phone.replace("+", ""), name, } if (password) { dataToClient.password = password; } await createClient(dataToClient); const paymentType = document.getElementById('paymentType').value; const extraInfoElement = document.getElementById('extraInfo'); const extraInfo = extraInfoElement && extraInfoElement.value; if(freights.active && freights.type === "fixed" && (!deliveryTypeElement || ![cartConfig.label_locally_freight_option, 'No Local'].includes(deliveryTypeElement.value))) { let freightPriceDiv = document.getElementById('freights-price'); valueFreight = 0; if (freightPriceDiv.innerText != cartTranslation.freeFreight) { freightPriceDiv.innerText = (freights.freight_value_label || cartTranslation.cardDeliveryTotalPriceLabel) + ': ' + convertToCurrency(freights.price); totalPrice += parseFloat(freights.price); const newCartItem = { title: cartConfig.wpp_delivery_title_label || cartTranslation.cardDeliveryPriceMessageLabel, amount: 1, price: parseFloat(freights.price) } wppCart.push(newCartItem) } } if (freights.active && freights.type === 'custom') { valueFreight = 0; } if (ticketId) { const user = JSON.parse(localStorage.getItem('user')); if (!user) { showSnackbar({ message: 'Usuário não encontrado, refaça o pedido!'}); setLoading({ isLoading: false }); return; } const clientId = user.id; const ticket = await fetch(orderApiUrl + '/v3/ticket/' + ticketId + '?clientId=' + clientId, { method: "GET", }) if (!ticket.ok) { ticketId = ''; showSnackbar({ message: 'Esse ticket já foi utilizado, refaça o pedido!'}); setLoading({ isLoading: false }); return; } } let nameTextRow = (cartConfig.label_name || cartTranslation.cardNameInputLabel) + ' *' + (name || cartTranslation.noInformation) + '*%0a%0a' let phoneTextRow = (cartConfig.label_phone || cartTranslation.cardPhoneInputLabel) + ' *' + (phone || cartTranslation.noInformation) + '*%0a%0a'; formattedPhone = phone ? phone.replace('+', '') : null; const shippingTextRow = (cartConfig.label_shipping_method || cartTranslation.cardDeliveryTypeInputLabel) + ' *' + (deliveryTypeElement && deliveryTypeElement.value) + '*%0a%0a' let observationTextRow = ''; if (extraInfo) { observationTextRow = (cartConfig.label_observation || cartTranslation.cardExtraInfoInputLabel) + ' *' + (extraInfo || 'Nenhuma') + '*%0a%0a' } let wppText = nameTextRow + phoneTextRow + shippingTextRow + getCompleteDeliveryInfo() + (cartConfig.label_purchase_method || cartTranslation.cardPaymentTypeInputLabel) + ' *' + getPaymentType() + '*%0a%0a' + observationTextRow + (cartConfig.wpp_order_label || cartTranslation.cardOrder) + ' %0a' + getOrderText() + (cartConfig.pop_up_subtotal_label || 'Subtotal') + ': *' + convertToCurrency(totalPrice) + '*%0a' + (cartConfig.pop_up_discount_label || 'Desconto') + ': *' + convertToCurrency(discount) + '*%0a' + (cartConfig.pop_up_total_label || 'Total') + ': *' + convertToCurrency(Math.max(totalPrice - discount, 0)) + '*' if (cartConfig && cartConfig.nextgo_orders_active && (!deliveryTypeElement || deliveryTypeElement.value !== 'On-line')) { const { error, success } = await updateSupplyProducts(); if (error && success != false) { const bodyResponse = await success.json(); showSnackbar({ message: 'Ocorreu um erro ao atualizar o estoque, erro: ' + bodyResponse.message }); setLoading({ isLoading: false }); return; } const { errorComplement, successComplement } = await updateSupplyProductComplements(); if (errorComplement && successComplement != false) { const bodyResponse = await successComplement.json(); showSnackbar({ message: 'Ocorreu um erro ao atualizar o estoque, erro: ' + bodyResponse.message }); setLoading({ isLoading: false }); return; } const nextGoOrdersResponse = await sendToNextGoOrders(); if (!nextGoOrdersResponse) { showSnackbar({ message: 'Ocorreu um erro ao enviar o pedido, tente novamente!'}); setLoading({ isLoading: false }); return; } if (nextGoOrdersResponse && nextGoOrdersResponse.orderId) { const orderId = nextGoOrdersResponse.orderId; redirectMethod = nextGoOrdersResponse.redirectMethod redirectUrl = nextGoOrdersResponse.redirectUrl if (!cartConfig.hide_status_url) { const statusURL = useNextGoOrdersV2 ? nextGoOrdersStatusURL + orderId : nextGoOrdersURL + '/status/' + orderId; window.localStorage.setItem("orderId", orderId); wppText += '%0a%0a' + (cartConfig.wpp_orders_link_label || 'Link para status do pedido') + ': ' + statusURL; } } } if (shareLocationLink) wppText += '%0a%0a' + cartTranslation.shareLocationLink + shareLocationLink; let redirectWppLink = 'https://api.whatsapp.com/send?phone=' + wppCartPhone + '&text=' + wppText; window.localStorage.setItem("redirectWppLink", redirectWppLink); sessionStorage.setItem("already-redirected", true); const infoPayment = "" if (redirectMethod === 'whatsapp-message') { resetSite(); document.getElementById('order-whatsapp-flow').classList.toggle('show'); } else if (redirectMethod === 'nextgo-pay') { resetSite(); window.location.href = redirectUrl } else if (infoPayment.active == true && paymentType == cartTranslation.onlinepayment) { const { res } = await createPreference("Compra na " + infoPayment.title, location.href, location.href); await updateOrder(window.localStorage.orderId, 1, res.body.collector_id); window.location.href = res.response.init_point } else { if (checkoutMethod !== 'bill') resetSite(); window.location.href = 'https://api.whatsapp.com/send?phone=' + wppCartPhone + '&text=' + wppText.replace(/&/g,'%26') } } else { document.getElementById("error-freights-price").style.display = "block"; document.getElementById('send-order').innerText = cartTranslation.cardFinishButtonText document.getElementById('send-order').disabled = false; } setLoading({ isLoading: false }); } -->