| | | 1 | | using FAU.Entidades; |
| | | 2 | | using FAU.Logica.DTOs; |
| | | 3 | | using FAU.Logica.Services; |
| | | 4 | | using Microsoft.AspNetCore.Authorization; |
| | | 5 | | using Microsoft.AspNetCore.Http; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | |
| | | 8 | | namespace FAU.API.Controllers; |
| | | 9 | | |
| | | 10 | | [ApiController] |
| | | 11 | | [Route("api/liquidacion/recibos")] |
| | | 12 | | [Authorize] |
| | | 13 | | [Produces("application/json")] |
| | | 14 | | public class RecibosController : ControllerBase |
| | | 15 | | { |
| | | 16 | | private readonly IReciboService _reciboService; |
| | | 17 | | private readonly IPeriodoService _periodoService; |
| | | 18 | | private readonly IAuditoriaService _auditoriaService; |
| | | 19 | | private readonly ICurrentUserContext _currentUser; |
| | | 20 | | private readonly ILogger<RecibosController> _logger; |
| | | 21 | | |
| | 12 | 22 | | public RecibosController( |
| | 12 | 23 | | IReciboService reciboService, |
| | 12 | 24 | | IPeriodoService periodoService, |
| | 12 | 25 | | IAuditoriaService auditoriaService, |
| | 12 | 26 | | ICurrentUserContext currentUser, |
| | 12 | 27 | | ILogger<RecibosController> logger) |
| | | 28 | | { |
| | 12 | 29 | | _reciboService = reciboService; |
| | 12 | 30 | | _periodoService = periodoService; |
| | 12 | 31 | | _auditoriaService = auditoriaService; |
| | 12 | 32 | | _currentUser = currentUser; |
| | 12 | 33 | | _logger = logger; |
| | 12 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Lista los recibos disponibles para un período cerrado, con filtros opcionales. |
| | | 38 | | /// GET /api/liquidacion/recibos/{periodoId} |
| | | 39 | | /// </summary> |
| | | 40 | | [HttpGet("{periodoId}")] |
| | | 41 | | [Authorize(Roles = "Administrador,Supervisor,Usuario")] |
| | | 42 | | [ProducesResponseType(typeof(ApiResponse<List<ReciboResumenDto>>), StatusCodes.Status200OK)] |
| | | 43 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 44 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 45 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 46 | | public async Task<IActionResult> GetResumenes( |
| | | 47 | | long periodoId, |
| | | 48 | | [FromQuery] string? regimen = null, |
| | | 49 | | [FromQuery] long? programaId = null, |
| | | 50 | | [FromQuery] long? unidadId = null, |
| | | 51 | | [FromQuery] string? cedula = null) |
| | | 52 | | { |
| | | 53 | | try |
| | | 54 | | { |
| | 3 | 55 | | var periodo = await _periodoService.ObtenerPorIdAsync(periodoId); |
| | 3 | 56 | | if (periodo == null) |
| | 1 | 57 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | | 58 | | |
| | 2 | 59 | | if (periodo.Estado != Periodo.EstadoCerrada) |
| | 1 | 60 | | return Conflict(ApiResponse<string>.ErrorResult( |
| | 1 | 61 | | "El período no está cerrado; los recibos solo están disponibles para períodos en estado CERRADA")); |
| | | 62 | | |
| | 1 | 63 | | var filtro = new ReciboFiltroRequest |
| | 1 | 64 | | { |
| | 1 | 65 | | Regimen = regimen, |
| | 1 | 66 | | ProgramaId = programaId, |
| | 1 | 67 | | UnidadId = unidadId, |
| | 1 | 68 | | Cedula = cedula |
| | 1 | 69 | | }; |
| | | 70 | | |
| | 1 | 71 | | var resumenes = await _reciboService.ObtenerResumenesAsync(periodoId, filtro); |
| | 1 | 72 | | return Ok(ApiResponse<List<ReciboResumenDto>>.SuccessResult(resumenes)); |
| | | 73 | | } |
| | 0 | 74 | | catch (Exception ex) |
| | | 75 | | { |
| | 0 | 76 | | _logger.LogError(ex, "Error al obtener resúmenes de recibos para período {PeriodoId}", periodoId); |
| | 0 | 77 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 78 | | } |
| | 3 | 79 | | } |
| | | 80 | | |
| | | 81 | | /// <summary> |
| | | 82 | | /// Retorna los datos completos de un recibo individual. |
| | | 83 | | /// GET /api/liquidacion/recibos/{periodoId}/{relacionId} |
| | | 84 | | /// </summary> |
| | | 85 | | [HttpGet("{periodoId}/{relacionId}")] |
| | | 86 | | [Authorize(Roles = "Administrador,Supervisor,Usuario")] |
| | | 87 | | [ProducesResponseType(typeof(ApiResponse<ReciboDto>), StatusCodes.Status200OK)] |
| | | 88 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 89 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 90 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 91 | | public async Task<IActionResult> GetRecibo(long periodoId, long relacionId) |
| | | 92 | | { |
| | | 93 | | try |
| | | 94 | | { |
| | 4 | 95 | | var periodo = await _periodoService.ObtenerPorIdAsync(periodoId); |
| | 4 | 96 | | if (periodo == null) |
| | 1 | 97 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | | 98 | | |
| | 3 | 99 | | if (periodo.Estado != Periodo.EstadoCerrada) |
| | 1 | 100 | | return Conflict(ApiResponse<string>.ErrorResult( |
| | 1 | 101 | | "El período no está cerrado; los recibos solo están disponibles para períodos en estado CERRADA")); |
| | | 102 | | |
| | 2 | 103 | | var recibo = await _reciboService.ObtenerReciboAsync(periodoId, relacionId); |
| | 2 | 104 | | if (recibo == null) |
| | 1 | 105 | | return NotFound(ApiResponse<string>.ErrorResult("No se encontró liquidación para el funcionario en este |
| | | 106 | | |
| | 1 | 107 | | return Ok(ApiResponse<ReciboDto>.SuccessResult(recibo)); |
| | | 108 | | } |
| | 0 | 109 | | catch (Exception ex) |
| | | 110 | | { |
| | 0 | 111 | | _logger.LogError(ex, "Error al obtener recibo {RelacionId} del período {PeriodoId}", relacionId, periodoId); |
| | 0 | 112 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 113 | | } |
| | 4 | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Descarga el recibo de un funcionario como PDF. |
| | | 118 | | /// GET /api/liquidacion/recibos/{periodoId}/{relacionId}/pdf |
| | | 119 | | /// </summary> |
| | | 120 | | [HttpGet("{periodoId}/{relacionId}/pdf")] |
| | | 121 | | [Authorize(Roles = "Administrador,Supervisor,Usuario")] |
| | | 122 | | [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)] |
| | | 123 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 124 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 125 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 126 | | public async Task<IActionResult> GetReciboPdf(long periodoId, long relacionId) |
| | | 127 | | { |
| | | 128 | | try |
| | | 129 | | { |
| | 3 | 130 | | var periodo = await _periodoService.ObtenerPorIdAsync(periodoId); |
| | 3 | 131 | | if (periodo == null) |
| | 1 | 132 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | | 133 | | |
| | 2 | 134 | | if (periodo.Estado != Periodo.EstadoCerrada) |
| | 1 | 135 | | return Conflict(ApiResponse<string>.ErrorResult( |
| | 1 | 136 | | "El período no está cerrado; los recibos solo están disponibles para períodos en estado CERRADA")); |
| | | 137 | | |
| | 1 | 138 | | var recibo = await _reciboService.ObtenerReciboAsync(periodoId, relacionId); |
| | 1 | 139 | | if (recibo == null) |
| | 1 | 140 | | return NotFound(ApiResponse<string>.ErrorResult("No se encontró liquidación para el funcionario en este |
| | | 141 | | |
| | 0 | 142 | | var pdfBytes = await _reciboService.GenerarPdfAsync(periodoId, relacionId); |
| | | 143 | | |
| | 0 | 144 | | await _auditoriaService.LogAuditoriaAsync( |
| | 0 | 145 | | _currentUser.UserId ?? 0, |
| | 0 | 146 | | AccionEnum.GenerarReciboIndividual, |
| | 0 | 147 | | ContextoEnum.Liquidaciones, |
| | 0 | 148 | | _currentUser.Host, |
| | 0 | 149 | | entidad: "Recibo", |
| | 0 | 150 | | entidadId: periodoId, |
| | 0 | 151 | | detalle: new { periodoId, relacionId }); |
| | | 152 | | |
| | 0 | 153 | | var fileName = $"recibo_{periodo.Anio}_{periodo.Mes:D2}_{recibo.Cedula}.pdf"; |
| | 0 | 154 | | return File(pdfBytes, "application/pdf", fileName); |
| | | 155 | | } |
| | 0 | 156 | | catch (Exception ex) |
| | | 157 | | { |
| | 0 | 158 | | _logger.LogError(ex, "Error al generar PDF del recibo {RelacionId} del período {PeriodoId}", relacionId, per |
| | 0 | 159 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 160 | | } |
| | 3 | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Descarga el lote completo de recibos de un período como ZIP. |
| | | 165 | | /// GET /api/liquidacion/recibos/{periodoId}/lote |
| | | 166 | | /// </summary> |
| | | 167 | | [HttpGet("{periodoId}/lote")] |
| | | 168 | | [Authorize(Roles = "Administrador,Supervisor,Usuario")] |
| | | 169 | | [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)] |
| | | 170 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 171 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 172 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 173 | | public async Task<IActionResult> GetLote( |
| | | 174 | | long periodoId, |
| | | 175 | | [FromQuery] string? regimen = null, |
| | | 176 | | [FromQuery] long? programaId = null, |
| | | 177 | | [FromQuery] long? unidadId = null) |
| | | 178 | | { |
| | | 179 | | try |
| | | 180 | | { |
| | 2 | 181 | | var periodo = await _periodoService.ObtenerPorIdAsync(periodoId); |
| | 2 | 182 | | if (periodo == null) |
| | 1 | 183 | | return NotFound(ApiResponse<string>.ErrorResult("Período no encontrado")); |
| | | 184 | | |
| | 1 | 185 | | if (periodo.Estado != Periodo.EstadoCerrada) |
| | 1 | 186 | | return Conflict(ApiResponse<string>.ErrorResult( |
| | 1 | 187 | | "El período no está cerrado; los recibos solo están disponibles para períodos en estado CERRADA")); |
| | | 188 | | |
| | 0 | 189 | | var filtro = new ReciboFiltroRequest |
| | 0 | 190 | | { |
| | 0 | 191 | | Regimen = regimen, |
| | 0 | 192 | | ProgramaId = programaId, |
| | 0 | 193 | | UnidadId = unidadId |
| | 0 | 194 | | }; |
| | | 195 | | |
| | 0 | 196 | | var zipStream = await _reciboService.GenerarLoteZipAsync(periodoId, filtro); |
| | | 197 | | |
| | | 198 | | // Contar recibos para auditoría (el stream ya fue generado) |
| | 0 | 199 | | var resumenes = await _reciboService.ObtenerResumenesAsync(periodoId, filtro); |
| | | 200 | | |
| | 0 | 201 | | await _auditoriaService.LogAuditoriaAsync( |
| | 0 | 202 | | _currentUser.UserId ?? 0, |
| | 0 | 203 | | AccionEnum.GenerarRecibosLote, |
| | 0 | 204 | | ContextoEnum.Liquidaciones, |
| | 0 | 205 | | _currentUser.Host, |
| | 0 | 206 | | entidad: "Recibo", |
| | 0 | 207 | | entidadId: periodoId, |
| | 0 | 208 | | detalle: new { periodoId, cantidad = resumenes.Count }); |
| | | 209 | | |
| | 0 | 210 | | var fileName = $"recibos_{periodo.Anio}_{periodo.Mes:D2}.zip"; |
| | 0 | 211 | | return File(zipStream, "application/zip", fileName); |
| | | 212 | | } |
| | 0 | 213 | | catch (Exception ex) |
| | | 214 | | { |
| | 0 | 215 | | _logger.LogError(ex, "Error al generar lote de recibos del período {PeriodoId}", periodoId); |
| | 0 | 216 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 217 | | } |
| | 2 | 218 | | } |
| | | 219 | | } |