| | | 1 | | using System.Security.Claims; |
| | | 2 | | using FAU.Entidades; |
| | | 3 | | using FAU.Logica.DTOs; |
| | | 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/tipos-beneficio")] |
| | | 12 | | public class TiposBeneficioController : ControllerBase |
| | | 13 | | { |
| | | 14 | | private readonly ITipoBeneficioService _tipoBeneficioService; |
| | | 15 | | private readonly ILogger<TiposBeneficioController> _logger; |
| | | 16 | | |
| | 30 | 17 | | public TiposBeneficioController( |
| | 30 | 18 | | ITipoBeneficioService tipoBeneficioService, |
| | 30 | 19 | | ILogger<TiposBeneficioController> logger) |
| | | 20 | | { |
| | 30 | 21 | | _tipoBeneficioService = tipoBeneficioService; |
| | 30 | 22 | | _logger = logger; |
| | 30 | 23 | | } |
| | | 24 | | |
| | | 25 | | [HttpGet] |
| | | 26 | | [FAU.API.Security.RequirePermission(PermisoEnum.VerBeneficios)] |
| | | 27 | | public async Task<IActionResult> GetTiposBeneficio( |
| | | 28 | | [FromQuery] int pagina = 1, |
| | | 29 | | [FromQuery] int tamano = 10, |
| | | 30 | | [FromQuery] string? busqueda = null, |
| | | 31 | | [FromQuery] bool? activo = null) |
| | | 32 | | { |
| | | 33 | | try |
| | | 34 | | { |
| | 2 | 35 | | var resultado = await _tipoBeneficioService.ObtenerPaginadoAsync(pagina, tamano, busqueda, activo); |
| | | 36 | | |
| | 1 | 37 | | var response = new |
| | 1 | 38 | | { |
| | 1 | 39 | | items = resultado.Items, |
| | 1 | 40 | | page = resultado.Page, |
| | 1 | 41 | | pageSize = resultado.PageSize, |
| | 1 | 42 | | totalCount = resultado.TotalCount, |
| | 1 | 43 | | totalPages = resultado.TotalPages, |
| | 1 | 44 | | hasPreviousPage = resultado.HasPreviousPage, |
| | 1 | 45 | | hasNextPage = resultado.HasNextPage |
| | 1 | 46 | | }; |
| | | 47 | | |
| | 1 | 48 | | return Ok(ApiResponse<object>.SuccessResult(response)); |
| | | 49 | | } |
| | 1 | 50 | | catch (Exception ex) |
| | | 51 | | { |
| | 1 | 52 | | _logger.LogError(ex, "Error al listar tipos de beneficio"); |
| | 1 | 53 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 54 | | } |
| | 2 | 55 | | } |
| | | 56 | | |
| | | 57 | | [HttpGet("{id:long}")] |
| | | 58 | | [FAU.API.Security.RequirePermission(PermisoEnum.VerBeneficios)] |
| | | 59 | | public async Task<IActionResult> GetTipoBeneficio(long id) |
| | | 60 | | { |
| | | 61 | | try |
| | | 62 | | { |
| | 3 | 63 | | var tipo = await _tipoBeneficioService.ObtenerPorIdAsync(id); |
| | 2 | 64 | | if (tipo == null) |
| | | 65 | | { |
| | 1 | 66 | | return NotFound(ApiResponse<string>.ErrorResult("Tipo de beneficio no encontrado")); |
| | | 67 | | } |
| | | 68 | | |
| | 1 | 69 | | return Ok(ApiResponse<object>.SuccessResult(MapearRespuesta(tipo))); |
| | | 70 | | } |
| | 1 | 71 | | catch (Exception ex) |
| | | 72 | | { |
| | 1 | 73 | | _logger.LogError(ex, "Error al obtener tipo de beneficio {Id}", id); |
| | 1 | 74 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 75 | | } |
| | 3 | 76 | | } |
| | | 77 | | |
| | | 78 | | [HttpPost] |
| | | 79 | | [FAU.API.Security.RequirePermission(PermisoEnum.CrearBeneficios)] |
| | | 80 | | public async Task<IActionResult> CreateTipoBeneficio([FromBody] CrearTipoBeneficioRequest request) |
| | | 81 | | { |
| | | 82 | | try |
| | | 83 | | { |
| | 7 | 84 | | if (string.IsNullOrWhiteSpace(request.Codigo)) |
| | | 85 | | { |
| | 1 | 86 | | return BadRequest(ApiResponse<string>.ErrorResult("El codigo es requerido")); |
| | | 87 | | } |
| | | 88 | | |
| | 6 | 89 | | if (string.IsNullOrWhiteSpace(request.Nombre)) |
| | | 90 | | { |
| | 1 | 91 | | return BadRequest(ApiResponse<string>.ErrorResult("El nombre es requerido")); |
| | | 92 | | } |
| | | 93 | | |
| | 5 | 94 | | var (exito, resultado, error) = await _tipoBeneficioService.CrearAsync( |
| | 5 | 95 | | request.Codigo, |
| | 5 | 96 | | request.Nombre, |
| | 5 | 97 | | request.EsMensual, |
| | 5 | 98 | | request.PermiteRetroactividad, |
| | 5 | 99 | | request.PlazoPresentacionDias, |
| | 5 | 100 | | request.MontoReferencia, |
| | 5 | 101 | | request.CatalogoItemId, |
| | 5 | 102 | | request.Activo, |
| | 5 | 103 | | ObtenerUsuarioIdActual(), |
| | 5 | 104 | | ObtenerHost()); |
| | | 105 | | |
| | 4 | 106 | | if (!exito) |
| | | 107 | | { |
| | 2 | 108 | | if (error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true) |
| | | 109 | | { |
| | 1 | 110 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 111 | | } |
| | | 112 | | |
| | 1 | 113 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear tipo de beneficio")); |
| | | 114 | | } |
| | | 115 | | |
| | 2 | 116 | | return CreatedAtAction( |
| | 2 | 117 | | nameof(GetTipoBeneficio), |
| | 2 | 118 | | new { id = resultado!.Id }, |
| | 2 | 119 | | ApiResponse<object>.SuccessResult(new { id = resultado.Id, creado = true }, "Tipo de beneficio creado ex |
| | | 120 | | } |
| | 1 | 121 | | catch (Exception ex) |
| | | 122 | | { |
| | 1 | 123 | | _logger.LogError(ex, "Error al crear tipo de beneficio"); |
| | 1 | 124 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 125 | | } |
| | 7 | 126 | | } |
| | | 127 | | |
| | | 128 | | [HttpPut("{id:long}")] |
| | | 129 | | [FAU.API.Security.RequirePermission(PermisoEnum.ActualizarBeneficios)] |
| | | 130 | | public async Task<IActionResult> UpdateTipoBeneficio(long id, [FromBody] ActualizarTipoBeneficioRequest request) |
| | | 131 | | { |
| | | 132 | | try |
| | | 133 | | { |
| | 6 | 134 | | if (request.Codigo == null && |
| | 6 | 135 | | request.Nombre == null && |
| | 6 | 136 | | !request.EsMensual.HasValue && |
| | 6 | 137 | | !request.PermiteRetroactividad.HasValue && |
| | 6 | 138 | | !request.PlazoPresentacionDias.HasValue && |
| | 6 | 139 | | !request.MontoReferencia.HasValue && |
| | 6 | 140 | | !request.CatalogoItemId.HasValue) |
| | | 141 | | { |
| | 1 | 142 | | return BadRequest(ApiResponse<string>.ErrorResult("Debe proporcionar al menos un campo para actualizar") |
| | | 143 | | } |
| | | 144 | | |
| | 5 | 145 | | var (exito, resultado, error) = await _tipoBeneficioService.ActualizarAsync( |
| | 5 | 146 | | id, |
| | 5 | 147 | | request.Codigo, |
| | 5 | 148 | | request.Nombre, |
| | 5 | 149 | | request.EsMensual, |
| | 5 | 150 | | request.PermiteRetroactividad, |
| | 5 | 151 | | request.PlazoPresentacionDias, |
| | 5 | 152 | | request.MontoReferencia, |
| | 5 | 153 | | request.CatalogoItemId, |
| | 5 | 154 | | ObtenerUsuarioIdActual(), |
| | 5 | 155 | | ObtenerHost()); |
| | | 156 | | |
| | 4 | 157 | | if (!exito) |
| | | 158 | | { |
| | 3 | 159 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | | 160 | | { |
| | 1 | 161 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 162 | | } |
| | | 163 | | |
| | 2 | 164 | | if (error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true) |
| | | 165 | | { |
| | 1 | 166 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 167 | | } |
| | | 168 | | |
| | 1 | 169 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al actualizar tipo de beneficio")); |
| | | 170 | | } |
| | | 171 | | |
| | 1 | 172 | | return Ok(ApiResponse<object>.SuccessResult(new |
| | 1 | 173 | | { |
| | 1 | 174 | | actualizado = true, |
| | 1 | 175 | | id = resultado!.Id |
| | 1 | 176 | | }, "Tipo de beneficio actualizado exitosamente")); |
| | | 177 | | } |
| | 1 | 178 | | catch (Exception ex) |
| | | 179 | | { |
| | 1 | 180 | | _logger.LogError(ex, "Error al actualizar tipo de beneficio {Id}", id); |
| | 1 | 181 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 182 | | } |
| | 6 | 183 | | } |
| | | 184 | | |
| | | 185 | | [HttpPatch("{id:long}/activar")] |
| | | 186 | | [FAU.API.Security.RequirePermission(PermisoEnum.ActivarBeneficios)] |
| | | 187 | | public async Task<IActionResult> ActivarTipoBeneficio(long id) |
| | | 188 | | { |
| | 3 | 189 | | return await CambiarEstadoAsync(id, activar: true); |
| | 3 | 190 | | } |
| | | 191 | | |
| | | 192 | | [HttpPatch("{id:long}/desactivar")] |
| | | 193 | | [FAU.API.Security.RequirePermission(PermisoEnum.DesactivarBeneficios)] |
| | | 194 | | public async Task<IActionResult> DesactivarTipoBeneficio(long id) |
| | | 195 | | { |
| | 4 | 196 | | return await CambiarEstadoAsync(id, activar: false); |
| | 4 | 197 | | } |
| | | 198 | | |
| | | 199 | | [HttpDelete("{id:long}")] |
| | | 200 | | [FAU.API.Security.RequirePermission(PermisoEnum.EliminarBeneficios)] |
| | | 201 | | public async Task<IActionResult> DeleteTipoBeneficio(long id) |
| | | 202 | | { |
| | | 203 | | try |
| | | 204 | | { |
| | 5 | 205 | | var (exito, bajaLogica, error) = await _tipoBeneficioService.EliminarAsync( |
| | 5 | 206 | | id, |
| | 5 | 207 | | ObtenerUsuarioIdActual(), |
| | 5 | 208 | | ObtenerHost()); |
| | | 209 | | |
| | 4 | 210 | | if (!exito) |
| | | 211 | | { |
| | 3 | 212 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | | 213 | | { |
| | 1 | 214 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 215 | | } |
| | | 216 | | |
| | 2 | 217 | | if (error?.Contains("liquidaciones abiertas", StringComparison.OrdinalIgnoreCase) == true) |
| | | 218 | | { |
| | 1 | 219 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 220 | | } |
| | | 221 | | |
| | 1 | 222 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al eliminar tipo de beneficio")); |
| | | 223 | | } |
| | | 224 | | |
| | 1 | 225 | | return Ok(ApiResponse<object>.SuccessResult(new |
| | 1 | 226 | | { |
| | 1 | 227 | | eliminado = true, |
| | 1 | 228 | | bajaLogica |
| | 1 | 229 | | }, bajaLogica |
| | 1 | 230 | | ? "Tipo de beneficio dado de baja logicamente" |
| | 1 | 231 | | : "Tipo de beneficio eliminado exitosamente")); |
| | | 232 | | } |
| | 1 | 233 | | catch (Exception ex) |
| | | 234 | | { |
| | 1 | 235 | | _logger.LogError(ex, "Error al eliminar tipo de beneficio {Id}", id); |
| | 1 | 236 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 237 | | } |
| | 5 | 238 | | } |
| | | 239 | | |
| | | 240 | | private async Task<IActionResult> CambiarEstadoAsync(long id, bool activar) |
| | | 241 | | { |
| | | 242 | | try |
| | | 243 | | { |
| | 7 | 244 | | var (exito, resultado, error) = activar |
| | 7 | 245 | | ? await _tipoBeneficioService.ActivarAsync(id, ObtenerUsuarioIdActual(), ObtenerHost()) |
| | 7 | 246 | | : await _tipoBeneficioService.DesactivarAsync(id, ObtenerUsuarioIdActual(), ObtenerHost()); |
| | | 247 | | |
| | 6 | 248 | | if (!exito) |
| | | 249 | | { |
| | 4 | 250 | | if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true) |
| | | 251 | | { |
| | 2 | 252 | | return NotFound(ApiResponse<string>.ErrorResult(error)); |
| | | 253 | | } |
| | | 254 | | |
| | 2 | 255 | | if (error?.Contains("liquidaciones abiertas", StringComparison.OrdinalIgnoreCase) == true) |
| | | 256 | | { |
| | 1 | 257 | | return Conflict(ApiResponse<string>.ErrorResult(error)); |
| | | 258 | | } |
| | | 259 | | |
| | 1 | 260 | | return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al cambiar estado")); |
| | | 261 | | } |
| | | 262 | | |
| | 2 | 263 | | return Ok(ApiResponse<object>.SuccessResult(new |
| | 2 | 264 | | { |
| | 2 | 265 | | id = resultado!.Id, |
| | 2 | 266 | | activo = resultado.Activo |
| | 2 | 267 | | }, activar |
| | 2 | 268 | | ? "Tipo de beneficio activado exitosamente" |
| | 2 | 269 | | : "Tipo de beneficio desactivado exitosamente")); |
| | | 270 | | } |
| | 1 | 271 | | catch (Exception ex) |
| | | 272 | | { |
| | 1 | 273 | | _logger.LogError(ex, "Error al cambiar estado del tipo de beneficio {Id}", id); |
| | 1 | 274 | | return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor")); |
| | | 275 | | } |
| | 7 | 276 | | } |
| | | 277 | | |
| | | 278 | | private long ObtenerUsuarioIdActual() |
| | | 279 | | { |
| | 22 | 280 | | var usuario = HttpContext?.User; |
| | 22 | 281 | | if (usuario == null) |
| | | 282 | | { |
| | 1 | 283 | | return 0; |
| | | 284 | | } |
| | | 285 | | |
| | 21 | 286 | | var claimId = usuario.FindFirstValue(ClaimTypes.NameIdentifier) |
| | 21 | 287 | | ?? usuario.FindFirstValue("sub") |
| | 21 | 288 | | ?? usuario.FindFirstValue("id"); |
| | | 289 | | |
| | 21 | 290 | | return long.TryParse(claimId, out var usuarioId) ? usuarioId : 0; |
| | | 291 | | } |
| | | 292 | | |
| | | 293 | | private string ObtenerHost() |
| | | 294 | | { |
| | 22 | 295 | | return HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Desconocido"; |
| | | 296 | | } |
| | | 297 | | |
| | | 298 | | private static object MapearRespuesta(TipoBeneficio tipo) |
| | | 299 | | { |
| | 1 | 300 | | return new |
| | 1 | 301 | | { |
| | 1 | 302 | | id = tipo.Id, |
| | 1 | 303 | | codigo = tipo.Codigo, |
| | 1 | 304 | | nombre = tipo.Nombre, |
| | 1 | 305 | | esMensual = tipo.EsMensual, |
| | 1 | 306 | | permiteRetroactividad = tipo.PermiteRetroactividad, |
| | 1 | 307 | | plazoPresentacionDias = tipo.PlazoPresentacionDias, |
| | 1 | 308 | | montoReferencia = tipo.MontoReferencia, |
| | 1 | 309 | | catalogoItemId = tipo.CatalogoItemId, |
| | 1 | 310 | | activo = tipo.Activo |
| | 1 | 311 | | }; |
| | | 312 | | } |
| | | 313 | | } |