| | | 1 | | using FAU.DataAccess.Repositories; |
| | | 2 | | using FAU.Entidades; |
| | | 3 | | using FAU.Logica.DTOs; |
| | | 4 | | using FAU.Logica.Validadores; |
| | | 5 | | using Microsoft.Extensions.Logging; |
| | | 6 | | |
| | | 7 | | namespace FAU.Logica.Services; |
| | | 8 | | |
| | | 9 | | public class DependienteService : IDependienteService |
| | | 10 | | { |
| | 1 | 11 | | private static readonly HashSet<string> TiposValidos = new(StringComparer.Ordinal) |
| | 1 | 12 | | { |
| | 1 | 13 | | "hijo", "conyuge_sin_ingresos" |
| | 1 | 14 | | }; |
| | | 15 | | |
| | 1 | 16 | | private static readonly HashSet<short> PorcentajesValidos = new() { 50, 100 }; |
| | | 17 | | |
| | | 18 | | private readonly IDependienteRepository _dependienteRepository; |
| | | 19 | | private readonly IPersonalRepository _personalRepository; |
| | | 20 | | private readonly ILogger<DependienteService> _logger; |
| | | 21 | | private readonly IAuditoriaService _auditoriaService; |
| | | 22 | | private readonly ICurrentUserContext _currentUser; |
| | | 23 | | |
| | 21 | 24 | | public DependienteService( |
| | 21 | 25 | | IDependienteRepository dependienteRepository, |
| | 21 | 26 | | IPersonalRepository personalRepository, |
| | 21 | 27 | | ILogger<DependienteService> logger, |
| | 21 | 28 | | IAuditoriaService auditoriaService, |
| | 21 | 29 | | ICurrentUserContext currentUser) |
| | | 30 | | { |
| | 21 | 31 | | _dependienteRepository = dependienteRepository; |
| | 21 | 32 | | _personalRepository = personalRepository; |
| | 21 | 33 | | _logger = logger; |
| | 21 | 34 | | _auditoriaService = auditoriaService; |
| | 21 | 35 | | _currentUser = currentUser; |
| | 21 | 36 | | } |
| | | 37 | | |
| | | 38 | | public async Task<PagedResult<DependienteDto>> GetDependientesPagedAsync( |
| | | 39 | | int page, int pageSize, string? cedulaTitular = null, string? tipo = null, bool? activo = null) |
| | | 40 | | { |
| | 1 | 41 | | long? personaId = null; |
| | 1 | 42 | | if (!string.IsNullOrWhiteSpace(cedulaTitular)) |
| | | 43 | | { |
| | 0 | 44 | | var relacion = await _personalRepository.GetByCedulaAsync(cedulaTitular); |
| | 0 | 45 | | if (relacion == null) |
| | 0 | 46 | | return new PagedResult<DependienteDto> { Items = [], Page = page, PageSize = pageSize, TotalCount = 0 }; |
| | 0 | 47 | | personaId = relacion.PersonaId; |
| | | 48 | | } |
| | | 49 | | |
| | 1 | 50 | | var (items, totalCount) = await _dependienteRepository.GetDependientesPagedAsync(page, pageSize, personaId, tipo |
| | 1 | 51 | | return new PagedResult<DependienteDto> |
| | 1 | 52 | | { |
| | 1 | 53 | | Items = items.Select(MapToDto), |
| | 1 | 54 | | Page = page, |
| | 1 | 55 | | PageSize = pageSize, |
| | 1 | 56 | | TotalCount = totalCount |
| | 1 | 57 | | }; |
| | 1 | 58 | | } |
| | | 59 | | |
| | | 60 | | public async Task<IEnumerable<DependienteDto>> GetDependientesByPersonaAsync(string cedula) |
| | | 61 | | { |
| | 1 | 62 | | var relacion = await _personalRepository.GetByCedulaAsync(cedula); |
| | 1 | 63 | | if (relacion == null) return []; |
| | 1 | 64 | | var dependientes = await _dependienteRepository.GetDependientesByPersonaAsync(relacion.PersonaId); |
| | 1 | 65 | | return dependientes.Select(MapToDto); |
| | 1 | 66 | | } |
| | | 67 | | |
| | | 68 | | public async Task<DependienteDto?> GetDependienteByIdAsync(long id) |
| | | 69 | | { |
| | 4 | 70 | | var dependiente = await _dependienteRepository.GetDependienteByIdAsync(id); |
| | 4 | 71 | | return dependiente == null ? null : MapToDto(dependiente); |
| | 4 | 72 | | } |
| | | 73 | | |
| | | 74 | | public async Task<(bool Success, Dependiente? Dependiente, string? Error)> CreateDependienteAsync(CreateDependienteR |
| | | 75 | | { |
| | 12 | 76 | | if (!TiposValidos.Contains(request.Tipo)) |
| | 1 | 77 | | return (false, null, $"Tipo inválido. Valores aceptados: {string.Join(", ", TiposValidos)}"); |
| | | 78 | | |
| | | 79 | | // Validaciones específicas por tipo |
| | 11 | 80 | | if (request.Tipo == "hijo") |
| | | 81 | | { |
| | 8 | 82 | | if (!request.FechaNacimiento.HasValue) |
| | 1 | 83 | | return (false, null, "fecha_nacimiento es obligatoria para dependientes de tipo hijo"); |
| | | 84 | | |
| | 7 | 85 | | if (request.FechaNacimiento.Value.Date > DateTime.Today) |
| | 1 | 86 | | return (false, null, "fecha_nacimiento no puede ser una fecha futura"); |
| | | 87 | | |
| | 6 | 88 | | if (request.PorcentajeDeduccion.HasValue && !PorcentajesValidos.Contains(request.PorcentajeDeduccion.Value)) |
| | 1 | 89 | | return (false, null, "porcentaje_deduccion debe ser 50 o 100"); |
| | | 90 | | } |
| | 3 | 91 | | else if (request.Tipo == "conyuge_sin_ingresos") |
| | | 92 | | { |
| | 3 | 93 | | if (request.PorcentajeDeduccion.HasValue) |
| | 1 | 94 | | return (false, null, "porcentaje_deduccion no aplica para tipo conyuge_sin_ingresos"); |
| | | 95 | | } |
| | | 96 | | |
| | 7 | 97 | | if (!string.IsNullOrWhiteSpace(request.Cedula) && !CedulaValidator.Validar(request.Cedula)) |
| | 1 | 98 | | return (false, null, "La cédula ingresada no es válida"); |
| | | 99 | | |
| | 6 | 100 | | var vigenteDesde = DateTime.Today; |
| | | 101 | | |
| | 6 | 102 | | if (request.VigenteHasta.HasValue && request.VigenteHasta.Value < vigenteDesde) |
| | 1 | 103 | | return (false, null, "vigente_hasta debe ser mayor o igual a la fecha actual"); |
| | | 104 | | |
| | | 105 | | // Resolver cédula titular → personaId |
| | 5 | 106 | | var relacionActiva = await _personalRepository.GetByCedulaAsync(request.CedulaTitular); |
| | 5 | 107 | | if (relacionActiva == null) |
| | 1 | 108 | | return (false, null, $"No se encontró personal activo con cédula {request.CedulaTitular}"); |
| | | 109 | | |
| | 4 | 110 | | var personaId = relacionActiva.PersonaId; |
| | | 111 | | |
| | | 112 | | // Restricción: solo un cónyuge activo por persona |
| | 4 | 113 | | if (request.Tipo == "conyuge_sin_ingresos") |
| | | 114 | | { |
| | 2 | 115 | | if (await _dependienteRepository.ExisteConyugeActivoAsync(personaId)) |
| | 1 | 116 | | return (false, null, "Ya existe un dependiente activo de tipo conyuge_sin_ingresos para este funcionario |
| | | 117 | | } |
| | | 118 | | |
| | 3 | 119 | | var dependiente = new Dependiente |
| | 3 | 120 | | { |
| | 3 | 121 | | PersonaId = personaId, |
| | 3 | 122 | | Tipo = request.Tipo, |
| | 3 | 123 | | Nombre = request.Nombre, |
| | 3 | 124 | | Cedula = request.Cedula, |
| | 3 | 125 | | FechaNacimiento = request.FechaNacimiento, |
| | 3 | 126 | | Discapacitado = request.Discapacitado, |
| | 3 | 127 | | PorcentajeDeduccion = request.Tipo == "hijo" ? request.PorcentajeDeduccion : null, |
| | 3 | 128 | | VigenteDesde = vigenteDesde, |
| | 3 | 129 | | VigenteHasta = request.VigenteHasta, |
| | 3 | 130 | | Activo = true |
| | 3 | 131 | | }; |
| | | 132 | | |
| | 3 | 133 | | var creado = await _dependienteRepository.CreateDependienteAsync(dependiente); |
| | 3 | 134 | | _logger.LogInformation("Dependiente tipo {Tipo} creado para persona {PersonaId}", dependiente.Tipo, dependiente. |
| | 3 | 135 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.CrearDependientes, ContextoEnum.D |
| | 3 | 136 | | return (true, creado, null); |
| | 12 | 137 | | } |
| | | 138 | | |
| | | 139 | | public async Task<(bool Success, Dependiente? Dependiente, string? Error)> UpdateDependienteAsync(long id, UpdateDep |
| | | 140 | | { |
| | 3 | 141 | | var dependiente = await _dependienteRepository.GetDependienteByIdAsync(id); |
| | 4 | 142 | | if (dependiente == null) return (false, null, "Dependiente no encontrado"); |
| | | 143 | | |
| | 2 | 144 | | if (request.VigenteHasta.HasValue && request.VigenteHasta.Value < dependiente.VigenteDesde) |
| | 0 | 145 | | return (false, null, "vigente_hasta debe ser mayor o igual a vigente_desde"); |
| | | 146 | | |
| | 2 | 147 | | if (request.PorcentajeDeduccion.HasValue) |
| | | 148 | | { |
| | 0 | 149 | | if (dependiente.Tipo != "hijo") |
| | 0 | 150 | | return (false, null, "porcentaje_deduccion no aplica para tipo conyuge_sin_ingresos"); |
| | 0 | 151 | | if (!PorcentajesValidos.Contains(request.PorcentajeDeduccion.Value)) |
| | 0 | 152 | | return (false, null, "porcentaje_deduccion debe ser 50 o 100"); |
| | 0 | 153 | | dependiente.PorcentajeDeduccion = request.PorcentajeDeduccion; |
| | | 154 | | } |
| | | 155 | | |
| | 2 | 156 | | if (request.Discapacitado.HasValue) |
| | 0 | 157 | | dependiente.Discapacitado = request.Discapacitado.Value; |
| | | 158 | | |
| | 2 | 159 | | if (request.VigenteHasta.HasValue) |
| | 0 | 160 | | dependiente.VigenteHasta = request.VigenteHasta; |
| | | 161 | | |
| | 2 | 162 | | if (request.Activo.HasValue) |
| | | 163 | | { |
| | | 164 | | // Si se reactiva un cónyuge, verificar que no haya otro activo |
| | 2 | 165 | | if (request.Activo.Value && dependiente.Tipo == "conyuge_sin_ingresos" && !dependiente.Activo) |
| | | 166 | | { |
| | 1 | 167 | | if (await _dependienteRepository.ExisteConyugeActivoAsync(dependiente.PersonaId)) |
| | 1 | 168 | | return (false, null, "Ya existe un dependiente activo de tipo conyuge_sin_ingresos para este funcion |
| | | 169 | | } |
| | | 170 | | |
| | 1 | 171 | | dependiente.Activo = request.Activo.Value; |
| | | 172 | | // Al desactivar sin fecha de cierre, setear vigente_hasta = hoy |
| | 1 | 173 | | if (!request.Activo.Value && !dependiente.VigenteHasta.HasValue && !request.VigenteHasta.HasValue) |
| | 1 | 174 | | dependiente.VigenteHasta = DateTime.UtcNow.Date; |
| | | 175 | | } |
| | | 176 | | |
| | 1 | 177 | | var actualizado = await _dependienteRepository.UpdateDependienteAsync(dependiente); |
| | 1 | 178 | | await _auditoriaService.LogAuditoriaAsync(_currentUser.UserId ?? 0, AccionEnum.ActualizarDependientes, ContextoE |
| | 1 | 179 | | return (true, actualizado, null); |
| | 3 | 180 | | } |
| | | 181 | | |
| | | 182 | | // ── Helper ────────────────────────────────────────────────────────────── |
| | | 183 | | |
| | | 184 | | private static DependienteDto MapToDto(Dependiente d) |
| | | 185 | | { |
| | 5 | 186 | | var tipoDeduccion = CalcularTipoDeduccionIrpf(d); |
| | 5 | 187 | | var aplicaDeduccion = d.Activo && tipoDeduccion != null; |
| | | 188 | | |
| | 5 | 189 | | return new DependienteDto |
| | 5 | 190 | | { |
| | 5 | 191 | | Id = d.Id, |
| | 5 | 192 | | PersonaId = d.PersonaId, |
| | 5 | 193 | | CedulaTitular = d.Persona?.Cedula ?? string.Empty, |
| | 5 | 194 | | NombreTitular = d.Persona?.NombreCompleto ?? string.Empty, |
| | 5 | 195 | | Tipo = d.Tipo, |
| | 5 | 196 | | Nombre = d.Nombre, |
| | 5 | 197 | | Cedula = d.Cedula, |
| | 5 | 198 | | FechaNacimiento = d.FechaNacimiento, |
| | 5 | 199 | | Discapacitado = d.Discapacitado, |
| | 5 | 200 | | PorcentajeDeduccion = d.PorcentajeDeduccion, |
| | 5 | 201 | | VigenteDesde = d.VigenteDesde, |
| | 5 | 202 | | VigenteHasta = d.VigenteHasta, |
| | 5 | 203 | | Activo = d.Activo, |
| | 5 | 204 | | AplicaDeduccion = aplicaDeduccion, |
| | 5 | 205 | | TipoDeduccionIrpf = d.Activo ? tipoDeduccion : null |
| | 5 | 206 | | }; |
| | | 207 | | } |
| | | 208 | | |
| | | 209 | | private static string? CalcularTipoDeduccionIrpf(Dependiente d) |
| | | 210 | | { |
| | 5 | 211 | | if (d.Tipo == "conyuge_sin_ingresos") |
| | 0 | 212 | | return "conyuge_sin_ingresos"; |
| | | 213 | | |
| | 5 | 214 | | if (d.Tipo == "hijo") |
| | | 215 | | { |
| | 5 | 216 | | if (d.Discapacitado) |
| | 1 | 217 | | return "hijo_discapacidad"; |
| | | 218 | | |
| | 4 | 219 | | if (d.FechaNacimiento.HasValue && CalcularEdad(d.FechaNacimiento.Value) < 18) |
| | 1 | 220 | | return "hijo_menor"; |
| | | 221 | | } |
| | | 222 | | |
| | 3 | 223 | | return null; |
| | | 224 | | } |
| | | 225 | | |
| | | 226 | | private static int CalcularEdad(DateTime fechaNacimiento) |
| | | 227 | | { |
| | 2 | 228 | | var hoy = DateTime.Today; |
| | 2 | 229 | | var edad = hoy.Year - fechaNacimiento.Year; |
| | 2 | 230 | | if (fechaNacimiento.Date > hoy.AddYears(-edad)) edad--; |
| | 2 | 231 | | return edad; |
| | | 232 | | } |
| | | 233 | | } |