1. Funcionalidad Principal: Auditoría General
Se creó una nueva sección de "Auditoría" en la aplicación, diseñada para ser accedida por SuperAdmins. Se implementó una página AuditoriaGeneralPage.tsx que actúa como un visor centralizado para el historial de cambios de múltiples entidades del sistema. 2. Backend: Nuevo Controlador (AuditoriaController.cs): Centraliza los endpoints para obtener datos de las tablas de historial (_H). Servicios y Repositorios Extendidos: Se añadieron métodos GetHistorialAsync y ObtenerHistorialAsync a las capas de repositorio y servicio para cada una de las siguientes entidades, permitiendo consultar sus tablas _H con filtros: Usuarios (gral_Usuarios_H) Pagos de Distribuidores (cue_PagosDistribuidor_H) Notas de Crédito/Débito (cue_CreditosDebitos_H) Entradas/Salidas de Distribuidores (dist_EntradasSalidas_H) Entradas/Salidas de Canillitas (dist_EntradasSalidasCanillas_H) Novedades de Canillitas (dist_dtNovedadesCanillas_H) Tipos de Pago (cue_dtTipopago_H) Canillitas (Maestro) (dist_dtCanillas_H) Distribuidores (Maestro) (dist_dtDistribuidores_H) Empresas (Maestro) (dist_dtEmpresas_H) Zonas (Maestro) (dist_dtZonas_H) Otros Destinos (Maestro) (dist_dtOtrosDestinos_H) Publicaciones (Maestro) (dist_dtPublicaciones_H) Secciones de Publicación (dist_dtPubliSecciones_H) Precios de Publicación (dist_Precios_H) Recargos por Zona (dist_RecargoZona_H) Porcentajes Pago Distribuidores (dist_PorcPago_H) Porcentajes/Montos Canillita (dist_PorcMonPagoCanilla_H) Control de Devoluciones (dist_dtCtrlDevoluciones_H) Tipos de Bobina (bob_dtBobinas_H) Estados de Bobina (bob_dtEstadosBobinas_H) Plantas de Impresión (bob_dtPlantas_H) Stock de Bobinas (bob_StockBobinas_H) Tiradas (Registro Principal) (bob_RegTiradas_H) Secciones de Tirada (bob_RegPublicaciones_H) Cambios de Parada de Canillitas (dist_CambiosParadasCanillas_H) Ajustes Manuales de Saldo (cue_SaldoAjustesHistorial) DTOs de Historial: Se crearon DTOs específicos para cada tabla de historial (ej. UsuarioHistorialDto, PagoDistribuidorHistorialDto, etc.) para transferir los datos al frontend, incluyendo el nombre del usuario que realizó la modificación. Corrección de Lógica de Saldos: Se revisó y corrigió la lógica de afectación de saldos en los servicios PagoDistribuidorService y NotaCreditoDebitoService para asegurar que los débitos y créditos se apliquen correctamente. 3. Frontend: Nuevo Servicio (auditoriaService.ts): Contiene métodos para llamar a cada uno de los nuevos endpoints de auditoría del backend. Nueva Página (AuditoriaGeneralPage.tsx): Permite al SuperAdmin seleccionar el "Tipo de Entidad" a auditar desde un dropdown. Ofrece filtros comunes (rango de fechas, usuario modificador, tipo de acción) y filtros específicos que aparecen dinámicamente según la entidad seleccionada. Utiliza un DataGrid de Material-UI para mostrar el historial, con columnas que se adaptan dinámicamente al tipo de entidad consultada. Nuevos DTOs en TypeScript: Se crearon las interfaces correspondientes a los DTOs de historial del backend. Gestión de Permisos: La sección de Auditoría en MainLayout.tsx y su ruta en AppRoutes.tsx están protegidas para ser visibles y accesibles solo por SuperAdmins. Se añadió un permiso de ejemplo AU_GENERAL_VIEW para ser usado si se decide extender el acceso en el futuro. Corrección de Errores Menores: Se solucionó el problema del "parpadeo" del selector de fecha en GestionarNovedadesCanillaPage al adoptar un patrón de carga de datos más controlado, similar a otras páginas funcionales.
This commit is contained in:
@@ -181,5 +181,27 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
}
|
||||
finally { if (connection.State == ConnectionState.Open) { if (connection is System.Data.Common.DbConnection dbConn) await dbConn.CloseAsync(); else connection.Close(); } }
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<CambioParadaHistorialDto>> ObtenerCambiosParadaHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idCanillaAfectado)
|
||||
{
|
||||
var historialData = await _paradaRepo.GetCambiosParadaHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idCanillaAfectado);
|
||||
|
||||
return historialData.Select(h => new CambioParadaHistorialDto
|
||||
{
|
||||
Id_Registro = h.Historial.Id_Registro,
|
||||
Id_Canilla = h.Historial.Id_Canilla,
|
||||
NombreCanilla = h.NombreCanilla,
|
||||
Parada = h.Historial.Parada,
|
||||
VigenciaD = h.Historial.VigenciaD,
|
||||
VigenciaH = h.Historial.VigenciaH ?? default(DateTime),
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -287,6 +287,6 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -167,5 +168,29 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ControlDevolucionesHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idControlAfectado, int? idEmpresaAfectada, DateTime? fechaAfectada)
|
||||
{
|
||||
var historialData = await _controlDevRepo.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idControlAfectado, idEmpresaAfectada, fechaAfectada);
|
||||
|
||||
return historialData.Select(h => new ControlDevolucionesHistorialDto
|
||||
{
|
||||
Id_Control = h.Historial.Id_Control,
|
||||
Id_Empresa = h.Historial.Id_Empresa,
|
||||
Fecha = h.Historial.Fecha,
|
||||
Entrada = h.Historial.Entrada,
|
||||
Sobrantes = h.Historial.Sobrantes,
|
||||
Detalle = h.Historial.Detalle,
|
||||
SinCargo = h.Historial.SinCargo,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
// Mapear NombreEmpresa aquí si lo añades al DTO y lo obtienes
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
// Update podría ser solo para cerrar la vigencia, no para cambiar la dirección de una parada histórica.
|
||||
Task<(bool Exito, string? Error)> CerrarParadaAsync(int idRegistro, UpdateCambioParadaDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarParadaAsync(int idRegistro, int idUsuario); // Si se permite
|
||||
Task<IEnumerable<CambioParadaHistorialDto>> ObtenerCambiosParadaHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idCanillaAfectado);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(ControlDevolucionesDto? Control, string? Error)> CrearAsync(CreateControlDevolucionesDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idControl, UpdateControlDevolucionesDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idControl, int idUsuario);
|
||||
Task<IEnumerable<ControlDevolucionesHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idControlAfectado, int? idEmpresaAfectada, DateTime? fechaAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(OtroDestinoDto? Destino, string? Error)> CrearAsync(CreateOtroDestinoDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateOtroDestinoDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
|
||||
Task<IEnumerable<OtroDestinoHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idOtroDestinoAfectado);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(PorcMonCanillaDto? Item, string? Error)> CrearAsync(CreatePorcMonCanillaDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idPorcMon, UpdatePorcMonCanillaDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPorcMon, int idUsuario);
|
||||
Task<IEnumerable<PorcMonCanillaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPorcMonAfectado, int? idPublicacionAfectada, int? idCanillaAfectado);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -12,5 +14,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(PorcPagoDto? PorcPago, string? Error)> CrearAsync(CreatePorcPagoDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idPorcentaje, UpdatePorcPagoDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPorcentaje, int idUsuario);
|
||||
Task<IEnumerable<PorcPagoHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPorcentajeAfectado, int? idPublicacionAfectada, int? idDistribuidorAfectado);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(PrecioDto? Precio, string? Error)> CrearAsync(CreatePrecioDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idPrecio, UpdatePrecioDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPrecio, int idUsuario);
|
||||
Task<IEnumerable<PrecioHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPrecioAfectado, int? idPublicacionAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(PubliSeccionDto? Seccion, string? Error)> CrearAsync(CreatePubliSeccionDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idSeccion, UpdatePubliSeccionDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idSeccion, int idUsuario);
|
||||
Task<IEnumerable<PubliSeccionHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idSeccionAfectada, int? idPublicacionAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -15,5 +16,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<IEnumerable<PublicacionDto>> ObtenerPublicacionesPorDiaSemanaAsync(byte diaSemana); // Devolvemos el DTO completo
|
||||
Task<(bool Exito, string? Error)> ActualizarConfiguracionDiasAsync(int idPublicacion, UpdatePublicacionDiasSemanaRequestDto requestDto, int idUsuario);
|
||||
Task<IEnumerable<PublicacionDropdownDto>> ObtenerParaDropdownAsync(bool soloHabilitadas = true);
|
||||
Task<IEnumerable<PublicacionHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPublicacionAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(RecargoZonaDto? Recargo, string? Error)> CrearAsync(CreateRecargoZonaDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int idRecargo, UpdateRecargoZonaDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int idRecargo, int idUsuario);
|
||||
Task<IEnumerable<RecargoZonaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idRecargoAfectado, int? idPublicacionAfectada, int? idZonaAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Zonas; // Para los DTOs de Zonas
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
Task<(ZonaDto? Zona, string? Error)> CrearAsync(CreateZonaDto createDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateZonaDto updateDto, int idUsuario);
|
||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario); // Eliminar lógico (cambiar estado)
|
||||
Task<IEnumerable<ZonaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idZonaAfectada);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -139,5 +140,24 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno al eliminar el destino: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<OtroDestinoHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idOtroDestinoAfectado)
|
||||
{
|
||||
var historialData = await _otroDestinoRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idOtroDestinoAfectado);
|
||||
|
||||
return historialData.Select(h => new OtroDestinoHistorialDto
|
||||
{
|
||||
Id_Destino = h.Historial.Id_Destino,
|
||||
Nombre = h.Historial.Nombre,
|
||||
Obs = h.Historial.Obs,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -44,7 +45,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
PorcMon = data.Item.PorcMon,
|
||||
EsPorcentaje = data.Item.EsPorcentaje
|
||||
};
|
||||
|
||||
|
||||
private async Task<PorcMonCanillaDto?> MapToDtoWithLookup(PorcMonCanilla? item)
|
||||
{
|
||||
if (item == null) return null; // Si el item es null, devuelve null
|
||||
@@ -81,7 +82,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
{
|
||||
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
||||
return (null, "La publicación especificada no existe.");
|
||||
|
||||
|
||||
var canillaData = await _canillaRepository.GetByIdAsync(createDto.IdCanilla);
|
||||
if (canillaData.Canilla == null) // GetByIdAsync devuelve una tupla
|
||||
return (null, "El canillita especificado no existe o no está activo.");
|
||||
@@ -116,7 +117,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var itemAnterior = await _porcMonCanillaRepository.GetPreviousActiveAsync(createDto.IdPublicacion, createDto.IdCanilla, nuevoItem.VigenciaD, transaction);
|
||||
if (itemAnterior != null)
|
||||
{
|
||||
if (itemAnterior.VigenciaD.Date >= nuevoItem.VigenciaD.Date)
|
||||
if (itemAnterior.VigenciaD.Date >= nuevoItem.VigenciaD.Date)
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (null, $"La fecha de inicio ({nuevoItem.VigenciaD:dd/MM/yyyy}) no puede ser anterior o igual a la del último período vigente ({itemAnterior.VigenciaD:dd/MM/yyyy}).");
|
||||
@@ -152,19 +153,19 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
|
||||
if (updateDto.VigenciaH.HasValue && updateDto.VigenciaH.Value.Date < itemExistente.VigenciaD.Date)
|
||||
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
||||
|
||||
|
||||
if (updateDto.VigenciaH.HasValue)
|
||||
{
|
||||
var itemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemExistente.IdPublicacion);
|
||||
var itemsPosteriores = itemsPubCanillaData
|
||||
.Where(i => i.Item.IdCanilla == itemExistente.IdCanilla &&
|
||||
i.Item.IdPorcMon != idPorcMon &&
|
||||
i.Item.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
i.Item.VigenciaD.Date > itemExistente.VigenciaD.Date);
|
||||
if(itemsPosteriores.Any())
|
||||
{
|
||||
var itemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemExistente.IdPublicacion);
|
||||
var itemsPosteriores = itemsPubCanillaData
|
||||
.Where(i => i.Item.IdCanilla == itemExistente.IdCanilla &&
|
||||
i.Item.IdPorcMon != idPorcMon &&
|
||||
i.Item.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
i.Item.VigenciaD.Date > itemExistente.VigenciaD.Date);
|
||||
if (itemsPosteriores.Any())
|
||||
{
|
||||
return (false, "No se puede cerrar este período porque existen configuraciones posteriores para este canillita que se solaparían.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
itemExistente.PorcMon = updateDto.PorcMon;
|
||||
@@ -200,19 +201,19 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var itemAEliminar = await _porcMonCanillaRepository.GetByIdAsync(idPorcMon);
|
||||
if (itemAEliminar == null) return (false, "Registro no encontrado.");
|
||||
|
||||
if (itemAEliminar.VigenciaH == null)
|
||||
if (itemAEliminar.VigenciaH == null)
|
||||
{
|
||||
var todosItemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemAEliminar.IdPublicacion);
|
||||
var todosItemsPubCanilla = todosItemsPubCanillaData
|
||||
.Where(i => i.Item.IdCanilla == itemAEliminar.IdCanilla)
|
||||
.Select(i => i.Item)
|
||||
.OrderByDescending(i => i.VigenciaD).ToList();
|
||||
|
||||
|
||||
var indiceActual = todosItemsPubCanilla.FindIndex(i => i.IdPorcMon == idPorcMon);
|
||||
if(indiceActual != -1 && (indiceActual + 1) < todosItemsPubCanilla.Count)
|
||||
if (indiceActual != -1 && (indiceActual + 1) < todosItemsPubCanilla.Count)
|
||||
{
|
||||
var itemAnteriorDirecto = todosItemsPubCanilla[indiceActual + 1];
|
||||
if(itemAnteriorDirecto.VigenciaH.HasValue &&
|
||||
if (itemAnteriorDirecto.VigenciaH.HasValue &&
|
||||
itemAnteriorDirecto.VigenciaH.Value.Date == itemAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
{
|
||||
itemAnteriorDirecto.VigenciaH = null;
|
||||
@@ -236,5 +237,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<PorcMonCanillaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPorcMonAfectado, int? idPublicacionAfectada, int? idCanillaAfectado)
|
||||
{
|
||||
var historialData = await _porcMonCanillaRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPorcMonAfectado, idPublicacionAfectada, idCanillaAfectado);
|
||||
|
||||
return historialData.Select(h => new PorcMonCanillaHistorialDto
|
||||
{
|
||||
Id_PorcMon = h.Historial.Id_PorcMon,
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
Id_Canilla = h.Historial.Id_Canilla,
|
||||
VigenciaD = h.Historial.VigenciaD,
|
||||
VigenciaH = h.Historial.VigenciaH,
|
||||
PorcMon = h.Historial.PorcMon,
|
||||
EsPorcentaje = h.Historial.EsPorcentaje,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -43,7 +44,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
VigenciaH = data.PorcPago.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||
Porcentaje = data.PorcPago.Porcentaje
|
||||
};
|
||||
|
||||
|
||||
private async Task<PorcPagoDto> MapToDtoWithLookup(PorcPago porcPago)
|
||||
{
|
||||
var distribuidorData = await _distribuidorRepository.GetByIdAsync(porcPago.IdDistribuidor);
|
||||
@@ -117,7 +118,8 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("PorcPago ID {Id} creado por Usuario ID {UserId}.", porcPagoCreado.IdPorcentaje, idUsuario);
|
||||
return (new PorcPagoDto { // Construir DTO manualmente ya que tenemos NombreDistribuidor
|
||||
return (new PorcPagoDto
|
||||
{ // Construir DTO manualmente ya que tenemos NombreDistribuidor
|
||||
IdPorcentaje = porcPagoCreado.IdPorcentaje,
|
||||
IdPublicacion = porcPagoCreado.IdPublicacion,
|
||||
IdDistribuidor = porcPagoCreado.IdDistribuidor,
|
||||
@@ -156,9 +158,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
p.PorcPago.IdPorcentaje != idPorcentaje &&
|
||||
p.PorcPago.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
p.PorcPago.VigenciaD.Date > porcPagoExistente.VigenciaD.Date);
|
||||
if(porcentajesPosteriores.Any())
|
||||
if (porcentajesPosteriores.Any())
|
||||
{
|
||||
return (false, "No se puede cerrar este período porque existen porcentajes posteriores para este distribuidor que se solaparían.");
|
||||
return (false, "No se puede cerrar este período porque existen porcentajes posteriores para este distribuidor que se solaparían.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,19 +196,19 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var porcPagoAEliminar = await _porcPagoRepository.GetByIdAsync(idPorcentaje);
|
||||
if (porcPagoAEliminar == null) return (false, "Porcentaje de pago no encontrado.");
|
||||
|
||||
if (porcPagoAEliminar.VigenciaH == null)
|
||||
if (porcPagoAEliminar.VigenciaH == null)
|
||||
{
|
||||
var todosPorcPubDistData = await _porcPagoRepository.GetByPublicacionIdAsync(porcPagoAEliminar.IdPublicacion);
|
||||
var todosPorcPubDist = todosPorcPubDistData
|
||||
.Where(p => p.PorcPago.IdDistribuidor == porcPagoAEliminar.IdDistribuidor)
|
||||
.Select(p => p.PorcPago)
|
||||
.OrderByDescending(p => p.VigenciaD).ToList();
|
||||
|
||||
|
||||
var indiceActual = todosPorcPubDist.FindIndex(p => p.IdPorcentaje == idPorcentaje);
|
||||
if(indiceActual != -1 && (indiceActual + 1) < todosPorcPubDist.Count)
|
||||
if (indiceActual != -1 && (indiceActual + 1) < todosPorcPubDist.Count)
|
||||
{
|
||||
var porcPagoAnteriorDirecto = todosPorcPubDist[indiceActual + 1];
|
||||
if(porcPagoAnteriorDirecto.VigenciaH.HasValue &&
|
||||
if (porcPagoAnteriorDirecto.VigenciaH.HasValue &&
|
||||
porcPagoAnteriorDirecto.VigenciaH.Value.Date == porcPagoAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
{
|
||||
porcPagoAnteriorDirecto.VigenciaH = null;
|
||||
@@ -230,5 +232,27 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<PorcPagoHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPorcentajeAfectado, int? idPublicacionAfectada, int? idDistribuidorAfectado)
|
||||
{
|
||||
var historialData = await _porcPagoRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPorcentajeAfectado, idPublicacionAfectada, idDistribuidorAfectado);
|
||||
|
||||
return historialData.Select(h => new PorcPagoHistorialDto
|
||||
{
|
||||
Id_Porcentaje = h.Historial.Id_Porcentaje,
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
Id_Distribuidor = h.Historial.Id_Distribuidor,
|
||||
VigenciaD = h.Historial.VigenciaD,
|
||||
VigenciaH = h.Historial.VigenciaH,
|
||||
Porcentaje = h.Historial.Porcentaje,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -37,8 +38,13 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
IdPublicacion = precio.IdPublicacion,
|
||||
VigenciaD = precio.VigenciaD.ToString("yyyy-MM-dd"),
|
||||
VigenciaH = precio.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||
Lunes = precio.Lunes, Martes = precio.Martes, Miercoles = precio.Miercoles,
|
||||
Jueves = precio.Jueves, Viernes = precio.Viernes, Sabado = precio.Sabado, Domingo = precio.Domingo
|
||||
Lunes = precio.Lunes,
|
||||
Martes = precio.Martes,
|
||||
Miercoles = precio.Miercoles,
|
||||
Jueves = precio.Jueves,
|
||||
Viernes = precio.Viernes,
|
||||
Sabado = precio.Sabado,
|
||||
Domingo = precio.Domingo
|
||||
};
|
||||
|
||||
public async Task<IEnumerable<PrecioDto>> ObtenerPorPublicacionIdAsync(int idPublicacion)
|
||||
@@ -73,8 +79,13 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
IdPublicacion = createDto.IdPublicacion,
|
||||
VigenciaD = createDto.VigenciaD.Date, // Asegurar que solo sea fecha
|
||||
VigenciaH = null, // Se establece al crear el siguiente o al cerrar manualmente
|
||||
Lunes = createDto.Lunes ?? 0, Martes = createDto.Martes ?? 0, Miercoles = createDto.Miercoles ?? 0,
|
||||
Jueves = createDto.Jueves ?? 0, Viernes = createDto.Viernes ?? 0, Sabado = createDto.Sabado ?? 0, Domingo = createDto.Domingo ?? 0
|
||||
Lunes = createDto.Lunes ?? 0,
|
||||
Martes = createDto.Martes ?? 0,
|
||||
Miercoles = createDto.Miercoles ?? 0,
|
||||
Jueves = createDto.Jueves ?? 0,
|
||||
Viernes = createDto.Viernes ?? 0,
|
||||
Sabado = createDto.Sabado ?? 0,
|
||||
Domingo = createDto.Domingo ?? 0
|
||||
};
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
@@ -99,7 +110,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
{
|
||||
throw new DataException("No se pudo cerrar el período de precio anterior.");
|
||||
}
|
||||
_logger.LogInformation("Precio anterior ID {IdPrecioAnterior} cerrado con VigenciaH {VigenciaH}.", precioAnterior.IdPrecio, precioAnterior.VigenciaH);
|
||||
_logger.LogInformation("Precio anterior ID {IdPrecioAnterior} cerrado con VigenciaH {VigenciaH}.", precioAnterior.IdPrecio, precioAnterior.VigenciaH);
|
||||
}
|
||||
|
||||
// 3. Crear el nuevo registro de precio
|
||||
@@ -126,91 +137,150 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
|
||||
try
|
||||
{
|
||||
var precioExistente = await _precioRepository.GetByIdAsync(idPrecio); // Obtener dentro de la TX por si acaso
|
||||
if (precioExistente == null) return (false, "Período de precio no encontrado.");
|
||||
|
||||
// En una actualización, principalmente actualizamos los montos de los días.
|
||||
// VigenciaH se puede actualizar para cerrar un período explícitamente.
|
||||
// No se permite cambiar IdPublicacion ni VigenciaD aquí.
|
||||
// Si VigenciaH se establece, debe ser >= VigenciaD
|
||||
if (updateDto.VigenciaH.HasValue && updateDto.VigenciaH.Value.Date < precioExistente.VigenciaD.Date)
|
||||
var precioExistente = await _precioRepository.GetByIdAsync(idPrecio); // Obtener dentro de TX
|
||||
if (precioExistente == null)
|
||||
{
|
||||
return (false, "La Vigencia Hasta no puede ser anterior a la Vigencia Desde.");
|
||||
transaction.Rollback();
|
||||
return (false, "Período de precio no encontrado.");
|
||||
}
|
||||
// Adicional: si se establece VigenciaH, verificar que no haya precios posteriores que se solapen
|
||||
if (updateDto.VigenciaH.HasValue)
|
||||
|
||||
bool preciosDiasCambiaron =
|
||||
(updateDto.Lunes.HasValue && updateDto.Lunes != precioExistente.Lunes) ||
|
||||
(updateDto.Martes.HasValue && updateDto.Martes != precioExistente.Martes) ||
|
||||
(updateDto.Miercoles.HasValue && updateDto.Miercoles != precioExistente.Miercoles) ||
|
||||
(updateDto.Jueves.HasValue && updateDto.Jueves != precioExistente.Jueves) ||
|
||||
(updateDto.Viernes.HasValue && updateDto.Viernes != precioExistente.Viernes) ||
|
||||
(updateDto.Sabado.HasValue && updateDto.Sabado != precioExistente.Sabado) ||
|
||||
(updateDto.Domingo.HasValue && updateDto.Domingo != precioExistente.Domingo);
|
||||
|
||||
if (precioExistente.VigenciaH != null && preciosDiasCambiaron)
|
||||
{
|
||||
var preciosPosteriores = await _precioRepository.GetByPublicacionIdAsync(precioExistente.IdPublicacion);
|
||||
if (preciosPosteriores.Any(p => p.IdPrecio != idPrecio && p.VigenciaD.Date <= updateDto.VigenciaH.Value.Date && p.VigenciaD.Date > precioExistente.VigenciaD.Date ))
|
||||
transaction.Rollback();
|
||||
return (false, "No se pueden modificar los precios de los días de un período que ya ha sido cerrado.");
|
||||
}
|
||||
|
||||
// Validación 2: No modificar precios de días si el período está en uso
|
||||
if (preciosDiasCambiaron && await _precioRepository.IsInUseAsync(idPrecio, precioExistente.VigenciaD, precioExistente.VigenciaH))
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (false, "No se pueden modificar los precios de los días de este período porque ya existen movimientos asociados.");
|
||||
}
|
||||
|
||||
// Solo realizar validaciones de VigenciaH si se está intentando SETEAR o CAMBIAR VigenciaH
|
||||
if (updateDto.VigenciaH.HasValue) // <<--- CHEQUEO IMPORTANTE
|
||||
{
|
||||
// Validación 3: Nueva VigenciaH debe ser >= VigenciaD
|
||||
if (updateDto.VigenciaH.Value.Date < precioExistente.VigenciaD.Date)
|
||||
{
|
||||
return (false, "No se puede cerrar este período porque existen períodos de precios posteriores que se solaparían. Elimine o ajuste los períodos posteriores primero.");
|
||||
transaction.Rollback();
|
||||
return (false, "La Vigencia Hasta no puede ser anterior a la Vigencia Desde.");
|
||||
}
|
||||
|
||||
// Validación 4: Nueva VigenciaH no debe solaparse con períodos posteriores
|
||||
var todosLosPreciosPub = await _precioRepository.GetByPublicacionIdAsync(precioExistente.IdPublicacion);
|
||||
if (todosLosPreciosPub.Any(p =>
|
||||
p.IdPrecio != idPrecio &&
|
||||
p.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
p.VigenciaD.Date > precioExistente.VigenciaD.Date &&
|
||||
(p.VigenciaH == null || p.VigenciaH.Value.Date >= p.VigenciaD.Date)
|
||||
))
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (false, "No se puede cerrar este período con la Vigencia Hasta especificada porque se solaparía con un período posterior existente. Ajuste los períodos posteriores primero.");
|
||||
}
|
||||
// Si pasa las validaciones, se asigna la nueva VigenciaH más abajo
|
||||
}
|
||||
// Si updateDto.VigenciaH es null, estas validaciones de fecha no aplican.
|
||||
|
||||
// Aplicar actualizaciones
|
||||
bool seRealizoAlgunaActualizacion = false;
|
||||
|
||||
precioExistente.Lunes = updateDto.Lunes ?? precioExistente.Lunes;
|
||||
precioExistente.Martes = updateDto.Martes ?? precioExistente.Martes;
|
||||
precioExistente.Miercoles = updateDto.Miercoles ?? precioExistente.Miercoles;
|
||||
precioExistente.Jueves = updateDto.Jueves ?? precioExistente.Jueves;
|
||||
precioExistente.Viernes = updateDto.Viernes ?? precioExistente.Viernes;
|
||||
precioExistente.Sabado = updateDto.Sabado ?? precioExistente.Sabado;
|
||||
precioExistente.Domingo = updateDto.Domingo ?? precioExistente.Domingo;
|
||||
if (updateDto.VigenciaH.HasValue) // Solo actualizar VigenciaH si se proporciona
|
||||
// Aplicar actualizaciones
|
||||
if (preciosDiasCambiaron)
|
||||
{
|
||||
precioExistente.VigenciaH = updateDto.VigenciaH.Value.Date;
|
||||
precioExistente.Lunes = updateDto.Lunes ?? precioExistente.Lunes;
|
||||
precioExistente.Martes = updateDto.Martes ?? precioExistente.Martes;
|
||||
precioExistente.Miercoles = updateDto.Miercoles ?? precioExistente.Miercoles;
|
||||
precioExistente.Jueves = updateDto.Jueves ?? precioExistente.Jueves;
|
||||
precioExistente.Viernes = updateDto.Viernes ?? precioExistente.Viernes;
|
||||
precioExistente.Sabado = updateDto.Sabado ?? precioExistente.Sabado;
|
||||
precioExistente.Domingo = updateDto.Domingo ?? precioExistente.Domingo;
|
||||
seRealizoAlgunaActualizacion = true;
|
||||
}
|
||||
|
||||
// Actualizar VigenciaH solo si el valor recibido en el DTO es diferente al existente,
|
||||
// o si se quiere pasar de un valor a null (reabrir) o de null a un valor (cerrar).
|
||||
if ((updateDto.VigenciaH.HasValue && (!precioExistente.VigenciaH.HasValue || updateDto.VigenciaH.Value.Date != precioExistente.VigenciaH.Value.Date)) ||
|
||||
(!updateDto.VigenciaH.HasValue && precioExistente.VigenciaH.HasValue))
|
||||
{
|
||||
precioExistente.VigenciaH = updateDto.VigenciaH.HasValue ? updateDto.VigenciaH.Value.Date : (DateTime?)null;
|
||||
seRealizoAlgunaActualizacion = true;
|
||||
}
|
||||
|
||||
var actualizado = await _precioRepository.UpdateAsync(precioExistente, idUsuario, transaction);
|
||||
if (!actualizado) throw new DataException("Error al actualizar el período de precio.");
|
||||
if (seRealizoAlgunaActualizacion)
|
||||
{
|
||||
var actualizado = await _precioRepository.UpdateAsync(precioExistente, idUsuario, transaction);
|
||||
if (!actualizado) throw new DataException("Error al actualizar el período de precio.");
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("No se detectaron cambios para Precio ID {IdPrecio}. No se realizó actualización.", idPrecio);
|
||||
}
|
||||
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Precio ID {IdPrecio} actualizado por Usuario ID {IdUsuario}.", idPrecio, idUsuario);
|
||||
_logger.LogInformation("Precio ID {IdPrecio} procesado (actualizado si hubo cambios) por Usuario ID {IdUsuario}.", idPrecio, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) { try { transaction.Rollback(); } catch {} return (false, "Período de precio no encontrado.");}
|
||||
catch (KeyNotFoundException) { try { transaction?.Rollback(); } catch { } return (false, "Período de precio no encontrado."); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
try { transaction?.Rollback(); } catch { }
|
||||
_logger.LogError(ex, "Error ActualizarAsync Precio ID: {IdPrecio}", idPrecio);
|
||||
return (false, $"Error interno al actualizar el período de precio: {ex.Message}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (connection.State == ConnectionState.Open)
|
||||
{
|
||||
if (connection is System.Data.Common.DbConnection dbConnClose) await dbConnClose.CloseAsync(); else connection.Close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(bool Exito, string? Error)> EliminarAsync(int idPrecio, int idUsuario)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var precioAEliminar = await _precioRepository.GetByIdAsync(idPrecio);
|
||||
var precioAEliminar = await _precioRepository.GetByIdAsync(idPrecio); // Obtener dentro de TX
|
||||
if (precioAEliminar == null) return (false, "Período de precio no encontrado.");
|
||||
|
||||
// Lógica de ajuste de VigenciaH del período anterior si este que se elimina era el "último" abierto.
|
||||
// Si el precio a eliminar tiene un VigenciaH == null (estaba activo indefinidamente)
|
||||
// Y existe un precio anterior para la misma publicación.
|
||||
// Entonces, el VigenciaH de ese precio anterior debe volver a ser NULL.
|
||||
// --- VERIFICACIÓN DE USO ---
|
||||
if (await _precioRepository.IsInUseAsync(idPrecio, precioAEliminar.VigenciaD, precioAEliminar.VigenciaH))
|
||||
{
|
||||
transaction.Rollback(); // No olvidar rollback si la verificación falla
|
||||
return (false, "No se puede eliminar. Este período de precio está referenciado en movimientos existentes.");
|
||||
}
|
||||
if (precioAEliminar.VigenciaH == null)
|
||||
{
|
||||
var todosLosPreciosPub = (await _precioRepository.GetByPublicacionIdAsync(precioAEliminar.IdPublicacion))
|
||||
.OrderByDescending(p => p.VigenciaD).ToList();
|
||||
|
||||
var indiceActual = todosLosPreciosPub.FindIndex(p=> p.IdPrecio == idPrecio);
|
||||
if(indiceActual != -1 && (indiceActual + 1) < todosLosPreciosPub.Count)
|
||||
var indiceActual = todosLosPreciosPub.FindIndex(p => p.IdPrecio == idPrecio);
|
||||
if (indiceActual != -1 && (indiceActual + 1) < todosLosPreciosPub.Count)
|
||||
{
|
||||
var precioAnteriorDirecto = todosLosPreciosPub[indiceActual + 1];
|
||||
// Solo si el precioAnteriorDirecto fue cerrado por este que se elimina
|
||||
if(precioAnteriorDirecto.VigenciaH.HasValue && precioAnteriorDirecto.VigenciaH.Value.Date == precioAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
if (precioAnteriorDirecto.VigenciaH.HasValue && precioAnteriorDirecto.VigenciaH.Value.Date == precioAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
{
|
||||
precioAnteriorDirecto.VigenciaH = null;
|
||||
await _precioRepository.UpdateAsync(precioAnteriorDirecto, idUsuario, transaction); // Usar un ID de auditoría adecuado
|
||||
_logger.LogInformation("Precio anterior ID {IdPrecioAnterior} reabierto (VigenciaH a NULL) tras eliminación de Precio ID {IdPrecioEliminado}.", precioAnteriorDirecto.IdPrecio, idPrecio);
|
||||
// Asegurar que UpdateAsync tome la transacción
|
||||
await _precioRepository.UpdateAsync(precioAnteriorDirecto, idUsuario, transaction);
|
||||
_logger.LogInformation("Precio anterior ID {IdPrecioAnterior} reabierto tras eliminación de Precio ID {IdPrecioEliminado}.", precioAnteriorDirecto.IdPrecio, idPrecio);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
var eliminado = await _precioRepository.DeleteAsync(idPrecio, idUsuario, transaction);
|
||||
if (!eliminado) throw new DataException("Error al eliminar el período de precio.");
|
||||
|
||||
@@ -218,13 +288,40 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
_logger.LogInformation("Precio ID {IdPrecio} eliminado por Usuario ID {IdUsuario}.", idPrecio, idUsuario);
|
||||
return (true, null);
|
||||
}
|
||||
catch (KeyNotFoundException) { try { transaction.Rollback(); } catch {} return (false, "Período de precio no encontrado."); }
|
||||
catch (KeyNotFoundException) { try { transaction.Rollback(); } catch { } return (false, "Período de precio no encontrado."); }
|
||||
catch (Exception ex)
|
||||
{
|
||||
try { transaction.Rollback(); } catch {}
|
||||
try { transaction.Rollback(); } catch { }
|
||||
_logger.LogError(ex, "Error EliminarAsync Precio ID: {IdPrecio}", idPrecio);
|
||||
return (false, $"Error interno al eliminar el período de precio: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<PrecioHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPrecioAfectado, int? idPublicacionAfectada)
|
||||
{
|
||||
var historialData = await _precioRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPrecioAfectado, idPublicacionAfectada);
|
||||
|
||||
return historialData.Select(h => new PrecioHistorialDto
|
||||
{
|
||||
Id_Precio = h.Historial.Id_Precio,
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
VigenciaD = h.Historial.VigenciaD,
|
||||
VigenciaH = h.Historial.VigenciaH,
|
||||
Lunes = h.Historial.Lunes,
|
||||
Martes = h.Historial.Martes,
|
||||
Miercoles = h.Historial.Miercoles,
|
||||
Jueves = h.Historial.Jueves,
|
||||
Viernes = h.Historial.Viernes,
|
||||
Sabado = h.Historial.Sabado,
|
||||
Domingo = h.Historial.Domingo,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -121,7 +122,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
|
||||
public async Task<(bool Exito, string? Error)> EliminarAsync(int idSeccion, int idUsuario)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
@@ -149,5 +150,26 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<PubliSeccionHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idSeccionAfectada, int? idPublicacionAfectada)
|
||||
{
|
||||
var historialData = await _publiSeccionRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idSeccionAfectada, idPublicacionAfectada);
|
||||
|
||||
// Si necesitas NombrePublicacion, harías la llamada a _publicacionRepository aquí.
|
||||
return historialData.Select(h => new PubliSeccionHistorialDto
|
||||
{
|
||||
Id_Seccion = h.Historial.Id_Seccion,
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
Nombre = h.Historial.Nombre,
|
||||
Estado = h.Historial.Estado,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
// src/Services/Distribucion/PublicacionService.cs
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -284,5 +285,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno al actualizar la configuración de días: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<PublicacionHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idPublicacionAfectada)
|
||||
{
|
||||
var historialData = await _publicacionRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPublicacionAfectada);
|
||||
|
||||
// Si necesitas NombreEmpresa, harías el JOIN en repo o llamada a _empresaRepository aquí.
|
||||
return historialData.Select(h => new PublicacionHistorialDto
|
||||
{
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
Nombre = h.Historial.Nombre,
|
||||
Observacion = h.Historial.Observacion,
|
||||
Id_Empresa = h.Historial.Id_Empresa,
|
||||
Habilitada = h.Historial.Habilitada,
|
||||
// CtrlDevoluciones no está en _H, si se añade, mapearla aquí
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data;
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -43,7 +44,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
VigenciaH = data.Recargo.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||
Valor = data.Recargo.Valor
|
||||
};
|
||||
|
||||
|
||||
// Helper para mapear cuando solo tenemos el RecargoZona y necesitamos buscar NombreZona
|
||||
private async Task<RecargoZonaDto> MapToDtoWithZonaLookup(RecargoZona recargo)
|
||||
{
|
||||
@@ -74,10 +75,11 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
{
|
||||
var recargo = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||
if (recargo == null) return null;
|
||||
|
||||
|
||||
var zona = await _zonaRepository.GetByIdAsync(recargo.IdZona); // Obtiene ZonaDto
|
||||
return new RecargoZonaDto {
|
||||
IdRecargo = recargo.IdRecargo,
|
||||
return new RecargoZonaDto
|
||||
{
|
||||
IdRecargo = recargo.IdRecargo,
|
||||
IdPublicacion = recargo.IdPublicacion,
|
||||
IdZona = recargo.IdZona,
|
||||
NombreZona = zona?.Nombre ?? "Zona Desconocida/Inactiva",
|
||||
@@ -92,7 +94,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
||||
return (null, "La publicación especificada no existe.");
|
||||
var zona = await _zonaRepository.GetByIdAsync(createDto.IdZona); // Devuelve ZonaDto
|
||||
if (zona == null)
|
||||
if (zona == null)
|
||||
return (null, "La zona especificada no existe o no está activa.");
|
||||
|
||||
// Usar createDto.VigenciaD directamente que ya es DateTime
|
||||
@@ -119,7 +121,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var recargoAnterior = await _recargoZonaRepository.GetPreviousActiveRecargoAsync(createDto.IdPublicacion, createDto.IdZona, nuevoRecargo.VigenciaD, transaction);
|
||||
if (recargoAnterior != null)
|
||||
{
|
||||
if (recargoAnterior.VigenciaD.Date >= nuevoRecargo.VigenciaD.Date) // Comparar solo fechas
|
||||
if (recargoAnterior.VigenciaD.Date >= nuevoRecargo.VigenciaD.Date) // Comparar solo fechas
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (null, $"La fecha de inicio del nuevo recargo ({nuevoRecargo.VigenciaD:dd/MM/yyyy}) no puede ser anterior o igual a la del último recargo vigente ({recargoAnterior.VigenciaD:dd/MM/yyyy}) para esta zona.");
|
||||
@@ -134,10 +136,15 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
transaction.Commit();
|
||||
_logger.LogInformation("Recargo ID {Id} creado por Usuario ID {UserId}.", recargoCreado.IdRecargo, idUsuario);
|
||||
// Pasar el nombre de la zona ya obtenido
|
||||
return (new RecargoZonaDto {
|
||||
IdRecargo = recargoCreado.IdRecargo, IdPublicacion = recargoCreado.IdPublicacion, IdZona = recargoCreado.IdZona,
|
||||
NombreZona = zona.Nombre, VigenciaD = recargoCreado.VigenciaD.ToString("yyyy-MM-dd"),
|
||||
VigenciaH = recargoCreado.VigenciaH?.ToString("yyyy-MM-dd"), Valor = recargoCreado.Valor
|
||||
return (new RecargoZonaDto
|
||||
{
|
||||
IdRecargo = recargoCreado.IdRecargo,
|
||||
IdPublicacion = recargoCreado.IdPublicacion,
|
||||
IdZona = recargoCreado.IdZona,
|
||||
NombreZona = zona.Nombre,
|
||||
VigenciaD = recargoCreado.VigenciaD.ToString("yyyy-MM-dd"),
|
||||
VigenciaH = recargoCreado.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||
Valor = recargoCreado.Valor
|
||||
}, null);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -155,21 +162,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
using var transaction = connection.BeginTransaction();
|
||||
try
|
||||
{
|
||||
var recargoExistente = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||
var recargoExistente = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||
if (recargoExistente == null) return (false, "Recargo por zona no encontrado.");
|
||||
|
||||
// --- VERIFICACIÓN PERÍODO CERRADO ---
|
||||
if (recargoExistente.VigenciaH != null && updateDto.Valor != recargoExistente.Valor)
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (false, "No se puede modificar el valor de un recargo que ya ha sido cerrado (tiene Vigencia Hasta).");
|
||||
}
|
||||
|
||||
if (updateDto.VigenciaH.HasValue && updateDto.VigenciaH.Value.Date < recargoExistente.VigenciaD.Date)
|
||||
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
||||
|
||||
|
||||
if (updateDto.VigenciaH.HasValue)
|
||||
{
|
||||
var recargosDeLaPublicacion = await _recargoZonaRepository.GetByPublicacionIdAsync(recargoExistente.IdPublicacion);
|
||||
var recargosPosteriores = recargosDeLaPublicacion
|
||||
.Where(r => r.Recargo.IdZona == recargoExistente.IdZona &&
|
||||
r.Recargo.IdRecargo != idRecargo &&
|
||||
r.Recargo.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
.Where(r => r.Recargo.IdZona == recargoExistente.IdZona &&
|
||||
r.Recargo.IdRecargo != idRecargo &&
|
||||
r.Recargo.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||
r.Recargo.VigenciaD.Date > recargoExistente.VigenciaD.Date);
|
||||
if(recargosPosteriores.Any())
|
||||
if (recargosPosteriores.Any())
|
||||
{
|
||||
return (false, "No se puede cerrar este período porque existen recargos posteriores para esta zona que se solaparían.");
|
||||
}
|
||||
@@ -207,19 +221,26 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var recargoAEliminar = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||
if (recargoAEliminar == null) return (false, "Recargo no encontrado.");
|
||||
|
||||
if (recargoAEliminar.VigenciaH == null)
|
||||
// --- VERIFICACIÓN DE USO ---
|
||||
if (await _recargoZonaRepository.IsInUseAsync(idRecargo, recargoAEliminar.VigenciaD, recargoAEliminar.VigenciaH))
|
||||
{
|
||||
transaction.Rollback();
|
||||
return (false, "No se puede eliminar. Este recargo está referenciado en movimientos existentes.");
|
||||
}
|
||||
|
||||
if (recargoAEliminar.VigenciaH == null)
|
||||
{
|
||||
var todosRecargosPubZonaData = await _recargoZonaRepository.GetByPublicacionIdAsync(recargoAEliminar.IdPublicacion);
|
||||
var todosRecargosPubZona = todosRecargosPubZonaData
|
||||
.Where(r => r.Recargo.IdZona == recargoAEliminar.IdZona)
|
||||
.Select(r => r.Recargo)
|
||||
.OrderByDescending(r => r.VigenciaD).ToList();
|
||||
|
||||
|
||||
var indiceActual = todosRecargosPubZona.FindIndex(r => r.IdRecargo == idRecargo);
|
||||
if(indiceActual != -1 && (indiceActual + 1) < todosRecargosPubZona.Count)
|
||||
if (indiceActual != -1 && (indiceActual + 1) < todosRecargosPubZona.Count)
|
||||
{
|
||||
var recargoAnteriorDirecto = todosRecargosPubZona[indiceActual + 1];
|
||||
if(recargoAnteriorDirecto.VigenciaH.HasValue && recargoAnteriorDirecto.VigenciaH.Value.Date == recargoAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
if (recargoAnteriorDirecto.VigenciaH.HasValue && recargoAnteriorDirecto.VigenciaH.Value.Date == recargoAEliminar.VigenciaD.AddDays(-1).Date)
|
||||
{
|
||||
recargoAnteriorDirecto.VigenciaH = null;
|
||||
await _recargoZonaRepository.UpdateAsync(recargoAnteriorDirecto, idUsuario, transaction);
|
||||
@@ -243,5 +264,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, $"Error interno: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<RecargoZonaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idRecargoAfectado, int? idPublicacionAfectada, int? idZonaAfectada)
|
||||
{
|
||||
var historialData = await _recargoZonaRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idRecargoAfectado, idPublicacionAfectada, idZonaAfectada);
|
||||
|
||||
return historialData.Select(h => new RecargoZonaHistorialDto
|
||||
{
|
||||
Id_Recargo = h.Historial.Id_Recargo,
|
||||
Id_Publicacion = h.Historial.Id_Publicacion,
|
||||
Id_Zona = h.Historial.Id_Zona,
|
||||
VigenciaD = h.Historial.VigenciaD,
|
||||
VigenciaH = h.Historial.VigenciaH,
|
||||
Valor = h.Historial.Valor,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
// Mapear NombrePublicacion y NombreZona si se añaden al DTO
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using GestionIntegral.Api.Data.Repositories; // Para IZonaRepository
|
||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||
using GestionIntegral.Api.Dtos.Auditoria;
|
||||
using GestionIntegral.Api.Dtos.Zonas;
|
||||
using GestionIntegral.Api.Models.Distribucion; // Para Zona
|
||||
using System.Collections.Generic;
|
||||
@@ -123,7 +124,8 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
return (false, "Zona no encontrada.");
|
||||
}
|
||||
// Si ya está inactiva, consideramos la operación exitosa (idempotencia)
|
||||
if (!zonaExistente.Estado) {
|
||||
if (!zonaExistente.Estado)
|
||||
{
|
||||
return (true, null);
|
||||
}
|
||||
|
||||
@@ -137,10 +139,30 @@ namespace GestionIntegral.Api.Services.Distribucion
|
||||
var eliminado = await _zonaRepository.SoftDeleteAsync(id, idUsuario);
|
||||
if (!eliminado)
|
||||
{
|
||||
_logger.LogError("Falló la eliminación lógica de la Zona en el repositorio para el ID: {Id}", id);
|
||||
_logger.LogError("Falló la eliminación lógica de la Zona en el repositorio para el ID: {Id}", id);
|
||||
return (false, "Error al eliminar la zona de la base de datos.");
|
||||
}
|
||||
return (true, null); // Éxito
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ZonaHistorialDto>> ObtenerHistorialAsync(
|
||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||
int? idUsuarioModifico, string? tipoModificacion,
|
||||
int? idZonaAfectada)
|
||||
{
|
||||
var historialData = await _zonaRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idZonaAfectada);
|
||||
|
||||
return historialData.Select(h => new ZonaHistorialDto
|
||||
{
|
||||
Id_Zona = h.Historial.Id_Zona,
|
||||
Nombre = h.Historial.Nombre,
|
||||
Descripcion = h.Historial.Descripcion,
|
||||
Estado = h.Historial.Estado,
|
||||
Id_Usuario = h.Historial.Id_Usuario,
|
||||
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||
FechaMod = h.Historial.FechaMod,
|
||||
TipoMod = h.Historial.TipoMod
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user