| | | 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.Mvc; |
| | | 7 | | |
| | | 8 | | namespace FAU.API.Controllers; |
| | | 9 | | |
| | | 10 | | [ApiController] |
| | | 11 | | [Route("api/beneficios-sociales")] |
| | | 12 | | [Authorize(Roles = "Administrador,Supervisor")] |
| | | 13 | | public class BeneficiosSocialesController : ControllerBase |
| | | 14 | | { |
| | | 15 | | private readonly IBeneficioSocialService _beneficioSocialService; |
| | | 16 | | private readonly ILogger<BeneficiosSocialesController> _logger; |
| | | 17 | | |
| | 10 | 18 | | public BeneficiosSocialesController( |
| | 10 | 19 | | IBeneficioSocialService beneficioSocialService, |
| | 10 | 20 | | ILogger<BeneficiosSocialesController> logger) |
| | | 21 | | { |
| | 10 | 22 | | _beneficioSocialService = beneficioSocialService; |
| | 10 | 23 | | _logger = logger; |
| | 10 | 24 | | } |
| | | 25 | | |
| | | 26 | | [HttpGet] |
| | | 27 | | public async Task<IActionResult> GetBeneficiosSociales( |
| | | 28 | | [FromQuery] int pagina = 1, |
| | | 29 | | [FromQuery] int tamano = 10, |
| | | 30 | | [FromQuery] long? personaId = null, |
| | | 31 | | [FromQuery] string? estado = null) |
| | | 32 | | { |
| | | 33 | | try |
| | | 34 | | { |
| | 1 | 35 | | var resultado = await _beneficioSocialService.ObtenerPaginadoAsync(pagina, tamano, personaId, estado); |
| | 1 | 36 | | return Ok(ApiResponse<object>.SuccessResult(new |
| | 1 | 37 | | { |
| | 1 | 38 | | items = resultado.Items, |
| | 1 | 39 | | page = resultado.Page, |
| | 1 | 40 | | pageSize = resultado.PageSize, |
| | 1 | 41 | | totalCount = resultado.TotalCount, |
| | 1 | 42 | | totalPages = resultado.TotalPages, |
| | 1 | 43 | | hasPreviousPage = resultado.HasPreviousPage, |
| | 1 | 44 | | hasNextPage = resultado.HasNextPage |
| | 1 | 45 | | })); |
| | | 46 | | } |
| | 0 | 47 | | catch (Exception ex) |
| | | 48 | | { |
| | 0 | 49 | | _logger.LogError(ex, "Error al listar beneficios sociales"); |
| | 0 | 50 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 51 | | } |
| | 1 | 52 | | } |
| | | 53 | | |
| | | 54 | | [HttpGet("{id:long}")] |
| | | 55 | | public async Task<IActionResult> GetBeneficioSocial(long id) |
| | | 56 | | { |
| | | 57 | | try |
| | | 58 | | { |
| | 2 | 59 | | var beneficio = await _beneficioSocialService.ObtenerPorIdAsync(id); |
| | 2 | 60 | | if (beneficio == null) |
| | | 61 | | { |
| | 1 | 62 | | return NotFound(ApiResponse<string>.ErrorResult("Beneficio social no encontrado")); |
| | | 63 | | } |
| | | 64 | | |
| | 1 | 65 | | return Ok(ApiResponse<BeneficioSocialDto>.SuccessResult(beneficio)); |
| | | 66 | | } |
| | 0 | 67 | | catch (Exception ex) |
| | | 68 | | { |
| | 0 | 69 | | _logger.LogError(ex, "Error al obtener beneficio social {Id}", id); |
| | 0 | 70 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 71 | | } |
| | 2 | 72 | | } |
| | | 73 | | |
| | | 74 | | [HttpPost] |
| | | 75 | | public async Task<IActionResult> CreateBeneficioSocial([FromBody] CrearBeneficioSocialRequest request) |
| | | 76 | | { |
| | | 77 | | try |
| | | 78 | | { |
| | 3 | 79 | | var (exito, resultado, error) = await _beneficioSocialService.CrearAsync(request, ObtenerUsuarioIdActual(), |
| | 3 | 80 | | if (!exito) |
| | | 81 | | { |
| | 2 | 82 | | return MapearError(error, "Error al crear beneficio social"); |
| | | 83 | | } |
| | | 84 | | |
| | 1 | 85 | | return CreatedAtAction( |
| | 1 | 86 | | nameof(GetBeneficioSocial), |
| | 1 | 87 | | new { id = resultado!.Id }, |
| | 1 | 88 | | ApiResponse<object>.SuccessResult(new { id = resultado.Id, creado = true }, "Beneficio social creado exi |
| | | 89 | | } |
| | 0 | 90 | | catch (PeriodoBloqueadoException ex) |
| | | 91 | | { |
| | 0 | 92 | | return Conflict(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 93 | | } |
| | 0 | 94 | | catch (Exception ex) |
| | | 95 | | { |
| | 0 | 96 | | _logger.LogError(ex, "Error al crear beneficio social"); |
| | 0 | 97 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 98 | | } |
| | 3 | 99 | | } |
| | | 100 | | |
| | | 101 | | [HttpPut("{id:long}")] |
| | | 102 | | public async Task<IActionResult> UpdateBeneficioSocial(long id, [FromBody] ActualizarBeneficioSocialRequest request) |
| | | 103 | | { |
| | | 104 | | try |
| | | 105 | | { |
| | 2 | 106 | | var (exito, resultado, error) = await _beneficioSocialService.ActualizarAsync(id, request, ObtenerUsuarioIdA |
| | 2 | 107 | | if (!exito) |
| | | 108 | | { |
| | 2 | 109 | | return MapearError(error, "Error al actualizar beneficio social"); |
| | | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true, id = resultado!.Id }, "Beneficio socia |
| | | 113 | | } |
| | 0 | 114 | | catch (Exception ex) |
| | | 115 | | { |
| | 0 | 116 | | _logger.LogError(ex, "Error al actualizar beneficio social {Id}", id); |
| | 0 | 117 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 118 | | } |
| | 2 | 119 | | } |
| | | 120 | | |
| | | 121 | | [HttpPost("{id:long}/documento")] |
| | | 122 | | [RequestSizeLimit(20_000_000)] |
| | | 123 | | public async Task<IActionResult> SubirDocumento(long id, IFormFile file) |
| | | 124 | | { |
| | 0 | 125 | | if (file == null || file.Length == 0) |
| | 0 | 126 | | return BadRequest(ApiResponse<string>.ErrorResult("Archivo requerido")); |
| | | 127 | | |
| | | 128 | | try |
| | | 129 | | { |
| | 0 | 130 | | await using var stream = file.OpenReadStream(); |
| | 0 | 131 | | var ruta = await _beneficioSocialService.SubirDocumentoAsync( |
| | 0 | 132 | | id, stream, file.FileName, file.ContentType, ObtenerUsuarioIdActual()); |
| | 0 | 133 | | return Ok(ApiResponse<object>.SuccessResult(new { rutaRelativa = ruta, subido = true }, "Documento subido ex |
| | 0 | 134 | | } |
| | 0 | 135 | | catch (ArgumentException ex) |
| | | 136 | | { |
| | 0 | 137 | | return ex.Message.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) |
| | 0 | 138 | | ? NotFound(ApiResponse<string>.ErrorResult(ex.Message)) |
| | 0 | 139 | | : BadRequest(ApiResponse<string>.ErrorResult(ex.Message)); |
| | | 140 | | } |
| | 0 | 141 | | catch (Exception ex) |
| | | 142 | | { |
| | 0 | 143 | | _logger.LogError(ex, "Error al subir documento de beneficio {Id}", id); |
| | 0 | 144 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 145 | | } |
| | 0 | 146 | | } |
| | | 147 | | |
| | | 148 | | [HttpDelete("{id:long}")] |
| | | 149 | | public async Task<IActionResult> DeleteBeneficioSocial(long id) |
| | | 150 | | { |
| | | 151 | | try |
| | | 152 | | { |
| | 2 | 153 | | var (exito, bajaLogica, error) = await _beneficioSocialService.EliminarAsync(id, ObtenerUsuarioIdActual(), O |
| | 2 | 154 | | if (!exito) |
| | | 155 | | { |
| | 1 | 156 | | return MapearError(error, "Error al eliminar beneficio social"); |
| | | 157 | | } |
| | | 158 | | |
| | 1 | 159 | | return Ok(ApiResponse<object>.SuccessResult(new { eliminado = true, bajaLogica }, "Beneficio social dado de |
| | | 160 | | } |
| | 0 | 161 | | catch (Exception ex) |
| | | 162 | | { |
| | 0 | 163 | | _logger.LogError(ex, "Error al eliminar beneficio social {Id}", id); |
| | 0 | 164 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 165 | | } |
| | 2 | 166 | | } |
| | | 167 | | |
| | | 168 | | private IActionResult MapearError(string? error, string errorPorDefecto) |
| | | 169 | | { |
| | 5 | 170 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | | 171 | | { |
| | 1 | 172 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 173 | | } |
| | | 174 | | |
| | 4 | 175 | | if (error?.Contains("duplicado", StringComparison.OrdinalIgnoreCase) == true |
| | 4 | 176 | | || error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true) |
| | | 177 | | { |
| | 2 | 178 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 179 | | } |
| | | 180 | | |
| | 2 | 181 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? errorPorDefecto)); |
| | | 182 | | } |
| | | 183 | | |
| | | 184 | | private long ObtenerUsuarioIdActual() |
| | | 185 | | { |
| | 7 | 186 | | var usuario = HttpContext?.User; |
| | 7 | 187 | | if (usuario == null) |
| | | 188 | | { |
| | 0 | 189 | | return 0; |
| | | 190 | | } |
| | | 191 | | |
| | 7 | 192 | | var claimId = usuario.FindFirstValue(ClaimTypes.NameIdentifier) |
| | 7 | 193 | | ?? usuario.FindFirstValue("sub") |
| | 7 | 194 | | ?? usuario.FindFirstValue("id"); |
| | | 195 | | |
| | 7 | 196 | | return long.TryParse(claimId, out var usuarioId) ? usuarioId : 0; |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | private string ObtenerHost() |
| | | 200 | | { |
| | 7 | 201 | | return HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Desconocido"; |
| | | 202 | | } |
| | | 203 | | } |