< Summary

Information
Class: FAU.DataAccess.Repositories.ReciboRepository
Assembly: FAU.DataAccess
File(s): /home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.DataAccess/Repositories/ReciboRepository.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 145
Coverable lines: 145
Total lines: 201
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 62
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%210%
ObtenerVersionMaximaAsync()100%210%
ObtenerResumenesAsync()0%156120%
ObtenerDatosReciboAsync()0%1806420%

File(s)

/home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.DataAccess/Repositories/ReciboRepository.cs

#LineLine coverage
 1using FAU.Entidades;
 2using Microsoft.EntityFrameworkCore;
 3
 4namespace FAU.DataAccess.Repositories;
 5
 6public class ReciboRepository : IReciboRepository
 7{
 8    private readonly ApplicationDbContext _context;
 9
 010    public ReciboRepository(ApplicationDbContext context)
 11    {
 012        _context = context;
 013    }
 14
 15    public async Task<int> ObtenerVersionMaximaAsync(long periodoId)
 16    {
 017        return await _context.LiquidacionItems
 018            .AsNoTracking()
 019            .Where(i => i.PeriodoId == periodoId)
 020            .MaxAsync(i => (int?)i.Version) ?? 0;
 021    }
 22
 23    public async Task<List<ReciboResumenDto>> ObtenerResumenesAsync(long periodoId, int version, ReciboFiltroRequest fil
 24    {
 025        var query = _context.RelacionesLaborales
 026            .AsNoTracking()
 027            .Include(r => r.Persona)
 028                .ThenInclude(p => p.CuentasBancarias)
 029                    .ThenInclude(c => c.Banco)
 030            .Include(r => r.Regimen)
 031            .Include(r => r.Programa)
 032            .Include(r => r.Unidad)
 033            .Where(r => r.Estado == EstadoRelacion.Activo);
 34
 035        if (!string.IsNullOrWhiteSpace(filtro.Cedula))
 036            query = query.Where(r => r.Persona.Cedula == filtro.Cedula);
 37
 038        if (filtro.ProgramaId.HasValue)
 039            query = query.Where(r => r.ProgramaId == filtro.ProgramaId.Value);
 40
 041        if (filtro.UnidadId.HasValue)
 042            query = query.Where(r => r.UnidadId == filtro.UnidadId.Value);
 43
 044        var relaciones = await query.ToListAsync();
 45
 46        // Obtener cédulas que tienen liquidación en el período/versión
 047        var cedulasConLiquidacion = await _context.LiquidacionEstadosPersonal
 048            .AsNoTracking()
 049            .Where(e => e.PeriodoId == periodoId && e.Version == version)
 050            .Select(e => e.Cedula)
 051            .ToHashSetAsync();
 52
 53        // Calcular líquido pagable (suma de todos los ítems por cédula)
 054        var liquidosPorCedula = await _context.LiquidacionItems
 055            .AsNoTracking()
 056            .Where(i => i.PeriodoId == periodoId && i.Version == version)
 057            .GroupBy(i => i.Cedula)
 058            .Select(g => new { Cedula = g.Key, Liquido = g.Sum(i => i.Importe) })
 059            .ToDictionaryAsync(x => x.Cedula, x => x.Liquido);
 60
 061        var resultados = relaciones
 062            .Where(r => cedulasConLiquidacion.Contains(r.Persona.Cedula))
 063            .ToList();
 64
 065        if (!string.IsNullOrWhiteSpace(filtro.Regimen))
 66        {
 067            var regimenNorm = filtro.Regimen.Replace('_', '-').ToLowerInvariant();
 068            resultados = regimenNorm switch
 069            {
 070                "ley-vieja" => resultados.Where(r => r.Regimen.EsLeyVieja).ToList(),
 071                "ley-nueva" => resultados.Where(r => !r.Regimen.EsLeyVieja).ToList(),
 072                _ => resultados.Where(r => r.Regimen.NumeroLey.Contains(filtro.Regimen, StringComparison.OrdinalIgnoreCa
 073            };
 74        }
 75
 076        return resultados.Select(r => new ReciboResumenDto
 077        {
 078            RelacionLaboralId   = r.Id,
 079            Cedula       = r.Persona.Cedula,
 080            Nombre       = r.Persona.PrimerNombre,
 081            Apellido     = r.Persona.PrimerApellido,
 082            Regimen      = r.Regimen.NumeroLey,
 083            Programa     = r.Programa?.Denominacion ?? string.Empty,
 084            Unidad       = r.Unidad?.Denominacion ?? string.Empty,
 085            LiquidoPagable = liquidosPorCedula.TryGetValue(r.Persona.Cedula, out var liq) ? liq : 0m
 086        }).ToList();
 087    }
 88
 89    public async Task<ReciboDto?> ObtenerDatosReciboAsync(long periodoId, int version, long relacionId)
 90    {
 091        var relacion = await _context.RelacionesLaborales
 092            .AsNoTracking()
 093            .Include(r => r.Persona)
 094                .ThenInclude(p => p.CuentasBancarias.Where(c => c.Estado == "activa"))
 095                    .ThenInclude(c => c.Banco)
 096            .Include(r => r.Regimen)
 097            .Include(r => r.Programa)
 098            .Include(r => r.Unidad)
 099            .Include(r => r.Grado)
 0100            .Include(r => r.Escalafon)
 0101            .FirstOrDefaultAsync(r => r.Id == relacionId);
 102
 0103        if (relacion == null) return null;
 104
 0105        var cedula = relacion.Persona.Cedula;
 106
 0107        var items = await _context.LiquidacionItems
 0108            .AsNoTracking()
 0109            .Where(i => i.PeriodoId == periodoId && i.Version == version && i.Cedula == cedula)
 0110            .ToListAsync();
 111
 0112        if (!items.Any()) return null;
 113
 0114        var periodo = await _context.PeriodosLiquidacion
 0115            .AsNoTracking()
 0116            .Where(p => p.Id == periodoId)
 0117            .Select(p => new { p.Anio, p.Mes })
 0118            .FirstOrDefaultAsync();
 119
 120        // Obtener tipos de catálogo para clasificar ítems
 0121        var codigosNumericos = items
 0122            .Select(i => i.CodigoConcepto)
 0123            .Where(c => int.TryParse(c, out _))
 0124            .Select(int.Parse)
 0125            .ToHashSet();
 126
 0127        var catalogoPorCodigo = await _context.CatalogoItems
 0128            .AsNoTracking()
 0129            .Where(c => codigosNumericos.Contains(c.Codigo))
 0130            .ToDictionaryAsync(c => c.Codigo.ToString(), c => c.Tipo);
 131
 0132        var haberes           = new List<ReciboItemDto>();
 0133        var descuentosLegales = new List<ReciboItemDto>();
 0134        var descuentosPersonales = new List<ReciboItemDto>();
 135
 0136        foreach (var item in items.OrderBy(i => i.CodigoConcepto))
 137        {
 0138            var dto = new ReciboItemDto
 0139            {
 0140                Codigo      = item.CodigoConcepto,
 0141                Descripcion = item.NombreConcepto,
 0142                RubroContable = item.RubroContable,
 0143                Monto       = item.Importe
 0144            };
 145
 0146            if (item.Importe > 0)
 147            {
 0148                haberes.Add(dto);
 149            }
 0150            else if (catalogoPorCodigo.TryGetValue(item.CodigoConcepto, out var tipo) &&
 0151                     string.Equals(tipo, "descuento_legal", StringComparison.OrdinalIgnoreCase))
 152            {
 0153                descuentosLegales.Add(dto);
 154            }
 155            else
 156            {
 0157                descuentosPersonales.Add(dto);
 158            }
 159        }
 160
 0161        var totalHaberes           = haberes.Sum(i => i.Monto);
 0162        var totalDescuentosLegales = Math.Abs(descuentosLegales.Sum(i => i.Monto));
 0163        var totalDescuentosPersonales = Math.Abs(descuentosPersonales.Sum(i => i.Monto));
 0164        var totalDescuentos        = totalDescuentosLegales + totalDescuentosPersonales;
 0165        var liquidoPagable         = totalHaberes - totalDescuentos;
 166
 0167        var cuentaActiva = relacion.Persona.CuentasBancarias.FirstOrDefault();
 168
 0169        return new ReciboDto
 0170        {
 0171            Anio          = periodo?.Anio ?? 0,
 0172            Mes           = periodo?.Mes ?? 0,
 0173            RelacionLaboralId    = relacion.Id,
 0174            Cedula        = cedula,
 0175            PrimerNombre  = relacion.Persona.PrimerNombre,
 0176            SegundoNombre = relacion.Persona.SegundoNombre ?? string.Empty,
 0177            PrimerApellido  = relacion.Persona.PrimerApellido,
 0178            SegundoApellido = relacion.Persona.SegundoApellido ?? string.Empty,
 0179            Grado         = relacion.Grado?.Denominacion ?? string.Empty,
 0180            Escalafon     = relacion.Escalafon?.Denominacion ?? string.Empty,
 0181            Regimen       = relacion.Regimen.NumeroLey,
 0182            Unidad        = relacion.Unidad?.Denominacion ?? string.Empty,
 0183            Programa      = relacion.Programa?.Denominacion ?? string.Empty,
 0184            Haberes               = haberes,
 0185            DescuentosLegales     = descuentosLegales,
 0186            DescuentosPersonales  = descuentosPersonales,
 0187            TotalHaberes          = totalHaberes,
 0188            TotalDescuentosLegales   = totalDescuentosLegales,
 0189            TotalDescuentosPersonales = totalDescuentosPersonales,
 0190            TotalDescuentos       = totalDescuentos,
 0191            LiquidoPagable        = liquidoPagable,
 0192            DatosBancarios = cuentaActiva != null
 0193                ? new ReciboDatosBancariosDto
 0194                  {
 0195                      Banco  = cuentaActiva.Banco?.Nombre,
 0196                      Cuenta = cuentaActiva.NumeroCuenta
 0197                  }
 0198                : new ReciboDatosBancariosDto { Observacion = "Sin cuenta registrada" }
 0199        };
 0200    }
 201}