< Summary

Information
Class: FAU.API.Controllers.BeneficiosSocialesController
Assembly: FAU.API
File(s): /home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Controllers/BeneficiosSocialesController.cs
Line coverage
75%
Covered lines: 53
Uncovered lines: 17
Coverable lines: 70
Total lines: 171
Line coverage: 75.7%
Branch coverage
72%
Covered branches: 29
Total branches: 40
Branch coverage: 72.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetBeneficiosSociales()100%1180%
GetBeneficioSocial()100%2262.5%
CreateBeneficioSocial()100%2272.72%
UpdateBeneficioSocial()50%3250%
DeleteBeneficioSocial()100%2262.5%
MapearError(...)92.85%1414100%
ObtenerUsuarioIdActual()50%101085.71%
ObtenerHost()50%88100%

File(s)

/home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Controllers/BeneficiosSocialesController.cs

#LineLine coverage
 1using System.Security.Claims;
 2using FAU.Logica.DTOs;
 3using FAU.Logica.Services;
 4using Microsoft.AspNetCore.Authorization;
 5using Microsoft.AspNetCore.Mvc;
 6
 7namespace FAU.API.Controllers;
 8
 9[ApiController]
 10[Route("api/beneficios-sociales")]
 11[Authorize(Roles = "Administrador,Supervisor")]
 12public class BeneficiosSocialesController : ControllerBase
 13{
 14    private readonly IBeneficioSocialService _beneficioSocialService;
 15    private readonly ILogger<BeneficiosSocialesController> _logger;
 16
 1017    public BeneficiosSocialesController(
 1018        IBeneficioSocialService beneficioSocialService,
 1019        ILogger<BeneficiosSocialesController> logger)
 20    {
 1021        _beneficioSocialService = beneficioSocialService;
 1022        _logger = logger;
 1023    }
 24
 25    [HttpGet]
 26    public async Task<IActionResult> GetBeneficiosSociales(
 27        [FromQuery] int pagina = 1,
 28        [FromQuery] int tamano = 10,
 29        [FromQuery] long? personaId = null,
 30        [FromQuery] string? estado = null)
 31    {
 32        try
 33        {
 134            var resultado = await _beneficioSocialService.ObtenerPaginadoAsync(pagina, tamano, personaId, estado);
 135            return Ok(ApiResponse<object>.SuccessResult(new
 136            {
 137                items = resultado.Items,
 138                page = resultado.Page,
 139                pageSize = resultado.PageSize,
 140                totalCount = resultado.TotalCount,
 141                totalPages = resultado.TotalPages,
 142                hasPreviousPage = resultado.HasPreviousPage,
 143                hasNextPage = resultado.HasNextPage
 144            }));
 45        }
 046        catch (Exception ex)
 47        {
 048            _logger.LogError(ex, "Error al listar beneficios sociales");
 049            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 50        }
 151    }
 52
 53    [HttpGet("{id:long}")]
 54    public async Task<IActionResult> GetBeneficioSocial(long id)
 55    {
 56        try
 57        {
 258            var beneficio = await _beneficioSocialService.ObtenerPorIdAsync(id);
 259            if (beneficio == null)
 60            {
 161                return NotFound(ApiResponse<string>.ErrorResult("Beneficio social no encontrado"));
 62            }
 63
 164            return Ok(ApiResponse<BeneficioSocialDto>.SuccessResult(beneficio));
 65        }
 066        catch (Exception ex)
 67        {
 068            _logger.LogError(ex, "Error al obtener beneficio social {Id}", id);
 069            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 70        }
 271    }
 72
 73    [HttpPost]
 74    public async Task<IActionResult> CreateBeneficioSocial([FromBody] CrearBeneficioSocialRequest request)
 75    {
 76        try
 77        {
 378            var (exito, resultado, error) = await _beneficioSocialService.CrearAsync(request, ObtenerUsuarioIdActual(), 
 379            if (!exito)
 80            {
 281                return MapearError(error, "Error al crear beneficio social");
 82            }
 83
 184            return CreatedAtAction(
 185                nameof(GetBeneficioSocial),
 186                new { id = resultado!.Id },
 187                ApiResponse<object>.SuccessResult(new { id = resultado.Id, creado = true }, "Beneficio social creado exi
 88        }
 089        catch (Exception ex)
 90        {
 091            _logger.LogError(ex, "Error al crear beneficio social");
 092            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 93        }
 394    }
 95
 96    [HttpPut("{id:long}")]
 97    public async Task<IActionResult> UpdateBeneficioSocial(long id, [FromBody] ActualizarBeneficioSocialRequest request)
 98    {
 99        try
 100        {
 2101            var (exito, resultado, error) = await _beneficioSocialService.ActualizarAsync(id, request, ObtenerUsuarioIdA
 2102            if (!exito)
 103            {
 2104                return MapearError(error, "Error al actualizar beneficio social");
 105            }
 106
 0107            return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true, id = resultado!.Id }, "Beneficio socia
 108        }
 0109        catch (Exception ex)
 110        {
 0111            _logger.LogError(ex, "Error al actualizar beneficio social {Id}", id);
 0112            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 113        }
 2114    }
 115
 116    [HttpDelete("{id:long}")]
 117    public async Task<IActionResult> DeleteBeneficioSocial(long id)
 118    {
 119        try
 120        {
 2121            var (exito, bajaLogica, error) = await _beneficioSocialService.EliminarAsync(id, ObtenerUsuarioIdActual(), O
 2122            if (!exito)
 123            {
 1124                return MapearError(error, "Error al eliminar beneficio social");
 125            }
 126
 1127            return Ok(ApiResponse<object>.SuccessResult(new { eliminado = true, bajaLogica }, "Beneficio social dado de 
 128        }
 0129        catch (Exception ex)
 130        {
 0131            _logger.LogError(ex, "Error al eliminar beneficio social {Id}", id);
 0132            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 133        }
 2134    }
 135
 136    private IActionResult MapearError(string? error, string errorPorDefecto)
 137    {
 5138        if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true)
 139        {
 1140            return NotFound(ApiResponse<string>.ErrorResult(error));
 141        }
 142
 4143        if (error?.Contains("duplicado", StringComparison.OrdinalIgnoreCase) == true
 4144            || error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true)
 145        {
 2146            return Conflict(ApiResponse<string>.ErrorResult(error));
 147        }
 148
 2149        return BadRequest(ApiResponse<string>.ErrorResult(error ?? errorPorDefecto));
 150    }
 151
 152    private long ObtenerUsuarioIdActual()
 153    {
 7154        var usuario = HttpContext?.User;
 7155        if (usuario == null)
 156        {
 0157            return 0;
 158        }
 159
 7160        var claimId = usuario.FindFirstValue(ClaimTypes.NameIdentifier)
 7161                      ?? usuario.FindFirstValue("sub")
 7162                      ?? usuario.FindFirstValue("id");
 163
 7164        return long.TryParse(claimId, out var usuarioId) ? usuarioId : 0;
 165    }
 166
 167    private string ObtenerHost()
 168    {
 7169        return HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "Desconocido";
 170    }
 171}