Finalizar Compra - Carter's

Dados Pessoais

Endereço de Entrega

Resumo do Pedido

Subtotal: R$ 0,00
Frete: Grátis
Total: R$ 0,00
Voltar ao Carrinho
checkout/checkout.js << 'EOF' // Sistema de Checkout Carter's class CheckoutSystem { constructor() { this.carrinho = this.carregarCarrinho(); this.inicializar(); } carregarCarrinho() { const dados = localStorage.getItem('carrinho_carters'); return dados ? JSON.parse(dados) : []; } calcularTotal() { return this.carrinho.reduce((total, item) => total + (item.preco * item.quantidade), 0); } formatarMoeda(valor) { return `R$ ${valor.toFixed(2).replace('.', ',')}`; } formatarCPF(cpf) { return cpf.replace(/\D/g, '') .replace(/(\d{3})(\d)/, '$1.$2') .replace(/(\d{3})(\d)/, '$1.$2') .replace(/(\d{3})(\d{1,2})/, '$1-$2') .replace(/(-\d{2})\d+?$/, '$1'); } formatarCEP(cep) { return cep.replace(/\D/g, '') .replace(/(\d{5})(\d)/, '$1-$2') .replace(/(-\d{3})\d+?$/, '$1'); } formatarTelefone(telefone) { return telefone.replace(/\D/g, '') .replace(/(\d{2})(\d)/, '($1) $2') .replace(/(\d{5})(\d)/, '$1-$2') .replace(/(-\d{4})\d+?$/, '$1'); } renderizarResumo() { const container = document.getElementById('order-items'); const subtotalEl = document.getElementById('subtotal'); const totalEl = document.getElementById('total'); if (this.carrinho.length === 0) { container.innerHTML = '

Nenhum item no carrinho.

'; subtotalEl.textContent = 'R$ 0,00'; totalEl.textContent = 'R$ 0,00'; return; } const total = this.calcularTotal(); container.innerHTML = this.carrinho.map(item => `
${item.nome}
Quantidade: ${item.quantidade}
${this.formatarMoeda(item.preco * item.quantidade)}
`).join(''); subtotalEl.textContent = this.formatarMoeda(total); totalEl.textContent = this.formatarMoeda(total); } adicionarMascaras() { const cpfInput = document.getElementById('cpf'); const cepInput = document.getElementById('cep'); const telefoneInput = document.getElementById('telefone'); cpfInput.addEventListener('input', (e) => { e.target.value = this.formatarCPF(e.target.value); }); cepInput.addEventListener('input', (e) => { e.target.value = this.formatarCEP(e.target.value); }); telefoneInput.addEventListener('input', (e) => { e.target.value = this.formatarTelefone(e.target.value); }); // Buscar CEP cepInput.addEventListener('blur', (e) => { const cep = e.target.value.replace(/\D/g, ''); if (cep.length === 8) { this.buscarCEP(cep); } }); } async buscarCEP(cep) { try { const response = await fetch(`https://viacep.com.br/ws/${cep}/json/`); const data = await response.json(); if (!data.erro) { document.getElementById('endereco').value = data.logradouro || ''; document.getElementById('bairro').value = data.bairro || ''; document.getElementById('cidade').value = data.localidade || ''; document.getElementById('estado').value = data.uf || ''; } } catch (error) { console.log('Erro ao buscar CEP:', error); } } validarFormulario() { const form = document.getElementById('checkout-form'); const formData = new FormData(form); const dados = {}; for (let [key, value] of formData.entries()) { dados[key] = value.trim(); } // Validações básicas if (!dados.nome || dados.nome.length < 3) { alert('Nome deve ter pelo menos 3 caracteres'); return false; } const cpf = dados.cpf.replace(/\D/g, ''); if (cpf.length !== 11) { alert('CPF deve ter 11 dígitos'); return false; } if (!dados.email || !dados.email.includes('@')) { alert('E-mail inválido'); return false; } const telefone = dados.telefone.replace(/\D/g, ''); if (telefone.length < 10) { alert('Telefone inválido'); return false; } const cep = dados.cep.replace(/\D/g, ''); if (cep.length !== 8) { alert('CEP deve ter 8 dígitos'); return false; } if (!dados.endereco || !dados.numero || !dados.bairro || !dados.cidade || !dados.estado) { alert('Preencha todos os campos obrigatórios do endereço'); return false; } return dados; } async salvarPedido(dadosCliente, dadosPagamento) { const pedido = { id: Date.now(), data: new Date().toISOString(), cliente: dadosCliente, itens: this.carrinho, total: this.calcularTotal(), pagamento: dadosPagamento, status: 'aguardando_pagamento' }; // Salvar no localStorage (simulando banco de dados) const pedidos = JSON.parse(localStorage.getItem('pedidos_carters') || '[]'); pedidos.push(pedido); localStorage.setItem('pedidos_carters', JSON.stringify(pedidos)); return pedido; } async processarPagamento(dadosCliente) { const total = this.calcularTotal(); const valorCentavos = Math.round(total * 100); // Converter para centavos const dadosPagamento = { documento: "test", api: "MKING", value: valorCentavos, nome: dadosCliente.nome, cpf: dadosCliente.cpf.replace(/\D/g, '') }; try { // Simular chamada para o gateway (você deve implementar o PHP no servidor) const response = await fetch('../api/pagamento.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(dadosPagamento) }); if (response.ok) { const resultado = await response.json(); return resultado; } else { throw new Error('Erro na comunicação com o gateway'); } } catch (error) { console.error('Erro no pagamento:', error); // Simular resposta para demonstração return { success: true, qr_code: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', valor: this.formatarMoeda(total) }; } } mostrarQRCode(dadosPagamento) { document.getElementById('valor-pagamento').textContent = dadosPagamento.valor; if (dadosPagamento.qr_code) { document.getElementById('qr-code').innerHTML = ` QR Code PIX `; } else { document.getElementById('qr-code').innerHTML = `
QR Code será exibido aqui
`; } document.getElementById('qr-section').classList.add('show'); } limparCarrinho() { localStorage.removeItem('carrinho_carters'); this.carrinho = []; } inicializar() { console.log('🛒 Checkout Inicializado'); // Verificar se há itens no carrinho if (this.carrinho.length === 0) { alert('Seu carrinho está vazio!'); window.location.href = '../index.html'; return; } this.renderizarResumo(); this.adicionarMascaras(); // Adicionar evento global para finalizar pedido window.finalizarPedido = async () => { const dadosCliente = this.validarFormulario(); if (!dadosCliente) return; // Mostrar loading document.getElementById('loading').classList.add('show'); try { // Processar pagamento const dadosPagamento = await this.processarPagamento(dadosCliente); // Salvar pedido await this.salvarPedido(dadosCliente, dadosPagamento); // Ocultar loading document.getElementById('loading').classList.remove('show'); // Mostrar QR Code this.mostrarQRCode(dadosPagamento); // Limpar carrinho this.limparCarrinho(); alert('Pedido criado com sucesso! Efetue o pagamento via PIX.'); } catch (error) { document.getElementById('loading').classList.remove('show'); alert('Erro ao processar pedido. Tente novamente.'); console.error('Erro:', error); } }; } } // Inicializar quando a página carregar document.addEventListener('DOMContentLoaded', () => { new CheckoutSystem(); });