Feat Widgets 1540
This commit is contained in:
		| @@ -1,104 +1,119 @@ | ||||
| // src/components/ConcejalesWidget.tsx | ||||
| import { useState, useEffect, useMemo } from 'react'; | ||||
| import { useState, useMemo, useEffect } from 'react'; | ||||
| import { useQuery } from '@tanstack/react-query'; | ||||
| import { getSeccionesElectorales, getResultadosConcejales, getConfiguracionPublica } from '../apiService'; | ||||
| import Select from 'react-select'; // <-- 1. Importar react-select | ||||
| import { getMunicipios, getResultadosConcejalesPorMunicipio, getConfiguracionPublica } from '../apiService'; | ||||
| import type { MunicipioSimple, ResultadoTicker } from '../types/types'; | ||||
| import { ImageWithFallback } from './ImageWithFallback'; | ||||
| import './TickerWidget.css'; // Reutilizamos los estilos del ticker | ||||
| import './TickerWidget.css'; | ||||
|  | ||||
| const formatPercent = (num: number) => `${(num || 0).toFixed(2).replace('.', ',')}%`; | ||||
|  | ||||
| export const ConcejalesWidget = () => { | ||||
|   const [secciones, setSecciones] = useState<MunicipioSimple[]>([]); | ||||
|   const [seccionActualId, setSeccionActualId] = useState<string>(''); | ||||
| // Estilos personalizados para que el selector se vea bien | ||||
| const customSelectStyles = { | ||||
|   control: (base: any) => ({ ...base, minWidth: '220px', border: '1px solid #ced4da' }), | ||||
|   menu: (base: any) => ({ ...base, zIndex: 10 }), // Para que el menú se superponga | ||||
| }; | ||||
|  | ||||
| export const ConcejalesWidget = () => { | ||||
|   // 2. Cambiamos el estado para que se adapte a react-select | ||||
|   const [selectedMunicipio, setSelectedMunicipio] = useState<{ value: string; label: string } | null>(null); | ||||
|  | ||||
|   // Query para la configuración (para saber cuántos resultados mostrar) | ||||
|   const { data: configData } = useQuery({ | ||||
|     queryKey: ['configuracionPublica'], | ||||
|     queryFn: getConfiguracionPublica, | ||||
|     staleTime: 0, | ||||
|   }); | ||||
|  | ||||
|   // Calculamos la cantidad a mostrar desde la configuración | ||||
|   const cantidadAMostrar = useMemo(() => { | ||||
|     return parseInt(configData?.TickerResultadosCantidad || '5', 10) + 1; | ||||
|   }, [configData]); | ||||
|   // Usamos la clave de configuración correcta | ||||
|   const cantidadAMostrar = parseInt(configData?.ConcejalesResultadosCantidad || '5', 10); | ||||
|  | ||||
|   useEffect(() => { | ||||
|     getSeccionesElectorales().then(seccionesData => { | ||||
|       if (seccionesData && seccionesData.length > 0) { | ||||
|         const orden = new Map([ | ||||
|           ['Capital', 0], ['Primera', 1], ['Segunda', 2], ['Tercera', 3], | ||||
|           ['Cuarta', 4], ['Quinta', 5], ['Sexta', 6], ['Séptima', 7] | ||||
|         ]); | ||||
|         const getOrden = (nombre: string) => { | ||||
|           const match = nombre.match(/Capital|Primera|Segunda|Tercera|Cuarta|Quinta|Sexta|Séptima/); | ||||
|           return match ? orden.get(match[0]) ?? 99 : 99; | ||||
|         }; | ||||
|         seccionesData.sort((a, b) => getOrden(a.nombre) - getOrden(b.nombre)); | ||||
|         setSecciones(seccionesData); | ||||
|         // Al estar los datos ya ordenados, el [0] será "Sección Capital" | ||||
|         setSeccionActualId(seccionesData[0].id); | ||||
|       } | ||||
|     }); | ||||
|   }, []); // El array de dependencias vacío asegura que esto solo se ejecute una vez | ||||
|  | ||||
|   // Query para obtener los resultados de la sección seleccionada | ||||
|   const { data: resultados, isLoading } = useQuery<ResultadoTicker[]>({ | ||||
|     queryKey: ['resultadosConcejales', seccionActualId], | ||||
|     queryFn: () => getResultadosConcejales(seccionActualId), | ||||
|     enabled: !!seccionActualId, | ||||
|   // 3. Query para obtener la lista de MUNICIPIOS | ||||
|   const { data: municipios = [], isLoading: isLoadingMunicipios } = useQuery<MunicipioSimple[]>({ | ||||
|     queryKey: ['municipios'], | ||||
|     queryFn: getMunicipios, | ||||
|   }); | ||||
|  | ||||
|   // --- INICIO DE LA LÓGICA DE PROCESAMIENTO "OTROS" --- | ||||
|   // Este useEffect se encarga de establecer el valor por defecto | ||||
|   useEffect(() => { | ||||
|     // Se ejecuta solo si tenemos la lista de municipios y aún no hemos seleccionado nada | ||||
|     if (municipios.length > 0 && !selectedMunicipio) { | ||||
|       // Buscamos "LA PLATA" en la lista (insensible a mayúsculas/minúsculas) | ||||
|       const laPlata = municipios.find(m => m.nombre.toUpperCase() === 'LA PLATA'); | ||||
|  | ||||
|       // Si lo encontramos, lo establecemos como el municipio seleccionado | ||||
|       if (laPlata) { | ||||
|         setSelectedMunicipio({ value: laPlata.id, label: laPlata.nombre }); | ||||
|       } | ||||
|     } | ||||
|   }, [municipios, selectedMunicipio]); // Se ejecuta cuando 'municipios' o 'selectedMunicipio' cambian | ||||
|  | ||||
|   // 4. Transformamos los datos para react-select | ||||
|   const municipioOptions = useMemo(() => | ||||
|     municipios | ||||
|       .map(m => ({ value: m.id, label: m.nombre })) | ||||
|       .sort((a, b) => a.label.localeCompare(b.label)), // Orden alfabético | ||||
|     [municipios]); | ||||
|  | ||||
|   // 5. Query para obtener los resultados del MUNICIPIO seleccionado | ||||
|   const { data: resultados, isLoading: isLoadingResultados } = useQuery<ResultadoTicker[]>({ | ||||
|     queryKey: ['resultadosConcejalesPorMunicipio', selectedMunicipio?.value], | ||||
|     queryFn: () => getResultadosConcejalesPorMunicipio(selectedMunicipio!.value), | ||||
|     enabled: !!selectedMunicipio, | ||||
|   }); | ||||
|  | ||||
|   // 6. Lógica para "Otros" (sin cambios funcionales) | ||||
|   let displayResults: ResultadoTicker[] = resultados || []; | ||||
|   if (resultados && resultados.length > cantidadAMostrar) { | ||||
|     const topParties = resultados.slice(0, cantidadAMostrar - 1); | ||||
|     const otherParties = resultados.slice(cantidadAMostrar - 1); | ||||
|     const otrosPorcentaje = otherParties.reduce((sum, party) => sum + party.votosPorcentaje, 0); | ||||
|  | ||||
|     const otrosPorcentaje = otherParties.reduce((sum, party) => sum + (party.porcentaje || 0), 0); | ||||
|     const otrosEntry: ResultadoTicker = { | ||||
|       id: `otros-concejales-${seccionActualId}`, | ||||
|       id: `otros-concejales-${selectedMunicipio?.value}`, | ||||
|       nombre: 'Otros', | ||||
|       nombreCorto: 'Otros', | ||||
|       color: '#888888', | ||||
|       logoUrl: null, | ||||
|       votos: 0, // No es relevante para la visualización del porcentaje | ||||
|       votosPorcentaje: otrosPorcentaje, | ||||
|       votos: 0, | ||||
|       porcentaje: otrosPorcentaje, | ||||
|     }; | ||||
|     displayResults = [...topParties, otrosEntry]; | ||||
|   } else if (resultados) { | ||||
|     displayResults = resultados.slice(0, cantidadAMostrar); | ||||
|   } | ||||
|   // --- FIN DE LA LÓGICA DE PROCESAMIENTO "OTROS" --- | ||||
|  | ||||
|   return ( | ||||
|     <div className="ticker-card" style={{ gridColumn: '1 / -1' }}> | ||||
|       <div className="ticker-header"> | ||||
|         <h3>CONCEJALES POR SECCIÓN ELECTORAL</h3> | ||||
|         <select value={seccionActualId} onChange={e => setSeccionActualId(e.target.value)} disabled={secciones.length === 0}> | ||||
|           {secciones.map(s => <option key={s.id} value={s.id}>{s.nombre}</option>)} | ||||
|         </select> | ||||
|         <h3>CONCEJALES POR MUNICIPIO</h3> | ||||
|         <Select | ||||
|           options={municipioOptions} | ||||
|           value={selectedMunicipio} | ||||
|           onChange={(option) => setSelectedMunicipio(option)} | ||||
|           isLoading={isLoadingMunicipios} | ||||
|           placeholder="Buscar y seleccionar un municipio..." | ||||
|           styles={customSelectStyles} | ||||
|         /> | ||||
|       </div> | ||||
|       <div className="ticker-results"> | ||||
|         {isLoading ? <p>Cargando...</p> : | ||||
|           displayResults.map(partido => ( | ||||
|             <div key={partido.id} className="ticker-party"> | ||||
|               <div className="party-logo"> | ||||
|                 <ImageWithFallback src={partido.logoUrl || undefined} fallbackSrc="/default-avatar.png" alt={`Logo de ${partido.nombre}`} /> | ||||
|         {(isLoadingMunicipios || (isLoadingResultados && selectedMunicipio)) && <p>Cargando...</p>} | ||||
|         {!selectedMunicipio && !isLoadingMunicipios && <p style={{textAlign: 'center', color: '#666'}}>Seleccione un municipio.</p>} | ||||
|         {displayResults.map(partido => ( | ||||
|           <div key={partido.id} className="ticker-party"> | ||||
|             <div className="party-logo"> | ||||
|               <ImageWithFallback src={partido.logoUrl || undefined} fallbackSrc="/default-avatar.png" alt={`Logo de ${partido.nombre}`} /> | ||||
|             </div> | ||||
|             <div className="party-details"> | ||||
|               <div className="party-info"> | ||||
|                 <span className="party-name">{partido.nombreCorto || partido.nombre}</span> | ||||
|                 <span className="party-percent">{formatPercent(partido.porcentaje)}</span> | ||||
|               </div> | ||||
|               <div className="party-details"> | ||||
|                 <div className="party-info"> | ||||
|                   <span className="party-name">{partido.nombreCorto || partido.nombre}</span> | ||||
|                   <span className="party-percent">{formatPercent(partido.votosPorcentaje)}</span> | ||||
|                 </div> | ||||
|                 <div className="party-bar-background"> | ||||
|                   <div className="party-bar-foreground" style={{ width: `${partido.votosPorcentaje}%`, backgroundColor: partido.color || '#888' }}></div> | ||||
|                 </div> | ||||
|               <div className="party-bar-background"> | ||||
|                 <div className="party-bar-foreground" style={{ width: `${partido.porcentaje}%`, backgroundColor: partido.color || '#888' }}></div> | ||||
|               </div> | ||||
|             </div> | ||||
|           )) | ||||
|         } | ||||
|           </div> | ||||
|         ))} | ||||
|       </div> | ||||
|     </div> | ||||
|   ); | ||||
|   | ||||
		Reference in New Issue
	
	Block a user