2025-04-03 15:05:48 -03:00
|
|
|
console.log('Carregando script militantes.js...');
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Constantes para responsabilidades
|
|
|
|
|
const Militante = {
|
|
|
|
|
RESPONSAVEL_FINANCAS: 256,
|
|
|
|
|
RESPONSAVEL_IMPRENSA: 512,
|
|
|
|
|
QUADRO_ORIENTADOR: 64,
|
|
|
|
|
SECRETARIO: 1,
|
|
|
|
|
TESOUREIRO: 2,
|
|
|
|
|
IMPRENSA: 4,
|
|
|
|
|
MNS: 8,
|
|
|
|
|
MPS: 16,
|
|
|
|
|
JUVENTUDE: 32,
|
|
|
|
|
ASPIRANTE: 128
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Função para obter o token CSRF da meta tag
|
|
|
|
|
function getCsrfToken() {
|
|
|
|
|
const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
|
|
|
|
if (!token) {
|
|
|
|
|
console.error('CSRF token não encontrado!');
|
|
|
|
|
return '';
|
|
|
|
|
}
|
|
|
|
|
return token;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Variáveis globais para controle dos filtros e paginação
|
2025-04-04 09:49:06 -03:00
|
|
|
let filtroAtual = 'todos';
|
|
|
|
|
let filtroResponsabilidade = null;
|
|
|
|
|
let filtroCelula = null;
|
2025-04-04 13:31:52 -03:00
|
|
|
let currentPage = 1;
|
|
|
|
|
let rowsPerPage = 20;
|
|
|
|
|
let totalRows = 0;
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Mapa de responsabilidades para valores numéricos
|
|
|
|
|
const RESPONSABILIDADES_MAP = {
|
2025-04-09 09:59:12 -03:00
|
|
|
'Secretário': 1,
|
2025-04-04 20:37:22 -03:00
|
|
|
'Tesoureiro': 2,
|
|
|
|
|
'Imprensa': 4,
|
|
|
|
|
'MNS': 8,
|
|
|
|
|
'MPS': 16,
|
|
|
|
|
'Juventude': 32,
|
|
|
|
|
'Quadro-Orientador': 64,
|
|
|
|
|
'Aspirante': 128,
|
2025-04-09 09:59:12 -03:00
|
|
|
'Responsável de Finanças': 256,
|
|
|
|
|
'Responsável de Imprensa': 512
|
2025-04-04 20:37:22 -03:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Mapa reverso para converter valores em nomes
|
|
|
|
|
const RESPONSABILIDADES_REVERSE_MAP = {
|
2025-04-09 09:59:12 -03:00
|
|
|
1: 'Secretário',
|
2025-04-04 20:37:22 -03:00
|
|
|
2: 'Tesoureiro',
|
|
|
|
|
4: 'Imprensa',
|
|
|
|
|
8: 'MNS',
|
|
|
|
|
16: 'MPS',
|
|
|
|
|
32: 'Juventude',
|
|
|
|
|
64: 'Quadro-Orientador',
|
|
|
|
|
128: 'Aspirante',
|
2025-04-09 09:59:12 -03:00
|
|
|
256: 'Responsável de Finanças',
|
|
|
|
|
512: 'Responsável de Imprensa'
|
2025-04-04 20:37:22 -03:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Função para validar data no formato DD/MM/YYYY
|
|
|
|
|
function validarData(data) {
|
|
|
|
|
if (!data) return true; // Campo vazio é válido
|
|
|
|
|
|
|
|
|
|
// Verifica o formato
|
|
|
|
|
if (!/^\d{2}\/\d{2}\/\d{4}$/.test(data)) return false;
|
|
|
|
|
|
|
|
|
|
// Extrai dia, mês e ano
|
|
|
|
|
const [dia, mes, ano] = data.split('/').map(Number);
|
|
|
|
|
|
|
|
|
|
// Cria um objeto Date
|
|
|
|
|
const dataObj = new Date(ano, mes - 1, dia);
|
|
|
|
|
|
|
|
|
|
// Verifica se a data é válida
|
|
|
|
|
return dataObj.getDate() === dia &&
|
|
|
|
|
dataObj.getMonth() === mes - 1 &&
|
|
|
|
|
dataObj.getFullYear() === ano &&
|
|
|
|
|
ano >= 1900 && ano <= 2100;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 15:54:26 -03:00
|
|
|
// Função para formatar data do formato ISO (YYYY-MM-DD) para DD/MM/YYYY
|
|
|
|
|
function formatarData(data) {
|
|
|
|
|
if (!data) return '';
|
|
|
|
|
const [ano, mes, dia] = data.split('-');
|
|
|
|
|
return `${dia}/${mes}/${ano}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para converter data de DD/MM/YYYY para YYYY-MM-DD
|
|
|
|
|
function converterDataParaISO(data) {
|
|
|
|
|
if (!data) return '';
|
2025-04-04 20:37:22 -03:00
|
|
|
if (data.includes('-')) return data;
|
2025-04-04 15:54:26 -03:00
|
|
|
const [dia, mes, ano] = data.split('/');
|
|
|
|
|
return `${ano}-${mes}-${dia}`;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Função para calcular o total de páginas
|
|
|
|
|
function calculateTotalPages() {
|
|
|
|
|
const allRows = document.querySelectorAll('#militantesTable tbody tr');
|
|
|
|
|
const visibleRows = Array.from(allRows).filter(row =>
|
|
|
|
|
!row.hasAttribute('data-filtered-out')
|
|
|
|
|
);
|
|
|
|
|
totalRows = visibleRows.length;
|
|
|
|
|
return Math.ceil(totalRows / rowsPerPage);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para atualizar o texto de contagem
|
|
|
|
|
function updateCountText() {
|
|
|
|
|
const allRows = document.querySelectorAll('#militantesTable tbody tr');
|
|
|
|
|
const visibleRows = Array.from(allRows).filter(row =>
|
|
|
|
|
!row.hasAttribute('data-filtered-out')
|
|
|
|
|
);
|
|
|
|
|
totalRows = visibleRows.length;
|
|
|
|
|
const startIndex = (currentPage - 1) * rowsPerPage + 1;
|
|
|
|
|
const endIndex = Math.min(currentPage * rowsPerPage, totalRows);
|
|
|
|
|
|
|
|
|
|
// Atualizar texto de contagem
|
|
|
|
|
document.getElementById('countMilitantes').textContent =
|
|
|
|
|
`${startIndex}-${endIndex} de ${totalRows}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para atualizar a paginação
|
|
|
|
|
function updatePagination() {
|
|
|
|
|
const totalPages = calculateTotalPages();
|
|
|
|
|
const paginationUl = document.querySelector('.pagination');
|
|
|
|
|
const prevPage = document.getElementById('prevPage');
|
|
|
|
|
const nextPage = document.getElementById('nextPage');
|
|
|
|
|
|
|
|
|
|
// Limpar páginas existentes (exceto prev e next)
|
|
|
|
|
const pageItems = paginationUl.querySelectorAll('li:not(#prevPage):not(#nextPage)');
|
|
|
|
|
pageItems.forEach(item => item.remove());
|
|
|
|
|
|
|
|
|
|
// Adicionar novas páginas
|
|
|
|
|
for (let i = 1; i <= totalPages; i++) {
|
|
|
|
|
const li = document.createElement('li');
|
|
|
|
|
li.className = `page-item${i === currentPage ? ' active' : ''}`;
|
|
|
|
|
li.innerHTML = `<a class="page-link" href="#">${i}</a>`;
|
|
|
|
|
li.addEventListener('click', (e) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
currentPage = i;
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
|
|
|
|
});
|
|
|
|
|
paginationUl.insertBefore(li, nextPage);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Atualizar estado dos botões prev/next
|
|
|
|
|
prevPage.classList.toggle('disabled', currentPage === 1);
|
|
|
|
|
nextPage.classList.toggle('disabled', currentPage === totalPages || totalPages === 0);
|
|
|
|
|
|
|
|
|
|
// Adicionar eventos aos botões prev/next
|
|
|
|
|
prevPage.onclick = (e) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
if (currentPage > 1) {
|
|
|
|
|
currentPage--;
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
nextPage.onclick = (e) => {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
if (currentPage < totalPages) {
|
|
|
|
|
currentPage++;
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Atualizar texto de contagem
|
|
|
|
|
updateCountText();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para atualizar as linhas visíveis
|
|
|
|
|
function updateVisibleRows() {
|
|
|
|
|
const allRows = document.querySelectorAll('#militantesTable tbody tr');
|
|
|
|
|
const visibleRows = Array.from(allRows).filter(row =>
|
|
|
|
|
!row.hasAttribute('data-filtered-out')
|
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
const startIndex = (currentPage - 1) * rowsPerPage;
|
|
|
|
|
const endIndex = startIndex + rowsPerPage;
|
|
|
|
|
|
|
|
|
|
visibleRows.forEach((row, index) => {
|
|
|
|
|
if (index >= startIndex && index < endIndex) {
|
|
|
|
|
row.style.display = '';
|
|
|
|
|
} else {
|
|
|
|
|
row.style.display = 'none';
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
updateCountText();
|
|
|
|
|
}
|
2025-04-04 09:49:06 -03:00
|
|
|
|
|
|
|
|
// Função para filtrar militantes
|
|
|
|
|
function filtrarMilitantes() {
|
|
|
|
|
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
|
|
|
|
|
const rows = document.querySelectorAll('#militantesTable tbody tr');
|
|
|
|
|
|
|
|
|
|
rows.forEach(row => {
|
|
|
|
|
let shouldShow = true;
|
|
|
|
|
|
|
|
|
|
// Filtro de texto
|
|
|
|
|
const textContent = row.textContent.toLowerCase();
|
|
|
|
|
if (!textContent.includes(searchTerm)) {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filtro de responsabilidades
|
|
|
|
|
if (filtroResponsabilidade) {
|
2025-04-04 20:37:22 -03:00
|
|
|
const responsabilidadeMap = {
|
2025-04-09 09:59:12 -03:00
|
|
|
'responsavel-financas': Militante.RESPONSAVEL_FINANCAS,
|
|
|
|
|
'responsavel-imprensa': Militante.RESPONSAVEL_IMPRENSA,
|
|
|
|
|
'quadro-orientador': Militante.QUADRO_ORIENTADOR,
|
|
|
|
|
'secretario': Militante.SECRETARIO,
|
|
|
|
|
'tesoureiro': Militante.TESOUREIRO,
|
|
|
|
|
'imprensa': Militante.IMPRENSA,
|
|
|
|
|
'mns': Militante.MNS,
|
|
|
|
|
'mps': Militante.MPS,
|
|
|
|
|
'juventude': Militante.JUVENTUDE,
|
|
|
|
|
'aspirante': Militante.ASPIRANTE
|
2025-04-04 20:37:22 -03:00
|
|
|
};
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
const valorResponsabilidade = responsabilidadeMap[filtroResponsabilidade];
|
|
|
|
|
const responsabilidades = parseInt(row.getAttribute('data-responsabilidades') || '0');
|
|
|
|
|
|
|
|
|
|
if ((responsabilidades & valorResponsabilidade) === 0) {
|
2025-04-04 09:49:06 -03:00
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filtro de célula
|
|
|
|
|
if (filtroCelula) {
|
2025-04-09 09:59:12 -03:00
|
|
|
const celula = row.querySelector('[data-celula-id]')?.getAttribute('data-celula-id');
|
2025-04-04 09:49:06 -03:00
|
|
|
if (celula !== filtroCelula) {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Marcar linha como filtrada ou não
|
|
|
|
|
if (shouldShow) {
|
|
|
|
|
row.removeAttribute('data-filtered-out');
|
2025-04-04 20:37:22 -03:00
|
|
|
row.style.display = '';
|
2025-04-04 13:31:52 -03:00
|
|
|
} else {
|
|
|
|
|
row.setAttribute('data-filtered-out', '');
|
|
|
|
|
row.style.display = 'none';
|
|
|
|
|
}
|
2025-04-04 09:49:06 -03:00
|
|
|
});
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Resetar para a primeira página e atualizar paginação
|
|
|
|
|
currentPage = 1;
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
|
|
|
|
|
2025-04-04 16:01:41 -03:00
|
|
|
// Função para configurar um campo de data
|
|
|
|
|
function configurarCampoData(campo) {
|
|
|
|
|
if (!campo) return;
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Remover campo de texto anterior se existir
|
|
|
|
|
const campoTextoExistente = campo.previousElementSibling;
|
|
|
|
|
if (campoTextoExistente && campoTextoExistente.classList.contains('campo-data-texto')) {
|
|
|
|
|
campoTextoExistente.remove();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Configurar o campo de data
|
2025-04-04 16:01:41 -03:00
|
|
|
campo.type = 'date';
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Se já tiver valor, garantir que está no formato ISO
|
2025-04-04 16:01:41 -03:00
|
|
|
if (campo.value) {
|
2025-04-04 20:37:22 -03:00
|
|
|
campo.value = converterDataParaISO(campo.value);
|
2025-04-04 16:01:41 -03:00
|
|
|
}
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Quando o valor mudar, garantir formato ISO
|
2025-04-04 16:01:41 -03:00
|
|
|
campo.addEventListener('change', function() {
|
2025-04-04 20:37:22 -03:00
|
|
|
if (this.value) {
|
|
|
|
|
this.value = converterDataParaISO(this.value);
|
|
|
|
|
}
|
2025-04-04 16:01:41 -03:00
|
|
|
});
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para carregar os dados do militante no modal de edição
|
2025-04-09 09:59:12 -03:00
|
|
|
async function carregarDadosMilitante(militanteId) {
|
|
|
|
|
try {
|
|
|
|
|
console.log('Carregando dados do militante:', militanteId);
|
|
|
|
|
const response = await fetch(`/militantes/dados/${militanteId}`);
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
|
|
if (data.status === 'error') {
|
|
|
|
|
throw new Error(data.message);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
console.log('Dados recebidos:', data);
|
|
|
|
|
|
|
|
|
|
// Mapear campos básicos
|
|
|
|
|
const campos = [
|
|
|
|
|
'nome', 'cpf', 'titulo_eleitoral', 'data_nascimento', 'data_entrada_oci',
|
|
|
|
|
'data_efetivacao_oci', 'telefone1', 'telefone2', 'profissao',
|
|
|
|
|
'regime_trabalho', 'empresa', 'contratante', 'instituicao_ensino',
|
|
|
|
|
'tipo_instituicao', 'sindicato', 'cargo_sindical', 'central_sindical',
|
|
|
|
|
'dirigente_sindical'
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
campos.forEach(campo => {
|
|
|
|
|
const elemento = document.getElementById(`edit_${campo}`);
|
|
|
|
|
if (elemento) {
|
|
|
|
|
if (elemento.type === 'checkbox') {
|
|
|
|
|
elemento.checked = data[campo];
|
2025-04-04 20:37:22 -03:00
|
|
|
} else {
|
2025-04-09 09:59:12 -03:00
|
|
|
elemento.value = data[campo] || '';
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Preencher o email (primeiro email da lista)
|
|
|
|
|
const emailElement = document.getElementById('edit_email');
|
|
|
|
|
if (emailElement) {
|
|
|
|
|
if (data.emails && data.emails.length > 0) {
|
2025-04-07 03:42:01 -03:00
|
|
|
emailElement.value = data.emails[0]; // O email já vem como string
|
2025-04-09 09:59:12 -03:00
|
|
|
} else {
|
|
|
|
|
emailElement.value = '';
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mapear campos de endereço
|
|
|
|
|
if (data.endereco) {
|
|
|
|
|
const camposEndereco = ['cep', 'estado', 'cidade', 'bairro', 'rua', 'numero', 'complemento'];
|
|
|
|
|
camposEndereco.forEach(campo => {
|
|
|
|
|
const elemento = document.getElementById(`edit_${campo}`);
|
|
|
|
|
if (elemento) {
|
|
|
|
|
elemento.value = data.endereco[campo] || '';
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
});
|
2025-04-09 09:59:12 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mapear estado
|
|
|
|
|
const selectEstado = document.getElementById('edit_estado');
|
|
|
|
|
if (selectEstado && data.estado) {
|
|
|
|
|
selectEstado.value = data.estado;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mapear célula
|
|
|
|
|
const selectCelula = document.getElementById('edit_celula_id');
|
|
|
|
|
if (selectCelula && data.celula_id) {
|
|
|
|
|
selectCelula.value = data.celula_id;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Processar responsabilidades
|
|
|
|
|
if (data.responsabilidades_valor !== undefined) {
|
|
|
|
|
console.log('Valor das responsabilidades:', data.responsabilidades_valor);
|
2025-04-04 20:37:22 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Resetar todas as badges para seu estado inicial
|
|
|
|
|
document.querySelectorAll('.badge-clickable').forEach(badge => {
|
2025-04-04 20:37:22 -03:00
|
|
|
badge.classList.remove('active');
|
2025-04-09 09:59:12 -03:00
|
|
|
const originalClass = badge.getAttribute('data-original-class');
|
|
|
|
|
if (originalClass) {
|
|
|
|
|
badge.className = `badge badge-clickable ${originalClass}`;
|
|
|
|
|
}
|
2025-04-04 20:37:22 -03:00
|
|
|
});
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Ativar as badges correspondentes
|
|
|
|
|
document.querySelectorAll('.badge-clickable').forEach(badge => {
|
|
|
|
|
const valor = parseInt(badge.getAttribute('data-value'));
|
|
|
|
|
if (!isNaN(valor) && (data.responsabilidades_valor & valor)) {
|
2025-04-04 20:37:22 -03:00
|
|
|
badge.classList.add('active');
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Atualizar o campo hidden com o valor total
|
|
|
|
|
document.getElementById('responsabilidades_values').value = data.responsabilidades_valor;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Erro ao carregar dados:', error);
|
|
|
|
|
alert('Erro ao carregar dados do militante');
|
|
|
|
|
}
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para mostrar alertas
|
2025-04-09 09:59:12 -03:00
|
|
|
function mostrarAlerta(mensagem, tipo) {
|
|
|
|
|
const alertDiv = document.createElement('div');
|
|
|
|
|
alertDiv.className = `alert alert-${tipo} alert-dismissible fade show`;
|
|
|
|
|
alertDiv.role = 'alert';
|
|
|
|
|
alertDiv.innerHTML = `
|
|
|
|
|
${mensagem}
|
|
|
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
2025-04-04 20:37:22 -03:00
|
|
|
`;
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
const container = document.querySelector('.container');
|
|
|
|
|
container.insertBefore(alertDiv, container.firstChild);
|
2025-04-04 20:37:22 -03:00
|
|
|
|
|
|
|
|
// Remover o alerta após 5 segundos
|
|
|
|
|
setTimeout(() => {
|
2025-04-09 09:59:12 -03:00
|
|
|
alertDiv.remove();
|
2025-04-04 20:37:22 -03:00
|
|
|
}, 5000);
|
2025-04-04 16:01:41 -03:00
|
|
|
}
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Configurar o token CSRF para todas as requisições AJAX
|
|
|
|
|
$.ajaxSetup({
|
|
|
|
|
beforeSend: function(xhr, settings) {
|
|
|
|
|
if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
|
|
|
|
|
xhr.setRequestHeader("X-CSRFToken", getCsrfToken());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-04 09:49:06 -03:00
|
|
|
// Configurar eventos quando o DOM estiver carregado
|
2025-04-03 15:05:48 -03:00
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('DOM carregado, configurando eventos...');
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Configurar seletor de linhas por página
|
|
|
|
|
const rowsPerPageSelect = document.getElementById('rowsPerPage');
|
|
|
|
|
if (rowsPerPageSelect) {
|
|
|
|
|
rowsPerPageSelect.addEventListener('change', function() {
|
|
|
|
|
rowsPerPage = parseInt(this.value);
|
|
|
|
|
currentPage = 1;
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 09:49:06 -03:00
|
|
|
// Configurar pesquisa
|
|
|
|
|
const searchInput = document.getElementById('searchInput');
|
|
|
|
|
if (searchInput) {
|
|
|
|
|
let timeoutId;
|
|
|
|
|
searchInput.addEventListener('input', function() {
|
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
|
timeoutId = setTimeout(filtrarMilitantes, 300);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Configurar filtros
|
|
|
|
|
document.querySelectorAll('.dropdown-item[data-filter]').forEach(item => {
|
|
|
|
|
item.addEventListener('click', function(e) {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
|
|
|
|
|
const filter = this.getAttribute('data-filter');
|
|
|
|
|
const celula = this.getAttribute('data-celula');
|
|
|
|
|
|
|
|
|
|
// Resetar filtros anteriores
|
|
|
|
|
if (filter === 'todos') {
|
|
|
|
|
filtroAtual = 'todos';
|
|
|
|
|
filtroResponsabilidade = null;
|
|
|
|
|
filtroCelula = null;
|
2025-04-04 20:37:22 -03:00
|
|
|
} else if (['responsavel-financas', 'responsavel-imprensa', 'quadro-orientador'].includes(filter)) {
|
2025-04-04 09:49:06 -03:00
|
|
|
filtroAtual = 'todos';
|
2025-04-04 20:37:22 -03:00
|
|
|
filtroResponsabilidade = filter === 'responsavel-financas' ? 'Responsável de Finanças' :
|
|
|
|
|
filter === 'responsavel-imprensa' ? 'Responsável de Imprensa' :
|
2025-04-04 09:49:06 -03:00
|
|
|
'Quadro-Orientador';
|
|
|
|
|
filtroCelula = null;
|
|
|
|
|
} else if (filter === 'celula') {
|
|
|
|
|
filtroAtual = 'todos';
|
|
|
|
|
filtroResponsabilidade = null;
|
|
|
|
|
filtroCelula = celula;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
filtrarMilitantes();
|
|
|
|
|
|
|
|
|
|
// Atualizar texto do botão de filtro
|
|
|
|
|
const filterText = this.textContent;
|
|
|
|
|
const dropdownButton = document.querySelector('.dropdown-toggle');
|
|
|
|
|
dropdownButton.innerHTML = `<i class="fas fa-filter me-2"></i>${filterText}`;
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('Configurando modal de edição...');
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Configurar máscara para campos de data
|
|
|
|
|
$('.date-mask').mask('00/00/0000', {
|
|
|
|
|
placeholder: 'DD/MM/AAAA',
|
|
|
|
|
clearIfNotMatch: true
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Validar campos de data quando perderem o foco
|
|
|
|
|
$('.date-mask').on('blur', function() {
|
|
|
|
|
const valor = $(this).val();
|
|
|
|
|
if (valor && !validarData(valor)) {
|
|
|
|
|
$(this).addClass('is-invalid');
|
|
|
|
|
if (!$(this).next('.invalid-feedback').length) {
|
|
|
|
|
$(this).after('<div class="invalid-feedback">Data inválida</div>');
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
$(this).removeClass('is-invalid');
|
|
|
|
|
$(this).next('.invalid-feedback').remove();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-04 16:03:36 -03:00
|
|
|
// Configurar campos de data em todos os modais
|
|
|
|
|
const modalNovoMilitante = document.getElementById('modalNovoMilitante');
|
2025-04-03 15:05:48 -03:00
|
|
|
const modalEditarMilitante = document.getElementById('modalEditarMilitante');
|
2025-04-04 16:03:36 -03:00
|
|
|
|
|
|
|
|
// Configurar modal de edição
|
2025-04-03 15:05:48 -03:00
|
|
|
if (modalEditarMilitante) {
|
2025-04-09 09:59:12 -03:00
|
|
|
modalEditarMilitante.addEventListener('show.bs.modal', async function(event) {
|
|
|
|
|
console.log('Modal de edição aberto');
|
2025-04-04 12:15:19 -03:00
|
|
|
const button = event.relatedTarget;
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
if (!button) {
|
|
|
|
|
console.error('Botão não encontrado');
|
|
|
|
|
alert('Erro ao abrir modal: botão não encontrado');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-03 15:05:48 -03:00
|
|
|
const militanteId = button.getAttribute('data-militante-id');
|
2025-04-04 11:37:48 -03:00
|
|
|
const militanteNome = button.getAttribute('data-militante-nome');
|
2025-04-04 12:15:19 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
console.log('Dados do botão:', { militanteId, militanteNome });
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
if (!militanteId) {
|
|
|
|
|
console.error('ID do militante não encontrado no botão');
|
|
|
|
|
alert('Erro ao abrir modal: ID do militante não encontrado');
|
|
|
|
|
return;
|
2025-04-04 11:37:48 -03:00
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-04 12:15:19 -03:00
|
|
|
// Definir o ID do militante no campo hidden
|
|
|
|
|
const idField = document.getElementById('edit_militante_id');
|
2025-04-09 09:59:12 -03:00
|
|
|
if (!idField) {
|
|
|
|
|
console.error('Campo hidden para ID do militante não encontrado');
|
|
|
|
|
alert('Erro ao abrir modal: campo para ID do militante não encontrado');
|
|
|
|
|
return;
|
2025-04-04 11:37:48 -03:00
|
|
|
}
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
idField.value = militanteId;
|
|
|
|
|
console.log('ID do militante definido:', idField.value);
|
|
|
|
|
|
|
|
|
|
// Atualizar título do modal
|
|
|
|
|
const modalTitle = this.querySelector('.modal-title');
|
|
|
|
|
if (modalTitle) {
|
|
|
|
|
modalTitle.textContent = `Editar ${militanteNome}`;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
// Carregar dados do militante
|
|
|
|
|
const response = await fetch(`/militantes/dados/${militanteId}`);
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
throw new Error(`Erro HTTP: ${response.status}`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
console.log('Dados recebidos:', data);
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
if (data.status === 'error') {
|
|
|
|
|
throw new Error(data.message || 'Erro ao carregar dados do militante');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mapear campos básicos
|
|
|
|
|
const campos = [
|
|
|
|
|
'nome', 'cpf', 'titulo_eleitoral', 'data_nascimento', 'data_entrada_oci',
|
|
|
|
|
'data_efetivacao_oci', 'telefone1', 'telefone2', 'profissao',
|
|
|
|
|
'regime_trabalho', 'empresa', 'contratante', 'instituicao_ensino',
|
|
|
|
|
'tipo_instituicao', 'sindicato', 'cargo_sindical', 'central_sindical',
|
|
|
|
|
'dirigente_sindical'
|
|
|
|
|
];
|
2025-04-04 16:01:41 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
campos.forEach(campo => {
|
|
|
|
|
const elemento = document.getElementById(`edit_${campo}`);
|
|
|
|
|
if (elemento) {
|
|
|
|
|
if (elemento.type === 'checkbox') {
|
|
|
|
|
elemento.checked = data[campo];
|
|
|
|
|
} else {
|
|
|
|
|
elemento.value = data[campo] || '';
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 12:15:19 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Preencher o email (primeiro email da lista)
|
|
|
|
|
const emailElement = document.getElementById('edit_email');
|
|
|
|
|
if (emailElement) {
|
|
|
|
|
if (data.emails && data.emails.length > 0) {
|
2025-04-07 03:42:01 -03:00
|
|
|
emailElement.value = data.emails[0]; // O email já vem como string
|
2025-04-09 09:59:12 -03:00
|
|
|
} else {
|
|
|
|
|
emailElement.value = '';
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
}
|
2025-04-04 12:15:19 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Mapear campos de endereço
|
|
|
|
|
if (data.endereco) {
|
|
|
|
|
const camposEndereco = ['cep', 'estado', 'cidade', 'bairro', 'rua', 'numero', 'complemento'];
|
|
|
|
|
camposEndereco.forEach(campo => {
|
|
|
|
|
const elemento = document.getElementById(`edit_${campo}`);
|
|
|
|
|
if (elemento) {
|
|
|
|
|
elemento.value = data.endereco[campo] || '';
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
2025-04-04 11:37:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Mapear estado
|
|
|
|
|
const selectEstado = document.getElementById('edit_estado');
|
|
|
|
|
if (selectEstado && data.estado) {
|
|
|
|
|
selectEstado.value = data.estado;
|
|
|
|
|
}
|
2025-04-04 11:37:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Mapear célula
|
|
|
|
|
const selectCelula = document.getElementById('edit_celula_id');
|
|
|
|
|
if (selectCelula && data.celula_id) {
|
|
|
|
|
selectCelula.value = data.celula_id;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Processar responsabilidades
|
|
|
|
|
if (data.responsabilidades_valor !== undefined) {
|
|
|
|
|
console.log('Valor das responsabilidades:', data.responsabilidades_valor);
|
|
|
|
|
|
|
|
|
|
// Resetar todas as badges para seu estado inicial
|
|
|
|
|
document.querySelectorAll('.badge-clickable').forEach(badge => {
|
|
|
|
|
badge.classList.remove('active');
|
|
|
|
|
const originalClass = badge.getAttribute('data-original-class');
|
|
|
|
|
if (originalClass) {
|
|
|
|
|
badge.className = `badge badge-clickable ${originalClass}`;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Ativar as badges correspondentes
|
|
|
|
|
document.querySelectorAll('.badge-clickable').forEach(badge => {
|
|
|
|
|
const valor = parseInt(badge.getAttribute('data-value'));
|
|
|
|
|
if (!isNaN(valor) && (data.responsabilidades_valor & valor)) {
|
|
|
|
|
badge.classList.add('active');
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Atualizar o campo hidden com o valor total
|
|
|
|
|
document.getElementById('responsabilidades_values').value = data.responsabilidades_valor;
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Erro ao carregar dados:', error);
|
|
|
|
|
alert('Erro ao carregar dados do militante');
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Configurar clique nas badges
|
|
|
|
|
document.querySelectorAll('.badge-clickable').forEach(badge => {
|
|
|
|
|
badge.addEventListener('click', function() {
|
|
|
|
|
// Toggle classe active
|
|
|
|
|
this.classList.toggle('active');
|
2025-04-04 20:37:22 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Atualizar classes visuais
|
|
|
|
|
if (this.classList.contains('active')) {
|
|
|
|
|
const originalClass = this.getAttribute('data-original-class');
|
|
|
|
|
this.className = `badge badge-clickable ${originalClass} active`;
|
|
|
|
|
} else {
|
|
|
|
|
const originalClass = this.getAttribute('data-original-class');
|
|
|
|
|
this.className = `badge badge-clickable ${originalClass}`;
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
// Atualizar o valor total das responsabilidades
|
|
|
|
|
let valorTotal = 0;
|
|
|
|
|
document.querySelectorAll('.badge-clickable.active').forEach(activeBadge => {
|
|
|
|
|
const valor = parseInt(activeBadge.getAttribute('data-value'));
|
|
|
|
|
if (!isNaN(valor)) {
|
|
|
|
|
valorTotal |= valor;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Atualizar o campo hidden
|
|
|
|
|
const responsabilidadesInput = document.getElementById('responsabilidades_values');
|
|
|
|
|
if (responsabilidadesInput) {
|
|
|
|
|
responsabilidadesInput.value = valorTotal;
|
|
|
|
|
console.log('Valor total das responsabilidades atualizado:', valorTotal);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
2025-04-04 20:37:22 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Configurar formulário de edição
|
|
|
|
|
const formEditarMilitante = document.getElementById('formEditarMilitante');
|
|
|
|
|
if (formEditarMilitante) {
|
|
|
|
|
formEditarMilitante.addEventListener('submit', async function(event) {
|
|
|
|
|
event.preventDefault();
|
|
|
|
|
console.log('Formulário de edição enviado');
|
2025-04-07 03:42:01 -03:00
|
|
|
|
|
|
|
|
// Validar todos os campos antes do envio
|
|
|
|
|
const form = this;
|
|
|
|
|
form.classList.add('was-validated');
|
|
|
|
|
|
|
|
|
|
// Verificar se o formulário é válido
|
|
|
|
|
if (!form.checkValidity()) {
|
|
|
|
|
event.stopPropagation();
|
|
|
|
|
|
|
|
|
|
// Encontrar o primeiro campo inválido
|
|
|
|
|
const invalidField = form.querySelector(':invalid');
|
|
|
|
|
if (invalidField) {
|
|
|
|
|
// Encontrar a aba que contém o campo inválido
|
|
|
|
|
const tabPane = invalidField.closest('.tab-pane');
|
|
|
|
|
if (tabPane) {
|
|
|
|
|
// Ativar a aba
|
|
|
|
|
const tabId = tabPane.id;
|
|
|
|
|
const tab = document.querySelector(`button[data-bs-target="#${tabId}"]`);
|
|
|
|
|
if (tab) {
|
|
|
|
|
const bsTab = new bootstrap.Tab(tab);
|
|
|
|
|
bsTab.show();
|
|
|
|
|
|
|
|
|
|
// Focar no campo inválido após a aba ser exibida
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
invalidField.focus();
|
|
|
|
|
}, 200);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
|
2025-04-07 03:42:01 -03:00
|
|
|
// Se chegou aqui, o formulário é válido
|
2025-04-09 09:59:12 -03:00
|
|
|
// Obter ID do militante
|
2025-04-04 20:37:22 -03:00
|
|
|
const militanteId = document.getElementById('edit_militante_id').value;
|
2025-04-09 09:59:12 -03:00
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
if (!militanteId) {
|
2025-04-09 09:59:12 -03:00
|
|
|
console.error('ID do militante não encontrado');
|
|
|
|
|
alert('Erro ao salvar: ID do militante não encontrado');
|
2025-04-04 11:37:48 -03:00
|
|
|
return;
|
|
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
// Criar FormData com todos os campos
|
2025-04-07 03:42:01 -03:00
|
|
|
const formData = new FormData(form);
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
// Garantir que o valor das responsabilidades seja enviado
|
|
|
|
|
const responsabilidadesValue = document.getElementById('responsabilidades_values').value;
|
|
|
|
|
formData.set('responsabilidades_valor', responsabilidadesValue);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const url = `/militantes/editar/${militanteId}`;
|
2025-04-07 03:42:01 -03:00
|
|
|
const csrfToken = document.querySelector('input[name="csrf_token"]').value;
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
const response = await fetch(url, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
|
|
|
|
'X-Requested-With': 'XMLHttpRequest',
|
2025-04-07 03:42:01 -03:00
|
|
|
'X-CSRF-Token': csrfToken
|
2025-04-09 09:59:12 -03:00
|
|
|
},
|
|
|
|
|
body: formData
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
if (!response.ok) {
|
2025-04-09 09:59:12 -03:00
|
|
|
throw new Error(`Erro HTTP: ${response.status}`);
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
|
|
if (data.status === 'success') {
|
2025-04-04 20:37:22 -03:00
|
|
|
const modal = bootstrap.Modal.getInstance(document.getElementById('modalEditarMilitante'));
|
2025-04-09 09:59:12 -03:00
|
|
|
modal.hide();
|
|
|
|
|
mostrarAlerta('Militante atualizado com sucesso!', 'success');
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
location.reload();
|
|
|
|
|
}, 1000);
|
2025-04-03 15:05:48 -03:00
|
|
|
} else {
|
2025-04-09 09:59:12 -03:00
|
|
|
throw new Error(data.message || 'Erro desconhecido ao salvar militante');
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
2025-04-09 09:59:12 -03:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Erro ao salvar:', error);
|
|
|
|
|
mostrarAlerta(`Erro ao salvar militante: ${error.message}`, 'danger');
|
|
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Limpar alertas quando o modal for fechado
|
|
|
|
|
modalEditarMilitante.addEventListener('hidden.bs.modal', function () {
|
|
|
|
|
const alerts = this.querySelectorAll('.alert');
|
|
|
|
|
alerts.forEach(alert => alert.remove());
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
console.error('Modal de edição não encontrado!');
|
|
|
|
|
}
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Ajustar o formulário de novo militante
|
2025-04-03 15:05:48 -03:00
|
|
|
const formNovoMilitante = document.getElementById('formNovoMilitante');
|
|
|
|
|
if (formNovoMilitante) {
|
|
|
|
|
formNovoMilitante.addEventListener('submit', function(e) {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Validar todas as datas antes do envio
|
|
|
|
|
const camposData = this.querySelectorAll('.date-mask');
|
|
|
|
|
let datasValidas = true;
|
|
|
|
|
|
|
|
|
|
camposData.forEach(campo => {
|
|
|
|
|
const valor = campo.value;
|
|
|
|
|
if (valor && !validarData(valor)) {
|
|
|
|
|
datasValidas = false;
|
|
|
|
|
$(campo).addClass('is-invalid');
|
|
|
|
|
if (!$(campo).next('.invalid-feedback').length) {
|
|
|
|
|
$(campo).after('<div class="invalid-feedback">Data inválida</div>');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!datasValidas) {
|
|
|
|
|
return; // Não envia o formulário se houver datas inválidas
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Converter datas para formato ISO antes do envio
|
|
|
|
|
camposData.forEach(campo => {
|
|
|
|
|
if (campo.value) {
|
|
|
|
|
campo.value = converterDataParaISO(campo.value);
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 16:01:41 -03:00
|
|
|
|
2025-04-03 15:05:48 -03:00
|
|
|
const formData = new FormData(this);
|
|
|
|
|
|
|
|
|
|
fetch(this.action, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: {
|
2025-04-09 09:59:12 -03:00
|
|
|
'X-Requested-With': 'XMLHttpRequest',
|
|
|
|
|
'X-CSRF-Token': getCsrfToken()
|
|
|
|
|
},
|
|
|
|
|
body: formData
|
2025-04-03 15:05:48 -03:00
|
|
|
})
|
|
|
|
|
.then(response => response.json())
|
|
|
|
|
.then(data => {
|
|
|
|
|
if (data.status === 'success') {
|
|
|
|
|
// Fechar o modal
|
2025-04-04 16:03:36 -03:00
|
|
|
const modal = bootstrap.Modal.getInstance(modalNovoMilitante);
|
2025-04-03 15:05:48 -03:00
|
|
|
modal.hide();
|
|
|
|
|
|
|
|
|
|
// Limpar o formulário
|
|
|
|
|
formNovoMilitante.reset();
|
|
|
|
|
|
|
|
|
|
// Adicionar o novo militante à tabela
|
|
|
|
|
const tbody = document.querySelector('#militantesTable tbody');
|
|
|
|
|
const tr = document.createElement('tr');
|
|
|
|
|
tr.setAttribute('data-militante', data.militante.id);
|
|
|
|
|
tr.setAttribute('data-filiado', data.militante.filiado ? 'sim' : 'nao');
|
|
|
|
|
|
|
|
|
|
tr.innerHTML = `
|
|
|
|
|
<td data-nome="${data.militante.nome}">${data.militante.nome}</td>
|
|
|
|
|
<td data-cpf="${data.militante.cpf}">${data.militante.cpf}</td>
|
2025-04-09 09:59:12 -03:00
|
|
|
<td data-email="${data.militante.emails && data.militante.emails.length > 0 ? data.militante.emails[0].endereco_email : ''}">${data.militante.emails && data.militante.emails.length > 0 ? data.militante.emails[0].endereco_email : ''}</td>
|
|
|
|
|
<td data-telefone="${data.militante.telefone1}">${data.militante.telefone1}</td>
|
2025-04-03 15:05:48 -03:00
|
|
|
<td data-filiado="${data.militante.filiado}">
|
|
|
|
|
<span class="badge ${data.militante.filiado ? 'bg-success' : 'bg-secondary'}">
|
|
|
|
|
${data.militante.filiado ? 'Sim' : 'Não'}
|
|
|
|
|
</span>
|
|
|
|
|
</td>
|
|
|
|
|
<td class="text-end">
|
|
|
|
|
<div class="btn-group">
|
|
|
|
|
<button type="button"
|
|
|
|
|
class="btn btn-sm btn-outline-primary"
|
|
|
|
|
data-bs-toggle="modal"
|
|
|
|
|
data-bs-target="#modalEditarMilitante"
|
|
|
|
|
data-militante-id="${data.militante.id}"
|
|
|
|
|
data-militante-nome="${data.militante.nome}"
|
|
|
|
|
data-militante-cpf="${data.militante.cpf}"
|
2025-04-09 09:59:12 -03:00
|
|
|
data-militante-email="${data.militante.emails && data.militante.emails.length > 0 ? data.militante.emails[0].endereco_email : ''}"
|
|
|
|
|
data-militante-telefone="${data.militante.telefone1}"
|
2025-04-03 15:05:48 -03:00
|
|
|
data-militante-endereco="${data.militante.endereco}"
|
|
|
|
|
data-militante-filiado="${data.militante.filiado}"
|
|
|
|
|
title="Editar">
|
|
|
|
|
<i class="fas fa-edit"></i>
|
|
|
|
|
</button>
|
|
|
|
|
<button type="button"
|
|
|
|
|
class="btn btn-sm btn-outline-danger"
|
|
|
|
|
data-bs-toggle="modal"
|
|
|
|
|
data-bs-target="#deleteModal"
|
|
|
|
|
data-militante-id="${data.militante.id}"
|
|
|
|
|
data-militante-nome="${data.militante.nome}"
|
|
|
|
|
title="Excluir">
|
|
|
|
|
<i class="fas fa-trash"></i>
|
|
|
|
|
</button>
|
|
|
|
|
</div>
|
|
|
|
|
</td>
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
// Inserir no início da tabela
|
|
|
|
|
tbody.insertBefore(tr, tbody.firstChild);
|
|
|
|
|
|
|
|
|
|
// Atualizar contador
|
|
|
|
|
const countElement = document.getElementById('countMilitantes');
|
|
|
|
|
countElement.textContent = parseInt(countElement.textContent) + 1;
|
|
|
|
|
|
|
|
|
|
// Mostrar mensagem de sucesso
|
|
|
|
|
const alertDiv = document.createElement('div');
|
|
|
|
|
alertDiv.className = 'alert alert-success alert-dismissible fade show';
|
|
|
|
|
alertDiv.innerHTML = `
|
|
|
|
|
${data.message}
|
|
|
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
|
|
|
`;
|
|
|
|
|
document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.container').firstChild);
|
|
|
|
|
} else {
|
|
|
|
|
// Mostrar erro
|
|
|
|
|
const alertDiv = document.createElement('div');
|
|
|
|
|
alertDiv.className = 'alert alert-danger alert-dismissible fade show';
|
|
|
|
|
alertDiv.innerHTML = `
|
|
|
|
|
${data.message}
|
|
|
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
|
|
|
`;
|
|
|
|
|
document.querySelector('.modal-body').insertBefore(alertDiv, formNovoMilitante);
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.catch(error => {
|
|
|
|
|
console.error('Erro:', error);
|
|
|
|
|
// Mostrar erro genérico
|
|
|
|
|
const alertDiv = document.createElement('div');
|
|
|
|
|
alertDiv.className = 'alert alert-danger alert-dismissible fade show';
|
|
|
|
|
alertDiv.innerHTML = `
|
|
|
|
|
Erro ao cadastrar militante. Tente novamente.
|
|
|
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
|
|
|
`;
|
|
|
|
|
document.querySelector('.modal-body').insertBefore(alertDiv, formNovoMilitante);
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Máscara para CPF
|
2025-04-04 11:37:48 -03:00
|
|
|
const cpfInputs = document.querySelectorAll('input[name="cpf"]');
|
|
|
|
|
cpfInputs.forEach(input => {
|
|
|
|
|
input.addEventListener('input', function(e) {
|
2025-04-03 15:05:48 -03:00
|
|
|
let value = e.target.value.replace(/\D/g, '');
|
|
|
|
|
if (value.length <= 11) {
|
2025-04-04 11:37:48 -03:00
|
|
|
value = value.replace(/(\d{3})(\d)/, '$1.$2');
|
|
|
|
|
value = value.replace(/(\d{3})(\d)/, '$1.$2');
|
|
|
|
|
value = value.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
|
2025-04-03 15:05:48 -03:00
|
|
|
e.target.value = value;
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 11:37:48 -03:00
|
|
|
});
|
2025-04-03 15:05:48 -03:00
|
|
|
|
|
|
|
|
// Máscara para telefone
|
2025-04-04 11:37:48 -03:00
|
|
|
const telefoneInputs = document.querySelectorAll('input[name="telefone1"], input[name="telefone2"]');
|
|
|
|
|
telefoneInputs.forEach(input => {
|
|
|
|
|
input.addEventListener('input', function(e) {
|
2025-04-03 15:05:48 -03:00
|
|
|
let value = e.target.value.replace(/\D/g, '');
|
|
|
|
|
if (value.length <= 11) {
|
2025-04-04 11:37:48 -03:00
|
|
|
value = value.replace(/(\d{2})(\d)/, '($1) $2');
|
|
|
|
|
value = value.replace(/(\d{4,5})(\d{4})$/, '$1-$2');
|
2025-04-03 15:05:48 -03:00
|
|
|
e.target.value = value;
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 11:37:48 -03:00
|
|
|
});
|
2025-04-03 15:05:48 -03:00
|
|
|
|
|
|
|
|
// Configuração do modal de exclusão
|
|
|
|
|
const deleteModal = document.getElementById('deleteModal');
|
|
|
|
|
if (deleteModal) {
|
|
|
|
|
deleteModal.addEventListener('show.bs.modal', function(event) {
|
|
|
|
|
const button = event.relatedTarget;
|
|
|
|
|
const militanteId = button.getAttribute('data-militante-id');
|
|
|
|
|
const militanteNome = button.getAttribute('data-militante-nome');
|
|
|
|
|
|
|
|
|
|
document.getElementById('militanteNome').textContent = militanteNome;
|
|
|
|
|
document.getElementById('deleteForm').action = `/militantes/excluir/${militanteId}`;
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Ordenação
|
|
|
|
|
const headers = document.querySelectorAll('#militantesTable th[data-sort]');
|
|
|
|
|
headers.forEach(header => {
|
|
|
|
|
header.addEventListener('click', function() {
|
|
|
|
|
const column = this.getAttribute('data-sort');
|
|
|
|
|
const tbody = document.querySelector('#militantesTable tbody');
|
|
|
|
|
const rows = Array.from(tbody.querySelectorAll('tr'));
|
|
|
|
|
const isAsc = !this.classList.contains('sort-asc');
|
|
|
|
|
|
|
|
|
|
// Remover classes de ordenação de todos os headers
|
|
|
|
|
headers.forEach(h => {
|
|
|
|
|
h.classList.remove('sort-asc', 'sort-desc');
|
|
|
|
|
h.querySelector('i').className = 'fas fa-sort';
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Adicionar classe de ordenação ao header clicado
|
|
|
|
|
this.classList.add(isAsc ? 'sort-asc' : 'sort-desc');
|
|
|
|
|
this.querySelector('i').className = `fas fa-sort-${isAsc ? 'up' : 'down'}`;
|
|
|
|
|
|
|
|
|
|
// Ordenar linhas
|
|
|
|
|
rows.sort((a, b) => {
|
|
|
|
|
const aVal = a.querySelector(`td[data-${column}]`).getAttribute(`data-${column}`);
|
|
|
|
|
const bVal = b.querySelector(`td[data-${column}]`).getAttribute(`data-${column}`);
|
|
|
|
|
return isAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Reposicionar linhas
|
|
|
|
|
rows.forEach(row => tbody.appendChild(row));
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Exportar para CSV
|
|
|
|
|
const btnExportar = document.getElementById('btnExportar');
|
|
|
|
|
if (btnExportar) {
|
|
|
|
|
btnExportar.addEventListener('click', function() {
|
|
|
|
|
const rows = document.querySelectorAll('#militantesTable tbody tr:not([style*="display: none"])');
|
|
|
|
|
const headers = ['Nome', 'CPF', 'Email', 'Telefone', 'Filiado'];
|
|
|
|
|
let csv = headers.join(',') + '\n';
|
|
|
|
|
|
|
|
|
|
rows.forEach(row => {
|
|
|
|
|
const cols = row.querySelectorAll('td');
|
|
|
|
|
const values = [
|
|
|
|
|
cols[0].textContent,
|
|
|
|
|
cols[1].textContent,
|
|
|
|
|
cols[2].textContent,
|
|
|
|
|
cols[3].textContent,
|
|
|
|
|
cols[4].textContent.trim()
|
|
|
|
|
].map(val => `"${val}"`);
|
|
|
|
|
csv += values.join(',') + '\n';
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
|
|
|
|
const link = document.createElement('a');
|
|
|
|
|
link.href = URL.createObjectURL(blob);
|
|
|
|
|
link.setAttribute('download', 'militantes.csv');
|
|
|
|
|
document.body.appendChild(link);
|
|
|
|
|
link.click();
|
|
|
|
|
document.body.removeChild(link);
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-04-04 11:37:48 -03:00
|
|
|
|
|
|
|
|
// Configurar máscaras de input
|
|
|
|
|
// CEP
|
|
|
|
|
const cepInputs = document.querySelectorAll('input[name="cep"]');
|
|
|
|
|
cepInputs.forEach(input => {
|
|
|
|
|
input.addEventListener('input', function(e) {
|
|
|
|
|
let value = e.target.value.replace(/\D/g, '');
|
|
|
|
|
if (value.length <= 8) {
|
|
|
|
|
value = value.replace(/(\d{5})(\d)/, '$1-$2');
|
|
|
|
|
e.target.value = value;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Buscar endereço pelo CEP
|
|
|
|
|
input.addEventListener('blur', function(e) {
|
|
|
|
|
const cep = e.target.value.replace(/\D/g, '');
|
|
|
|
|
if (cep.length === 8) {
|
|
|
|
|
fetch(`https://viacep.com.br/ws/${cep}/json/`)
|
|
|
|
|
.then(response => response.json())
|
|
|
|
|
.then(data => {
|
|
|
|
|
if (!data.erro) {
|
|
|
|
|
const form = input.closest('form');
|
|
|
|
|
form.querySelector('input[name="logradouro"]').value = data.logradouro;
|
|
|
|
|
form.querySelector('input[name="bairro"]').value = data.bairro;
|
|
|
|
|
form.querySelector('input[name="cidade"]').value = data.localidade;
|
|
|
|
|
form.querySelector('select[name="estado"]').value = data.uf;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Título Eleitoral
|
|
|
|
|
const tituloInputs = document.querySelectorAll('input[name="titulo_eleitoral"]');
|
|
|
|
|
tituloInputs.forEach(input => {
|
|
|
|
|
input.addEventListener('input', function(e) {
|
|
|
|
|
let value = e.target.value.replace(/\D/g, '');
|
|
|
|
|
if (value.length <= 12) {
|
|
|
|
|
value = value.replace(/(\d{4})(\d)/, '$1 $2');
|
|
|
|
|
value = value.replace(/(\d{4})(\d)/, '$1 $2');
|
|
|
|
|
e.target.value = value;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
2025-04-04 13:31:52 -03:00
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
// Inicializar tooltips do Bootstrap
|
|
|
|
|
const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
|
|
|
|
|
tooltipTriggerList.map(function (tooltipTriggerEl) {
|
|
|
|
|
return new bootstrap.Tooltip(tooltipTriggerEl, {
|
|
|
|
|
placement: 'top',
|
|
|
|
|
trigger: 'hover'
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2025-04-04 13:31:52 -03:00
|
|
|
// Inicializar paginação
|
|
|
|
|
updateVisibleRows();
|
|
|
|
|
updatePagination();
|
2025-04-04 11:37:48 -03:00
|
|
|
});
|
|
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
// Função para atualizar o valor total das responsabilidades
|
|
|
|
|
function atualizarValorResponsabilidades() {
|
|
|
|
|
const badges = document.querySelectorAll('.badge-clickable.active');
|
|
|
|
|
let valorTotal = 0;
|
2025-04-04 11:37:48 -03:00
|
|
|
|
2025-04-04 20:37:22 -03:00
|
|
|
badges.forEach(badge => {
|
2025-04-09 09:59:12 -03:00
|
|
|
const valor = parseInt(badge.getAttribute('data-value'));
|
|
|
|
|
if (!isNaN(valor)) {
|
|
|
|
|
valorTotal |= valor;
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
});
|
2025-04-04 11:37:48 -03:00
|
|
|
|
2025-04-09 09:59:12 -03:00
|
|
|
const input = document.getElementById('responsabilidades_values');
|
|
|
|
|
if (input) {
|
|
|
|
|
input.value = valorTotal;
|
|
|
|
|
}
|
|
|
|
|
return valorTotal;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Função para salvar as alterações do militante
|
|
|
|
|
async function salvarAlteracoesMilitante(militanteId) {
|
|
|
|
|
try {
|
|
|
|
|
const form = document.getElementById('formEditarMilitante');
|
|
|
|
|
const formData = new FormData(form);
|
|
|
|
|
|
|
|
|
|
// Adicionar responsabilidades
|
|
|
|
|
let responsabilidadesValor = 0;
|
|
|
|
|
form.querySelectorAll('input[name="responsabilidades"]:checked').forEach(checkbox => {
|
|
|
|
|
responsabilidadesValor |= parseInt(checkbox.value);
|
|
|
|
|
});
|
|
|
|
|
formData.append('responsabilidades_valor', responsabilidadesValor);
|
|
|
|
|
|
|
|
|
|
const response = await fetch(`/militantes/editar/${militanteId}`, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
body: formData,
|
|
|
|
|
headers: {
|
|
|
|
|
'X-CSRFToken': getCsrfToken()
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|
|
|
|
|
});
|
2025-04-09 09:59:12 -03:00
|
|
|
|
|
|
|
|
const data = await response.json();
|
|
|
|
|
|
|
|
|
|
if (data.status === 'success') {
|
|
|
|
|
mostrarAlerta(data.message, 'success');
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
window.location.reload();
|
|
|
|
|
}, 1500);
|
|
|
|
|
} else {
|
|
|
|
|
mostrarAlerta(data.message || 'Erro ao salvar alterações', 'danger');
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Erro ao salvar alterações:', error);
|
|
|
|
|
mostrarAlerta('Erro ao salvar alterações. Por favor, tente novamente.', 'danger');
|
|
|
|
|
}
|
2025-04-04 20:37:22 -03:00
|
|
|
}
|