| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | using FAU.DataAccess; |
| | | 5 | | using FAU.DataAccess.Repositories; |
| | | 6 | | using FAU.Entidades; |
| | | 7 | | using FAU.Logica.DTOs; |
| | | 8 | | using Microsoft.EntityFrameworkCore; |
| | | 9 | | |
| | | 10 | | namespace FAU.Logica.Services; |
| | | 11 | | |
| | | 12 | | public class PeriodoService : IPeriodoService |
| | | 13 | | { |
| | | 14 | | private readonly IPeriodosRepository _periodosRepository; |
| | | 15 | | private readonly ISnapshotsRepository _snapshotsRepository; |
| | | 16 | | private readonly ApplicationDbContext _context; |
| | | 17 | | private readonly IAuditoriaService _auditoriaService; |
| | | 18 | | private readonly ICurrentUserContext _currentUser; |
| | | 19 | | private readonly IInsumoEvaluador _evaluador; |
| | | 20 | | private readonly IDescuentoPersonalRepository _descuentoPersonalRepo; |
| | | 21 | | |
| | 25 | 22 | | public PeriodoService( |
| | 25 | 23 | | IPeriodosRepository periodosRepository, |
| | 25 | 24 | | ISnapshotsRepository snapshotsRepository, |
| | 25 | 25 | | ApplicationDbContext context, |
| | 25 | 26 | | IAuditoriaService auditoriaService, |
| | 25 | 27 | | ICurrentUserContext currentUser, |
| | 25 | 28 | | IInsumoEvaluador evaluador, |
| | 25 | 29 | | IDescuentoPersonalRepository descuentoPersonalRepo) |
| | | 30 | | { |
| | 25 | 31 | | _periodosRepository = periodosRepository; |
| | 25 | 32 | | _snapshotsRepository = snapshotsRepository; |
| | 25 | 33 | | _context = context; |
| | 25 | 34 | | _auditoriaService = auditoriaService; |
| | 25 | 35 | | _currentUser = currentUser; |
| | 25 | 36 | | _evaluador = evaluador; |
| | 25 | 37 | | _descuentoPersonalRepo = descuentoPersonalRepo; |
| | 25 | 38 | | } |
| | | 39 | | |
| | | 40 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> AbrirPeriodoAsync(short anio, short mes) |
| | | 41 | | { |
| | 9 | 42 | | if (anio < 2000 || anio > 2100) |
| | | 43 | | { |
| | 0 | 44 | | return (false, null, "El año debe estar entre 2000 y 2100"); |
| | | 45 | | } |
| | | 46 | | |
| | 9 | 47 | | if (mes < 1 || mes > 12) |
| | | 48 | | { |
| | 0 | 49 | | return (false, null, "El mes debe estar entre 1 y 12"); |
| | | 50 | | } |
| | | 51 | | |
| | 9 | 52 | | var periodoExistente = await _periodosRepository.ObtenerPorAnioMesAsync(anio, mes); |
| | 9 | 53 | | if (periodoExistente is not null) |
| | | 54 | | { |
| | | 55 | | // Ya existe un período para este mes → devolver el existente si está abierto, |
| | | 56 | | // o un error descriptivo si está en otro estado (cerrado, calculado, etc.). |
| | 1 | 57 | | if (periodoExistente.Estado == Periodo.EstadoAbierta && periodoExistente.Activo) |
| | 1 | 58 | | return (true, periodoExistente, null); |
| | | 59 | | |
| | 0 | 60 | | var sugerencia = periodoExistente.Estado == Periodo.EstadoListaCalculo |
| | 0 | 61 | | ? " Podés reabrirlo desde el panel del período." |
| | 0 | 62 | | : periodoExistente.Estado == Periodo.EstadoCerrada |
| | 0 | 63 | | ? " Un período cerrado es definitivo." |
| | 0 | 64 | | : string.Empty; |
| | | 65 | | |
| | 0 | 66 | | return (false, null, |
| | 0 | 67 | | $"Ya existe un período para {mes:D2}/{anio} en estado '{periodoExistente.Estado}'.{sugerencia}"); |
| | | 68 | | } |
| | | 69 | | |
| | 8 | 70 | | var periodoEnCurso = await _periodosRepository.ObtenerEnCursoAsync(); |
| | 8 | 71 | | if (periodoEnCurso is not null) |
| | | 72 | | { |
| | 1 | 73 | | return (false, null, $"Ya existe un período activo en estado {periodoEnCurso.Estado}"); |
| | | 74 | | } |
| | | 75 | | |
| | 7 | 76 | | var parametrosPeriodo = await _context.ParametrosPeriodo |
| | 7 | 77 | | .AsNoTracking() |
| | 7 | 78 | | .FirstOrDefaultAsync(p => p.Anio == anio && p.Mes == mes); |
| | | 79 | | |
| | 7 | 80 | | if (parametrosPeriodo is null) |
| | | 81 | | { |
| | 2 | 82 | | return (false, null, "No existen parámetros de liquidación para el período indicado"); |
| | | 83 | | } |
| | | 84 | | |
| | 5 | 85 | | var fechaInicioPeriodo = new DateTime(anio, mes, 1, 0, 0, 0, DateTimeKind.Utc); |
| | 5 | 86 | | var fechaFinPeriodo = fechaInicioPeriodo.AddMonths(1).AddTicks(-1); |
| | | 87 | | |
| | 5 | 88 | | var existeRemuneraciones = await _context.RemuneracionesGrado |
| | 5 | 89 | | .AsNoTracking() |
| | 5 | 90 | | .AnyAsync(r => r.VigenteDesde <= fechaInicioPeriodo && (r.VigenteHasta == null || r.VigenteHasta >= fechaIni |
| | | 91 | | |
| | 5 | 92 | | if (!existeRemuneraciones) |
| | | 93 | | { |
| | 0 | 94 | | return (false, null, "No existen remuneraciones de grado vigentes para el período"); |
| | | 95 | | } |
| | | 96 | | |
| | 5 | 97 | | var existeFranjaIrpf = await _context.FranjasIrpf |
| | 5 | 98 | | .AsNoTracking() |
| | 5 | 99 | | .AnyAsync(f => f.VigenteDesde <= fechaInicioPeriodo && (f.VigenteHasta == null || f.VigenteHasta >= fechaIni |
| | | 100 | | |
| | 5 | 101 | | if (!existeFranjaIrpf) |
| | | 102 | | { |
| | 0 | 103 | | return (false, null, "No existen franjas IRPF vigentes para el período"); |
| | | 104 | | } |
| | | 105 | | |
| | 5 | 106 | | var existeRelacionLaboral = await _context.RelacionesLaborales |
| | 5 | 107 | | .AsNoTracking() |
| | 5 | 108 | | .AnyAsync(r => r.Estado == EstadoRelacion.Activo); |
| | | 109 | | |
| | 5 | 110 | | if (!existeRelacionLaboral) |
| | | 111 | | { |
| | 0 | 112 | | return (false, null, "No hay funcionarios activos en el padrón"); |
| | | 113 | | } |
| | | 114 | | |
| | 5 | 115 | | var snapshotJson = await SerializarSnapshotAsync(anio, mes, parametrosPeriodo, fechaInicioPeriodo, fechaFinPerio |
| | 5 | 116 | | var hashSnapshot = CalcularHash(snapshotJson); |
| | | 117 | | |
| | 5 | 118 | | var snapshot = new SnapshotInsumos |
| | 5 | 119 | | { |
| | 5 | 120 | | ContenidoJson = snapshotJson, |
| | 5 | 121 | | HashIntegridad = hashSnapshot |
| | 5 | 122 | | }; |
| | | 123 | | |
| | 5 | 124 | | var snapshotCreado = await _snapshotsRepository.CrearAsync(snapshot); |
| | | 125 | | |
| | 5 | 126 | | var periodo = new Periodo |
| | 5 | 127 | | { |
| | 5 | 128 | | Anio = anio, |
| | 5 | 129 | | Mes = mes, |
| | 5 | 130 | | Estado = Periodo.EstadoAbierta, |
| | 5 | 131 | | SnapshotId = snapshotCreado.Id, |
| | 5 | 132 | | FechaApertura = DateTime.UtcNow, |
| | 5 | 133 | | UsuarioApertura = _currentUser.UserId ?? 0, |
| | 5 | 134 | | HashSnapshot = hashSnapshot, |
| | 5 | 135 | | Activo = true |
| | 5 | 136 | | }; |
| | | 137 | | |
| | 5 | 138 | | var periodoCreado = await _periodosRepository.CrearAsync(periodo); |
| | | 139 | | |
| | 5 | 140 | | await _auditoriaService.LogAuditoriaAsync( |
| | 5 | 141 | | _currentUser.UserId ?? 0, |
| | 5 | 142 | | AccionEnum.AbrirPeriodoLiquidacion, |
| | 5 | 143 | | ContextoEnum.Liquidaciones, |
| | 5 | 144 | | _currentUser.Host, |
| | 5 | 145 | | entidad: nameof(Periodo), |
| | 5 | 146 | | entidadId: periodoCreado.Id, |
| | 5 | 147 | | detalle: new |
| | 5 | 148 | | { |
| | 5 | 149 | | anio, |
| | 5 | 150 | | mes, |
| | 5 | 151 | | snapshotId = snapshotCreado.Id, |
| | 5 | 152 | | hashSnapshot |
| | 5 | 153 | | }); |
| | | 154 | | |
| | 5 | 155 | | return (true, periodoCreado, null); |
| | 9 | 156 | | } |
| | | 157 | | |
| | | 158 | | public Task<Periodo?> ObtenerActivoAsync() |
| | | 159 | | { |
| | 0 | 160 | | return _periodosRepository.ObtenerActivoAsync(); |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | public Task<Periodo?> ObtenerEnCursoAsync() |
| | | 164 | | { |
| | 0 | 165 | | return _periodosRepository.ObtenerEnCursoAsync(); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | public Task<Periodo?> ObtenerPorIdAsync(long id) |
| | | 169 | | { |
| | 0 | 170 | | return _periodosRepository.ObtenerPorIdAsync(id); |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | public async Task<PrecondicionesDto?> ObtenerPrecondicionesAsync(long periodoId) |
| | | 174 | | { |
| | 0 | 175 | | var validacion = await ValidarInsumosAsync(periodoId); |
| | 0 | 176 | | if (validacion is null) return null; |
| | | 177 | | |
| | 0 | 178 | | bool Ok(string tipo) => validacion.ItemsIncompletos.All(i => i.Tipo != tipo); |
| | | 179 | | string Detail(string tipo, string okMsg, string failMsg) => |
| | 0 | 180 | | Ok(tipo) ? okMsg : (validacion.ItemsIncompletos.FirstOrDefault(i => i.Tipo == tipo)?.Descripcion ?? failMsg) |
| | | 181 | | |
| | 0 | 182 | | var lotesOk = Ok("lote_faltante"); |
| | 0 | 183 | | var novedadesOk = Ok("novedades_pendientes"); |
| | 0 | 184 | | var beneficiosOk = Ok("beneficios_faltantes"); |
| | 0 | 185 | | var remuneracionesOk = Ok("tabla_referencia") || |
| | 0 | 186 | | !validacion.ItemsIncompletos.Any(i => i.Clave == "SinRemuneraciones"); |
| | 0 | 187 | | var franjasOk = !validacion.ItemsIncompletos.Any(i => i.Clave == "SinFranjasIrpf"); |
| | 0 | 188 | | var funcionariosOk = !validacion.ItemsIncompletos.Any(i => i.Clave == "SinFuncionarios"); |
| | | 189 | | |
| | 0 | 190 | | return new PrecondicionesDto |
| | 0 | 191 | | { |
| | 0 | 192 | | LotesAprobados = new PrecondicionItemDto |
| | 0 | 193 | | { |
| | 0 | 194 | | Ok = lotesOk, |
| | 0 | 195 | | Detail = lotesOk ? "Lotes aprobados" : "Sin lotes aprobados para el período" |
| | 0 | 196 | | }, |
| | 0 | 197 | | NovedadesSinConfirmar = new PrecondicionItemDto |
| | 0 | 198 | | { |
| | 0 | 199 | | Ok = novedadesOk, |
| | 0 | 200 | | Detail = novedadesOk ? "Sin novedades pendientes" : |
| | 0 | 201 | | validacion.ItemsIncompletos.FirstOrDefault(i => i.Tipo == "novedades_pendientes")?.Descripcion ?? "N |
| | 0 | 202 | | }, |
| | 0 | 203 | | BeneficiosVigentes = new PrecondicionItemDto |
| | 0 | 204 | | { |
| | 0 | 205 | | Ok = beneficiosOk, |
| | 0 | 206 | | Detail = beneficiosOk ? "Beneficios sociales activos" : "Sin beneficios sociales activos vigentes" |
| | 0 | 207 | | }, |
| | 0 | 208 | | RemuneracionesVigentes = new PrecondicionItemDto |
| | 0 | 209 | | { |
| | 0 | 210 | | Ok = remuneracionesOk, |
| | 0 | 211 | | Detail = remuneracionesOk ? "Tablas de remuneración vigentes" : "Sin tablas de remuneración para el perí |
| | 0 | 212 | | }, |
| | 0 | 213 | | FranjasIrpf = new PrecondicionItemDto |
| | 0 | 214 | | { |
| | 0 | 215 | | Ok = franjasOk, |
| | 0 | 216 | | Detail = franjasOk ? "Franjas IRPF vigentes" : "Sin franjas IRPF para el período" |
| | 0 | 217 | | }, |
| | 0 | 218 | | FuncionariosActivos = new PrecondicionItemDto |
| | 0 | 219 | | { |
| | 0 | 220 | | Ok = funcionariosOk, |
| | 0 | 221 | | Detail = funcionariosOk ? "Funcionarios activos en el padrón" : "No hay funcionarios activos" |
| | 0 | 222 | | } |
| | 0 | 223 | | }; |
| | 0 | 224 | | } |
| | | 225 | | |
| | | 226 | | public async Task<ValidacionInsumosDto?> ValidarInsumosAsync(long periodoId) |
| | | 227 | | { |
| | 0 | 228 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 0 | 229 | | if (periodo is null) return null; |
| | 0 | 230 | | return await _evaluador.EvaluarAsync(periodo); |
| | 0 | 231 | | } |
| | | 232 | | |
| | | 233 | | public async Task<(bool Exito, Periodo? Periodo, ValidacionInsumosDto? Validacion, string? Error)> CerrarInsumosAsyn |
| | | 234 | | long periodoId, List<string>? confirmaciones = null) |
| | | 235 | | { |
| | 8 | 236 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 8 | 237 | | if (periodo is null) |
| | 0 | 238 | | return (false, null, null, "Período no encontrado"); |
| | | 239 | | |
| | 8 | 240 | | if (periodo.Estado != Periodo.EstadoAbierta) |
| | 1 | 241 | | return (false, null, null, $"Solo se puede cerrar insumos desde estado ABIERTA. Estado actual: {periodo.Esta |
| | | 242 | | |
| | 7 | 243 | | var validacion = await _evaluador.EvaluarAsync(periodo); |
| | | 244 | | |
| | 7 | 245 | | if (!validacion.TodosCompletos) |
| | | 246 | | { |
| | 5 | 247 | | if (confirmaciones is null || confirmaciones.Count == 0) |
| | 4 | 248 | | return (false, null, validacion, "Hay insumos incompletos. Revisá el detalle y confirmá cada omisión par |
| | | 249 | | |
| | 2 | 250 | | var bloqueantes = validacion.ItemsIncompletos.Where(i => !i.EsConfirmable).ToList(); |
| | 1 | 251 | | if (bloqueantes.Count > 0) |
| | 0 | 252 | | return (false, null, validacion, "Existen problemas bloqueantes que no pueden omitirse."); |
| | | 253 | | |
| | 1 | 254 | | var clavesSinConfirmar = validacion.ItemsIncompletos |
| | 1 | 255 | | .Where(i => !confirmaciones.Contains(i.Clave)) |
| | 1 | 256 | | .ToList(); |
| | 1 | 257 | | if (clavesSinConfirmar.Count > 0) |
| | 0 | 258 | | return (false, null, new ValidacionInsumosDto |
| | 0 | 259 | | { |
| | 0 | 260 | | TodosCompletos = false, |
| | 0 | 261 | | PuedeConfirmar = true, |
| | 0 | 262 | | ItemsIncompletos = clavesSinConfirmar |
| | 0 | 263 | | }, "Faltan confirmar algunos items incompletos."); |
| | | 264 | | } |
| | | 265 | | |
| | 3 | 266 | | if (confirmaciones?.Contains("DescuentosBorrador") == true) |
| | 0 | 267 | | await _descuentoPersonalRepo.ConfirmarBorradoresAsync(periodoId); |
| | | 268 | | |
| | 3 | 269 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 3 | 270 | | periodo.Estado = Periodo.EstadoListaCalculo; |
| | 3 | 271 | | periodo.FechaCierreInsumos = DateTime.UtcNow; |
| | 3 | 272 | | periodo.UsuarioCierreInsumosId = usuarioId; |
| | 3 | 273 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 274 | | |
| | 3 | 275 | | var omisiones = confirmaciones ?? new List<string>(); |
| | 3 | 276 | | await _auditoriaService.LogAuditoriaAsync( |
| | 3 | 277 | | usuarioId, |
| | 3 | 278 | | AccionEnum.CerrarInsumosPeriodo, |
| | 3 | 279 | | ContextoEnum.Liquidaciones, |
| | 3 | 280 | | _currentUser.Host, |
| | 3 | 281 | | entidad: nameof(Periodo), |
| | 3 | 282 | | entidadId: periodo.Id, |
| | 3 | 283 | | detalle: new |
| | 3 | 284 | | { |
| | 3 | 285 | | anio = periodo.Anio, |
| | 3 | 286 | | mes = periodo.Mes, |
| | 3 | 287 | | omisionesConfirmadas = omisiones.Select(c => |
| | 0 | 288 | | validacion.ItemsIncompletos.FirstOrDefault(i => i.Clave == c)?.Descripcion ?? c) |
| | 3 | 289 | | }); |
| | | 290 | | |
| | 3 | 291 | | return (true, periodo, null, null); |
| | 8 | 292 | | } |
| | | 293 | | |
| | | 294 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> ReabrirInsumosAsync(long periodoId) |
| | | 295 | | { |
| | 3 | 296 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 3 | 297 | | if (periodo is null) |
| | 0 | 298 | | return (false, null, "Período no encontrado"); |
| | | 299 | | |
| | 3 | 300 | | if (periodo.Estado != Periodo.EstadoListaCalculo) |
| | 1 | 301 | | return (false, null, $"Solo se puede reabrir desde estado LISTA_CALCULO. Estado actual: {periodo.Estado}"); |
| | | 302 | | |
| | 2 | 303 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 2 | 304 | | periodo.Estado = Periodo.EstadoAbierta; |
| | 2 | 305 | | periodo.FechaCierreInsumos = null; |
| | 2 | 306 | | periodo.UsuarioCierreInsumosId = null; |
| | 2 | 307 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 308 | | |
| | 2 | 309 | | await _auditoriaService.LogAuditoriaAsync( |
| | 2 | 310 | | usuarioId, |
| | 2 | 311 | | AccionEnum.ReabrirInsumosPeriodo, |
| | 2 | 312 | | ContextoEnum.Liquidaciones, |
| | 2 | 313 | | _currentUser.Host, |
| | 2 | 314 | | entidad: nameof(Periodo), |
| | 2 | 315 | | entidadId: periodo.Id, |
| | 2 | 316 | | detalle: new { anio = periodo.Anio, mes = periodo.Mes }); |
| | | 317 | | |
| | 2 | 318 | | return (true, periodo, null); |
| | 3 | 319 | | } |
| | | 320 | | |
| | | 321 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> IniciarCalculoAsync(long periodoId) |
| | | 322 | | { |
| | 2 | 323 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 2 | 324 | | if (periodo is null) |
| | 0 | 325 | | return (false, null, "Período no encontrado"); |
| | | 326 | | |
| | 2 | 327 | | if (periodo.Estado != Periodo.EstadoListaCalculo) |
| | 1 | 328 | | return (false, null, $"Solo se puede calcular desde estado LISTA_CALCULO. Estado actual: {periodo.Estado}"); |
| | | 329 | | |
| | 1 | 330 | | if (await _descuentoPersonalRepo.TieneBorradoresAsync(periodoId)) |
| | 0 | 331 | | return (false, null, "Existen descuentos personales sin confirmar. Confirme todos los borradores antes de in |
| | | 332 | | |
| | 1 | 333 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 1 | 334 | | periodo.Estado = Periodo.EstadoEnCalculo; |
| | 1 | 335 | | periodo.FechaCalculo = DateTime.UtcNow; |
| | 1 | 336 | | periodo.UsuarioCalculoId = usuarioId; |
| | 1 | 337 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 338 | | |
| | 1 | 339 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 340 | | usuarioId, |
| | 1 | 341 | | AccionEnum.IniciarCalculoPeriodo, |
| | 1 | 342 | | ContextoEnum.Liquidaciones, |
| | 1 | 343 | | _currentUser.Host, |
| | 1 | 344 | | entidad: nameof(Periodo), |
| | 1 | 345 | | entidadId: periodo.Id, |
| | 1 | 346 | | detalle: new { anio = periodo.Anio, mes = periodo.Mes }); |
| | | 347 | | |
| | 1 | 348 | | return (true, periodo, null); |
| | 2 | 349 | | } |
| | | 350 | | |
| | | 351 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> FinalizarCalculoAsync(long periodoId, bool exitoso, |
| | | 352 | | { |
| | 2 | 353 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 2 | 354 | | if (periodo is null) |
| | 0 | 355 | | return (false, null, "Período no encontrado"); |
| | | 356 | | |
| | 2 | 357 | | if (periodo.Estado != Periodo.EstadoEnCalculo) |
| | 0 | 358 | | return (false, null, $"Solo se puede finalizar el cálculo desde estado EN_CALCULO. Estado actual: {periodo.E |
| | | 359 | | |
| | 2 | 360 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 2 | 361 | | if (exitoso) |
| | | 362 | | { |
| | 1 | 363 | | periodo.Estado = Periodo.EstadoCalculada; |
| | 1 | 364 | | periodo.FechaCalculo = DateTime.UtcNow; |
| | | 365 | | } |
| | | 366 | | else |
| | | 367 | | { |
| | 1 | 368 | | periodo.Estado = Periodo.EstadoListaCalculo; |
| | | 369 | | } |
| | | 370 | | |
| | 2 | 371 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 372 | | |
| | 2 | 373 | | await _auditoriaService.LogAuditoriaAsync( |
| | 2 | 374 | | usuarioId, |
| | 2 | 375 | | AccionEnum.IniciarCalculoPeriodo, |
| | 2 | 376 | | ContextoEnum.Liquidaciones, |
| | 2 | 377 | | _currentUser.Host, |
| | 2 | 378 | | entidad: nameof(Periodo), |
| | 2 | 379 | | entidadId: periodo.Id, |
| | 2 | 380 | | detalle: new { exitoso, mensajeError }); |
| | | 381 | | |
| | 2 | 382 | | return (true, periodo, null); |
| | 2 | 383 | | } |
| | | 384 | | |
| | | 385 | | /// <summary> |
| | | 386 | | /// Reabre un período CALCULADA → ABIERTA para permitir correcciones y un nuevo cálculo. |
| | | 387 | | /// Los ítems de la versión anterior quedan en la BD como historial de auditoría. |
| | | 388 | | /// El próximo cálculo genera version = max_version_anterior + 1. |
| | | 389 | | /// </summary> |
| | | 390 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> ReabrirDesdeCalculadaAsync(long periodoId) |
| | | 391 | | { |
| | 0 | 392 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 0 | 393 | | if (periodo is null) |
| | 0 | 394 | | return (false, null, "Período no encontrado"); |
| | | 395 | | |
| | 0 | 396 | | if (periodo.Estado != Periodo.EstadoCalculada) |
| | 0 | 397 | | return (false, null, |
| | 0 | 398 | | $"Solo se puede reabrir desde estado CALCULADA. Estado actual: {periodo.Estado}"); |
| | | 399 | | |
| | 0 | 400 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 0 | 401 | | periodo.Estado = Periodo.EstadoAbierta; |
| | | 402 | | // Limpiamos la fecha de cálculo para que quede como un período nuevo en proceso |
| | 0 | 403 | | periodo.FechaCalculo = null; |
| | 0 | 404 | | periodo.UsuarioCalculoId = null; |
| | 0 | 405 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 406 | | |
| | 0 | 407 | | await _auditoriaService.LogAuditoriaAsync( |
| | 0 | 408 | | usuarioId, |
| | 0 | 409 | | AccionEnum.AbrirPeriodoLiquidacion, |
| | 0 | 410 | | ContextoEnum.Liquidaciones, |
| | 0 | 411 | | _currentUser.Host, |
| | 0 | 412 | | entidad: nameof(Periodo), |
| | 0 | 413 | | entidadId: periodo.Id, |
| | 0 | 414 | | detalle: new { anio = periodo.Anio, mes = periodo.Mes, motivo = "reapertura desde CALCULADA para corrección" |
| | | 415 | | |
| | 0 | 416 | | return (true, periodo, null); |
| | 0 | 417 | | } |
| | | 418 | | |
| | | 419 | | public async Task<(bool Exito, Periodo? Periodo, string? Error)> CerrarAsync(long periodoId) |
| | | 420 | | { |
| | 3 | 421 | | var periodo = await _periodosRepository.ObtenerPorIdAsync(periodoId); |
| | 3 | 422 | | if (periodo is null) |
| | 0 | 423 | | return (false, null, "Período no encontrado"); |
| | | 424 | | |
| | 3 | 425 | | if (periodo.Estado != Periodo.EstadoCalculada) |
| | 1 | 426 | | return (false, null, $"Solo se puede cerrar desde estado CALCULADA. Estado actual: {periodo.Estado}"); |
| | | 427 | | |
| | 2 | 428 | | var usuarioId = _currentUser.UserId ?? 0; |
| | 2 | 429 | | periodo.Estado = Periodo.EstadoCerrada; |
| | 2 | 430 | | periodo.FechaCierre = DateTime.UtcNow; |
| | 2 | 431 | | periodo.UsuarioCierreId = usuarioId; |
| | 2 | 432 | | await _periodosRepository.ActualizarAsync(periodo); |
| | | 433 | | |
| | 2 | 434 | | await _auditoriaService.LogAuditoriaAsync( |
| | 2 | 435 | | usuarioId, |
| | 2 | 436 | | AccionEnum.CerrarPeriodo, |
| | 2 | 437 | | ContextoEnum.Liquidaciones, |
| | 2 | 438 | | _currentUser.Host, |
| | 2 | 439 | | entidad: nameof(Periodo), |
| | 2 | 440 | | entidadId: periodo.Id, |
| | 2 | 441 | | detalle: new { anio = periodo.Anio, mes = periodo.Mes }); |
| | | 442 | | |
| | 2 | 443 | | return (true, periodo, null); |
| | 3 | 444 | | } |
| | | 445 | | |
| | | 446 | | private async Task<string> SerializarSnapshotAsync( |
| | | 447 | | short anio, |
| | | 448 | | short mes, |
| | | 449 | | ParametroPeriodo parametrosPeriodo, |
| | | 450 | | DateTime fechaInicioPeriodo, |
| | | 451 | | DateTime fechaFinPeriodo) |
| | | 452 | | { |
| | 5 | 453 | | var lotes = await _context.LotesCompensacion |
| | 5 | 454 | | .AsNoTracking() |
| | 5 | 455 | | .Where(l => l.Periodo.Anio == anio && l.Periodo.Mes == mes && l.Estado == "aprobado") |
| | 5 | 456 | | .Select(l => new |
| | 5 | 457 | | { |
| | 5 | 458 | | l.Id, |
| | 5 | 459 | | l.TipoCompensacionId, |
| | 5 | 460 | | l.PeriodoId, |
| | 5 | 461 | | l.Estado, |
| | 5 | 462 | | l.Fuente, |
| | 5 | 463 | | l.NombreArchivo, |
| | 5 | 464 | | l.HashArchivo, |
| | 5 | 465 | | l.UsuarioId, |
| | 5 | 466 | | l.AprobadoPor, |
| | 5 | 467 | | l.AprobadoEn |
| | 5 | 468 | | }) |
| | 5 | 469 | | .ToListAsync(); |
| | | 470 | | |
| | 5 | 471 | | var beneficios = await _context.BeneficiosSociales |
| | 5 | 472 | | .AsNoTracking() |
| | 5 | 473 | | .Where(b => b.Estado == "activo" && b.VigenteDesde <= fechaFinPeriodo && (b.VigenteHasta == null || b.Vigent |
| | 5 | 474 | | .Select(b => new |
| | 5 | 475 | | { |
| | 5 | 476 | | b.Id, |
| | 5 | 477 | | b.PersonaId, |
| | 5 | 478 | | b.TipoBeneficioId, |
| | 5 | 479 | | b.Cantidad, |
| | 5 | 480 | | b.VigenteDesde, |
| | 5 | 481 | | b.VigenteHasta, |
| | 5 | 482 | | b.Estado, |
| | 5 | 483 | | b.ClaveEvento, |
| | 5 | 484 | | b.FechaEvento, |
| | 5 | 485 | | b.RetroactividadPendiente |
| | 5 | 486 | | }) |
| | 5 | 487 | | .ToListAsync(); |
| | | 488 | | |
| | 5 | 489 | | var remuneraciones = await _context.RemuneracionesGrado |
| | 5 | 490 | | .AsNoTracking() |
| | 5 | 491 | | .Where(r => r.VigenteDesde <= fechaInicioPeriodo && (r.VigenteHasta == null || r.VigenteHasta >= fechaInicio |
| | 5 | 492 | | .Select(r => new |
| | 5 | 493 | | { |
| | 5 | 494 | | r.Id, |
| | 5 | 495 | | r.GradoId, |
| | 5 | 496 | | r.ItemId, |
| | 5 | 497 | | r.Monto, |
| | 5 | 498 | | r.VigenteDesde, |
| | 5 | 499 | | r.VigenteHasta |
| | 5 | 500 | | }) |
| | 5 | 501 | | .ToListAsync(); |
| | | 502 | | |
| | 5 | 503 | | var franjasIrpf = await _context.FranjasIrpf |
| | 5 | 504 | | .AsNoTracking() |
| | 5 | 505 | | .Where(f => f.VigenteDesde <= fechaInicioPeriodo && (f.VigenteHasta == null || f.VigenteHasta >= fechaInicio |
| | 5 | 506 | | .Select(f => new |
| | 5 | 507 | | { |
| | 5 | 508 | | f.Id, |
| | 5 | 509 | | f.NumeroFranja, |
| | 5 | 510 | | f.DesdeBpc, |
| | 5 | 511 | | f.HastaBpc, |
| | 5 | 512 | | f.Tasa, |
| | 5 | 513 | | f.VigenteDesde, |
| | 5 | 514 | | f.VigenteHasta |
| | 5 | 515 | | }) |
| | 5 | 516 | | .ToListAsync(); |
| | | 517 | | |
| | 5 | 518 | | var snapshot = new |
| | 5 | 519 | | { |
| | 5 | 520 | | anio, |
| | 5 | 521 | | mes, |
| | 5 | 522 | | fechaCreacion = DateTime.UtcNow, |
| | 5 | 523 | | parametros = new |
| | 5 | 524 | | { |
| | 5 | 525 | | parametrosPeriodo.Anio, |
| | 5 | 526 | | parametrosPeriodo.Mes, |
| | 5 | 527 | | parametrosPeriodo.BpcAnual, |
| | 5 | 528 | | parametrosPeriodo.TasaMontepioLeyVieja, |
| | 5 | 529 | | parametrosPeriodo.TasaMontepioLeyNueva, |
| | 5 | 530 | | parametrosPeriodo.TasaFonasa, |
| | 5 | 531 | | parametrosPeriodo.TasaFrl, |
| | 5 | 532 | | parametrosPeriodo.UmbralDeduccionBpc, |
| | 5 | 533 | | parametrosPeriodo.TasaDeduccionAlta, |
| | 5 | 534 | | parametrosPeriodo.TasaDeduccionBaja, |
| | 5 | 535 | | parametrosPeriodo.PorcentajeMinimoDeficit |
| | 5 | 536 | | }, |
| | 5 | 537 | | lotesCompensacion = lotes, |
| | 5 | 538 | | beneficiosSociales = beneficios, |
| | 5 | 539 | | remuneracionesGrado = remuneraciones, |
| | 5 | 540 | | franjasIrpf = franjasIrpf |
| | 5 | 541 | | }; |
| | | 542 | | |
| | 5 | 543 | | return JsonSerializer.Serialize(snapshot, new JsonSerializerOptions |
| | 5 | 544 | | { |
| | 5 | 545 | | PropertyNamingPolicy = JsonNamingPolicy.CamelCase, |
| | 5 | 546 | | WriteIndented = false |
| | 5 | 547 | | }); |
| | 5 | 548 | | } |
| | | 549 | | |
| | | 550 | | private static string CalcularHash(string contenidoJson) |
| | | 551 | | { |
| | 5 | 552 | | using var sha256 = SHA256.Create(); |
| | 5 | 553 | | var bytes = Encoding.UTF8.GetBytes(contenidoJson); |
| | 5 | 554 | | return Convert.ToHexString(sha256.ComputeHash(bytes)).ToLowerInvariant(); |
| | 5 | 555 | | } |
| | | 556 | | |
| | | 557 | | public async Task<List<Periodo>> ObtenerUltimosAsync(int cantidad = 6) |
| | | 558 | | { |
| | 0 | 559 | | return await _context.PeriodosLiquidacion |
| | 0 | 560 | | .AsNoTracking() |
| | 0 | 561 | | .OrderByDescending(p => p.Anio) |
| | 0 | 562 | | .ThenByDescending(p => p.Mes) |
| | 0 | 563 | | .Take(cantidad) |
| | 0 | 564 | | .ToListAsync(); |
| | 0 | 565 | | } |
| | | 566 | | } |