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