2025-04-03 15:05:48 -03:00
|
|
|
console.log('Carregando script militantes.js...');
|
|
|
|
|
|
2025-04-04 09:49:06 -03:00
|
|
|
// Variáveis globais para controle dos filtros
|
|
|
|
|
let filtroAtual = 'todos';
|
|
|
|
|
let filtroResponsabilidade = null;
|
|
|
|
|
let filtroCelula = null;
|
|
|
|
|
|
|
|
|
|
// Função para filtrar militantes
|
|
|
|
|
function filtrarMilitantes() {
|
|
|
|
|
const searchTerm = document.getElementById('searchInput').value.toLowerCase();
|
|
|
|
|
const rows = document.querySelectorAll('#militantesTable tbody tr');
|
|
|
|
|
let count = 0;
|
|
|
|
|
|
|
|
|
|
rows.forEach(row => {
|
|
|
|
|
let shouldShow = true;
|
|
|
|
|
|
|
|
|
|
// Filtro de texto
|
|
|
|
|
const textContent = row.textContent.toLowerCase();
|
|
|
|
|
if (!textContent.includes(searchTerm)) {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filtro de status (filiado/não filiado)
|
|
|
|
|
if (filtroAtual !== 'todos') {
|
|
|
|
|
const filiado = row.getAttribute('data-filiado');
|
|
|
|
|
if (filtroAtual === 'filiados' && filiado !== 'sim') {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
if (filtroAtual === 'nao-filiados' && filiado !== 'nao') {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filtro de responsabilidades
|
|
|
|
|
if (filtroResponsabilidade) {
|
|
|
|
|
const badges = row.querySelectorAll('.badge');
|
|
|
|
|
const hasResponsabilidade = Array.from(badges).some(badge =>
|
|
|
|
|
badge.textContent.toLowerCase() === filtroResponsabilidade.toLowerCase()
|
|
|
|
|
);
|
|
|
|
|
if (!hasResponsabilidade) {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Filtro de célula
|
|
|
|
|
if (filtroCelula) {
|
|
|
|
|
const celula = row.querySelector('[data-celula]').getAttribute('data-celula');
|
|
|
|
|
if (celula !== filtroCelula) {
|
|
|
|
|
shouldShow = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Aplicar visibilidade
|
|
|
|
|
row.style.display = shouldShow ? '' : 'none';
|
|
|
|
|
if (shouldShow) count++;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Atualizar contador
|
|
|
|
|
document.getElementById('countMilitantes').textContent = count;
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
|
|
|
|
|
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 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;
|
|
|
|
|
} else if (['filiados', 'nao-filiados'].includes(filter)) {
|
|
|
|
|
filtroAtual = filter;
|
|
|
|
|
filtroResponsabilidade = null;
|
|
|
|
|
filtroCelula = null;
|
|
|
|
|
} else if (['financas', 'imprensa', 'quadro-orientador'].includes(filter)) {
|
|
|
|
|
filtroAtual = 'todos';
|
|
|
|
|
filtroResponsabilidade = filter === 'financas' ? 'Finanças' :
|
|
|
|
|
filter === 'imprensa' ? 'Imprensa' :
|
|
|
|
|
'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
|
|
|
|
|
|
|
|
// Configuração do modal de edição
|
|
|
|
|
const modalEditarMilitante = document.getElementById('modalEditarMilitante');
|
|
|
|
|
console.log('Modal de edição:', modalEditarMilitante);
|
|
|
|
|
|
|
|
|
|
if (modalEditarMilitante) {
|
|
|
|
|
console.log('Modal encontrado, configurando eventos...');
|
|
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
// Criar instância do modal Bootstrap
|
|
|
|
|
const modalInstance = new bootstrap.Modal(modalEditarMilitante);
|
|
|
|
|
console.log('Instância do modal criada:', modalInstance);
|
|
|
|
|
|
2025-04-03 15:05:48 -03:00
|
|
|
modalEditarMilitante.addEventListener('show.bs.modal', function(event) {
|
|
|
|
|
console.log('Modal sendo exibido');
|
|
|
|
|
const button = event.relatedTarget;
|
|
|
|
|
console.log('Botão:', button);
|
|
|
|
|
|
|
|
|
|
if (!button) {
|
|
|
|
|
console.error('Botão não encontrado!');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const militanteId = button.getAttribute('data-militante-id');
|
2025-04-04 11:37:48 -03:00
|
|
|
const militanteNome = button.getAttribute('data-militante-nome');
|
2025-04-03 15:05:48 -03:00
|
|
|
console.log('ID do militante:', militanteId);
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('Nome do militante:', militanteNome);
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
if (!militanteId) {
|
|
|
|
|
console.error('ID do militante não encontrado no botão!');
|
|
|
|
|
return;
|
|
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
// Atualizar o título do modal com o nome do militante
|
|
|
|
|
const modalTitle = modalEditarMilitante.querySelector('.modal-title');
|
|
|
|
|
if (modalTitle) {
|
|
|
|
|
modalTitle.innerHTML = `<i class="fas fa-user-edit me-2"></i>Editar ${militanteNome}`;
|
|
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
|
|
|
|
|
// Configurar formulário
|
|
|
|
|
const form = document.getElementById('formEditarMilitante');
|
|
|
|
|
if (form) {
|
|
|
|
|
form.action = `/militantes/editar/${militanteId}`;
|
2025-04-04 11:37:48 -03:00
|
|
|
const idInput = document.getElementById('edit_militante_id');
|
|
|
|
|
if (idInput) {
|
|
|
|
|
idInput.value = militanteId;
|
|
|
|
|
}
|
2025-04-03 15:05:48 -03:00
|
|
|
console.log('Action do formulário:', form.action);
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('ID do militante no formulário:', militanteId);
|
|
|
|
|
} else {
|
|
|
|
|
console.error('Formulário não encontrado!');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Mostrar loading
|
|
|
|
|
const modalBody = modalEditarMilitante.querySelector('.modal-body');
|
|
|
|
|
if (modalBody) {
|
|
|
|
|
modalBody.style.opacity = '0.5';
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
2025-04-04 11:37:48 -03:00
|
|
|
|
|
|
|
|
// Buscar dados completos do militante via AJAX
|
|
|
|
|
console.log(`Fazendo requisição para /militantes/${militanteId}/dados`);
|
|
|
|
|
|
|
|
|
|
// Obter o CSRF token
|
|
|
|
|
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
|
|
|
|
console.log('CSRF token:', csrfToken);
|
|
|
|
|
|
|
|
|
|
fetch(`/militantes/${militanteId}/dados`, {
|
|
|
|
|
method: 'GET',
|
|
|
|
|
headers: {
|
|
|
|
|
'Accept': 'application/json',
|
|
|
|
|
'X-Requested-With': 'XMLHttpRequest',
|
|
|
|
|
'X-CSRFToken': csrfToken
|
|
|
|
|
},
|
|
|
|
|
credentials: 'same-origin'
|
|
|
|
|
})
|
|
|
|
|
.then(response => {
|
|
|
|
|
console.log('Resposta recebida:', response);
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
return response.json().then(data => {
|
|
|
|
|
throw new Error(data.message || `HTTP error! status: ${response.status}`);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
return response.json();
|
|
|
|
|
})
|
|
|
|
|
.then(dados => {
|
|
|
|
|
console.log('Dados do militante recebidos:', dados);
|
|
|
|
|
|
|
|
|
|
if (!dados) {
|
|
|
|
|
throw new Error('Dados do militante não encontrados');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
console.log('Preenchendo dados básicos...');
|
|
|
|
|
// Dados Básicos
|
|
|
|
|
document.getElementById('edit_nome').value = dados.nome || '';
|
|
|
|
|
document.getElementById('edit_cpf').value = dados.cpf || '';
|
|
|
|
|
document.getElementById('edit_titulo_eleitoral').value = dados.titulo_eleitoral || '';
|
|
|
|
|
document.getElementById('edit_data_nascimento').value = dados.data_nascimento || '';
|
|
|
|
|
document.getElementById('edit_data_entrada').value = dados.data_entrada_oci || '';
|
|
|
|
|
document.getElementById('edit_data_efetivacao').value = dados.data_efetivacao_oci || '';
|
|
|
|
|
console.log('Dados básicos preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados de contato...');
|
|
|
|
|
// Contato
|
|
|
|
|
document.getElementById('edit_telefone1').value = dados.telefone1 || '';
|
|
|
|
|
document.getElementById('edit_telefone2').value = dados.telefone2 || '';
|
|
|
|
|
document.getElementById('edit_email').value = dados.email || '';
|
|
|
|
|
console.log('Dados de contato preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados de endereço...');
|
|
|
|
|
// Endereço
|
|
|
|
|
if (dados.endereco) {
|
|
|
|
|
document.getElementById('edit_cep').value = dados.endereco.cep || '';
|
|
|
|
|
document.getElementById('edit_estado').value = dados.endereco.estado || '';
|
|
|
|
|
document.getElementById('edit_cidade').value = dados.endereco.cidade || '';
|
|
|
|
|
document.getElementById('edit_bairro').value = dados.endereco.bairro || '';
|
|
|
|
|
document.getElementById('edit_logradouro').value = dados.endereco.rua || '';
|
|
|
|
|
document.getElementById('edit_numero').value = dados.endereco.numero || '';
|
|
|
|
|
document.getElementById('edit_complemento').value = dados.endereco.complemento || '';
|
|
|
|
|
}
|
|
|
|
|
console.log('Dados de endereço preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados profissionais...');
|
|
|
|
|
// Profissional
|
|
|
|
|
document.getElementById('edit_profissao').value = dados.profissao || '';
|
|
|
|
|
document.getElementById('edit_regime_trabalho').value = dados.regime_trabalho || '';
|
|
|
|
|
document.getElementById('edit_empresa').value = dados.empresa || '';
|
|
|
|
|
document.getElementById('edit_contratante').value = dados.contratante || '';
|
|
|
|
|
console.log('Dados profissionais preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados acadêmicos...');
|
|
|
|
|
// Acadêmico
|
|
|
|
|
document.getElementById('edit_instituicao_ensino').value = dados.instituicao_ensino || '';
|
|
|
|
|
document.getElementById('edit_tipo_instituicao').value = dados.tipo_instituicao || '';
|
|
|
|
|
console.log('Dados acadêmicos preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados sindicais...');
|
|
|
|
|
// Sindical
|
|
|
|
|
document.getElementById('edit_sindicato').value = dados.sindicato || '';
|
|
|
|
|
document.getElementById('edit_cargo_sindical').value = dados.cargo_sindical || '';
|
|
|
|
|
document.getElementById('edit_central_sindical').value = dados.central_sindical || '';
|
|
|
|
|
document.getElementById('edit_dirigente_sindical').checked = dados.dirigente_sindical || false;
|
|
|
|
|
console.log('Dados sindicais preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Preenchendo dados organizacionais...');
|
|
|
|
|
// Organização
|
|
|
|
|
document.getElementById('edit_estado_militante').value = dados.estado || 'ATIVO';
|
|
|
|
|
document.getElementById('edit_celula').value = dados.celula_id || '';
|
|
|
|
|
|
|
|
|
|
// Responsabilidades
|
|
|
|
|
const responsabilidades = dados.responsabilidades || 0;
|
|
|
|
|
document.querySelectorAll('input[name="responsabilidades"]').forEach(checkbox => {
|
|
|
|
|
const valor = parseInt(checkbox.value);
|
|
|
|
|
checkbox.checked = (responsabilidades & valor) !== 0;
|
|
|
|
|
});
|
|
|
|
|
console.log('Dados organizacionais preenchidos');
|
|
|
|
|
|
|
|
|
|
console.log('Todos os dados preenchidos com sucesso!');
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Erro ao preencher os campos:', error);
|
|
|
|
|
throw new Error('Erro ao preencher os dados do militante: ' + error.message);
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.catch(error => {
|
|
|
|
|
console.error('Erro ao buscar dados do militante:', error);
|
|
|
|
|
alert('Erro ao carregar dados do militante: ' + error.message);
|
|
|
|
|
})
|
|
|
|
|
.finally(() => {
|
|
|
|
|
if (modalBody) {
|
|
|
|
|
modalBody.style.opacity = '1';
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-04-03 15:05:48 -03:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Envio do formulário de edição via AJAX
|
|
|
|
|
const formEditarMilitante = document.getElementById('formEditarMilitante');
|
|
|
|
|
if (formEditarMilitante) {
|
|
|
|
|
formEditarMilitante.addEventListener('submit', function(e) {
|
|
|
|
|
e.preventDefault();
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('Enviando formulário de edição...');
|
2025-04-03 15:05:48 -03:00
|
|
|
|
|
|
|
|
const formData = new FormData(this);
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('Dados do formulário:', Object.fromEntries(formData));
|
|
|
|
|
|
|
|
|
|
// Adicionar responsabilidades selecionadas
|
|
|
|
|
const responsabilidades = Array.from(this.querySelectorAll('input[name="responsabilidades"]:checked'))
|
|
|
|
|
.map(cb => parseInt(cb.value))
|
|
|
|
|
.reduce((a, b) => a + b, 0);
|
|
|
|
|
formData.set('responsabilidades', responsabilidades);
|
|
|
|
|
|
|
|
|
|
// Obter o CSRF token
|
|
|
|
|
const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
|
|
|
|
|
console.log('CSRF token:', csrfToken);
|
|
|
|
|
|
|
|
|
|
// Obter o ID do militante do campo hidden
|
|
|
|
|
const militanteId = document.getElementById('edit_militante_id').value;
|
|
|
|
|
console.log('ID do militante:', militanteId);
|
2025-04-03 15:05:48 -03:00
|
|
|
|
2025-04-04 11:37:48 -03:00
|
|
|
if (!militanteId) {
|
|
|
|
|
console.error('ID do militante não encontrado!');
|
|
|
|
|
mostrarAlerta('Erro: ID do militante não encontrado', 'danger');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Garantir que o campo de endereço está correto
|
|
|
|
|
const logradouro = formData.get('logradouro');
|
|
|
|
|
if (logradouro) {
|
|
|
|
|
formData.set('rua', logradouro);
|
|
|
|
|
formData.delete('logradouro');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fetch(`/militantes/editar/${militanteId}`, {
|
2025-04-03 15:05:48 -03:00
|
|
|
method: 'POST',
|
|
|
|
|
body: formData,
|
|
|
|
|
headers: {
|
2025-04-04 11:37:48 -03:00
|
|
|
'X-Requested-With': 'XMLHttpRequest',
|
|
|
|
|
'X-CSRFToken': csrfToken
|
|
|
|
|
},
|
|
|
|
|
credentials: 'same-origin'
|
|
|
|
|
})
|
|
|
|
|
.then(response => {
|
|
|
|
|
console.log('Resposta recebida:', response);
|
|
|
|
|
if (!response.ok) {
|
|
|
|
|
return response.json().then(data => {
|
|
|
|
|
throw new Error(data.message || `HTTP error! status: ${response.status}`);
|
|
|
|
|
});
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
2025-04-04 11:37:48 -03:00
|
|
|
return response.json();
|
2025-04-03 15:05:48 -03:00
|
|
|
})
|
|
|
|
|
.then(data => {
|
2025-04-04 11:37:48 -03:00
|
|
|
console.log('Resposta processada:', data);
|
2025-04-03 15:05:48 -03:00
|
|
|
if (data.status === 'success') {
|
|
|
|
|
// Fechar o modal
|
|
|
|
|
bootstrap.Modal.getInstance(modalEditarMilitante).hide();
|
|
|
|
|
|
|
|
|
|
// Mostrar mensagem de sucesso
|
2025-04-04 11:37:48 -03:00
|
|
|
mostrarAlerta(data.message, 'success');
|
|
|
|
|
|
|
|
|
|
// Recarregar a página após um breve delay
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
location.reload();
|
|
|
|
|
}, 1500);
|
2025-04-03 15:05:48 -03:00
|
|
|
} else {
|
2025-04-04 11:37:48 -03:00
|
|
|
throw new Error(data.message || 'Erro ao salvar dados');
|
2025-04-03 15:05:48 -03:00
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.catch(error => {
|
2025-04-04 11:37:48 -03:00
|
|
|
console.error('Erro ao enviar formulário:', error);
|
|
|
|
|
mostrarAlerta(`Erro ao salvar dados: ${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!');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Envio do formulário via AJAX
|
|
|
|
|
const formNovoMilitante = document.getElementById('formNovoMilitante');
|
|
|
|
|
if (formNovoMilitante) {
|
|
|
|
|
formNovoMilitante.addEventListener('submit', function(e) {
|
|
|
|
|
e.preventDefault();
|
|
|
|
|
|
|
|
|
|
const formData = new FormData(this);
|
|
|
|
|
|
|
|
|
|
fetch(this.action, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
body: formData,
|
|
|
|
|
headers: {
|
|
|
|
|
'X-Requested-With': 'XMLHttpRequest'
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.then(response => response.json())
|
|
|
|
|
.then(data => {
|
|
|
|
|
if (data.status === 'success') {
|
|
|
|
|
// Fechar o modal
|
|
|
|
|
const modal = bootstrap.Modal.getInstance(document.getElementById('modalNovoMilitante'));
|
|
|
|
|
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>
|
|
|
|
|
<td data-email="${data.militante.email}">${data.militante.email}</td>
|
|
|
|
|
<td data-telefone="${data.militante.telefone}">${data.militante.telefone}</td>
|
|
|
|
|
<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}"
|
|
|
|
|
data-militante-email="${data.militante.email}"
|
|
|
|
|
data-militante-telefone="${data.militante.telefone}"
|
|
|
|
|
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
|
|
|
|
|
|
|
|
// Limpar formulário e alertas quando o modal for fechado
|
|
|
|
|
const modalNovoMilitante = document.getElementById('modalNovoMilitante');
|
|
|
|
|
if (modalNovoMilitante) {
|
|
|
|
|
modalNovoMilitante.addEventListener('hidden.bs.modal', function () {
|
|
|
|
|
formNovoMilitante.reset();
|
|
|
|
|
const alerts = this.querySelectorAll('.alert');
|
|
|
|
|
alerts.forEach(alert => alert.remove());
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 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;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Função para mostrar alertas
|
|
|
|
|
function mostrarAlerta(mensagem, tipo) {
|
|
|
|
|
// Criar o elemento de alerta
|
|
|
|
|
const alertDiv = document.createElement('div');
|
|
|
|
|
alertDiv.className = `alert alert-${tipo} alert-dismissible fade show position-fixed top-0 start-50 translate-middle-x mt-3`;
|
|
|
|
|
alertDiv.style.zIndex = '9999';
|
|
|
|
|
alertDiv.innerHTML = `
|
|
|
|
|
${mensagem}
|
|
|
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
|
|
|
`;
|
|
|
|
|
|
|
|
|
|
// Adicionar o alerta ao corpo do documento
|
|
|
|
|
document.body.appendChild(alertDiv);
|
|
|
|
|
|
|
|
|
|
// Configurar o Bootstrap alert
|
|
|
|
|
const bsAlert = new bootstrap.Alert(alertDiv);
|
|
|
|
|
|
|
|
|
|
// Remover o alerta após 3 segundos
|
|
|
|
|
setTimeout(() => {
|
|
|
|
|
bsAlert.close();
|
|
|
|
|
}, 3000);
|
|
|
|
|
}
|