< Summary

Information
Class: FAU.API.Controllers.NovedadesPeriodoController
Assembly: FAU.API
File(s): /home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Controllers/NovedadesPeriodoController.cs
Line coverage
22%
Covered lines: 22
Uncovered lines: 74
Coverable lines: 96
Total lines: 225
Line coverage: 22.9%
Branch coverage
15%
Covered branches: 10
Total branches: 66
Branch coverage: 15.1%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
GetNovedades()100%210%
GetNovedad()0%156120%
CreateNovedad()25%481650%
UpdateNovedad()0%210140%
DeleteNovedad()0%7280%
ConfirmarNovedad()12.5%22840%
AnularNovedad()62.5%16850%

File(s)

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

#LineLine coverage
 1using FAU.API.Security;
 2using FAU.Entidades;
 3using FAU.Logica.DTOs;
 4using FAU.Logica.Services;
 5using Microsoft.AspNetCore.Authorization;
 6using Microsoft.AspNetCore.Mvc;
 7
 8namespace FAU.API.Controllers;
 9
 10[ApiController]
 11[Route("api/novedades-periodo")]
 12[Authorize(Roles = "Administrador,Operador")]
 13public class NovedadesPeriodoController : ControllerBase
 14{
 15    private readonly INovedadPeriodoService _novedadPeriodoService;
 16    private readonly ILogger<NovedadesPeriodoController> _logger;
 17
 418    public NovedadesPeriodoController(
 419        INovedadPeriodoService novedadPeriodoService,
 420        ILogger<NovedadesPeriodoController> logger)
 21    {
 422        _novedadPeriodoService = novedadPeriodoService;
 423        _logger = logger;
 424    }
 25
 26    [HttpGet]
 27    public async Task<IActionResult> GetNovedades(
 28        [FromQuery] int page = 1,
 29        [FromQuery] int pageSize = 10,
 30        [FromQuery] long? periodoId = null,
 31        [FromQuery] long? personaId = null,
 32        [FromQuery] string? tipo = null,
 33        [FromQuery] string? estado = null)
 34    {
 35        try
 36        {
 037            var resultado = await _novedadPeriodoService.GetPaginatedAsync(page, pageSize, periodoId, personaId, tipo, e
 38
 039            return Ok(ApiResponse<PagedResult<NovedadPeriodoDto>>.SuccessResult(resultado));
 40        }
 041        catch (Exception ex)
 42        {
 043            _logger.LogError(ex, "Error al obtener novedades de período");
 044            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 45        }
 046    }
 47
 48    [HttpGet("{id}")]
 49    public async Task<IActionResult> GetNovedad(long id)
 50    {
 51        try
 52        {
 053            var novedad = await _novedadPeriodoService.GetByIdAsync(id);
 054            if (novedad == null)
 55            {
 056                return NotFound(ApiResponse<string>.ErrorResult("Novedad de período no encontrada"));
 57            }
 58
 059            var response = new NovedadPeriodoDto
 060            {
 061                Id = novedad.Id,
 062                PeriodoId = novedad.PeriodoId,
 063                PersonaId = novedad.PersonaId,
 064                Cedula = novedad.Persona?.Cedula ?? string.Empty,
 065                NombreCompleto = novedad.Persona?.NombreCompleto ?? string.Empty,
 066                Tipo = novedad.Tipo,
 067                DiasAfectados = novedad.DiasAfectados,
 068                PorcentajeSubsidio = novedad.PorcentajeSubsidio,
 069                FechaDesde = novedad.FechaDesde ?? DateTime.MinValue,
 070                FechaHasta = novedad.FechaHasta,
 071                Observaciones = novedad.Observaciones,
 072                Estado = novedad.Estado,
 073                CreadoPor = novedad.CreadoPor,
 074                CreadoEn = novedad.CreadoEn,
 075                ConfirmadoPor = novedad.ConfirmadoPor,
 076                ConfirmadoEn = novedad.ConfirmadoEn
 077            };
 78
 079            return Ok(ApiResponse<NovedadPeriodoDto>.SuccessResult(response));
 80        }
 081        catch (Exception ex)
 82        {
 083            _logger.LogError(ex, "Error al obtener novedad de período {Id}", id);
 084            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 85        }
 086    }
 87
 88    [HttpPost]
 89    [RequirePermission(PermisoEnum.CrearNovedades)]
 90    public async Task<IActionResult> CreateNovedad([FromBody] CrearNovedadPeriodoRequest request)
 91    {
 92        try
 93        {
 294            var (success, novedad, error) = await _novedadPeriodoService.CreateAsync(request);
 295            if (!success)
 96            {
 197                if (error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true)
 98                {
 199                    return Conflict(ApiResponse<string>.ErrorResult(error));
 100                }
 0101                if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true ||
 0102                    error?.Contains("no existe", StringComparison.OrdinalIgnoreCase) == true)
 103                {
 0104                    return NotFound(ApiResponse<string>.ErrorResult(error));
 105                }
 106
 0107                return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear la novedad de período"));
 108            }
 109
 1110            var response = new { id = novedad!.Id, creado = true };
 1111            return CreatedAtAction(nameof(GetNovedad), new { id = novedad.Id }, ApiResponse<object>.SuccessResult(respon
 112        }
 0113        catch (Exception ex)
 114        {
 0115            _logger.LogError(ex, "Error al crear novedad de período");
 0116            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 117        }
 2118    }
 119
 120    [HttpPut("{id}")]
 121    [RequirePermission(PermisoEnum.CrearNovedades)]
 122    public async Task<IActionResult> UpdateNovedad(long id, [FromBody] ActualizarNovedadPeriodoRequest request)
 123    {
 124        try
 125        {
 0126            var (success, novedad, error) = await _novedadPeriodoService.UpdateAsync(id, request);
 0127            if (!success)
 128            {
 0129                if (error?.Contains("no encontrada", StringComparison.OrdinalIgnoreCase) == true)
 130                {
 0131                    return NotFound(ApiResponse<string>.ErrorResult(error));
 132                }
 0133                if (error?.Contains("solo se pueden", StringComparison.OrdinalIgnoreCase) == true ||
 0134                    error?.Contains("debe proporcionar", StringComparison.OrdinalIgnoreCase) == true)
 135                {
 0136                    return BadRequest(ApiResponse<string>.ErrorResult(error));
 137                }
 138
 0139                return Conflict(ApiResponse<string>.ErrorResult(error));
 140            }
 141
 0142            return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true }, "Novedad de período actualizada exit
 143        }
 0144        catch (Exception ex)
 145        {
 0146            _logger.LogError(ex, "Error al actualizar novedad de período {Id}", id);
 0147            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 148        }
 0149    }
 150
 151    [HttpDelete("{id}")]
 152    [RequirePermission(PermisoEnum.CrearNovedades)]
 153    public async Task<IActionResult> DeleteNovedad(long id)
 154    {
 155        try
 156        {
 0157            var (success, novedad, error) = await _novedadPeriodoService.DeleteAsync(id);
 0158            if (!success)
 159            {
 0160                if (error?.Contains("no encontrada", StringComparison.OrdinalIgnoreCase) == true)
 161                {
 0162                    return NotFound(ApiResponse<string>.ErrorResult(error));
 163                }
 0164                return Conflict(ApiResponse<string>.ErrorResult(error ?? "No se pudo eliminar la novedad de período"));
 165            }
 166
 0167            return NoContent();
 168        }
 0169        catch (Exception ex)
 170        {
 0171            _logger.LogError(ex, "Error al eliminar novedad de período {Id}", id);
 0172            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 173        }
 0174    }
 175
 176    [HttpPost("{id}/confirmar")]
 177    [RequirePermission(PermisoEnum.ConfirmarNovedades)]
 178    public async Task<IActionResult> ConfirmarNovedad(long id)
 179    {
 180        try
 181        {
 1182            var (success, novedad, error) = await _novedadPeriodoService.ChangeStateToConfirmedAsync(id);
 1183            if (!success)
 184            {
 0185                if (error?.Contains("no encontrada", StringComparison.OrdinalIgnoreCase) == true)
 186                {
 0187                    return NotFound(ApiResponse<string>.ErrorResult(error));
 188                }
 0189                return Conflict(ApiResponse<string>.ErrorResult(error ?? "No se pudo confirmar la novedad de período"));
 190            }
 191
 1192            return Ok(ApiResponse<object>.SuccessResult(new { confirmado = true }, "Novedad de período confirmada exitos
 193        }
 0194        catch (Exception ex)
 195        {
 0196            _logger.LogError(ex, "Error al confirmar novedad de período {Id}", id);
 0197            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 198        }
 1199    }
 200
 201    [HttpPost("{id}/anular")]
 202    [RequirePermission(PermisoEnum.ConfirmarNovedades)]
 203    public async Task<IActionResult> AnularNovedad(long id)
 204    {
 205        try
 206        {
 1207            var (success, novedad, error) = await _novedadPeriodoService.AnularAsync(id);
 1208            if (!success)
 209            {
 1210                if (error?.Contains("no encontrada", StringComparison.OrdinalIgnoreCase) == true)
 211                {
 0212                    return NotFound(ApiResponse<string>.ErrorResult(error));
 213                }
 1214                return Conflict(ApiResponse<string>.ErrorResult(error ?? "No se pudo anular la novedad de período"));
 215            }
 216
 0217            return Ok(ApiResponse<object>.SuccessResult(new { anulada = true }, "Novedad de período anulada exitosamente
 218        }
 0219        catch (Exception ex)
 220        {
 0221            _logger.LogError(ex, "Error al anular novedad de período {Id}", id);
 0222            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 223        }
 1224    }
 225}