< 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: 178
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>
 31    /// Listar acreedores con paginación y filtros
 32    /// GET /api/acreedores?page=1&pageSize=20&q=&activo=&categoria=
 33    /// </summary>
 34    [HttpGet]
 35    [FAU.API.Security.RequirePermission(PermisoEnum.VerAcreedores)]
 36    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 37    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 38    public async Task<IActionResult> GetAcreedores(
 39        [FromQuery] int page = 1,
 40        [FromQuery] int pageSize = 20,
 41        [FromQuery] string? q = null,
 42        [FromQuery] bool? activo = null,
 43        [FromQuery] string? categoria = null)
 44    {
 45        try
 46        {
 347            var resultado = await _acreedorService.GetPagedAsync(page, pageSize, q, activo, categoria);
 48
 349            var response = new
 350            {
 351                items = resultado.Items,
 352                page = resultado.Page,
 353                pageSize = resultado.PageSize,
 354                totalCount = resultado.TotalCount,
 355                totalPages = resultado.TotalPages,
 356                hasPreviousPage = resultado.HasPreviousPage,
 357                hasNextPage = resultado.HasNextPage,
 358            };
 59
 360            return Ok(ApiResponse<object>.SuccessResult(response));
 61        }
 062        catch (Exception ex)
 63        {
 064            _logger.LogError(ex, "Error al obtener acreedores");
 065            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 66        }
 367    }
 68
 69    /// <summary>
 70    /// Obtener detalle de un acreedor por ID
 71    /// GET /api/acreedores/{id}
 72    /// </summary>
 73    [HttpGet("{id}")]
 74    [FAU.API.Security.RequirePermission(PermisoEnum.VerAcreedores)]
 75    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 76    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)]
 77    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 78    public async Task<IActionResult> GetAcreedor(long id)
 79    {
 80        try
 81        {
 282            var acreedor = await _acreedorService.GetByIdAsync(id);
 83
 284            if (acreedor == null)
 185                return NotFound(ApiResponse<string>.ErrorResult("Acreedor no encontrado"));
 86
 187            var response = new
 188            {
 189                id = acreedor.Id,
 190                codigo = acreedor.Codigo,
 191                nombre = acreedor.Nombre,
 192                categoriaDeficit = acreedor.CategoriaDeficit,
 193                ordenLegalDeficit = acreedor.OrdenLegalDeficit,
 194                formatoArchivo = acreedor.FormatoArchivo,
 195                contacto = acreedor.Contacto,
 196                activo = acreedor.Activo,
 197            };
 98
 199            return Ok(ApiResponse<object>.SuccessResult(response));
 100        }
 0101        catch (Exception ex)
 102        {
 0103            _logger.LogError(ex, "Error al obtener acreedor {Id}", id);
 0104            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 105        }
 2106    }
 107
 108    /// <summary>
 109    /// Crear un nuevo acreedor
 110    /// POST /api/acreedores
 111    /// </summary>
 112    [HttpPost]
 113    [FAU.API.Security.RequirePermission(PermisoEnum.CrearAcreedor)]
 114    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status201Created)]
 115    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)]
 116    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status409Conflict)]
 117    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 118    public async Task<IActionResult> CreateAcreedor([FromBody] CreateAcreedorRequest request)
 119    {
 120        try
 121        {
 2122            var (success, acreedor, error) = await _acreedorService.CreateAsync(request);
 123
 2124            if (!success)
 125            {
 1126                if (error?.Contains("ya existe", StringComparison.OrdinalIgnoreCase) == true)
 1127                    return Conflict(ApiResponse<string>.ErrorResult(error));
 128
 0129                return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al crear acreedor"));
 130            }
 131
 1132            var response = new { id = acreedor!.Id, creado = true };
 133
 1134            return CreatedAtAction(
 1135                nameof(GetAcreedor),
 1136                new { id = acreedor.Id },
 1137                ApiResponse<object>.SuccessResult(response, "Acreedor creado exitosamente"));
 138        }
 0139        catch (Exception ex)
 140        {
 0141            _logger.LogError(ex, "Error al crear acreedor");
 0142            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 143        }
 2144    }
 145
 146    /// <summary>
 147    /// Editar un acreedor existente (incluye activar/desactivar)
 148    /// PUT /api/acreedores/{id}
 149    /// </summary>
 150    [HttpPut("{id}")]
 151    [FAU.API.Security.RequirePermission(PermisoEnum.ActualizarAcreedor)]
 152    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status200OK)]
 153    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status400BadRequest)]
 154    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status404NotFound)]
 155    [ProducesResponseType(typeof(ApiResponse<string>), StatusCodes.Status500InternalServerError)]
 156    public async Task<IActionResult> UpdateAcreedor(long id, [FromBody] UpdateAcreedorRequest request)
 157    {
 158        try
 159        {
 2160            var (success, _, error) = await _acreedorService.UpdateAsync(id, request);
 161
 2162            if (!success)
 163            {
 1164                if (error?.Contains("no encontrado", StringComparison.OrdinalIgnoreCase) == true)
 1165                    return NotFound(ApiResponse<string>.ErrorResult(error));
 166
 0167                return BadRequest(ApiResponse<string>.ErrorResult(error ?? "Error al actualizar acreedor"));
 168            }
 169
 1170            return Ok(ApiResponse<object>.SuccessResult(new { actualizado = true }, "Acreedor actualizado exitosamente")
 171        }
 0172        catch (Exception ex)
 173        {
 0174            _logger.LogError(ex, "Error al actualizar acreedor {Id}", id);
 0175            return StatusCode(500, ApiResponse<string>.ErrorResult("Error interno del servidor"));
 176        }
 2177    }
 178}