Files
controles/static/js/testes.js

284 lines
12 KiB
JavaScript
Raw Permalink Normal View History

// Testes para o formulário de edição de militantes
console.log('Iniciando testes do formulário de edição...');
// Lista de campos que devem existir no formulário
const camposEsperados = {
'edit_militante_id': { tipo: 'hidden', obrigatorio: true },
'edit_nome': { tipo: 'text', obrigatorio: true },
'edit_cpf': { tipo: 'text', obrigatorio: true },
'edit_titulo_eleitoral': { tipo: 'text', obrigatorio: false },
'edit_data_nascimento': { tipo: 'text', obrigatorio: false },
'edit_data_entrada_oci': { tipo: 'text', obrigatorio: false },
'edit_data_efetivacao_oci': { tipo: 'text', obrigatorio: false },
'edit_email': { tipo: 'email', obrigatorio: true },
'edit_telefone1': { tipo: 'text', obrigatorio: false },
'edit_telefone2': { tipo: 'text', obrigatorio: false },
'edit_cep': { tipo: 'text', obrigatorio: false },
'edit_estado': { tipo: 'select', obrigatorio: false },
'edit_cidade': { tipo: 'text', obrigatorio: false },
'edit_bairro': { tipo: 'text', obrigatorio: false },
'edit_rua': { tipo: 'text', obrigatorio: false },
'edit_numero': { tipo: 'text', obrigatorio: false },
'edit_complemento': { tipo: 'text', obrigatorio: false },
'edit_empresa': { tipo: 'text', obrigatorio: false },
'edit_contratante': { tipo: 'text', obrigatorio: false },
'edit_instituicao_ensino': { tipo: 'text', obrigatorio: false },
'edit_tipo_instituicao': { tipo: 'select', obrigatorio: false },
'edit_sindicato': { tipo: 'text', obrigatorio: false },
'edit_cargo_sindical': { tipo: 'text', obrigatorio: false },
'edit_central_sindical': { tipo: 'text', obrigatorio: false },
'edit_celula': { tipo: 'select', obrigatorio: false },
'responsabilidades_values': { tipo: 'hidden', obrigatorio: false }
};
// Função para testar a existência e configuração dos campos
function testarCamposFormulario() {
console.log('Testando campos do formulário...');
const form = document.getElementById('formEditarMilitante');
const erros = [];
if (!form) {
console.error('Formulário não encontrado!');
return false;
}
// Testar cada campo esperado
for (const [id, config] of Object.entries(camposEsperados)) {
const campo = document.getElementById(id);
if (!campo) {
erros.push(`Campo ${id} não encontrado`);
continue;
}
// Verificar tipo
if (campo.type !== config.tipo && config.tipo !== 'select') {
erros.push(`Campo ${id} tem tipo ${campo.type}, esperado ${config.tipo}`);
}
// Verificar obrigatoriedade
if (config.obrigatorio && !campo.hasAttribute('required')) {
erros.push(`Campo ${id} deveria ser obrigatório`);
}
// Verificar se o campo tem name attribute
if (!campo.hasAttribute('name')) {
erros.push(`Campo ${id} não tem atributo name`);
}
}
// Reportar erros encontrados
if (erros.length > 0) {
console.error('Erros encontrados nos campos:', erros);
return false;
}
console.log('Todos os campos estão configurados corretamente');
return true;
}
// Função para testar o carregamento de dados
async function testarCarregamentoDados(militanteId) {
console.log('Testando carregamento de dados...');
try {
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);
// Verificar se os dados foram carregados corretamente
const erros = [];
// Verificar campos básicos
if (!data.nome) erros.push('Nome não carregado');
if (!data.cpf) erros.push('CPF não carregado');
// Verificar se os campos foram preenchidos
for (const [id, config] of Object.entries(camposEsperados)) {
const campo = document.getElementById(id);
if (!campo) continue;
// Mapear campos do servidor para campos do formulário
let valorEsperado = '';
switch(id) {
case 'edit_nome': valorEsperado = data.nome; break;
case 'edit_cpf': valorEsperado = data.cpf; break;
case 'edit_email': valorEsperado = data.emails?.[0]; break;
case 'edit_telefone1': valorEsperado = data.telefone1; break;
case 'edit_celula': valorEsperado = data.celula_id?.toString(); break;
case 'edit_cargo_sindical': valorEsperado = data.cargo_sindical; break;
case 'edit_central_sindical': valorEsperado = data.central_sindical; break;
case 'edit_sindicato': valorEsperado = data.sindicato; break;
// Adicione mais campos conforme necessário
}
if (config.obrigatorio && !valorEsperado) {
erros.push(`Campo obrigatório ${id} não tem valor no servidor`);
}
if (valorEsperado && campo.value !== valorEsperado) {
erros.push(`Campo ${id} tem valor diferente do servidor. Esperado: ${valorEsperado}, Atual: ${campo.value}`);
}
}
if (erros.length > 0) {
console.error('Erros no carregamento:', erros);
return false;
}
console.log('Dados carregados corretamente');
return true;
} catch (error) {
console.error('Erro ao carregar dados:', error);
return false;
}
}
// Função para testar o salvamento de dados
async function testarSalvamentoDados(militanteId) {
console.log('Testando salvamento de dados...');
try {
const form = document.getElementById('formEditarMilitante');
const formData = new FormData(form);
// Guardar valores originais para comparação
const valoresOriginais = {
nome: formData.get('nome'),
cpf: formData.get('cpf'),
email: formData.get('email'),
celula: formData.get('celula'),
cargo_sindical: formData.get('cargo_sindical'),
central_sindical: formData.get('central_sindical'),
sindicato: formData.get('sindicato'),
responsabilidades: formData.get('responsabilidades_values')
};
const response = await fetch(`/militantes/editar/${militanteId}`, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content')
},
body: formData
});
if (!response.ok) {
throw new Error(`Erro HTTP: ${response.status}`);
}
const data = await response.json();
console.log('Resposta do servidor:', data);
// Verificar se os dados foram salvos corretamente
const row = document.querySelector(`tr[data-militante="${militanteId}"]`);
if (!row) {
console.error('Linha da tabela não encontrada após salvamento');
return false;
}
const erros = [];
// Verificar dados básicos na tabela
const nome = row.querySelector('td[data-nome]')?.textContent;
const cpf = row.querySelector('td[data-cpf]')?.textContent;
const email = row.querySelector('td[data-email]')?.textContent;
if (nome !== valoresOriginais.nome) erros.push(`Nome não atualizado na tabela. Esperado: ${valoresOriginais.nome}, Atual: ${nome}`);
if (cpf !== valoresOriginais.cpf) erros.push(`CPF não atualizado na tabela. Esperado: ${valoresOriginais.cpf}, Atual: ${cpf}`);
if (email !== valoresOriginais.email) erros.push(`Email não atualizado na tabela. Esperado: ${valoresOriginais.email}, Atual: ${email}`);
// Verificar atributos para filtros
const celulaId = row.getAttribute('data-celula-id');
const responsabilidades = row.getAttribute('data-responsabilidades');
if (celulaId !== valoresOriginais.celula) erros.push(`Célula não atualizada na tabela. Esperado: ${valoresOriginais.celula}, Atual: ${celulaId}`);
if (responsabilidades !== valoresOriginais.responsabilidades) erros.push(`Responsabilidades não atualizadas na tabela. Esperado: ${valoresOriginais.responsabilidades}, Atual: ${responsabilidades}`);
// Verificar botão de edição
const btnEditar = row.querySelector('button[data-bs-target="#modalEditarMilitante"]');
if (btnEditar) {
if (btnEditar.getAttribute('data-militante-nome') !== valoresOriginais.nome) {
erros.push('Nome não atualizado no botão de edição');
}
if (btnEditar.getAttribute('data-celula-id') !== valoresOriginais.celula) {
erros.push('Célula não atualizada no botão de edição');
}
}
if (erros.length > 0) {
console.error('Erros no salvamento:', erros);
return false;
}
console.log('Dados salvos e atualizados corretamente');
return true;
} catch (error) {
console.error('Erro ao salvar dados:', error);
return false;
}
}
// Função principal de teste
async function testarFormularioEdicao(militanteId) {
console.log('Iniciando teste completo do formulário...');
// Testar campos do formulário
if (!testarCamposFormulario()) {
console.error('Teste dos campos falhou');
return false;
}
// Testar carregamento de dados
if (!await testarCarregamentoDados(militanteId)) {
console.error('Teste de carregamento falhou');
return false;
}
// Testar salvamento de dados
if (!await testarSalvamentoDados(militanteId)) {
console.error('Teste de salvamento falhou');
return false;
}
console.log('Todos os testes passaram com sucesso!');
return true;
}
// Executar testes quando o documento estiver carregado
document.addEventListener('DOMContentLoaded', function() {
// Adicionar botão de teste na interface
const btnTeste = document.createElement('button');
btnTeste.className = 'btn btn-info me-2';
btnTeste.innerHTML = '<i class="fas fa-vial me-2"></i>Testar Formulário';
btnTeste.onclick = function() {
// Pegar ID do primeiro militante da lista
const primeiraLinha = document.querySelector('#militantesTable tbody tr');
if (!primeiraLinha) {
mostrarAlerta('danger', 'Nenhum militante encontrado para teste');
return;
}
const militanteId = primeiraLinha.getAttribute('data-militante');
if (!militanteId) {
mostrarAlerta('danger', 'ID do militante não encontrado');
return;
}
// Executar testes
testarFormularioEdicao(militanteId).then(sucesso => {
if (sucesso) {
mostrarAlerta('success', 'Testes concluídos com sucesso!');
} else {
mostrarAlerta('danger', 'Alguns testes falharam. Verifique o console para mais detalhes.');
}
});
};
// Adicionar botão ao lado do botão de exportar
const btnExportar = document.querySelector('.btn-exportar');
if (btnExportar && btnExportar.parentNode) {
btnExportar.parentNode.insertBefore(btnTeste, btnExportar);
}
});