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