refactor: renomeia pagamentos para comprovantes e adiciona novos tipos
This commit is contained in:
51
static/js/comprovantes.js
Normal file
51
static/js/comprovantes.js
Normal file
@@ -0,0 +1,51 @@
|
||||
$(document).ready(function() {
|
||||
// Inicialização da tabela
|
||||
$('#tabelaComprovantes').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
}
|
||||
});
|
||||
|
||||
// Modal de edição
|
||||
$('#modalEditarComprovante').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var comprovanteId = button.data('comprovante-id');
|
||||
var militanteId = button.data('militante-id');
|
||||
var militanteNome = button.data('militante-nome');
|
||||
var tipoComprovante = button.data('tipo-comprovante');
|
||||
var valor = button.data('valor');
|
||||
var dataComprovante = button.data('data-comprovante');
|
||||
|
||||
var modal = $(this);
|
||||
modal.find('#editMilitante').val(militanteId);
|
||||
modal.find('#editMilitanteNome').val(militanteNome);
|
||||
modal.find('#editTipoComprovante').val(tipoComprovante);
|
||||
modal.find('#editValor').val(valor);
|
||||
modal.find('#editDataComprovante').val(dataComprovante);
|
||||
|
||||
modal.find('form').attr('action', '/comprovantes/editar/' + comprovanteId);
|
||||
});
|
||||
|
||||
// Modal de exclusão
|
||||
$('#modalExcluirComprovante').on('show.bs.modal', function(event) {
|
||||
var button = $(event.relatedTarget);
|
||||
var comprovanteId = button.data('comprovante-id');
|
||||
var comprovanteInfo = button.data('comprovante-info');
|
||||
|
||||
var modal = $(this);
|
||||
modal.find('#comprovanteInfo').text(comprovanteInfo);
|
||||
modal.find('form').attr('action', '/comprovantes/excluir/' + comprovanteId);
|
||||
});
|
||||
|
||||
// Formatação de valores monetários
|
||||
$('.money').mask('000.000.000.000.000,00', {reverse: true});
|
||||
|
||||
// Validação de formulários
|
||||
$('form').on('submit', function(e) {
|
||||
if (!this.checkValidity()) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
$(this).addClass('was-validated');
|
||||
});
|
||||
});
|
||||
@@ -1,316 +0,0 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
console.log('Carregando script pagamentos.js...');
|
||||
|
||||
// Inicializar DataTable
|
||||
const table = $('#tabelaPagamentos').DataTable({
|
||||
language: {
|
||||
url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/pt-BR.json'
|
||||
},
|
||||
columnDefs: [
|
||||
{
|
||||
targets: 3, // Coluna de data
|
||||
type: 'date-br',
|
||||
render: function(data, type, row) {
|
||||
if (type === 'sort') {
|
||||
return data.split('/').reverse().join('');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
},
|
||||
{
|
||||
targets: 2, // Coluna de valor
|
||||
type: 'numeric',
|
||||
render: function(data, type, row) {
|
||||
if (type === 'sort') {
|
||||
return parseFloat(data.replace('R$ ', '').replace(',', '.'));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
},
|
||||
{ targets: -1, orderable: false } // Coluna de ações
|
||||
],
|
||||
order: [[3, 'desc']] // Ordenar por data decrescente por padrão
|
||||
});
|
||||
|
||||
// Configuração do modal de edição
|
||||
const modalEditarPagamento = document.getElementById('modalEditarPagamento');
|
||||
if (modalEditarPagamento) {
|
||||
modalEditarPagamento.addEventListener('show.bs.modal', function(event) {
|
||||
console.log('Modal de edição sendo exibido');
|
||||
const button = event.relatedTarget;
|
||||
|
||||
if (!button) {
|
||||
console.error('Botão não encontrado!');
|
||||
return;
|
||||
}
|
||||
|
||||
const pagamentoId = button.getAttribute('data-pagamento-id');
|
||||
console.log('ID do pagamento:', pagamentoId);
|
||||
|
||||
// Dados do pagamento
|
||||
const dados = {
|
||||
militanteId: button.getAttribute('data-militante-id'),
|
||||
militanteNome: button.closest('tr').querySelector('td').textContent.trim(),
|
||||
tipoPagamento: button.getAttribute('data-tipo-pagamento'),
|
||||
valor: button.getAttribute('data-valor'),
|
||||
dataPagamento: button.getAttribute('data-data-pagamento')
|
||||
};
|
||||
console.log('Dados do pagamento:', dados);
|
||||
|
||||
// Preencher campos
|
||||
document.getElementById('editMilitante').value = dados.militanteId;
|
||||
document.getElementById('editMilitanteNome').value = dados.militanteNome;
|
||||
document.getElementById('editTipoPagamento').value = dados.tipoPagamento;
|
||||
document.getElementById('editValor').value = dados.valor;
|
||||
document.getElementById('editDataPagamento').value = dados.dataPagamento;
|
||||
|
||||
// Configurar formulário
|
||||
const form = document.getElementById('formEditarPagamento');
|
||||
if (form) {
|
||||
form.action = `/pagamentos/editar/${pagamentoId}`;
|
||||
console.log('Action do formulário:', form.action);
|
||||
|
||||
// Remover listeners antigos para evitar duplicação
|
||||
const newForm = form.cloneNode(true);
|
||||
form.parentNode.replaceChild(newForm, form);
|
||||
|
||||
// Adicionar listener para o submit do formulário
|
||||
newForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário submetido');
|
||||
|
||||
// Criar FormData com os dados do formulário
|
||||
const formData = new FormData(this);
|
||||
|
||||
// Log dos dados sendo enviados
|
||||
console.log('Dados do formulário:');
|
||||
for (let [key, value] of formData.entries()) {
|
||||
console.log(key + ': ' + value);
|
||||
}
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(modalEditarPagamento);
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao atualizar pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao atualizar pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do modal de exclusão
|
||||
const modalExcluirPagamento = document.getElementById('modalExcluirPagamento');
|
||||
if (modalExcluirPagamento) {
|
||||
modalExcluirPagamento.addEventListener('show.bs.modal', function(event) {
|
||||
console.log('Modal de exclusão sendo exibido');
|
||||
const button = event.relatedTarget;
|
||||
|
||||
if (!button) {
|
||||
console.error('Botão não encontrado!');
|
||||
return;
|
||||
}
|
||||
|
||||
const pagamentoId = button.getAttribute('data-pagamento-id');
|
||||
const pagamentoInfo = button.getAttribute('data-pagamento-info');
|
||||
console.log('ID do pagamento:', pagamentoId);
|
||||
|
||||
// Atualizar informações no modal
|
||||
document.getElementById('pagamentoInfo').textContent = pagamentoInfo;
|
||||
|
||||
// Configurar formulário
|
||||
const form = document.getElementById('formExcluirPagamento');
|
||||
if (form) {
|
||||
form.action = `/pagamentos/excluir/${pagamentoId}`;
|
||||
console.log('Action do formulário:', form.action);
|
||||
|
||||
// Remover listeners antigos para evitar duplicação
|
||||
const newForm = form.cloneNode(true);
|
||||
form.parentNode.replaceChild(newForm, form);
|
||||
|
||||
// Adicionar listener para o submit do formulário
|
||||
newForm.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário submetido');
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST'
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(modalExcluirPagamento);
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao excluir pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao excluir pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do formulário de novo pagamento
|
||||
const formNovoPagamento = document.getElementById('formNovoPagamento');
|
||||
if (formNovoPagamento) {
|
||||
formNovoPagamento.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
console.log('Formulário de novo pagamento submetido');
|
||||
|
||||
// Criar FormData com os dados do formulário
|
||||
const formData = new FormData(this);
|
||||
|
||||
// Log dos dados sendo enviados
|
||||
console.log('Dados do formulário:');
|
||||
for (let [key, value] of formData.entries()) {
|
||||
console.log(key + ': ' + value);
|
||||
}
|
||||
|
||||
// Enviar requisição
|
||||
fetch(this.action, {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => {
|
||||
console.log('Status da resposta:', response.status);
|
||||
return response.json();
|
||||
})
|
||||
.then(data => {
|
||||
console.log('Resposta:', data);
|
||||
if (data.status === 'success') {
|
||||
// Fechar modal
|
||||
const modal = bootstrap.Modal.getInstance(document.getElementById('modalNovoPagamento'));
|
||||
modal.hide();
|
||||
|
||||
// Recarregar página
|
||||
window.location.reload();
|
||||
} else {
|
||||
alert('Erro ao adicionar pagamento: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao adicionar pagamento. Por favor, tente novamente.');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Configuração do botão de exportar
|
||||
const btnExportar = document.getElementById('btnExportar');
|
||||
if (btnExportar) {
|
||||
btnExportar.addEventListener('click', function() {
|
||||
console.log('Exportando dados...');
|
||||
|
||||
// Coletar dados da tabela
|
||||
const dados = [];
|
||||
table.rows().every(function() {
|
||||
const row = this.data();
|
||||
dados.push({
|
||||
militante: row[0],
|
||||
tipo_pagamento: row[1],
|
||||
valor: row[2].replace('R$ ', ''),
|
||||
data_pagamento: row[3]
|
||||
});
|
||||
});
|
||||
|
||||
// Converter para CSV
|
||||
const csv = [
|
||||
['Militante', 'Tipo de Pagamento', 'Valor', 'Data do Pagamento'],
|
||||
...dados.map(row => [
|
||||
row.militante,
|
||||
row.tipo_pagamento,
|
||||
row.valor,
|
||||
row.data_pagamento
|
||||
])
|
||||
]
|
||||
.map(row => row.join(','))
|
||||
.join('\n');
|
||||
|
||||
// Criar blob e fazer download
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const link = document.createElement('a');
|
||||
if (link.download !== undefined) {
|
||||
const url = URL.createObjectURL(blob);
|
||||
link.setAttribute('href', url);
|
||||
link.setAttribute('download', 'pagamentos.csv');
|
||||
link.style.visibility = 'hidden';
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Funções de validação e formatação de datas
|
||||
function validarData(data) {
|
||||
if (!data) return false;
|
||||
|
||||
const dataObj = new Date(data);
|
||||
if (isNaN(dataObj.getTime())) return false;
|
||||
|
||||
const hoje = new Date();
|
||||
hoje.setHours(0, 0, 0, 0);
|
||||
|
||||
return dataObj <= hoje;
|
||||
}
|
||||
|
||||
function formatarData(data) {
|
||||
if (!data) return '';
|
||||
|
||||
const dataObj = new Date(data);
|
||||
if (isNaN(dataObj.getTime())) return '';
|
||||
|
||||
return dataObj.toLocaleDateString('pt-BR');
|
||||
}
|
||||
|
||||
// Configurar campos de data
|
||||
const camposData = document.querySelectorAll('input[type="date"]');
|
||||
camposData.forEach(campo => {
|
||||
// Definir data máxima como hoje
|
||||
const hoje = new Date().toISOString().split('T')[0];
|
||||
campo.setAttribute('max', hoje);
|
||||
|
||||
campo.addEventListener('change', function() {
|
||||
if (!validarData(this.value)) {
|
||||
this.setCustomValidity('Data inválida ou futura');
|
||||
this.classList.add('is-invalid');
|
||||
} else {
|
||||
this.setCustomValidity('');
|
||||
this.classList.remove('is-invalid');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user