var obrigaCliente = 0; $(document).ready(function() { const hoje = new Date(); const dataVencimentoPadrao = new Date(); dataVencimentoPadrao.setDate(hoje.getDate() + 30); $('.data_atual').val(formatarData(hoje)); $('.data_vencimento_padrao').val(formatarData(dataVencimentoPadrao)); $('#data_primeiro_pagamento').val(formatarData(dataVencimentoPadrao)); const tiposPagamento = { '01': { nome: 'Dinheiro', tipo: 'vista' }, '17': { nome: 'PIX', tipo: 'vista' }, '10': { nome: 'Vale Alimentação', tipo: 'vista' }, '11': { nome: 'Vale Refeição', tipo: 'vista' }, '02': { nome: 'Cheque', tipo: 'vista' }, '13': { nome: 'Vale Presente', tipo: 'vista' }, '14': { nome: 'Vale Combustível', tipo: 'vista' }, '16': { nome: 'Depósito Bancário', tipo: 'vista' }, '04': { nome: 'Cartão de Débito', tipo: 'cartao' }, '03': { nome: 'Cartão de Crédito', tipo: 'cartao' }, '06': { nome: 'Crediário', tipo: 'prazo' }, '05': { nome: 'Crédito Loja', tipo: 'prazo' }, '15': { nome: 'Boleto', tipo: 'prazo' }, '14': { nome: 'Duplicata Mercantil', tipo: 'prazo' }, '07': { nome: 'Cartão de Crédito TEF', tipo: 'tef' }, '08': { nome: 'Cartão de Débito TEF', tipo: 'tef' }, '12': { nome: 'PIX TEF', tipo: 'tef' } }; let pagamentoId = 0; function getValorTotal() { // var totalProdutos = convertMoedaToFloat($('.total-venda').text()) // let total = totalProdutos + parseFloat(VALORACRESCIMO) + parseFloat(VALORFRETE) - parseFloat(DESCONTO) let total = convertMoedaToFloat($('#painel-total-venda').text()) return total; } $(document).ready(function() { setTimeout(function() { const valorTotal = getValorTotal(); if (valorTotal > 0) { $('#valor-restante').text(`R$ ${convertFloatToMoeda(valorTotal)}`); $('#mensagem-pagamento').html('Adicione pagamentos para cobrir o valor total da venda.'); } }, 500); }); // $('#cliente').on('hidden.bs.modal', function () { // console.log($('.cliente_selecionado').text().trim()) // if(obrigaCliente == 1 && $('.cliente_selecionado').text().trim() == 'selecionar cliente'){ // toastr.warning("Selecione o cliente, obrigatório!"); // $('.cliente_selecionado').trigger('click') // } // }); $('#tipo_pagamento_atual').on('change', function() { const tipoPagamento = $(this).val(); $('.campos-especificos').addClass('d-none'); if (!tipoPagamento) return; if (tiposPagamento[tipoPagamento]) { const tipo = tiposPagamento[tipoPagamento].tipo; // if(tipo == 'prazo'){ // toastr.warning("Selecione o cliente para finalizar a venda!"); // $('.cliente_selecionado').trigger('click') // obrigaCliente = 1 // } switch(tipo) { case 'cartao': $('.campos-cartao').removeClass('d-none'); break; case 'prazo': $('.campos-prazo').removeClass('d-none'); $('#tem_parcelamento').prop('checked', false); $('.campos-parcelamento').addClass('d-none'); break; case 'tef': break; } } setTimeout(function() { const valorRestante = calcularValorRestante(); if (valorRestante > 0) { $('#valor_pagamento_atual').val(convertFloatToMoeda(valorRestante)); } }, 100); }); $('#tem_parcelamento').on('change', function() { if ($(this).is(':checked')) { $('.div-data-vencimento').addClass('d-none'); $('.campos-parcelamento').removeClass('d-none'); } else { $('.div-data-vencimento').removeClass('d-none'); $('.campos-parcelamento').addClass('d-none'); } }); function calcularValorRestante() { let valorTotal = getValorTotal(); let totalPago = pagamentosRegistrados.reduce((sum, item) => sum + parseFloat(item.valor), 0); totalPago = Math.round(totalPago * 100) / 100; valorTotal = Math.round(valorTotal * 100) / 100; let valorRestante = valorTotal - totalPago; if (valorRestante > -0.01 && valorRestante < 0) { valorRestante = 0; } // Atualizar os valores exibidos $('#valor-total-venda').text('R$ ' + convertFloatToMoeda(valorTotal)); $('#valor-pago').text('R$ ' + convertFloatToMoeda(totalPago)); $('#valor-restante').text('R$ ' + convertFloatToMoeda(valorRestante)); // Calcular e exibir o troco se aplicável const troco = totalPago > valorTotal ? totalPago - valorTotal : 0; $('#valor-troco').text('R$ ' + convertFloatToMoeda(troco)); // console.log("Calculando valor restante. Total da venda:", valorTotal, "Total pago:", totalPago, "Restante:", valorRestante); return valorRestante; } $('#adicionar-pagamento').on('click', function() { // console.log("Handler original do botão adicionar-pagamento acionado"); const tipoPagamento = $('#tipo_pagamento_atual').val(); const valorPagamento = $('#valor_pagamento_atual').val(); if (!tipoPagamento) { swal('Atenção', 'Selecione um tipo de pagamento', 'warning'); return; } if (!valorPagamento || parseFloat(valorPagamento.replace(/\./g, '').replace(',', '.')) <= 0) { swal('Atenção', 'Informe um valor válido para o pagamento', 'warning'); return; } if ((tipoPagamento == '06' || tipoPagamento == '05' || tipoPagamento == '15') && $("#inp-cliente_id").val() == null) { swal('Atenção', 'Selecione um cliente para pagamento a prazo', 'warning'); return; } const valorNumerico = parseFloat(valorPagamento.replace(/\./g, '').replace(',', '.')); let detalhes = ''; let pagamento = { id: pagamentoId++, tipo: tipoPagamento, tipoNome: $('#tipo_pagamento_atual option:selected').text(), valor: valorNumerico, valorFormatado: valorPagamento }; if (tiposPagamento[tipoPagamento]) { const tipo = tiposPagamento[tipoPagamento].tipo; switch(tipo) { case 'cartao': const bandeira = $('#bandeira_cartao').val(); const codAutorizacao = $('#cod_autorizacao').val(); pagamento.bandeira = bandeira; pagamento.codAutorizacao = codAutorizacao; if (bandeira) { detalhes += `Bandeira: ${bandeira}`; } if (codAutorizacao) { detalhes += detalhes ? ` | Autorização: ${codAutorizacao}` : `Autorização: ${codAutorizacao}`; } break; case 'prazo': const temParcelamento = $('#tem_parcelamento').is(':checked'); if (temParcelamento) { const qtdParcelas = $('#qtd_parcelas').val(); const dataPrimeiroPagamento = $('#data_primeiro_pagamento').val(); const periodicidade = $('#periodicidade').val(); pagamento.parcelado = true; pagamento.parcelas = qtdParcelas; pagamento.dataPrimeiroPagamento = dataPrimeiroPagamento; pagamento.periodicidade = periodicidade; detalhes = `${qtdParcelas}x de ${convertFloatToMoeda(valorNumerico / qtdParcelas)} | Início: ${formatarDataBR(dataPrimeiroPagamento)}`; } else { const dataVencimento = $('#data_vencimento_atual').val(); pagamento.parcelado = false; pagamento.dataVencimento = dataVencimento; detalhes = `Vencimento: ${formatarDataBR(dataVencimento)}`; } break; } } pagamento.detalhes = detalhes; console.log("pagamento", pagamento) pagamentosRegistrados.push(pagamento); window.pagamentosRegistradosPDV = pagamentosRegistrados; const $form = $('#form-pdv'); $form.find('input[name^="pagamentos"]').remove(); window.pagamentosRegistradosPDV.forEach((pag, idx) => { $form.append(``); $form.append(``); if (pag.bandeira) { $form.append(``); } if (pag.codAutorizacao) { $form.append(``); } if (pag.dataVencimento) { $form.append(``); } if (pag.parcelado) { $form.append(``); $form.append(``); $form.append(``); $form.append(``); } }); atualizarListaPagamentos(); atualizarResumoPagamentos() $('#tipo_pagamento_atual').val(''); $('#valor_pagamento_atual').val(''); $('.campos-especificos').addClass('d-none'); $('#bandeira_cartao').val(''); $('#cod_autorizacao').val(''); $('#tem_parcelamento').prop('checked', false); }); $('.btn-store-fatura').click(() => { console.clear() if(!$('#inp-parcelas_fatura').val()){ swal("Erro", "Informe a quantidade de parcelas!", "error") return; } if(!$('#inp-intervalo_fatura').val()){ swal("Erro", "Informe o intervalo!", "error") return; } let data = { entrada_fatura: $('#inp-entrada_fatura').val(), parcelas_fatura: $('#inp-parcelas_fatura').val(), intervalo_fatura: $('#inp-intervalo_fatura').val(), primeiro_vencimento_fatura: $('#inp-primeiro_vencimento_fatura').val(), tipo_pagamento_fatura: $('#inp-tipo_pagamento_fatura').val(), total: convertMoedaToFloat($('#painel-total-venda').text()) } // console.log(data) $.get(path_url + "api/frenteCaixa/gerar-fatura-pdv", data) .done((res) => { console.log(res) setTimeout(() => { $('#modal_fatura_venda').modal('hide') pagamentosRegistrados = [] let pagamentoId = 0 res.map((x) => { let pagamento = { id: pagamentoId++, tipo: $('#inp-tipo_pagamento_fatura').val(), tipoNome: $('#inp-tipo_pagamento_fatura option:selected').text(), valor: x.valor, valorFormatado: convertFloatToMoeda(x.valor), dataVencimento: x.vencimento, detalhes: `Vencimento: ${formatarDataBR(x.vencimento)}` }; // console.log(pagamento) pagamentosRegistrados.push(pagamento); window.pagamentosRegistradosPDV = pagamentosRegistrados; atualizarListaPagamentos(); atualizarResumoPagamentos() }) }, 100) }) .fail((err) => { console.log(err); }); }) $(function(){ let fatura = $('#fatura_venda').val() if(fatura){ fatura = JSON.parse(fatura) pagamentosRegistrados = [] let pagamentoId = 0 fatura.map((f) => { $('#inp-tipo_pagamento_fatura').val(f.tipo_pagamento).change() let pagamento = { id: pagamentoId++, tipo: f.tipo_pagamento, tipoNome: $('#inp-tipo_pagamento_fatura option:selected').text(), valor: parseFloat(f.valor), valorFormatado: convertFloatToMoeda(parseFloat(f.valor)), dataVencimento: f.data_vencimento, detalhes: `Vencimento: ${formatarDataBR(f.data_vencimento)}` }; pagamentosRegistrados.push(pagamento); }) setTimeout(() => { window.pagamentosRegistradosPDV = pagamentosRegistrados; atualizarListaPagamentos(); atualizarResumoPagamentos() }, 100) } }) function formatarData(data) { const dia = data.getDate().toString().padStart(2, '0'); const mes = (data.getMonth() + 1).toString().padStart(2, '0'); const ano = data.getFullYear(); return `${ano}-${mes}-${dia}`; } function formatarDataBR(dataIso) { if (!dataIso) return ''; const [ano, mes, dia] = dataIso.split('-'); return `${dia}/${mes}/${ano}`; } function atualizarListaPagamentos() { const $lista = $('#lista-pagamentos'); const $semPagamentos = $('#sem-pagamentos'); const $tabelaPagamentos = $('#tabela-pagamentos'); const $finalizarBtn = $('#finalizar_venda_tab'); $lista.empty(); const valorTotal = getValorTotal(); // console.log('Valor total para cálculo do restante:', valorTotal); if (pagamentosRegistrados.length === 0) { $semPagamentos.removeClass('d-none'); $tabelaPagamentos.addClass('d-none'); $finalizarBtn.prop('disabled', true); $('#valor-recebido-total').text(`R$ 0,00`); $('#valor-restante').text(`R$ ${convertFloatToMoeda(valorTotal)}`); const $valorRestanteBadge = $('#valor-restante-badge'); $valorRestanteBadge.removeClass('bg-success text-white').addClass('bg-warning text-dark'); $('#mensagem-pagamento').html('Adicione pagamentos para cobrir o valor total da venda.'); return; } else { $semPagamentos.addClass('d-none'); $tabelaPagamentos.removeClass('d-none'); pagamentosRegistrados.forEach(pagamento => { const $row = $('