| | | 1 | | using FAU.DataAccess.Repositories; |
| | | 2 | | using FAU.Entidades; |
| | | 3 | | using FAU.Logica.DTOs; |
| | | 4 | | |
| | | 5 | | namespace FAU.Logica.Services; |
| | | 6 | | |
| | | 7 | | public class BeneficioSocialService : IBeneficioSocialService |
| | | 8 | | { |
| | | 9 | | private const string EstadoActivo = "activo"; |
| | | 10 | | private const string EstadoInactivo = "inactivo"; |
| | | 11 | | private const string EstadoPendienteDoc = "pendiente_doc"; |
| | | 12 | | |
| | | 13 | | private readonly IBeneficioSocialRepository _beneficioSocialRepository; |
| | | 14 | | private readonly IAuditoriaService _auditoriaService; |
| | | 15 | | private readonly IPeriodoGuard _periodoGuard; |
| | | 16 | | private readonly IStorageService _storage; |
| | | 17 | | private readonly IDocumentoRepository _docRepo; |
| | | 18 | | |
| | 10 | 19 | | public BeneficioSocialService( |
| | 10 | 20 | | IBeneficioSocialRepository beneficioSocialRepository, |
| | 10 | 21 | | IAuditoriaService auditoriaService, |
| | 10 | 22 | | IPeriodoGuard periodoGuard, |
| | 10 | 23 | | IStorageService storage, |
| | 10 | 24 | | IDocumentoRepository docRepo) |
| | | 25 | | { |
| | 10 | 26 | | _beneficioSocialRepository = beneficioSocialRepository; |
| | 10 | 27 | | _auditoriaService = auditoriaService; |
| | 10 | 28 | | _periodoGuard = periodoGuard; |
| | 10 | 29 | | _storage = storage; |
| | 10 | 30 | | _docRepo = docRepo; |
| | 10 | 31 | | } |
| | | 32 | | |
| | | 33 | | public async Task<BeneficioSocialDto?> ObtenerPorIdAsync(long id) |
| | | 34 | | { |
| | 2 | 35 | | var entidad = await _beneficioSocialRepository.ObtenerPorIdAsync(id); |
| | 2 | 36 | | return entidad == null ? null : MapearDto(entidad); |
| | 2 | 37 | | } |
| | | 38 | | |
| | | 39 | | public async Task<PagedResult<BeneficioSocialDto>> ObtenerPaginadoAsync(int pagina, int tamano, long? personaId = nu |
| | | 40 | | { |
| | 2 | 41 | | if (pagina < 1) pagina = 1; |
| | 1 | 42 | | if (tamano < 1) tamano = 10; |
| | 2 | 43 | | if (tamano > 100) tamano = 100; |
| | | 44 | | |
| | 1 | 45 | | var (items, totalCount) = await _beneficioSocialRepository.ObtenerPaginadoAsync(pagina, tamano, personaId, estad |
| | | 46 | | |
| | 1 | 47 | | return new PagedResult<BeneficioSocialDto> |
| | 1 | 48 | | { |
| | 1 | 49 | | Items = items.Select(item => MapearDto(item)).ToList(), |
| | 1 | 50 | | Page = pagina, |
| | 1 | 51 | | PageSize = tamano, |
| | 1 | 52 | | TotalCount = totalCount |
| | 1 | 53 | | }; |
| | 1 | 54 | | } |
| | | 55 | | |
| | | 56 | | public async Task<(bool Exito, BeneficioSocialDto? Resultado, string? Error)> CrearAsync(CrearBeneficioSocialRequest |
| | | 57 | | { |
| | 3 | 58 | | await _periodoGuard.VerificarPeriodoAbiertoAsync(); |
| | | 59 | | try |
| | | 60 | | { |
| | 3 | 61 | | var tipo = await _beneficioSocialRepository.ObtenerTipoBeneficioAsync(request.TipoBeneficioId); |
| | 3 | 62 | | if (tipo == null || !tipo.Activo) |
| | | 63 | | { |
| | 0 | 64 | | return (false, null, "Tipo de beneficio no encontrado o inactivo"); |
| | | 65 | | } |
| | | 66 | | |
| | 3 | 67 | | var categoriaEsperada = ConvertirCategoriaRequest(DeterminarCategoria(tipo)); |
| | 3 | 68 | | if (request.CategoriaBeneficio != categoriaEsperada) |
| | | 69 | | { |
| | 0 | 70 | | return (false, null, "La categoria declarada no coincide con el tipo de beneficio seleccionado"); |
| | | 71 | | } |
| | | 72 | | |
| | 3 | 73 | | var personaActiva = await _beneficioSocialRepository.ExistePersonaActivaAsync(request.PersonaId, request.Vig |
| | 3 | 74 | | if (!personaActiva) |
| | | 75 | | { |
| | 1 | 76 | | return (false, null, "La persona no tiene relacion laboral activa para la vigencia indicada"); |
| | | 77 | | } |
| | | 78 | | |
| | 2 | 79 | | var validacion = ValidarReglasPorTipo(tipo, request, esActualizacion: false); |
| | 2 | 80 | | if (!string.IsNullOrEmpty(validacion)) |
| | | 81 | | { |
| | 0 | 82 | | return (false, null, validacion); |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | // Para beneficios mensuales: no permitir más de uno activo del mismo tipo por persona |
| | 2 | 86 | | if (tipo.EsMensual && await _beneficioSocialRepository.ExisteBeneficioActivoMismoTipoAsync(request.PersonaId |
| | | 87 | | { |
| | 0 | 88 | | return (false, null, $"La persona ya tiene un beneficio activo del tipo '{tipo.Nombre}'. Debe darlo de b |
| | | 89 | | } |
| | | 90 | | |
| | 2 | 91 | | var claveEvento = ConstruirClaveEvento(tipo, request.DatosTipo.FechaEvento, request.VigenteDesde); |
| | 2 | 92 | | if (EsBeneficioUnicaVez(tipo) && await _beneficioSocialRepository.ExisteDuplicadoEventoAsync(request.Persona |
| | | 93 | | { |
| | 1 | 94 | | return (false, null, "Existe un beneficio duplicado para un evento de unica vez"); |
| | | 95 | | } |
| | | 96 | | |
| | 1 | 97 | | var retroactividadPendiente = CalcularRetroactividadPendiente(request.VigenteDesde); |
| | 1 | 98 | | if (retroactividadPendiente && !tipo.PermiteRetroactividad) |
| | | 99 | | { |
| | 0 | 100 | | return (false, null, "El tipo de beneficio no permite retroactividad para la vigencia indicada"); |
| | | 101 | | } |
| | | 102 | | |
| | 1 | 103 | | var estado = request.DatosTipo.PendienteDocumentacion ? EstadoPendienteDoc : EstadoActivo; |
| | 1 | 104 | | var entidad = new BeneficioSocial |
| | 1 | 105 | | { |
| | 1 | 106 | | PersonaId = request.PersonaId, |
| | 1 | 107 | | TipoBeneficioId = request.TipoBeneficioId, |
| | 1 | 108 | | Cantidad = (short)Math.Max(request.Cantidad ?? 1, (short)0), |
| | 1 | 109 | | VigenteDesde = request.VigenteDesde.Date, |
| | 1 | 110 | | VigenteHasta = request.VigenteHasta?.Date, |
| | 1 | 111 | | Estado = estado, |
| | 1 | 112 | | DocumentoRespaldo = request.DocumentoRespaldo?.Trim(), |
| | 1 | 113 | | Observaciones = ConstruirObservaciones(request.Observaciones, request.DatosTipo.JustificacionRetroactivo |
| | 1 | 114 | | CreadoPor = usuarioId, |
| | 1 | 115 | | FechaEvento = request.DatosTipo.FechaEvento?.Date, |
| | 1 | 116 | | ClaveEvento = claveEvento, |
| | 1 | 117 | | Subtipo = request.DatosTipo.Subtipo?.Trim().ToUpperInvariant(), |
| | 1 | 118 | | RetroactividadPendiente = retroactividadPendiente |
| | 1 | 119 | | }; |
| | | 120 | | |
| | 1 | 121 | | var creado = await _beneficioSocialRepository.CrearAsync(entidad); |
| | | 122 | | |
| | 1 | 123 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 124 | | usuarioId, |
| | 1 | 125 | | AccionEnum.CrearBeneficio, |
| | 1 | 126 | | ContextoEnum.Beneficios, |
| | 1 | 127 | | host: host, |
| | 1 | 128 | | entidad: nameof(BeneficioSocial), |
| | 1 | 129 | | entidadId: creado.Id, |
| | 1 | 130 | | detalle: new { operacion = "crear", id = creado.Id, personaId = creado.PersonaId, tipoBeneficioId = crea |
| | | 131 | | |
| | 1 | 132 | | var recargado = await _beneficioSocialRepository.ObtenerPorIdAsync(creado.Id); |
| | 1 | 133 | | return (true, recargado == null ? MapearDto(creado, tipo) : MapearDto(recargado), null); |
| | | 134 | | } |
| | 0 | 135 | | catch (Exception ex) |
| | | 136 | | { |
| | 0 | 137 | | return (false, null, $"Error al crear beneficio social: {ex.Message}"); |
| | | 138 | | } |
| | 3 | 139 | | } |
| | | 140 | | |
| | | 141 | | public async Task<(bool Exito, BeneficioSocialDto? Resultado, string? Error)> ActualizarAsync(long id, ActualizarBen |
| | | 142 | | { |
| | 2 | 143 | | await _periodoGuard.VerificarPeriodoAbiertoAsync(); |
| | | 144 | | try |
| | | 145 | | { |
| | 2 | 146 | | var entidad = await _beneficioSocialRepository.ObtenerPorIdAsync(id); |
| | 2 | 147 | | if (entidad == null) |
| | | 148 | | { |
| | 1 | 149 | | return (false, null, "Beneficio social no encontrado"); |
| | | 150 | | } |
| | | 151 | | |
| | 1 | 152 | | var tipo = entidad.TipoBeneficio ?? await _beneficioSocialRepository.ObtenerTipoBeneficioAsync(entidad.TipoB |
| | 1 | 153 | | if (tipo == null || !tipo.Activo) |
| | | 154 | | { |
| | 0 | 155 | | return (false, null, "Tipo de beneficio no encontrado o inactivo"); |
| | | 156 | | } |
| | | 157 | | |
| | 1 | 158 | | var vigenteDesde = request.VigenteDesde?.Date ?? entidad.VigenteDesde.Date; |
| | 1 | 159 | | var fechaEvento = request.FechaEvento?.Date ?? entidad.FechaEvento; |
| | | 160 | | |
| | 1 | 161 | | if (!await _beneficioSocialRepository.ExistePersonaActivaAsync(entidad.PersonaId, vigenteDesde)) |
| | | 162 | | { |
| | 0 | 163 | | return (false, null, "La persona no tiene relacion laboral activa para la vigencia indicada"); |
| | | 164 | | } |
| | | 165 | | |
| | 1 | 166 | | var requestConsolidado = new CrearBeneficioSocialRequest |
| | 1 | 167 | | { |
| | 1 | 168 | | PersonaId = entidad.PersonaId, |
| | 1 | 169 | | TipoBeneficioId = entidad.TipoBeneficioId, |
| | 1 | 170 | | Cantidad = request.Cantidad ?? entidad.Cantidad, |
| | 1 | 171 | | VigenteDesde = vigenteDesde, |
| | 1 | 172 | | VigenteHasta = request.VigenteHasta ?? entidad.VigenteHasta, |
| | 1 | 173 | | DocumentoRespaldo = request.DocumentoRespaldo ?? entidad.DocumentoRespaldo, |
| | 1 | 174 | | Observaciones = request.Observaciones ?? entidad.Observaciones, |
| | 1 | 175 | | CategoriaBeneficio = ConvertirCategoriaRequest(DeterminarCategoria(tipo)), |
| | 1 | 176 | | DatosTipo = new DatosTipoBeneficioRequest |
| | 1 | 177 | | { |
| | 1 | 178 | | FechaEvento = fechaEvento, |
| | 1 | 179 | | EstadoCivilUnion = request.EstadoCivilUnion, |
| | 1 | 180 | | TieneHijosACargo = request.TieneHijosACargo, |
| | 1 | 181 | | CantidadHijosMenores = request.CantidadHijosMenores, |
| | 1 | 182 | | CantidadHijosDiscapacidad = request.CantidadHijosDiscapacidad, |
| | 1 | 183 | | PrimaSolidariaFamiliarTipo = request.PrimaSolidariaFamiliarTipo, |
| | 1 | 184 | | TieneJustificacionRetroactivo = request.TieneJustificacionRetroactivo ?? false, |
| | 1 | 185 | | JustificacionRetroactivo = request.JustificacionRetroactivo, |
| | 1 | 186 | | PendienteDocumentacion = request.PendienteDocumentacion ?? (entidad.Estado == EstadoPendienteDoc) |
| | 1 | 187 | | } |
| | 1 | 188 | | }; |
| | | 189 | | |
| | 1 | 190 | | var validacion = ValidarReglasPorTipo(tipo, requestConsolidado, esActualizacion: true); |
| | 1 | 191 | | if (!string.IsNullOrEmpty(validacion)) |
| | | 192 | | { |
| | 0 | 193 | | return (false, null, validacion); |
| | | 194 | | } |
| | | 195 | | |
| | 1 | 196 | | var claveEvento = ConstruirClaveEvento(tipo, fechaEvento, vigenteDesde); |
| | 1 | 197 | | if (EsBeneficioUnicaVez(tipo) |
| | 1 | 198 | | && await _beneficioSocialRepository.ExisteDuplicadoEventoAsync(entidad.PersonaId, entidad.TipoBeneficioI |
| | | 199 | | { |
| | 0 | 200 | | return (false, null, "Existe un beneficio duplicado para un evento de unica vez"); |
| | | 201 | | } |
| | | 202 | | |
| | 1 | 203 | | var retroactividadPendiente = CalcularRetroactividadPendiente(vigenteDesde); |
| | 1 | 204 | | if (retroactividadPendiente && !tipo.PermiteRetroactividad) |
| | | 205 | | { |
| | 0 | 206 | | return (false, null, "El tipo de beneficio no permite retroactividad para la vigencia indicada"); |
| | | 207 | | } |
| | | 208 | | |
| | 1 | 209 | | entidad.Cantidad = requestConsolidado.Cantidad ?? entidad.Cantidad; |
| | 1 | 210 | | entidad.VigenteDesde = vigenteDesde; |
| | 1 | 211 | | entidad.VigenteHasta = requestConsolidado.VigenteHasta?.Date; |
| | 1 | 212 | | entidad.DocumentoRespaldo = requestConsolidado.DocumentoRespaldo?.Trim(); |
| | 1 | 213 | | entidad.Observaciones = ConstruirObservaciones(requestConsolidado.Observaciones, requestConsolidado.DatosTip |
| | 1 | 214 | | entidad.Estado = requestConsolidado.DatosTipo.PendienteDocumentacion ? EstadoPendienteDoc : EstadoActivo; |
| | 1 | 215 | | entidad.FechaEvento = fechaEvento; |
| | 1 | 216 | | entidad.ClaveEvento = claveEvento; |
| | 1 | 217 | | entidad.RetroactividadPendiente = retroactividadPendiente; |
| | | 218 | | |
| | 1 | 219 | | var actualizado = await _beneficioSocialRepository.ActualizarAsync(entidad); |
| | | 220 | | |
| | 1 | 221 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 222 | | usuarioId, |
| | 1 | 223 | | AccionEnum.ActualizarBeneficio, |
| | 1 | 224 | | ContextoEnum.Beneficios, |
| | 1 | 225 | | host: host, |
| | 1 | 226 | | entidad: nameof(BeneficioSocial), |
| | 1 | 227 | | entidadId: actualizado.Id, |
| | 1 | 228 | | detalle: new { operacion = "actualizar", id = actualizado.Id, personaId = actualizado.PersonaId, tipoBen |
| | | 229 | | |
| | 1 | 230 | | return (true, MapearDto(actualizado, tipo), null); |
| | | 231 | | } |
| | 0 | 232 | | catch (Exception ex) |
| | | 233 | | { |
| | 0 | 234 | | return (false, null, $"Error al actualizar beneficio social: {ex.Message}"); |
| | | 235 | | } |
| | 2 | 236 | | } |
| | | 237 | | |
| | | 238 | | public async Task<(bool Exito, bool BajaLogica, string? Error)> EliminarAsync(long id, long usuarioId, string host) |
| | | 239 | | { |
| | 2 | 240 | | await _periodoGuard.VerificarPeriodoAbiertoAsync(); |
| | | 241 | | try |
| | | 242 | | { |
| | 2 | 243 | | var entidad = await _beneficioSocialRepository.ObtenerPorIdAsync(id); |
| | 2 | 244 | | if (entidad == null) |
| | | 245 | | { |
| | 0 | 246 | | return (false, false, "Beneficio social no encontrado"); |
| | | 247 | | } |
| | | 248 | | |
| | 2 | 249 | | if (entidad.Estado == EstadoInactivo) |
| | | 250 | | { |
| | 1 | 251 | | return (true, true, null); |
| | | 252 | | } |
| | | 253 | | |
| | 1 | 254 | | entidad.Estado = EstadoInactivo; |
| | 1 | 255 | | entidad.VigenteHasta ??= DateTime.UtcNow.Date; |
| | 1 | 256 | | await _beneficioSocialRepository.ActualizarAsync(entidad); |
| | | 257 | | |
| | 1 | 258 | | await _auditoriaService.LogAuditoriaAsync( |
| | 1 | 259 | | usuarioId, |
| | 1 | 260 | | AccionEnum.EliminarBeneficio, |
| | 1 | 261 | | ContextoEnum.Beneficios, |
| | 1 | 262 | | host: host, |
| | 1 | 263 | | entidad: nameof(BeneficioSocial), |
| | 1 | 264 | | entidadId: entidad.Id, |
| | 1 | 265 | | detalle: new { operacion = "eliminar", id = entidad.Id, personaId = entidad.PersonaId, tipoBeneficioId = |
| | | 266 | | |
| | 1 | 267 | | return (true, true, null); |
| | | 268 | | } |
| | 0 | 269 | | catch (Exception ex) |
| | | 270 | | { |
| | 0 | 271 | | return (false, false, $"Error al eliminar beneficio social: {ex.Message}"); |
| | | 272 | | } |
| | 2 | 273 | | } |
| | | 274 | | |
| | | 275 | | private static string? ValidarReglasPorTipo(TipoBeneficio tipo, CrearBeneficioSocialRequest request, bool esActualiz |
| | | 276 | | { |
| | 3 | 277 | | var datosTipo = request.DatosTipo ?? new DatosTipoBeneficioRequest(); |
| | | 278 | | |
| | 3 | 279 | | if (request.Cantidad.HasValue && request.Cantidad.Value < 0) |
| | | 280 | | { |
| | 0 | 281 | | return "La cantidad no puede ser negativa"; |
| | | 282 | | } |
| | | 283 | | |
| | 3 | 284 | | if (request.VigenteHasta.HasValue && request.VigenteHasta.Value.Date < request.VigenteDesde.Date) |
| | | 285 | | { |
| | 0 | 286 | | return "La vigencia hasta no puede ser anterior a la vigencia desde"; |
| | | 287 | | } |
| | | 288 | | |
| | 3 | 289 | | var categoria = DeterminarCategoria(tipo); |
| | | 290 | | switch (categoria) |
| | | 291 | | { |
| | | 292 | | case CategoriaTipoBeneficio.AsignacionFamiliar: |
| | | 293 | | // Los hijos se registran individualmente en beneficio_social_beneficiarios. |
| | | 294 | | // Los documentos se suben vía /beneficiarios/{id}/documentos. |
| | | 295 | | // No se requieren campos en DatosTipo ni DocumentoRespaldo al crear. |
| | | 296 | | break; |
| | | 297 | | |
| | | 298 | | case CategoriaTipoBeneficio.HogarConstituido: |
| | 0 | 299 | | if (string.IsNullOrWhiteSpace(datosTipo.EstadoCivilUnion)) |
| | | 300 | | { |
| | 0 | 301 | | return "Debe indicar estado civil o union concubinaria para hogar constituido"; |
| | | 302 | | } |
| | | 303 | | break; |
| | | 304 | | |
| | | 305 | | case CategoriaTipoBeneficio.PrimaSolidariaFamiliar: |
| | | 306 | | // El tipo PSF se determina por Cantidad (1=soltero, 2=casado, 3=con hijos). |
| | | 307 | | // Se valida que la cantidad esté en rango; el procesador emite incidencia si no. |
| | 1 | 308 | | var cantidadPsf = request.Cantidad.GetValueOrDefault(1); |
| | 1 | 309 | | if (cantidadPsf < 1 || cantidadPsf > 3) |
| | | 310 | | { |
| | 0 | 311 | | return "La cantidad para Prima Solidaria Familiar debe ser 1, 2 o 3 (soltero, casado, con hijos)"; |
| | | 312 | | } |
| | | 313 | | break; |
| | | 314 | | |
| | | 315 | | case CategoriaTipoBeneficio.PrimaNacimiento: |
| | 1 | 316 | | if (!datosTipo.FechaEvento.HasValue) |
| | | 317 | | { |
| | 0 | 318 | | return "Debe indicar la fecha de nacimiento para prima por nacimiento"; |
| | | 319 | | } |
| | | 320 | | |
| | 1 | 321 | | if ((request.VigenteDesde.Date - datosTipo.FechaEvento.Value.Date).TotalDays > 60) |
| | | 322 | | { |
| | 0 | 323 | | return "La solicitud de prima por nacimiento debe presentarse dentro de los 60 días del nacimiento. |
| | | 324 | | } |
| | | 325 | | break; |
| | | 326 | | |
| | | 327 | | case CategoriaTipoBeneficio.PrimaMatrimonio: |
| | 1 | 328 | | if (!datosTipo.FechaEvento.HasValue) |
| | | 329 | | { |
| | 0 | 330 | | return "Debe indicar la fecha de matrimonio o union"; |
| | | 331 | | } |
| | | 332 | | |
| | 1 | 333 | | if ((request.VigenteDesde.Date - datosTipo.FechaEvento.Value.Date).TotalDays > 60) |
| | | 334 | | { |
| | 0 | 335 | | return "La solicitud de prima por matrimonio debe presentarse dentro de los 60 días del matrimonio. |
| | | 336 | | } |
| | | 337 | | break; |
| | | 338 | | |
| | | 339 | | case CategoriaTipoBeneficio.General: |
| | 0 | 340 | | if (!esActualizacion && request.Cantidad.GetValueOrDefault(1) <= 0) |
| | | 341 | | { |
| | 0 | 342 | | return "La cantidad debe ser mayor a cero"; |
| | | 343 | | } |
| | | 344 | | break; |
| | | 345 | | } |
| | | 346 | | |
| | 3 | 347 | | return null; |
| | | 348 | | } |
| | | 349 | | |
| | | 350 | | private static CategoriaBeneficioRequest ConvertirCategoriaRequest(CategoriaTipoBeneficio categoria) |
| | | 351 | | { |
| | 4 | 352 | | return categoria switch |
| | 4 | 353 | | { |
| | 0 | 354 | | CategoriaTipoBeneficio.AsignacionFamiliar => CategoriaBeneficioRequest.AsignacionFamiliar, |
| | 0 | 355 | | CategoriaTipoBeneficio.HogarConstituido => CategoriaBeneficioRequest.HogarConstituido, |
| | 1 | 356 | | CategoriaTipoBeneficio.PrimaSolidariaFamiliar => CategoriaBeneficioRequest.PrimaSolidariaFamiliar, |
| | 2 | 357 | | CategoriaTipoBeneficio.PrimaNacimiento => CategoriaBeneficioRequest.PrimaNacimiento, |
| | 1 | 358 | | CategoriaTipoBeneficio.PrimaMatrimonio => CategoriaBeneficioRequest.PrimaMatrimonio, |
| | 0 | 359 | | _ => CategoriaBeneficioRequest.General |
| | 4 | 360 | | }; |
| | | 361 | | } |
| | | 362 | | |
| | | 363 | | private static string ConstruirObservaciones(string? observaciones, string? justificacionRetroactivo) |
| | | 364 | | { |
| | 2 | 365 | | var observacionNormalizada = observaciones?.Trim(); |
| | 2 | 366 | | var justificacionNormalizada = justificacionRetroactivo?.Trim(); |
| | | 367 | | |
| | 2 | 368 | | if (string.IsNullOrWhiteSpace(justificacionNormalizada)) |
| | | 369 | | { |
| | 2 | 370 | | return observacionNormalizada ?? string.Empty; |
| | | 371 | | } |
| | | 372 | | |
| | 0 | 373 | | if (string.IsNullOrWhiteSpace(observacionNormalizada)) |
| | | 374 | | { |
| | 0 | 375 | | return $"Justificacion retroactivo: {justificacionNormalizada}"; |
| | | 376 | | } |
| | | 377 | | |
| | 0 | 378 | | return $"{observacionNormalizada} | Justificacion retroactivo: {justificacionNormalizada}"; |
| | | 379 | | } |
| | | 380 | | |
| | | 381 | | private static bool RequiereJustificacionFueraPlazo(DateTime fechaEvento, DateTime vigenteDesde) |
| | | 382 | | { |
| | 0 | 383 | | return (vigenteDesde.Date - fechaEvento.Date).TotalDays > 90; |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | private static bool CalcularRetroactividadPendiente(DateTime vigenteDesde) |
| | | 387 | | { |
| | 2 | 388 | | var primerDiaMes = new DateTime(DateTime.UtcNow.Year, DateTime.UtcNow.Month, 1); |
| | 2 | 389 | | return vigenteDesde.Date < primerDiaMes; |
| | | 390 | | } |
| | | 391 | | |
| | | 392 | | private static bool EsBeneficioUnicaVez(TipoBeneficio tipo) |
| | | 393 | | { |
| | 3 | 394 | | var categoria = DeterminarCategoria(tipo); |
| | 3 | 395 | | return categoria == CategoriaTipoBeneficio.HogarConstituido |
| | 3 | 396 | | || categoria == CategoriaTipoBeneficio.PrimaNacimiento |
| | 3 | 397 | | || categoria == CategoriaTipoBeneficio.PrimaMatrimonio; |
| | | 398 | | } |
| | | 399 | | |
| | | 400 | | private static string ConstruirClaveEvento(TipoBeneficio tipo, DateTime? fechaEvento, DateTime vigenteDesde) |
| | | 401 | | { |
| | 3 | 402 | | var categoria = DeterminarCategoria(tipo); |
| | | 403 | | |
| | 3 | 404 | | return categoria switch |
| | 3 | 405 | | { |
| | 1 | 406 | | CategoriaTipoBeneficio.PrimaNacimiento => fechaEvento?.Date.ToString("yyyy-MM-dd") ?? vigenteDesde.Date.ToSt |
| | 1 | 407 | | CategoriaTipoBeneficio.PrimaMatrimonio => fechaEvento?.Date.ToString("yyyy-MM-dd") ?? vigenteDesde.Date.ToSt |
| | 0 | 408 | | CategoriaTipoBeneficio.HogarConstituido => "UNICA", |
| | 1 | 409 | | _ => vigenteDesde.Date.ToString("yyyy-MM") |
| | 3 | 410 | | }; |
| | | 411 | | } |
| | | 412 | | |
| | | 413 | | private static CategoriaTipoBeneficio DeterminarCategoria(TipoBeneficio tipo) |
| | | 414 | | { |
| | 13 | 415 | | var codigo = (tipo.Codigo ?? string.Empty).Trim().ToUpperInvariant(); |
| | 13 | 416 | | var nombre = (tipo.Nombre ?? string.Empty).Trim().ToUpperInvariant(); |
| | | 417 | | |
| | 13 | 418 | | if (codigo == "ASIGNACION_FAMILIAR" |
| | 13 | 419 | | || codigo.StartsWith("300") || codigo.StartsWith("301") || codigo.StartsWith("302") |
| | 13 | 420 | | || codigo.StartsWith("303") || codigo.StartsWith("304") || codigo.StartsWith("305") |
| | 13 | 421 | | || codigo.StartsWith("306") || codigo.StartsWith("307") || codigo.StartsWith("308") |
| | 13 | 422 | | || codigo.StartsWith("309") || codigo.StartsWith("310") |
| | 13 | 423 | | || nombre.Contains("ASIGNACION FAMILIAR") || nombre.Contains("ASIGNACIÓN FAMILIAR")) |
| | | 424 | | { |
| | 0 | 425 | | return CategoriaTipoBeneficio.AsignacionFamiliar; |
| | | 426 | | } |
| | | 427 | | |
| | 13 | 428 | | if (codigo == "HOGAR_CONSTITUIDO" || codigo == "320" || nombre.Contains("HOGAR")) |
| | | 429 | | { |
| | 0 | 430 | | return CategoriaTipoBeneficio.HogarConstituido; |
| | | 431 | | } |
| | | 432 | | |
| | 13 | 433 | | if (codigo == "PRIMA_SOLIDARIA_FAMILIAR" || codigo == "330" |
| | 13 | 434 | | || nombre.Contains("SOLIDARIA") || nombre.Contains("PSF")) |
| | | 435 | | { |
| | 4 | 436 | | return CategoriaTipoBeneficio.PrimaSolidariaFamiliar; |
| | | 437 | | } |
| | | 438 | | |
| | 9 | 439 | | if (codigo == "PRIMA_NACIMIENTO" || codigo == "340" |
| | 9 | 440 | | || (nombre.Contains("NACIMIENTO") && !nombre.Contains("MATRIMONIO"))) |
| | | 441 | | { |
| | 5 | 442 | | return CategoriaTipoBeneficio.PrimaNacimiento; |
| | | 443 | | } |
| | | 444 | | |
| | 4 | 445 | | if (codigo == "PRIMA_MATRIMONIO" || codigo == "350" |
| | 4 | 446 | | || (nombre.Contains("MATRIMONIO") && !nombre.Contains("NACIMIENTO")) |
| | 4 | 447 | | || nombre.Contains("UNION")) |
| | | 448 | | { |
| | 4 | 449 | | return CategoriaTipoBeneficio.PrimaMatrimonio; |
| | | 450 | | } |
| | | 451 | | |
| | | 452 | | // PRIMA_NACIMIENTO_MATRIMONIO: el subtipo determina si es nacimiento o matrimonio. |
| | | 453 | | // Se valida como General para que el frontend pueda declarar PrimaNacimiento o PrimaMatrimonio |
| | | 454 | | // según el subtipo enviado. El procesador lo resuelve internamente. |
| | 0 | 455 | | if (codigo == "PRIMA_NACIMIENTO_MATRIMONIO" |
| | 0 | 456 | | || (nombre.Contains("NACIMIENTO") && nombre.Contains("MATRIMONIO"))) |
| | | 457 | | { |
| | 0 | 458 | | return CategoriaTipoBeneficio.General; |
| | | 459 | | } |
| | | 460 | | |
| | 0 | 461 | | return CategoriaTipoBeneficio.General; |
| | | 462 | | } |
| | | 463 | | |
| | | 464 | | private static BeneficioSocialDto MapearDto(BeneficioSocial entidad, TipoBeneficio? tipo = null) |
| | | 465 | | { |
| | 4 | 466 | | var tipoBeneficio = tipo ?? entidad.TipoBeneficio; |
| | | 467 | | |
| | 4 | 468 | | return new BeneficioSocialDto |
| | 4 | 469 | | { |
| | 4 | 470 | | Id = entidad.Id, |
| | 4 | 471 | | PersonaId = entidad.PersonaId, |
| | 4 | 472 | | PersonaCedula = entidad.Persona?.Cedula ?? string.Empty, |
| | 4 | 473 | | PersonaNombre = entidad.Persona?.NombreCompleto ?? string.Empty, |
| | 4 | 474 | | TipoBeneficioId = entidad.TipoBeneficioId, |
| | 4 | 475 | | TipoBeneficioCodigo = tipoBeneficio?.Codigo ?? string.Empty, |
| | 4 | 476 | | TipoBeneficioNombre = tipoBeneficio?.Nombre ?? string.Empty, |
| | 4 | 477 | | Cantidad = entidad.Cantidad, |
| | 4 | 478 | | VigenteDesde = entidad.VigenteDesde, |
| | 4 | 479 | | VigenteHasta = entidad.VigenteHasta, |
| | 4 | 480 | | Estado = entidad.Estado, |
| | 4 | 481 | | DocumentoRespaldo = entidad.DocumentoRespaldo, |
| | 4 | 482 | | Observaciones = entidad.Observaciones, |
| | 4 | 483 | | FechaEvento = entidad.FechaEvento, |
| | 4 | 484 | | ClaveEvento = entidad.ClaveEvento, |
| | 4 | 485 | | RetroactividadPendiente = entidad.RetroactividadPendiente |
| | 4 | 486 | | }; |
| | | 487 | | } |
| | | 488 | | |
| | | 489 | | private enum CategoriaTipoBeneficio |
| | | 490 | | { |
| | | 491 | | General = 0, |
| | | 492 | | AsignacionFamiliar = 1, |
| | | 493 | | HogarConstituido = 2, |
| | | 494 | | PrimaSolidariaFamiliar = 3, |
| | | 495 | | PrimaNacimiento = 4, |
| | | 496 | | PrimaMatrimonio = 5 |
| | | 497 | | } |
| | | 498 | | |
| | | 499 | | public async Task<string> SubirDocumentoAsync(long beneficioId, Stream contenido, string nombreOriginal, string cont |
| | | 500 | | { |
| | 0 | 501 | | var entidad = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 502 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 503 | | |
| | 0 | 504 | | var ext = Path.GetExtension(nombreOriginal); |
| | 0 | 505 | | var nombreSanitizado = Path.GetFileNameWithoutExtension(nombreOriginal) |
| | 0 | 506 | | .Replace(" ", "_").Replace("..", "") + ext; |
| | 0 | 507 | | var rutaRelativa = $"beneficios/{beneficioId}/{nombreSanitizado}"; |
| | | 508 | | |
| | 0 | 509 | | await _storage.GuardarAsync(contenido, rutaRelativa, contentType); |
| | 0 | 510 | | entidad.DocumentoRespaldo = rutaRelativa; |
| | 0 | 511 | | await _beneficioSocialRepository.ActualizarAsync(entidad); |
| | 0 | 512 | | return rutaRelativa; |
| | 0 | 513 | | } |
| | | 514 | | |
| | | 515 | | public async Task<(Stream Contenido, string NombreOriginal, string ContentType)> DescargarDocumentoAsync(long benefi |
| | | 516 | | { |
| | 0 | 517 | | var entidad = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 518 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 519 | | |
| | 0 | 520 | | if (string.IsNullOrEmpty(entidad.DocumentoRespaldo)) |
| | 0 | 521 | | throw new KeyNotFoundException("El beneficio no tiene documento adjunto."); |
| | | 522 | | |
| | 0 | 523 | | var stream = await _storage.ObtenerAsync(entidad.DocumentoRespaldo); |
| | 0 | 524 | | var nombre = Path.GetFileName(entidad.DocumentoRespaldo); |
| | 0 | 525 | | var ext = Path.GetExtension(nombre).ToLowerInvariant(); |
| | 0 | 526 | | var contentType = ext switch |
| | 0 | 527 | | { |
| | 0 | 528 | | ".pdf" => "application/pdf", |
| | 0 | 529 | | ".jpg" or ".jpeg" => "image/jpeg", |
| | 0 | 530 | | ".png" => "image/png", |
| | 0 | 531 | | ".tif" or ".tiff" => "image/tiff", |
| | 0 | 532 | | ".doc" => "application/msword", |
| | 0 | 533 | | ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", |
| | 0 | 534 | | _ => "application/octet-stream" |
| | 0 | 535 | | }; |
| | 0 | 536 | | return (stream, nombre, contentType); |
| | 0 | 537 | | } |
| | | 538 | | |
| | | 539 | | public async Task<string> AgregarDocumentoAsync(long beneficioId, Stream contenido, string nombreOriginal, string co |
| | | 540 | | { |
| | 0 | 541 | | _ = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 542 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 543 | | |
| | 0 | 544 | | var ext = Path.GetExtension(nombreOriginal); |
| | 0 | 545 | | var nombreSanitizado = Path.GetFileNameWithoutExtension(nombreOriginal) |
| | 0 | 546 | | .Replace(" ", "_").Replace("..", "") + ext; |
| | 0 | 547 | | var rutaRelativa = $"beneficios/{beneficioId}/{nombreSanitizado}"; |
| | 0 | 548 | | var tamanio = contenido.CanSeek ? contenido.Length : 0; |
| | | 549 | | |
| | 0 | 550 | | await _storage.GuardarAsync(contenido, rutaRelativa, contentType); |
| | | 551 | | |
| | 0 | 552 | | await _docRepo.CreateAsync(new Documento |
| | 0 | 553 | | { |
| | 0 | 554 | | Tipo = "beneficio_social", |
| | 0 | 555 | | EntidadId = beneficioId, |
| | 0 | 556 | | RutaRelativa = rutaRelativa, |
| | 0 | 557 | | NombreOriginal = nombreOriginal, |
| | 0 | 558 | | ContentType = contentType, |
| | 0 | 559 | | TamanioBytes = tamanio, |
| | 0 | 560 | | UsuarioCargaId = usuarioId |
| | 0 | 561 | | }); |
| | | 562 | | |
| | 0 | 563 | | return rutaRelativa; |
| | 0 | 564 | | } |
| | | 565 | | |
| | | 566 | | public async Task<IEnumerable<DocumentoDto>> ObtenerDocumentosAsync(long beneficioId) |
| | | 567 | | { |
| | 0 | 568 | | _ = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 569 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 570 | | |
| | 0 | 571 | | var docs = await _docRepo.GetByTipoEntidadAsync("beneficio_social", beneficioId); |
| | 0 | 572 | | return docs.Select(d => new DocumentoDto |
| | 0 | 573 | | { |
| | 0 | 574 | | Id = d.Id, |
| | 0 | 575 | | NombreOriginal = d.NombreOriginal, |
| | 0 | 576 | | ContentType = d.ContentType, |
| | 0 | 577 | | TamanioBytes = d.TamanioBytes, |
| | 0 | 578 | | FechaCarga = d.FechaCarga |
| | 0 | 579 | | }); |
| | 0 | 580 | | } |
| | | 581 | | |
| | | 582 | | public async Task<(Stream Contenido, string NombreOriginal, string ContentType)> DescargarDocumentoPorIdAsync(long b |
| | | 583 | | { |
| | 0 | 584 | | _ = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 585 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 586 | | |
| | 0 | 587 | | var doc = await _docRepo.GetByIdAsync(documentoId) |
| | 0 | 588 | | ?? throw new KeyNotFoundException($"Documento {documentoId} no encontrado."); |
| | | 589 | | |
| | 0 | 590 | | var stream = await _storage.ObtenerAsync(doc.RutaRelativa); |
| | 0 | 591 | | return (stream, doc.NombreOriginal, doc.ContentType); |
| | 0 | 592 | | } |
| | | 593 | | |
| | | 594 | | public async Task EliminarDocumentoAsync(long beneficioId, long documentoId) |
| | | 595 | | { |
| | 0 | 596 | | _ = await _beneficioSocialRepository.ObtenerPorIdAsync(beneficioId) |
| | 0 | 597 | | ?? throw new ArgumentException($"Beneficio social {beneficioId} no encontrado."); |
| | | 598 | | |
| | 0 | 599 | | var doc = await _docRepo.GetByIdAsync(documentoId) |
| | 0 | 600 | | ?? throw new KeyNotFoundException($"Documento {documentoId} no encontrado."); |
| | | 601 | | |
| | 0 | 602 | | try { await _storage.EliminarAsync(doc.RutaRelativa); } |
| | 0 | 603 | | catch { /* archivo físico ya eliminado, igual borramos el registro */ } |
| | | 604 | | |
| | 0 | 605 | | await _docRepo.DeleteAsync(documentoId); |
| | 0 | 606 | | } |
| | | 607 | | } |