Fix Overrides Candidatos
This commit is contained in:
		| @@ -1,10 +1,11 @@ | ||||
| // src/components/CandidatoOverridesManager.tsx | ||||
|  | ||||
| import { useState, useMemo, useEffect } from 'react'; | ||||
| import { useQuery, useQueryClient } from '@tanstack/react-query'; | ||||
| import Select from 'react-select'; | ||||
| import { getMunicipiosForAdmin, getAgrupaciones, getCandidatos, updateCandidatos } from '../services/apiService'; | ||||
| import type { MunicipioSimple, AgrupacionPolitica, CandidatoOverride } from '../types'; | ||||
|  | ||||
| // Las categorías son las mismas que para los logos | ||||
| const CATEGORIAS_OPTIONS = [ | ||||
|     { value: 5, label: 'Senadores' }, | ||||
|     { value: 6, label: 'Diputados' }, | ||||
| @@ -15,23 +16,31 @@ export const CandidatoOverridesManager = () => { | ||||
|     const queryClient = useQueryClient(); | ||||
|     const { data: municipios = [] } = useQuery<MunicipioSimple[]>({ queryKey: ['municipiosForAdmin'], queryFn: getMunicipiosForAdmin }); | ||||
|     const { data: agrupaciones = [] } = useQuery<AgrupacionPolitica[]>({ queryKey: ['agrupaciones'], queryFn: getAgrupaciones }); | ||||
|     // --- Usar la query para candidatos --- | ||||
|     const { data: candidatos = [] } = useQuery<CandidatoOverride[]>({ queryKey: ['candidatos'], queryFn: getCandidatos }); | ||||
|  | ||||
|     const [selectedCategoria, setSelectedCategoria] = useState<{ value: number; label: string } | null>(null); | ||||
|     const [selectedMunicipio, setSelectedMunicipio] = useState<{ value: string; label: string } | null>(null); | ||||
|     const [selectedAgrupacion, setSelectedAgrupacion] = useState<{ value: string; label: string } | null>(null); | ||||
|     // --- El estado es para el nombre del candidato --- | ||||
|     const [nombreCandidato, setNombreCandidato] = useState(''); | ||||
|  | ||||
|     const municipioOptions = useMemo(() => municipios.map(m => ({ value: m.id, label: m.nombre })), [municipios]); | ||||
|     const municipioOptions = useMemo(() =>  | ||||
|         // Añadimos la opción "General" que representará un ámbito nulo | ||||
|         [{ value: 'general', label: 'General (Todos los Municipios)' }, ...municipios.map(m => ({ value: m.id, label: m.nombre }))] | ||||
|     , [municipios]); | ||||
|      | ||||
|     const agrupacionOptions = useMemo(() => agrupaciones.map(a => ({ value: a.id, label: a.nombre })), [agrupaciones]); | ||||
|  | ||||
|     // --- Lógica para encontrar el nombre del candidato actual --- | ||||
|     const currentCandidato = useMemo(() => { | ||||
|         if (!selectedMunicipio || !selectedAgrupacion || !selectedCategoria) return ''; | ||||
|         if (!selectedAgrupacion || !selectedCategoria) return ''; | ||||
|          | ||||
|         // Determina si estamos buscando un override general (null) o específico (ID numérico) | ||||
|         const ambitoIdBuscado = selectedMunicipio?.value === 'general' ? null : (selectedMunicipio ? parseInt(selectedMunicipio.value) : undefined); | ||||
|  | ||||
|         // Si no se ha seleccionado un municipio, no buscamos nada | ||||
|         if (ambitoIdBuscado === undefined) return ''; | ||||
|  | ||||
|         return candidatos.find(c =>  | ||||
|             c.ambitoGeograficoId === parseInt(selectedMunicipio.value) &&  | ||||
|             c.ambitoGeograficoId === ambitoIdBuscado &&  | ||||
|             c.agrupacionPoliticaId === selectedAgrupacion.value && | ||||
|             c.categoriaId === selectedCategoria.value | ||||
|         )?.nombreCandidato || ''; | ||||
| @@ -42,34 +51,40 @@ export const CandidatoOverridesManager = () => { | ||||
|     const handleSave = async () => { | ||||
|         if (!selectedMunicipio || !selectedAgrupacion || !selectedCategoria) return; | ||||
|  | ||||
|         // --- Construir el objeto CandidatoOverride --- | ||||
|         const ambitoIdParaEnviar = selectedMunicipio.value === 'general'  | ||||
|             ? null  | ||||
|             : parseInt(selectedMunicipio.value); | ||||
|  | ||||
|         const newCandidatoEntry: CandidatoOverride = { | ||||
|             id: 0, // El backend no necesita el ID para un upsert | ||||
|             id: 0, // El backend no lo necesita para el upsert | ||||
|             agrupacionPoliticaId: selectedAgrupacion.value, | ||||
|             categoriaId: selectedCategoria.value, | ||||
|             ambitoGeograficoId: parseInt(selectedMunicipio.value), | ||||
|             nombreCandidato: nombreCandidato | ||||
|             ambitoGeograficoId: ambitoIdParaEnviar, | ||||
|             nombreCandidato: nombreCandidato || null | ||||
|         }; | ||||
|  | ||||
|         try { | ||||
|             await updateCandidatos([newCandidatoEntry]); | ||||
|             queryClient.invalidateQueries({ queryKey: ['candidatos'] }); | ||||
|             alert('Override de candidato guardado.'); | ||||
|         } catch { alert('Error al guardar.'); } | ||||
|         } catch (error) { | ||||
|             console.error(error); | ||||
|             alert('Error al guardar el override del candidato.'); | ||||
|         } | ||||
|     }; | ||||
|      | ||||
|     return ( | ||||
|         <div className="admin-module"> | ||||
|             <h3>Overrides de Nombres de Candidatos</h3> | ||||
|             <p>Configure un nombre de candidato específico para un partido en un municipio y categoría determinados.</p> | ||||
|             <div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-end' }}> | ||||
|             <p>Configure un nombre de candidato específico para un partido, categoría y municipio (o general).</p> | ||||
|             <div style={{ display: 'flex', gap: '1rem', alignItems: 'flex-end', flexWrap: 'wrap' }}> | ||||
|                 <div style={{ flex: 1 }}> | ||||
|                     <label>Categoría</label> | ||||
|                     <Select options={CATEGORIAS_OPTIONS} value={selectedCategoria} onChange={setSelectedCategoria} isClearable placeholder="Seleccione..."/> | ||||
|                 </div> | ||||
|                 <div style={{ flex: 1 }}> | ||||
|                     <label>Municipio</label> | ||||
|                     <Select options={municipioOptions} value={selectedMunicipio} onChange={setSelectedMunicipio} isClearable placeholder="Seleccione..."/> | ||||
|                     <label>Municipio (Opcional)</label> | ||||
|                     <Select options={municipioOptions} value={selectedMunicipio} onChange={setSelectedMunicipio} isClearable placeholder="General..."/> | ||||
|                 </div> | ||||
|                 <div style={{ flex: 1 }}> | ||||
|                     <label>Agrupación</label> | ||||
| @@ -77,9 +92,9 @@ export const CandidatoOverridesManager = () => { | ||||
|                 </div> | ||||
|                 <div style={{ flex: 2 }}> | ||||
|                     <label>Nombre del Candidato</label> | ||||
|                     <input type="text" value={nombreCandidato} onChange={e => setNombreCandidato(e.target.value)} style={{ width: '100%' }} disabled={!selectedMunicipio || !selectedAgrupacion || !selectedCategoria} /> | ||||
|                     <input type="text" value={nombreCandidato} onChange={e => setNombreCandidato(e.target.value)} style={{ width: '100%' }} disabled={!selectedAgrupacion || !selectedCategoria} /> | ||||
|                 </div> | ||||
|                 <button onClick={handleSave} disabled={!selectedMunicipio || !selectedAgrupacion || !selectedCategoria}>Guardar</button> | ||||
|                 <button onClick={handleSave} disabled={!selectedAgrupacion || !selectedCategoria}>Guardar</button> | ||||
|             </div> | ||||
|         </div> | ||||
|     ); | ||||
|   | ||||
		Reference in New Issue
	
	Block a user