Merge branch 'Legislativas-Nacionales-2025'

# Conflicts:
#	Elecciones-Web/src/Elecciones.Api/obj/Debug/net9.0/Elecciones.Api.AssemblyInfo.cs
#	Elecciones-Web/src/Elecciones.Core/obj/Debug/net9.0/Elecciones.Core.AssemblyInfo.cs
This commit is contained in:
2025-10-01 10:29:52 -03:00
161 changed files with 9990 additions and 1079 deletions

View File

@@ -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();
}
@@ -92,6 +87,36 @@ public class AdminController : ControllerBase
return Ok();
}
// --- ENDPOINTS PARA NACIONALES ---
[HttpPut("agrupaciones/orden-diputados-nacionales")]
public async Task<IActionResult> UpdateDiputadosNacionalesOrden([FromBody] List<string> idsAgrupacionesOrdenadas)
{
await _dbContext.AgrupacionesPoliticas.ExecuteUpdateAsync(s => s.SetProperty(a => a.OrdenDiputadosNacionales, (int?)null));
for (int i = 0; i < idsAgrupacionesOrdenadas.Count; i++)
{
var agrupacion = await _dbContext.AgrupacionesPoliticas.FindAsync(idsAgrupacionesOrdenadas[i]);
if (agrupacion != null) agrupacion.OrdenDiputadosNacionales = i + 1;
}
await _dbContext.SaveChangesAsync();
return Ok();
}
[HttpPut("agrupaciones/orden-senadores-nacionales")]
public async Task<IActionResult> UpdateSenadoresNacionalesOrden([FromBody] List<string> idsAgrupacionesOrdenadas)
{
await _dbContext.AgrupacionesPoliticas.ExecuteUpdateAsync(s => s.SetProperty(a => a.OrdenSenadoresNacionales, (int?)null));
for (int i = 0; i < idsAgrupacionesOrdenadas.Count; i++)
{
var agrupacion = await _dbContext.AgrupacionesPoliticas.FindAsync(idsAgrupacionesOrdenadas[i]);
if (agrupacion != null) agrupacion.OrdenSenadoresNacionales = i + 1;
}
await _dbContext.SaveChangesAsync();
return Ok();
}
// LEER todas las configuraciones
[HttpGet("configuracion")]
public async Task<IActionResult> GetConfiguracion()
@@ -125,14 +150,15 @@ public class AdminController : ControllerBase
// LEER: Obtener todas las bancadas para una cámara, con su partido y ocupante actual
[HttpGet("bancadas/{camara}")]
public async Task<IActionResult> GetBancadas(TipoCamara camara)
public async Task<IActionResult> GetBancadas(TipoCamara camara, [FromQuery] int eleccionId)
{
// 3. La lógica interna se mantiene igual, ya que filtra por ambos parámetros.
var bancadas = await _dbContext.Bancadas
.AsNoTracking()
.Include(b => b.AgrupacionPolitica)
.Include(b => b.Ocupante)
.Where(b => b.Camara == camara)
.OrderBy(b => b.Id) // Ordenar por ID para consistencia
.Where(b => b.EleccionId == eleccionId && b.Camara == camara)
.OrderBy(b => b.NumeroBanca)
.ToListAsync();
return Ok(bancadas);
@@ -181,10 +207,39 @@ public class AdminController : ControllerBase
return NoContent();
}
[HttpGet("logos")]
public async Task<IActionResult> GetLogos()
[HttpGet("catalogos/provincias")]
public async Task<IActionResult> GetProvinciasForAdmin()
{
return Ok(await _dbContext.LogosAgrupacionesCategorias.AsNoTracking().ToListAsync());
var provincias = await _dbContext.AmbitosGeograficos
.AsNoTracking()
.Where(a => a.NivelId == 10) // Nivel 10 = Provincia
.OrderBy(a => a.Nombre)
.Select(a => new { Id = a.Id.ToString(), Nombre = a.Nombre })
.ToListAsync();
return Ok(provincias);
}
// --- ENDPOINTS MODIFICADOS ---
[HttpGet("logos")]
public async Task<IActionResult> GetLogos([FromQuery] int eleccionId)
{
// Añadimos el filtro por EleccionId
return Ok(await _dbContext.LogosAgrupacionesCategorias
.AsNoTracking()
.Where(l => l.EleccionId == eleccionId)
.ToListAsync());
}
[HttpGet("candidatos")]
public async Task<IActionResult> GetCandidatos([FromQuery] int eleccionId)
{
// Añadimos el filtro por EleccionId
var candidatos = await _dbContext.CandidatosOverrides
.AsNoTracking()
.Where(c => c.EleccionId == eleccionId)
.ToListAsync();
return Ok(candidatos);
}
[HttpPut("logos")]
@@ -192,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();
@@ -239,18 +297,6 @@ public class AdminController : ControllerBase
return Ok(municipios);
}
/// <summary>
/// Obtiene todos los overrides de candidatos configurados.
/// </summary>
[HttpGet("candidatos")]
public async Task<IActionResult> GetCandidatos()
{
var candidatos = await _dbContext.CandidatosOverrides
.AsNoTracking()
.ToListAsync();
return Ok(candidatos);
}
/// <summary>
/// Guarda (actualiza o crea) una lista de overrides de candidatos.
/// </summary>
@@ -337,4 +383,40 @@ public class AdminController : ControllerBase
_logger.LogWarning("El nivel de logging ha sido cambiado a: {Level}", request.Level);
return Ok(new { message = $"Nivel de logging actualizado a '{request.Level}'." });
}
// LEER todas las bancas previas para una elección
[HttpGet("bancas-previas/{eleccionId}")]
public async Task<IActionResult> GetBancasPrevias(int eleccionId)
{
var bancas = await _dbContext.BancasPrevias
.AsNoTracking()
.Where(b => b.EleccionId == eleccionId)
.Include(b => b.AgrupacionPolitica)
.ToListAsync();
return Ok(bancas);
}
// GUARDAR (Upsert) una lista de bancas previas
[HttpPut("bancas-previas/{eleccionId}")]
public async Task<IActionResult> UpdateBancasPrevias(int eleccionId, [FromBody] List<BancaPrevia> bancas)
{
// Borramos los registros existentes para esta elección para simplificar la lógica
await _dbContext.BancasPrevias.Where(b => b.EleccionId == eleccionId).ExecuteDeleteAsync();
// Añadimos los nuevos registros que tienen al menos una banca
foreach (var banca in bancas.Where(b => b.Cantidad > 0))
{
_dbContext.BancasPrevias.Add(new BancaPrevia
{
EleccionId = eleccionId,
Camara = banca.Camara,
AgrupacionPoliticaId = banca.AgrupacionPoliticaId,
Cantidad = banca.Cantidad
});
}
await _dbContext.SaveChangesAsync();
_logger.LogInformation("Se actualizaron las bancas previas para la EleccionId: {EleccionId}", eleccionId);
return NoContent();
}
}

View File

@@ -1,4 +1,5 @@
// src/Elecciones.Api/Controllers/ResultadosController.cs
using Elecciones.Core.DTOs;
using Elecciones.Core.DTOs.ApiResponses;
using Elecciones.Database;
using Elecciones.Database.Entities;
@@ -8,7 +9,7 @@ using Microsoft.EntityFrameworkCore;
namespace Elecciones.Api.Controllers;
[ApiController]
[Route("api/[controller]")]
[Route("api/elecciones/{eleccionId}")]
public class ResultadosController : ControllerBase
{
private readonly EleccionesDbContext _dbContext;
@@ -46,7 +47,7 @@ public class ResultadosController : ControllerBase
}
[HttpGet("partido/{municipioId}")]
public async Task<IActionResult> GetResultadosPorPartido(string municipioId, [FromQuery] int categoriaId)
public async Task<IActionResult> GetResultadosPorPartido([FromRoute] int eleccionId, string municipioId, [FromQuery] int categoriaId)
{
var ambito = await _dbContext.AmbitosGeograficos.AsNoTracking()
.FirstOrDefaultAsync(a => a.SeccionId == municipioId && a.NivelId == 30);
@@ -57,7 +58,7 @@ public class ResultadosController : ControllerBase
}
var estadoRecuento = await _dbContext.EstadosRecuentos.AsNoTracking()
.FirstOrDefaultAsync(e => e.AmbitoGeograficoId == ambito.Id && e.CategoriaId == categoriaId);
.FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.AmbitoGeograficoId == ambito.Id && e.CategoriaId == categoriaId);
var agrupacionIds = await _dbContext.ResultadosVotos
.Where(rv => rv.AmbitoGeograficoId == ambito.Id && rv.CategoriaId == categoriaId)
@@ -71,7 +72,7 @@ public class ResultadosController : ControllerBase
var resultadosVotos = await _dbContext.ResultadosVotos.AsNoTracking()
.Include(rv => rv.AgrupacionPolitica)
.Where(rv => rv.AmbitoGeograficoId == ambito.Id && rv.CategoriaId == categoriaId)
.Where(rv => rv.EleccionId == eleccionId && rv.AmbitoGeograficoId == ambito.Id && rv.CategoriaId == categoriaId)
.ToListAsync();
var candidatosRelevantes = await _dbContext.CandidatosOverrides.AsNoTracking()
@@ -119,7 +120,7 @@ public class ResultadosController : ControllerBase
}
[HttpGet("provincia/{distritoId}")]
public async Task<IActionResult> GetResultadosProvinciales(string distritoId)
public async Task<IActionResult> GetResultadosProvinciales([FromRoute] int eleccionId, string distritoId)
{
var provincia = await _dbContext.AmbitosGeograficos.AsNoTracking()
.FirstOrDefaultAsync(a => a.DistritoId == distritoId && a.NivelId == 10);
@@ -131,19 +132,21 @@ public class ResultadosController : ControllerBase
var estadosPorCategoria = await _dbContext.EstadosRecuentosGenerales.AsNoTracking()
.Include(e => e.CategoriaElectoral)
.Where(e => e.AmbitoGeograficoId == provincia.Id)
.Where(e => e.EleccionId == eleccionId && e.AmbitoGeograficoId == provincia.Id)
.ToDictionaryAsync(e => e.CategoriaId);
var resultadosPorMunicipio = await _dbContext.ResultadosVotos
.AsNoTracking()
.Include(r => r.AgrupacionPolitica)
.Where(r => r.AmbitoGeografico.NivelId == 30) // Nivel 30 = Municipio
.Where(r => r.EleccionId == eleccionId && r.AmbitoGeografico.NivelId == 30) // Nivel 30 = Municipio
.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 ---
// --- LÓGICA DE AGRUPACIÓN Y CÁLCULO ---
var resultadosAgrupados = resultadosPorMunicipio
.GroupBy(r => r.CategoriaId)
.Select(g => new
@@ -194,8 +197,8 @@ public class ResultadosController : ControllerBase
}
[HttpGet("bancas-por-seccion/{seccionId}/{camara}")] // <-- CAMBIO 1: Modificar la ruta
public async Task<IActionResult> GetBancasPorSeccion(string seccionId, string camara) // <-- CAMBIO 2: Añadir el nuevo parámetro
[HttpGet("bancas-por-seccion/{seccionId}/{camara}")]
public async Task<IActionResult> GetBancasPorSeccion([FromRoute] int eleccionId, string seccionId, string camara)
{
// Convertimos el string de la cámara a un enum o un valor numérico para la base de datos
// 0 = Diputados, 1 = Senadores. Esto debe coincidir con cómo lo guardas en la DB.
@@ -228,7 +231,7 @@ public class ResultadosController : ControllerBase
var proyecciones = await _dbContext.ProyeccionesBancas
.AsNoTracking()
.Include(p => p.AgrupacionPolitica)
.Where(p => p.AmbitoGeograficoId == seccion.Id && p.CategoriaId == CategoriaId) // <-- AÑADIDO EL FILTRO
.Where(p => p.EleccionId == eleccionId && p.AmbitoGeograficoId == seccion.Id && p.CategoriaId == CategoriaId)
.Select(p => new
{
AgrupacionId = p.AgrupacionPolitica.Id, // Añadir para el 'key' en React
@@ -347,7 +350,7 @@ public class ResultadosController : ControllerBase
}
[HttpGet("composicion-congreso")]
public async Task<IActionResult> GetComposicionCongreso()
public async Task<IActionResult> GetComposicionCongreso([FromRoute] int eleccionId)
{
var config = await _dbContext.Configuraciones
.AsNoTracking()
@@ -360,23 +363,24 @@ public class ResultadosController : ControllerBase
if (usarDatosOficiales)
{
// Si el interruptor está en 'true', llama a este método
return await GetComposicionDesdeBancadasOficiales(config);
return await GetComposicionDesdeBancadasOficiales(config, eleccionId);
}
else
{
// Si está en 'false' o no existe, llama a este otro
return await GetComposicionDesdeProyecciones(config);
return await GetComposicionDesdeProyecciones(config, eleccionId);
}
}
// En ResultadosController.cs
private async Task<IActionResult> GetComposicionDesdeBancadasOficiales(Dictionary<string, string> config)
private async Task<IActionResult> GetComposicionDesdeBancadasOficiales(Dictionary<string, string> config, int eleccionId)
{
config.TryGetValue("MostrarOcupantes", out var mostrarOcupantesValue);
bool mostrarOcupantes = mostrarOcupantesValue == "true";
IQueryable<Bancada> bancadasQuery = _dbContext.Bancadas.AsNoTracking()
.Include(b => b.AgrupacionPolitica);
.Where(b => b.EleccionId == eleccionId)
.Include(b => b.AgrupacionPolitica);
if (mostrarOcupantes)
{
bancadasQuery = bancadasQuery.Include(b => b.Ocupante);
@@ -459,9 +463,8 @@ public class ResultadosController : ControllerBase
return Ok(new { Diputados = diputados, Senadores = senadores });
}
private async Task<IActionResult> GetComposicionDesdeProyecciones(Dictionary<string, string> config)
private async Task<IActionResult> GetComposicionDesdeProyecciones(Dictionary<string, string> config, int eleccionId)
{
// --- INICIO DE LA CORRECCIÓN ---
// 1. Obtenemos el ID del ámbito provincial para usarlo en el filtro.
var provincia = await _dbContext.AmbitosGeograficos.AsNoTracking()
.FirstOrDefaultAsync(a => a.NivelId == 10);
@@ -476,18 +479,15 @@ public class ResultadosController : ControllerBase
Senadores = new { Partidos = new List<object>() }
});
}
// --- FIN DE LA CORRECCIÓN ---
var bancasPorAgrupacion = await _dbContext.ProyeccionesBancas
.AsNoTracking()
// --- CAMBIO CLAVE: Añadimos el filtro por AmbitoGeograficoId ---
.Where(p => p.AmbitoGeograficoId == provincia.Id)
.Where(p => p.EleccionId == eleccionId && p.AmbitoGeograficoId == provincia.Id)
.GroupBy(p => new { p.AgrupacionPoliticaId, p.CategoriaId })
.Select(g => new
{
AgrupacionId = g.Key.AgrupacionPoliticaId,
CategoriaId = g.Key.CategoriaId,
// Ahora la suma es correcta porque solo considera los registros a nivel provincial
BancasTotales = g.Sum(p => p.NroBancas)
})
.ToListAsync();
@@ -551,7 +551,7 @@ public class ResultadosController : ControllerBase
}
[HttpGet("bancadas-detalle")]
public async Task<IActionResult> GetBancadasConOcupantes()
public async Task<IActionResult> GetBancadasConOcupantes([FromRoute] int eleccionId)
{
var config = await _dbContext.Configuraciones.AsNoTracking().ToDictionaryAsync(c => c.Clave, c => c.Valor);
@@ -565,6 +565,7 @@ public class ResultadosController : ControllerBase
// Si el modo oficial SÍ está activo, devolvemos los detalles.
var bancadasConOcupantes = await _dbContext.Bancadas
.AsNoTracking()
.Where(b => b.EleccionId == eleccionId)
.Include(b => b.Ocupante)
.Select(b => new
{
@@ -614,16 +615,12 @@ public class ResultadosController : ControllerBase
return Ok(new { UltimaActualizacion = DateTime.UtcNow, Resultados = new List<object>() });
}
// --- INICIO DE LA CORRECCIÓN DE LOGOS ---
// 1. Buscamos logos que sean para esta categoría Y que sean generales (ámbito null).
var logosGenerales = await _dbContext.LogosAgrupacionesCategorias
.AsNoTracking()
.Where(l => l.CategoriaId == categoriaId && l.AmbitoGeograficoId == null)
.ToDictionaryAsync(l => l.AgrupacionPoliticaId);
// --- FIN DE LA CORRECCIÓN DE LOGOS ---
var resultadosMunicipales = await _dbContext.ResultadosVotos
.AsNoTracking()
.Include(r => r.AgrupacionPolitica)
@@ -683,7 +680,6 @@ public class ResultadosController : ControllerBase
.GroupBy(r => r.AmbitoGeografico.SeccionProvincialId)
.Select(g =>
{
// --- INICIO DE LA CORRECCIÓN ---
// Para cada sección, encontramos al partido con más votos.
var ganador = g
// CAMBIO CLAVE: Agrupamos por el ID de la agrupación, no por el objeto.
@@ -696,7 +692,6 @@ public class ResultadosController : ControllerBase
})
.OrderByDescending(x => x.TotalVotos)
.FirstOrDefault();
// --- FIN DE LA CORRECCIÓN ---
// Buscamos el nombre de la sección
var seccionInfo = _dbContext.AmbitosGeograficos
@@ -1012,4 +1007,614 @@ public class ResultadosController : ControllerBase
Resultados = resultadosPorMunicipio
});
}
[HttpGet("panel/{ambitoId?}")]
public async Task<IActionResult> GetPanelElectoral(int eleccionId, string? ambitoId, [FromQuery] int categoriaId)
{
if (string.IsNullOrEmpty(ambitoId))
{
// CASO 1: No hay ID -> Vista Nacional
return await GetPanelNacional(eleccionId, categoriaId);
}
// CASO 2: El ID es un número (y no un string corto como "02") -> Vista Municipal
// La condición clave es que los IDs de distrito son cortos. Los IDs de BD son más largos.
// O simplemente, un ID de distrito nunca será un ID de municipio.
if (int.TryParse(ambitoId, out int idNumerico) && ambitoId.Length > 2)
{
return await GetPanelMunicipal(eleccionId, idNumerico, categoriaId);
}
else
{
// CASO 3: El ID es un string corto como "02" o "06" -> Vista Provincial
return await GetPanelProvincial(eleccionId, ambitoId, categoriaId);
}
}
private async Task<IActionResult> GetPanelMunicipal(int eleccionId, int ambitoId, int categoriaId)
{
// 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}.");
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 &&
r.CategoriaId == categoriaId &&
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())
{
return Ok(new PanelElectoralDto
{
AmbitoNombre = municipio.Nombre,
MapaData = new List<ResultadoMapaDto>(),
ResultadosPanel = new List<AgrupacionResultadoDto>(),
EstadoRecuento = new EstadoRecuentoDto()
});
}
var totalVotosMunicipio = (decimal)resultadosCrudos.Sum(r => r.CantidadVotos);
var resultadosPanel = resultadosCrudos
.Select(g =>
{
// 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();
var estadoRecuento = await _dbContext.EstadosRecuentos
.AsNoTracking()
.FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.AmbitoGeograficoId == ambitoId && e.CategoriaId == categoriaId);
var respuesta = new PanelElectoralDto
{
AmbitoNombre = municipio.Nombre,
MapaData = new List<ResultadoMapaDto>(),
ResultadosPanel = resultadosPanel,
EstadoRecuento = new EstadoRecuentoDto
{
ParticipacionPorcentaje = estadoRecuento?.ParticipacionPorcentaje ?? 0,
MesasTotalizadasPorcentaje = estadoRecuento?.MesasTotalizadasPorcentaje ?? 0
}
};
return Ok(respuesta);
}
// Este método se ejecutará cuando la URL sea, por ejemplo, /api/elecciones/2/panel/02?categoriaId=2
private async Task<IActionResult> GetPanelProvincial(int eleccionId, string distritoId, 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}.");
// --- 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)
.Select(g => new { Agrupacion = g.Key, TotalVotos = g.Sum(r => r.CantidadVotos) })
.ToListAsync();
var totalVotosProvincia = (decimal)resultadosAgregados.Sum(r => r.TotalVotos);
var resultadosPanel = resultadosAgregados
.Select(g =>
{
// 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();
var estadoRecuento = await _dbContext.EstadosRecuentosGenerales.AsNoTracking()
.FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.AmbitoGeograficoId == provincia.Id && e.CategoriaId == categoriaId);
var respuesta = new PanelElectoralDto
{
AmbitoNombre = provincia.Nombre,
MapaData = new List<ResultadoMapaDto>(), // Se carga por separado
ResultadosPanel = resultadosPanel,
EstadoRecuento = new EstadoRecuentoDto
{
ParticipacionPorcentaje = estadoRecuento?.ParticipacionPorcentaje ?? 0,
MesasTotalizadasPorcentaje = estadoRecuento?.MesasTotalizadasPorcentaje ?? 0
}
};
return Ok(respuesta);
}
private async Task<IActionResult> GetPanelNacional(int eleccionId, int 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 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) })
.ToListAsync();
var totalVotosNacional = (decimal)resultadosAgregados.Sum(r => r.TotalVotos);
var resultadosPanel = resultadosAgregados
.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,
NombreCandidato = null,
LogoUrl = logoMatch?.LogoUrl
};
})
.OrderByDescending(r => r.Votos)
.ToList();
var estadoRecuento = await _dbContext.EstadosRecuentosGenerales.AsNoTracking()
.FirstOrDefaultAsync(e => e.EleccionId == eleccionId && e.CategoriaId == categoriaId && e.AmbitoGeografico.NivelId == 0);
var respuesta = new PanelElectoralDto
{
AmbitoNombre = "Argentina",
MapaData = new List<ResultadoMapaDto>(),
ResultadosPanel = resultadosPanel,
EstadoRecuento = new EstadoRecuentoDto
{
ParticipacionPorcentaje = estadoRecuento?.ParticipacionPorcentaje ?? 0,
MesasTotalizadasPorcentaje = estadoRecuento?.MesasTotalizadasPorcentaje ?? 0
}
};
return Ok(respuesta);
}
[HttpGet("mapa-resultados")]
public async Task<IActionResult> GetResultadosMapaPorMunicipio(
[FromRoute] int eleccionId,
[FromQuery] int categoriaId,
[FromQuery] string? distritoId = null)
{
if (string.IsNullOrEmpty(distritoId))
{
// PASO 1: Agrupar y sumar los votos por provincia y partido directamente en la BD.
// Esto crea una lista con los totales, que es mucho más pequeña que los datos crudos.
var votosAgregadosPorProvincia = await _dbContext.ResultadosVotos
.AsNoTracking()
.Where(r => r.EleccionId == eleccionId
&& r.CategoriaId == categoriaId
&& r.AmbitoGeografico.NivelId == 30
&& r.AmbitoGeografico.DistritoId != null)
.GroupBy(r => new { r.AmbitoGeografico.DistritoId, r.AgrupacionPoliticaId })
.Select(g => new
{
DistritoId = g.Key.DistritoId!, // Sabemos que no es nulo por el .Where()
AgrupacionPoliticaId = g.Key.AgrupacionPoliticaId,
TotalVotos = g.Sum(r => r.CantidadVotos)
})
.ToListAsync();
// PASO 2: Encontrar el ganador para cada provincia en la memoria de la aplicación.
// Esto es muy rápido porque se hace sobre la lista ya agregada.
var ganadoresPorProvincia = votosAgregadosPorProvincia
.GroupBy(r => r.DistritoId)
.Select(g => g.OrderByDescending(x => x.TotalVotos).First())
.ToList();
// PASO 3: Obtener los datos adicionales (nombres, colores) para construir la respuesta final.
var agrupacionesInfo = await _dbContext.AgrupacionesPoliticas.AsNoTracking().ToDictionaryAsync(a => a.Id);
var provinciasInfo = await _dbContext.AmbitosGeograficos.AsNoTracking().Where(a => a.NivelId == 10).ToListAsync();
var mapaDataNacional = ganadoresPorProvincia.Select(g => new ResultadoMapaDto
{
AmbitoId = g.DistritoId,
AmbitoNombre = provinciasInfo.FirstOrDefault(p => p.DistritoId == g.DistritoId)?.Nombre ?? "Desconocido",
AgrupacionGanadoraId = g.AgrupacionPoliticaId,
ColorGanador = agrupacionesInfo.GetValueOrDefault(g.AgrupacionPoliticaId)?.Color ?? "#808080"
}).ToList();
return Ok(mapaDataNacional);
}
else
{
// --- VISTA PROVINCIAL ---
var votosAgregadosPorMunicipio = await _dbContext.ResultadosVotos
.AsNoTracking()
.Where(r => r.EleccionId == eleccionId
&& r.CategoriaId == categoriaId
&& r.AmbitoGeografico.DistritoId == distritoId
&& r.AmbitoGeografico.NivelId == 30)
.GroupBy(r => new { r.AmbitoGeograficoId, r.AgrupacionPoliticaId })
.Select(g => new
{
g.Key.AmbitoGeograficoId,
g.Key.AgrupacionPoliticaId,
TotalVotos = g.Sum(r => r.CantidadVotos)
})
.ToListAsync();
var ganadoresPorMunicipio = votosAgregadosPorMunicipio
.GroupBy(r => r.AmbitoGeograficoId)
.Select(g => g.OrderByDescending(x => x.TotalVotos).First())
.ToList();
var idsMunicipios = ganadoresPorMunicipio.Select(g => g.AmbitoGeograficoId).ToList();
var idsAgrupaciones = ganadoresPorMunicipio.Select(g => g.AgrupacionPoliticaId).ToList();
var municipiosInfo = await _dbContext.AmbitosGeograficos.AsNoTracking()
.Where(a => idsMunicipios.Contains(a.Id)).ToDictionaryAsync(a => a.Id);
var agrupacionesInfo = await _dbContext.AgrupacionesPoliticas.AsNoTracking()
.Where(a => idsAgrupaciones.Contains(a.Id)).ToDictionaryAsync(a => a.Id);
var mapaDataProvincial = ganadoresPorMunicipio.Select(g => new ResultadoMapaDto
{
AmbitoId = g.AmbitoGeograficoId.ToString(),
AmbitoNombre = municipiosInfo.GetValueOrDefault(g.AmbitoGeograficoId)?.Nombre ?? "Desconocido",
AgrupacionGanadoraId = g.AgrupacionPoliticaId,
ColorGanador = agrupacionesInfo.GetValueOrDefault(g.AgrupacionPoliticaId)?.Color ?? "#808080"
}).ToList();
return Ok(mapaDataProvincial);
}
}
[HttpGet("composicion-nacional")]
public async Task<IActionResult> GetComposicionNacional([FromRoute] int eleccionId)
{
// 1. Obtener todas las configuraciones relevantes en una sola consulta.
var config = await _dbContext.Configuraciones.AsNoTracking().ToDictionaryAsync(c => c.Clave, c => c.Valor);
// 2. Obtener todas las agrupaciones políticas en una sola consulta.
var todasAgrupaciones = await _dbContext.AgrupacionesPoliticas.AsNoTracking().ToDictionaryAsync(a => a.Id);
// 3. Obtener las bancas PREVIAS (las que no están en juego).
var bancasPrevias = await _dbContext.BancasPrevias
.AsNoTracking()
.Where(b => b.EleccionId == eleccionId)
.ToListAsync();
// 4. Obtener las bancas EN JUEGO (proyectadas por provincia).
var proyecciones = await _dbContext.ProyeccionesBancas
.AsNoTracking()
.Where(p => p.EleccionId == eleccionId && p.AmbitoGeografico.NivelId == 10) // Nivel 10 = Ámbito Provincial
.ToListAsync();
//Calculamos la fecha de la última proyección.
// Si no hay proyecciones aún, usamos la fecha y hora actual como un fallback seguro.
var ultimaActualizacion = proyecciones.Any()
? proyecciones.Max(p => p.FechaTotalizacion)
: DateTime.UtcNow;
// 5. Combinar los datos para obtener la composición final de cada partido.
var composicionFinal = todasAgrupaciones.Values.Select(agrupacion => new
{
Agrupacion = agrupacion,
DiputadosFijos = bancasPrevias.FirstOrDefault(b => b.AgrupacionPoliticaId == agrupacion.Id && b.Camara == Core.Enums.TipoCamara.Diputados)?.Cantidad ?? 0,
DiputadosGanados = proyecciones.Where(p => p.AgrupacionPoliticaId == agrupacion.Id && p.CategoriaId == 2).Sum(p => p.NroBancas),
SenadoresFijos = bancasPrevias.FirstOrDefault(b => b.AgrupacionPoliticaId == agrupacion.Id && b.Camara == Core.Enums.TipoCamara.Senadores)?.Cantidad ?? 0,
SenadoresGanados = proyecciones.Where(p => p.AgrupacionPoliticaId == agrupacion.Id && p.CategoriaId == 1).Sum(p => p.NroBancas)
})
.Select(r => new
{
r.Agrupacion,
r.DiputadosFijos,
r.DiputadosGanados,
DiputadosTotales = r.DiputadosFijos + r.DiputadosGanados,
r.SenadoresFijos,
r.SenadoresGanados,
SenadoresTotales = r.SenadoresFijos + r.SenadoresGanados
})
.ToList();
// 6. Determinar la información de la presidencia para cada cámara.
config.TryGetValue("PresidenciaDiputadosNacional", out var idPartidoPresDip);
var partidoPresidenteDiputados = !string.IsNullOrEmpty(idPartidoPresDip) ? todasAgrupaciones.GetValueOrDefault(idPartidoPresDip) : null;
config.TryGetValue("PresidenciaDiputadosNacional_TipoBanca", out var tipoBancaDip);
config.TryGetValue("PresidenciaSenadoNacional", out var idPartidoPresSen);
var partidoPresidenteSenadores = !string.IsNullOrEmpty(idPartidoPresSen) ? todasAgrupaciones.GetValueOrDefault(idPartidoPresSen) : null;
config.TryGetValue("PresidenciaSenadoNacional_TipoBanca", out var tipoBancaSen);
// 7. Construir el objeto de respuesta final para D Diputados
var diputados = new
{
CamaraNombre = "Cámara de Diputados",
TotalBancas = 257,
BancasEnJuego = 127,
UltimaActualizacion = ultimaActualizacion,
Partidos = composicionFinal
.Where(p => p.DiputadosTotales > 0)
.OrderByDescending(p => p.DiputadosTotales)
.Select(p => new
{
p.Agrupacion.Id,
p.Agrupacion.Nombre,
p.Agrupacion.NombreCorto,
p.Agrupacion.Color,
BancasFijos = p.DiputadosFijos,
BancasGanadas = p.DiputadosGanados,
BancasTotales = p.DiputadosTotales,
p.Agrupacion.OrdenDiputadosNacionales,
p.Agrupacion.OrdenSenadoresNacionales
}).ToList(),
PresidenteBancada = partidoPresidenteDiputados != null
? new { Color = partidoPresidenteDiputados.Color, TipoBanca = tipoBancaDip ?? "ganada" }
: null
};
// 8. Construir el objeto de respuesta final para Senadores
var senadores = new
{
CamaraNombre = "Senado de la Nación",
TotalBancas = 72,
BancasEnJuego = 24,
UltimaActualizacion = ultimaActualizacion,
Partidos = composicionFinal
.Where(p => p.SenadoresTotales > 0)
.OrderByDescending(p => p.SenadoresTotales)
.Select(p => new
{
p.Agrupacion.Id,
p.Agrupacion.Nombre,
p.Agrupacion.NombreCorto,
p.Agrupacion.Color,
BancasFijos = p.SenadoresFijos,
BancasGanadas = p.SenadoresGanados,
BancasTotales = p.SenadoresTotales,
p.Agrupacion.OrdenDiputadosNacionales,
p.Agrupacion.OrdenSenadoresNacionales
}).ToList(),
PresidenteBancada = partidoPresidenteSenadores != null
? new { Color = partidoPresidenteSenadores.Color, TipoBanca = tipoBancaSen ?? "ganada" }
: null
};
return Ok(new { Diputados = diputados, Senadores = senadores });
}
// --- INICIO DE FUNCIONES DE AYUDA ---
private CandidatoOverride? FindBestCandidatoMatch(
List<CandidatoOverride> overrides, string agrupacionId, int categoriaId, int? ambitoId, int eleccionId)
{
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)
// Prioridad 5: LOGO GLOBAL. Coincidencia solo por Partido (Elección y Categoría genéricas)
?? logos.FirstOrDefault(l => l.EleccionId == 0 && l.AgrupacionPoliticaId == agrupacionId && l.CategoriaId == 0 && l.AmbitoGeograficoId == null);
}
[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;
const int catDiputadosNac = 2;
const int catSenadoresNac = 1;
var provinciasQueRenuevanSenadores = new HashSet<string> { "01", "06", "08", "15", "16", "17", "22", "23" };
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 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 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)
{
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
{
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.Nombre,
NombreCortoAgrupacion = r.Agrupacion.NombreCorto,
NombreCandidato = candidatoMatch?.NombreCandidato,
Color = r.Agrupacion.Color,
Votos = r.Votos,
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()
});
}
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);
}
}

View File

@@ -10,6 +10,8 @@ using Microsoft.IdentityModel.Tokens;
using Elecciones.Database.Entities;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.HttpOverrides;
using Elecciones.Core.Enums;
using Microsoft.OpenApi.Models;
// Esta es la estructura estándar y recomendada.
var builder = WebApplication.CreateBuilder(args);
@@ -81,8 +83,40 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(options =>
{
// 1. Definir el esquema de seguridad que usaremos (Bearer Token)
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "Autorización JWT usando el esquema Bearer. Ingresa 'Bearer' [espacio] y luego tu token. Ejemplo: 'Bearer 12345abcdef'",
Name = "Authorization", // El nombre del header HTTP
In = ParameterLocation.Header, // Dónde se ubicará el token (en el header)
Type = SecuritySchemeType.ApiKey, // El tipo de esquema
Scheme = "Bearer" // El nombre del esquema
});
// 2. Aplicar este requisito de seguridad a todos los endpoints que lo necesiten
options.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer" // Debe coincidir con el nombre que le dimos en AddSecurityDefinition
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
@@ -125,95 +159,246 @@ 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 para las bancas vacías
// --- INICIO DEL BLOQUE DE SEEDERS UNIFICADO Y CORREGIDO ---
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var context = services.GetRequiredService<EleccionesDbContext>();
if (!context.Bancadas.Any())
var logger = services.GetRequiredService<ILogger<Program>>();
var hasher = services.GetRequiredService<IPasswordHasher>();
// --- 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.
// Usuario Admin
if (!await context.AdminUsers.AnyAsync())
{
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.");
}
// 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>();
// 92 bancas de diputados
for (int i = 1; i <= 92; i++) // Bucle de 1 a 92
{
bancas.Add(new Bancada
{
Camara = Elecciones.Core.Enums.TipoCamara.Diputados,
NumeroBanca = i // Asignamos el número de banca
});
}
// 46 bancas de senadores
for (int i = 1; i <= 46; i++) // Bucle de 1 a 46
{
bancas.Add(new Bancada
{
Camara = Elecciones.Core.Enums.TipoCamara.Senadores,
NumeroBanca = i // Asignamos el número de banca
});
}
context.Bancadas.AddRange(bancas);
context.SaveChanges();
Console.WriteLine("--> Seeded 138 bancas físicas.");
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);
}
}
// 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" }
// 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 (!context.Configuraciones.Any(c => c.Clave == config.Key))
{
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();
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))
{
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 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 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;
var categoriasParaProcesar = new List<CategoriaElectoral> { categoriaDiputadosNac! };
if (provinciasQueRenuevanSenadores.Contains(provincia.DistritoId!))
categoriasParaProcesar.Add(categoriaSenadoresNac!);
foreach (var categoria in categoriasParaProcesar)
{
long totalVotosProvinciaCategoria = 0;
int partidoIndex = rand.Next(todosLosPartidos.Count);
foreach (var municipio in municipiosDeProvincia)
{
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;
}
}
}
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 = ambitoNacional.Id,
CategoriaId = categoriaDiputadosNac.Id,
FechaTotalizacion = DateTime.UtcNow,
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
});
}
else
{
logger.LogWarning("--> No se encontró el ámbito nacional (NivelId == 0) o las categorías electorales nacionales. No se agregaron estados nacionales.");
}
if (nuevosResultados.Any())
{
await context.ResultadosVotos.AddRangeAsync(nuevosResultados);
await context.EstadosRecuentosGenerales.AddRangeAsync(nuevosEstados);
await context.SaveChangesAsync();
logger.LogInformation("--> Se generaron {Votos} registros de votos y {Estados} de estados de recuento.", nuevosResultados.Count, nuevosEstados.Count);
}
// PASO C: GENERAR BANCAS PREVIAS Y PROYECCIONES
if (!await context.BancasPrevias.AnyAsync(b => b.EleccionId == eleccionNacionalId))
{
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();
logger.LogInformation("--> Seeded Bancas Previas para la Elección Nacional.");
}
}
context.SaveChanges();
Console.WriteLine("--> Seeded default configurations.");
}
// --- FIN DEL BLOQUE DE SEEDERS UNIFICADO ---
// Configurar el pipeline de peticiones HTTP.
// Añadimos el logging de peticiones de Serilog aquí.

View File

@@ -5,7 +5,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"ApiKey": "badb1a38d221c9e23bcf70958840ca7f5a5dc54f2047dadf7ce45b578b5bc3e2",

View File

@@ -5,7 +5,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Information"
}
},
"ApiKey": "badb1a38d221c9e23bcf70958840ca7f5a5dc54f2047dadf7ce45b578b5bc3e2",

View File

@@ -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+64dc7ef440f585cb5e7723585b6327d5387f1b32")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+11d9417ef5e3645d51c0ab227a0804985db4b1fb")]
[assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Api")]
[assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Api")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@@ -1 +1 @@
{"GlobalPropertiesHash":"b5T/+ta4fUd8qpIzUTm3KyEwAYYUsU5ASo+CSFM3ByE=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["TyIJk/eQMWjmB5LsDE\u002BZIJC9P9ciVxd7bnzRiTZsGt4=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","6WTvWQ72AaZBYOVSmaxaci9tc1dW5p7IK9Kscjj2cb0=","vAy46VJ9Gp8QqG/Px4J1mj8jL6ws4/A01UKRmMYfYek=","cdgbHR/E4DJsddPc\u002BTpzoUMOVNaFJZm33Pw7AxU9Ees=","4r4JGR4hS5m4rsLfuCSZxzrknTBxKFkLQDXc\u002B2KbqTU=","yVoZ4UnBcSOapsJIi046hnn7ylD3jAcEBUxQ\u002Brkvj/4=","/GfbpJthEWmsuz0uFx1QLHM7gyM1wLLeQgAIl4SzUD4=","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=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","/f\u002B\u002BdIRysg7dipW05N4RtxXuPBXZZIhhi3aMiCZ\u002BB2w="],"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":{}}

View File

@@ -1 +1 @@
{"GlobalPropertiesHash":"tJTBjV/i0Ihkc6XuOu69wxL8PBac9c9Kak6srMso4pU=","FingerprintPatternsHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","PropertyOverridesHash":"8ZRc1sGeVrPBx4lD717BgRaQekyh78QKV9SKsdt638U=","InputHashes":["TyIJk/eQMWjmB5LsDE\u002BZIJC9P9ciVxd7bnzRiTZsGt4=","t631p0kaOa0gMRIcaPzz1ZVPZ1kuq4pq4kYPWQgoPcM=","PA/Beu9jJpOBY5r5Y1CiSyqrARA2j7LHeWYUnEZpQO8=","E2ODTAlJxzsXY1iP1eB/02NIUK\u002BnQveGlWAOHY1cpgA=","6WTvWQ72AaZBYOVSmaxaci9tc1dW5p7IK9Kscjj2cb0=","vAy46VJ9Gp8QqG/Px4J1mj8jL6ws4/A01UKRmMYfYek=","cdgbHR/E4DJsddPc\u002BTpzoUMOVNaFJZm33Pw7AxU9Ees=","4r4JGR4hS5m4rsLfuCSZxzrknTBxKFkLQDXc\u002B2KbqTU=","yVoZ4UnBcSOapsJIi046hnn7ylD3jAcEBUxQ\u002Brkvj/4=","/GfbpJthEWmsuz0uFx1QLHM7gyM1wLLeQgAIl4SzUD4=","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=","P8JRhYPpULTLMAydvl3Ky\u002B92/tYDIjui0l66En4aXuQ=","/f\u002B\u002BdIRysg7dipW05N4RtxXuPBXZZIhhi3aMiCZ\u002BB2w="],"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":{}}

View File

@@ -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":{}}

View File

@@ -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>

View File

@@ -0,0 +1,10 @@
using Elecciones.Core.DTOs;
using Elecciones.Core.DTOs.ApiResponses;
public class PanelElectoralDto
{
public required string AmbitoNombre { get; set; }
public required List<ResultadoMapaDto> MapaData { get; set; }
public required List<AgrupacionResultadoDto> ResultadosPanel { get; set; }
public required EstadoRecuentoDto EstadoRecuento { get; set; }
}

View File

@@ -0,0 +1,7 @@
public class ResultadoMapaDto
{
public required string AmbitoId { get; set; } // ID de la provincia o municipio
public required string AmbitoNombre { get; set; }
public required string AgrupacionGanadoraId { get; set; }
public required string ColorGanador { get; set; }
}

View File

@@ -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();
}

View File

@@ -0,0 +1,32 @@
namespace Elecciones.Core.DTOs.ApiResponses;
public class ResultadoCandidatoDto
{
public string AgrupacionId { get; set; } = string.Empty;
public string? NombreCandidato { get; set; }
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; }
public long Votos { get; set; }
public int BancasObtenidas { get; set; }
}
// Representa una única categoría (ej. "Diputados") con sus resultados y estado de recuento.
public class CategoriaResumenDto
{
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();
}

View File

@@ -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+64dc7ef440f585cb5e7723585b6327d5387f1b32")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+11d9417ef5e3645d51c0ab227a0804985db4b1fb")]
[assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Core")]
[assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Core")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@@ -21,6 +21,8 @@ public class EleccionesDbContext(DbContextOptions<EleccionesDbContext> options)
public DbSet<OcupanteBanca> OcupantesBancas { get; set; }
public DbSet<LogoAgrupacionCategoria> LogosAgrupacionesCategorias { get; set; }
public DbSet<CandidatoOverride> CandidatosOverrides { get; set; }
public DbSet<Eleccion> Elecciones { get; set; }
public DbSet<BancaPrevia> BancasPrevias { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -28,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();
@@ -89,5 +98,10 @@ public class EleccionesDbContext(DbContextOptions<EleccionesDbContext> options)
entity.HasIndex(c => new { c.AgrupacionPoliticaId, c.CategoriaId, c.AmbitoGeograficoId })
.IsUnique();
});
modelBuilder.Entity<BancaPrevia>(entity =>
{
entity.Property(e => e.AgrupacionPoliticaId)
.UseCollation("Modern_Spanish_CI_AS");
});
}
}

View File

@@ -10,8 +10,14 @@ public class AgrupacionPolitica
public string IdTelegrama { get; set; } = null!;
[Required]
public string Nombre { get; set; } = null!;
public string? NombreCorto { get; set; } // Para leyendas y gráficos
public string? Color { get; set; } // Código hexadecimal, ej: "#1f77b4"
public string? NombreCorto { get; set; }
public string? Color { get; set; }
// --- Campos para Provinciales ---
public int? OrdenDiputados { get; set; }
public int? OrdenSenadores { get; set; }
// --- Campos para Nacionales ---
public int? OrdenDiputadosNacionales { get; set; }
public int? OrdenSenadoresNacionales { get; set; }
}

View File

@@ -0,0 +1,28 @@
// src/Elecciones.Database/Entities/BancaPrevia.cs
using Elecciones.Core.Enums;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Elecciones.Database.Entities;
public class BancaPrevia
{
[Key]
public int Id { get; set; }
[Required]
public int EleccionId { get; set; }
[Required]
public TipoCamara Camara { get; set; }
[Required]
public string AgrupacionPoliticaId { get; set; } = null!;
[ForeignKey("AgrupacionPoliticaId")]
public AgrupacionPolitica AgrupacionPolitica { get; set; } = null!;
// Cantidad de bancas que el partido retiene (no están en juego)
[Required]
public int Cantidad { get; set; }
}

View File

@@ -12,15 +12,17 @@ public class Bancada
[Required]
public TipoCamara Camara { get; set; }
[Required]
public int NumeroBanca { get; set; }
public string? AgrupacionPoliticaId { get; set; }
[ForeignKey("AgrupacionPoliticaId")]
public AgrupacionPolitica? AgrupacionPolitica { get; set; }
// Relación uno a uno con OcupanteBanca
public OcupanteBanca? Ocupante { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -11,19 +11,19 @@ public class CandidatoOverride
[Required]
public string AgrupacionPoliticaId { get; set; } = null!;
[ForeignKey("AgrupacionPoliticaId")]
public AgrupacionPolitica AgrupacionPolitica { get; set; } = null!;
[Required]
public int CategoriaId { get; set; }
[ForeignKey("CategoriaId")]
public CategoriaElectoral CategoriaElectoral { get; set; } = null!;
// El AmbitoGeograficoId es opcional. Si es null, el override es general.
public int? AmbitoGeograficoId { get; set; }
[ForeignKey("AmbitoGeograficoId")]
public AmbitoGeografico? AmbitoGeografico { get; set; }
@@ -31,4 +31,5 @@ public class CandidatoOverride
[Required]
[MaxLength(255)]
public string NombreCandidato { get; set; } = null!;
public int EleccionId { get; set; }
}

View File

@@ -1,3 +1,4 @@
// src/Elecciones.Database/Entities/CategoriaElectoral.cs
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

View File

@@ -0,0 +1,14 @@
using System.ComponentModel.DataAnnotations;
public class Eleccion
{
[Key]
public int Id { get; set; }
[Required]
public string Nombre { get; set; } = null!; // Ej: "Elecciones Provinciales BA 2025"
[Required]
public string Nivel { get; set; } = null!; // Ej: "Provincial" o "Nacional"
[Required]
public string DistritoId { get; set; } = null!; // Ej: "02" para PBA, "00" para Nacional
public DateOnly Fecha { get; set; }
}

View File

@@ -10,7 +10,7 @@ public class EstadoRecuento
public int AmbitoGeograficoId { get; set; }
public int CategoriaId { get; set; }
[ForeignKey("AmbitoGeograficoId")]
public AmbitoGeografico AmbitoGeografico { get; set; } = null!;
public AmbitoGeografico AmbitoGeografico { get; set; } = null!;
public DateTime FechaTotalizacion { get; set; }
public int MesasEsperadas { get; set; }
public int MesasTotalizadas { get; set; }
@@ -24,4 +24,5 @@ public class EstadoRecuento
public decimal VotosNulosPorcentaje { get; set; }
public decimal VotosEnBlancoPorcentaje { get; set; }
public decimal VotosRecurridosPorcentaje { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -7,6 +7,7 @@ namespace Elecciones.Database.Entities;
public class EstadoRecuentoGeneral
{
public int AmbitoGeograficoId { get; set; }
public AmbitoGeografico AmbitoGeografico { get; set; } = null!;
public int CategoriaId { get; set; }
public DateTime FechaTotalizacion { get; set; }
public int MesasEsperadas { get; set; }
@@ -16,7 +17,9 @@ public class EstadoRecuentoGeneral
public int CantidadVotantes { get; set; }
public decimal ParticipacionPorcentaje { get; set; }
// --- Propiedades de navegación (Opcional pero recomendado) ---
// --- Propiedad de navegación (Opcional pero recomendado) ---
[ForeignKey("CategoriaId")]
public CategoriaElectoral CategoriaElectoral { get; set; } = null!;
public int EleccionId { get; set; }
}

View File

@@ -10,7 +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; }
}

View File

@@ -10,8 +10,8 @@ public class OcupanteBanca
public int Id { get; set; }
// Esta será la clave primaria y foránea para la relación 1-a-1
public int BancadaId { get; set; }
public int BancadaId { get; set; }
[ForeignKey("BancadaId")]
public Bancada Bancada { get; set; } = null!;
@@ -19,6 +19,8 @@ public class OcupanteBanca
public string NombreOcupante { get; set; } = null!;
public string? FotoUrl { get; set; }
public string? Periodo { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -24,4 +24,5 @@ public class ProyeccionBanca
// Cantidad de bancas obtenidas
public int NroBancas { get; set; }
public DateTime FechaTotalizacion { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -12,7 +12,7 @@ public class ResultadoVoto
public int AmbitoGeograficoId { get; set; }
public int CategoriaId { get; set; }
[ForeignKey("AmbitoGeograficoId")]
public AmbitoGeografico AmbitoGeografico { get; set; } = null!;
@@ -22,6 +22,8 @@ public class ResultadoVoto
// Datos
public long CantidadVotos { get; set; }
public decimal PorcentajeVotos { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -15,13 +15,15 @@ public class ResumenVoto
[Required]
public string AgrupacionPoliticaId { get; set; } = null!;
[ForeignKey("AgrupacionPoliticaId")]
public AgrupacionPolitica AgrupacionPolitica { get; set; } = null!;
[Required]
public long Votos { get; set; }
[Required]
public decimal VotosPorcentaje { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -12,10 +12,12 @@ public class Telegrama
// En qué ámbito fue escrutado
public int AmbitoGeograficoId { get; set; }
// El contenido del telegrama en Base64
public string ContenidoBase64 { get; set; } = null!;
public DateTime FechaEscaneo { get; set; }
public DateTime FechaTotalizacion { get; set; }
public int EleccionId { get; set; }
}

View File

@@ -0,0 +1,726 @@
// <auto-generated />
using System;
using Elecciones.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Elecciones.Database.Migrations
{
[DbContext(typeof(EleccionesDbContext))]
[Migration("20250929124756_LegislativasNacionales2025")]
partial class LegislativasNacionales2025
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Modern_Spanish_CI_AS")
.HasAnnotation("ProductVersion", "9.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Eleccion", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("DistritoId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateOnly>("Fecha")
.HasColumnType("date");
b.Property<string>("Nivel")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Elecciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.AdminUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordSalt")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("AdminUsers");
});
modelBuilder.Entity("Elecciones.Database.Entities.AgrupacionPolitica", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<string>("IdTelegrama")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreCorto")
.HasColumnType("nvarchar(max)");
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.AmbitoGeografico", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("CircuitoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("DistritoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("EstablecimientoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MesaId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MunicipioId")
.HasColumnType("nvarchar(max)");
b.Property<int>("NivelId")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionId")
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionProvincialId")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
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")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.HasColumnType("nvarchar(450)");
b.Property<int>("Camara")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<int>("NumeroBanca")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("Bancadas");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("NombreCandidato")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.HasKey("Id");
b.HasIndex("AmbitoGeograficoId");
b.HasIndex("CategoriaId");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("CandidatosOverrides");
});
modelBuilder.Entity("Elecciones.Database.Entities.CategoriaElectoral", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Orden")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("CategoriasElectorales");
});
modelBuilder.Entity("Elecciones.Database.Entities.Configuracion", b =>
{
b.Property<string>("Clave")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Valor")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Clave");
b.ToTable("Configuraciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<long>("VotosEnBlanco")
.HasColumnType("bigint");
b.Property<decimal>("VotosEnBlancoPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosNulos")
.HasColumnType("bigint");
b.Property<decimal>("VotosNulosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosRecurridos")
.HasColumnType("bigint");
b.Property<decimal>("VotosRecurridosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.ToTable("EstadosRecuentos");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.HasIndex("CategoriaId");
b.ToTable("EstadosRecuentosGenerales");
});
modelBuilder.Entity("Elecciones.Database.Entities.LogoAgrupacionCategoria", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("LogoUrl")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("LogosAgrupacionesCategorias");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BancadaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("FotoUrl")
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreOcupante")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Periodo")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("BancadaId")
.IsUnique();
b.ToTable("OcupantesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("NroBancas")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ProyeccionesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<long>("CantidadVotos")
.HasColumnType("bigint");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<decimal>("PorcentajeVotos")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ResultadosVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<long>("Votos")
.HasColumnType("bigint");
b.Property<decimal>("VotosPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("ResumenesVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.Telegrama", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<string>("ContenidoBase64")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaEscaneo")
.HasColumnType("datetime2");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.HasKey("Id");
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")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId");
b.Navigation("AgrupacionPolitica");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId");
b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral")
.WithMany()
.HasForeignKey("CategoriaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
b.Navigation("CategoriaElectoral");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AmbitoGeografico");
});
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.Bancada", "Bancada")
.WithOne("Ocupante")
.HasForeignKey("Elecciones.Database.Entities.OcupanteBanca", "BancadaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Bancada");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", 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.Navigation("Ocupante");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,209 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Elecciones.Database.Migrations
{
/// <inheritdoc />
public partial class LegislativasNacionales2025 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "Telegramas",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "ResumenesVotos",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "ResultadosVotos",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "ProyeccionesBancas",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "OcupantesBancas",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "LogosAgrupacionesCategorias",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "EstadosRecuentosGenerales",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "EstadosRecuentos",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "CandidatosOverrides",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<int>(
name: "EleccionId",
table: "Bancadas",
type: "int",
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: "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),
Fecha = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
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");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "Telegramas");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "ResumenesVotos");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "ResultadosVotos");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "ProyeccionesBancas");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "OcupantesBancas");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "LogosAgrupacionesCategorias");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "EstadosRecuentosGenerales");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "EstadosRecuentos");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "CandidatosOverrides");
migrationBuilder.DropColumn(
name: "EleccionId",
table: "Bancadas");
migrationBuilder.DropColumn(
name: "OrdenDiputadosNacionales",
table: "AgrupacionesPoliticas");
migrationBuilder.DropColumn(
name: "OrdenSenadoresNacionales",
table: "AgrupacionesPoliticas");
}
}
}

View File

@@ -0,0 +1,726 @@
// <auto-generated />
using System;
using Elecciones.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Elecciones.Database.Migrations
{
[DbContext(typeof(EleccionesDbContext))]
[Migration("20250929153202_MakeCategoriaIdNullableInLogos")]
partial class MakeCategoriaIdNullableInLogos
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Modern_Spanish_CI_AS")
.HasAnnotation("ProductVersion", "9.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Eleccion", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("DistritoId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateOnly>("Fecha")
.HasColumnType("date");
b.Property<string>("Nivel")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Elecciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.AdminUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordSalt")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("AdminUsers");
});
modelBuilder.Entity("Elecciones.Database.Entities.AgrupacionPolitica", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<string>("IdTelegrama")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreCorto")
.HasColumnType("nvarchar(max)");
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.AmbitoGeografico", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("CircuitoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("DistritoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("EstablecimientoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MesaId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MunicipioId")
.HasColumnType("nvarchar(max)");
b.Property<int>("NivelId")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionId")
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionProvincialId")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
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")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.HasColumnType("nvarchar(450)");
b.Property<int>("Camara")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<int>("NumeroBanca")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("Bancadas");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("NombreCandidato")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.HasKey("Id");
b.HasIndex("AmbitoGeograficoId");
b.HasIndex("CategoriaId");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("CandidatosOverrides");
});
modelBuilder.Entity("Elecciones.Database.Entities.CategoriaElectoral", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Orden")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("CategoriasElectorales");
});
modelBuilder.Entity("Elecciones.Database.Entities.Configuracion", b =>
{
b.Property<string>("Clave")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Valor")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Clave");
b.ToTable("Configuraciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<long>("VotosEnBlanco")
.HasColumnType("bigint");
b.Property<decimal>("VotosEnBlancoPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosNulos")
.HasColumnType("bigint");
b.Property<decimal>("VotosNulosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosRecurridos")
.HasColumnType("bigint");
b.Property<decimal>("VotosRecurridosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.ToTable("EstadosRecuentos");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.HasIndex("CategoriaId");
b.ToTable("EstadosRecuentosGenerales");
});
modelBuilder.Entity("Elecciones.Database.Entities.LogoAgrupacionCategoria", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("LogoUrl")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("LogosAgrupacionesCategorias");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BancadaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("FotoUrl")
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreOcupante")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Periodo")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("BancadaId")
.IsUnique();
b.ToTable("OcupantesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("NroBancas")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ProyeccionesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<long>("CantidadVotos")
.HasColumnType("bigint");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<decimal>("PorcentajeVotos")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ResultadosVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<long>("Votos")
.HasColumnType("bigint");
b.Property<decimal>("VotosPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("ResumenesVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.Telegrama", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<string>("ContenidoBase64")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaEscaneo")
.HasColumnType("datetime2");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.HasKey("Id");
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")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId");
b.Navigation("AgrupacionPolitica");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId");
b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral")
.WithMany()
.HasForeignKey("CategoriaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
b.Navigation("CategoriaElectoral");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AmbitoGeografico");
});
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.Bancada", "Bancada")
.WithOne("Ocupante")
.HasForeignKey("Elecciones.Database.Entities.OcupanteBanca", "BancadaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Bancada");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", 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.Navigation("Ocupante");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -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)
{
}
}
}

View File

@@ -0,0 +1,726 @@
// <auto-generated />
using System;
using Elecciones.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Elecciones.Database.Migrations
{
[DbContext(typeof(EleccionesDbContext))]
[Migration("20250929163650_FixLogoCategoriaNullability")]
partial class FixLogoCategoriaNullability
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.UseCollation("Modern_Spanish_CI_AS")
.HasAnnotation("ProductVersion", "9.0.8")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Eleccion", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("DistritoId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateOnly>("Fecha")
.HasColumnType("date");
b.Property<string>("Nivel")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Elecciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.AdminUser", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("PasswordHash")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("PasswordSalt")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Id");
b.ToTable("AdminUsers");
});
modelBuilder.Entity("Elecciones.Database.Entities.AgrupacionPolitica", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("Color")
.HasColumnType("nvarchar(max)");
b.Property<string>("IdTelegrama")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreCorto")
.HasColumnType("nvarchar(max)");
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.AmbitoGeografico", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("CircuitoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("DistritoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("EstablecimientoId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MesaId")
.HasColumnType("nvarchar(max)");
b.Property<string>("MunicipioId")
.HasColumnType("nvarchar(max)");
b.Property<int>("NivelId")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionId")
.HasColumnType("nvarchar(max)");
b.Property<string>("SeccionProvincialId")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
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")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.HasColumnType("nvarchar(450)");
b.Property<int>("Camara")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<int>("NumeroBanca")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("Bancadas");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("NombreCandidato")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("nvarchar(255)");
b.HasKey("Id");
b.HasIndex("AmbitoGeograficoId");
b.HasIndex("CategoriaId");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("CandidatosOverrides");
});
modelBuilder.Entity("Elecciones.Database.Entities.CategoriaElectoral", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("Orden")
.HasColumnType("int");
b.HasKey("Id");
b.ToTable("CategoriasElectorales");
});
modelBuilder.Entity("Elecciones.Database.Entities.Configuracion", b =>
{
b.Property<string>("Clave")
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.Property<string>("Valor")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");
b.HasKey("Clave");
b.ToTable("Configuraciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<long>("VotosEnBlanco")
.HasColumnType("bigint");
b.Property<decimal>("VotosEnBlancoPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosNulos")
.HasColumnType("bigint");
b.Property<decimal>("VotosNulosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.Property<long>("VotosRecurridos")
.HasColumnType("bigint");
b.Property<decimal>("VotosRecurridosPorcentaje")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.ToTable("EstadosRecuentos");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuentoGeneral", b =>
{
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("CantidadElectores")
.HasColumnType("int");
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("MesasEsperadas")
.HasColumnType("int");
b.Property<int>("MesasTotalizadas")
.HasColumnType("int");
b.Property<decimal>("MesasTotalizadasPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.Property<decimal>("ParticipacionPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("AmbitoGeograficoId", "CategoriaId");
b.HasIndex("CategoriaId");
b.ToTable("EstadosRecuentosGenerales");
});
modelBuilder.Entity("Elecciones.Database.Entities.LogoAgrupacionCategoria", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int?>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int?>("EleccionId")
.HasColumnType("int");
b.Property<string>("LogoUrl")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId", "CategoriaId", "AmbitoGeograficoId")
.IsUnique()
.HasFilter("[AmbitoGeograficoId] IS NOT NULL");
b.ToTable("LogosAgrupacionesCategorias");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("BancadaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("FotoUrl")
.HasColumnType("nvarchar(max)");
b.Property<string>("NombreOcupante")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Periodo")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("BancadaId")
.IsUnique();
b.ToTable("OcupantesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.Property<int>("NroBancas")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ProyeccionesBancas");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<long>("CantidadVotos")
.HasColumnType("bigint");
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<decimal>("PorcentajeVotos")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.HasIndex("AmbitoGeograficoId", "CategoriaId", "AgrupacionPoliticaId")
.IsUnique();
b.ToTable("ResultadosVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<string>("AgrupacionPoliticaId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<long>("Votos")
.HasColumnType("bigint");
b.Property<decimal>("VotosPorcentaje")
.HasPrecision(5, 2)
.HasColumnType("decimal(5,2)");
b.HasKey("Id");
b.HasIndex("AgrupacionPoliticaId");
b.ToTable("ResumenesVotos");
});
modelBuilder.Entity("Elecciones.Database.Entities.Telegrama", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<string>("ContenidoBase64")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaEscaneo")
.HasColumnType("datetime2");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
b.HasKey("Id");
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")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId");
b.Navigation("AgrupacionPolitica");
});
modelBuilder.Entity("Elecciones.Database.Entities.CandidatoOverride", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId");
b.HasOne("Elecciones.Database.Entities.CategoriaElectoral", "CategoriaElectoral")
.WithMany()
.HasForeignKey("CategoriaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
b.Navigation("CategoriaElectoral");
});
modelBuilder.Entity("Elecciones.Database.Entities.EstadoRecuento", b =>
{
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AmbitoGeografico");
});
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");
});
modelBuilder.Entity("Elecciones.Database.Entities.OcupanteBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.Bancada", "Bancada")
.WithOne("Ocupante")
.HasForeignKey("Elecciones.Database.Entities.OcupanteBanca", "BancadaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Bancada");
});
modelBuilder.Entity("Elecciones.Database.Entities.ProyeccionBanca", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResultadoVoto", b =>
{
b.HasOne("Elecciones.Database.Entities.AgrupacionPolitica", "AgrupacionPolitica")
.WithMany()
.HasForeignKey("AgrupacionPoliticaId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Elecciones.Database.Entities.AmbitoGeografico", "AmbitoGeografico")
.WithMany()
.HasForeignKey("AmbitoGeograficoId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("AgrupacionPolitica");
b.Navigation("AmbitoGeografico");
});
modelBuilder.Entity("Elecciones.Database.Entities.ResumenVoto", 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.Navigation("Ocupante");
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -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");
}
}
}

View File

@@ -23,6 +23,31 @@ namespace Elecciones.Database.Migrations
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("Eleccion", b =>
{
b.Property<int>("Id")
.HasColumnType("int");
b.Property<string>("DistritoId")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateOnly>("Fecha")
.HasColumnType("date");
b.Property<string>("Nivel")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Nombre")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Elecciones");
});
modelBuilder.Entity("Elecciones.Database.Entities.AdminUser", b =>
{
b.Property<int>("Id")
@@ -71,9 +96,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");
@@ -120,6 +151,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")
@@ -134,6 +194,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("Camara")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<int>("NumeroBanca")
.HasColumnType("int");
@@ -162,6 +225,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("NombreCandidato")
.IsRequired()
.HasMaxLength(255)
@@ -227,6 +293,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
@@ -284,6 +353,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CantidadVotantes")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
@@ -326,6 +398,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int?>("EleccionId")
.HasColumnType("int");
b.Property<string>("LogoUrl")
.HasColumnType("nvarchar(max)");
@@ -349,6 +424,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("BancadaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<string>("FotoUrl")
.HasColumnType("nvarchar(max)");
@@ -385,6 +463,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaTotalizacion")
.HasColumnType("datetime2");
@@ -422,6 +503,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("CategoriaId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<decimal>("PorcentajeVotos")
.HasPrecision(18, 4)
.HasColumnType("decimal(18,4)");
@@ -451,6 +535,9 @@ namespace Elecciones.Database.Migrations
b.Property<int>("AmbitoGeograficoId")
.HasColumnType("int");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<long>("Votos")
.HasColumnType("bigint");
@@ -477,6 +564,9 @@ namespace Elecciones.Database.Migrations
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("EleccionId")
.HasColumnType("int");
b.Property<DateTime>("FechaEscaneo")
.HasColumnType("datetime2");
@@ -488,6 +578,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")
@@ -535,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");
});

View File

@@ -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+843c0f725893a48eae1236473cb5eeb00ef3d91c")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+11d9417ef5e3645d51c0ab227a0804985db4b1fb")]
[assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Database")]
[assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Database")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@@ -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+843c0f725893a48eae1236473cb5eeb00ef3d91c")]
[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")]

View File

@@ -14,7 +14,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Elecciones.Worker")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+843c0f725893a48eae1236473cb5eeb00ef3d91c")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+3a8f64bf854b2bdf66d83e503aaacc7dca77138e")]
[assembly: System.Reflection.AssemblyProductAttribute("Elecciones.Worker")]
[assembly: System.Reflection.AssemblyTitleAttribute("Elecciones.Worker")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]

View File

@@ -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>