< Summary

Information
Class: FAU.API.Controllers.AcreedoresController
Assembly: FAU.API
File(s): /home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Controllers/AcreedoresController.cs
Line coverage
78%
Covered lines: 51
Uncovered lines: 14
Coverable lines: 65
Total lines: 170
Line coverage: 78.4%
Branch coverage
55%
Covered branches: 10
Total branches: 18
Branch coverage: 55.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%
GetAcreedores()100%1181.25%
GetAcreedor()100%2284.21%
CreateAcreedor()50%9871.42%
UpdateAcreedor()50%12860%

File(s)

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

#LineLine coverage
 1using FAU.Entidades;
 2using FAU.Logica.DTOs;
 3using FAU.Logica.Services;
 4using Microsoft.AspNetCore.Authorization;
 5using Microsoft.AspNetCore.Http;
 6using Microsoft.AspNetCore.Mvc;
 7
 8namespace FAU.API.Controllers;
 9
 10/// <summary>
 11/// Gestión del catálogo de acreedores
 12/// </summary>
 13[ApiController]
 14[Route("api/acreedores")]
 15[Authorize]
 16[Produces("application/json")]
 17public class AcreedoresController : ControllerBase
 18{
 19    private readonly IAcreedorService _acreedorService;
 20    private readonly ILogger<AcreedoresController> _logger;
 21
 922    public AcreedoresController(
 923        IAcreedorService acreedorService,
 924        ILogger<AcreedoresController> logger)
 25    {
 926        _acreedorService = acreedorService;
 927        _logger = logger;
 928    }
 29
 30    /// <summary>Listar acreedores con paginación y filtros</summary>
 31    /// <remarks>Roles: Administrador, Supervisor, Usuario</remarks>
 32    [HttpGet]
 33    [Authorize(Roles = "Administrador,Supervisor,Usuario")]
 34    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 35    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 36    public async Task<IActionResult> GetAcreedores(
 37        [FromQuery] int page = 1,
 38        [FromQuery] int pageSize = 20,
 39        [FromQuery] string? q = null,
 40        [FromQuery] bool? activo = null,
 41        [FromQuery] string? categoria = null)
 42    {
 43        try
 44        {
 345            var resultado = await _acreedorService.GetPagedAsync(page, pageSize, q, activo, categoria);
 46
 347            var response = new
 348            {
 349                items = resultado.Items,
 350                page = resultado.Page,
 351                pageSize = resultado.PageSize,
 352                totalCount = resultado.TotalCount,
 353                totalPages = resultado.TotalPages,
 354                hasPreviousPage = resultado.HasPreviousPage,
 355                hasNextPage = resultado.HasNextPage,
 356            };
 57
 358            return Ok(ApiResponse<object>.SuccessResult(response));
 59        }
 060        catch (Exception ex)
 61        {
 062            _logger.LogError(ex, "Error al obtener acreedores");
 063            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 64        }
 365    }
 66
 67    /// <summary>Obtener detalle de un acreedor por ID</summary>
 68    /// <remarks>Roles: Administrador, Supervisor, Usuario</remarks>
 69    [HttpGet("{id}")]
 70    [Authorize(Roles = "Administrador,Supervisor,Usuario")]
 71    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 72    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)]
 73    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 74    public async Task<IActionResult> GetAcreedor(long id)
 75    {
 76        try
 77        {
 278            var acreedor = await _acreedorService.GetByIdAsync(id);
 79
 280            if (acreedor == null)
 181                return NotFound(ApiResponse<string>.ErrorResult("Acreedor no encontrado"));
 82
 183            var response = new
 184            {
 185                id = acreedor.Id,
 186                codigo = acreedor.Codigo,
 187                nombre = acreedor.Nombre,
 188                categoriaDeficit = acreedor.CategoriaDeficit,
 189                ordenLegalDeficit = acreedor.OrdenLegalDeficit,
 190                formatoArchivo = acreedor.FormatoArchivo,
 191                contacto = acreedor.Contacto,
 192                activo = acreedor.Activo,
 193            };
 94
 195            return Ok(ApiResponse<object>.SuccessResult(response));
 96        }
 097        catch (Exception ex)
 98        {
 099            _logger.LogError(ex, "Error al obtener acreedor {Id}", id);
 0100            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 101        }
 2102    }
 103
 104    /// <summary>Crear un nuevo acreedor</summary>
 105    /// <remarks>Roles: Administrador</remarks>
 106    [HttpPost]
 107    [Authorize(Roles = "Administrador")]
 108    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)]
 109    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)]
 110    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)]
 111    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 112    public async Task<IActionResult> CreateAcreedor([FromBody] CreateAcreedorRequest request)
 113    {
 114        try
 115        {
 2116            var (success, acreedor, error) = await _acreedorService.CreateAsync(request);
 117
 2118            if (!success)
 119            {
 1120                if (error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true)
 1121                    return Conflict(ApiResponse<string>.ErrorResult(error));
 122
 0123                return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear acreedor"));
 124            }
 125
 1126            var response = new { id = acreedor!.Id, creado = true };
 127
 1128            return CreatedAtAction(
 1129                nameof(GetAcreedor),
 1130                new { id = acreedor.Id },
 1131                ApiResponse<object>.SuccessResult(response, "Acreedor creado exitosamente"));
 132        }
 0133        catch (Exception ex)
 134        {
 0135            _logger.LogError(ex, "Error al crear acreedor");
 0136            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 137        }
 2138    }
 139
 140    /// <summary>Editar un acreedor existente (incluye activar/desactivar)</summary>
 141    /// <remarks>Roles: Administrador</remarks>
 142    [HttpPut("{id}")]
 143    [Authorize(Roles = "Administrador")]
 144    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 145    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)]
 146    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)]
 147    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 148    public async Task<IActionResult> UpdateAcreedor(long id, [FromBody] UpdateAcreedorRequest request)
 149    {
 150        try
 151        {
 2152            var (success, _, error) = await _acreedorService.UpdateAsync(id, request);
 153
 2154            if (!success)
 155            {
 1156                if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true)
 1157                    return NotFound(ApiResponse<string>.ErrorResult(error));
 158
 0159                return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al actualizar acreedor"));
 160            }
 161
 1162            return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true }, "Acreedor actualizado exitosamente")
 163        }
 0164        catch (Exception ex)
 165        {
 0166            _logger.LogError(ex, "Error al actualizar acreedor {Id}", id);
 0167            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 168        }
 2169    }
 170}