| | | 1 | | using FAU.API.Security; |
| | | 2 | | using FAU.Entidades; |
| | | 3 | | using FAU.Logica.DTOs; |
| | | 4 | | using FAU.Logica.Exceptions; |
| | | 5 | | using FAU.Logica.Services; |
| | | 6 | | using Microsoft.AspNetCore.Authorization; |
| | | 7 | | using Microsoft.AspNetCore.Mvc; |
| | | 8 | | |
| | | 9 | | namespace FAU.API.Controllers; |
| | | 10 | | |
| | | 11 | | [ApiController] |
| | | 12 | | [Route("api/liquidacion/[controller]")] |
| | | 13 | | [Authorize(Roles = "Administrador")] |
| | | 14 | | public class PeriodosController : ControllerBase |
| | | 15 | | { |
| | | 16 | | private readonly IPeriodoService _periodoService; |
| | | 17 | | private readonly ILiquidacionService _liquidacionService; |
| | | 18 | | private readonly ILogger<PeriodosController> _logger; |
| | | 19 | | |
| | 19 | 20 | | public PeriodosController( |
| | 19 | 21 | | IPeriodoService periodoService, |
| | 19 | 22 | | ILiquidacionService liquidacionService, |
| | 19 | 23 | | ILogger<PeriodosController> logger) |
| | | 24 | | { |
| | 19 | 25 | | _periodoService = periodoService; |
| | 19 | 26 | | _liquidacionService = liquidacionService; |
| | 19 | 27 | | _logger = logger; |
| | 19 | 28 | | } |
| | | 29 | | |
| | | 30 | | [HttpPost] |
| | | 31 | | public async Task<IActionResult> AbrirPeriodo([FromBody] AbrirPeriodoRequest request) |
| | | 32 | | { |
| | | 33 | | try |
| | | 34 | | { |
| | 3 | 35 | | if (!ModelState.IsValid) |
| | | 36 | | { |
| | 0 | 37 | | return BadRequest(ApiResponse<string>.ErrorResult("Solicitud de apertura de período inválida")); |
| | | 38 | | } |
| | | 39 | | |
| | 3 | 40 | | var (success, periodo, error) = await _periodoService.AbrirPeriodoAsync(request.Anio, request.Mes); |
| | | 41 | | |
| | 3 | 42 | | if (!success) |
| | | 43 | | { |
| | 2 | 44 | | if (error?.Contains("Ya existe un período activo", StringComparison.OrdinalIgnoreCase) == true) |
| | | 45 | | { |
| | 1 | 46 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 47 | | } |
| | | 48 | | |
| | 1 | 49 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al abrir el período")); |
| | | 50 | | } |
| | | 51 | | |
| | 1 | 52 | | var dto = MapearPeriodo(periodo!); |
| | 1 | 53 | | return CreatedAtAction(nameof(GetPeriodo), new { id = periodo!.Id }, ApiResponse<PeriodoDto>.SuccessResult(d |
| | | 54 | | } |
| | 0 | 55 | | catch (Exception ex) |
| | | 56 | | { |
| | 0 | 57 | | _logger.LogError(ex, "Error al abrir período"); |
| | 0 | 58 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 59 | | } |
| | 3 | 60 | | } |
| | | 61 | | |
| | | 62 | | [HttpGet] |
| | | 63 | | public async Task<IActionResult> GetUltimos([FromQuery] int cantidad = 6) |
| | | 64 | | { |
| | | 65 | | try |
| | | 66 | | { |
| | 0 | 67 | | var periodos = await _periodoService.ObtenerUltimosAsync(Math.Min(cantidad, 12)); |
| | 0 | 68 | | return Ok(ApiResponse<List<PeriodoDto>>.SuccessResult(periodos.Select(MapearPeriodo).ToList())); |
| | | 69 | | } |
| | 0 | 70 | | catch (Exception ex) |
| | | 71 | | { |
| | 0 | 72 | | _logger.LogError(ex, "Error al obtener últimos períodos"); |
| | 0 | 73 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 74 | | } |
| | 0 | 75 | | } |
| | | 76 | | |
| | | 77 | | [HttpGet("activo")] |
| | | 78 | | public async Task<IActionResult> GetPeriodoActivo() |
| | | 79 | | { |
| | | 80 | | try |
| | | 81 | | { |
| | 2 | 82 | | var periodo = await _periodoService.ObtenerEnCursoAsync(); |
| | 2 | 83 | | if (periodo == null) |
| | | 84 | | { |
| | 1 | 85 | | return NotFound(ApiResponse<string>.ErrorResult("No hay un período activo")); |
| | | 86 | | } |
| | | 87 | | |
| | 1 | 88 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult(MapearPeriodo(periodo))); |
| | | 89 | | } |
| | 0 | 90 | | catch (Exception ex) |
| | | 91 | | { |
| | 0 | 92 | | _logger.LogError(ex, "Error al obtener período activo"); |
| | 0 | 93 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 94 | | } |
| | 2 | 95 | | } |
| | | 96 | | |
| | | 97 | | [HttpGet("{id}")] |
| | | 98 | | public async Task<IActionResult> GetPeriodo(long id) |
| | | 99 | | { |
| | | 100 | | try |
| | | 101 | | { |
| | 2 | 102 | | var periodo = await _periodoService.ObtenerPorIdAsync(id); |
| | 2 | 103 | | if (periodo == null) |
| | | 104 | | { |
| | 1 | 105 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | | 106 | | } |
| | | 107 | | |
| | 1 | 108 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult(MapearPeriodo(periodo))); |
| | | 109 | | } |
| | 0 | 110 | | catch (Exception ex) |
| | | 111 | | { |
| | 0 | 112 | | _logger.LogError(ex, "Error al obtener período {Id}", id); |
| | 0 | 113 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 114 | | } |
| | 2 | 115 | | } |
| | | 116 | | |
| | | 117 | | [HttpGet("{id}/precondiciones")] |
| | | 118 | | public async Task<IActionResult> GetPrecondiciones(long id) |
| | | 119 | | { |
| | | 120 | | try |
| | | 121 | | { |
| | 0 | 122 | | var precondiciones = await _periodoService.ObtenerPrecondicionesAsync(id); |
| | 0 | 123 | | if (precondiciones == null) |
| | 0 | 124 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | 0 | 125 | | return Ok(ApiResponse<PrecondicionesDto>.SuccessResult(precondiciones)); |
| | | 126 | | } |
| | 0 | 127 | | catch (Exception ex) |
| | | 128 | | { |
| | 0 | 129 | | _logger.LogError(ex, "Error al obtener precondiciones del período {Id}", id); |
| | 0 | 130 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 131 | | } |
| | 0 | 132 | | } |
| | | 133 | | |
| | | 134 | | [HttpGet("{id}/validar-insumos")] |
| | | 135 | | public async Task<IActionResult> ValidarInsumos(long id) |
| | | 136 | | { |
| | | 137 | | try |
| | | 138 | | { |
| | 0 | 139 | | var validacion = await _periodoService.ValidarInsumosAsync(id); |
| | 0 | 140 | | if (validacion == null) |
| | 0 | 141 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | 0 | 142 | | return Ok(ApiResponse<ValidacionInsumosDto>.SuccessResult(validacion)); |
| | | 143 | | } |
| | 0 | 144 | | catch (Exception ex) |
| | | 145 | | { |
| | 0 | 146 | | _logger.LogError(ex, "Error al validar insumos del período {Id}", id); |
| | 0 | 147 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 148 | | } |
| | 0 | 149 | | } |
| | | 150 | | |
| | | 151 | | [HttpPost("{id}/cerrar-insumos")] |
| | | 152 | | public async Task<IActionResult> CerrarInsumos(long id, [FromBody] CerrarInsumosRequest? request = null) |
| | | 153 | | { |
| | | 154 | | try |
| | | 155 | | { |
| | 4 | 156 | | var (success, periodo, validacion, error) = |
| | 4 | 157 | | await _periodoService.CerrarInsumosAsync(id, request?.Confirmaciones); |
| | | 158 | | |
| | 4 | 159 | | if (!success) |
| | | 160 | | { |
| | 3 | 161 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | 1 | 162 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | 2 | 163 | | if (error?.Contains("Solo se puede", StringComparison.OrdinalIgnoreCase) == true) |
| | 1 | 164 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | 1 | 165 | | if (validacion != null) |
| | 1 | 166 | | return UnprocessableEntity(validacion); |
| | 0 | 167 | | return UnprocessableEntity(ApiResponse<string>.ErrorResult(error ?? "Error al cerrar insumos")); |
| | | 168 | | } |
| | | 169 | | |
| | 1 | 170 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult(MapearPeriodo(periodo!), "Insumos cerrados. Período listo pa |
| | | 171 | | } |
| | 0 | 172 | | catch (Exception ex) |
| | | 173 | | { |
| | 0 | 174 | | _logger.LogError(ex, "Error al cerrar insumos del período {Id}", id); |
| | 0 | 175 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 176 | | } |
| | 4 | 177 | | } |
| | | 178 | | |
| | | 179 | | [HttpPost("{id}/reabrir-insumos")] |
| | | 180 | | [RequirePermission(PermisoEnum.ReabrirPeriodo)] |
| | | 181 | | public async Task<IActionResult> ReabrirInsumos(long id) |
| | | 182 | | { |
| | | 183 | | try |
| | | 184 | | { |
| | 2 | 185 | | var (success, periodo, error) = await _periodoService.ReabrirInsumosAsync(id); |
| | | 186 | | |
| | 2 | 187 | | if (!success) |
| | | 188 | | { |
| | 1 | 189 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | 0 | 190 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | 1 | 191 | | return Conflict(ApiResponse<string>.ErrorResult(error ?? "Error al reabrir insumos")); |
| | | 192 | | } |
| | | 193 | | |
| | 1 | 194 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult(MapearPeriodo(periodo!), "Insumos reabiertos. Período en est |
| | | 195 | | } |
| | 0 | 196 | | catch (Exception ex) |
| | | 197 | | { |
| | 0 | 198 | | _logger.LogError(ex, "Error al reabrir insumos del período {Id}", id); |
| | 0 | 199 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 200 | | } |
| | 2 | 201 | | } |
| | | 202 | | |
| | | 203 | | [HttpPost("{id}/reabrir")] |
| | | 204 | | [RequirePermission(PermisoEnum.ReabrirPeriodo)] |
| | | 205 | | public async Task<IActionResult> ReabrirDesdeCalculada(long id) |
| | | 206 | | { |
| | | 207 | | try |
| | | 208 | | { |
| | 0 | 209 | | var (success, periodo, error) = await _periodoService.ReabrirDesdeCalculadaAsync(id); |
| | | 210 | | |
| | 0 | 211 | | if (!success) |
| | | 212 | | { |
| | 0 | 213 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | 0 | 214 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | 0 | 215 | | return Conflict(ApiResponse<string>.ErrorResult(error ?? "Error al reabrir período")); |
| | | 216 | | } |
| | | 217 | | |
| | 0 | 218 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult( |
| | 0 | 219 | | MapearPeriodo(periodo!), |
| | 0 | 220 | | "Período reabierto. Realizá las correcciones y volvé a calcular. El próximo cálculo generará una nueva v |
| | | 221 | | } |
| | 0 | 222 | | catch (Exception ex) |
| | | 223 | | { |
| | 0 | 224 | | _logger.LogError(ex, "Error al reabrir período {Id}", id); |
| | 0 | 225 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 226 | | } |
| | 0 | 227 | | } |
| | | 228 | | |
| | | 229 | | [HttpPost("{id}/calcular")] |
| | | 230 | | public async Task<IActionResult> Calcular(long id) |
| | | 231 | | { |
| | | 232 | | try |
| | | 233 | | { |
| | | 234 | | // 1. Marcar período como EN_CALCULO |
| | 3 | 235 | | var (success, periodo, error) = await _periodoService.IniciarCalculoAsync(id); |
| | 3 | 236 | | if (!success) |
| | | 237 | | { |
| | 2 | 238 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | 1 | 239 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | 1 | 240 | | return Conflict(ApiResponse<string>.ErrorResult(error ?? "Error al iniciar cálculo")); |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | // 2. Ejecutar el cálculo — la versión se determina automáticamente (max+1) |
| | 1 | 244 | | var (exitoCalculo, errorCalculo, version) = await _liquidacionService.GenerarLiquidacionAsync(id); |
| | | 245 | | |
| | | 246 | | // 3. Finalizar — éxito o error vuelve a LISTA_CALCULO para reintentar |
| | 1 | 247 | | await _periodoService.FinalizarCalculoAsync(id, exitoCalculo); |
| | | 248 | | |
| | 1 | 249 | | if (!exitoCalculo) |
| | 0 | 250 | | return StatusCode(500, ApiResponse<string>.ErrorResult(errorCalculo ?? "Error durante el cálculo")); |
| | | 251 | | |
| | 1 | 252 | | var periodoFinal = await _periodoService.ObtenerPorIdAsync(id); |
| | 1 | 253 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult( |
| | 1 | 254 | | MapearPeriodo(periodoFinal!), |
| | 1 | 255 | | $"Liquidación versión {version} generada correctamente.")); |
| | | 256 | | } |
| | 0 | 257 | | catch (Exception ex) |
| | | 258 | | { |
| | 0 | 259 | | await _periodoService.FinalizarCalculoAsync(id, exitoso: false).ConfigureAwait(false); |
| | 0 | 260 | | _logger.LogError(ex, "Error al calcular período {Id}", id); |
| | 0 | 261 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 262 | | } |
| | 3 | 263 | | } |
| | | 264 | | |
| | | 265 | | [HttpPost("{id}/cerrar")] |
| | | 266 | | [RequirePermission(PermisoEnum.CerrarPeriodo)] |
| | | 267 | | public async Task<IActionResult> Cerrar(long id) |
| | | 268 | | { |
| | | 269 | | try |
| | | 270 | | { |
| | 3 | 271 | | var (success, periodo, error) = await _periodoService.CerrarAsync(id); |
| | | 272 | | |
| | 3 | 273 | | if (!success) |
| | | 274 | | { |
| | 2 | 275 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | 1 | 276 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | 1 | 277 | | return Conflict(ApiResponse<string>.ErrorResult(error ?? "Error al cerrar período")); |
| | | 278 | | } |
| | | 279 | | |
| | 1 | 280 | | return Ok(ApiResponse<PeriodoDto>.SuccessResult(MapearPeriodo(periodo!), "Período cerrado definitivamente.") |
| | | 281 | | } |
| | 0 | 282 | | catch (Exception ex) |
| | | 283 | | { |
| | 0 | 284 | | _logger.LogError(ex, "Error al cerrar período {Id}", id); |
| | 0 | 285 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 286 | | } |
| | 3 | 287 | | } |
| | | 288 | | |
| | | 289 | | private static PeriodoDto MapearPeriodo(Periodo periodo) |
| | | 290 | | { |
| | 7 | 291 | | return new PeriodoDto |
| | 7 | 292 | | { |
| | 7 | 293 | | Id = periodo.Id, |
| | 7 | 294 | | Anio = periodo.Anio, |
| | 7 | 295 | | Mes = periodo.Mes, |
| | 7 | 296 | | Estado = periodo.Estado, |
| | 7 | 297 | | SnapshotId = periodo.SnapshotId, |
| | 7 | 298 | | FechaApertura = periodo.FechaApertura, |
| | 7 | 299 | | UsuarioApertura = periodo.UsuarioApertura, |
| | 7 | 300 | | HashSnapshot = periodo.HashSnapshot, |
| | 7 | 301 | | FechaCierreInsumos = periodo.FechaCierreInsumos, |
| | 7 | 302 | | UsuarioCierreInsumosId = periodo.UsuarioCierreInsumosId, |
| | 7 | 303 | | FechaCalculo = periodo.FechaCalculo, |
| | 7 | 304 | | FechaCierre = periodo.FechaCierre, |
| | 7 | 305 | | UsuarioCierreId = periodo.UsuarioCierreId |
| | 7 | 306 | | }; |
| | | 307 | | } |
| | | 308 | | } |