| | | 1 | | using System.Security.Claims; |
| | | 2 | | using FAU.Logica.DTOs; |
| | | 3 | | using FAU.Logica.Exceptions; |
| | | 4 | | using FAU.Logica.Services; |
| | | 5 | | using Microsoft.AspNetCore.Authorization; |
| | | 6 | | using Microsoft.AspNetCore.Http; |
| | | 7 | | using Microsoft.AspNetCore.Mvc; |
| | | 8 | | |
| | | 9 | | namespace FAU.API.Controllers; |
| | | 10 | | |
| | | 11 | | [ApiController] |
| | | 12 | | [Route("api/beneficios-sociales")] |
| | | 13 | | [Authorize(Roles = "Administrador")] |
| | | 14 | | [Produces("application/json")] |
| | | 15 | | public class BeneficiosSocialesController : ControllerBase |
| | | 16 | | { |
| | | 17 | | private readonly IBeneficioSocialService _beneficioSocialService; |
| | | 18 | | private readonly ILogger<BeneficiosSocialesController> _logger; |
| | | 19 | | |
| | 10 | 20 | | public BeneficiosSocialesController( |
| | 10 | 21 | | IBeneficioSocialService beneficioSocialService, |
| | 10 | 22 | | ILogger<BeneficiosSocialesController> logger) |
| | | 23 | | { |
| | 10 | 24 | | _beneficioSocialService = beneficioSocialService; |
| | 10 | 25 | | _logger = logger; |
| | 10 | 26 | | } |
| | | 27 | | |
| | | 28 | | [HttpGet] |
| | | 29 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 30 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 31 | | public async Task<IActionResult> GetBeneficiosSociales( |
| | | 32 | | [FromQuery] int pagina = 1, |
| | | 33 | | [FromQuery] int tamano = 10, |
| | | 34 | | [FromQuery] long? personaId = null, |
| | | 35 | | [FromQuery] string? estado = null) |
| | | 36 | | { |
| | | 37 | | try |
| | | 38 | | { |
| | 1 | 39 | | var resultado = await _beneficioSocialService.ObtenerPaginadoAsync(pagina, tamano, personaId, estado); |
| | 1 | 40 | | return Ok(ApiResponse<object>.SuccessResult(new |
| | 1 | 41 | | { |
| | 1 | 42 | | items = resultado.Items, |
| | 1 | 43 | | page = resultado.Page, |
| | 1 | 44 | | pageSize = resultado.PageSize, |
| | 1 | 45 | | totalCount = resultado.TotalCount, |
| | 1 | 46 | | totalPages = resultado.TotalPages, |
| | 1 | 47 | | hasPreviousPage = resultado.HasPreviousPage, |
| | 1 | 48 | | hasNextPage = resultado.HasNextPage |
| | 1 | 49 | | })); |
| | | 50 | | } |
| | 0 | 51 | | catch (Exception ex) |
| | | 52 | | { |
| | 0 | 53 | | _logger.LogError(ex, "Error al listar beneficios sociales"); |
| | 0 | 54 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 55 | | } |
| | 1 | 56 | | } |
| | | 57 | | |
| | | 58 | | [HttpGet("{id:long}")] |
| | | 59 | | [ProducesResponseType(typeof(ApiResponse<BeneficioSocialDto>), StatusCodes.Status200OK)] |
| | | 60 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 61 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 62 | | public async Task<IActionResult> GetBeneficioSocial(long id) |
| | | 63 | | { |
| | | 64 | | try |
| | | 65 | | { |
| | 2 | 66 | | var beneficio = await _beneficioSocialService.ObtenerPorIdAsync(id); |
| | 2 | 67 | | if (beneficio == null) |
| | | 68 | | { |
| | 1 | 69 | | return NotFound(ApiResponse<string>.ErrorResult("Beneficio social no encontrado")); |
| | | 70 | | } |
| | | 71 | | |
| | 1 | 72 | | return Ok(ApiResponse<BeneficioSocialDto>.SuccessResult(beneficio)); |
| | | 73 | | } |
| | 0 | 74 | | catch (Exception ex) |
| | | 75 | | { |
| | 0 | 76 | | _logger.LogError(ex, "Error al obtener beneficio social {Id}", id); |
| | 0 | 77 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 78 | | } |
| | 2 | 79 | | } |
| | | 80 | | |
| | | 81 | | [HttpPost] |
| | | 82 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)] |
| | | 83 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 84 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 85 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 86 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 87 | | public async Task<IActionResult> CreateBeneficioSocial([FromBody] CrearBeneficioSocialRequest request) |
| | | 88 | | { |
| | | 89 | | try |
| | | 90 | | { |
| | 3 | 91 | | var (exito, resultado, error) = await _beneficioSocialService.CrearAsync(request, ObtenerUsuarioIdActual(), |
| | 3 | 92 | | if (!exito) |
| | | 93 | | { |
| | 2 | 94 | | return MapearError(error, "Error al crear beneficio social"); |
| | | 95 | | } |
| | | 96 | | |
| | 1 | 97 | | return CreatedAtAction( |
| | 1 | 98 | | nameof(GetBeneficioSocial), |
| | 1 | 99 | | new { id = resultado!.Id }, |
| | 1 | 100 | | ApiResponse<object>.SuccessResult(new { id = resultado.Id, creado = true }, "Beneficio social creado exi |
| | | 101 | | } |
| | 0 | 102 | | catch (PeriodoBloqueadoException ex) |
| | | 103 | | { |
| | 0 | 104 | | return Conflict(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 105 | | } |
| | 0 | 106 | | catch (Exception ex) |
| | | 107 | | { |
| | 0 | 108 | | _logger.LogError(ex, "Error al crear beneficio social"); |
| | 0 | 109 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 110 | | } |
| | 3 | 111 | | } |
| | | 112 | | |
| | | 113 | | [HttpPut("{id:long}")] |
| | | 114 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 115 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 116 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 117 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 118 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 119 | | public async Task<IActionResult> UpdateBeneficioSocial(long id, [FromBody] ActualizarBeneficioSocialRequest request) |
| | | 120 | | { |
| | | 121 | | try |
| | | 122 | | { |
| | 2 | 123 | | var (exito, resultado, error) = await _beneficioSocialService.ActualizarAsync(id, request, ObtenerUsuarioIdA |
| | 2 | 124 | | if (!exito) |
| | | 125 | | { |
| | 2 | 126 | | return MapearError(error, "Error al actualizar beneficio social"); |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true, id = resultado!.Id }, "Beneficio socia |
| | | 130 | | } |
| | 0 | 131 | | catch (Exception ex) |
| | | 132 | | { |
| | 0 | 133 | | _logger.LogError(ex, "Error al actualizar beneficio social {Id}", id); |
| | 0 | 134 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 135 | | } |
| | 2 | 136 | | } |
| | | 137 | | |
| | | 138 | | [HttpPost("{id:long}/documento")] |
| | | 139 | | [RequestSizeLimit(20_000_000)] |
| | | 140 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 141 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 142 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 143 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 144 | | public async Task<IActionResult> SubirDocumento(long id, IFormFile file) |
| | | 145 | | { |
| | 0 | 146 | | if (file == null || file.Length == 0) |
| | 0 | 147 | | return BadRequest(ApiResponse<string>.ErrorResult("Archivo requerido")); |
| | | 148 | | |
| | | 149 | | try |
| | | 150 | | { |
| | 0 | 151 | | await using var stream = file.OpenReadStream(); |
| | 0 | 152 | | var ruta = await _beneficioSocialService.SubirDocumentoAsync( |
| | 0 | 153 | | id, stream, file.FileName, file.ContentType, ObtenerUsuarioIdActual()); |
| | 0 | 154 | | return Ok(ApiResponse<object>.SuccessResult(new { rutaRelativa = ruta, subido = true }, "Documento subido ex |
| | 0 | 155 | | } |
| | 0 | 156 | | catch (ArgumentException ex) |
| | | 157 | | { |
| | 0 | 158 | | return ex.Message.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) |
| | 0 | 159 | | ? NotFound(ApiResponse<string>.ErrorResult(ex.Message)) |
| | 0 | 160 | | : BadRequest(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 161 | | } |
| | 0 | 162 | | catch (Exception ex) |
| | | 163 | | { |
| | 0 | 164 | | _logger.LogError(ex, "Error al subir documento de beneficio {Id}", id); |
| | 0 | 165 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 166 | | } |
| | 0 | 167 | | } |
| | | 168 | | |
| | | 169 | | [HttpGet("{id:long}/documento")] |
| | | 170 | | [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)] |
| | | 171 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 172 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 173 | | public async Task<IActionResult> DescargarDocumento(long id, [FromQuery] bool inline = false) |
| | | 174 | | { |
| | | 175 | | try |
| | | 176 | | { |
| | 0 | 177 | | var (stream, nombre, contentType) = await _beneficioSocialService.DescargarDocumentoAsync(id); |
| | 0 | 178 | | var disposition = inline ? "inline" : "attachment"; |
| | 0 | 179 | | Response.Headers.Append("Content-Disposition", $"{disposition}; filename=\"{nombre}\""); |
| | 0 | 180 | | return File(stream, contentType); |
| | | 181 | | } |
| | 0 | 182 | | catch (KeyNotFoundException ex) |
| | | 183 | | { |
| | 0 | 184 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 185 | | } |
| | 0 | 186 | | catch (ArgumentException ex) |
| | | 187 | | { |
| | 0 | 188 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 189 | | } |
| | 0 | 190 | | catch (Exception ex) |
| | | 191 | | { |
| | 0 | 192 | | _logger.LogError(ex, "Error al descargar documento del beneficio {Id}", id); |
| | 0 | 193 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 194 | | } |
| | 0 | 195 | | } |
| | | 196 | | |
| | | 197 | | // ── Múltiples documentos ────────────────────────────────────────────────── |
| | | 198 | | |
| | | 199 | | [HttpPost("{id:long}/documentos")] |
| | | 200 | | [RequestSizeLimit(20_000_000)] |
| | | 201 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 202 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 203 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 204 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 205 | | public async Task<IActionResult> AgregarDocumento(long id, IFormFile archivo) |
| | | 206 | | { |
| | 0 | 207 | | if (archivo == null || archivo.Length == 0) |
| | 0 | 208 | | return BadRequest(ApiResponse<string>.ErrorResult("Archivo requerido")); |
| | | 209 | | |
| | | 210 | | try |
| | | 211 | | { |
| | 0 | 212 | | await using var stream = archivo.OpenReadStream(); |
| | 0 | 213 | | var ruta = await _beneficioSocialService.AgregarDocumentoAsync( |
| | 0 | 214 | | id, stream, archivo.FileName, archivo.ContentType, ObtenerUsuarioIdActual()); |
| | 0 | 215 | | return Ok(ApiResponse<object>.SuccessResult(new { ruta, subido = true }, "Documento agregado correctamente") |
| | 0 | 216 | | } |
| | 0 | 217 | | catch (ArgumentException ex) |
| | | 218 | | { |
| | 0 | 219 | | return ex.Message.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) |
| | 0 | 220 | | ? NotFound(ApiResponse<string>.ErrorResult(ex.Message)) |
| | 0 | 221 | | : BadRequest(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 222 | | } |
| | 0 | 223 | | catch (Exception ex) |
| | | 224 | | { |
| | 0 | 225 | | _logger.LogError(ex, "Error al agregar documento al beneficio {Id}", id); |
| | 0 | 226 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 227 | | } |
| | 0 | 228 | | } |
| | | 229 | | |
| | | 230 | | [HttpGet("{id:long}/documentos")] |
| | | 231 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 232 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 233 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 234 | | public async Task<IActionResult> ListarDocumentos(long id) |
| | | 235 | | { |
| | | 236 | | try |
| | | 237 | | { |
| | 0 | 238 | | var docs = await _beneficioSocialService.ObtenerDocumentosAsync(id); |
| | 0 | 239 | | return Ok(ApiResponse<object>.SuccessResult(docs)); |
| | | 240 | | } |
| | 0 | 241 | | catch (ArgumentException ex) |
| | | 242 | | { |
| | 0 | 243 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 244 | | } |
| | 0 | 245 | | catch (Exception ex) |
| | | 246 | | { |
| | 0 | 247 | | _logger.LogError(ex, "Error al listar documentos del beneficio {Id}", id); |
| | 0 | 248 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 249 | | } |
| | 0 | 250 | | } |
| | | 251 | | |
| | | 252 | | [HttpGet("{id:long}/documentos/{docId:long}")] |
| | | 253 | | [ProducesResponseType(typeof(FileResult), StatusCodes.Status200OK)] |
| | | 254 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 255 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 256 | | public async Task<IActionResult> DescargarDocumentoPorId(long id, long docId, [FromQuery] bool inline = false) |
| | | 257 | | { |
| | | 258 | | try |
| | | 259 | | { |
| | 0 | 260 | | var (stream, nombre, contentType) = await _beneficioSocialService.DescargarDocumentoPorIdAsync(id, docId); |
| | 0 | 261 | | var disposition = inline ? "inline" : "attachment"; |
| | 0 | 262 | | Response.Headers.Append("Content-Disposition", $"{disposition}; filename=\"{nombre}\""); |
| | 0 | 263 | | return File(stream, contentType); |
| | | 264 | | } |
| | 0 | 265 | | catch (KeyNotFoundException ex) |
| | | 266 | | { |
| | 0 | 267 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 268 | | } |
| | 0 | 269 | | catch (ArgumentException ex) |
| | | 270 | | { |
| | 0 | 271 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 272 | | } |
| | 0 | 273 | | catch (Exception ex) |
| | | 274 | | { |
| | 0 | 275 | | _logger.LogError(ex, "Error al descargar documento {DocId} del beneficio {Id}", docId, id); |
| | 0 | 276 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 277 | | } |
| | 0 | 278 | | } |
| | | 279 | | |
| | | 280 | | [HttpDelete("{id:long}/documentos/{docId:long}")] |
| | | 281 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status200OK)] |
| | | 282 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 283 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 284 | | public async Task<IActionResult> EliminarDocumento(long id, long docId) |
| | | 285 | | { |
| | | 286 | | try |
| | | 287 | | { |
| | 0 | 288 | | await _beneficioSocialService.EliminarDocumentoAsync(id, docId); |
| | 0 | 289 | | return Ok(ApiResponse<string>.SuccessResult("ok", "Documento eliminado correctamente")); |
| | | 290 | | } |
| | 0 | 291 | | catch (KeyNotFoundException) |
| | | 292 | | { |
| | 0 | 293 | | return NotFound(ApiResponse<string>.ErrorResult("Documento no encontrado")); |
| | | 294 | | } |
| | 0 | 295 | | catch (ArgumentException ex) |
| | | 296 | | { |
| | 0 | 297 | | return NotFound(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 298 | | } |
| | 0 | 299 | | catch (Exception ex) |
| | | 300 | | { |
| | 0 | 301 | | _logger.LogError(ex, "Error al eliminar documento {DocId} del beneficio {Id}", docId, id); |
| | 0 | 302 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 303 | | } |
| | 0 | 304 | | } |
| | | 305 | | |
| | | 306 | | [HttpDelete("{id:long}")] |
| | | 307 | | [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)] |
| | | 308 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)] |
| | | 309 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)] |
| | | 310 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)] |
| | | 311 | | [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)] |
| | | 312 | | public async Task<IActionResult> DeleteBeneficioSocial(long id) |
| | | 313 | | { |
| | | 314 | | try |
| | | 315 | | { |
| | 2 | 316 | | var (exito, bajaLogica, error) = await _beneficioSocialService.EliminarAsync(id, ObtenerUsuarioIdActual(), O |
| | 2 | 317 | | if (!exito) |
| | | 318 | | { |
| | 1 | 319 | | return MapearError(error, "Error al eliminar beneficio social"); |
| | | 320 | | } |
| | | 321 | | |
| | 1 | 322 | | return Ok(ApiResponse<object>.SuccessResult(new { eliminado = true, bajaLogica }, "Beneficio social dado de |
| | | 323 | | } |
| | 0 | 324 | | catch (Exception ex) |
| | | 325 | | { |
| | 0 | 326 | | _logger.LogError(ex, "Error al eliminar beneficio social {Id}", id); |
| | 0 | 327 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 328 | | } |
| | 2 | 329 | | } |
| | | 330 | | |
| | | 331 | | private IActionResult MapearError(string? error, string errorPorDefecto) |
| | | 332 | | { |
| | 5 | 333 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | | 334 | | { |
| | 1 | 335 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 336 | | } |
| | | 337 | | |
| | 4 | 338 | | if (error?.Contains("duplicado", StringComparison.OrdinalIgnoreCase) == true |
| | 4 | 339 | | || error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true) |
| | | 340 | | { |
| | 2 | 341 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 342 | | } |
| | | 343 | | |
| | 2 | 344 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? errorPorDefecto)); |
| | | 345 | | } |
| | | 346 | | |
| | | 347 | | private long ObtenerUsuarioIdActual() |
| | | 348 | | { |
| | 7 | 349 | | var usuario = HttpContext?.User; |
| | 7 | 350 | | if (usuario == null) |
| | | 351 | | { |
| | 0 | 352 | | return 0; |
| | | 353 | | } |
| | | 354 | | |
| | 7 | 355 | | var claimId = usuario.FindFirstValue(ClaimTypes.NameIdentifier) |
| | 7 | 356 | | ?? usuario.FindFirstValue("sub") |
| | 7 | 357 | | ?? usuario.FindFirstValue("id"); |
| | | 358 | | |
| | 7 | 359 | | return long.TryParse(claimId, out var usuarioId) ? usuarioId : 0; |
| | | 360 | | } |
| | | 361 | | |
| | | 362 | | private string ObtenerHost() |
| | | 363 | | { |
| | 7 | 364 | | return HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Desconocido"; |
| | | 365 | | } |
| | | 366 | | } |