Feat Widgets
- Widget de Home - Widget Cards por Provincias - Widget Mapa por Categorias
This commit is contained in:
		| @@ -1,148 +1,110 @@ | ||||
| // src/components/AgrupacionesManager.tsx | ||||
| // EN: src/components/AgrupacionesManager.tsx | ||||
| import { useState, useEffect } from 'react'; | ||||
| import { useQuery, useQueryClient } from '@tanstack/react-query'; | ||||
| import Select from 'react-select'; // Importamos Select | ||||
| import Select from 'react-select'; | ||||
| import { getAgrupaciones, updateAgrupacion, getLogos, updateLogos } from '../services/apiService'; | ||||
| import type { AgrupacionPolitica, LogoAgrupacionCategoria } from '../types'; | ||||
| import type { AgrupacionPolitica, LogoAgrupacionCategoria, UpdateAgrupacionData } from '../types'; | ||||
| import './AgrupacionesManager.css'; | ||||
|  | ||||
| // Constantes para los IDs de categoría | ||||
| const SENADORES_ID = 5; | ||||
| const DIPUTADOS_ID = 6; | ||||
| const CONCEJALES_ID = 7; | ||||
| const SENADORES_NAC_ID = 1; | ||||
| const DIPUTADOS_NAC_ID = 2; | ||||
| const GLOBAL_ELECTION_ID = 0; | ||||
|  | ||||
| // Opciones para el nuevo selector de Elección | ||||
| const ELECCION_OPTIONS = [ | ||||
|     { value: 2, label: 'Elecciones Nacionales' }, | ||||
|     { value: 1, label: 'Elecciones Provinciales' }     | ||||
|     { value: GLOBAL_ELECTION_ID, label: 'Global (Logo por Defecto)' }, | ||||
|     { value: 2, label: 'Elecciones Nacionales (Override General)' }, | ||||
|     { value: 1, label: 'Elecciones Provinciales (Override General)' } | ||||
| ]; | ||||
|  | ||||
| const sanitizeColor = (color: string | null | undefined): string => { | ||||
|     if (!color) return '#000000'; | ||||
|     const sanitized = color.replace(/[^#0-9a-fA-F]/g, ''); | ||||
|     return sanitized.startsWith('#') ? sanitized : `#${sanitized}`; | ||||
|     return color.startsWith('#') ? color : `#${color}`; | ||||
| }; | ||||
|  | ||||
| export const AgrupacionesManager = () => { | ||||
|     const queryClient = useQueryClient(); | ||||
|      | ||||
|     // --- NUEVO ESTADO PARA LA ELECCIÓN SELECCIONADA --- | ||||
|     const [selectedEleccion, setSelectedEleccion] = useState(ELECCION_OPTIONS[0]); | ||||
|  | ||||
|     const [editedAgrupaciones, setEditedAgrupaciones] = useState<Record<string, Partial<AgrupacionPolitica>>>({}); | ||||
|     const [editedLogos, setEditedLogos] = useState<LogoAgrupacionCategoria[]>([]); | ||||
|     const [editedAgrupaciones, setEditedAgrupaciones] = useState<Record<string, { nombreCorto: string | null; color: string | null; }>>({}); | ||||
|     const [editedLogos, setEditedLogos] = useState<Record<string, string | null>>({}); | ||||
|  | ||||
|     const { data: agrupaciones = [], isLoading: isLoadingAgrupaciones } = useQuery<AgrupacionPolitica[]>({ | ||||
|         queryKey: ['agrupaciones'], | ||||
|         queryFn: getAgrupaciones, | ||||
|         queryKey: ['agrupaciones'], queryFn: getAgrupaciones, | ||||
|     }); | ||||
|  | ||||
|     // --- CORRECCIÓN: La query de logos ahora depende del ID de la elección --- | ||||
|      | ||||
|     const { data: logos = [], isLoading: isLoadingLogos } = useQuery<LogoAgrupacionCategoria[]>({ | ||||
|         queryKey: ['logos', selectedEleccion.value], | ||||
|         queryFn: () => getLogos(selectedEleccion.value), // Pasamos el valor numérico | ||||
|         queryKey: ['allLogos'], | ||||
|         queryFn: () => Promise.all([getLogos(0), getLogos(1), getLogos(2)]).then(res => res.flat()), | ||||
|     }); | ||||
|  | ||||
|     useEffect(() => { | ||||
|         if (agrupaciones && agrupaciones.length > 0) { | ||||
|             setEditedAgrupaciones(prev => { | ||||
|                 if (Object.keys(prev).length === 0) { | ||||
|                     return Object.fromEntries(agrupaciones.map(a => [a.id, {}])); | ||||
|                 } | ||||
|                 return prev; | ||||
|             }); | ||||
|         if (agrupaciones.length > 0) { | ||||
|             const initialEdits = Object.fromEntries( | ||||
|                 agrupaciones.map(a => [a.id, { nombreCorto: a.nombreCorto, color: a.color }]) | ||||
|             ); | ||||
|             setEditedAgrupaciones(initialEdits); | ||||
|         } | ||||
|     }, [agrupaciones]); | ||||
|      | ||||
|     // Este useEffect ahora también depende de 'logos' para reinicializarse | ||||
|  | ||||
|     useEffect(() => { | ||||
|         if (logos) { | ||||
|             setEditedLogos(JSON.parse(JSON.stringify(logos))); | ||||
|             const logoMap = Object.fromEntries( | ||||
|                 logos | ||||
|                     // --- CORRECCIÓN CLAVE 1: Comprobar contra `null` en lugar de `0` --- | ||||
|                     .filter(l => l.categoriaId === 0 && l.ambitoGeograficoId === null) | ||||
|                     .map(l => [`${l.agrupacionPoliticaId}-${l.eleccionId}`, l.logoUrl]) | ||||
|             ); | ||||
|             setEditedLogos(logoMap); | ||||
|         } | ||||
|     }, [logos]); | ||||
|  | ||||
|     const handleInputChange = (id: string, field: 'nombreCorto' | 'color', value: string) => { | ||||
|         setEditedAgrupaciones(prev => ({ | ||||
|             ...prev, | ||||
|             [id]: { ...prev[id], [field]: value } | ||||
|         })); | ||||
|     const handleInputChange = (id: string, field: 'nombreCorto' | 'color', value: string | null) => { | ||||
|         setEditedAgrupaciones(prev => ({ ...prev, [id]: { ...prev[id], [field]: value } })); | ||||
|     }; | ||||
|  | ||||
|     const handleLogoChange = (agrupacionId: string, categoriaId: number, value: string) => { | ||||
|         setEditedLogos(prev => { | ||||
|             const newLogos = [...prev]; | ||||
|             const existing = newLogos.find(l => | ||||
|                 l.eleccionId === selectedEleccion.value && | ||||
|                 l.agrupacionPoliticaId === agrupacionId && | ||||
|                 l.categoriaId === categoriaId && | ||||
|                 l.ambitoGeograficoId == null | ||||
|             ); | ||||
|  | ||||
|             if (existing) { | ||||
|                 existing.logoUrl = value; | ||||
|             } else { | ||||
|                 newLogos.push({ | ||||
|                     id: 0, | ||||
|                     eleccionId: selectedEleccion.value, // Añadimos el ID de la elección | ||||
|                     agrupacionPoliticaId: agrupacionId, | ||||
|                     categoriaId, | ||||
|                     logoUrl: value, | ||||
|                     ambitoGeograficoId: null | ||||
|                 }); | ||||
|             } | ||||
|             return newLogos; | ||||
|         }); | ||||
|     const handleLogoInputChange = (agrupacionId: string, value: string | null) => { | ||||
|         const key = `${agrupacionId}-${selectedEleccion.value}`; | ||||
|         setEditedLogos(prev => ({ ...prev, [key]: value })); | ||||
|     }; | ||||
|  | ||||
|      | ||||
|     const handleSaveAll = async () => { | ||||
|         try { | ||||
|             const agrupacionPromises = Object.entries(editedAgrupaciones).map(([id, changes]) => { | ||||
|                 if (Object.keys(changes).length > 0) { | ||||
|                     const original = agrupaciones.find(a => a.id === id); | ||||
|                     if (original) { | ||||
|                         return updateAgrupacion(id, { ...original, ...changes }); | ||||
|                     } | ||||
|                 } | ||||
|                 return Promise.resolve(); | ||||
|             const agrupacionPromises = agrupaciones.map(agrupacion => { | ||||
|                 const changes = editedAgrupaciones[agrupacion.id] || {}; | ||||
|                 const payload: UpdateAgrupacionData = { | ||||
|                     nombreCorto: changes.nombreCorto ?? agrupacion.nombreCorto, | ||||
|                     color: changes.color ?? agrupacion.color, | ||||
|                 }; | ||||
|                 return updateAgrupacion(agrupacion.id, payload); | ||||
|             }); | ||||
|              | ||||
|             // --- CORRECCIÓN CLAVE 2: Enviar `null` a la API en lugar de `0` --- | ||||
|             const logosPayload = Object.entries(editedLogos) | ||||
|                 .map(([key, logoUrl]) => { | ||||
|                     const [agrupacionPoliticaId, eleccionIdStr] = key.split('-'); | ||||
|                     return { id: 0, eleccionId: parseInt(eleccionIdStr), agrupacionPoliticaId, categoriaId: 0, logoUrl: logoUrl || null, ambitoGeograficoId: null }; | ||||
|                 }); | ||||
|  | ||||
|             const logoPromise = updateLogos(editedLogos); | ||||
|             const logoPromise = updateLogos(logosPayload); | ||||
|  | ||||
|             await Promise.all([...agrupacionPromises, logoPromise]); | ||||
|  | ||||
|             queryClient.invalidateQueries({ queryKey: ['agrupaciones'] }); | ||||
|             queryClient.invalidateQueries({ queryKey: ['logos', selectedEleccion.value] }); // Invalidamos la query correcta | ||||
|  | ||||
|              | ||||
|             await queryClient.invalidateQueries({ queryKey: ['agrupaciones'] }); | ||||
|             await queryClient.invalidateQueries({ queryKey: ['allLogos'] }); | ||||
|             alert('¡Todos los cambios han sido guardados!'); | ||||
|         } catch (err) { | ||||
|             console.error("Error al guardar todo:", err); | ||||
|             alert("Ocurrió un error al guardar los cambios."); | ||||
|         } | ||||
|         } catch (err) { console.error("Error al guardar todo:", err); alert("Ocurrió un error."); } | ||||
|     }; | ||||
|      | ||||
|     const getLogoValue = (agrupacionId: string): string => { | ||||
|         const key = `${agrupacionId}-${selectedEleccion.value}`; | ||||
|         return editedLogos[key] ?? ''; | ||||
|     }; | ||||
|  | ||||
|     const isLoading = isLoadingAgrupaciones || isLoadingLogos; | ||||
|  | ||||
|     const getLogoUrl = (agrupacionId: string, categoriaId: number) => { | ||||
|         return editedLogos.find(l => | ||||
|             l.eleccionId === selectedEleccion.value && | ||||
|             l.agrupacionPoliticaId === agrupacionId && | ||||
|             l.categoriaId === categoriaId && | ||||
|             l.ambitoGeograficoId == null | ||||
|         )?.logoUrl || ''; | ||||
|     }; | ||||
|  | ||||
|     return ( | ||||
|         <div className="admin-module"> | ||||
|             <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}> | ||||
|                 <h3>Gestión de Agrupaciones y Logos Generales</h3> | ||||
|                 <div style={{width: '250px', zIndex: 100 }}> | ||||
|                     <Select | ||||
|                         options={ELECCION_OPTIONS} | ||||
|                         value={selectedEleccion} | ||||
|                         onChange={(opt) => setSelectedEleccion(opt!)} | ||||
|                     /> | ||||
|                 <h3>Gestión de Agrupaciones y Logos</h3> | ||||
|                 <div style={{width: '350px', zIndex: 100 }}> | ||||
|                     <Select options={ELECCION_OPTIONS} value={selectedEleccion} onChange={(opt) => setSelectedEleccion(opt!)} /> | ||||
|                 </div> | ||||
|             </div> | ||||
|  | ||||
| @@ -155,42 +117,23 @@ export const AgrupacionesManager = () => { | ||||
|                                     <th>Nombre</th> | ||||
|                                     <th>Nombre Corto</th> | ||||
|                                     <th>Color</th> | ||||
|                                     {/* --- CABECERAS CONDICIONALES --- */} | ||||
|                                     {selectedEleccion.value === 2 ? ( | ||||
|                                         <> | ||||
|                                             <th>Logo Senadores Nac.</th> | ||||
|                                             <th>Logo Diputados Nac.</th> | ||||
|                                         </> | ||||
|                                     ) : ( | ||||
|                                         <> | ||||
|                                             <th>Logo Senadores Prov.</th> | ||||
|                                             <th>Logo Diputados Prov.</th> | ||||
|                                             <th>Logo Concejales</th> | ||||
|                                         </> | ||||
|                                     )} | ||||
|                                     <th>Logo</th> | ||||
|                                 </tr> | ||||
|                             </thead> | ||||
|                             <tbody> | ||||
|                                 {agrupaciones.map(agrupacion => ( | ||||
|                                     <tr key={agrupacion.id}> | ||||
|                                         <td>{agrupacion.nombre}</td> | ||||
|                                         <td><input type="text" value={editedAgrupaciones[agrupacion.id]?.nombreCorto ?? agrupacion.nombreCorto ?? ''} onChange={(e) => handleInputChange(agrupacion.id, 'nombreCorto', e.target.value)} /></td> | ||||
|                                         <td><input type="text" value={editedAgrupaciones[agrupacion.id]?.nombreCorto ?? ''} onChange={(e) => handleInputChange(agrupacion.id, 'nombreCorto', e.target.value)} /></td> | ||||
|                                         <td><input type="color" value={sanitizeColor(editedAgrupaciones[agrupacion.id]?.color)} onChange={(e) => handleInputChange(agrupacion.id, 'color', e.target.value)} /></td> | ||||
|                                         <td> | ||||
|                                             <input type="color" value={sanitizeColor(editedAgrupaciones[agrupacion.id]?.color ?? agrupacion.color)} onChange={(e) => handleInputChange(agrupacion.id, 'color', e.target.value)} /> | ||||
|                                             <input  | ||||
|                                                 type="text"  | ||||
|                                                 placeholder="URL..."  | ||||
|                                                 value={getLogoValue(agrupacion.id)}  | ||||
|                                                 onChange={(e) => handleLogoInputChange(agrupacion.id, e.target.value)}  | ||||
|                                             /> | ||||
|                                         </td> | ||||
|                                         {/* --- CELDAS CONDICIONALES --- */} | ||||
|                                         {selectedEleccion.value === 2 ? ( | ||||
|                                             <> | ||||
|                                                 <td><input type="text" placeholder="URL..." value={getLogoUrl(agrupacion.id, SENADORES_NAC_ID)} onChange={(e) => handleLogoChange(agrupacion.id, SENADORES_NAC_ID, e.target.value)} /></td> | ||||
|                                                 <td><input type="text" placeholder="URL..." value={getLogoUrl(agrupacion.id, DIPUTADOS_NAC_ID)} onChange={(e) => handleLogoChange(agrupacion.id, DIPUTADOS_NAC_ID, e.target.value)} /></td> | ||||
|                                             </> | ||||
|                                         ) : ( | ||||
|                                             <> | ||||
|                                                 <td><input type="text" placeholder="URL..." value={getLogoUrl(agrupacion.id, SENADORES_ID)} onChange={(e) => handleLogoChange(agrupacion.id, SENADORES_ID, e.target.value)} /></td> | ||||
|                                                 <td><input type="text" placeholder="URL..." value={getLogoUrl(agrupacion.id, DIPUTADOS_ID)} onChange={(e) => handleLogoChange(agrupacion.id, DIPUTADOS_ID, e.target.value)} /></td> | ||||
|                                                 <td><input type="text" placeholder="URL..." value={getLogoUrl(agrupacion.id, CONCEJALES_ID)} onChange={(e) => handleLogoChange(agrupacion.id, CONCEJALES_ID, e.target.value)} /></td> | ||||
|                                             </> | ||||
|                                         )} | ||||
|                                     </tr> | ||||
|                                 ))} | ||||
|                             </tbody> | ||||
|   | ||||
| @@ -7,6 +7,7 @@ import type { MunicipioSimple, AgrupacionPolitica, LogoAgrupacionCategoria, Prov | ||||
| import { CATEGORIAS_NACIONALES_OPTIONS, CATEGORIAS_PROVINCIALES_OPTIONS } from '../constants/categorias'; | ||||
|  | ||||
| const ELECCION_OPTIONS = [ | ||||
|     { value: 0, label: 'General (Toda la elección)' }, | ||||
|     { value: 2, label: 'Elecciones Nacionales' }, | ||||
|     { value: 1, label: 'Elecciones Provinciales' } | ||||
| ]; | ||||
| @@ -44,7 +45,7 @@ export const LogoOverridesManager = () => { | ||||
|     const getAmbitoId = () => { | ||||
|         if (selectedAmbitoLevel.value === 'municipio' && selectedMunicipio) return parseInt(selectedMunicipio.id); | ||||
|         if (selectedAmbitoLevel.value === 'provincia' && selectedProvincia) return parseInt(selectedProvincia.id); | ||||
|         return null; | ||||
|         return 0; | ||||
|     }; | ||||
|  | ||||
|     const currentLogo = useMemo(() => { | ||||
|   | ||||
| @@ -8,7 +8,6 @@ export interface AgrupacionPolitica { | ||||
|   color: string | null; | ||||
|   ordenDiputados: number | null; | ||||
|   ordenSenadores: number | null; | ||||
|   // Añadimos los nuevos campos para el ordenamiento nacional | ||||
|   ordenDiputadosNacionales: number | null; | ||||
|   ordenSenadoresNacionales: number | null; | ||||
| } | ||||
| @@ -58,7 +57,7 @@ export interface LogoAgrupacionCategoria { | ||||
|     id: number; | ||||
|     eleccionId: number; // Clave para diferenciar | ||||
|     agrupacionPoliticaId: string; | ||||
|     categoriaId: number; | ||||
|     categoriaId: number | null; | ||||
|     logoUrl: string | null; | ||||
|     ambitoGeograficoId: number | null; | ||||
| } | ||||
|   | ||||
							
								
								
									
										47
									
								
								Elecciones-Web/frontend/package-lock.json
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										47
									
								
								Elecciones-Web/frontend/package-lock.json
									
									
									
										generated
									
									
									
								
							| @@ -21,11 +21,13 @@ | ||||
|         "react": "^19.1.1", | ||||
|         "react-circular-progressbar": "^2.2.0", | ||||
|         "react-dom": "^19.1.1", | ||||
|         "react-hot-toast": "^2.6.0", | ||||
|         "react-icons": "^5.5.0", | ||||
|         "react-pdf": "^10.1.0", | ||||
|         "react-select": "^5.10.2", | ||||
|         "react-simple-maps": "github:ozimmortal/react-simple-maps#feat/react-19-support", | ||||
|         "react-tooltip": "^5.29.1", | ||||
|         "swiper": "^12.0.2", | ||||
|         "topojson-client": "^3.1.0", | ||||
|         "vite-plugin-svgr": "^4.5.0" | ||||
|       }, | ||||
| @@ -3962,6 +3964,15 @@ | ||||
|         "url": "https://github.com/sponsors/sindresorhus" | ||||
|       } | ||||
|     }, | ||||
|     "node_modules/goober": { | ||||
|       "version": "2.1.16", | ||||
|       "resolved": "https://registry.npmjs.org/goober/-/goober-2.1.16.tgz", | ||||
|       "integrity": "sha512-erjk19y1U33+XAMe1VTvIONHYoSqE4iS7BYUZfHaqeohLmnC0FdxEh7rQU+6MZ4OajItzjZFSRtVANrQwNq6/g==", | ||||
|       "license": "MIT", | ||||
|       "peerDependencies": { | ||||
|         "csstype": "^3.0.10" | ||||
|       } | ||||
|     }, | ||||
|     "node_modules/gopd": { | ||||
|       "version": "1.2.0", | ||||
|       "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", | ||||
| @@ -4745,6 +4756,23 @@ | ||||
|         "react": "^19.1.1" | ||||
|       } | ||||
|     }, | ||||
|     "node_modules/react-hot-toast": { | ||||
|       "version": "2.6.0", | ||||
|       "resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz", | ||||
|       "integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==", | ||||
|       "license": "MIT", | ||||
|       "dependencies": { | ||||
|         "csstype": "^3.1.3", | ||||
|         "goober": "^2.1.16" | ||||
|       }, | ||||
|       "engines": { | ||||
|         "node": ">=10" | ||||
|       }, | ||||
|       "peerDependencies": { | ||||
|         "react": ">=16", | ||||
|         "react-dom": ">=16" | ||||
|       } | ||||
|     }, | ||||
|     "node_modules/react-icons": { | ||||
|       "version": "5.5.0", | ||||
|       "resolved": "https://registry.npmjs.org/react-icons/-/react-icons-5.5.0.tgz", | ||||
| @@ -5120,6 +5148,25 @@ | ||||
|       "integrity": "sha512-e4hG1hRwoOdRb37cIMSgzNsxyzKfayW6VOflrwvR+/bzrkyxY/31WkbgnQpgtrNp1SdpJvpUAGTa/ZoiPNDuRQ==", | ||||
|       "license": "MIT" | ||||
|     }, | ||||
|     "node_modules/swiper": { | ||||
|       "version": "12.0.2", | ||||
|       "resolved": "https://registry.npmjs.org/swiper/-/swiper-12.0.2.tgz", | ||||
|       "integrity": "sha512-y8F6fDGXmTVVgwqJj6I00l4FdGuhpFJn0U/9Ucn1MwWOw3NdLV8aH88pZOjyhBgU/6PyBlUx+JuAQ5KMWz906Q==", | ||||
|       "funding": [ | ||||
|         { | ||||
|           "type": "patreon", | ||||
|           "url": "https://www.patreon.com/swiperjs" | ||||
|         }, | ||||
|         { | ||||
|           "type": "open_collective", | ||||
|           "url": "http://opencollective.com/swiper" | ||||
|         } | ||||
|       ], | ||||
|       "license": "MIT", | ||||
|       "engines": { | ||||
|         "node": ">= 4.7.0" | ||||
|       } | ||||
|     }, | ||||
|     "node_modules/terser": { | ||||
|       "version": "5.43.1", | ||||
|       "resolved": "https://registry.npmjs.org/terser/-/terser-5.43.1.tgz", | ||||
|   | ||||
| @@ -23,11 +23,13 @@ | ||||
|     "react": "^19.1.1", | ||||
|     "react-circular-progressbar": "^2.2.0", | ||||
|     "react-dom": "^19.1.1", | ||||
|     "react-hot-toast": "^2.6.0", | ||||
|     "react-icons": "^5.5.0", | ||||
|     "react-pdf": "^10.1.0", | ||||
|     "react-select": "^5.10.2", | ||||
|     "react-simple-maps": "github:ozimmortal/react-simple-maps#feat/react-19-support", | ||||
|     "react-tooltip": "^5.29.1", | ||||
|     "swiper": "^12.0.2", | ||||
|     "topojson-client": "^3.1.0", | ||||
|     "vite-plugin-svgr": "^4.5.0" | ||||
|   }, | ||||
|   | ||||
| @@ -1,9 +1,12 @@ | ||||
| // src/apiService.ts | ||||
| import axios from 'axios'; | ||||
| import type { ApiResponseRankingMunicipio, ApiResponseRankingSeccion,  | ||||
|   ApiResponseTablaDetallada, ProyeccionBancas, MunicipioSimple,  | ||||
|   TelegramaData, CatalogoItem, CategoriaResumen, ResultadoTicker,  | ||||
|   ApiResponseResultadosPorSeccion, PanelElectoralDto, ResumenProvincia } from './types/types'; | ||||
| import type { | ||||
|   ApiResponseRankingMunicipio, ApiResponseRankingSeccion, | ||||
|   ApiResponseTablaDetallada, ProyeccionBancas, MunicipioSimple, | ||||
|   TelegramaData, CatalogoItem, CategoriaResumen, ResultadoTicker, | ||||
|   ApiResponseResultadosPorSeccion, PanelElectoralDto, ResumenProvincia, | ||||
|   CategoriaResumenHome | ||||
| } from './types/types'; | ||||
|  | ||||
| /** | ||||
|  * URL base para las llamadas a la API. | ||||
| @@ -76,7 +79,6 @@ export interface BancadaDetalle { | ||||
| export interface ConfiguracionPublica { | ||||
|   TickerResultadosCantidad?: string; | ||||
|   ConcejalesResultadosCantidad?: string; | ||||
|   // ... otras claves públicas que pueda añadir en el futuro | ||||
| } | ||||
|  | ||||
| export interface ResultadoDetalleSeccion { | ||||
| @@ -88,29 +90,35 @@ export interface ResultadoDetalleSeccion { | ||||
| } | ||||
|  | ||||
| export interface PartidoComposicionNacional { | ||||
|     id: string; | ||||
|     nombre: string; | ||||
|     nombreCorto: string | null; | ||||
|     color: string | null; | ||||
|     bancasFijos: number; | ||||
|     bancasGanadas: number; | ||||
|     bancasTotales: number; | ||||
|     ordenDiputadosNacionales: number | null; | ||||
|     ordenSenadoresNacionales: number | null; | ||||
|   id: string; | ||||
|   nombre: string; | ||||
|   nombreCorto: string | null; | ||||
|   color: string | null; | ||||
|   bancasFijos: number; | ||||
|   bancasGanadas: number; | ||||
|   bancasTotales: number; | ||||
|   ordenDiputadosNacionales: number | null; | ||||
|   ordenSenadoresNacionales: number | null; | ||||
| } | ||||
|  | ||||
| export interface CamaraComposicionNacional { | ||||
|     camaraNombre: string; | ||||
|     totalBancas: number; | ||||
|     bancasEnJuego: number; | ||||
|     partidos: PartidoComposicionNacional[]; | ||||
|     presidenteBancada: { color: string | null; tipoBanca: 'ganada' | 'previa' | null } | null; | ||||
|     ultimaActualizacion: string; | ||||
|   camaraNombre: string; | ||||
|   totalBancas: number; | ||||
|   bancasEnJuego: number; | ||||
|   partidos: PartidoComposicionNacional[]; | ||||
|   presidenteBancada: { color: string | null; tipoBanca: 'ganada' | 'previa' | null } | null; | ||||
|   ultimaActualizacion: string; | ||||
| } | ||||
|  | ||||
| export interface ComposicionNacionalData { | ||||
|     diputados: CamaraComposicionNacional; | ||||
|     senadores: CamaraComposicionNacional; | ||||
|   diputados: CamaraComposicionNacional; | ||||
|   senadores: CamaraComposicionNacional; | ||||
| } | ||||
|  | ||||
| export interface ResumenParams { | ||||
|   focoDistritoId?: string; | ||||
|   focoCategoriaId?: number; | ||||
|   cantidadResultados?: number; | ||||
| } | ||||
|  | ||||
| export const getResumenProvincial = async (eleccionId: number): Promise<CategoriaResumen[]> => { | ||||
| @@ -239,27 +247,55 @@ export const getEstablecimientosPorMunicipio = async (municipioId: string): Prom | ||||
| }; | ||||
|  | ||||
| export const getPanelElectoral = async (eleccionId: number, ambitoId: string | null, categoriaId: number): Promise<PanelElectoralDto> => { | ||||
|      | ||||
|     // Construimos la URL base | ||||
|     let url = ambitoId  | ||||
|         ? `/elecciones/${eleccionId}/panel/${ambitoId}` | ||||
|         : `/elecciones/${eleccionId}/panel`; | ||||
|  | ||||
|     // Añadimos categoriaId como un query parameter | ||||
|     url += `?categoriaId=${categoriaId}`; | ||||
|          | ||||
|     const { data } = await apiClient.get(url); | ||||
|     return data; | ||||
|   // Construimos la URL base | ||||
|   let url = ambitoId | ||||
|     ? `/elecciones/${eleccionId}/panel/${ambitoId}` | ||||
|     : `/elecciones/${eleccionId}/panel`; | ||||
|  | ||||
|   // Añadimos categoriaId como un query parameter | ||||
|   url += `?categoriaId=${categoriaId}`; | ||||
|  | ||||
|   const { data } = await apiClient.get(url); | ||||
|   return data; | ||||
| }; | ||||
|  | ||||
| export const getComposicionNacional = async (eleccionId: number): Promise<ComposicionNacionalData> => { | ||||
|     const { data } = await apiClient.get(`/elecciones/${eleccionId}/composicion-nacional`); | ||||
|     return data; | ||||
|   const { data } = await apiClient.get(`/elecciones/${eleccionId}/composicion-nacional`); | ||||
|   return data; | ||||
| }; | ||||
|  | ||||
| // 11. Endpoint para el widget de tarjetas nacionales | ||||
| export const getResumenPorProvincia = async (eleccionId: number): Promise<ResumenProvincia[]> => { | ||||
|     // Usamos el cliente público ya que son datos de resultados | ||||
|     const { data } = await apiClient.get(`/elecciones/${eleccionId}/resumen-por-provincia`); | ||||
| export const getResumenPorProvincia = async (eleccionId: number, params: ResumenParams = {}): Promise<ResumenProvincia[]> => { | ||||
|   // Usamos URLSearchParams para construir la query string de forma segura y limpia | ||||
|   const queryParams = new URLSearchParams(); | ||||
|  | ||||
|   if (params.focoDistritoId) { | ||||
|     queryParams.append('focoDistritoId', params.focoDistritoId); | ||||
|   } | ||||
|   if (params.focoCategoriaId) { | ||||
|     queryParams.append('focoCategoriaId', params.focoCategoriaId.toString()); | ||||
|   } | ||||
|   if (params.cantidadResultados) { | ||||
|     queryParams.append('cantidadResultados', params.cantidadResultados.toString()); | ||||
|   } | ||||
|  | ||||
|   const queryString = queryParams.toString(); | ||||
|  | ||||
|   // Añadimos la query string a la URL solo si tiene contenido | ||||
|   const url = `/elecciones/${eleccionId}/resumen-por-provincia${queryString ? `?${queryString}` : ''}`; | ||||
|  | ||||
|   const { data } = await apiClient.get(url); | ||||
|   return data; | ||||
| }; | ||||
|  | ||||
| export const getHomeResumen = async (eleccionId: number, distritoId: string, categoriaId: number): Promise<CategoriaResumenHome> => { | ||||
|     const queryParams = new URLSearchParams({ | ||||
|         eleccionId: eleccionId.toString(), | ||||
|         distritoId: distritoId, | ||||
|         categoriaId: categoriaId.toString(), | ||||
|     }); | ||||
|     const url = `/elecciones/home-resumen?${queryParams.toString()}`; | ||||
|     const { data } = await apiClient.get(url); | ||||
|     return data; | ||||
| }; | ||||
| @@ -38,7 +38,7 @@ export const DevApp = () => { | ||||
|         <DiputadosPorSeccionWidget /> | ||||
|         <SenadoresPorSeccionWidget /> | ||||
|         <ConcejalesPorSeccionWidget /> | ||||
|         <CongresoWidget /> | ||||
|         <CongresoWidget eleccionId={1} /> | ||||
|         <BancasWidget /> | ||||
|         <MapaBsAs /> | ||||
|         <MapaBsAsSecciones /> | ||||
|   | ||||
| @@ -1,14 +1,145 @@ | ||||
| // src/features/legislativas/rovinciales/DevAppLegislativas.tsx | ||||
| // src/features/legislativas/nacionales/DevAppLegislativas.tsx | ||||
| import { useState } from 'react'; // <-- Importar useState | ||||
| import { ResultadosNacionalesCardsWidget } from './nacionales/ResultadosNacionalesCardsWidget'; | ||||
| import { CongresoNacionalWidget } from './nacionales/CongresoNacionalWidget'; | ||||
| import { PanelNacionalWidget } from './nacionales/PanelNacionalWidget'; | ||||
| import { HomeCarouselWidget } from './nacionales/HomeCarouselWidget'; | ||||
| import './DevAppStyle.css' | ||||
|  | ||||
| // --- NUEVO COMPONENTE REUTILIZABLE PARA CONTENIDO COLAPSABLE --- | ||||
| const CollapsibleWidgetWrapper = ({ children }: { children: React.ReactNode }) => { | ||||
|     const [isExpanded, setIsExpanded] = useState(false); | ||||
|  | ||||
|     return ( | ||||
|         <div className="collapsible-container"> | ||||
|             <div className={`collapsible-content ${isExpanded ? 'expanded' : ''}`}> | ||||
|                 {children} | ||||
|             </div> | ||||
|             <button className="toggle-button" onClick={() => setIsExpanded(!isExpanded)}> | ||||
|                 {isExpanded ? 'Mostrar Menos' : 'Mostrar Más'} | ||||
|             </button> | ||||
|         </div> | ||||
|     ); | ||||
| }; | ||||
|  | ||||
| export const DevAppLegislativas = () => { | ||||
|     // Estilos para los separadores y descripciones para mejorar la legibilidad | ||||
|     const sectionStyle = { | ||||
|         border: '2px solid #007bff', | ||||
|         borderRadius: '8px', | ||||
|         padding: '1rem 2rem', | ||||
|         marginTop: '3rem', | ||||
|         marginBottom: '3rem', | ||||
|         backgroundColor: '#f8f9fa' | ||||
|     }; | ||||
|     const descriptionStyle = { | ||||
|         fontFamily: 'sans-serif', | ||||
|         color: '#333', | ||||
|         lineHeight: 1.6 | ||||
|     }; | ||||
|     const codeStyle = { | ||||
|         backgroundColor: '#e9ecef', | ||||
|         padding: '2px 6px', | ||||
|         borderRadius: '4px', | ||||
|         fontFamily: 'Roboto' | ||||
|     }; | ||||
|  | ||||
|     return ( | ||||
|         <div className="container"> | ||||
|             <h1>Visor de Widgets</h1> | ||||
|             <ResultadosNacionalesCardsWidget eleccionId={2} /> | ||||
|  | ||||
|             <div style={sectionStyle}> | ||||
|                 <h2>Widget: Carrusel de Resultados (Home)</h2> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Uso: <code style={codeStyle}><HomeCarouselWidget eleccionId={2} distritoId="02" categoriaId={2} titulo="Diputados - Provincia de Buenos Aires" /></code> | ||||
|                 </p> | ||||
|                 <HomeCarouselWidget | ||||
|                     eleccionId={2} // Nacional | ||||
|                     distritoId="02" // Buenos Aires | ||||
|                     categoriaId={2} // Diputados Nacionales | ||||
|                     titulo="Diputados - Provincia de Buenos Aires" | ||||
|                 /> | ||||
|             </div> | ||||
|  | ||||
|             {/* --- SECCIÓN PARA EL WIDGET DE TARJETAS CON EJEMPLOS --- */} | ||||
|             <div style={sectionStyle}> | ||||
|                 <h2>Widget: Resultados por Provincia (Tarjetas)</h2> | ||||
|                  | ||||
|                 <hr /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>1. Vista por Defecto</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Sin parámetros adicionales. Muestra todas las provincias, con sus categorías correspondientes (Diputados para las 24, Senadores para las 8 que renuevan). Muestra los 2 principales partidos por defecto. | ||||
|                     <br /> | ||||
|                     Uso: <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} /></code> | ||||
|                 </p> | ||||
|                 <CollapsibleWidgetWrapper> | ||||
|                     <ResultadosNacionalesCardsWidget eleccionId={2} /> | ||||
|                 </CollapsibleWidgetWrapper> | ||||
|  | ||||
|                 <hr style={{ marginTop: '2rem' }} /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>2. Filtrado por Provincia (focoDistritoId)</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Muestra únicamente la tarjeta de una provincia específica. Ideal para páginas de noticias locales. El ID de distrito ("02" para Bs. As., "06" para Chaco) se pasa como prop. | ||||
|                     <br /> | ||||
|                     Ejemplo Buenos Aires: <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="02" /></code> | ||||
|                 </p> | ||||
|                 <ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="02" /> | ||||
|                  | ||||
|                 <p style={{ ...descriptionStyle, marginTop: '2rem' }}> | ||||
|                     Ejemplo Chaco (que también renueva Senadores): <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="06" /></code> | ||||
|                 </p> | ||||
|                 <ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="06" /> | ||||
|  | ||||
|                 <hr style={{ marginTop: '2rem' }} /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>3. Filtrado por Categoría (focoCategoriaId)</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Muestra todas las provincias que votan para una categoría específica. | ||||
|                     <br /> | ||||
|                     Ejemplo Senadores (ID 1): <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} focoCategoriaId={1} /></code> | ||||
|                 </p> | ||||
|                 <ResultadosNacionalesCardsWidget eleccionId={2} focoCategoriaId={1} /> | ||||
|                  | ||||
|                 <hr style={{ marginTop: '2rem' }} /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>4. Indicando Cantidad de Resultados (cantidadResultados)</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Controla cuántos partidos se muestran en cada categoría. Por defecto son 2. | ||||
|                     <br /> | ||||
|                     Ejemplo mostrando el TOP 3 de cada categoría: <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} cantidadResultados={3} /></code> | ||||
|                 </p> | ||||
|                 <CollapsibleWidgetWrapper> | ||||
|                     <ResultadosNacionalesCardsWidget eleccionId={2} cantidadResultados={3} /> | ||||
|                 </CollapsibleWidgetWrapper> | ||||
|  | ||||
|                 <hr style={{ marginTop: '2rem' }} /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>5. Mostrando las Bancas (mostrarBancas)</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Útil para contextos donde importan las bancas. La prop <code style={codeStyle}>mostrarBancas</code> se establece en <code style={codeStyle}>true</code>. | ||||
|                     <br /> | ||||
|                     Ejemplo en Tierra del Fuego: <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="23" mostrarBancas={true} /></code> | ||||
|                 </p> | ||||
|                 <ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="23" mostrarBancas={true} /> | ||||
|  | ||||
|                 <hr style={{ marginTop: '2rem' }} /> | ||||
|  | ||||
|                 <h3 style={{ marginTop: '2rem' }}>6. Combinación de Parámetros</h3> | ||||
|                 <p style={descriptionStyle}> | ||||
|                     Se pueden combinar todos los parámetros para vistas muy específicas. | ||||
|                     <br /> | ||||
|                     Ejemplo: Mostrar el TOP 1 (el ganador) para la categoría de SENADORES en la provincia de RÍO NEGRO (Distrito ID "16"). | ||||
|                     <br /> | ||||
|                     Uso: <code style={codeStyle}><ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="16" focoCategoriaId={1} cantidadResultados={1} /></code> | ||||
|                 </p> | ||||
|                 <ResultadosNacionalesCardsWidget eleccionId={2} focoDistritoId="16" focoCategoriaId={1} cantidadResultados={1} /> | ||||
|  | ||||
|             </div> | ||||
|  | ||||
|  | ||||
|             {/* --- OTROS WIDGETS --- */} | ||||
|             <CongresoNacionalWidget eleccionId={2} /> | ||||
|             <PanelNacionalWidget eleccionId={2} /> | ||||
|         </div> | ||||
|   | ||||
| @@ -1,3 +1,50 @@ | ||||
| .container{ | ||||
|     text-align: center; | ||||
| } | ||||
|  | ||||
| /* --- ESTILOS PARA EL CONTENEDOR COLAPSABLE --- */ | ||||
|  | ||||
| .collapsible-container { | ||||
|     position: relative; | ||||
|     padding-bottom: 50px; /* Espacio para el botón de expandir */ | ||||
| } | ||||
|  | ||||
| .collapsible-content { | ||||
|     max-height: 950px; /* Altura suficiente para 2 filas de tarjetas (aprox) */ | ||||
|     overflow: hidden; | ||||
|     transition: max-height 0.7s ease-in-out; | ||||
|     position: relative; | ||||
| } | ||||
|  | ||||
| .collapsible-content.expanded { | ||||
|     max-height: 100%; /* Un valor grande para asegurar que todo el contenido sea visible */ | ||||
| } | ||||
|  | ||||
| /* Pseudo-elemento para crear un degradado y sugerir que hay más contenido */ | ||||
| .collapsible-content:not(.expanded)::after { | ||||
|     content: ''; | ||||
|     position: absolute; | ||||
|     bottom: 0; | ||||
|     left: 0; | ||||
|     right: 0; | ||||
|     height: 150px; | ||||
|     background: linear-gradient(to top, rgba(248, 249, 250, 1) 20%, rgba(248, 249, 250, 0)); | ||||
|     pointer-events: none; /* Permite hacer clic a través del degradado */ | ||||
| } | ||||
|  | ||||
| .toggle-button { | ||||
|     position: absolute; | ||||
|     bottom: 10px; | ||||
|     left: 50%; | ||||
|     transform: translateX(-50%); | ||||
|     padding: 10px 20px; | ||||
|     font-size: 1rem; | ||||
|     font-weight: bold; | ||||
|     color: #fff; | ||||
|     background-color: #007bff; | ||||
|     border: none; | ||||
|     border-radius: 20px; | ||||
|     cursor: pointer; | ||||
|     box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); | ||||
|     z-index: 2; | ||||
| } | ||||
| @@ -0,0 +1,239 @@ | ||||
| /* src/features/legislativas/nacionales/HomeCarouselWidget.css */ | ||||
|  | ||||
| .home-carousel-widget { | ||||
|     --primary-text: #212529; | ||||
|     --secondary-text: #6c757d; | ||||
|     --border-color: #dee2e6; | ||||
|     --background-light: #f8f9fa; | ||||
|     --background-white: #ffffff; | ||||
|     --shadow: 0 2px 8px rgba(0, 0, 0, 0.07); | ||||
|     --font-family-sans: "Roboto", system-ui, sans-serif; | ||||
| } | ||||
|  | ||||
| .home-carousel-widget { | ||||
|     font-family: var(--font-family-sans); | ||||
|     background-color: var(--background-white); | ||||
|     border: 1px solid var(--border-color); | ||||
|     border-radius: 8px; | ||||
|     padding: 0.75rem; | ||||
|     max-width: 1200px; | ||||
|     margin: 2rem auto; | ||||
| } | ||||
|  | ||||
| .widget-title { | ||||
|     font-size: 1.2rem; | ||||
|     font-weight: 900; | ||||
|     color: var(--primary-text); | ||||
|     margin: 0 0 0.5rem 0; | ||||
|     padding-bottom: 0.5rem; | ||||
|     border-bottom: 1px solid var(--border-color); | ||||
|     text-align: left; | ||||
| } | ||||
|  | ||||
| .top-stats-bar { | ||||
|     display: flex; | ||||
|     justify-content: space-around; | ||||
|     background-color: transparent; | ||||
|     border: 1px solid var(--border-color); | ||||
|     border-radius: 8px; | ||||
|     padding: 0.3rem 0.5rem; | ||||
|     margin-bottom: 0.5rem; | ||||
| } | ||||
|  | ||||
| .top-stats-bar > div {  | ||||
|     display: flex; | ||||
|     align-items: baseline; | ||||
|     gap: 0.5rem; | ||||
|     border-right: 1px solid var(--border-color);  | ||||
|     padding: 0 0.5rem; | ||||
|     flex-grow: 1; | ||||
|     justify-content: center; | ||||
| } | ||||
| .top-stats-bar > div:last-child { border-right: none; } | ||||
| .top-stats-bar span { font-size: 0.9rem; color: var(--secondary-text); } | ||||
| .top-stats-bar strong { font-size: 0.9rem; font-weight: 600; color: var(--primary-text); } | ||||
|  | ||||
| .candidate-card { | ||||
|     display: flex; | ||||
|     align-items: center; | ||||
|     gap: 0.75rem; | ||||
|     background: var(--background-white); | ||||
|     border: 1px solid var(--border-color); | ||||
|     border-radius: 12px; | ||||
|     padding: 0.75rem; | ||||
|     box-shadow: var(--shadow); | ||||
|     height: 100%; | ||||
|     border-left: 5px solid; | ||||
|     border-left-color: var(--candidate-color, #ccc); | ||||
|     position: relative; | ||||
| } | ||||
|  | ||||
| .candidate-photo-wrapper { | ||||
|     flex-shrink: 0; | ||||
|     width: 60px; | ||||
|     height: 60px; | ||||
|     border-radius: 8px; | ||||
|     overflow: hidden; | ||||
|     background-color: var(--candidate-color, #e9ecef); | ||||
| } | ||||
|  | ||||
| .candidate-photo { | ||||
|     width: 100%; | ||||
|     height: 100%; | ||||
|     object-fit: cover; | ||||
|     box-sizing: border-box; | ||||
| } | ||||
|  | ||||
| .candidate-details { | ||||
|     flex-grow: 1; | ||||
|     display: flex; | ||||
|     justify-content: space-between; | ||||
|     align-items: center; | ||||
|     min-width: 0; | ||||
| } | ||||
|  | ||||
| .candidate-info { | ||||
|     display: flex; | ||||
|     flex-direction: column; | ||||
|     justify-content: center; | ||||
|     align-items:flex-start; | ||||
|     gap: 0.1rem; | ||||
|     min-width: 0; | ||||
|     margin-right: 0.75rem; | ||||
| } | ||||
|  | ||||
| .candidate-name, .party-name { | ||||
|     white-space: nowrap; | ||||
|     overflow: hidden; | ||||
|     text-overflow: ellipsis; | ||||
|     display: block; | ||||
|     width: 100%; | ||||
| } | ||||
| .candidate-name { | ||||
|     font-size: 0.95rem; | ||||
|     text-align: left; | ||||
|     font-weight: 700; | ||||
|     color: var(--primary-text); | ||||
| } | ||||
| .party-name { | ||||
|     font-size: 0.8rem; | ||||
|     text-align: left; | ||||
|     text-transform: uppercase; | ||||
|     color: var(--secondary-text); | ||||
|     text-transform: uppercase; | ||||
| } | ||||
|  | ||||
| .candidate-results { text-align: right; flex-shrink: 0; } | ||||
| .percentage { | ||||
|     display: block; | ||||
|     font-size: 1.2rem; | ||||
|     font-weight: 700; | ||||
|     color: var(--primary-text); | ||||
|     line-height: 1.1; | ||||
| } | ||||
| .votes { | ||||
|     font-size: 0.75rem; | ||||
|     color: var(--secondary-text); | ||||
|     white-space: nowrap; | ||||
| } | ||||
|  | ||||
| .swiper-slide:not(:last-child) .candidate-card::after { | ||||
|     content: ''; | ||||
|     position: absolute; | ||||
|     right: -8px; | ||||
|     top: 20%; | ||||
|     bottom: 20%; | ||||
|     width: 1px; | ||||
|     background-color: var(--border-color); | ||||
| } | ||||
|  | ||||
| .swiper-button-prev, .swiper-button-next { | ||||
|     width: 30px; height: 30px; | ||||
|     background-color: rgba(255, 255, 255, 0.9); | ||||
|     border: 1px solid var(--border-color); | ||||
|     border-radius: 50%; | ||||
|     box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1); | ||||
|     transition: opacity 0.2s; | ||||
|     color: var(--secondary-text); | ||||
| } | ||||
| .swiper-button-prev:after, .swiper-button-next:after { | ||||
|     font-size: 18px; | ||||
|     font-weight: bold; | ||||
| } | ||||
| .swiper-button-prev { left: -10px; } | ||||
| .swiper-button-next { right: -10px; } | ||||
| .swiper-button-disabled { opacity: 0; pointer-events: none; } | ||||
|  | ||||
| .widget-footer { | ||||
|   text-align: right; | ||||
|   font-size: 0.75rem; | ||||
|   color: var(--secondary-text); | ||||
|   margin-top: 0.5rem;  | ||||
| } | ||||
|  | ||||
| .short-text { | ||||
|     display: none; /* Oculto por defecto en la vista de escritorio */ | ||||
| } | ||||
|  | ||||
| /* --- INICIO DE LA SECCIÓN DE ESTILOS PARA MÓVIL --- */ | ||||
| @media (max-width: 768px) { | ||||
|     .home-carousel-widget {  | ||||
|         padding: 0.75rem;  | ||||
|     } | ||||
|  | ||||
|     /* 1. Centrar el título en móvil */ | ||||
|     .widget-title { | ||||
|         text-align: center; | ||||
|         font-size: 1.1rem; | ||||
|     } | ||||
|  | ||||
|     /* 2. Reestructurar la barra de estadísticas a 2x2 y usar textos cortos */ | ||||
|     .top-stats-bar { | ||||
|         display: grid; | ||||
|         grid-template-columns: repeat(2, 1fr); | ||||
|         gap: 0.2rem; | ||||
|         padding: 0.3rem; | ||||
|     } | ||||
|  | ||||
|     .top-stats-bar > div { | ||||
|         padding: 0.25rem 0.5rem; | ||||
|         border-right: none; /* Quitar todos los bordes derechos */ | ||||
|     } | ||||
|  | ||||
|     .top-stats-bar > div:nth-child(odd) { | ||||
|         border-right: 1px solid var(--border-color); /* Restablecer borde solo para la columna izquierda */ | ||||
|     } | ||||
|      | ||||
|     /* Lógica de visibilidad de textos */ | ||||
|     .long-text { | ||||
|         display: none; /* Ocultar el texto largo en móvil */ | ||||
|     } | ||||
|     .short-text { | ||||
|         display:inline; /* Mostrar el texto corto en móvil */ | ||||
|     } | ||||
|  | ||||
|     /* Reducir fuentes para que quepan mejor */ | ||||
|     .top-stats-bar span { font-size: 0.8rem; text-align: left; } | ||||
|     .top-stats-bar strong { font-size: 0.85rem; text-align: right;} | ||||
|  | ||||
|     /* --- Botones del Carrusel (sin cambios) --- */ | ||||
|     .swiper-button-prev, .swiper-button-next { | ||||
|         width: 32px; | ||||
|         height: 32px; | ||||
|         top: 45%; | ||||
|     } | ||||
|     .swiper-button-prev { left: 2px; } | ||||
|     .swiper-button-next { right: 2px; } | ||||
|  | ||||
|     /* --- Ajustes en la tarjeta (sin cambios) --- */ | ||||
|     .candidate-card { gap: 0.5rem; padding: 0.5rem; } | ||||
|     .candidate-photo-wrapper { width: 50px; height: 50px; } | ||||
|     .candidate-name { font-size: 0.9rem; } | ||||
|     .percentage { font-size: 1.1rem; } | ||||
|     .votes { font-size: 0.7rem; } | ||||
|  | ||||
|     /* 3. Centrar el footer en móvil */ | ||||
|     .widget-footer { | ||||
|         text-align: center; | ||||
|     } | ||||
| } | ||||
| @@ -0,0 +1,135 @@ | ||||
| // src/features/legislativas/nacionales/HomeCarouselWidget.tsx | ||||
| import { useQuery } from '@tanstack/react-query'; | ||||
| import { getHomeResumen } from '../../../apiService'; | ||||
| import { ImageWithFallback } from '../../../components/common/ImageWithFallback'; | ||||
| import { assetBaseUrl } from '../../../apiService'; | ||||
| import { Swiper, SwiperSlide } from 'swiper/react'; | ||||
| import { Navigation, A11y } from 'swiper/modules'; | ||||
|  | ||||
| // @ts-ignore | ||||
| import 'swiper/css'; | ||||
| // @ts-ignore | ||||
| import 'swiper/css/navigation'; | ||||
| import './HomeCarouselWidget.css'; | ||||
|  | ||||
| interface Props { | ||||
|     eleccionId: number; | ||||
|     distritoId: string; | ||||
|     categoriaId: number; | ||||
|     titulo: string; | ||||
| } | ||||
|  | ||||
| const formatPercent = (num: number | null | undefined) => `${(num || 0).toFixed(2).replace('.', ',')}%`; | ||||
| const formatNumber = (num: number) => num.toLocaleString('es-AR'); | ||||
|  | ||||
| // --- Lógica de formateo de fecha --- | ||||
| const formatDateTime = (dateString: string | undefined | null) => { | ||||
|     if (!dateString) return '...'; | ||||
|     try { | ||||
|         const date = new Date(dateString); | ||||
|         // Verificar si la fecha es válida | ||||
|         if (isNaN(date.getTime())) { | ||||
|             return dateString; // Si no se puede parsear, devolver el string original | ||||
|         } | ||||
|         const day = String(date.getDate()).padStart(2, '0'); | ||||
|         const month = String(date.getMonth() + 1).padStart(2, '0'); | ||||
|         const year = date.getFullYear(); | ||||
|         const hours = String(date.getHours()).padStart(2, '0'); | ||||
|         const minutes = String(date.getMinutes()).padStart(2, '0'); | ||||
|         return `${day}/${month}/${year}, ${hours}:${minutes} hs.`; | ||||
|     } catch (e) { | ||||
|         return dateString; // En caso de cualquier error, devolver el string original | ||||
|     } | ||||
| }; | ||||
|  | ||||
| export const HomeCarouselWidget = ({ eleccionId, distritoId, categoriaId, titulo }: Props) => { | ||||
|     const { data, isLoading, error } = useQuery({ | ||||
|         queryKey: ['homeResumen', eleccionId, distritoId, categoriaId], | ||||
|         queryFn: () => getHomeResumen(eleccionId, distritoId, categoriaId), | ||||
|     }); | ||||
|  | ||||
|     if (isLoading) return <div>Cargando widget...</div>; | ||||
|     if (error || !data) return <div>No se pudieron cargar los datos.</div>; | ||||
|  | ||||
|     return ( | ||||
|         <div className="home-carousel-widget"> | ||||
|             <h2 className="widget-title">{titulo}</h2> | ||||
|  | ||||
|             <div className="top-stats-bar"> | ||||
|                 <div> | ||||
|                     <span>Participación</span> | ||||
|                     <strong>{formatPercent(data.estadoRecuento?.participacionPorcentaje)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span className="long-text">Mesas escrutadas</span> | ||||
|                     <span className="short-text">Escrutado</span> | ||||
|                     <strong>{formatPercent(data.estadoRecuento?.mesasTotalizadasPorcentaje)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span className="long-text">Votos en blanco</span> | ||||
|                     <span className="short-text">En blanco</span> | ||||
|                     <strong>{formatPercent(data.votosEnBlancoPorcentaje)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span className="long-text">Votos totales</span> | ||||
|                     <span className="short-text">Votos</span> | ||||
|                     <strong>{formatNumber(data.votosTotales)}</strong> | ||||
|                 </div> | ||||
|             </div> | ||||
|  | ||||
|             <Swiper | ||||
|                 modules={[Navigation, A11y]} | ||||
|                 spaceBetween={16} | ||||
|                 slidesPerView={1.15} | ||||
|                 navigation | ||||
|                 breakpoints={{ 640: { slidesPerView: 2 }, 1024: { slidesPerView: 3 }, 1200: { slidesPerView: 3.5 } }} // Añadir breakpoint | ||||
|             > | ||||
|                 {data.resultados.map(candidato => ( | ||||
|                     <SwiperSlide key={candidato.agrupacionId}> | ||||
|                         <div className="candidate-card" style={{ '--candidate-color': candidato.color || '#ccc' } as React.CSSProperties}> | ||||
|  | ||||
|                             <div className="candidate-photo-wrapper"> | ||||
|                                 <ImageWithFallback | ||||
|                                     src={candidato.fotoUrl ?? undefined} | ||||
|                                     fallbackSrc={`${assetBaseUrl}/default-avatar.png`} | ||||
|                                     alt={candidato.nombreCandidato ?? ''} | ||||
|                                     className="candidate-photo" | ||||
|                                 /> | ||||
|                             </div> | ||||
|  | ||||
|                             <div className="candidate-details"> | ||||
|                                 <div className="candidate-info"> | ||||
|                                     {candidato.nombreCandidato ? ( | ||||
|                                         // CASO 1: Hay un candidato (se muestran dos líneas) | ||||
|                                         <> | ||||
|                                             <span className="candidate-name"> | ||||
|                                                 {candidato.nombreCandidato} | ||||
|                                             </span> | ||||
|                                             <span className="party-name"> | ||||
|                                                 {candidato.nombreCortoAgrupacion || candidato.nombreAgrupacion} | ||||
|                                             </span> | ||||
|                                         </> | ||||
|                                     ) : ( | ||||
|                                         // CASO 2: No hay candidato (se muestra solo una línea) | ||||
|                                         <span className="candidate-name"> | ||||
|                                             {candidato.nombreCortoAgrupacion || candidato.nombreAgrupacion} | ||||
|                                         </span> | ||||
|                                     )} | ||||
|                                 </div> | ||||
|                                 <div className="candidate-results"> | ||||
|                                     <span className="percentage">{formatPercent(candidato.porcentaje)}</span> | ||||
|                                     <span className="votes">{formatNumber(candidato.votos)} votos</span> | ||||
|                                 </div> | ||||
|                             </div> | ||||
|  | ||||
|                         </div> | ||||
|                     </SwiperSlide> | ||||
|                 ))} | ||||
|             </Swiper> | ||||
|  | ||||
|             <div className="widget-footer"> | ||||
|                 Última actualización: {formatDateTime(data.ultimaActualizacion)} | ||||
|             </div> | ||||
|         </div> | ||||
|     ); | ||||
| }; | ||||
| @@ -22,14 +22,9 @@ | ||||
| /* Contenedor para alinear título y selector */ | ||||
| .header-top-row { | ||||
|   display: flex; | ||||
|   justify-content: space-between; | ||||
|   justify-content: flex-start; /* Alinea los items al inicio */ | ||||
|   align-items: center; | ||||
|   margin-bottom: 0.5rem; | ||||
| } | ||||
|  | ||||
| .panel-header h1 { | ||||
|   font-size: 1.5rem; | ||||
|   margin: 0; | ||||
|   gap: 2rem; /* Añade un espacio de separación de 2rem entre el selector y el breadcrumb */ | ||||
| } | ||||
|  | ||||
| .categoria-selector { | ||||
| @@ -188,6 +183,7 @@ | ||||
|   padding: 1rem 0; | ||||
|   border-bottom: 1px solid #f0f0f0; | ||||
|   border-left: 5px solid; | ||||
|   border-radius: 12px; | ||||
|   padding-left: 1rem; | ||||
| } | ||||
|  | ||||
| @@ -227,18 +223,25 @@ | ||||
| .partido-info-wrapper { | ||||
|   /* Ocupa el espacio disponible a la izquierda */ | ||||
|   min-width: 0; | ||||
|   text-align: left; | ||||
| } | ||||
|  | ||||
| .partido-nombre { | ||||
|   font-weight: 800; | ||||
|   font-weight: 700; | ||||
|   font-size: 1.05rem; | ||||
|   color: #212529; | ||||
|   white-space: nowrap; | ||||
|   overflow: hidden; | ||||
|   text-overflow: ellipsis; | ||||
|   line-height: 1.2; | ||||
| } | ||||
|  | ||||
| .candidato-nombre { | ||||
|   font-size: 0.85rem; | ||||
|   color: #666; | ||||
|   font-size: 0.8rem; | ||||
|   color: #6c757d; | ||||
|   text-transform: uppercase; | ||||
|   font-weight: 500; | ||||
|   line-height: 1.1; | ||||
| } | ||||
|  | ||||
| .partido-stats { | ||||
| @@ -381,10 +384,13 @@ | ||||
| } | ||||
|  | ||||
| .rsm-geography:not(.selected):hover { | ||||
|   filter: brightness(1.25); /* Mantenemos el brillo */ | ||||
|   stroke: #ffffff;      /* Color del borde a blanco */ | ||||
|   filter: brightness(1.25); | ||||
|   /* Mantenemos el brillo */ | ||||
|   stroke: #ffffff; | ||||
|   /* Color del borde a blanco */ | ||||
|   stroke-width: 0.25px; | ||||
|   paint-order: stroke;  /* Asegura que el borde se dibuje encima del relleno */ | ||||
|   paint-order: stroke; | ||||
|   /* Asegura que el borde se dibuje encima del relleno */ | ||||
| } | ||||
|  | ||||
| .rsm-geography.selected { | ||||
| @@ -492,8 +498,10 @@ | ||||
| /* --- NUEVOS ESTILOS PARA EL TOGGLE MÓVIL --- */ | ||||
| .mobile-view-toggle { | ||||
|   display: none; | ||||
|   position: absolute; /* <-- CAMBIO: De 'fixed' a 'absolute' */ | ||||
|   bottom: 10px; /* <-- AJUSTE: Menos espacio desde abajo */ | ||||
|   position: absolute; | ||||
|   /* <-- CAMBIO: De 'fixed' a 'absolute' */ | ||||
|   bottom: 10px; | ||||
|   /* <-- AJUSTE: Menos espacio desde abajo */ | ||||
|   left: 50%; | ||||
|   transform: translateX(-50%); | ||||
|   z-index: 100; | ||||
| @@ -685,6 +693,14 @@ | ||||
|     display: flex; | ||||
|     align-items: center; | ||||
|     gap: 1rem; | ||||
|     padding: 1rem 0; | ||||
|     border-bottom: 1px solid #f0f0f0; | ||||
|     border-left: 5px solid; | ||||
|     /* Grosor del borde */ | ||||
|     border-radius: 12px; | ||||
|     /* Redondeamos las esquinas */ | ||||
|     padding-left: 1rem; | ||||
|     /* Espacio a la izquierda */ | ||||
|   } | ||||
|  | ||||
|   .partido-logo { | ||||
|   | ||||
| @@ -10,6 +10,7 @@ import Select from 'react-select'; | ||||
| import type { PanelElectoralDto } from '../../../types/types'; | ||||
| import { FiMap, FiList } from 'react-icons/fi'; | ||||
| import { useMediaQuery } from './hooks/useMediaQuery'; | ||||
| import { Toaster } from 'react-hot-toast'; | ||||
|  | ||||
| interface PanelNacionalWidgetProps { | ||||
|   eleccionId: number; | ||||
| @@ -79,9 +80,9 @@ export const PanelNacionalWidget = ({ eleccionId }: PanelNacionalWidgetProps) => | ||||
|  | ||||
|   return ( | ||||
|     <div className="panel-nacional-container"> | ||||
|       <Toaster containerClassName="widget-toaster-container" /> | ||||
|       <header className="panel-header"> | ||||
|         <div className="header-top-row"> | ||||
|           <h1>Legislativas Argentina 2025</h1> | ||||
|           <Select | ||||
|             options={CATEGORIAS_NACIONALES} | ||||
|             value={selectedCategoria} | ||||
| @@ -90,14 +91,14 @@ export const PanelNacionalWidget = ({ eleccionId }: PanelNacionalWidgetProps) => | ||||
|             classNamePrefix="categoria-selector" | ||||
|             isSearchable={false} | ||||
|           /> | ||||
|           <Breadcrumbs | ||||
|             nivel={ambitoActual.nivel} | ||||
|             nombreAmbito={ambitoActual.nombre} | ||||
|             nombreProvincia={ambitoActual.provinciaNombre} | ||||
|             onReset={handleResetToPais} | ||||
|             onVolverProvincia={handleVolverAProvincia} | ||||
|           /> | ||||
|         </div> | ||||
|         <Breadcrumbs | ||||
|           nivel={ambitoActual.nivel} | ||||
|           nombreAmbito={ambitoActual.nombre} | ||||
|           nombreProvincia={ambitoActual.provinciaNombre} | ||||
|           onReset={handleResetToPais} | ||||
|           onVolverProvincia={handleVolverAProvincia} | ||||
|         /> | ||||
|       </header> | ||||
|       <main className={`panel-main-content ${!isPanelOpen ? 'panel-collapsed' : ''} ${isMobile ? `mobile-view-${mobileView}` : ''}`}> | ||||
|         <div className="mapa-column"> | ||||
|   | ||||
| @@ -8,7 +8,7 @@ | ||||
|     --card-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); | ||||
|     --text-primary: #212529; | ||||
|     --text-secondary: #6c757d; | ||||
|     --font-family: "Public Sans", system-ui, sans-serif; | ||||
|     --font-family: "Roboto", system-ui, sans-serif; | ||||
|     --primary-accent-color: #007bff; | ||||
| } | ||||
|  | ||||
| @@ -34,6 +34,7 @@ | ||||
|     /* Crea columnas flexibles que se ajustan al espacio disponible */ | ||||
|     grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); | ||||
|     gap: 1.5rem; | ||||
|     align-items: start; | ||||
| } | ||||
|  | ||||
| /* --- Tarjeta Individual --- */ | ||||
| @@ -110,6 +111,9 @@ | ||||
|     gap: 0.75rem; | ||||
|     padding: 0.75rem 0; | ||||
|     border-bottom: 1px solid #f0f0f0; | ||||
|     border-left: 5px solid; /* Grosor del borde */ | ||||
|     border-radius: 12px;     /* Redondeamos las esquinas para un look más suave */ | ||||
|     padding-left: 1rem;      /* Añadimos un poco de espacio a la izquierda */ | ||||
| } | ||||
|  | ||||
| .candidato-row:last-child { | ||||
| @@ -117,9 +121,9 @@ | ||||
| } | ||||
|  | ||||
| .candidato-foto { | ||||
|     width: 45px; | ||||
|     height: 45px; | ||||
|     border-radius: 50%; | ||||
|     width: 60px; | ||||
|     height: 60px; | ||||
|     border-radius: 5%; | ||||
|     object-fit: cover; | ||||
|     flex-shrink: 0; | ||||
| } | ||||
| @@ -135,6 +139,7 @@ | ||||
|     font-size: 0.95rem; | ||||
|     color: var(--text-primary); | ||||
|     display: block; | ||||
|     text-align: left; | ||||
| } | ||||
|  | ||||
| .candidato-partido { | ||||
| @@ -143,10 +148,11 @@ | ||||
|     text-transform: uppercase; | ||||
|     display: block; | ||||
|     margin-bottom: 0.3rem; | ||||
|     text-align: left; | ||||
| } | ||||
|  | ||||
| .progress-bar-container { | ||||
|     height: 6px; | ||||
|     height: 16px; | ||||
|     background-color: #e9ecef; | ||||
|     border-radius: 3px; | ||||
|     overflow: hidden; | ||||
| @@ -249,11 +255,49 @@ | ||||
|     } | ||||
| } | ||||
|  | ||||
| /* --- NUEVOS ESTILOS PARA EL NOMBRE DEL PARTIDO CUANDO ES EL TÍTULO PRINCIPAL --- */ | ||||
| /* --- ESTILOS PARA EL NOMBRE DEL PARTIDO CUANDO ES EL TÍTULO PRINCIPAL --- */ | ||||
| .candidato-partido.main-title { | ||||
|     font-size: 0.95rem;      /* Hacemos la fuente más grande */ | ||||
|     font-weight: 700;        /* La ponemos en negrita, como el nombre del candidato */ | ||||
|     color: var(--text-primary); /* Usamos el color de texto principal */ | ||||
|     text-transform: none;    /* Quitamos el 'uppercase' para que se lea mejor */ | ||||
|     margin-bottom: 0.3rem; | ||||
| } | ||||
|  | ||||
| /* --- ESTILOS PARA LA ESTRUCTURA MULTI-CATEGORÍA --- */ | ||||
|  | ||||
| .categoria-bloque { | ||||
|     width: 100%; | ||||
| } | ||||
|  | ||||
| /* Añadimos un separador si hay más de una categoría en la misma tarjeta */ | ||||
| .categoria-bloque + .categoria-bloque { | ||||
|     border-top: 1px dashed var(--card-border-color); | ||||
|     margin-top: 1rem; | ||||
|     padding-top: 1rem; | ||||
| } | ||||
|  | ||||
| .categoria-titulo { | ||||
|     font-size: 0.8rem; | ||||
|     color: var(--text-secondary); | ||||
|     text-transform: uppercase; | ||||
|     text-align: center; | ||||
|     margin: 0 0 1rem 0; | ||||
| } | ||||
|  | ||||
| /* Ajuste para el footer, que ahora está dentro de cada categoría */ | ||||
| .categoria-bloque .card-footer { | ||||
|     grid-template-columns: repeat(3, 1fr); | ||||
|     background-color: transparent; /* Quitamos el fondo gris */ | ||||
|     border-top: 1px solid var(--card-border-color); | ||||
|     padding: 0.75rem 0; | ||||
|     margin-top: 0.75rem; /* Espacio antes del footer */ | ||||
|     text-align: center; | ||||
| } | ||||
|  | ||||
| .categoria-bloque .card-footer div { | ||||
|     border-right: 1px solid var(--card-border-color); | ||||
| } | ||||
| .categoria-bloque .card-footer div:last-child { | ||||
|     border-right: none; | ||||
| } | ||||
| @@ -4,25 +4,47 @@ import { getResumenPorProvincia } from '../../../apiService'; | ||||
| import { ProvinciaCard } from './components/ProvinciaCard'; | ||||
| import './ResultadosNacionalesCardsWidget.css'; | ||||
|  | ||||
| // --- 1. AÑADIR LA PROP A LA INTERFAZ --- | ||||
| interface Props { | ||||
|     eleccionId: number; | ||||
|     focoDistritoId?: string; | ||||
|     focoCategoriaId?: number; | ||||
|     cantidadResultados?: number; | ||||
|     mostrarBancas?: boolean; // Booleano opcional | ||||
| } | ||||
|  | ||||
| export const ResultadosNacionalesCardsWidget = ({ eleccionId }: Props) => { | ||||
| // --- 2. RECIBIR LA PROP Y ESTABLECER UN VALOR POR DEFECTO --- | ||||
| export const ResultadosNacionalesCardsWidget = ({  | ||||
|     eleccionId,  | ||||
|     focoDistritoId,  | ||||
|     focoCategoriaId,  | ||||
|     cantidadResultados, | ||||
|     mostrarBancas = false // Por defecto, no se muestran las bancas | ||||
| }: Props) => { | ||||
|      | ||||
|     const { data, isLoading, error } = useQuery({ | ||||
|         queryKey: ['resumenPorProvincia', eleccionId], | ||||
|         queryFn: () => getResumenPorProvincia(eleccionId), | ||||
|         queryKey: ['resumenPorProvincia', eleccionId, focoDistritoId, focoCategoriaId, cantidadResultados], | ||||
|          | ||||
|         queryFn: () => getResumenPorProvincia(eleccionId, { | ||||
|             focoDistritoId, | ||||
|             focoCategoriaId, | ||||
|             cantidadResultados | ||||
|         }), | ||||
|     }); | ||||
|  | ||||
|     if (isLoading) return <div>Cargando resultados por provincia...</div>; | ||||
|     if (error) return <div>Error al cargar los datos.</div>; | ||||
|     if (!data || data.length === 0) return <div>No hay resultados para mostrar con los filtros seleccionados.</div> | ||||
|  | ||||
|     return ( | ||||
|         <section className="cards-widget-container"> | ||||
|             <h2>Resultados elecciones nacionales 2025</h2> | ||||
|             <div className="cards-grid"> | ||||
|                 {data?.map(provinciaData => ( | ||||
|                     <ProvinciaCard key={provinciaData.provinciaId} data={provinciaData} /> | ||||
|                     <ProvinciaCard  | ||||
|                         key={provinciaData.provinciaId}  | ||||
|                         data={provinciaData}  | ||||
|                         mostrarBancas={mostrarBancas}  | ||||
|                     /> | ||||
|                 ))} | ||||
|             </div> | ||||
|         </section> | ||||
|   | ||||
| @@ -11,6 +11,7 @@ import type { ResultadoMapaDto, AmbitoGeography } from '../../../../types/types' | ||||
| import { MapaProvincial } from './MapaProvincial'; | ||||
| import { CabaLupa } from './CabaLupa'; | ||||
| import { BiZoomIn, BiZoomOut } from "react-icons/bi"; | ||||
| import toast from 'react-hot-toast'; | ||||
|  | ||||
| const DEFAULT_MAP_COLOR = '#E0E0E0'; | ||||
| const FADED_BACKGROUND_COLOR = '#F0F0F0'; | ||||
| @@ -166,9 +167,45 @@ export const MapaNacional = ({ eleccionId, categoriaId, nivel, nombreAmbito, nom | ||||
|     }; | ||||
|   }, [position, nivel]); | ||||
|  | ||||
|   const handleZoomIn = () => setPosition(prev => ({ ...prev, zoom: Math.min(prev.zoom * 1.8, 100) })); | ||||
|   const panEnabled = | ||||
|     nivel === 'provincia' && | ||||
|     initialProvincePositionRef.current !== null && | ||||
|     position.zoom > initialProvincePositionRef.current.zoom && | ||||
|     !nombreMunicipioSeleccionado; | ||||
|  | ||||
|   // --- INICIO DE LA CORRECCIÓN --- | ||||
|  | ||||
|   const handleZoomIn = () => { | ||||
|     // Solo mostramos la notificación si el paneo NO está ya habilitado | ||||
|     if (!panEnabled && initialProvincePositionRef.current) { | ||||
|       // Calculamos cuál será el nuevo nivel de zoom | ||||
|       const newZoom = position.zoom * 1.8; | ||||
|       // Si el nuevo zoom supera el umbral inicial, activamos la notificación | ||||
|       if (newZoom > initialProvincePositionRef.current.zoom) { | ||||
|         toast.success('Desplazamiento Habilitado', { | ||||
|           icon: '🖐️', | ||||
|           style: { background: '#32e5f1ff', color: 'white' }, | ||||
|           duration: 1000, | ||||
|         }); | ||||
|       } | ||||
|     } | ||||
|     setPosition(prev => ({ ...prev, zoom: Math.min(prev.zoom * 1.8, 100) })); | ||||
|   }; | ||||
|  | ||||
|   const handleZoomOut = () => { | ||||
|     // Solo mostramos la notificación si el paneo SÍ está habilitado actualmente | ||||
|     if (panEnabled && initialProvincePositionRef.current) { | ||||
|       const newZoom = position.zoom / 1.8; | ||||
|       // Si el nuevo zoom es igual o menor al umbral, desactivamos | ||||
|       if (newZoom <= initialProvincePositionRef.current.zoom) { | ||||
|         toast.error('Desplazamiento Deshabilitado', { | ||||
|           icon: '🔒', | ||||
|           style: { background: '#32e5f1ff', color: 'white' }, | ||||
|           duration: 1000, | ||||
|         }); | ||||
|       } | ||||
|     } | ||||
|     // La lógica para actualizar la posición no cambia | ||||
|     setPosition(prev => { | ||||
|       const newZoom = Math.max(prev.zoom / 1.8, 1); | ||||
|       const initialPos = initialProvincePositionRef.current; | ||||
| @@ -182,12 +219,6 @@ export const MapaNacional = ({ eleccionId, categoriaId, nivel, nombreAmbito, nom | ||||
|     setIsPanning(false); | ||||
|   }; | ||||
|  | ||||
|   const panEnabled = | ||||
|     nivel === 'provincia' && | ||||
|     initialProvincePositionRef.current !== null && | ||||
|     position.zoom > initialProvincePositionRef.current.zoom && | ||||
|     !nombreMunicipioSeleccionado; | ||||
|  | ||||
|   const filterInteractionEvents = (event: any) => { | ||||
|     if (event.sourceEvent && event.sourceEvent.type === 'wheel') return false; | ||||
|     return panEnabled; | ||||
|   | ||||
| @@ -71,15 +71,25 @@ export const PanelResultados = ({ resultados, estadoRecuento }: PanelResultadosP | ||||
|  | ||||
|       <div className="panel-partidos-container"> | ||||
|         {resultados.map(partido => ( | ||||
|           <div key={partido.id} className="partido-fila" style={{ borderLeftColor: partido.color || '#888' }}> | ||||
|           <div | ||||
|             key={partido.id} | ||||
|             className="partido-fila" | ||||
|             style={{ borderLeftColor: partido.color || '#ccc' }} | ||||
|           > | ||||
|             <div className="partido-logo"> | ||||
|               <ImageWithFallback src={partido.logoUrl || undefined} fallbackSrc={`${assetBaseUrl}/default-avatar.png`} alt={partido.nombre} /> | ||||
|             </div> | ||||
|             <div className="partido-main-content"> | ||||
|               <div className="partido-top-row"> | ||||
|                 <div className="partido-info-wrapper"> | ||||
|                   <span className="partido-nombre">{partido.nombreCorto || partido.nombre}</span> | ||||
|                   {partido.nombreCandidato && <span className="candidato-nombre">{partido.nombreCandidato}</span>} | ||||
|                   {partido.nombreCandidato ? ( | ||||
|                     <> | ||||
|                       <span className="candidato-nombre">{partido.nombreCandidato}</span> | ||||
|                       <span className="partido-nombre">{partido.nombreCorto || partido.nombre}</span> | ||||
|                     </> | ||||
|                   ) : ( | ||||
|                     <span className="partido-nombre">{partido.nombreCorto || partido.nombre}</span> | ||||
|                   )} | ||||
|                 </div> | ||||
|                 <div className="partido-stats"> | ||||
|                   <span className="partido-porcentaje"> | ||||
|   | ||||
| @@ -1,78 +1,110 @@ | ||||
| // src/features/legislativas/nacionales/components/ProvinciaCard.tsx | ||||
| import type { ResumenProvincia } from '../../../../types/types'; | ||||
| import type { ResumenProvincia, CategoriaResumen } from '../../../../types/types'; | ||||
| import { MiniMapaSvg } from './MiniMapaSvg'; | ||||
| import { ImageWithFallback } from '../../../../components/common/ImageWithFallback'; | ||||
| import { assetBaseUrl } from '../../../../apiService'; | ||||
|  | ||||
| // --- 1. AÑADIR LA PROP A AMBAS INTERFACES --- | ||||
| interface CategoriaDisplayProps { | ||||
|     categoria: CategoriaResumen; | ||||
|     mostrarBancas?: boolean; | ||||
| } | ||||
|  | ||||
| interface ProvinciaCardProps { | ||||
|     data: ResumenProvincia; | ||||
|     mostrarBancas?: boolean; | ||||
| } | ||||
|  | ||||
| const formatNumber = (num: number) => num.toLocaleString('es-AR'); | ||||
| const formatPercent = (num: number) => `${num.toFixed(2).replace('.', ',')}%`; | ||||
|  | ||||
| export const ProvinciaCard = ({ data }: ProvinciaCardProps) => { | ||||
|     // Determinamos el color del ganador para pasárselo al mapa. | ||||
|     // Si no hay ganador, usamos un color gris por defecto. | ||||
|     const colorGanador = data.resultados[0]?.color || '#d1d1d1'; | ||||
| // --- 2. RECIBIR Y USAR LA PROP EN EL SUB-COMPONENTE --- | ||||
| const CategoriaDisplay = ({ categoria, mostrarBancas }: CategoriaDisplayProps) => { | ||||
|     return ( | ||||
|         <div className="categoria-bloque"> | ||||
|             <h4 className="categoria-titulo">{categoria.categoriaNombre}</h4> | ||||
|  | ||||
|             {categoria.resultados.map(res => ( | ||||
|                 <div  | ||||
|                     key={res.agrupacionId}  | ||||
|                     className="candidato-row" | ||||
|                     style={{ borderLeftColor: res.color || '#ccc' }} | ||||
|                 > | ||||
|                     <ImageWithFallback | ||||
|                         src={res.fotoUrl ?? undefined} | ||||
|                         fallbackSrc={`${assetBaseUrl}/default-avatar.png`} | ||||
|                         alt={res.nombreCandidato ?? res.nombreAgrupacion} | ||||
|                         className="candidato-foto" | ||||
|                     /> | ||||
|  | ||||
|                     <div className="candidato-data"> | ||||
|                         {res.nombreCandidato && ( | ||||
|                             <span className="candidato-nombre">{res.nombreCandidato}</span> | ||||
|                         )} | ||||
|                         <span className={`candidato-partido ${!res.nombreCandidato ? 'main-title' : ''}`}> | ||||
|                             {res.nombreAgrupacion} | ||||
|                         </span> | ||||
|                         <div className="progress-bar-container"> | ||||
|                             <div className="progress-bar" style={{ width: `${res.porcentaje}%`, backgroundColor: res.color || '#ccc' }} /> | ||||
|                         </div> | ||||
|                     </div> | ||||
|                     <div className="candidato-stats"> | ||||
|                         <span className="stats-percent">{formatPercent(res.porcentaje)}</span> | ||||
|                         <span className="stats-votos">{formatNumber(res.votos)} votos</span> | ||||
|                     </div> | ||||
|  | ||||
|                     {/* --- 3. RENDERIZADO CONDICIONAL DEL CUADRO DE BANCAS --- */} | ||||
|                     {/* Este div solo se renderizará si mostrarBancas es true */} | ||||
|                     {mostrarBancas && ( | ||||
|                         <div className="stats-bancas"> | ||||
|                             +{res.bancasObtenidas} | ||||
|                             <span>Bancas</span> | ||||
|                         </div> | ||||
|                     )} | ||||
|                 </div> | ||||
|             ))} | ||||
|  | ||||
|             <footer className="card-footer"> | ||||
|                 <div> | ||||
|                     <span>Participación</span> | ||||
|                     <strong>{formatPercent(categoria.estadoRecuento?.participacionPorcentaje ?? 0)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span>Mesas escrutadas</span> | ||||
|                     <strong>{formatPercent(categoria.estadoRecuento?.mesasTotalizadasPorcentaje ?? 0)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span>Votos totales</span> | ||||
|                     <strong>{formatNumber(categoria.estadoRecuento?.cantidadVotantes ?? 0)}</strong> | ||||
|                 </div> | ||||
|             </footer> | ||||
|         </div> | ||||
|     ); | ||||
| }; | ||||
|  | ||||
| // --- 4. RECIBIR Y PASAR LA PROP EN EL COMPONENTE PRINCIPAL --- | ||||
| export const ProvinciaCard = ({ data, mostrarBancas }: ProvinciaCardProps) => { | ||||
|     const colorGanador = data.categorias[0]?.resultados[0]?.color || '#d1d1d1'; | ||||
|  | ||||
|     return ( | ||||
|         <div className="provincia-card"> | ||||
|             <header className="card-header"> | ||||
|                 <div className="header-info"> | ||||
|                     <h3 style={{ whiteSpace: 'normal' }}>{data.provinciaNombre}</h3> | ||||
|                     <span>DIPUTADOS NACIONALES</span> | ||||
|                 </div> | ||||
|                 <div className="header-map"> | ||||
|                     <MiniMapaSvg provinciaNombre={data.provinciaNombre} fillColor={colorGanador} /> | ||||
|                 </div> | ||||
|             </header> | ||||
|             <div className="card-body"> | ||||
|                 {data.resultados.map(res => ( | ||||
|                     <div key={res.agrupacionId} className="candidato-row"> | ||||
|                         <ImageWithFallback src={res.fotoUrl ?? undefined} fallbackSrc={`${assetBaseUrl}/default-avatar.png`} alt={res.nombreCandidato ?? res.nombreAgrupacion} className="candidato-foto" /> | ||||
|  | ||||
|                         <div className="candidato-data"> | ||||
|                             {res.nombreCandidato && ( | ||||
|                                 <span className="candidato-nombre">{res.nombreCandidato}</span> | ||||
|                             )} | ||||
|  | ||||
|                             <span className={`candidato-partido ${!res.nombreCandidato ? 'main-title' : ''}`}> | ||||
|                                 {res.nombreAgrupacion} | ||||
|                             </span> | ||||
|  | ||||
|                             <div className="progress-bar-container"> | ||||
|                                 <div className="progress-bar" style={{ width: `${res.porcentaje}%`, backgroundColor: res.color || '#ccc' }} /> | ||||
|                             </div> | ||||
|                         </div> | ||||
|  | ||||
|                         <div className="candidato-stats"> | ||||
|                             <span className="stats-percent">{formatPercent(res.porcentaje)}</span> | ||||
|                             <span className="stats-votos">{formatNumber(res.votos)} votos</span> | ||||
|                         </div> | ||||
|                         <div className="stats-bancas"> | ||||
|                             +{res.bancasObtenidas} | ||||
|                             <span>Bancas</span> | ||||
|                         </div> | ||||
|                     </div> | ||||
|                 {data.categorias.map(categoria => ( | ||||
|                     <CategoriaDisplay | ||||
|                         key={categoria.categoriaId} | ||||
|                         categoria={categoria} | ||||
|                         mostrarBancas={mostrarBancas} // Pasar la prop hacia abajo | ||||
|                     /> | ||||
|                 ))} | ||||
|             </div> | ||||
|             <footer className="card-footer"> | ||||
|                 <div> | ||||
|                     <span>Participación</span> | ||||
|                     {/* Usamos los datos reales del estado de recuento */} | ||||
|                     <strong>{formatPercent(data.estadoRecuento?.participacionPorcentaje ?? 0)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span>Mesas escrutadas</span> | ||||
|                     <strong>{formatPercent(data.estadoRecuento?.mesasTotalizadasPorcentaje ?? 0)}</strong> | ||||
|                 </div> | ||||
|                 <div> | ||||
|                     <span>Votos totales</span> | ||||
|                     {/* Usamos el nuevo campo cantidadVotantes */} | ||||
|                     <strong>{formatNumber(data.estadoRecuento?.cantidadVotantes ?? 0)}</strong> | ||||
|                 </div> | ||||
|             </footer> | ||||
|         </div> | ||||
|     ); | ||||
| }; | ||||
| @@ -1,31 +1,37 @@ | ||||
| // src/types/types.ts | ||||
| import type { Feature as GeoJsonFeature, Geometry } from 'geojson'; | ||||
|  | ||||
|  | ||||
| // Definimos nuestras propiedades personalizadas | ||||
| // --- TIPOS GEOGRÁFICOS Y DE MAPAS --- | ||||
| export interface GeoProperties { | ||||
|   nombre: string; | ||||
|   id: string; | ||||
|   [key: string]: any; // Permite otras propiedades | ||||
|   [key: string]: any; | ||||
| } | ||||
| export type AmbitoGeography = GeoJsonFeature<Geometry, GeoProperties> & { rsmKey: string }; | ||||
| export interface GeographyObject { | ||||
|   rsmKey: string; | ||||
|   properties: { | ||||
|     NAME_2: string; | ||||
|     [key: string]: any; | ||||
|   }; | ||||
| } | ||||
| export interface MapaDto { | ||||
|   ambitoId: number; | ||||
|   departamentoNombre: string; | ||||
|   agrupacionGanadoraId: string; | ||||
| } | ||||
|  | ||||
| // Nuestro tipo de geografía ahora se basa en el tipo estándar de GeoJSON | ||||
| // y le añadimos la propiedad 'rsmKey' que 'react-simple-maps' añade. | ||||
| export type AmbitoGeography = GeoJsonFeature<Geometry, GeoProperties> & { rsmKey: string }; | ||||
|  | ||||
| // Tipos para la respuesta de la API de resultados por municipio | ||||
| // --- TIPOS DE RESPUESTAS DE API --- | ||||
| export interface AgrupacionResultadoDto { | ||||
|   nombre: string; | ||||
|   votos: number; | ||||
|   porcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface VotosAdicionalesDto { | ||||
|   enBlanco: number; | ||||
|   nulos: number; | ||||
|   recorridos: number; | ||||
| } | ||||
|  | ||||
| export interface MunicipioResultadosDto { | ||||
|   municipioNombre: string; | ||||
|   ultimaActualizacion: string; | ||||
| @@ -34,25 +40,7 @@ export interface MunicipioResultadosDto { | ||||
|   resultados: AgrupacionResultadoDto[]; | ||||
|   votosAdicionales: VotosAdicionalesDto; | ||||
| } | ||||
|  | ||||
| // Tipo para la respuesta del endpoint del mapa | ||||
| export interface MapaDto { | ||||
|   ambitoId: number; | ||||
|   departamentoNombre: string; | ||||
|   agrupacionGanadoraId: string; | ||||
| } | ||||
|  | ||||
| // Definición de tipo para los objetos de geografía de react-simple-maps | ||||
| export interface GeographyObject { | ||||
|   rsmKey: string; | ||||
|   properties: { | ||||
|     NAME_2: string; | ||||
|     [key: string]: any; | ||||
|   }; | ||||
| } | ||||
|  | ||||
| export interface MunicipioSimple { id: string; nombre: string; camarasDisponibles?: ('diputados' | 'senadores')[]; } | ||||
|  | ||||
| export interface ResultadoTicker { | ||||
|   id: string; | ||||
|   nombre: string; | ||||
| @@ -63,50 +51,19 @@ export interface ResultadoTicker { | ||||
|   porcentaje: number; | ||||
|   nombreCandidato?: string | null; | ||||
| } | ||||
|  | ||||
| export interface EstadoRecuentoTicker { | ||||
|   mesasTotalizadasPorcentaje: number; | ||||
|   participacionPorcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface CategoriaResumen { | ||||
|   categoriaId: number; | ||||
|   categoriaNombre: string; | ||||
|   estadoRecuento: EstadoRecuentoTicker | null; | ||||
|   resultados: ResultadoTicker[]; | ||||
| } | ||||
|  | ||||
| export interface VotosAdicionales { enBlanco: number; nulos: number; recurridos: number; } | ||||
|  | ||||
| export interface MunicipioDetalle { | ||||
|   municipioNombre: string; | ||||
|   ultimaActualizacion: string; | ||||
|   porcentajeEscrutado: number; | ||||
|   porcentajeParticipacion: number; | ||||
|   resultados: CategoriaResumen[]; | ||||
|   votosAdicionales: VotosAdicionales; | ||||
| } | ||||
|  | ||||
| export interface ResumenProvincial { | ||||
|   provinciaNombre: string; | ||||
|   ultimaActualizacion: string; | ||||
|   porcentajeEscrutado: number; | ||||
|   porcentajeParticipacion: number; | ||||
|   resultados: CategoriaResumen[]; | ||||
|   votosAdicionales: VotosAdicionales; | ||||
| } | ||||
|  | ||||
| export interface Banca { | ||||
|   agrupacionNombre: string; | ||||
|   bancas: number; | ||||
|   [key: string]: string | number; | ||||
| } | ||||
|  | ||||
| export interface ProyeccionBancas { | ||||
|   seccionNombre: string; | ||||
|   proyeccion: Banca[]; | ||||
| } | ||||
|  | ||||
| export interface TelegramaData { | ||||
|   id: string; | ||||
|   ambitoGeograficoId: number; | ||||
| @@ -114,58 +71,22 @@ export interface TelegramaData { | ||||
|   fechaEscaneo: string; | ||||
|   fechaTotalizacion: string; | ||||
| } | ||||
|  | ||||
| export interface CatalogoItem { | ||||
|   id: string; | ||||
|   nombre: string; | ||||
| } | ||||
|  | ||||
| export interface ApiResponseResultadosPorSeccion { | ||||
|   ultimaActualizacion: string; | ||||
|   resultados: ResultadoTicker[]; | ||||
| } | ||||
|  | ||||
| export interface ResultadoTablaAgrupacion { | ||||
|   id: string; | ||||
|   nombre: string; | ||||
|   nombreCorto: string | null; | ||||
|   porcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface ResultadoTablaCategoria { | ||||
|   categoriaId: number; | ||||
|   categoriaNombre: string; | ||||
|   resultados: ResultadoTablaAgrupacion[]; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaPartidoPrincipal { | ||||
|   id: string; | ||||
|   nombre: string; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoPartido { | ||||
|   id: string; | ||||
|   porcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoCategoria { | ||||
|   categoriaId: number; | ||||
|   partidos: TablaDetalladaResultadoPartido[]; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoMunicipio { | ||||
|   municipioId: number; | ||||
|   municipioNombre: string; | ||||
|   resultadosPorCategoria: TablaDetalladaResultadoCategoria[]; | ||||
| } | ||||
|  | ||||
| // --- TIPOS PARA TABLAS DE RANKING --- | ||||
| export interface PartidoPrincipalDetalle { | ||||
|   puesto: number; | ||||
|   id: string; | ||||
|   nombre: string; | ||||
|   porcentajeTotalSeccion: number; | ||||
| } | ||||
|  | ||||
| export interface ApiResponseTablaDetallada { | ||||
|   categorias: { id: number; nombre: string }[]; | ||||
|   partidosPorCategoria: { [catId: string]: PartidoPrincipalDetalle[] }; | ||||
| @@ -175,99 +96,86 @@ export interface ApiResponseTablaDetallada { | ||||
|     celdas: { [catId: string]: { [partidoId: string]: number } }; | ||||
|   }[]; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaPartidoPrincipal { | ||||
|   id: string; | ||||
|   nombre: string; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoPartido { | ||||
|   id: string; | ||||
|   porcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoCategoria { | ||||
|   categoriaId: number; | ||||
|   partidos: TablaDetalladaResultadoPartido[]; | ||||
| } | ||||
|  | ||||
| export interface TablaDetalladaResultadoMunicipio { | ||||
|   municipioId: number; | ||||
|   municipioNombre: string; | ||||
|   resultadosPorCategoria: TablaDetalladaResultadoCategoria[]; | ||||
| } | ||||
|  | ||||
| export interface RankingPartido { | ||||
|   nombreCorto: string; | ||||
|   porcentaje: number; | ||||
|   votos: number; | ||||
| } | ||||
|  | ||||
| export interface RankingCategoria { | ||||
|   categoriaId: number; | ||||
|   ranking: RankingPartido[]; | ||||
| } | ||||
|  | ||||
| export interface ApiResponseRankingSeccion { | ||||
|   categorias: { id: number; nombre: string }[]; | ||||
|   resultados: RankingMunicipio[]; | ||||
| } | ||||
|  | ||||
| export interface RankingPartido { | ||||
|   nombreCorto: string; | ||||
|   porcentaje: number; | ||||
| } | ||||
|  | ||||
| export interface RankingCategoria { | ||||
|   ranking: RankingPartido[]; | ||||
| } | ||||
|  | ||||
| export interface RankingMunicipio { | ||||
|   municipioId: number; | ||||
|   municipioNombre: string; | ||||
|   resultadosPorCategoria: { [catId: string]: RankingCategoria }; | ||||
|   resultadosPorCategoria: { [catId: string]: { ranking: { nombreCorto: string; porcentaje: number }[] } }; | ||||
| } | ||||
|  | ||||
| export interface ApiResponseRankingMunicipio { | ||||
|   categorias: { id: number; nombre: string }[]; | ||||
|   resultados: RankingMunicipio[]; | ||||
| } | ||||
|  | ||||
| // --- TIPOS PARA PANEL ELECTORAL --- | ||||
| export interface ResultadoMapaDto { | ||||
|   ambitoId: string; | ||||
|   ambitoNombre: string; | ||||
|   agrupacionGanadoraId: string; | ||||
|   colorGanador: string; | ||||
| } | ||||
|  | ||||
| export interface PanelElectoralDto { | ||||
|   ambitoNombre: string; | ||||
|   mapaData: ResultadoMapaDto[]; | ||||
|   resultadosPanel: ResultadoTicker[]; // Reutilizamos el tipo que ya tienes | ||||
|   estadoRecuento: EstadoRecuentoTicker; // Reutilizamos el tipo que ya tienes | ||||
|   resultadosPanel: ResultadoTicker[]; | ||||
|   estadoRecuento: EstadoRecuentoTicker; | ||||
| } | ||||
|  | ||||
| // --- TIPOS PARA EL WIDGET DE TARJETAS --- | ||||
| // --- TIPOS PARA EL WIDGET DE TARJETAS NACIONALES --- | ||||
| // Definición correcta y más completa. Reemplaza a EstadoRecuentoTicker. | ||||
| export interface EstadoRecuentoDto { | ||||
|     participacionPorcentaje: number; | ||||
|     mesasTotalizadasPorcentaje: number; | ||||
|     cantidadVotantes: number; | ||||
|   participacionPorcentaje: number; | ||||
|   mesasTotalizadasPorcentaje: number; | ||||
|   cantidadVotantes: number; | ||||
| } | ||||
|  | ||||
| // Definición para los resultados en las tarjetas. | ||||
| export interface ResultadoCandidato { | ||||
|     agrupacionId: string; | ||||
|     nombreCandidato: string | null; | ||||
|     nombreAgrupacion: string; | ||||
|     fotoUrl: string | null; | ||||
|     color: string | null; | ||||
|     porcentaje: number; | ||||
|     votos: number; | ||||
|     bancasObtenidas: number; | ||||
|   agrupacionId: string; | ||||
|   nombreAgrupacion: string; // Nombre completo | ||||
|   nombreCortoAgrupacion: string | null; // <-- AÑADIR ESTA LÍNEA | ||||
|   nombreCandidato: string | null; | ||||
|   fotoUrl: string | null; | ||||
|   color: string | null; | ||||
|   porcentaje: number; | ||||
|   votos: number; | ||||
|   bancasObtenidas?: number;  | ||||
| } | ||||
|  | ||||
| // Definición para una categoría. | ||||
| export interface CategoriaResumen { | ||||
|   categoriaId: number; | ||||
|   categoriaNombre: string; | ||||
|   estadoRecuento: EstadoRecuentoDto | null; | ||||
|   resultados: ResultadoCandidato[]; | ||||
| } | ||||
|  | ||||
| // Definición para el objeto de una provincia. | ||||
| export interface ResumenProvincia { | ||||
|     provinciaId: string; | ||||
|     provinciaNombre: string; | ||||
|   provinciaId: string; | ||||
|   provinciaNombre: string; | ||||
|   categorias: CategoriaResumen[]; | ||||
| } | ||||
|  | ||||
| export interface CategoriaResumenHome { | ||||
|     categoriaId: number; | ||||
|     categoriaNombre: string; | ||||
|     estadoRecuento: EstadoRecuentoDto | null; | ||||
|     resultados: ResultadoCandidato[]; | ||||
|     votosEnBlanco: number; | ||||
|     votosEnBlancoPorcentaje: number; | ||||
|     votosTotales: number; | ||||
|     ultimaActualizacion: string; | ||||
| } | ||||
| @@ -41,24 +41,19 @@ public class AdminController : ControllerBase | ||||
|   [HttpPut("agrupaciones/{id}")] | ||||
|   public async Task<IActionResult> UpdateAgrupacion(string id, [FromBody] UpdateAgrupacionDto agrupacionDto) | ||||
|   { | ||||
|     // Buscamos la agrupación en la base de datos por su ID. | ||||
|     var agrupacion = await _dbContext.AgrupacionesPoliticas.FindAsync(id); | ||||
|  | ||||
|     if (agrupacion == null) | ||||
|     { | ||||
|       // Si no existe, devolvemos un error 404 Not Found. | ||||
|       return NotFound(new { message = $"No se encontró la agrupación con ID {id}" }); | ||||
|     } | ||||
|  | ||||
|     // Actualizamos las propiedades de la entidad con los valores del DTO. | ||||
|     agrupacion.NombreCorto = agrupacionDto.NombreCorto; | ||||
|     agrupacion.Color = agrupacionDto.Color; | ||||
|  | ||||
|     // Guardamos los cambios en la base de datos. | ||||
|     await _dbContext.SaveChangesAsync(); | ||||
|     _logger.LogInformation("Se actualizó la agrupación: {Id}", id); | ||||
|  | ||||
|     // Devolvemos una respuesta 204 No Content, que es el estándar para un PUT exitoso sin devolver datos. | ||||
|     return NoContent(); | ||||
|   } | ||||
|  | ||||
| @@ -252,28 +247,31 @@ public class AdminController : ControllerBase | ||||
|   { | ||||
|     foreach (var logo in logos) | ||||
|     { | ||||
|       // Buscamos un registro existente que coincida exactamente | ||||
|       var logoExistente = await _dbContext.LogosAgrupacionesCategorias | ||||
|           .FirstOrDefaultAsync(l => | ||||
|               l.EleccionId == logo.EleccionId && | ||||
|               l.AgrupacionPoliticaId == logo.AgrupacionPoliticaId && | ||||
|               l.CategoriaId == logo.CategoriaId && | ||||
|               l.AmbitoGeograficoId == logo.AmbitoGeograficoId); | ||||
|  | ||||
|       if (logoExistente != null) | ||||
|       { | ||||
|         // Si encontramos el registro exacto, solo actualizamos su URL. | ||||
|         logoExistente.LogoUrl = logo.LogoUrl; | ||||
|         // Si existe, lo actualizamos | ||||
|         if (string.IsNullOrEmpty(logo.LogoUrl)) | ||||
|         { | ||||
|           // Si la URL nueva es vacía, eliminamos el override | ||||
|           _dbContext.LogosAgrupacionesCategorias.Remove(logoExistente); | ||||
|         } | ||||
|         else | ||||
|         { | ||||
|           logoExistente.LogoUrl = logo.LogoUrl; | ||||
|         } | ||||
|       } | ||||
|       else if (!string.IsNullOrEmpty(logo.LogoUrl)) | ||||
|       { | ||||
|         // Si no se encontró un registro exacto (es un override nuevo), | ||||
|         // lo añadimos a la base de datos. | ||||
|         _dbContext.LogosAgrupacionesCategorias.Add(new LogoAgrupacionCategoria | ||||
|         { | ||||
|           AgrupacionPoliticaId = logo.AgrupacionPoliticaId, | ||||
|           CategoriaId = logo.CategoriaId, | ||||
|           AmbitoGeograficoId = logo.AmbitoGeograficoId, | ||||
|           LogoUrl = logo.LogoUrl | ||||
|         }); | ||||
|         // Si no existe y la URL no es vacía, lo creamos | ||||
|         _dbContext.LogosAgrupacionesCategorias.Add(logo); | ||||
|       } | ||||
|     } | ||||
|     await _dbContext.SaveChangesAsync(); | ||||
|   | ||||
| @@ -142,7 +142,9 @@ public class ResultadosController : ControllerBase | ||||
|             .ToListAsync(); | ||||
|  | ||||
|         // Obtenemos TODOS los logos relevantes en una sola consulta | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking() | ||||
|         .Where(l => l.EleccionId == eleccionId || l.EleccionId == 0) // Trae los de la elección actual y los de fallback | ||||
|         .ToListAsync(); | ||||
|  | ||||
|         // --- LÓGICA DE AGRUPACIÓN Y CÁLCULO CORREGIDA --- | ||||
|         var resultadosAgrupados = resultadosPorMunicipio | ||||
| @@ -1040,13 +1042,25 @@ public class ResultadosController : ControllerBase | ||||
|  | ||||
|     private async Task<IActionResult> GetPanelMunicipal(int eleccionId, int ambitoId, int categoriaId) | ||||
|     { | ||||
|         // 1. Validar y obtener la entidad del municipio | ||||
|         // 1. Obtener la entidad del municipio y, a partir de ella, la de su provincia. | ||||
|         var municipio = await _dbContext.AmbitosGeograficos.AsNoTracking() | ||||
|             .FirstOrDefaultAsync(a => a.Id == ambitoId && a.NivelId == 30); | ||||
|  | ||||
|         if (municipio == null) return NotFound($"No se encontró el municipio con ID {ambitoId}."); | ||||
|  | ||||
|         // 2. Obtener los votos solo para ESE municipio | ||||
|         var provincia = await _dbContext.AmbitosGeograficos.AsNoTracking() | ||||
|             .FirstOrDefaultAsync(a => a.DistritoId == municipio.DistritoId && a.NivelId == 10); | ||||
|  | ||||
|         // Si por alguna razón no encontramos la provincia, no podemos continuar. | ||||
|         if (provincia == null) return NotFound($"No se pudo determinar la provincia para el municipio con ID {ambitoId}."); | ||||
|  | ||||
|         // 2. Cargar todos los overrides de candidatos y logos relevantes (igual que en la vista provincial). | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking() | ||||
|             .Where(c => c.EleccionId == eleccionId || c.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking() | ||||
|             .Where(l => l.EleccionId == eleccionId || l.EleccionId == 0).ToListAsync(); | ||||
|  | ||||
|         // 3. Obtener los votos solo para ESE municipio (esto no cambia). | ||||
|         var resultadosCrudos = await _dbContext.ResultadosVotos.AsNoTracking() | ||||
|             .Include(r => r.AgrupacionPolitica) | ||||
|             .Where(r => r.EleccionId == eleccionId && | ||||
| @@ -1054,29 +1068,38 @@ public class ResultadosController : ControllerBase | ||||
|                         r.AmbitoGeograficoId == ambitoId) | ||||
|             .ToListAsync(); | ||||
|  | ||||
|         // El resto de la lógica es muy similar, pero ahora usamos los helpers con el ID de la provincia. | ||||
|         if (!resultadosCrudos.Any()) | ||||
|         { | ||||
|             // Devolver un DTO vacío pero válido si no hay resultados | ||||
|             return Ok(new PanelElectoralDto | ||||
|             { | ||||
|                 AmbitoNombre = municipio.Nombre, | ||||
|                 MapaData = new List<ResultadoMapaDto>(), // El mapa estará vacío en la vista de un solo municipio | ||||
|                 MapaData = new List<ResultadoMapaDto>(), | ||||
|                 ResultadosPanel = new List<AgrupacionResultadoDto>(), | ||||
|                 EstadoRecuento = new EstadoRecuentoDto() | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         // 3. Calcular los resultados para el panel lateral (son los mismos datos crudos) | ||||
|         var totalVotosMunicipio = (decimal)resultadosCrudos.Sum(r => r.CantidadVotos); | ||||
|         var resultadosPanel = resultadosCrudos | ||||
|             .Select(g => new AgrupacionResultadoDto | ||||
|             .Select(g => | ||||
|             { | ||||
|                 Id = g.AgrupacionPolitica.Id, | ||||
|                 Nombre = g.AgrupacionPolitica.Nombre, | ||||
|                 NombreCorto = g.AgrupacionPolitica.NombreCorto, | ||||
|                 Color = g.AgrupacionPolitica.Color, | ||||
|                 Votos = g.CantidadVotos, | ||||
|                 Porcentaje = totalVotosMunicipio > 0 ? (g.CantidadVotos / totalVotosMunicipio) * 100 : 0 | ||||
|                 // 4. ¡LA CLAVE! Usamos el ID de la PROVINCIA para buscar el override. | ||||
|                 var candidatoMatch = FindBestCandidatoMatch(todosLosOverrides, g.AgrupacionPolitica.Id, categoriaId, provincia.Id, eleccionId); | ||||
|                 var logoMatch = FindBestLogoMatch(todosLosLogos, g.AgrupacionPolitica.Id, categoriaId, provincia.Id, eleccionId); | ||||
|  | ||||
|                 return new AgrupacionResultadoDto | ||||
|                 { | ||||
|                     Id = g.AgrupacionPolitica.Id, | ||||
|                     Nombre = g.AgrupacionPolitica.Nombre, | ||||
|                     NombreCorto = g.AgrupacionPolitica.NombreCorto, | ||||
|                     Color = g.AgrupacionPolitica.Color, | ||||
|                     Votos = g.CantidadVotos, | ||||
|                     Porcentaje = totalVotosMunicipio > 0 ? (g.CantidadVotos / totalVotosMunicipio) * 100 : 0, | ||||
|                     // Asignamos los datos del override encontrado | ||||
|                     NombreCandidato = candidatoMatch?.NombreCandidato, | ||||
|                     LogoUrl = logoMatch?.LogoUrl | ||||
|                 }; | ||||
|             }) | ||||
|             .OrderByDescending(r => r.Votos) | ||||
|             .ToList(); | ||||
| @@ -1088,7 +1111,7 @@ public class ResultadosController : ControllerBase | ||||
|         var respuesta = new PanelElectoralDto | ||||
|         { | ||||
|             AmbitoNombre = municipio.Nombre, | ||||
|             MapaData = new List<ResultadoMapaDto>(), // El mapa no muestra sub-geografías aquí | ||||
|             MapaData = new List<ResultadoMapaDto>(), | ||||
|             ResultadosPanel = resultadosPanel, | ||||
|             EstadoRecuento = new EstadoRecuentoDto | ||||
|             { | ||||
| @@ -1107,38 +1130,41 @@ public class ResultadosController : ControllerBase | ||||
|             .FirstOrDefaultAsync(a => a.DistritoId == distritoId && a.NivelId == 10); | ||||
|         if (provincia == null) return NotFound($"No se encontró la provincia con DistritoId {distritoId}."); | ||||
|  | ||||
|         // --- INICIO DE LA OPTIMIZACIÓN --- | ||||
|         // 1. Agrupar y sumar directamente en la base de datos. EF lo traducirá a un SQL eficiente. | ||||
|         // --- INICIO DE LA MODIFICACIÓN --- | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking().Where(c => c.EleccionId == eleccionId || c.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().Where(l => l.EleccionId == eleccionId || l.EleccionId == 0).ToListAsync(); | ||||
|         // --- FIN DE LA MODIFICACIÓN --- | ||||
|  | ||||
|         // ... (la lógica de agregación de votos no cambia) | ||||
|         var resultadosAgregados = await _dbContext.ResultadosVotos.AsNoTracking() | ||||
|             .Where(r => r.EleccionId == eleccionId && | ||||
|                         r.CategoriaId == categoriaId && | ||||
|                         r.AmbitoGeografico.DistritoId == distritoId && | ||||
|                         r.AmbitoGeografico.NivelId == 30) | ||||
|             .GroupBy(r => r.AgrupacionPolitica) // Agrupar por la entidad | ||||
|             .Select(g => new | ||||
|             { | ||||
|                 Agrupacion = g.Key, | ||||
|                 TotalVotos = g.Sum(r => r.CantidadVotos) | ||||
|             }) | ||||
|             .Where(r => r.EleccionId == eleccionId && r.CategoriaId == categoriaId && r.AmbitoGeografico.DistritoId == distritoId && r.AmbitoGeografico.NivelId == 30) | ||||
|             .GroupBy(r => r.AgrupacionPolitica) | ||||
|             .Select(g => new { Agrupacion = g.Key, TotalVotos = g.Sum(r => r.CantidadVotos) }) | ||||
|             .ToListAsync(); | ||||
|  | ||||
|         // 2. Calcular el total de votos en memoria (sobre una lista ya pequeña) | ||||
|         var totalVotosProvincia = (decimal)resultadosAgregados.Sum(r => r.TotalVotos); | ||||
|  | ||||
|         // 3. Mapear a DTO (muy rápido) | ||||
|         var resultadosPanel = resultadosAgregados | ||||
|             .Select(g => new AgrupacionResultadoDto | ||||
|             .Select(g => | ||||
|             { | ||||
|                 Id = g.Agrupacion.Id, | ||||
|                 Nombre = g.Agrupacion.Nombre, | ||||
|                 NombreCorto = g.Agrupacion.NombreCorto, | ||||
|                 Color = g.Agrupacion.Color, | ||||
|                 Votos = g.TotalVotos, | ||||
|                 Porcentaje = totalVotosProvincia > 0 ? (g.TotalVotos / totalVotosProvincia) * 100 : 0 | ||||
|                 // Aplicamos la misma lógica de búsqueda de overrides | ||||
|                 var candidatoMatch = FindBestCandidatoMatch(todosLosOverrides, g.Agrupacion.Id, categoriaId, provincia.Id, eleccionId); | ||||
|                 var logoMatch = FindBestLogoMatch(todosLosLogos, g.Agrupacion.Id, categoriaId, provincia.Id, eleccionId); | ||||
|  | ||||
|                 return new AgrupacionResultadoDto | ||||
|                 { | ||||
|                     Id = g.Agrupacion.Id, | ||||
|                     Nombre = g.Agrupacion.Nombre, | ||||
|                     NombreCorto = g.Agrupacion.NombreCorto, | ||||
|                     Color = g.Agrupacion.Color, | ||||
|                     Votos = g.TotalVotos, | ||||
|                     Porcentaje = totalVotosProvincia > 0 ? (g.TotalVotos / totalVotosProvincia) * 100 : 0, | ||||
|                     NombreCandidato = candidatoMatch?.NombreCandidato, // <-- DATO AÑADIDO | ||||
|                     LogoUrl = logoMatch?.LogoUrl // <-- DATO AÑADIDO | ||||
|                 }; | ||||
|             }) | ||||
|             .OrderByDescending(r => r.Votos) | ||||
|             .ToList(); | ||||
|         // --- FIN DE LA OPTIMIZACIÓN --- | ||||
|  | ||||
|         var estadoRecuento = await _dbContext.EstadosRecuentosGenerales.AsNoTracking() | ||||
|             .FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.AmbitoGeograficoId == provincia.Id && e.CategoriaId == categoriaId); | ||||
| @@ -1159,43 +1185,46 @@ public class ResultadosController : ControllerBase | ||||
|  | ||||
|     private async Task<IActionResult> GetPanelNacional(int eleccionId, int categoriaId) | ||||
|     { | ||||
|         // --- INICIO DE LA OPTIMIZACIÓN --- | ||||
|         // 1. Agrupar y sumar directamente en la base de datos a nivel nacional. | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking().Where(c => c.EleccionId == eleccionId || c.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().Where(l => l.EleccionId == eleccionId || l.EleccionId == 0).ToListAsync(); | ||||
|  | ||||
|  | ||||
|         var resultadosAgregados = await _dbContext.ResultadosVotos.AsNoTracking() | ||||
|             .Where(r => r.EleccionId == eleccionId && r.CategoriaId == categoriaId) | ||||
|             .GroupBy(r => r.AgrupacionPolitica) | ||||
|             .Select(g => new | ||||
|             { | ||||
|                 Agrupacion = g.Key, | ||||
|                 TotalVotos = g.Sum(r => r.CantidadVotos) | ||||
|             }) | ||||
|             .Select(g => new { Agrupacion = g.Key, TotalVotos = g.Sum(r => r.CantidadVotos) }) | ||||
|             .ToListAsync(); | ||||
|  | ||||
|         // 2. Calcular el total de votos en memoria | ||||
|         var totalVotosNacional = (decimal)resultadosAgregados.Sum(r => r.TotalVotos); | ||||
|  | ||||
|         // 3. Mapear a DTO | ||||
|         var resultadosPanel = resultadosAgregados | ||||
|             .Select(g => new AgrupacionResultadoDto | ||||
|         .Select(g => | ||||
|         { | ||||
|             var candidatoMatch = FindBestCandidatoMatch(todosLosOverrides, g.Agrupacion.Id, categoriaId, null, eleccionId); | ||||
|             var logoMatch = FindBestLogoMatch(todosLosLogos, g.Agrupacion.Id, categoriaId, null, eleccionId); | ||||
|  | ||||
|             return new AgrupacionResultadoDto | ||||
|             { | ||||
|                 Id = g.Agrupacion.Id, | ||||
|                 Nombre = g.Agrupacion.Nombre, | ||||
|                 NombreCorto = g.Agrupacion.NombreCorto, | ||||
|                 Color = g.Agrupacion.Color, | ||||
|                 Votos = g.TotalVotos, | ||||
|                 Porcentaje = totalVotosNacional > 0 ? (g.TotalVotos / totalVotosNacional) * 100 : 0 | ||||
|             }) | ||||
|             .OrderByDescending(r => r.Votos) | ||||
|             .ToList(); | ||||
|         // --- FIN DE LA OPTIMIZACIÓN --- | ||||
|                 Porcentaje = totalVotosNacional > 0 ? (g.TotalVotos / totalVotosNacional) * 100 : 0, | ||||
|                 NombreCandidato = null, | ||||
|                 LogoUrl = logoMatch?.LogoUrl | ||||
|             }; | ||||
|         }) | ||||
|         .OrderByDescending(r => r.Votos) | ||||
|         .ToList(); | ||||
|  | ||||
|         var estadoRecuento = await _dbContext.EstadosRecuentosGenerales.AsNoTracking() | ||||
|             .FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaId); | ||||
|                 .FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaId && e.AmbitoGeografico.NivelId == 0); | ||||
|  | ||||
|         var respuesta = new PanelElectoralDto | ||||
|         { | ||||
|             AmbitoNombre = "Argentina", | ||||
|             MapaData = new List<ResultadoMapaDto>(), // Se carga por separado | ||||
|             MapaData = new List<ResultadoMapaDto>(), | ||||
|             ResultadosPanel = resultadosPanel, | ||||
|             EstadoRecuento = new EstadoRecuentoDto | ||||
|             { | ||||
| @@ -1208,9 +1237,9 @@ public class ResultadosController : ControllerBase | ||||
|  | ||||
|     [HttpGet("mapa-resultados")] | ||||
|     public async Task<IActionResult> GetResultadosMapaPorMunicipio( | ||||
| [FromRoute] int eleccionId, | ||||
| [FromQuery] int categoriaId, | ||||
| [FromQuery] string? distritoId = null) | ||||
|     [FromRoute] int eleccionId, | ||||
|     [FromQuery] int categoriaId, | ||||
|     [FromQuery] string? distritoId = null) | ||||
|     { | ||||
|         if (string.IsNullOrEmpty(distritoId)) | ||||
|         { | ||||
| @@ -1413,77 +1442,196 @@ public class ResultadosController : ControllerBase | ||||
|         return Ok(new { Diputados = diputados, Senadores = senadores }); | ||||
|     } | ||||
|  | ||||
|     [HttpGet("resumen-por-provincia")] | ||||
|     public async Task<IActionResult> GetResumenPorProvincia([FromRoute] int eleccionId) | ||||
|     // --- INICIO DE FUNCIONES DE AYUDA --- | ||||
|     private CandidatoOverride? FindBestCandidatoMatch( | ||||
| List<CandidatoOverride> overrides, string agrupacionId, int categoriaId, int? ambitoId, int eleccionId) | ||||
|     { | ||||
|         const int categoriaDiputadosNacionales = 2; | ||||
|         return overrides.FirstOrDefault(c => c.EleccionId == eleccionId && c.AgrupacionPoliticaId == agrupacionId && c.CategoriaId == categoriaId && c.AmbitoGeograficoId == ambitoId) | ||||
|         ?? overrides.FirstOrDefault(c => c.EleccionId == eleccionId && c.AgrupacionPoliticaId == agrupacionId && c.CategoriaId == categoriaId && c.AmbitoGeograficoId == null) | ||||
|         ?? overrides.FirstOrDefault(c => c.EleccionId == 0 && c.AgrupacionPoliticaId == agrupacionId && c.CategoriaId == categoriaId && c.AmbitoGeograficoId == ambitoId) | ||||
|         ?? overrides.FirstOrDefault(c => c.EleccionId == 0 && c.AgrupacionPoliticaId == agrupacionId && c.CategoriaId == categoriaId && c.AmbitoGeograficoId == null); | ||||
|     } | ||||
|     private LogoAgrupacionCategoria? FindBestLogoMatch( | ||||
|     List<LogoAgrupacionCategoria> logos, string agrupacionId, int categoriaId, int? ambitoId, int eleccionId) | ||||
| { | ||||
|     // Prioridad 1: Coincidencia exacta (Elección, Categoría, Ámbito) | ||||
|     return logos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == ambitoId) | ||||
|     // Prioridad 2: Coincidencia por Elección y Categoría (Ámbito genérico) | ||||
|     ?? logos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null) | ||||
|     // Prioridad 3: Coincidencia de Fallback por Ámbito (Elección genérica) | ||||
|     ?? logos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == ambitoId) | ||||
|     // Prioridad 4: Coincidencia de Fallback por Categoría (Elección y Ámbito genéricos) | ||||
|     ?? logos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null) | ||||
|      | ||||
|     // --- INICIO DE LA CORRECCIÓN --- | ||||
|     // Prioridad 5: LOGO GLOBAL. Coincidencia solo por Partido (Elección y Categoría genéricas) | ||||
|     // Se busca EleccionId = 0 y CategoriaId = 0 (en lugar de null) para que coincida con la lógica de los otros widgets. | ||||
|     ?? logos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == 0 && l.AmbitoGeograficoId == null); | ||||
|     // --- FIN DE LA CORRECCIÓN --- | ||||
| } | ||||
|  | ||||
|         var todasLasProyecciones = await _dbContext.ProyeccionesBancas.AsNoTracking() | ||||
|             .Where(p => p.EleccionId == eleccionId && p.CategoriaId == categoriaDiputadosNacionales) | ||||
|             .ToDictionaryAsync(p => p.AmbitoGeograficoId + "_" + p.AgrupacionPoliticaId); | ||||
|     [HttpGet("resumen-por-provincia")] | ||||
|     public async Task<IActionResult> GetResumenPorProvincia( | ||||
|     [FromRoute] int eleccionId, | ||||
|     [FromQuery] string? focoDistritoId = null, | ||||
|     [FromQuery] int? focoCategoriaId = null, | ||||
|     [FromQuery] int cantidadResultados = 2) | ||||
|     { | ||||
|         if (cantidadResultados < 1) cantidadResultados = 1; | ||||
|  | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking() | ||||
|             .Where(c => c.EleccionId == eleccionId && c.CategoriaId == categoriaDiputadosNacionales) | ||||
|             .ToListAsync(); | ||||
|         const int catDiputadosNac = 2; | ||||
|         const int catSenadoresNac = 1; | ||||
|  | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking() | ||||
|             .Where(l => l.EleccionId == eleccionId && l.CategoriaId == categoriaDiputadosNacionales) | ||||
|             .ToListAsync(); | ||||
|         var provinciasQueRenuevanSenadores = new HashSet<string> { "01", "06", "08", "15", "16", "17", "22", "23" }; | ||||
|  | ||||
|         var datosBrutos = await _dbContext.AmbitosGeograficos.AsNoTracking() | ||||
|             .Where(a => a.NivelId == 10) | ||||
|             .Select(provincia => new | ||||
|             { | ||||
|                 ProvinciaAmbitoId = provincia.Id, | ||||
|                 ProvinciaDistritoId = provincia.DistritoId!, | ||||
|                 ProvinciaNombre = provincia.Nombre, | ||||
|                 EstadoRecuento = _dbContext.EstadosRecuentosGenerales | ||||
|                     .Where(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaDiputadosNacionales && e.AmbitoGeograficoId == provincia.Id) | ||||
|                     .Select(e => new EstadoRecuentoDto { /* ... */ }) | ||||
|                     .FirstOrDefault(), | ||||
|                 ResultadosBrutos = _dbContext.ResultadosVotos | ||||
|                     .Where(r => r.EleccionId == eleccionId && r.CategoriaId == categoriaDiputadosNacionales && r.AmbitoGeografico.DistritoId == provincia.DistritoId) | ||||
|                     .GroupBy(r => r.AgrupacionPolitica) | ||||
|                     .Select(g => new { Agrupacion = g.Key, Votos = g.Sum(r => r.CantidadVotos) }) | ||||
|                     .OrderByDescending(x => x.Votos) | ||||
|                     .Take(2) | ||||
|                     .ToList() | ||||
|             }) | ||||
|             .OrderBy(p => p.ProvinciaNombre) | ||||
|             .ToListAsync(); | ||||
|         // --- CORRECCIÓN FINAL: Simplificar la carga de datos de soporte --- | ||||
|         var todasLasProyecciones = await _dbContext.ProyeccionesBancas.AsNoTracking().Where(p => p.EleccionId == eleccionId && (p.CategoriaId == catDiputadosNac || p.CategoriaId == catSenadoresNac)).ToDictionaryAsync(p => p.AmbitoGeograficoId + "_" + p.AgrupacionPoliticaId + "_" + p.CategoriaId); | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking().Where(c => c.EleccionId == eleccionId || c.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().Where(l => l.EleccionId == eleccionId || l.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosEstados = await _dbContext.EstadosRecuentosGenerales.AsNoTracking().Include(e => e.CategoriaElectoral).Where(e => e.EleccionId == eleccionId && (e.CategoriaId == catDiputadosNac || e.CategoriaId == catSenadoresNac)).ToDictionaryAsync(e => e.AmbitoGeograficoId + "_" + e.CategoriaId); | ||||
|         var mapaMunicipioADistrito = await _dbContext.AmbitosGeograficos.AsNoTracking().Where(a => a.NivelId == 30 && a.DistritoId != null).ToDictionaryAsync(a => a.Id, a => a.DistritoId!); | ||||
|         var todosLosVotos = await _dbContext.ResultadosVotos.AsNoTracking().Where(r => r.EleccionId == eleccionId && (r.CategoriaId == catDiputadosNac || r.CategoriaId == catSenadoresNac)).Select(r => new { r.AmbitoGeograficoId, r.CategoriaId, r.AgrupacionPoliticaId, r.CantidadVotos }).ToListAsync(); | ||||
|         var votosAgregados = todosLosVotos.Where(v => mapaMunicipioADistrito.ContainsKey(v.AmbitoGeograficoId)).GroupBy(v => new { DistritoId = mapaMunicipioADistrito[v.AmbitoGeograficoId], v.CategoriaId, v.AgrupacionPoliticaId }).Select(g => new { g.Key.DistritoId, g.Key.CategoriaId, g.Key.AgrupacionPoliticaId, Votos = g.Sum(v => v.CantidadVotos) }).ToList(); | ||||
|  | ||||
|         var resultadosFinales = datosBrutos.Select(provinciaData => | ||||
|         var agrupaciones = await _dbContext.AgrupacionesPoliticas.AsNoTracking().ToDictionaryAsync(a => a.Id); | ||||
|         var resultadosFinales = new List<ResumenProvinciaDto>(); | ||||
|         var provinciasQuery = _dbContext.AmbitosGeograficos.AsNoTracking().Where(a => a.NivelId == 10); | ||||
|         if (!string.IsNullOrEmpty(focoDistritoId)) { provinciasQuery = provinciasQuery.Where(p => p.DistritoId == focoDistritoId); } | ||||
|         var provincias = await provinciasQuery.ToListAsync(); | ||||
|         if (!provincias.Any()) { return Ok(resultadosFinales); } | ||||
|  | ||||
|         foreach (var provincia in provincias.OrderBy(p => p.Nombre)) | ||||
|         { | ||||
|             var totalVotosProvincia = (decimal)provinciaData.ResultadosBrutos.Sum(r => r.Votos); | ||||
|             return new ResumenProvinciaDto | ||||
|             var categoriasDeLaProvincia = new List<int>(); | ||||
|             if (focoCategoriaId.HasValue) { if ((focoCategoriaId.Value == catDiputadosNac) || (focoCategoriaId.Value == catSenadoresNac && provinciasQueRenuevanSenadores.Contains(provincia.DistritoId!))) categoriasDeLaProvincia.Add(focoCategoriaId.Value); } | ||||
|             else { categoriasDeLaProvincia.Add(catDiputadosNac); if (provinciasQueRenuevanSenadores.Contains(provincia.DistritoId!)) categoriasDeLaProvincia.Add(catSenadoresNac); } | ||||
|  | ||||
|             var dtoProvincia = new ResumenProvinciaDto { ProvinciaId = provincia.DistritoId!, ProvinciaNombre = provincia.Nombre, Categorias = new List<CategoriaResumenDto>() }; | ||||
|  | ||||
|             foreach (var categoriaId in categoriasDeLaProvincia) | ||||
|             { | ||||
|                 ProvinciaId = provinciaData.ProvinciaDistritoId, | ||||
|                 ProvinciaNombre = provinciaData.ProvinciaNombre, | ||||
|                 EstadoRecuento = provinciaData.EstadoRecuento, | ||||
|                 Resultados = provinciaData.ResultadosBrutos.Select(r => | ||||
|                 var resultadosCategoriaCompleta = votosAgregados.Where(r => r.DistritoId == provincia.DistritoId && r.CategoriaId == categoriaId); | ||||
|                 var totalVotosCategoria = (decimal)resultadosCategoriaCompleta.Sum(r => r.Votos); | ||||
|                 var votosAgrupados = resultadosCategoriaCompleta.OrderByDescending(x => x.Votos).Take(cantidadResultados).Select(r => new { Agrupacion = agrupaciones[r.AgrupacionPoliticaId], r.Votos }).ToList(); | ||||
|                 todosLosEstados.TryGetValue(provincia.Id + "_" + categoriaId, out var estado); | ||||
|  | ||||
|                 dtoProvincia.Categorias.Add(new CategoriaResumenDto | ||||
|                 { | ||||
|                     var provinciaAmbitoId = provinciaData.ProvinciaAmbitoId; | ||||
|                     CategoriaId = categoriaId, | ||||
|                     CategoriaNombre = estado?.CategoriaElectoral.Nombre ?? (categoriaId == catDiputadosNac ? "DIPUTADOS NACIONALES" : "SENADORES NACIONALES"), | ||||
|                     EstadoRecuento = estado != null ? new EstadoRecuentoDto | ||||
|                     { | ||||
|                         ParticipacionPorcentaje = estado.ParticipacionPorcentaje, | ||||
|                         MesasTotalizadasPorcentaje = estado.MesasTotalizadasPorcentaje, | ||||
|                         CantidadVotantes = estado.CantidadVotantes | ||||
|                     } : null, | ||||
|                     Resultados = votosAgrupados.Select(r => | ||||
|                 { | ||||
|                     var provinciaAmbitoId = provincia.Id; | ||||
|                     var candidatoMatch = FindBestCandidatoMatch(todosLosOverrides, r.Agrupacion.Id, categoriaId, provinciaAmbitoId, eleccionId); | ||||
|  | ||||
|                     string? logoFinal = | ||||
|                         // Prioridad 1: Override Específico (EleccionId, CategoriaId, AmbitoId) | ||||
|                         todosLosLogos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == provinciaAmbitoId)?.LogoUrl | ||||
|                         // Prioridad 2: Override por Elección y Categoría (general a ámbitos) | ||||
|                         ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null)?.LogoUrl | ||||
|                         // Prioridad 3: Fallback Global para la CATEGORÍA (EleccionId = 0, CategoriaId) | ||||
|                         ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null)?.LogoUrl | ||||
|                         // Prioridad 4: Fallback "Super Global" (EleccionId = 0, CategoriaId = 0) | ||||
|                         ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == 0 && l.AmbitoGeograficoId == null)?.LogoUrl; | ||||
|  | ||||
|                     return new ResultadoCandidatoDto | ||||
|                     { | ||||
|                         AgrupacionId = r.Agrupacion.Id, | ||||
|                         NombreAgrupacion = r.Agrupacion.NombreCorto ?? r.Agrupacion.Nombre, | ||||
|                         NombreAgrupacion = r.Agrupacion.Nombre, | ||||
|                         NombreCortoAgrupacion = r.Agrupacion.NombreCorto, | ||||
|                         NombreCandidato = candidatoMatch?.NombreCandidato, | ||||
|                         Color = r.Agrupacion.Color, | ||||
|                         Votos = r.Votos, | ||||
|                         NombreCandidato = (todosLosOverrides.FirstOrDefault(c => c.AgrupacionPoliticaId == r.Agrupacion.Id && c.AmbitoGeograficoId == provinciaAmbitoId) | ||||
|                                           ?? todosLosOverrides.FirstOrDefault(c => c.AgrupacionPoliticaId == r.Agrupacion.Id && c.AmbitoGeograficoId == null)) | ||||
|                                           ?.NombreCandidato, | ||||
|                         FotoUrl = (todosLosLogos.FirstOrDefault(l => l.AgrupacionPoliticaId == r.Agrupacion.Id && l.AmbitoGeograficoId == provinciaAmbitoId) | ||||
|                                    ?? todosLosLogos.FirstOrDefault(l => l.AgrupacionPoliticaId == r.Agrupacion.Id && l.AmbitoGeograficoId == null)) | ||||
|                                    ?.LogoUrl, | ||||
|                         BancasObtenidas = todasLasProyecciones.ContainsKey(provinciaAmbitoId + "_" + r.Agrupacion.Id) | ||||
|                                         ? todasLasProyecciones[provinciaAmbitoId + "_" + r.Agrupacion.Id].NroBancas | ||||
|                                         : 0, | ||||
|                         Porcentaje = totalVotosProvincia > 0 ? (r.Votos / totalVotosProvincia) * 100 : 0 | ||||
|                         FotoUrl = logoFinal, | ||||
|                         BancasObtenidas = todasLasProyecciones.TryGetValue(provinciaAmbitoId + "_" + r.Agrupacion.Id + "_" + categoriaId, out var proyeccion) ? proyeccion.NroBancas : 0, | ||||
|                         Porcentaje = totalVotosCategoria > 0 ? (r.Votos / totalVotosCategoria) * 100 : 0 | ||||
|                     }; | ||||
|                 }).ToList() | ||||
|             }; | ||||
|         }).ToList(); | ||||
|  | ||||
|                 }); | ||||
|             } | ||||
|             if (dtoProvincia.Categorias.Any()) { resultadosFinales.Add(dtoProvincia); } | ||||
|         } | ||||
|         return Ok(resultadosFinales); | ||||
|     } | ||||
|  | ||||
|     [HttpGet("~/api/elecciones/home-resumen")] | ||||
|     public async Task<IActionResult> GetHomeResumen( | ||||
|     [FromQuery] int eleccionId, | ||||
|     [FromQuery] string distritoId, | ||||
|     [FromQuery] int categoriaId) | ||||
|     { | ||||
|         var provincia = await _dbContext.AmbitosGeograficos.AsNoTracking() | ||||
|             .FirstOrDefaultAsync(a => a.DistritoId == distritoId && a.NivelId == 10); | ||||
|  | ||||
|         if (provincia == null) return NotFound($"No se encontró la provincia con DistritoId {distritoId}."); | ||||
|  | ||||
|         var votosAgregados = await _dbContext.ResultadosVotos.AsNoTracking() | ||||
|             .Where(r => r.EleccionId == eleccionId && | ||||
|                         r.CategoriaId == categoriaId && | ||||
|                         r.AmbitoGeografico.DistritoId == distritoId) | ||||
|             .GroupBy(r => r.AgrupacionPolitica) | ||||
|             .Select(g => new { Agrupacion = g.Key, Votos = g.Sum(r => r.CantidadVotos) }) | ||||
|             .OrderByDescending(x => x.Votos) | ||||
|             .ToListAsync(); | ||||
|  | ||||
|         var todosLosOverrides = await _dbContext.CandidatosOverrides.AsNoTracking().Where(c => c.EleccionId == eleccionId || c.EleccionId == 0).ToListAsync(); | ||||
|         var todosLosLogos = await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().Where(l => l.EleccionId == eleccionId || l.EleccionId == 0).ToListAsync(); | ||||
|         var estado = await _dbContext.EstadosRecuentosGenerales.AsNoTracking().Include(e => e.CategoriaElectoral).FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaId && e.AmbitoGeograficoId == provincia.Id); | ||||
|         var votosNoPositivosAgregados = await _dbContext.EstadosRecuentos.AsNoTracking().Where(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaId && e.AmbitoGeografico.DistritoId == distritoId).GroupBy(e => 1).Select(g => new { VotosEnBlanco = g.Sum(e => e.VotosEnBlanco), VotosNulos = g.Sum(e => e.VotosNulos), VotosRecurridos = g.Sum(e => e.VotosRecurridos) }).FirstOrDefaultAsync(); | ||||
|  | ||||
|         var totalVotosPositivos = (decimal)votosAgregados.Sum(r => r.Votos); | ||||
|         var votosEnBlanco = votosNoPositivosAgregados?.VotosEnBlanco ?? 0; | ||||
|         var votosTotales = totalVotosPositivos + votosEnBlanco + (votosNoPositivosAgregados?.VotosNulos ?? 0) + (votosNoPositivosAgregados?.VotosRecurridos ?? 0); | ||||
|  | ||||
|         var respuesta = new CategoriaResumenHomeDto | ||||
|         { | ||||
|             CategoriaId = categoriaId, | ||||
|             CategoriaNombre = estado?.CategoriaElectoral.Nombre ?? (categoriaId == 2 ? "DIPUTADOS NACIONALES" : "SENADORES NACIONALES"), | ||||
|             UltimaActualizacion = estado?.FechaTotalizacion ?? DateTime.UtcNow, | ||||
|             EstadoRecuento = estado != null ? new EstadoRecuentoDto | ||||
|             { | ||||
|                 ParticipacionPorcentaje = estado.ParticipacionPorcentaje, | ||||
|                 MesasTotalizadasPorcentaje = estado.MesasTotalizadasPorcentaje, | ||||
|                 CantidadVotantes = estado.CantidadVotantes | ||||
|             } : null, | ||||
|             VotosEnBlanco = votosEnBlanco, | ||||
|             VotosEnBlancoPorcentaje = votosTotales > 0 ? (votosEnBlanco / votosTotales) * 100 : 0, | ||||
|             VotosTotales = (long)votosTotales, | ||||
|             Resultados = votosAgregados.Select(r => | ||||
|             { | ||||
|                 var provinciaAmbitoId = provincia.Id; | ||||
|                 var candidatoMatch = FindBestCandidatoMatch(todosLosOverrides, r.Agrupacion.Id, categoriaId, provinciaAmbitoId, eleccionId); | ||||
|  | ||||
|                 string? logoFinal = | ||||
|                     // Prioridad 1: Override Específico (EleccionId, CategoriaId, AmbitoId) | ||||
|                     todosLosLogos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == provinciaAmbitoId)?.LogoUrl | ||||
|                     // Prioridad 2: Override por Elección y Categoría (general a ámbitos) | ||||
|                     ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == eleccionId && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null)?.LogoUrl | ||||
|                     // Prioridad 3: Fallback Global para la CATEGORÍA (EleccionId = 0, CategoriaId) | ||||
|                     ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null)?.LogoUrl | ||||
|                     // Prioridad 4: Fallback "Super Global" (EleccionId = 0, CategoriaId = 0) | ||||
|                     ?? todosLosLogos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == r.Agrupacion.Id && l.CategoriaId == 0 && l.AmbitoGeograficoId == null)?.LogoUrl; | ||||
|  | ||||
|                 return new ResultadoCandidatoDto | ||||
|                 { | ||||
|                     AgrupacionId = r.Agrupacion.Id, | ||||
|                     NombreAgrupacion = r.Agrupacion.Nombre, | ||||
|                     NombreCortoAgrupacion = r.Agrupacion.NombreCorto, | ||||
|                     NombreCandidato = candidatoMatch?.NombreCandidato, | ||||
|                     Color = r.Agrupacion.Color, | ||||
|                     Votos = r.Votos, | ||||
|                     Porcentaje = totalVotosPositivos > 0 ? (r.Votos / totalVotosPositivos) * 100 : 0, | ||||
|                     FotoUrl = logoFinal | ||||
|                 }; | ||||
|             }).ToList() | ||||
|         }; | ||||
|  | ||||
|         return Ok(respuesta); | ||||
|     } | ||||
| } | ||||
| @@ -159,319 +159,215 @@ using (var scope = app.Services.CreateScope()) // O 'host.Services.CreateScope() | ||||
|  | ||||
| app.UseForwardedHeaders(); | ||||
|  | ||||
| // Seeder para el usuario admin | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     try | ||||
|     { | ||||
|         var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|         var hasher = services.GetRequiredService<IPasswordHasher>(); | ||||
|         if (!context.AdminUsers.Any()) | ||||
|         { | ||||
|             var (hash, salt) = hasher.HashPassword("PTP847elec"); | ||||
|             context.AdminUsers.Add(new Elecciones.Database.Entities.AdminUser | ||||
|             { | ||||
|                 Username = "admin", | ||||
|                 PasswordHash = hash, | ||||
|                 PasswordSalt = salt | ||||
|             }); | ||||
|             context.SaveChanges(); | ||||
|             Console.WriteLine("--> Admin user seeded."); | ||||
|         } | ||||
|     } | ||||
|     catch (Exception ex) | ||||
|     { | ||||
|         var logger = services.GetRequiredService<ILogger<Program>>(); | ||||
|         logger.LogError(ex, "An error occurred while seeding the database."); | ||||
|     } | ||||
| } | ||||
|  | ||||
| // --- SEEDER DE ELECCIONES (Añadir para asegurar que existan) --- | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var context = scope.ServiceProvider.GetRequiredService<EleccionesDbContext>(); | ||||
|     if (!context.Elecciones.Any()) | ||||
|     { | ||||
|         context.Elecciones.AddRange( | ||||
|             new Eleccion { Id = 1, Nombre = "Elecciones Provinciales 2025", Nivel = "Provincial", DistritoId = "02", Fecha = new DateOnly(2025, 10, 26) }, | ||||
|             new Eleccion { Id = 2, Nombre = "Elecciones Nacionales 2025", Nivel = "Nacional", DistritoId = "00", Fecha = new DateOnly(2025, 10, 26) } | ||||
|         ); | ||||
|         context.SaveChanges(); | ||||
|         Console.WriteLine("--> Seeded Eleccion entities."); | ||||
|     } | ||||
| } | ||||
|  | ||||
|  | ||||
| // --- SEEDER DE BANCAS (MODIFICADO Y COMPLETADO) --- | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|     if (!context.Bancadas.Any()) | ||||
|     { | ||||
|         var bancas = new List<Bancada>(); | ||||
|  | ||||
|         // --- BANCAS PROVINCIALES (EleccionId = 1) --- | ||||
|         // 92 bancas de diputados provinciales | ||||
|         for (int i = 1; i <= 92; i++) | ||||
|         { | ||||
|             bancas.Add(new Bancada | ||||
|             { | ||||
|                 EleccionId = 1, | ||||
|                 Camara = Elecciones.Core.Enums.TipoCamara.Diputados, | ||||
|                 NumeroBanca = i | ||||
|             }); | ||||
|         } | ||||
|         // 46 bancas de senadores provinciales | ||||
|         for (int i = 1; i <= 46; i++) | ||||
|         { | ||||
|             bancas.Add(new Bancada | ||||
|             { | ||||
|                 EleccionId = 1, | ||||
|                 Camara = Elecciones.Core.Enums.TipoCamara.Senadores, | ||||
|                 NumeroBanca = i | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         // --- BANCAS NACIONALES (EleccionId = 2) --- | ||||
|         // 257 bancas de diputados nacionales | ||||
|         for (int i = 1; i <= 257; i++) | ||||
|         { | ||||
|             bancas.Add(new Bancada | ||||
|             { | ||||
|                 EleccionId = 2, | ||||
|                 Camara = TipoCamara.Diputados, | ||||
|                 NumeroBanca = i | ||||
|             }); | ||||
|         } | ||||
|         // 72 bancas de senadores nacionales | ||||
|         for (int i = 1; i <= 72; i++) | ||||
|         { | ||||
|             bancas.Add(new Bancada | ||||
|             { | ||||
|                 EleccionId = 2, | ||||
|                 Camara = TipoCamara.Senadores, | ||||
|                 NumeroBanca = i | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         context.Bancadas.AddRange(bancas); | ||||
|         context.SaveChanges(); | ||||
|         Console.WriteLine($"--> Seeded {bancas.Count} bancas físicas para ambas elecciones."); | ||||
|     } | ||||
| } | ||||
|  | ||||
| // --- Seeder para Proyecciones de Bancas (Elección Nacional) --- | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|  | ||||
|     const int eleccionNacionalId = 2; | ||||
|     // Categoría 2: Diputados Nacionales, Categoría 1: Senadores Nacionales | ||||
|     if (!context.ProyeccionesBancas.Any(p => p.EleccionId == eleccionNacionalId)) | ||||
|     { | ||||
|         var partidos = await context.AgrupacionesPoliticas.Take(5).ToListAsync(); | ||||
|         var provincia = await context.AmbitosGeograficos.FirstOrDefaultAsync(a => a.NivelId == 10); // Asumimos un ámbito provincial genérico para la proyección total | ||||
|  | ||||
|         if (partidos.Count >= 5 && provincia != null) | ||||
|         { | ||||
|             var proyecciones = new List<ProyeccionBanca> | ||||
|             { | ||||
|                 // -- DIPUTADOS (Se renuevan 127) -- | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 2, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[0].Id, NroBancas = 50, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 2, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[1].Id, NroBancas = 40, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 2, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[2].Id, NroBancas = 20, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 2, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[3].Id, NroBancas = 10, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 2, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[4].Id, NroBancas = 7, FechaTotalizacion = DateTime.UtcNow }, | ||||
|  | ||||
|                 // -- SENADORES (Se renuevan 24) -- | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 1, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[0].Id, NroBancas = 10, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 1, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[1].Id, NroBancas = 8, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 1, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[2].Id, NroBancas = 4, FechaTotalizacion = DateTime.UtcNow }, | ||||
|                 new() { EleccionId = eleccionNacionalId, CategoriaId = 1, AmbitoGeograficoId = provincia.Id, AgrupacionPoliticaId = partidos[3].Id, NroBancas = 2, FechaTotalizacion = DateTime.UtcNow }, | ||||
|             }; | ||||
|             await context.ProyeccionesBancas.AddRangeAsync(proyecciones); | ||||
|             await context.SaveChangesAsync(); | ||||
|             Console.WriteLine("--> Seeded Proyecciones de Bancas para la Elección Nacional."); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| // Seeder para las configuraciones por defecto | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|  | ||||
|     // Lista de configuraciones por defecto a asegurar | ||||
|     var defaultConfiguraciones = new Dictionary<string, string> | ||||
|     { | ||||
|         { "MostrarOcupantes", "true" }, | ||||
|         { "TickerResultadosCantidad", "3" }, | ||||
|         { "ConcejalesResultadosCantidad", "5" }, | ||||
|         { "Worker_Resultados_Activado", "false" }, | ||||
|         { "Worker_Bajas_Activado", "false" }, | ||||
|         { "Worker_Prioridad", "Resultados" }, | ||||
|         { "Logging_Level", "Information" }, | ||||
|         { "PresidenciaDiputadosNacional", "" }, | ||||
|         { "PresidenciaDiputadosNacional_TipoBanca", "ganada" }, | ||||
|         { "PresidenciaSenadoNacional_TipoBanca", "ganada" } | ||||
|     }; | ||||
|  | ||||
|     foreach (var config in defaultConfiguraciones) | ||||
|     { | ||||
|         if (!context.Configuraciones.Any(c => c.Clave == config.Key)) | ||||
|         { | ||||
|             context.Configuraciones.Add(new Configuracion { Clave = config.Key, Valor = config.Value }); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     context.SaveChanges(); | ||||
|     Console.WriteLine("--> Seeded default configurations."); | ||||
| } | ||||
|  | ||||
| // --- SEEDER FINAL Y AUTOSUFICIENTE (CON DATOS DE RECUENTO) --- | ||||
| // --- INICIO DEL BLOQUE DE SEEDERS UNIFICADO Y CORREGIDO --- | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|     var logger = services.GetRequiredService<ILogger<Program>>(); | ||||
|     var hasher = services.GetRequiredService<IPasswordHasher>(); | ||||
|  | ||||
|     const int eleccionNacionalId = 2; | ||||
|     // --- SEEDER 1: DATOS ESTRUCTURALES BÁSICOS (se ejecutan una sola vez si la BD está vacía) --- | ||||
|     // Estos son los datos maestros que NUNCA cambian. | ||||
|  | ||||
|     if (!context.ResultadosVotos.Any(r => r.EleccionId == eleccionNacionalId)) | ||||
|     // Usuario Admin | ||||
|     if (!await context.AdminUsers.AnyAsync()) | ||||
|     { | ||||
|         logger.LogInformation("--> No se encontraron datos para la elección nacional ID {EleccionId}. Generando datos de simulación COMPLETOS...", eleccionNacionalId); | ||||
|  | ||||
|         var eleccionNacional = await context.Elecciones.FindAsync(eleccionNacionalId) ?? new Eleccion { Id = eleccionNacionalId, Nombre = "Elecciones Nacionales 2025", Nivel = "Nacional", DistritoId = "00", Fecha = new DateOnly(2025, 10, 26) }; | ||||
|         if (!context.Elecciones.Local.Any(e => e.Id == eleccionNacionalId)) context.Elecciones.Add(eleccionNacional); | ||||
|  | ||||
|         var categoriaDiputadosNac = await context.CategoriasElectorales.FindAsync(2) ?? new CategoriaElectoral { Id = 2, Nombre = "DIPUTADOS NACIONALES", Orden = 3 }; | ||||
|         if (!context.CategoriasElectorales.Local.Any(c => c.Id == 2)) context.CategoriasElectorales.Add(categoriaDiputadosNac); | ||||
|         var (hash, salt) = hasher.HashPassword("PTP847elec"); | ||||
|         context.AdminUsers.Add(new AdminUser { Username = "admin", PasswordHash = hash, PasswordSalt = salt }); | ||||
|         await context.SaveChangesAsync(); | ||||
|         logger.LogInformation("--> Admin user seeded."); | ||||
|     } | ||||
|  | ||||
|         var provinciasMaestras = new Dictionary<string, string> | ||||
|         { | ||||
|             { "01", "CIUDAD AUTONOMA DE BUENOS AIRES" }, { "02", "BUENOS AIRES" }, { "03", "CATAMARCA" }, { "04", "CORDOBA" }, | ||||
|             { "05", "CORRIENTES" },{ "06", "CHACO" }, { "07", "CHUBUT" }, { "08", "ENTRE RIOS" }, | ||||
|             { "09", "FORMOSA" }, { "10", "JUJUY" }, { "11", "LA PAMPA" }, { "12", "LA RIOJA" }, | ||||
|             { "13", "MENDOZA" }, { "14", "MISIONES" }, { "15", "NEUQUEN" }, { "16", "RIO NEGRO" }, | ||||
|             { "17", "SALTA" }, { "18", "SAN JUAN" }, { "19", "SAN LUIS" }, { "20", "SANTA CRUZ" }, | ||||
|             { "21", "SANTA FE" }, { "22", "SANTIAGO DEL ESTERO" }, { "23", "TIERRA DEL FUEGO" }, { "24", "TUCUMAN" } | ||||
|     // Elecciones | ||||
|     if (!await context.Elecciones.AnyAsync()) | ||||
|     { | ||||
|         context.Elecciones.AddRange( | ||||
|             new Eleccion { Id = 1, Nombre = "Elecciones Provinciales 2025", Nivel = "Provincial", DistritoId = "02", Fecha = new DateOnly(2025, 10, 26) }, | ||||
|             new Eleccion { Id = 2, Nombre = "Elecciones Nacionales 2025", Nivel = "Nacional", DistritoId = "00", Fecha = new DateOnly(2025, 10, 26) } | ||||
|         ); | ||||
|         await context.SaveChangesAsync(); | ||||
|         logger.LogInformation("--> Seeded Eleccion entities."); | ||||
|     } | ||||
|  | ||||
|     // Bancas Físicas | ||||
|     if (!await context.Bancadas.AnyAsync()) | ||||
|     { | ||||
|         var bancas = new List<Bancada>(); | ||||
|         for (int i = 1; i <= 92; i++) { bancas.Add(new Bancada { EleccionId = 1, Camara = TipoCamara.Diputados, NumeroBanca = i }); } | ||||
|         for (int i = 1; i <= 46; i++) { bancas.Add(new Bancada { EleccionId = 1, Camara = TipoCamara.Senadores, NumeroBanca = i }); } | ||||
|         for (int i = 1; i <= 257; i++) { bancas.Add(new Bancada { EleccionId = 2, Camara = TipoCamara.Diputados, NumeroBanca = i }); } | ||||
|         for (int i = 1; i <= 72; i++) { bancas.Add(new Bancada { EleccionId = 2, Camara = TipoCamara.Senadores, NumeroBanca = i }); } | ||||
|         await context.Bancadas.AddRangeAsync(bancas); | ||||
|         await context.SaveChangesAsync(); | ||||
|         logger.LogInformation("--> Seeded {Count} bancas físicas para ambas elecciones.", bancas.Count); | ||||
|     } | ||||
|  | ||||
|     // Configuraciones por Defecto | ||||
|     var defaultConfiguraciones = new Dictionary<string, string> { | ||||
|         { "MostrarOcupantes", "true" }, { "TickerResultadosCantidad", "3" }, { "ConcejalesResultadosCantidad", "5" }, | ||||
|         { "Worker_Resultados_Activado", "false" }, { "Worker_Bajas_Activado", "false" }, { "Worker_Prioridad", "Resultados" }, | ||||
|         { "Logging_Level", "Information" }, { "PresidenciaDiputadosNacional", "" }, { "PresidenciaDiputadosNacional_TipoBanca", "ganada" }, | ||||
|         { "PresidenciaSenadoNacional_TipoBanca", "ganada" } | ||||
|     }; | ||||
|     foreach (var config in defaultConfiguraciones) | ||||
|     { | ||||
|         if (!await context.Configuraciones.AnyAsync(c => c.Clave == config.Key)) | ||||
|             context.Configuraciones.Add(new Configuracion { Clave = config.Key, Valor = config.Value }); | ||||
|     } | ||||
|     await context.SaveChangesAsync(); | ||||
|     logger.LogInformation("--> Default configurations verified/seeded."); | ||||
|  | ||||
|  | ||||
|     // --- SEEDER 2: DATOS DE EJEMPLO PARA ELECCIÓN NACIONAL (se ejecuta solo si faltan sus votos) --- | ||||
|     const int eleccionNacionalId = 2; | ||||
|     if (!await context.ResultadosVotos.AnyAsync(r => r.EleccionId == eleccionNacionalId)) | ||||
|     { | ||||
|         logger.LogInformation("--> No se encontraron datos de votos para la elección nacional ID {EleccionId}. Generando datos de simulación...", eleccionNacionalId); | ||||
|  | ||||
|         // PASO A: VERIFICAR/CREAR DEPENDENCIAS (Ámbitos, Categorías) | ||||
|         if (!await context.CategoriasElectorales.AnyAsync(c => c.Id == 1)) | ||||
|             context.CategoriasElectorales.Add(new CategoriaElectoral { Id = 1, Nombre = "SENADORES NACIONALES", Orden = 2 }); | ||||
|         if (!await context.CategoriasElectorales.AnyAsync(c => c.Id == 2)) | ||||
|             context.CategoriasElectorales.Add(new CategoriaElectoral { Id = 2, Nombre = "DIPUTADOS NACIONALES", Orden = 3 }); | ||||
|  | ||||
|         var provinciasMaestras = new Dictionary<string, string> { | ||||
|             { "01", "CIUDAD AUTONOMA DE BUENOS AIRES" }, { "02", "BUENOS AIRES" }, { "03", "CATAMARCA" }, { "04", "CORDOBA" }, { "05", "CORRIENTES" }, | ||||
|             { "06", "CHACO" }, { "07", "CHUBUT" }, { "08", "ENTRE RIOS" }, { "09", "FORMOSA" }, { "10", "JUJUY" }, { "11", "LA PAMPA" }, | ||||
|             { "12", "LA RIOJA" }, { "13", "MENDOZA" }, { "14", "MISIONES" }, { "15", "NEUQUEN" }, { "16", "RIO NEGRO" }, { "17", "SALTA" }, | ||||
|             { "18", "SAN JUAN" }, { "19", "SAN LUIS" }, { "20", "SANTA CRUZ" }, { "21", "SANTA FE" }, { "22", "SANTIAGO DEL ESTERO" }, | ||||
|             { "23", "TIERRA DEL FUEGO" }, { "24", "TUCUMAN" } | ||||
|         }; | ||||
|  | ||||
|         foreach (var p in provinciasMaestras) | ||||
|         { | ||||
|             if (!await context.AmbitosGeograficos.AnyAsync(a => a.NivelId == 10 && a.DistritoId == p.Key)) | ||||
|             { | ||||
|                 context.AmbitosGeograficos.Add(new AmbitoGeografico { Nombre = p.Value, NivelId = 10, DistritoId = p.Key }); | ||||
|             } | ||||
|         } | ||||
|         await context.SaveChangesAsync(); | ||||
|         logger.LogInformation("--> Verificados/creados los 24 ámbitos geográficos de Nivel 10."); | ||||
|  | ||||
|         var provinciasEnDb = await context.AmbitosGeograficos.AsNoTracking().Where(a => a.NivelId == 10).ToListAsync(); | ||||
|         foreach (var provincia in provinciasEnDb) | ||||
|         { | ||||
|             if (!await context.AmbitosGeograficos.AnyAsync(a => a.NivelId == 30 && a.DistritoId == provincia.DistritoId)) | ||||
|             { | ||||
|                 logger.LogWarning("--> No se encontraron municipios para {Provincia}. Creando 5 de ejemplo.", provincia.Nombre); | ||||
|                 for (int i = 1; i <= 5; i++) | ||||
|                 { | ||||
|                     context.AmbitosGeograficos.Add(new AmbitoGeografico { Nombre = $"{provincia.Nombre} - Depto. {i}", NivelId = 30, DistritoId = provincia.DistritoId }); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|         await context.SaveChangesAsync(); | ||||
|         logger.LogInformation("--> Datos maestros para Elección Nacional (Ámbitos, Categorías) verificados/creados."); | ||||
|  | ||||
|         // PASO B: GENERAR DATOS TRANSACCIONALES (Votos, Recuentos, etc.) | ||||
|         var todosLosPartidos = await context.AgrupacionesPoliticas.Take(5).ToListAsync(); | ||||
|         if (!todosLosPartidos.Any()) | ||||
|         { | ||||
|             logger.LogWarning("--> No hay partidos, no se pueden generar votos."); | ||||
|             return; | ||||
|             logger.LogWarning("--> No hay partidos en la BD, no se pueden generar votos de ejemplo."); | ||||
|             return; // Salir si no hay partidos para evitar errores | ||||
|         } | ||||
|  | ||||
|         // (La lógica interna de generación de votos y recuentos que ya tenías y funcionaba) | ||||
|         // ... (el código de generación de `nuevosResultados` y `nuevosEstados` va aquí, sin cambios) | ||||
|         var nuevosResultados = new List<ResultadoVoto>(); | ||||
|         var nuevosEstados = new List<EstadoRecuentoGeneral>(); | ||||
|         var rand = new Random(); | ||||
|         var provinciasQueRenuevanSenadores = new HashSet<string> { "01", "06", "08", "15", "16", "17", "22", "23" }; | ||||
|         var categoriaDiputadosNac = await context.CategoriasElectorales.FindAsync(2); | ||||
|         var categoriaSenadoresNac = await context.CategoriasElectorales.FindAsync(1); | ||||
|  | ||||
|         long totalVotosNacional = 0; | ||||
|         int totalMesasNacional = 0; | ||||
|         int totalMesasEscrutadasNacional = 0; | ||||
|         long totalVotosNacionalDip = 0, totalVotosNacionalSen = 0; | ||||
|         int totalMesasNacionalDip = 0, totalMesasNacionalSen = 0; | ||||
|         int totalMesasEscrutadasNacionalDip = 0, totalMesasEscrutadasNacionalSen = 0; | ||||
|  | ||||
|         foreach (var provincia in provinciasEnDb) | ||||
|         { | ||||
|             var municipiosDeProvincia = await context.AmbitosGeograficos.AsNoTracking().Where(a => a.NivelId == 30 && a.DistritoId == provincia.DistritoId).ToListAsync(); | ||||
|             if (!municipiosDeProvincia.Any()) continue; | ||||
|  | ||||
|             long totalVotosProvincia = 0; | ||||
|             var categoriasParaProcesar = new List<CategoriaElectoral> { categoriaDiputadosNac! }; | ||||
|             if (provinciasQueRenuevanSenadores.Contains(provincia.DistritoId!)) | ||||
|                 categoriasParaProcesar.Add(categoriaSenadoresNac!); | ||||
|  | ||||
|             int partidoIndex = rand.Next(todosLosPartidos.Count); | ||||
|             foreach (var municipio in municipiosDeProvincia) | ||||
|             foreach (var categoria in categoriasParaProcesar) | ||||
|             { | ||||
|                 var partidoGanador = todosLosPartidos[partidoIndex++ % todosLosPartidos.Count]; | ||||
|                 var votosGanador = rand.Next(25000, 70000); | ||||
|                 nuevosResultados.Add(new ResultadoVoto { EleccionId = eleccionNacionalId, AmbitoGeograficoId = municipio.Id, CategoriaId = categoriaDiputadosNac.Id, AgrupacionPoliticaId = partidoGanador.Id, CantidadVotos = votosGanador }); | ||||
|                 totalVotosProvincia += votosGanador; | ||||
|  | ||||
|                 var otrosPartidos = todosLosPartidos.Where(p => p.Id != partidoGanador.Id).OrderBy(p => rand.Next()).Take(rand.Next(3, todosLosPartidos.Count)); | ||||
|                 foreach (var competidor in otrosPartidos) | ||||
|                 long totalVotosProvinciaCategoria = 0; | ||||
|                 int partidoIndex = rand.Next(todosLosPartidos.Count); | ||||
|                 foreach (var municipio in municipiosDeProvincia) | ||||
|                 { | ||||
|                     var votosCompetidor = rand.Next(1000, 24000); | ||||
|                     nuevosResultados.Add(new ResultadoVoto { EleccionId = eleccionNacionalId, AmbitoGeograficoId = municipio.Id, CategoriaId = categoriaDiputadosNac.Id, AgrupacionPoliticaId = competidor.Id, CantidadVotos = votosCompetidor }); | ||||
|                     totalVotosProvincia += votosCompetidor; | ||||
|                     var partidoGanador = todosLosPartidos[partidoIndex++ % todosLosPartidos.Count]; | ||||
|                     var votosGanador = rand.Next(25000, 70000); | ||||
|                     nuevosResultados.Add(new ResultadoVoto { EleccionId = eleccionNacionalId, AmbitoGeograficoId = municipio.Id, CategoriaId = categoria.Id, AgrupacionPoliticaId = partidoGanador.Id, CantidadVotos = votosGanador }); | ||||
|                     totalVotosProvinciaCategoria += votosGanador; | ||||
|                     var otrosPartidos = todosLosPartidos.Where(p => p.Id != partidoGanador.Id).OrderBy(p => rand.Next()).Take(rand.Next(3, todosLosPartidos.Count)); | ||||
|                     foreach (var competidor in otrosPartidos) | ||||
|                     { | ||||
|                         var votosCompetidor = rand.Next(1000, 24000); | ||||
|                         nuevosResultados.Add(new ResultadoVoto { EleccionId = eleccionNacionalId, AmbitoGeograficoId = municipio.Id, CategoriaId = categoria.Id, AgrupacionPoliticaId = competidor.Id, CantidadVotos = votosCompetidor }); | ||||
|                         totalVotosProvinciaCategoria += votosCompetidor; | ||||
|                     } | ||||
|                 } | ||||
|                 var mesasEsperadasProvincia = municipiosDeProvincia.Count * rand.Next(15, 30); | ||||
|                 var mesasTotalizadasProvincia = (int)(mesasEsperadasProvincia * (rand.Next(75, 99) / 100.0)); | ||||
|                 var cantidadElectoresProvincia = mesasEsperadasProvincia * 350; | ||||
|                 var participacionProvincia = (decimal)(rand.Next(65, 85) / 100.0); | ||||
|                 nuevosEstados.Add(new EstadoRecuentoGeneral | ||||
|                 { | ||||
|                     EleccionId = eleccionNacionalId, | ||||
|                     AmbitoGeograficoId = provincia.Id, | ||||
|                     CategoriaId = categoria.Id, | ||||
|                     FechaTotalizacion = DateTime.UtcNow, | ||||
|                     MesasEsperadas = mesasEsperadasProvincia, | ||||
|                     MesasTotalizadas = mesasTotalizadasProvincia, | ||||
|                     MesasTotalizadasPorcentaje = mesasEsperadasProvincia > 0 ? (decimal)mesasTotalizadasProvincia * 100 / mesasEsperadasProvincia : 0, | ||||
|                     CantidadElectores = cantidadElectoresProvincia, | ||||
|                     CantidadVotantes = (int)(cantidadElectoresProvincia * participacionProvincia), | ||||
|                     ParticipacionPorcentaje = participacionProvincia * 100 | ||||
|                 }); | ||||
|                 if (categoriaDiputadosNac != null && categoria.Id == categoriaDiputadosNac.Id) | ||||
|                 { | ||||
|                     totalVotosNacionalDip += totalVotosProvinciaCategoria; totalMesasNacionalDip += mesasEsperadasProvincia; totalMesasEscrutadasNacionalDip += mesasTotalizadasProvincia; | ||||
|                 } | ||||
|                 else | ||||
|                 { | ||||
|                     totalVotosNacionalSen += totalVotosProvinciaCategoria; totalMesasNacionalSen += mesasEsperadasProvincia; totalMesasEscrutadasNacionalSen += mesasTotalizadasProvincia; | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             // --- LÓGICA DE DATOS DE RECUENTO POR PROVINCIA --- | ||||
|             var mesasEsperadasProvincia = municipiosDeProvincia.Count * rand.Next(15, 30); | ||||
|             var mesasTotalizadasProvincia = (int)(mesasEsperadasProvincia * (rand.Next(75, 99) / 100.0)); | ||||
|             var cantidadElectoresProvincia = mesasEsperadasProvincia * 350; | ||||
|             var participacionProvincia = (decimal)(rand.Next(65, 85) / 100.0); | ||||
|  | ||||
|         } | ||||
|         var ambitoNacional = await context.AmbitosGeograficos.AsNoTracking().FirstOrDefaultAsync(a => a.NivelId == 0); | ||||
|         if (ambitoNacional != null && categoriaDiputadosNac != null && categoriaSenadoresNac != null) | ||||
|         { | ||||
|             var participacionNacionalDip = (decimal)(rand.Next(70, 88) / 100.0); | ||||
|             nuevosEstados.Add(new EstadoRecuentoGeneral | ||||
|             { | ||||
|                 EleccionId = eleccionNacionalId, | ||||
|                 AmbitoGeograficoId = provincia.Id, | ||||
|                 AmbitoGeograficoId = ambitoNacional.Id, | ||||
|                 CategoriaId = categoriaDiputadosNac.Id, | ||||
|                 FechaTotalizacion = DateTime.UtcNow, | ||||
|                 MesasEsperadas = mesasEsperadasProvincia, | ||||
|                 MesasTotalizadas = mesasTotalizadasProvincia, | ||||
|                 MesasTotalizadasPorcentaje = (decimal)mesasTotalizadasProvincia * 100 / mesasEsperadasProvincia, | ||||
|                 CantidadElectores = cantidadElectoresProvincia, | ||||
|                 CantidadVotantes = (int)(cantidadElectoresProvincia * participacionProvincia), | ||||
|                 ParticipacionPorcentaje = participacionProvincia * 100 | ||||
|                 MesasEsperadas = totalMesasNacionalDip, | ||||
|                 MesasTotalizadas = totalMesasEscrutadasNacionalDip, | ||||
|                 MesasTotalizadasPorcentaje = totalMesasNacionalDip > 0 ? (decimal)totalMesasEscrutadasNacionalDip * 100 / totalMesasNacionalDip : 0, | ||||
|                 CantidadElectores = totalMesasNacionalDip * 350, | ||||
|                 CantidadVotantes = (int)((totalMesasNacionalDip * 350) * participacionNacionalDip), | ||||
|                 ParticipacionPorcentaje = participacionNacionalDip * 100 | ||||
|             }); | ||||
|             var participacionNacionalSen = (decimal)(rand.Next(70, 88) / 100.0); | ||||
|             nuevosEstados.Add(new EstadoRecuentoGeneral | ||||
|             { | ||||
|                 EleccionId = eleccionNacionalId, | ||||
|                 AmbitoGeograficoId = ambitoNacional.Id, | ||||
|                 CategoriaId = categoriaSenadoresNac.Id, | ||||
|                 FechaTotalizacion = DateTime.UtcNow, | ||||
|                 MesasEsperadas = totalMesasNacionalSen, | ||||
|                 MesasTotalizadas = totalMesasEscrutadasNacionalSen, | ||||
|                 MesasTotalizadasPorcentaje = totalMesasNacionalSen > 0 ? (decimal)totalMesasEscrutadasNacionalSen * 100 / totalMesasNacionalSen : 0, | ||||
|                 CantidadElectores = totalMesasNacionalSen * 350, | ||||
|                 CantidadVotantes = (int)((totalMesasNacionalSen * 350) * participacionNacionalSen), | ||||
|                 ParticipacionPorcentaje = participacionNacionalSen * 100 | ||||
|             }); | ||||
|  | ||||
|             totalVotosNacional += totalVotosProvincia; | ||||
|             totalMesasNacional += mesasEsperadasProvincia; | ||||
|             totalMesasEscrutadasNacional += mesasTotalizadasProvincia; | ||||
|         } | ||||
|  | ||||
|         // --- LÓGICA DE DATOS DE RECUENTO A NIVEL NACIONAL --- | ||||
|         var ambitoNacional = await context.AmbitosGeograficos.AsNoTracking().FirstOrDefaultAsync(a => a.NivelId == 0); | ||||
|         if (ambitoNacional == null) | ||||
|         else | ||||
|         { | ||||
|             ambitoNacional = new AmbitoGeografico { Nombre = "Nacional", NivelId = 0, DistritoId = "00" }; | ||||
|             context.AmbitosGeograficos.Add(ambitoNacional); | ||||
|             await context.SaveChangesAsync(); | ||||
|             logger.LogWarning("--> No se encontró el ámbito nacional (NivelId == 0) o las categorías electorales nacionales. No se agregaron estados nacionales."); | ||||
|         } | ||||
|         var participacionNacional = (decimal)(rand.Next(70, 88) / 100.0); | ||||
|         nuevosEstados.Add(new EstadoRecuentoGeneral | ||||
|         { | ||||
|             EleccionId = eleccionNacionalId, | ||||
|             AmbitoGeograficoId = ambitoNacional.Id, | ||||
|             CategoriaId = categoriaDiputadosNac.Id, | ||||
|             FechaTotalizacion = DateTime.UtcNow, | ||||
|             MesasEsperadas = totalMesasNacional, | ||||
|             MesasTotalizadas = totalMesasEscrutadasNacional, | ||||
|             MesasTotalizadasPorcentaje = (decimal)totalMesasEscrutadasNacional * 100 / totalMesasNacional, | ||||
|             CantidadElectores = totalMesasNacional * 350, | ||||
|             CantidadVotantes = (int)((totalMesasNacional * 350) * participacionNacional), | ||||
|             ParticipacionPorcentaje = participacionNacional * 100 | ||||
|         }); | ||||
|  | ||||
|         if (nuevosResultados.Any()) | ||||
|         { | ||||
| @@ -480,48 +376,29 @@ using (var scope = app.Services.CreateScope()) | ||||
|             await context.SaveChangesAsync(); | ||||
|             logger.LogInformation("--> Se generaron {Votos} registros de votos y {Estados} de estados de recuento.", nuevosResultados.Count, nuevosEstados.Count); | ||||
|         } | ||||
|         else | ||||
|  | ||||
|         // PASO C: GENERAR BANCAS PREVIAS Y PROYECCIONES | ||||
|         if (!await context.BancasPrevias.AnyAsync(b => b.EleccionId == eleccionNacionalId)) | ||||
|         { | ||||
|             logger.LogWarning("--> No se generaron datos de simulación."); | ||||
|         } | ||||
|     } | ||||
| } | ||||
|  | ||||
| // --- Seeder para Bancas Previas (Composición Nacional 2025) --- | ||||
| using (var scope = app.Services.CreateScope()) | ||||
| { | ||||
|     var services = scope.ServiceProvider; | ||||
|     var context = services.GetRequiredService<EleccionesDbContext>(); | ||||
|  | ||||
|     const int eleccionNacionalId = 2; | ||||
|  | ||||
|     if (!context.BancasPrevias.Any(b => b.EleccionId == eleccionNacionalId)) | ||||
|     { | ||||
|         var partidos = await context.AgrupacionesPoliticas.Take(5).ToListAsync(); | ||||
|         if (partidos.Count >= 5) | ||||
|         { | ||||
|             var bancasPrevias = new List<BancaPrevia> | ||||
|             { | ||||
|                 // -- DIPUTADOS (Total: 257, se renuevan 127, quedan 130) -- | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = partidos[0].Id, Cantidad = 40 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = partidos[1].Id, Cantidad = 35 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = partidos[2].Id, Cantidad = 30 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = partidos[3].Id, Cantidad = 15 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = partidos[4].Id, Cantidad = 10 }, | ||||
|  | ||||
|                 // -- SENADORES (Total: 72, se renuevan 24, quedan 48) -- | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = partidos[0].Id, Cantidad = 18 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = partidos[1].Id, Cantidad = 15 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = partidos[2].Id, Cantidad = 8 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = partidos[3].Id, Cantidad = 4 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = partidos[4].Id, Cantidad = 3 }, | ||||
|             var bancasPrevias = new List<BancaPrevia> { | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = todosLosPartidos[0].Id, Cantidad = 40 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = todosLosPartidos[1].Id, Cantidad = 35 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = todosLosPartidos[2].Id, Cantidad = 30 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = todosLosPartidos[3].Id, Cantidad = 15 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Diputados, AgrupacionPoliticaId = todosLosPartidos[4].Id, Cantidad = 10 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = todosLosPartidos[0].Id, Cantidad = 18 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = todosLosPartidos[1].Id, Cantidad = 15 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = todosLosPartidos[2].Id, Cantidad = 8 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = todosLosPartidos[3].Id, Cantidad = 4 }, | ||||
|                 new() { EleccionId = eleccionNacionalId, Camara = TipoCamara.Senadores, AgrupacionPoliticaId = todosLosPartidos[4].Id, Cantidad = 3 }, | ||||
|             }; | ||||
|             await context.BancasPrevias.AddRangeAsync(bancasPrevias); | ||||
|             await context.SaveChangesAsync(); | ||||
|             Console.WriteLine("--> Seeded Bancas Previas para la Elección Nacional."); | ||||
|             logger.LogInformation("--> Seeded Bancas Previas para la Elección Nacional."); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| // --- FIN DEL BLOQUE DE SEEDERS UNIFICADO --- | ||||
|  | ||||
| // Configurar el pipeline de peticiones HTTP. | ||||
| // Añadimos el logging de peticiones de Serilog aquí. | ||||
|   | ||||
| @@ -5,7 +5,8 @@ | ||||
|   "Logging": { | ||||
|     "LogLevel": { | ||||
|       "Default": "Information", | ||||
|       "Microsoft.AspNetCore": "Warning" | ||||
|       "Microsoft.AspNetCore": "Warning", | ||||
|       "Microsoft.EntityFrameworkCore.Database.Command": "Information" | ||||
|     } | ||||
|   }, | ||||
|   "ApiKey": "badb1a38d221c9e23bcf70958840ca7f5a5dc54f2047dadf7ce45b578b5bc3e2", | ||||
|   | ||||
| @@ -5,7 +5,8 @@ | ||||
|   "Logging": { | ||||
|     "LogLevel": { | ||||
|       "Default": "Information", | ||||
|       "Microsoft.AspNetCore": "Warning" | ||||
|       "Microsoft.AspNetCore": "Warning", | ||||
|       "Microsoft.EntityFrameworkCore.Database.Command": "Information" | ||||
|     } | ||||
|   }, | ||||
|   "ApiKey": "badb1a38d221c9e23bcf70958840ca7f5a5dc54f2047dadf7ce45b578b5bc3e2", | ||||
|   | ||||
| @@ -14,7 +14,7 @@ using System.Reflection; | ||||
| [assembly: System.Reflection.AssemblyCompanyAttribute("Elecciones.Api")] | ||||
| [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] | ||||
| [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+67634ae947197595f6f644f3a80a982dd3573dfb")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+3b0eee25e6441da1831442a90b6552cc8ef59d07")] | ||||
| [assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Api")] | ||||
| [assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Api")] | ||||
| [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] | ||||
|   | ||||
| @@ -1 +1 @@ | ||||
| {"GlobalPropertiesHash":"b5T/+ta4fUd8qpIzUTm3KyEwAYYUsU5ASo+CSFM3ByE=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["TyIJk/eQMWjmB5LsDE\u002BZIJC9P9ciVxd7bnzRiTZsGt4=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","i5\u002B5LcfxQD8meRAkQbVf4wMvjxSE4\u002BjCd2/FdPtMpms=","AvSkxVPIg0GjnB1RJ4hDNyo9p9GONrzDs8uVuixH\u002BOE=","IgT9pOgRnK37qfILj2QcjFoBZ180HMt\u002BScgje2iYOo4=","ezUlOMzNZmyKDIe1wwXqvX\u002BvhwfB992xNVts7r2zcTc=","y2BV4WpkQuLfqQhfOQBtmuzh940c3s4LAopGKfztfTE=","lHTUEsMkDu8nqXtfTwl7FRfgocyyc7RI5O/edTHN1\u002B0=","A7nz7qgOtQ1CwZZLvNnr0b5QZB3fTi3y4i6y7rBIcxQ=","znnuRi2tsk7AACuYo4WSgj7NcLriG4PKVaF4L35SvDk=","GelE32odx/vTului267wqi6zL3abBnF9yvwC2Q66LoM=","TEsXImnzxFKTIq2f5fiDu7i6Ar/cbecW5MZ3z8Wb/a4=","5WogJu\u002BUPlF\u002BE5mq/ILtDXpVwqwmhHtsEB13nmT5JJk=","dcHQRkttjMjo2dvhL7hA9t4Pg\u002B7OnjZpkFmakT4QR9U=","Of8nTYw5l\u002BgiAJo7z6XYIntG2tUtCFcILzHbTiiXn\u002Bw=","PDy\u002BTiayvNAoXXBEgwC/kCojpgOOMI6RQOIoSXs3LJc=","ePXrkee3hv3wHUr8S7aYmRVvXUTxQf76zApKGv3/l3o=","DXx5dQywLo3UsY2zQaUG\u002BbW4ObiYbybxPBWxeJD2bhk=","muVh5sjH3sgdvuz4TbuTwTggX1uDnsWXgoosMKST/r4=","nrP5gSIA5vzgp8v12CAOr943QYLxU4Til6oiCcWSNI8=","yMd45U9BK07I3b3fBQ627PWTYyZ2ZjrmFc5VD\u002BQVx1Q=","xKskvcoJU0RVRN1a5dRqKRM7IP5vmmbraUaPFYjhnCc=","p7BjQw7aSZjfOCqmKm7/kPO9qegEQZBfirMjlOx/I1I=","MI0hVVLYavEhzHq/Z1UbajfrxanA1aET19aOH8G2ImI=","2dY8CqW9fAY8yN0foa\u002BZp2gc0RfPoPmB/tKSj1QoTw0=","79rfGLH4UjfTPvc//\u002BZjnBqdz585pUtYZ0/hwE2iEic=","PUqgvMdfTQkF5lpBVtHv2teQLV5WaEH0xMKTmINe2YQ=","\u002BFI0b4ppdxel/pby/y/xKImHrtdxo2g83OhskdREyIg=","jEESu6\u002BhbDvNMjLt/6OufuK\u002B9cHmzx\u002BTCIn4fWa9nSc=","UaCPJEvR4nVxxGCB5CUnRlJiw4drDW3Q3Nss\u002Bya2cv4=","ZqF13CT3rok/Gzl\u002BMsw3q9X1nf65bwEVD670efE3k\u002Bk=","gH3W7phPzBCY1DAVn4YnP4SA8Uaq73TpctS0yFSvzNM=","0dvJZBTDvT8AWA99AJa8lh9rnQsEsujRTFe1QDxskcw=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","amEOUyqq4sgg/zUP6A7nQMqSHcl7G5zl2HvyHRlhDvU="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| {"GlobalPropertiesHash":"b5T/+ta4fUd8qpIzUTm3KyEwAYYUsU5ASo+CSFM3ByE=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["VUEzgM3q00ehIicPw1uM8REVOid2zDpFbcwF9rvWytQ=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","ezUlOMzNZmyKDIe1wwXqvX\u002BvhwfB992xNVts7r2zcTc=","y2BV4WpkQuLfqQhfOQBtmuzh940c3s4LAopGKfztfTE=","lHTUEsMkDu8nqXtfTwl7FRfgocyyc7RI5O/edTHN1\u002B0=","A7nz7qgOtQ1CwZZLvNnr0b5QZB3fTi3y4i6y7rBIcxQ=","znnuRi2tsk7AACuYo4WSgj7NcLriG4PKVaF4L35SvDk=","GelE32odx/vTului267wqi6zL3abBnF9yvwC2Q66LoM=","TEsXImnzxFKTIq2f5fiDu7i6Ar/cbecW5MZ3z8Wb/a4=","5WogJu\u002BUPlF\u002BE5mq/ILtDXpVwqwmhHtsEB13nmT5JJk=","dcHQRkttjMjo2dvhL7hA9t4Pg\u002B7OnjZpkFmakT4QR9U=","Of8nTYw5l\u002BgiAJo7z6XYIntG2tUtCFcILzHbTiiXn\u002Bw=","PDy\u002BTiayvNAoXXBEgwC/kCojpgOOMI6RQOIoSXs3LJc=","ePXrkee3hv3wHUr8S7aYmRVvXUTxQf76zApKGv3/l3o=","DXx5dQywLo3UsY2zQaUG\u002BbW4ObiYbybxPBWxeJD2bhk=","muVh5sjH3sgdvuz4TbuTwTggX1uDnsWXgoosMKST/r4=","nrP5gSIA5vzgp8v12CAOr943QYLxU4Til6oiCcWSNI8=","yMd45U9BK07I3b3fBQ627PWTYyZ2ZjrmFc5VD\u002BQVx1Q=","xKskvcoJU0RVRN1a5dRqKRM7IP5vmmbraUaPFYjhnCc=","p7BjQw7aSZjfOCqmKm7/kPO9qegEQZBfirMjlOx/I1I=","MI0hVVLYavEhzHq/Z1UbajfrxanA1aET19aOH8G2ImI=","2dY8CqW9fAY8yN0foa\u002BZp2gc0RfPoPmB/tKSj1QoTw0=","79rfGLH4UjfTPvc//\u002BZjnBqdz585pUtYZ0/hwE2iEic=","PUqgvMdfTQkF5lpBVtHv2teQLV5WaEH0xMKTmINe2YQ=","\u002BFI0b4ppdxel/pby/y/xKImHrtdxo2g83OhskdREyIg=","jEESu6\u002BhbDvNMjLt/6OufuK\u002B9cHmzx\u002BTCIn4fWa9nSc=","UaCPJEvR4nVxxGCB5CUnRlJiw4drDW3Q3Nss\u002Bya2cv4=","ZqF13CT3rok/Gzl\u002BMsw3q9X1nf65bwEVD670efE3k\u002Bk=","gH3W7phPzBCY1DAVn4YnP4SA8Uaq73TpctS0yFSvzNM=","u5F4J4\u002BLHUIOCz5ze5NSF42mDeAaAfi\u002BKN3Ay3rKLY8=","GeUUID0ymF5rrBWdX7YHzWA5GiGkNWCNUog4sp4xL3c=","3BxX4I0JXoDqmE8m0BrRZhixBRlHEueS3jAlmUXE/I8=","s3VnfR5av25jQd9RIy\u002BMwczWKx/CJRSzFdhJAMaIN9k=","A\u002BWemDKn7UwHxqDXzVs57jXOqpea86CLYpxVWDzRnDo=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","jAqiyVzpgWGABD/mtww8iBZneRW/QcFx5ww\u002BXozPGx4="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| @@ -1 +1 @@ | ||||
| {"GlobalPropertiesHash":"tJTBjV/i0Ihkc6XuOu69wxL8PBac9c9Kak6srMso4pU=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["TyIJk/eQMWjmB5LsDE\u002BZIJC9P9ciVxd7bnzRiTZsGt4=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","i5\u002B5LcfxQD8meRAkQbVf4wMvjxSE4\u002BjCd2/FdPtMpms=","AvSkxVPIg0GjnB1RJ4hDNyo9p9GONrzDs8uVuixH\u002BOE=","IgT9pOgRnK37qfILj2QcjFoBZ180HMt\u002BScgje2iYOo4=","ezUlOMzNZmyKDIe1wwXqvX\u002BvhwfB992xNVts7r2zcTc=","y2BV4WpkQuLfqQhfOQBtmuzh940c3s4LAopGKfztfTE=","lHTUEsMkDu8nqXtfTwl7FRfgocyyc7RI5O/edTHN1\u002B0=","A7nz7qgOtQ1CwZZLvNnr0b5QZB3fTi3y4i6y7rBIcxQ=","znnuRi2tsk7AACuYo4WSgj7NcLriG4PKVaF4L35SvDk=","GelE32odx/vTului267wqi6zL3abBnF9yvwC2Q66LoM=","TEsXImnzxFKTIq2f5fiDu7i6Ar/cbecW5MZ3z8Wb/a4=","5WogJu\u002BUPlF\u002BE5mq/ILtDXpVwqwmhHtsEB13nmT5JJk=","dcHQRkttjMjo2dvhL7hA9t4Pg\u002B7OnjZpkFmakT4QR9U=","Of8nTYw5l\u002BgiAJo7z6XYIntG2tUtCFcILzHbTiiXn\u002Bw=","PDy\u002BTiayvNAoXXBEgwC/kCojpgOOMI6RQOIoSXs3LJc=","ePXrkee3hv3wHUr8S7aYmRVvXUTxQf76zApKGv3/l3o=","DXx5dQywLo3UsY2zQaUG\u002BbW4ObiYbybxPBWxeJD2bhk=","muVh5sjH3sgdvuz4TbuTwTggX1uDnsWXgoosMKST/r4=","nrP5gSIA5vzgp8v12CAOr943QYLxU4Til6oiCcWSNI8=","yMd45U9BK07I3b3fBQ627PWTYyZ2ZjrmFc5VD\u002BQVx1Q=","xKskvcoJU0RVRN1a5dRqKRM7IP5vmmbraUaPFYjhnCc=","p7BjQw7aSZjfOCqmKm7/kPO9qegEQZBfirMjlOx/I1I=","MI0hVVLYavEhzHq/Z1UbajfrxanA1aET19aOH8G2ImI=","2dY8CqW9fAY8yN0foa\u002BZp2gc0RfPoPmB/tKSj1QoTw0=","79rfGLH4UjfTPvc//\u002BZjnBqdz585pUtYZ0/hwE2iEic=","PUqgvMdfTQkF5lpBVtHv2teQLV5WaEH0xMKTmINe2YQ=","\u002BFI0b4ppdxel/pby/y/xKImHrtdxo2g83OhskdREyIg=","jEESu6\u002BhbDvNMjLt/6OufuK\u002B9cHmzx\u002BTCIn4fWa9nSc=","UaCPJEvR4nVxxGCB5CUnRlJiw4drDW3Q3Nss\u002Bya2cv4=","ZqF13CT3rok/Gzl\u002BMsw3q9X1nf65bwEVD670efE3k\u002Bk=","gH3W7phPzBCY1DAVn4YnP4SA8Uaq73TpctS0yFSvzNM=","0dvJZBTDvT8AWA99AJa8lh9rnQsEsujRTFe1QDxskcw=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","amEOUyqq4sgg/zUP6A7nQMqSHcl7G5zl2HvyHRlhDvU="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| {"GlobalPropertiesHash":"tJTBjV/i0Ihkc6XuOu69wxL8PBac9c9Kak6srMso4pU=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["VUEzgM3q00ehIicPw1uM8REVOid2zDpFbcwF9rvWytQ=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","ezUlOMzNZmyKDIe1wwXqvX\u002BvhwfB992xNVts7r2zcTc=","y2BV4WpkQuLfqQhfOQBtmuzh940c3s4LAopGKfztfTE=","lHTUEsMkDu8nqXtfTwl7FRfgocyyc7RI5O/edTHN1\u002B0=","A7nz7qgOtQ1CwZZLvNnr0b5QZB3fTi3y4i6y7rBIcxQ=","znnuRi2tsk7AACuYo4WSgj7NcLriG4PKVaF4L35SvDk=","GelE32odx/vTului267wqi6zL3abBnF9yvwC2Q66LoM=","TEsXImnzxFKTIq2f5fiDu7i6Ar/cbecW5MZ3z8Wb/a4=","5WogJu\u002BUPlF\u002BE5mq/ILtDXpVwqwmhHtsEB13nmT5JJk=","dcHQRkttjMjo2dvhL7hA9t4Pg\u002B7OnjZpkFmakT4QR9U=","Of8nTYw5l\u002BgiAJo7z6XYIntG2tUtCFcILzHbTiiXn\u002Bw=","PDy\u002BTiayvNAoXXBEgwC/kCojpgOOMI6RQOIoSXs3LJc=","ePXrkee3hv3wHUr8S7aYmRVvXUTxQf76zApKGv3/l3o=","DXx5dQywLo3UsY2zQaUG\u002BbW4ObiYbybxPBWxeJD2bhk=","muVh5sjH3sgdvuz4TbuTwTggX1uDnsWXgoosMKST/r4=","nrP5gSIA5vzgp8v12CAOr943QYLxU4Til6oiCcWSNI8=","yMd45U9BK07I3b3fBQ627PWTYyZ2ZjrmFc5VD\u002BQVx1Q=","xKskvcoJU0RVRN1a5dRqKRM7IP5vmmbraUaPFYjhnCc=","p7BjQw7aSZjfOCqmKm7/kPO9qegEQZBfirMjlOx/I1I=","MI0hVVLYavEhzHq/Z1UbajfrxanA1aET19aOH8G2ImI=","2dY8CqW9fAY8yN0foa\u002BZp2gc0RfPoPmB/tKSj1QoTw0=","79rfGLH4UjfTPvc//\u002BZjnBqdz585pUtYZ0/hwE2iEic=","PUqgvMdfTQkF5lpBVtHv2teQLV5WaEH0xMKTmINe2YQ=","\u002BFI0b4ppdxel/pby/y/xKImHrtdxo2g83OhskdREyIg=","jEESu6\u002BhbDvNMjLt/6OufuK\u002B9cHmzx\u002BTCIn4fWa9nSc=","UaCPJEvR4nVxxGCB5CUnRlJiw4drDW3Q3Nss\u002Bya2cv4=","ZqF13CT3rok/Gzl\u002BMsw3q9X1nf65bwEVD670efE3k\u002Bk=","gH3W7phPzBCY1DAVn4YnP4SA8Uaq73TpctS0yFSvzNM=","u5F4J4\u002BLHUIOCz5ze5NSF42mDeAaAfi\u002BKN3Ay3rKLY8=","GeUUID0ymF5rrBWdX7YHzWA5GiGkNWCNUog4sp4xL3c=","3BxX4I0JXoDqmE8m0BrRZhixBRlHEueS3jAlmUXE/I8=","s3VnfR5av25jQd9RIy\u002BMwczWKx/CJRSzFdhJAMaIN9k=","A\u002BWemDKn7UwHxqDXzVs57jXOqpea86CLYpxVWDzRnDo=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","jAqiyVzpgWGABD/mtww8iBZneRW/QcFx5ww\u002BXozPGx4="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| @@ -1 +1 @@ | ||||
| {"GlobalPropertiesHash":"O7YawHw32G/Fh2bs+snZgm9O7okI0WYgTQmXM931znY=","FingerprintPatternsHash":"gq3WsqcKBUGTSNle7RKKyXRIwh7M8ccEqOqYvIzoM04=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["TyIJk/eQMWjmB5LsDE\u002BZIJC9P9ciVxd7bnzRiTZsGt4=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| {"GlobalPropertiesHash":"O7YawHw32G/Fh2bs+snZgm9O7okI0WYgTQmXM931znY=","FingerprintPatternsHash":"gq3WsqcKBUGTSNle7RKKyXRIwh7M8ccEqOqYvIzoM04=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["VUEzgM3q00ehIicPw1uM8REVOid2zDpFbcwF9rvWytQ=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM="],"CachedAssets":{},"CachedCopyCandidates":{}} | ||||
| @@ -0,0 +1,28 @@ | ||||
| <?xml version="1.0" encoding="utf-8"?> | ||||
| <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> | ||||
|   <Target Name="GetEFProjectMetadata"> | ||||
|     <MSBuild Condition=" '$(TargetFramework)' == '' " | ||||
|              Projects="$(MSBuildProjectFile)" | ||||
|              Targets="GetEFProjectMetadata" | ||||
|              Properties="TargetFramework=$(TargetFrameworks.Split(';')[0]);EFProjectMetadataFile=$(EFProjectMetadataFile)" /> | ||||
|     <ItemGroup Condition=" '$(TargetFramework)' != '' "> | ||||
|       <EFProjectMetadata Include="AssemblyName: $(AssemblyName)" /> | ||||
|       <EFProjectMetadata Include="Language: $(Language)" /> | ||||
|       <EFProjectMetadata Include="OutputPath: $(OutputPath)" /> | ||||
|       <EFProjectMetadata Include="Platform: $(Platform)" /> | ||||
|       <EFProjectMetadata Include="PlatformTarget: $(PlatformTarget)" /> | ||||
|       <EFProjectMetadata Include="ProjectAssetsFile: $(ProjectAssetsFile)" /> | ||||
|       <EFProjectMetadata Include="ProjectDir: $(ProjectDir)" /> | ||||
|       <EFProjectMetadata Include="RootNamespace: $(RootNamespace)" /> | ||||
|       <EFProjectMetadata Include="RuntimeFrameworkVersion: $(RuntimeFrameworkVersion)" /> | ||||
|       <EFProjectMetadata Include="TargetFileName: $(TargetFileName)" /> | ||||
|       <EFProjectMetadata Include="TargetFrameworkMoniker: $(TargetFrameworkMoniker)" /> | ||||
|       <EFProjectMetadata Include="Nullable: $(Nullable)" /> | ||||
|       <EFProjectMetadata Include="TargetFramework: $(TargetFramework)" /> | ||||
|       <EFProjectMetadata Include="TargetPlatformIdentifier: $(TargetPlatformIdentifier)" /> | ||||
|     </ItemGroup> | ||||
|     <WriteLinesToFile Condition=" '$(TargetFramework)' != '' " | ||||
|                       File="$(EFProjectMetadataFile)" | ||||
|                       Lines="@(EFProjectMetadata)" /> | ||||
|   </Target> | ||||
| </Project> | ||||
| @@ -0,0 +1,14 @@ | ||||
| // src/Elecciones.Core/DTOs/ApiResponses/CategoriaResumenHomeDto.cs | ||||
| namespace Elecciones.Core.DTOs.ApiResponses; | ||||
|  | ||||
| public class CategoriaResumenHomeDto | ||||
| { | ||||
|     public int CategoriaId { get; set; } | ||||
|     public string CategoriaNombre { get; set; } = string.Empty; | ||||
|     public DateTime UltimaActualizacion { get; set; } | ||||
|     public EstadoRecuentoDto? EstadoRecuento { get; set; } | ||||
|     public long VotosEnBlanco { get; set; } | ||||
|     public decimal VotosEnBlancoPorcentaje { get; set; } | ||||
|     public long VotosTotales { get; set; } | ||||
|     public List<ResultadoCandidatoDto> Resultados { get; set; } = new(); | ||||
| } | ||||
| @@ -1,11 +1,11 @@ | ||||
| // src/Elecciones.Core/DTOs/ApiResponses/ResumenProvinciaDto.cs | ||||
| namespace Elecciones.Core.DTOs.ApiResponses; | ||||
|  | ||||
| public class ResultadoCandidatoDto | ||||
| { | ||||
|      public string AgrupacionId { get; set; } = string.Empty; | ||||
|     public string AgrupacionId { get; set; } = string.Empty; | ||||
|     public string? NombreCandidato { get; set; } | ||||
|     public string NombreAgrupacion { get; set; } = null!; | ||||
|     public string NombreAgrupacion { get; set; } = string.Empty; | ||||
|     public string? NombreCortoAgrupacion { get; set; } | ||||
|     public string? FotoUrl { get; set; } | ||||
|     public string? Color { get; set; } | ||||
|     public decimal Porcentaje { get; set; } | ||||
| @@ -13,10 +13,20 @@ public class ResultadoCandidatoDto | ||||
|     public int BancasObtenidas { get; set; } | ||||
| } | ||||
|  | ||||
| public class ResumenProvinciaDto | ||||
| // Representa una única categoría (ej. "Diputados") con sus resultados y estado de recuento. | ||||
| public class CategoriaResumenDto | ||||
| { | ||||
|     public string ProvinciaId { get; set; } = null!; // Corresponde al DistritoId | ||||
|     public string ProvinciaNombre { get; set; } = null!; | ||||
|     public int CategoriaId { get; set; } | ||||
|     public string CategoriaNombre { get; set; } = null!; | ||||
|     public EstadoRecuentoDto? EstadoRecuento { get; set; } | ||||
|     public List<ResultadoCandidatoDto> Resultados { get; set; } = new(); | ||||
| } | ||||
|  | ||||
| // --- DTO PRINCIPAL --- | ||||
| public class ResumenProvinciaDto | ||||
| { | ||||
|     public string ProvinciaId { get; set; } = null!; | ||||
|     public string ProvinciaNombre { get; set; } = null!; | ||||
|     // La propiedad 'Resultados' se reemplaza por 'Categorias' | ||||
|     public List<CategoriaResumenDto> Categorias { get; set; } = new(); | ||||
| } | ||||
| @@ -13,7 +13,7 @@ using System.Reflection; | ||||
| [assembly: System.Reflection.AssemblyCompanyAttribute("Elecciones.Core")] | ||||
| [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] | ||||
| [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+67634ae947197595f6f644f3a80a982dd3573dfb")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+3b0eee25e6441da1831442a90b6552cc8ef59d07")] | ||||
| [assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Core")] | ||||
| [assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Core")] | ||||
| [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] | ||||
|   | ||||
| @@ -30,6 +30,13 @@ public class EleccionesDbContext(DbContextOptions<EleccionesDbContext> options) | ||||
|  | ||||
|         modelBuilder.UseCollation("Modern_Spanish_CI_AS"); | ||||
|  | ||||
|         modelBuilder.Entity<Eleccion>(entity => | ||||
|         { | ||||
|             // Le decimos a EF que proporcionaremos el valor de la clave primaria. | ||||
|             // Esto evita que la configure como una columna IDENTITY en SQL Server. | ||||
|             entity.Property(e => e.Id).ValueGeneratedNever(); | ||||
|         }); | ||||
|  | ||||
|         modelBuilder.Entity<ResultadoVoto>() | ||||
|         .HasIndex(r => new { r.AmbitoGeograficoId, r.CategoriaId, r.AgrupacionPoliticaId }) | ||||
|         .IsUnique(); | ||||
|   | ||||
| @@ -10,8 +10,8 @@ public class LogoAgrupacionCategoria | ||||
|     [Required] | ||||
|     public string AgrupacionPoliticaId { get; set; } = null!; | ||||
|     [Required] | ||||
|     public int CategoriaId { get; set; } | ||||
|     public int? CategoriaId { get; set; } | ||||
|     public string? LogoUrl { get; set; } | ||||
|     public int? AmbitoGeograficoId { get; set; } | ||||
|     public int EleccionId { get; set; } | ||||
|     public int? EleccionId { get; set; } | ||||
| } | ||||
| @@ -1,48 +0,0 @@ | ||||
| using Microsoft.EntityFrameworkCore.Migrations; | ||||
|  | ||||
| #nullable disable | ||||
|  | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     /// <inheritdoc /> | ||||
|     public partial class AddBancasPreviasTable : Migration | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Up(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.CreateTable( | ||||
|                 name: "BancasPrevias", | ||||
|                 columns: table => new | ||||
|                 { | ||||
|                     Id = table.Column<int>(type: "int", nullable: false) | ||||
|                         .Annotation("SqlServer:Identity", "1, 1"), | ||||
|                     EleccionId = table.Column<int>(type: "int", nullable: false), | ||||
|                     Camara = table.Column<int>(type: "int", nullable: false), | ||||
|                     AgrupacionPoliticaId = table.Column<string>(type: "nvarchar(450)", nullable: false, collation: "Modern_Spanish_CI_AS"), | ||||
|                     Cantidad = table.Column<int>(type: "int", nullable: false) | ||||
|                 }, | ||||
|                 constraints: table => | ||||
|                 { | ||||
|                     table.PrimaryKey("PK_BancasPrevias", x => x.Id); | ||||
|                     table.ForeignKey( | ||||
|                         name: "FK_BancasPrevias_AgrupacionesPoliticas_AgrupacionPoliticaId", | ||||
|                         column: x => x.AgrupacionPoliticaId, | ||||
|                         principalTable: "AgrupacionesPoliticas", | ||||
|                         principalColumn: "Id", | ||||
|                         onDelete: ReferentialAction.Cascade); | ||||
|                 }); | ||||
|  | ||||
|             migrationBuilder.CreateIndex( | ||||
|                 name: "IX_BancasPrevias_AgrupacionPoliticaId", | ||||
|                 table: "BancasPrevias", | ||||
|                 column: "AgrupacionPoliticaId"); | ||||
|         } | ||||
|  | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Down(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.DropTable( | ||||
|                 name: "BancasPrevias"); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -1,38 +0,0 @@ | ||||
| using Microsoft.EntityFrameworkCore.Migrations; | ||||
|  | ||||
| #nullable disable | ||||
|  | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     /// <inheritdoc /> | ||||
|     public partial class AddOrdenNacionalToAgrupaciones : Migration | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Up(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.AddColumn<int>( | ||||
|                 name: "OrdenDiputadosNacionales", | ||||
|                 table: "AgrupacionesPoliticas", | ||||
|                 type: "int", | ||||
|                 nullable: true); | ||||
|  | ||||
|             migrationBuilder.AddColumn<int>( | ||||
|                 name: "OrdenSenadoresNacionales", | ||||
|                 table: "AgrupacionesPoliticas", | ||||
|                 type: "int", | ||||
|                 nullable: true); | ||||
|         } | ||||
|  | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Down(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.DropColumn( | ||||
|                 name: "OrdenDiputadosNacionales", | ||||
|                 table: "AgrupacionesPoliticas"); | ||||
|  | ||||
|             migrationBuilder.DropColumn( | ||||
|                 name: "OrdenSenadoresNacionales", | ||||
|                 table: "AgrupacionesPoliticas"); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     [DbContext(typeof(EleccionesDbContext))] | ||||
|     [Migration("20250924000007_AddOrdenNacionalToAgrupaciones")] | ||||
|     partial class AddOrdenNacionalToAgrupaciones | ||||
|     [Migration("20250929124756_LegislativasNacionales2025")] | ||||
|     partial class LegislativasNacionales2025 | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void BuildTargetModel(ModelBuilder modelBuilder) | ||||
| @@ -29,11 +29,8 @@ namespace Elecciones.Database.Migrations | ||||
|             modelBuilder.Entity("Eleccion", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
|                         .ValueGeneratedOnAdd() | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); | ||||
| 
 | ||||
|                     b.Property<string>("DistritoId") | ||||
|                         .IsRequired() | ||||
|                         .HasColumnType("nvarchar(max)"); | ||||
| @@ -642,12 +639,20 @@ namespace Elecciones.Database.Migrations | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("AmbitoGeograficoId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("CategoriaId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.Navigation("AmbitoGeografico"); | ||||
| 
 | ||||
|                     b.Navigation("CategoriaElectoral"); | ||||
|                 }); | ||||
| 
 | ||||
| @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     /// <inheritdoc /> | ||||
|     public partial class AddEleccionEntities : Migration | ||||
|     public partial class LegislativasNacionales2025 : Migration | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Up(MigrationBuilder migrationBuilder) | ||||
| @@ -81,12 +81,45 @@ namespace Elecciones.Database.Migrations | ||||
|                 nullable: false, | ||||
|                 defaultValue: 0); | ||||
| 
 | ||||
|             migrationBuilder.AddColumn<int>( | ||||
|                 name: "OrdenDiputadosNacionales", | ||||
|                 table: "AgrupacionesPoliticas", | ||||
|                 type: "int", | ||||
|                 nullable: true); | ||||
| 
 | ||||
|             migrationBuilder.AddColumn<int>( | ||||
|                 name: "OrdenSenadoresNacionales", | ||||
|                 table: "AgrupacionesPoliticas", | ||||
|                 type: "int", | ||||
|                 nullable: true); | ||||
| 
 | ||||
|             migrationBuilder.CreateTable( | ||||
|                 name: "Elecciones", | ||||
|                 name: "BancasPrevias", | ||||
|                 columns: table => new | ||||
|                 { | ||||
|                     Id = table.Column<int>(type: "int", nullable: false) | ||||
|                         .Annotation("SqlServer:Identity", "1, 1"), | ||||
|                     EleccionId = table.Column<int>(type: "int", nullable: false), | ||||
|                     Camara = table.Column<int>(type: "int", nullable: false), | ||||
|                     AgrupacionPoliticaId = table.Column<string>(type: "nvarchar(450)", nullable: false, collation: "Modern_Spanish_CI_AS"), | ||||
|                     Cantidad = table.Column<int>(type: "int", nullable: false) | ||||
|                 }, | ||||
|                 constraints: table => | ||||
|                 { | ||||
|                     table.PrimaryKey("PK_BancasPrevias", x => x.Id); | ||||
|                     table.ForeignKey( | ||||
|                         name: "FK_BancasPrevias_AgrupacionesPoliticas_AgrupacionPoliticaId", | ||||
|                         column: x => x.AgrupacionPoliticaId, | ||||
|                         principalTable: "AgrupacionesPoliticas", | ||||
|                         principalColumn: "Id", | ||||
|                         onDelete: ReferentialAction.Cascade); | ||||
|                 }); | ||||
| 
 | ||||
|             migrationBuilder.CreateTable( | ||||
|                 name: "Elecciones", | ||||
|                 columns: table => new | ||||
|                 { | ||||
|                     Id = table.Column<int>(type: "int", nullable: false), | ||||
|                     Nombre = table.Column<string>(type: "nvarchar(max)", nullable: false), | ||||
|                     Nivel = table.Column<string>(type: "nvarchar(max)", nullable: false), | ||||
|                     DistritoId = table.Column<string>(type: "nvarchar(max)", nullable: false), | ||||
| @@ -96,11 +129,31 @@ namespace Elecciones.Database.Migrations | ||||
|                 { | ||||
|                     table.PrimaryKey("PK_Elecciones", x => x.Id); | ||||
|                 }); | ||||
| 
 | ||||
|             migrationBuilder.CreateIndex( | ||||
|                 name: "IX_BancasPrevias_AgrupacionPoliticaId", | ||||
|                 table: "BancasPrevias", | ||||
|                 column: "AgrupacionPoliticaId"); | ||||
| 
 | ||||
|             migrationBuilder.AddForeignKey( | ||||
|                 name: "FK_EstadosRecuentosGenerales_AmbitosGeograficos_AmbitoGeograficoId", | ||||
|                 table: "EstadosRecuentosGenerales", | ||||
|                 column: "AmbitoGeograficoId", | ||||
|                 principalTable: "AmbitosGeograficos", | ||||
|                 principalColumn: "Id", | ||||
|                 onDelete: ReferentialAction.Cascade); | ||||
|         } | ||||
| 
 | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Down(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.DropForeignKey( | ||||
|                 name: "FK_EstadosRecuentosGenerales_AmbitosGeograficos_AmbitoGeograficoId", | ||||
|                 table: "EstadosRecuentosGenerales"); | ||||
| 
 | ||||
|             migrationBuilder.DropTable( | ||||
|                 name: "BancasPrevias"); | ||||
| 
 | ||||
|             migrationBuilder.DropTable( | ||||
|                 name: "Elecciones"); | ||||
| 
 | ||||
| @@ -143,6 +196,14 @@ namespace Elecciones.Database.Migrations | ||||
|             migrationBuilder.DropColumn( | ||||
|                 name: "EleccionId", | ||||
|                 table: "Bancadas"); | ||||
| 
 | ||||
|             migrationBuilder.DropColumn( | ||||
|                 name: "OrdenDiputadosNacionales", | ||||
|                 table: "AgrupacionesPoliticas"); | ||||
| 
 | ||||
|             migrationBuilder.DropColumn( | ||||
|                 name: "OrdenSenadoresNacionales", | ||||
|                 table: "AgrupacionesPoliticas"); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     [DbContext(typeof(EleccionesDbContext))] | ||||
|     [Migration("20250922213437_AddBancasPreviasTable")] | ||||
|     partial class AddBancasPreviasTable | ||||
|     [Migration("20250929153202_MakeCategoriaIdNullableInLogos")] | ||||
|     partial class MakeCategoriaIdNullableInLogos | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void BuildTargetModel(ModelBuilder modelBuilder) | ||||
| @@ -29,11 +29,8 @@ namespace Elecciones.Database.Migrations | ||||
|             modelBuilder.Entity("Eleccion", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
|                         .ValueGeneratedOnAdd() | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); | ||||
| 
 | ||||
|                     b.Property<string>("DistritoId") | ||||
|                         .IsRequired() | ||||
|                         .HasColumnType("nvarchar(max)"); | ||||
| @@ -102,9 +99,15 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.Property<int?>("OrdenDiputados") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenDiputadosNacionales") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenSenadores") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenSenadoresNacionales") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.HasKey("Id"); | ||||
| 
 | ||||
|                     b.ToTable("AgrupacionesPoliticas"); | ||||
| @@ -636,12 +639,20 @@ namespace Elecciones.Database.Migrations | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("AmbitoGeograficoId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("CategoriaId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.Navigation("AmbitoGeografico"); | ||||
| 
 | ||||
|                     b.Navigation("CategoriaElectoral"); | ||||
|                 }); | ||||
| 
 | ||||
| @@ -0,0 +1,22 @@ | ||||
| using Microsoft.EntityFrameworkCore.Migrations; | ||||
|  | ||||
| #nullable disable | ||||
|  | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     /// <inheritdoc /> | ||||
|     public partial class MakeCategoriaIdNullableInLogos : Migration | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Up(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|  | ||||
|         } | ||||
|  | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Down(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|  | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -12,8 +12,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion; | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     [DbContext(typeof(EleccionesDbContext))] | ||||
|     [Migration("20250911152547_AddEleccionEntities")] | ||||
|     partial class AddEleccionEntities | ||||
|     [Migration("20250929163650_FixLogoCategoriaNullability")] | ||||
|     partial class FixLogoCategoriaNullability | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void BuildTargetModel(ModelBuilder modelBuilder) | ||||
| @@ -29,11 +29,8 @@ namespace Elecciones.Database.Migrations | ||||
|             modelBuilder.Entity("Eleccion", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
|                         .ValueGeneratedOnAdd() | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); | ||||
| 
 | ||||
|                     b.Property<string>("DistritoId") | ||||
|                         .IsRequired() | ||||
|                         .HasColumnType("nvarchar(max)"); | ||||
| @@ -102,9 +99,15 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.Property<int?>("OrdenDiputados") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenDiputadosNacionales") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenSenadores") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int?>("OrdenSenadoresNacionales") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.HasKey("Id"); | ||||
| 
 | ||||
|                     b.ToTable("AgrupacionesPoliticas"); | ||||
| @@ -151,6 +154,35 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.ToTable("AmbitosGeograficos"); | ||||
|                 }); | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.BancaPrevia", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
|                         .ValueGeneratedOnAdd() | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); | ||||
| 
 | ||||
|                     b.Property<string>("AgrupacionPoliticaId") | ||||
|                         .IsRequired() | ||||
|                         .HasColumnType("nvarchar(450)") | ||||
|                         .UseCollation("Modern_Spanish_CI_AS"); | ||||
| 
 | ||||
|                     b.Property<int>("Camara") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int>("Cantidad") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int>("EleccionId") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.HasKey("Id"); | ||||
| 
 | ||||
|                     b.HasIndex("AgrupacionPoliticaId"); | ||||
| 
 | ||||
|                     b.ToTable("BancasPrevias"); | ||||
|                 }); | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.Bancada", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
| @@ -369,7 +401,7 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.Property<int>("CategoriaId") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<int>("EleccionId") | ||||
|                     b.Property<int?>("EleccionId") | ||||
|                         .HasColumnType("int"); | ||||
| 
 | ||||
|                     b.Property<string>("LogoUrl") | ||||
| @@ -549,6 +581,17 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.ToTable("Telegramas"); | ||||
|                 }); | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.BancaPrevia", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("AgrupacionPoliticaId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.Navigation("AgrupacionPolitica"); | ||||
|                 }); | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.Bancada", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica") | ||||
| @@ -596,12 +639,20 @@ namespace Elecciones.Database.Migrations | ||||
| 
 | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("AmbitoGeograficoId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("CategoriaId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
| 
 | ||||
|                     b.Navigation("AmbitoGeografico"); | ||||
| 
 | ||||
|                     b.Navigation("CategoriaElectoral"); | ||||
|                 }); | ||||
| 
 | ||||
| @@ -0,0 +1,36 @@ | ||||
| using Microsoft.EntityFrameworkCore.Migrations; | ||||
|  | ||||
| #nullable disable | ||||
|  | ||||
| namespace Elecciones.Database.Migrations | ||||
| { | ||||
|     /// <inheritdoc /> | ||||
|     public partial class FixLogoCategoriaNullability : Migration | ||||
|     { | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Up(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.AlterColumn<int>( | ||||
|                 name: "CategoriaId", | ||||
|                 table: "LogosAgrupacionesCategorias", | ||||
|                 type: "int", | ||||
|                 nullable: false, | ||||
|                 defaultValue: 0, | ||||
|                 oldClrType: typeof(int), | ||||
|                 oldType: "int", | ||||
|                 oldNullable: true); | ||||
|         } | ||||
|  | ||||
|         /// <inheritdoc /> | ||||
|         protected override void Down(MigrationBuilder migrationBuilder) | ||||
|         { | ||||
|             migrationBuilder.AlterColumn<int>( | ||||
|                 name: "CategoriaId", | ||||
|                 table: "LogosAgrupacionesCategorias", | ||||
|                 type: "int", | ||||
|                 nullable: true, | ||||
|                 oldClrType: typeof(int), | ||||
|                 oldType: "int"); | ||||
|         } | ||||
|     } | ||||
| } | ||||
| @@ -26,11 +26,8 @@ namespace Elecciones.Database.Migrations | ||||
|             modelBuilder.Entity("Eleccion", b => | ||||
|                 { | ||||
|                     b.Property<int>("Id") | ||||
|                         .ValueGeneratedOnAdd() | ||||
|                         .HasColumnType("int"); | ||||
|  | ||||
|                     SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id")); | ||||
|  | ||||
|                     b.Property<string>("DistritoId") | ||||
|                         .IsRequired() | ||||
|                         .HasColumnType("nvarchar(max)"); | ||||
| @@ -401,7 +398,7 @@ namespace Elecciones.Database.Migrations | ||||
|                     b.Property<int>("CategoriaId") | ||||
|                         .HasColumnType("int"); | ||||
|  | ||||
|                     b.Property<int>("EleccionId") | ||||
|                     b.Property<int?>("EleccionId") | ||||
|                         .HasColumnType("int"); | ||||
|  | ||||
|                     b.Property<string>("LogoUrl") | ||||
| @@ -639,12 +636,20 @@ namespace Elecciones.Database.Migrations | ||||
|  | ||||
|             modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b => | ||||
|                 { | ||||
|                     b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("AmbitoGeograficoId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
|  | ||||
|                     b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral") | ||||
|                         .WithMany() | ||||
|                         .HasForeignKey("CategoriaId") | ||||
|                         .OnDelete(DeleteBehavior.Cascade) | ||||
|                         .IsRequired(); | ||||
|  | ||||
|                     b.Navigation("AmbitoGeografico"); | ||||
|  | ||||
|                     b.Navigation("CategoriaElectoral"); | ||||
|                 }); | ||||
|  | ||||
|   | ||||
| @@ -13,7 +13,7 @@ using System.Reflection; | ||||
| [assembly: System.Reflection.AssemblyCompanyAttribute("Elecciones.Database")] | ||||
| [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] | ||||
| [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+67634ae947197595f6f644f3a80a982dd3573dfb")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+3b0eee25e6441da1831442a90b6552cc8ef59d07")] | ||||
| [assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Database")] | ||||
| [assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Database")] | ||||
| [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] | ||||
|   | ||||
| @@ -13,7 +13,7 @@ using System.Reflection; | ||||
| [assembly: System.Reflection.AssemblyCompanyAttribute("Elecciones.Infrastructure")] | ||||
| [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] | ||||
| [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+67634ae947197595f6f644f3a80a982dd3573dfb")] | ||||
| [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+3b0eee25e6441da1831442a90b6552cc8ef59d07")] | ||||
| [assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Infrastructure")] | ||||
| [assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Infrastructure")] | ||||
| [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] | ||||
|   | ||||
		Reference in New Issue
	
	Block a user