Feat: Implementar API de resultados y widget de prueba dinámico con selector

API (Backend):
Se crea el endpoint GET /api/resultados/municipio/{id} para servir los resultados detallados de un municipio específico.
Se añade el endpoint GET /api/catalogos/municipios para poblar selectores en el frontend.
Se incluye un endpoint simulado GET /api/resultados/provincia/{id} para facilitar el desarrollo futuro del frontend.
Worker (Servicio de Ingesta):
La lógica de sondeo se ha hecho dinámica. Ahora consulta todos los municipios presentes en la base de datos en lugar de uno solo.
El servicio falso (FakeElectoralApiService) se ha mejorado para generar datos aleatorios para cualquier municipio solicitado.
Frontend (React):
Se crea el componente <MunicipioSelector /> que se carga con datos desde la nueva API de catálogos.
Se integra el selector en la página principal, permitiendo al usuario elegir un municipio.
El componente <MunicipioWidget /> ahora recibe el ID del municipio como una prop y muestra los datos del municipio seleccionado, actualizándose en tiempo real.
Configuración:
Se ajusta la política de CORS en la API para permitir peticiones desde el servidor de desarrollo de Vite (localhost:5173), solucionando errores de conexión en el entorno local.
This commit is contained in:
2025-08-14 15:27:45 -03:00
parent b90baadeed
commit 1d58023113
70 changed files with 5563 additions and 89 deletions

View File

@@ -0,0 +1,37 @@
// src/components/MunicipioSelector.tsx
import { useState, useEffect } from 'react';
import { getMunicipios, type MunicipioSimple } from '../services/api';
interface Props {
onMunicipioChange: (municipioId: string) => void;
}
export const MunicipioSelector = ({ onMunicipioChange }: Props) => {
const [municipios, setMunicipios] = useState<MunicipioSimple[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadMunicipios = async () => {
try {
const data = await getMunicipios();
setMunicipios(data);
} catch (error) {
console.error("Error al cargar municipios", error);
} finally {
setLoading(false);
}
};
loadMunicipios();
}, []);
if (loading) return <p>Cargando municipios...</p>;
return (
<select onChange={(e) => onMunicipioChange(e.target.value)} defaultValue="">
<option value="" disabled>Seleccione un municipio</option>
{municipios.map(m => (
<option key={m.id} value={m.id}>{m.nombre}</option>
))}
</select>
);
};

View File

@@ -0,0 +1,69 @@
// src/components/MunicipioWidget.tsx
import { useState, useEffect } from 'react';
import { getResultadosPorMunicipio, type MunicipioResultados } from '../services/api';
interface Props {
municipioId: string;
}
export const MunicipioWidget = ({ municipioId }: Props) => {
const [data, setData] = useState<MunicipioResultados | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const resultados = await getResultadosPorMunicipio(municipioId);
setData(resultados);
setError(null);
} catch (err) {
setError('No se pudieron cargar los datos.');
console.error(err);
} finally {
setLoading(false);
}
};
// Hacemos la primera llamada inmediatamente
fetchData();
// Creamos un intervalo para refrescar los datos cada 10 segundos
const intervalId = setInterval(fetchData, 10000);
// ¡Importante! Limpiamos el intervalo cuando el componente se desmonta
return () => clearInterval(intervalId);
}, [municipioId]); // El efecto se volverá a ejecutar si el municipioId cambia
if (loading && !data) return <div>Cargando resultados...</div>;
if (error) return <div style={{ color: 'red' }}>{error}</div>;
if (!data) return <div>No hay datos disponibles.</div>;
return (
<div style={{ fontFamily: 'sans-serif', border: '1px solid #ccc', padding: '16px', borderRadius: '8px' }}>
<h2>{data.municipioNombre}</h2>
<p>Escrutado: {data.porcentajeEscrutado.toFixed(2)}% | Participación: {data.porcentajeParticipacion.toFixed(2)}%</p>
<hr />
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr>
<th style={{ textAlign: 'left' }}>Agrupación</th>
<th style={{ textAlign: 'right' }}>Votos</th>
<th style={{ textAlign: 'right' }}>%</th>
</tr>
</thead>
<tbody>
{data.resultados.map((partido) => (
<tr key={partido.nombre}>
<td>{partido.nombre}</td>
<td style={{ textAlign: 'right' }}>{partido.votos.toLocaleString('es-AR')}</td>
<td style={{ textAlign: 'right' }}>{partido.porcentaje.toFixed(2)}%</td>
</tr>
))}
</tbody>
</table>
<p style={{fontSize: '0.8em', color: '#666'}}>Última actualización: {new Date(data.ultimaActualizacion).toLocaleTimeString('es-AR')}</p>
</div>
);
};