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:
@@ -7,11 +7,13 @@ using System.Collections.Generic;
|
|||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using System.Security.Claims; // Para ClaimTypes
|
using System.Security.Claims; // Para ClaimTypes
|
||||||
using GestionIntegral.Api.Services.Contables; // Para IPagoDistribuidorService, etc.
|
using GestionIntegral.Api.Services.Contables; // Para IPagoDistribuidorService, etc.
|
||||||
using GestionIntegral.Api.Dtos.Contables; // Para PagoDistribuidorHistorialDto, etc.
|
|
||||||
using GestionIntegral.Api.Services.Distribucion;
|
using GestionIntegral.Api.Services.Distribucion;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
|
||||||
using GestionIntegral.Api.Dtos.Usuarios.Auditoria;
|
|
||||||
using GestionIntegral.Api.Dtos.Auditoria;
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
|
using GestionIntegral.Api.Dtos.Zonas;
|
||||||
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
|
using GestionIntegral.Api.Services.Impresion;
|
||||||
|
using GestionIntegral.Api.Dtos.Impresion;
|
||||||
|
using GestionIntegral.Api.Dtos.Usuarios;
|
||||||
|
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Controllers
|
namespace GestionIntegral.Api.Controllers
|
||||||
@@ -32,6 +34,23 @@ namespace GestionIntegral.Api.Controllers
|
|||||||
private readonly ISaldoService _saldoService;
|
private readonly ISaldoService _saldoService;
|
||||||
private readonly ITipoPagoService _tipoPagoService;
|
private readonly ITipoPagoService _tipoPagoService;
|
||||||
private readonly IEmpresaService _empresaService;
|
private readonly IEmpresaService _empresaService;
|
||||||
|
private readonly IZonaService _zonaService;
|
||||||
|
private readonly IOtroDestinoService _otroDestinoService;
|
||||||
|
private readonly IPublicacionService _publicacionService;
|
||||||
|
private readonly IPubliSeccionService _publiSeccionService;
|
||||||
|
private readonly IPrecioService _precioService;
|
||||||
|
private readonly IRecargoZonaService _recargoZonaService;
|
||||||
|
private readonly IPorcPagoService _porcPagoService;
|
||||||
|
private readonly IPorcMonCanillaService _porcMonCanillaService;
|
||||||
|
private readonly IControlDevolucionesService _controlDevolucionesService;
|
||||||
|
private readonly ITipoBobinaService _tipoBobinaService;
|
||||||
|
private readonly IEstadoBobinaService _estadoBobinaService;
|
||||||
|
private readonly IPlantaService _plantaService;
|
||||||
|
private readonly IStockBobinaService _stockBobinaService;
|
||||||
|
private readonly ITiradaService _tiradaService;
|
||||||
|
private readonly IPerfilService _perfilService;
|
||||||
|
private readonly IPermisoService _permisoService;
|
||||||
|
private readonly ICambioParadaService _cambioParadaService;
|
||||||
private readonly ILogger<AuditoriaController> _logger;
|
private readonly ILogger<AuditoriaController> _logger;
|
||||||
|
|
||||||
// Permiso general para ver cualquier auditoría.
|
// Permiso general para ver cualquier auditoría.
|
||||||
@@ -50,6 +69,23 @@ namespace GestionIntegral.Api.Controllers
|
|||||||
ISaldoService saldoService,
|
ISaldoService saldoService,
|
||||||
ITipoPagoService tipoPagoService,
|
ITipoPagoService tipoPagoService,
|
||||||
IEmpresaService empresaService,
|
IEmpresaService empresaService,
|
||||||
|
IZonaService zonaService,
|
||||||
|
IOtroDestinoService otroDestinoService,
|
||||||
|
IPublicacionService publicacionService,
|
||||||
|
IPubliSeccionService publiSeccionService,
|
||||||
|
IPrecioService precioService,
|
||||||
|
IRecargoZonaService recargoZonaService,
|
||||||
|
IPorcPagoService porcPagoService,
|
||||||
|
IPorcMonCanillaService porcMonCanillaService,
|
||||||
|
IControlDevolucionesService controlDevolucionesService,
|
||||||
|
ITipoBobinaService tipoBobinaService,
|
||||||
|
IEstadoBobinaService estadoBobinaService,
|
||||||
|
IPlantaService plantaService,
|
||||||
|
IStockBobinaService stockBobinaService,
|
||||||
|
ITiradaService tiradaService,
|
||||||
|
IPerfilService perfilService,
|
||||||
|
IPermisoService permisoService,
|
||||||
|
ICambioParadaService cambioParadaService,
|
||||||
ILogger<AuditoriaController> logger)
|
ILogger<AuditoriaController> logger)
|
||||||
{
|
{
|
||||||
_usuarioService = usuarioService;
|
_usuarioService = usuarioService;
|
||||||
@@ -63,6 +99,23 @@ namespace GestionIntegral.Api.Controllers
|
|||||||
_saldoService = saldoService;
|
_saldoService = saldoService;
|
||||||
_tipoPagoService = tipoPagoService;
|
_tipoPagoService = tipoPagoService;
|
||||||
_empresaService = empresaService;
|
_empresaService = empresaService;
|
||||||
|
_zonaService = zonaService;
|
||||||
|
_otroDestinoService = otroDestinoService;
|
||||||
|
_publicacionService = publicacionService;
|
||||||
|
_publiSeccionService = publiSeccionService;
|
||||||
|
_precioService = precioService;
|
||||||
|
_recargoZonaService = recargoZonaService;
|
||||||
|
_porcPagoService = porcPagoService;
|
||||||
|
_porcMonCanillaService = porcMonCanillaService;
|
||||||
|
_controlDevolucionesService = controlDevolucionesService;
|
||||||
|
_tipoBobinaService = tipoBobinaService;
|
||||||
|
_estadoBobinaService = estadoBobinaService;
|
||||||
|
_plantaService = plantaService;
|
||||||
|
_stockBobinaService = stockBobinaService;
|
||||||
|
_tiradaService = tiradaService;
|
||||||
|
_perfilService = perfilService;
|
||||||
|
_cambioParadaService = cambioParadaService;
|
||||||
|
_permisoService = permisoService;
|
||||||
_logger = logger;
|
_logger = logger;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,5 +327,389 @@ namespace GestionIntegral.Api.Controllers
|
|||||||
return StatusCode(500, "Error interno al obtener historial de Empresas (Maestro).");
|
return StatusCode(500, "Error interno al obtener historial de Empresas (Maestro).");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[HttpGet("zonas-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<ZonaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialZonasMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idZonaAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Asumiendo que _zonaService está inyectado
|
||||||
|
var historial = await _zonaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idZonaAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<ZonaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Zonas (Maestro).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Zonas (Maestro).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("otros-destinos-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<OtroDestinoHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialOtrosDestinosMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idOtroDestinoAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _otroDestinoService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idOtroDestinoAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<OtroDestinoHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Otros Destinos (Maestro).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Otros Destinos (Maestro).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("publicaciones-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PublicacionHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPublicacionesMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPublicacionAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _publicacionService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPublicacionAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PublicacionHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Publicaciones (Maestro).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Publicaciones (Maestro).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("publi-secciones-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PubliSeccionHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPubliSeccionesMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idSeccionAfectada, [FromQuery] int? idPublicacionAfectada) // Nuevos filtros
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _publiSeccionService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idSeccionAfectada, idPublicacionAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PubliSeccionHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Secciones de Publicación.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Secciones de Publicación.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("precios-publicacion-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PrecioHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPreciosMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPrecioAfectado, [FromQuery] int? idPublicacionAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _precioService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPrecioAfectado, idPublicacionAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PrecioHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Precios de Publicación.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Precios de Publicación.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("recargos-zona-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<RecargoZonaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialRecargosZonaMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idRecargoAfectado, [FromQuery] int? idPublicacionAfectada, [FromQuery] int? idZonaAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _recargoZonaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idRecargoAfectado, idPublicacionAfectada, idZonaAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<RecargoZonaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Recargos por Zona.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Recargos por Zona.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("porc-pago-dist-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PorcPagoHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPorcPagoDistMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPorcentajeAfectado, [FromQuery] int? idPublicacionAfectada, [FromQuery] int? idDistribuidorAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _porcPagoService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPorcentajeAfectado, idPublicacionAfectada, idDistribuidorAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PorcPagoHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Porcentajes de Pago (Dist).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Porcentajes de Pago (Dist).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("porc-mon-canilla-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PorcMonCanillaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPorcMonCanillaMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPorcMonAfectado, [FromQuery] int? idPublicacionAfectada, [FromQuery] int? idCanillaAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _porcMonCanillaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPorcMonAfectado, idPublicacionAfectada, idCanillaAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PorcMonCanillaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Porc/Mon Canillita.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Porc/Mon Canillita.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("control-devoluciones-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<ControlDevolucionesHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialControlDevolucionesMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idControlAfectado, [FromQuery] int? idEmpresaAfectada, [FromQuery] DateTime? fechaAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _controlDevolucionesService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idControlAfectado, idEmpresaAfectada, fechaAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<ControlDevolucionesHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Control de Devoluciones.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Control de Devoluciones.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("tipos-bobina-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<TipoBobinaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialTiposBobinaMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idTipoBobinaAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _tipoBobinaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idTipoBobinaAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<TipoBobinaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Tipos de Bobina.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Tipos de Bobina.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("estados-bobina-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<EstadoBobinaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialEstadosBobinaMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idEstadoBobinaAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _estadoBobinaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idEstadoBobinaAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<EstadoBobinaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Estados de Bobina.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Estados de Bobina.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("plantas-impresion-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PlantaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPlantasMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPlantaAfectada)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _plantaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPlantaAfectada);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PlantaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Plantas de Impresión.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Plantas de Impresión.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("stock-bobinas-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<StockBobinaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialStockBobinasMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idBobinaAfectada, [FromQuery] int? idTipoBobinaFiltro,
|
||||||
|
[FromQuery] int? idPlantaFiltro, [FromQuery] int? idEstadoBobinaFiltro)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _stockBobinaService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idBobinaAfectada, idTipoBobinaFiltro, idPlantaFiltro, idEstadoBobinaFiltro);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<StockBobinaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Stock de Bobinas.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Stock de Bobinas.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("reg-tiradas-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<RegTiradaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialRegTiradasMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idRegistroAfectado, [FromQuery] int? idPublicacionFiltro,
|
||||||
|
[FromQuery] int? idPlantaFiltro, [FromQuery] DateTime? fechaTiradaFiltro)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _tiradaService.ObtenerRegTiradasHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idRegistroAfectado, idPublicacionFiltro, idPlantaFiltro, fechaTiradaFiltro);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<RegTiradaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Registro de Tiradas.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Registro de Tiradas.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("reg-secciones-tirada-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<RegSeccionTiradaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialRegSeccionesTiradaMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idTiradaAfectada, [FromQuery] int? idPublicacionFiltro,
|
||||||
|
[FromQuery] int? idSeccionFiltro, [FromQuery] int? idPlantaFiltro, [FromQuery] DateTime? fechaTiradaFiltro)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _tiradaService.ObtenerRegSeccionesTiradaHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idTiradaAfectada, idPublicacionFiltro, idSeccionFiltro, idPlantaFiltro, fechaTiradaFiltro);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<RegSeccionTiradaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Secciones de Tirada.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Secciones de Tirada.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("perfiles-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PerfilHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPerfilesMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPerfilAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _perfilService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPerfilAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PerfilHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Perfiles (Maestro).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Perfiles (Maestro).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("permisos-maestro")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PermisoHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPermisosMaestro(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPermisoAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _permisoService.ObtenerHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPermisoAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PermisoHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Permisos (Maestro).");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Permisos (Maestro).");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("permisos-perfiles-historial")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<PermisosPerfilesHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialPermisosPerfiles(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idPerfilAfectado, [FromQuery] int? idPermisoAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _perfilService.ObtenerPermisosAsignadosHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idPerfilAfectado, idPermisoAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<PermisosPerfilesHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Asignación de Permisos.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Asignación de Permisos.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HttpGet("cambios-parada-canilla")]
|
||||||
|
[ProducesResponseType(typeof(IEnumerable<CambioParadaHistorialDto>), StatusCodes.Status200OK)]
|
||||||
|
public async Task<IActionResult> GetHistorialCambiosParada(
|
||||||
|
[FromQuery] DateTime? fechaDesde, [FromQuery] DateTime? fechaHasta,
|
||||||
|
[FromQuery] int? idUsuarioModifico, [FromQuery] string? tipoModificacion,
|
||||||
|
[FromQuery] int? idCanillaAfectado)
|
||||||
|
{
|
||||||
|
if (!TienePermiso(PermisoVerAuditoria)) return Forbid();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var historial = await _cambioParadaService.ObtenerCambiosParadaHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idCanillaAfectado);
|
||||||
|
return Ok(historial ?? Enumerable.Empty<CambioParadaHistorialDto>());
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error obteniendo historial de Cambios de Parada.");
|
||||||
|
return StatusCode(500, "Error interno al obtener historial de Cambios de Parada.");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,11 +124,15 @@ namespace GestionIntegral.Api.Controllers.Impresion
|
|||||||
public async Task<IActionResult> CambiarEstadoBobina(int idBobina, [FromBody] CambiarEstadoBobinaDto cambiarEstadoDto)
|
public async Task<IActionResult> CambiarEstadoBobina(int idBobina, [FromBody] CambiarEstadoBobinaDto cambiarEstadoDto)
|
||||||
{
|
{
|
||||||
if (!TienePermiso(PermisoCambiarEstado)) return Forbid();
|
if (!TienePermiso(PermisoCambiarEstado)) return Forbid();
|
||||||
if (!ModelState.IsValid) return BadRequest(ModelState);
|
if (!ModelState.IsValid) return BadRequest(ModelState); // Validaciones de DTO (Required, Range, etc.)
|
||||||
var userId = GetCurrentUserId();
|
var userId = GetCurrentUserId();
|
||||||
if (userId == null) return Unauthorized();
|
if (userId == null) return Unauthorized();
|
||||||
|
|
||||||
// Validación adicional en el controlador para el caso "En Uso"
|
// La validación de que IdPublicacion/IdSeccion son requeridos para estado "En Uso"
|
||||||
|
// ahora está más robusta en el servicio. Se puede quitar del controlador
|
||||||
|
// si se prefiere que el servicio sea la única fuente de verdad para esa lógica.
|
||||||
|
// Si la mantenés acá, es una validación temprana.
|
||||||
|
/*
|
||||||
if (cambiarEstadoDto.NuevoEstadoId == 2) // Asumiendo 2 = En Uso
|
if (cambiarEstadoDto.NuevoEstadoId == 2) // Asumiendo 2 = En Uso
|
||||||
{
|
{
|
||||||
if (!cambiarEstadoDto.IdPublicacion.HasValue || cambiarEstadoDto.IdPublicacion.Value <= 0)
|
if (!cambiarEstadoDto.IdPublicacion.HasValue || cambiarEstadoDto.IdPublicacion.Value <= 0)
|
||||||
@@ -136,12 +140,13 @@ namespace GestionIntegral.Api.Controllers.Impresion
|
|||||||
if (!cambiarEstadoDto.IdSeccion.HasValue || cambiarEstadoDto.IdSeccion.Value <=0)
|
if (!cambiarEstadoDto.IdSeccion.HasValue || cambiarEstadoDto.IdSeccion.Value <=0)
|
||||||
return BadRequest(new { message = "Se requiere IdSeccion para el estado 'En Uso'."});
|
return BadRequest(new { message = "Se requiere IdSeccion para el estado 'En Uso'."});
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
var (exito, error) = await _stockBobinaService.CambiarEstadoBobinaAsync(idBobina, cambiarEstadoDto, userId.Value);
|
var (exito, error) = await _stockBobinaService.CambiarEstadoBobinaAsync(idBobina, cambiarEstadoDto, userId.Value);
|
||||||
if (!exito)
|
if (!exito)
|
||||||
{
|
{
|
||||||
if (error == "Bobina no encontrada.") return NotFound(new { message = error });
|
if (error == "Bobina no encontrada.") return NotFound(new { message = error });
|
||||||
|
// Otros errores específicos del servicio (ej. flujo de estado no permitido) vienen como BadRequest
|
||||||
return BadRequest(new { message = error });
|
return BadRequest(new { message = error });
|
||||||
}
|
}
|
||||||
return NoContent();
|
return NoContent();
|
||||||
|
|||||||
@@ -105,23 +105,33 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> UpdateVigenciaHAsync(int idRegistro, DateTime vigenciaH, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> UpdateVigenciaHAsync(int idRegistro, DateTime vigenciaH, int idUsuario, IDbTransaction transaction)
|
||||||
|
{
|
||||||
|
var paradaOriginal = await GetByIdAsync(idRegistro);
|
||||||
|
if (paradaOriginal == null) throw new KeyNotFoundException("Registro de parada no encontrado para actualizar VigenciaH.");
|
||||||
|
|
||||||
|
var paradaParaHistorial = new CambioParadaCanilla
|
||||||
{
|
{
|
||||||
var paradaOriginal = await GetByIdAsync(idRegistro); // Obtener para el log
|
IdRegistro = paradaOriginal.IdRegistro,
|
||||||
if (paradaOriginal == null) throw new KeyNotFoundException("Registro de parada no encontrado para actualizar VigenciaH.");
|
IdCanilla = paradaOriginal.IdCanilla,
|
||||||
|
Parada = paradaOriginal.Parada,
|
||||||
|
VigenciaD = paradaOriginal.VigenciaD,
|
||||||
|
VigenciaH = vigenciaH.Date
|
||||||
|
};
|
||||||
|
|
||||||
// Loggear ANTES de actualizar
|
// Loggear el estado que QUEDARÁ en la tabla principal (con la VigenciaH actualizada)
|
||||||
await LogHistorialAsync(paradaOriginal, idUsuario, "Cerrada", transaction.Connection!, transaction);
|
// El TipoMod debería reflejar la acción. "Cerrada".
|
||||||
|
await LogHistorialAsync(paradaParaHistorial, idUsuario, "Cerrada", transaction.Connection!, transaction);
|
||||||
|
|
||||||
const string sqlUpdate = @"
|
const string sqlUpdate = @"
|
||||||
UPDATE dbo.dist_CambiosParadasCanillas
|
UPDATE dbo.dist_CambiosParadasCanillas
|
||||||
SET VigenciaH = @VigenciaH
|
SET VigenciaH = @VigenciaH
|
||||||
WHERE Id_Registro = @IdRegistro;";
|
WHERE Id_Registro = @IdRegistro;";
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate,
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate,
|
||||||
new { VigenciaH = vigenciaH.Date, IdRegistro = idRegistro },
|
new { VigenciaH = vigenciaH.Date, IdRegistro = idRegistro },
|
||||||
transaction);
|
transaction);
|
||||||
|
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
@@ -135,5 +145,49 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdRegistro = idRegistro }, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdRegistro = idRegistro }, transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(CambioParadaCanillaHistorial Historial, string NombreUsuarioModifico, string NombreCanilla)>> GetCambiosParadaHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idCanillaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Registro, h.Id_Canilla, h.Parada, h.VigenciaD, h.VigenciaH,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico,
|
||||||
|
c.NomApe AS NombreCanilla
|
||||||
|
FROM dbo.dist_CambiosParadasCanillas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
JOIN dbo.dist_dtCanillas c ON h.Id_Canilla = c.Id_Canilla
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idCanillaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Canilla = @IdCanillaOriginalParam"); parameters.Add("IdCanillaOriginalParam", idCanillaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<CambioParadaCanillaHistorial, string, string, (CambioParadaCanillaHistorial, string, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userMod, canillaNombre) => (hist, userMod, canillaNombre),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico,NombreCanilla"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Cambios de Parada.");
|
||||||
|
return Enumerable.Empty<(CambioParadaCanillaHistorial, string, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -36,7 +36,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND Fecha >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND Fecha >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND Fecha <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date); }
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND Fecha <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date); }
|
||||||
if (idEmpresa.HasValue) { sqlBuilder.Append(" AND Id_Empresa = @IdEmpresaParam"); parameters.Add("IdEmpresaParam", idEmpresa.Value); }
|
if (idEmpresa.HasValue) { sqlBuilder.Append(" AND Id_Empresa = @IdEmpresaParam"); parameters.Add("IdEmpresaParam", idEmpresa.Value); }
|
||||||
|
|
||||||
sqlBuilder.Append(" ORDER BY Fecha DESC, Id_Empresa;");
|
sqlBuilder.Append(" ORDER BY Fecha DESC, Id_Empresa;");
|
||||||
|
|
||||||
try
|
try
|
||||||
@@ -101,10 +101,18 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
var inserted = await transaction.Connection!.QuerySingleAsync<ControlDevoluciones>(sqlInsert, nuevoControl, transaction);
|
var inserted = await transaction.Connection!.QuerySingleAsync<ControlDevoluciones>(sqlInsert, nuevoControl, transaction);
|
||||||
if (inserted == null || inserted.IdControl == 0) throw new DataException("Error al crear control de devoluciones o ID no generado.");
|
if (inserted == null || inserted.IdControl == 0) throw new DataException("Error al crear control de devoluciones o ID no generado.");
|
||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdControlParam = inserted.IdControl, IdEmpresaParam = inserted.IdEmpresa, FechaParam = inserted.Fecha,
|
{
|
||||||
EntradaParam = inserted.Entrada, SobrantesParam = inserted.Sobrantes, DetalleParam = inserted.Detalle, SinCargoParam = inserted.SinCargo,
|
IdControlParam = inserted.IdControl,
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Creado"
|
IdEmpresaParam = inserted.IdEmpresa,
|
||||||
|
FechaParam = inserted.Fecha,
|
||||||
|
EntradaParam = inserted.Entrada,
|
||||||
|
SobrantesParam = inserted.Sobrantes,
|
||||||
|
DetalleParam = inserted.Detalle,
|
||||||
|
SinCargoParam = inserted.SinCargo,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Creado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
@@ -121,15 +129,23 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
UPDATE dbo.dist_dtCtrlDevoluciones SET
|
UPDATE dbo.dist_dtCtrlDevoluciones SET
|
||||||
Entrada = @Entrada, Sobrantes = @Sobrantes, Detalle = @Detalle, SinCargo = @SinCargo
|
Entrada = @Entrada, Sobrantes = @Sobrantes, Detalle = @Detalle, SinCargo = @SinCargo
|
||||||
WHERE Id_Control = @IdControl;";
|
WHERE Id_Control = @IdControl;";
|
||||||
const string sqlHistorico = @"
|
const string sqlHistorico = @"
|
||||||
INSERT INTO dbo.dist_dtCtrlDevoluciones_H
|
INSERT INTO dbo.dist_dtCtrlDevoluciones_H
|
||||||
(Id_Control, Id_Empresa, Fecha, Entrada, Sobrantes, Detalle, SinCargo, Id_Usuario, FechaMod, TipoMod)
|
(Id_Control, Id_Empresa, Fecha, Entrada, Sobrantes, Detalle, SinCargo, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdControlParam, @IdEmpresaParam, @FechaParam, @EntradaParam, @SobrantesParam, @DetalleParam, @SinCargoParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdControlParam, @IdEmpresaParam, @FechaParam, @EntradaParam, @SobrantesParam, @DetalleParam, @SinCargoParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdControlParam = actual.IdControl, IdEmpresaParam = actual.IdEmpresa, FechaParam = actual.Fecha, // Datos originales
|
{
|
||||||
EntradaParam = actual.Entrada, SobrantesParam = actual.Sobrantes, DetalleParam = actual.Detalle, SinCargoParam = actual.SinCargo, // Valores ANTERIORES
|
IdControlParam = actual.IdControl,
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Actualizado"
|
IdEmpresaParam = actual.IdEmpresa,
|
||||||
|
FechaParam = actual.Fecha, // Datos originales
|
||||||
|
EntradaParam = actual.Entrada,
|
||||||
|
SobrantesParam = actual.Sobrantes,
|
||||||
|
DetalleParam = actual.Detalle,
|
||||||
|
SinCargoParam = actual.SinCargo, // Valores ANTERIORES
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Actualizado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, controlAActualizar, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, controlAActualizar, transaction);
|
||||||
@@ -149,14 +165,66 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
(Id_Control, Id_Empresa, Fecha, Entrada, Sobrantes, Detalle, SinCargo, Id_Usuario, FechaMod, TipoMod)
|
(Id_Control, Id_Empresa, Fecha, Entrada, Sobrantes, Detalle, SinCargo, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdControlParam, @IdEmpresaParam, @FechaParam, @EntradaParam, @SobrantesParam, @DetalleParam, @SinCargoParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdControlParam, @IdEmpresaParam, @FechaParam, @EntradaParam, @SobrantesParam, @DetalleParam, @SinCargoParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdControlParam = actual.IdControl, IdEmpresaParam = actual.IdEmpresa, FechaParam = actual.Fecha,
|
{
|
||||||
EntradaParam = actual.Entrada, SobrantesParam = actual.Sobrantes, DetalleParam = actual.Detalle, SinCargoParam = actual.SinCargo,
|
IdControlParam = actual.IdControl,
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Eliminado"
|
IdEmpresaParam = actual.IdEmpresa,
|
||||||
|
FechaParam = actual.Fecha,
|
||||||
|
EntradaParam = actual.Entrada,
|
||||||
|
SobrantesParam = actual.Sobrantes,
|
||||||
|
DetalleParam = actual.Detalle,
|
||||||
|
SinCargoParam = actual.SinCargo,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Eliminado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdControlParam = idControl }, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdControlParam = idControl }, transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(ControlDevolucionesHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idControlOriginal, int? idEmpresaOriginal, DateTime? fechaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Control, h.Id_Empresa, h.Fecha, h.Entrada, h.Sobrantes, h.Detalle, h.SinCargo,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_dtCtrlDevoluciones_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idControlOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Control = @IdControlOriginalParam"); parameters.Add("IdControlOriginalParam", idControlOriginal.Value); }
|
||||||
|
if (idEmpresaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Empresa = @IdEmpresaOriginalParam"); parameters.Add("IdEmpresaOriginalParam", idEmpresaOriginal.Value); }
|
||||||
|
if (fechaOriginal.HasValue) { sqlBuilder.Append(" AND h.Fecha = @FechaOriginalParam"); parameters.Add("FechaOriginalParam", fechaOriginal.Value.Date); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<ControlDevolucionesHistorico, string, (ControlDevolucionesHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Control de Devoluciones.");
|
||||||
|
return Enumerable.Empty<(ControlDevolucionesHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<CambioParadaCanilla?> CreateAsync(CambioParadaCanilla nuevaParada, int idUsuario, IDbTransaction transaction);
|
Task<CambioParadaCanilla?> CreateAsync(CambioParadaCanilla nuevaParada, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> UpdateVigenciaHAsync(int idRegistro, DateTime vigenciaH, int idUsuario, IDbTransaction transaction);
|
Task<bool> UpdateVigenciaHAsync(int idRegistro, DateTime vigenciaH, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(CambioParadaCanillaHistorial Historial, string NombreUsuarioModifico, string NombreCanilla)>> GetCambiosParadaHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idCanillaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -17,6 +17,6 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<IEnumerable<(CanillaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
Task<IEnumerable<(CanillaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
DateTime? fechaDesde, DateTime? fechaHasta,
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
int? idUsuarioModifico, string? tipoModificacion,
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
int? idCanillaOriginal); // Para filtrar por un canillita específico
|
int? idCanillaOriginal); // Para filtrar por un canillita específico
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<ControlDevoluciones?> CreateAsync(ControlDevoluciones nuevoControl, int idUsuario, IDbTransaction transaction);
|
Task<ControlDevoluciones?> CreateAsync(ControlDevoluciones nuevoControl, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> UpdateAsync(ControlDevoluciones controlAActualizar, int idUsuario, IDbTransaction transaction);
|
Task<bool> UpdateAsync(ControlDevoluciones controlAActualizar, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteAsync(int idControl, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int idControl, int idUsuario, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(ControlDevolucionesHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idControlOriginal, int? idEmpresaOriginal, DateTime? fechaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
||||||
Task<bool> IsInUseAsync(int id); // Verificar si se usa en dist_SalidasOtrosDestinos
|
Task<bool> IsInUseAsync(int id); // Verificar si se usa en dist_SalidasOtrosDestinos
|
||||||
|
Task<IEnumerable<(OtroDestinoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idOtroDestinoOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,5 +16,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<bool> DeleteAsync(int idPorcMon, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int idPorcMon, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||||
Task<PorcMonCanilla?> GetPreviousActiveAsync(int idPublicacion, int idCanilla, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
Task<PorcMonCanilla?> GetPreviousActiveAsync(int idPublicacion, int idCanilla, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(PorcMonCanillaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPorcMonOriginal, int? idPublicacionOriginal, int? idCanillaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -16,5 +16,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<bool> DeleteAsync(int idPorcentaje, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int idPorcentaje, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||||
Task<PorcPago?> GetPreviousActivePorcPagoAsync(int idPublicacion, int idDistribuidor, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
Task<PorcPago?> GetPreviousActivePorcPagoAsync(int idPublicacion, int idDistribuidor, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(PorcPagoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPorcentajeOriginal, int? idPublicacionOriginal, int? idDistribuidorOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -9,6 +9,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
{
|
{
|
||||||
Task<IEnumerable<Precio>> GetByPublicacionIdAsync(int idPublicacion);
|
Task<IEnumerable<Precio>> GetByPublicacionIdAsync(int idPublicacion);
|
||||||
Task<Precio?> GetByIdAsync(int idPrecio);
|
Task<Precio?> GetByIdAsync(int idPrecio);
|
||||||
|
Task<bool> IsInUseAsync(int idPrecio, DateTime vigenciaD, DateTime? vigenciaH);
|
||||||
Task<Precio?> GetActiveByPublicacionAndDateAsync(int idPublicacion, DateTime fecha, IDbTransaction? transaction = null);
|
Task<Precio?> GetActiveByPublicacionAndDateAsync(int idPublicacion, DateTime fecha, IDbTransaction? transaction = null);
|
||||||
Task<Precio?> CreateAsync(Precio nuevoPrecio, int idUsuario, IDbTransaction transaction);
|
Task<Precio?> CreateAsync(Precio nuevoPrecio, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> UpdateAsync(Precio precioAActualizar, int idUsuario, IDbTransaction transaction);
|
Task<bool> UpdateAsync(Precio precioAActualizar, int idUsuario, IDbTransaction transaction);
|
||||||
@@ -16,5 +17,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
// MODIFICADO: Añadir idUsuarioAuditoria
|
// MODIFICADO: Añadir idUsuarioAuditoria
|
||||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction);
|
||||||
Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(PrecioHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPrecioOriginal, int? idPublicacionOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,5 +15,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction); // Ya existe
|
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction); // Ya existe
|
||||||
Task<bool> ExistsByNameInPublicacionAsync(string nombre, int idPublicacion, int? excludeIdSeccion = null);
|
Task<bool> ExistsByNameInPublicacionAsync(string nombre, int idPublicacion, int? excludeIdSeccion = null);
|
||||||
Task<bool> IsInUseAsync(int idSeccion); // Verificar en bob_RegPublicaciones, bob_StockBobinas
|
Task<bool> IsInUseAsync(int idSeccion); // Verificar en bob_RegPublicaciones, bob_StockBobinas
|
||||||
|
Task<IEnumerable<(PubliSeccionHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idSeccionOriginal, int? idPublicacionOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,5 +18,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<IEnumerable<PublicacionDiaSemana>> GetConfiguracionDiasAsync(int idPublicacion);
|
Task<IEnumerable<PublicacionDiaSemana>> GetConfiguracionDiasAsync(int idPublicacion);
|
||||||
Task<IEnumerable<int>> GetPublicacionesIdsPorDiaSemanaAsync(byte diaSemana); // Devuelve solo IDs
|
Task<IEnumerable<int>> GetPublicacionesIdsPorDiaSemanaAsync(byte diaSemana); // Devuelve solo IDs
|
||||||
Task UpdateConfiguracionDiasAsync(int idPublicacion, IEnumerable<byte> diasActivos, IDbTransaction transaction);
|
Task UpdateConfiguracionDiasAsync(int idPublicacion, IEnumerable<byte> diasActivos, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(PublicacionHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPublicacionOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -10,11 +10,16 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
{
|
{
|
||||||
Task<IEnumerable<(RecargoZona Recargo, string NombreZona)>> GetByPublicacionIdAsync(int idPublicacion);
|
Task<IEnumerable<(RecargoZona Recargo, string NombreZona)>> GetByPublicacionIdAsync(int idPublicacion);
|
||||||
Task<RecargoZona?> GetByIdAsync(int idRecargo); // Para obtener un recargo específico
|
Task<RecargoZona?> GetByIdAsync(int idRecargo); // Para obtener un recargo específico
|
||||||
|
Task<bool> IsInUseAsync(int idRecargo, DateTime vigenciaD, DateTime? vigenciaH);
|
||||||
Task<RecargoZona?> GetActiveByPublicacionZonaAndDateAsync(int idPublicacion, int idZona, DateTime fecha, IDbTransaction? transaction = null);
|
Task<RecargoZona?> GetActiveByPublicacionZonaAndDateAsync(int idPublicacion, int idZona, DateTime fecha, IDbTransaction? transaction = null);
|
||||||
Task<RecargoZona?> CreateAsync(RecargoZona nuevoRecargo, int idUsuario, IDbTransaction transaction);
|
Task<RecargoZona?> CreateAsync(RecargoZona nuevoRecargo, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> UpdateAsync(RecargoZona recargoAActualizar, int idUsuario, IDbTransaction transaction);
|
Task<bool> UpdateAsync(RecargoZona recargoAActualizar, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteAsync(int idRecargo, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int idRecargo, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction); // Ya existe
|
Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction); // Ya existe
|
||||||
Task<RecargoZona?> GetPreviousActiveRecargoAsync(int idPublicacion, int idZona, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
Task<RecargoZona?> GetPreviousActiveRecargoAsync(int idPublicacion, int idZona, DateTime vigenciaDNuevo, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(RecargoZonaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idRecargoOriginal, int? idPublicacionOriginal, int? idZonaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,5 +13,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<bool> SoftDeleteAsync(int id, int idUsuario); // Cambiado de DeleteAsync a SoftDeleteAsync
|
Task<bool> SoftDeleteAsync(int id, int idUsuario); // Cambiado de DeleteAsync a SoftDeleteAsync
|
||||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null, bool soloActivas = true);
|
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null, bool soloActivas = true);
|
||||||
Task<bool> IsInUseAsync(int id);
|
Task<bool> IsInUseAsync(int id);
|
||||||
|
Task<IEnumerable<(ZonaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idZonaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,5 +185,47 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction);
|
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(OtroDestinoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idOtroDestinoOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Destino, h.Nombre, h.Obs,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_dtOtrosDestinos_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idOtroDestinoOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Destino = @IdOtroDestinoOriginalParam"); parameters.Add("IdOtroDestinoOriginalParam", idOtroDestinoOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<OtroDestinoHistorico, string, (OtroDestinoHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Otros Destinos (Maestro).");
|
||||||
|
return Enumerable.Empty<(OtroDestinoHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||||
@@ -63,7 +64,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.LogError(ex, "Error al obtener PorcMonCanilla por ID: {IdPorcMon}", idPorcMon);
|
_log.LogError(ex, "Error al obtener PorcMonCanilla por ID: {IdPorcMon}", idPorcMon);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -79,15 +80,15 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD <= @FechaParam
|
AND VigenciaD <= @FechaParam
|
||||||
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
|
|
||||||
var cn = transaction?.Connection ?? _cf.CreateConnection();
|
var cn = transaction?.Connection ?? _cf.CreateConnection();
|
||||||
bool ownConnection = transaction == null;
|
bool ownConnection = transaction == null;
|
||||||
PorcMonCanilla? result = null;
|
PorcMonCanilla? result = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync();
|
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync();
|
||||||
result = await cn.QuerySingleOrDefaultAsync<PorcMonCanilla>(sql,
|
result = await cn.QuerySingleOrDefaultAsync<PorcMonCanilla>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, IdCanillaParam = idCanilla, FechaParam = fecha.Date },
|
new { IdPublicacionParam = idPublicacion, IdCanillaParam = idCanilla, FechaParam = fecha.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
@@ -109,8 +110,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD < @VigenciaDNuevoParam
|
AND VigenciaD < @VigenciaDNuevoParam
|
||||||
AND VigenciaH IS NULL
|
AND VigenciaH IS NULL
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
return await transaction.Connection!.QuerySingleOrDefaultAsync<PorcMonCanilla>(sql,
|
return await transaction.Connection!.QuerySingleOrDefaultAsync<PorcMonCanilla>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, IdCanillaParam = idCanilla, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
new { IdPublicacionParam = idPublicacion, IdCanillaParam = idCanilla, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,12 +185,12 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PorcMonCanilla>(
|
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PorcMonCanilla>(
|
||||||
@"SELECT Id_PorcMon AS IdPorcMon, Id_Publicacion AS IdPublicacion, Id_Canilla AS IdCanilla,
|
@"SELECT Id_PorcMon AS IdPorcMon, Id_Publicacion AS IdPublicacion, Id_Canilla AS IdCanilla,
|
||||||
VigenciaD, VigenciaH, PorcMon, EsPorcentaje
|
VigenciaD, VigenciaH, PorcMon, EsPorcentaje
|
||||||
FROM dbo.dist_PorcMonPagoCanilla WHERE Id_PorcMon = @IdPorcMonParam",
|
FROM dbo.dist_PorcMonPagoCanilla WHERE Id_PorcMon = @IdPorcMonParam",
|
||||||
new { IdPorcMonParam = idPorcMon }, transaction);
|
new { IdPorcMonParam = idPorcMon }, transaction);
|
||||||
if (actual == null) throw new KeyNotFoundException("Registro PorcMonCanilla no encontrado para eliminar.");
|
if (actual == null) throw new KeyNotFoundException("Registro PorcMonCanilla no encontrado para eliminar.");
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.dist_PorcMonPagoCanilla WHERE Id_PorcMon = @IdPorcMonParam";
|
const string sqlDelete = "DELETE FROM dbo.dist_PorcMonPagoCanilla WHERE Id_PorcMon = @IdPorcMonParam";
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
INSERT INTO dbo.dist_PorcMonPagoCanilla_H (Id_PorcMon, Id_Publicacion, Id_Canilla, VigenciaD, VigenciaH, PorcMon, EsPorcentaje, Id_Usuario, FechaMod, TipoMod)
|
INSERT INTO dbo.dist_PorcMonPagoCanilla_H (Id_PorcMon, Id_Publicacion, Id_Canilla, VigenciaD, VigenciaH, PorcMon, EsPorcentaje, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdPorcMonParam, @IdPublicacionParam, @IdCanillaParam, @VigenciaDParam, @VigenciaHParam, @PorcMonParam, @EsPorcentajeParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdPorcMonParam, @IdPublicacionParam, @IdCanillaParam, @VigenciaDParam, @VigenciaHParam, @PorcMonParam, @EsPorcentajeParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
|
|
||||||
@@ -253,5 +254,50 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PorcMonCanillaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPorcMonOriginal, int? idPublicacionOriginal, int? idCanillaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_PorcMon, h.Id_Publicacion, h.Id_Canilla,
|
||||||
|
h.VigenciaD, h.VigenciaH, h.PorcMon, h.EsPorcentaje,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_PorcMonPagoCanilla_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPorcMonOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_PorcMon = @IdPorcMonOriginalParam"); parameters.Add("IdPorcMonOriginalParam", idPorcMonOriginal.Value); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
if (idCanillaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Canilla = @IdCanillaOriginalParam"); parameters.Add("IdCanillaOriginalParam", idCanillaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PorcMonCanillaHistorico, string, (PorcMonCanillaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Porcentajes/Montos Canillita.");
|
||||||
|
return Enumerable.Empty<(PorcMonCanillaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||||
@@ -67,7 +68,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<PorcPago?> GetActiveByPublicacionDistribuidorAndDateAsync(int idPublicacion, int idDistribuidor, DateTime fecha, IDbTransaction? transaction = null)
|
public async Task<PorcPago?> GetActiveByPublicacionDistribuidorAndDateAsync(int idPublicacion, int idDistribuidor, DateTime fecha, IDbTransaction? transaction = null)
|
||||||
{
|
{
|
||||||
const string sql = @"
|
const string sql = @"
|
||||||
@@ -79,7 +80,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD <= @FechaParam
|
AND VigenciaD <= @FechaParam
|
||||||
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
|
|
||||||
var cn = transaction?.Connection ?? _cf.CreateConnection();
|
var cn = transaction?.Connection ?? _cf.CreateConnection();
|
||||||
bool ownConnection = transaction == null;
|
bool ownConnection = transaction == null;
|
||||||
PorcPago? result = null;
|
PorcPago? result = null;
|
||||||
@@ -107,8 +108,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD < @VigenciaDNuevoParam
|
AND VigenciaD < @VigenciaDNuevoParam
|
||||||
AND VigenciaH IS NULL
|
AND VigenciaH IS NULL
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
return await transaction.Connection!.QuerySingleOrDefaultAsync<PorcPago>(sql,
|
return await transaction.Connection!.QuerySingleOrDefaultAsync<PorcPago>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, IdDistribuidorParam = idDistribuidor, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
new { IdPublicacionParam = idPublicacion, IdDistribuidorParam = idDistribuidor, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +155,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
UPDATE dbo.dist_PorcPago SET
|
UPDATE dbo.dist_PorcPago SET
|
||||||
Porcentaje = @Porcentaje, VigenciaH = @VigenciaH
|
Porcentaje = @Porcentaje, VigenciaH = @VigenciaH
|
||||||
WHERE Id_Porcentaje = @IdPorcentaje;";
|
WHERE Id_Porcentaje = @IdPorcentaje;";
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
INSERT INTO dbo.dist_PorcPago_H (Id_Porcentaje, Id_Publicacion, Id_Distribuidor, VigenciaD, VigenciaH, Porcentaje, Id_Usuario, FechaMod, TipoMod)
|
INSERT INTO dbo.dist_PorcPago_H (Id_Porcentaje, Id_Publicacion, Id_Distribuidor, VigenciaD, VigenciaH, Porcentaje, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdPorcentajeHist, @IdPublicacionHist, @IdDistribuidorHist, @VigenciaDHist, @VigenciaHHist, @PorcentajeHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
VALUES (@IdPorcentajeHist, @IdPublicacionHist, @IdDistribuidorHist, @VigenciaDHist, @VigenciaHHist, @PorcentajeHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||||
|
|
||||||
@@ -180,7 +181,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PorcPago>(
|
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PorcPago>(
|
||||||
@"SELECT Id_Porcentaje AS IdPorcentaje, Id_Publicacion AS IdPublicacion, Id_Distribuidor AS IdDistribuidor,
|
@"SELECT Id_Porcentaje AS IdPorcentaje, Id_Publicacion AS IdPublicacion, Id_Distribuidor AS IdDistribuidor,
|
||||||
VigenciaD, VigenciaH, Porcentaje
|
VigenciaD, VigenciaH, Porcentaje
|
||||||
FROM dbo.dist_PorcPago WHERE Id_Porcentaje = @IdPorcentajeParam",
|
FROM dbo.dist_PorcPago WHERE Id_Porcentaje = @IdPorcentajeParam",
|
||||||
new { IdPorcentajeParam = idPorcentaje }, transaction);
|
new { IdPorcentajeParam = idPorcentaje }, transaction);
|
||||||
if (actual == null) throw new KeyNotFoundException("Porcentaje de pago no encontrado para eliminar.");
|
if (actual == null) throw new KeyNotFoundException("Porcentaje de pago no encontrado para eliminar.");
|
||||||
|
|
||||||
@@ -247,5 +248,50 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PorcPagoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPorcentajeOriginal, int? idPublicacionOriginal, int? idDistribuidorOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Porcentaje, h.Id_Publicacion, h.Id_Distribuidor,
|
||||||
|
h.VigenciaD, h.VigenciaH, h.Porcentaje,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_PorcPago_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPorcentajeOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Porcentaje = @IdPorcentajeOriginalParam"); parameters.Add("IdPorcentajeOriginalParam", idPorcentajeOriginal.Value); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
if (idDistribuidorOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Distribuidor = @IdDistribuidorOriginalParam"); parameters.Add("IdDistribuidorOriginalParam", idDistribuidorOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PorcPagoHistorico, string, (PorcPagoHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Porcentajes de Pago (Distribuidores).");
|
||||||
|
return Enumerable.Empty<(PorcPagoHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||||
@@ -71,18 +72,18 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
WHERE Id_Publicacion = @IdPublicacionParam AND VigenciaD <= @FechaParam
|
WHERE Id_Publicacion = @IdPublicacionParam AND VigenciaD <= @FechaParam
|
||||||
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
|
|
||||||
var cn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
var cn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||||
bool ownConnection = transaction == null;
|
bool ownConnection = transaction == null;
|
||||||
Precio? result = null;
|
Precio? result = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn)
|
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn)
|
||||||
{
|
{
|
||||||
await dbConn.OpenAsync();
|
await dbConn.OpenAsync();
|
||||||
}
|
}
|
||||||
result = await cn.QuerySingleOrDefaultAsync<Precio>(sql,
|
result = await cn.QuerySingleOrDefaultAsync<Precio>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, FechaParam = fecha.Date },
|
new { IdPublicacionParam = idPublicacion, FechaParam = fecha.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -92,7 +93,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Open && cn is System.Data.Common.DbConnection dbConnClose)
|
if (ownConnection && cn.State == ConnectionState.Open && cn is System.Data.Common.DbConnection dbConnClose)
|
||||||
{
|
{
|
||||||
await dbConnClose.CloseAsync();
|
await dbConnClose.CloseAsync();
|
||||||
}
|
}
|
||||||
@@ -100,7 +101,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction)
|
public async Task<Precio?> GetPreviousActivePriceAsync(int idPublicacion, DateTime vigenciaDNuevo, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
const string sql = @"
|
const string sql = @"
|
||||||
@@ -112,8 +113,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD < @VigenciaDNuevoParam
|
AND VigenciaD < @VigenciaDNuevoParam
|
||||||
AND VigenciaH IS NULL
|
AND VigenciaH IS NULL
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
return await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(sql,
|
return await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
new { IdPublicacionParam = idPublicacion, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +125,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
OUTPUT INSERTED.Id_Precio AS IdPrecio, INSERTED.Id_Publicacion AS IdPublicacion, INSERTED.VigenciaD, INSERTED.VigenciaH,
|
OUTPUT INSERTED.Id_Precio AS IdPrecio, INSERTED.Id_Publicacion AS IdPublicacion, INSERTED.VigenciaD, INSERTED.VigenciaH,
|
||||||
INSERTED.Lunes, INSERTED.Martes, INSERTED.Miercoles, INSERTED.Jueves, INSERTED.Viernes, INSERTED.Sabado, INSERTED.Domingo
|
INSERTED.Lunes, INSERTED.Martes, INSERTED.Miercoles, INSERTED.Jueves, INSERTED.Viernes, INSERTED.Sabado, INSERTED.Domingo
|
||||||
VALUES (@IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo);";
|
VALUES (@IdPublicacion, @VigenciaD, @VigenciaH, @Lunes, @Martes, @Miercoles, @Jueves, @Viernes, @Sabado, @Domingo);";
|
||||||
var inserted = await transaction.Connection!.QuerySingleAsync<Precio>(sqlInsert, nuevoPrecio, transaction);
|
var inserted = await transaction.Connection!.QuerySingleAsync<Precio>(sqlInsert, nuevoPrecio, transaction);
|
||||||
if (inserted == null || inserted.IdPrecio == 0) throw new DataException("Error al crear precio o al obtener el ID generado.");
|
if (inserted == null || inserted.IdPrecio == 0) throw new DataException("Error al crear precio o al obtener el ID generado.");
|
||||||
|
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
@@ -134,14 +135,19 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdPrecioHist = inserted.IdPrecio,
|
IdPrecioHist = inserted.IdPrecio,
|
||||||
IdPublicacionHist = inserted.IdPublicacion,
|
IdPublicacionHist = inserted.IdPublicacion,
|
||||||
VigenciaDHist = inserted.VigenciaD,
|
VigenciaDHist = inserted.VigenciaD,
|
||||||
VigenciaHHist = inserted.VigenciaH,
|
VigenciaHHist = inserted.VigenciaH,
|
||||||
LunesHist = inserted.Lunes, MartesHist = inserted.Martes, MiercolesHist = inserted.Miercoles, JuevesHist = inserted.Jueves,
|
LunesHist = inserted.Lunes,
|
||||||
ViernesHist = inserted.Viernes, SabadoHist = inserted.Sabado, DomingoHist = inserted.Domingo,
|
MartesHist = inserted.Martes,
|
||||||
IdUsuarioHist = idUsuario,
|
MiercolesHist = inserted.Miercoles,
|
||||||
FechaModHist = DateTime.Now,
|
JuevesHist = inserted.Jueves,
|
||||||
|
ViernesHist = inserted.Viernes,
|
||||||
|
SabadoHist = inserted.Sabado,
|
||||||
|
DomingoHist = inserted.Domingo,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
TipoModHist = "Creado"
|
TipoModHist = "Creado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
return inserted;
|
return inserted;
|
||||||
@@ -160,22 +166,27 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
VigenciaH = @VigenciaH, Lunes = @Lunes, Martes = @Martes, Miercoles = @Miercoles,
|
VigenciaH = @VigenciaH, Lunes = @Lunes, Martes = @Martes, Miercoles = @Miercoles,
|
||||||
Jueves = @Jueves, Viernes = @Viernes, Sabado = @Sabado, Domingo = @Domingo
|
Jueves = @Jueves, Viernes = @Viernes, Sabado = @Sabado, Domingo = @Domingo
|
||||||
WHERE Id_Precio = @IdPrecio;";
|
WHERE Id_Precio = @IdPrecio;";
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
INSERT INTO dbo.dist_Precios_H
|
INSERT INTO dbo.dist_Precios_H
|
||||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdPrecioHist, @IdPublicacionHist, @VigenciaDHist, @VigenciaHHist, @LunesHist, @MartesHist, @MiercolesHist, @JuevesHist, @ViernesHist, @SabadoHist, @DomingoHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
VALUES (@IdPrecioHist, @IdPublicacionHist, @VigenciaDHist, @VigenciaHHist, @LunesHist, @MartesHist, @MiercolesHist, @JuevesHist, @ViernesHist, @SabadoHist, @DomingoHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdPrecioHist = actual.IdPrecio,
|
IdPrecioHist = actual.IdPrecio,
|
||||||
IdPublicacionHist = actual.IdPublicacion,
|
IdPublicacionHist = actual.IdPublicacion,
|
||||||
VigenciaDHist = actual.VigenciaD,
|
VigenciaDHist = actual.VigenciaD,
|
||||||
VigenciaHHist = actual.VigenciaH,
|
VigenciaHHist = actual.VigenciaH,
|
||||||
LunesHist = actual.Lunes, MartesHist = actual.Martes, MiercolesHist = actual.Miercoles, JuevesHist = actual.Jueves,
|
LunesHist = actual.Lunes,
|
||||||
ViernesHist = actual.Viernes, SabadoHist = actual.Sabado, DomingoHist = actual.Domingo,
|
MartesHist = actual.Martes,
|
||||||
IdUsuarioHist = idUsuario,
|
MiercolesHist = actual.Miercoles,
|
||||||
FechaModHist = DateTime.Now,
|
JuevesHist = actual.Jueves,
|
||||||
TipoModHist = "Actualizado"
|
ViernesHist = actual.Viernes,
|
||||||
|
SabadoHist = actual.Sabado,
|
||||||
|
DomingoHist = actual.Domingo,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
|
TipoModHist = "Actualizado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, precioAActualizar, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, precioAActualizar, transaction);
|
||||||
@@ -184,8 +195,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
public async Task<bool> DeleteAsync(int idPrecio, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteAsync(int idPrecio, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(
|
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<Precio>(
|
||||||
@"SELECT Id_Precio AS IdPrecio, Id_Publicacion AS IdPublicacion, VigenciaD, VigenciaH,
|
@"SELECT Id_Precio AS IdPrecio, Id_Publicacion AS IdPublicacion, VigenciaD, VigenciaH,
|
||||||
Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo
|
Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo
|
||||||
FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecioParam", new { IdPrecioParam = idPrecio }, transaction);
|
FROM dbo.dist_Precios WHERE Id_Precio = @IdPrecioParam", new { IdPrecioParam = idPrecio }, transaction);
|
||||||
if (actual == null) throw new KeyNotFoundException("Precio no encontrado para eliminar.");
|
if (actual == null) throw new KeyNotFoundException("Precio no encontrado para eliminar.");
|
||||||
@@ -198,14 +209,19 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdPrecioHist = actual.IdPrecio,
|
IdPrecioHist = actual.IdPrecio,
|
||||||
IdPublicacionHist = actual.IdPublicacion,
|
IdPublicacionHist = actual.IdPublicacion,
|
||||||
VigenciaDHist = actual.VigenciaD,
|
VigenciaDHist = actual.VigenciaD,
|
||||||
VigenciaHHist = actual.VigenciaH,
|
VigenciaHHist = actual.VigenciaH,
|
||||||
LunesHist = actual.Lunes, MartesHist = actual.Martes, MiercolesHist = actual.Miercoles, JuevesHist = actual.Jueves,
|
LunesHist = actual.Lunes,
|
||||||
ViernesHist = actual.Viernes, SabadoHist = actual.Sabado, DomingoHist = actual.Domingo,
|
MartesHist = actual.Martes,
|
||||||
IdUsuarioHist = idUsuario,
|
MiercolesHist = actual.Miercoles,
|
||||||
FechaModHist = DateTime.Now,
|
JuevesHist = actual.Jueves,
|
||||||
|
ViernesHist = actual.Viernes,
|
||||||
|
SabadoHist = actual.Sabado,
|
||||||
|
DomingoHist = actual.Domingo,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
TipoModHist = "Eliminado"
|
TipoModHist = "Eliminado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
@@ -214,7 +230,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
public async Task<bool> DeleteByPublicacionIdAsync(int idPublicacion, int idUsuarioAuditoria, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
const string selectSql = @"
|
const string selectSql = @"
|
||||||
SELECT
|
SELECT
|
||||||
Id_Precio AS IdPrecio, Id_Publicacion AS IdPublicacion, VigenciaD, VigenciaH,
|
Id_Precio AS IdPrecio, Id_Publicacion AS IdPublicacion, VigenciaD, VigenciaH,
|
||||||
@@ -228,19 +244,24 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
INSERT INTO dbo.dist_Precios_H
|
INSERT INTO dbo.dist_Precios_H
|
||||||
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
(Id_Precio, Id_Publicacion, VigenciaD, VigenciaH, Lunes, Martes, Miercoles, Jueves, Viernes, Sabado, Domingo, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdPrecioHist, @IdPublicacionHist, @VigenciaDHist, @VigenciaHHist, @LunesHist, @MartesHist, @MiercolesHist, @JuevesHist, @ViernesHist, @SabadoHist, @DomingoHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
VALUES (@IdPrecioHist, @IdPublicacionHist, @VigenciaDHist, @VigenciaHHist, @LunesHist, @MartesHist, @MiercolesHist, @JuevesHist, @ViernesHist, @SabadoHist, @DomingoHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||||
|
|
||||||
foreach (var item in itemsToDelete)
|
foreach (var item in itemsToDelete)
|
||||||
{
|
{
|
||||||
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
||||||
{
|
{
|
||||||
IdPrecioHist = item.IdPrecio,
|
IdPrecioHist = item.IdPrecio,
|
||||||
IdPublicacionHist = item.IdPublicacion,
|
IdPublicacionHist = item.IdPublicacion,
|
||||||
VigenciaDHist = item.VigenciaD,
|
VigenciaDHist = item.VigenciaD,
|
||||||
VigenciaHHist = item.VigenciaH,
|
VigenciaHHist = item.VigenciaH,
|
||||||
LunesHist = item.Lunes, MartesHist = item.Martes, MiercolesHist = item.Miercoles, JuevesHist = item.Jueves,
|
LunesHist = item.Lunes,
|
||||||
ViernesHist = item.Viernes, SabadoHist = item.Sabado, DomingoHist = item.Domingo,
|
MartesHist = item.Martes,
|
||||||
IdUsuarioHist = idUsuarioAuditoria,
|
MiercolesHist = item.Miercoles,
|
||||||
FechaModHist = DateTime.Now,
|
JuevesHist = item.Jueves,
|
||||||
|
ViernesHist = item.Viernes,
|
||||||
|
SabadoHist = item.Sabado,
|
||||||
|
DomingoHist = item.Domingo,
|
||||||
|
IdUsuarioHist = idUsuarioAuditoria,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
TipoModHist = "Eliminado (Cascada)"
|
TipoModHist = "Eliminado (Cascada)"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
}
|
}
|
||||||
@@ -257,5 +278,82 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IsInUseAsync(int idPrecio, DateTime vigenciaD, DateTime? vigenciaH)
|
||||||
|
{
|
||||||
|
// Verificar si el Id_Precio se usa en movimientos DENTRO del rango de vigencia del precio
|
||||||
|
// Si VigenciaH es NULL, significa que el precio está activo indefinidamente hacia el futuro.
|
||||||
|
var sql = @"
|
||||||
|
SELECT TOP 1 1
|
||||||
|
FROM (
|
||||||
|
SELECT Id_Precio, Fecha FROM dbo.dist_EntradasSalidas
|
||||||
|
UNION ALL
|
||||||
|
SELECT Id_Precio, Fecha FROM dbo.dist_EntradasSalidasCanillas
|
||||||
|
) AS Movimientos
|
||||||
|
WHERE Movimientos.Id_Precio = @IdPrecioParam
|
||||||
|
AND Movimientos.Fecha >= @VigenciaDParam
|
||||||
|
AND (@VigenciaHParam IS NULL OR Movimientos.Fecha <= @VigenciaHParam);";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var parameters = new
|
||||||
|
{
|
||||||
|
IdPrecioParam = idPrecio,
|
||||||
|
VigenciaDParam = vigenciaD.Date,
|
||||||
|
VigenciaHParam = vigenciaH?.Date
|
||||||
|
};
|
||||||
|
var inUse = await connection.ExecuteScalarAsync<int?>(sql, parameters);
|
||||||
|
return inUse.HasValue && inUse.Value == 1;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error en IsInUseAsync para Precio ID: {IdPrecio}", idPrecio);
|
||||||
|
return true; // Asumir en uso si hay error, para ser cauteloso
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PrecioHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPrecioOriginal, int? idPublicacionOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Precio, h.Id_Publicacion, h.VigenciaD, h.VigenciaH,
|
||||||
|
h.Lunes, h.Martes, h.Miercoles, h.Jueves, h.Viernes, h.Sabado, h.Domingo,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_Precios_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPrecioOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Precio = @IdPrecioOriginalParam"); parameters.Add("IdPrecioOriginalParam", idPrecioOriginal.Value); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PrecioHistorico, string, (PrecioHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Precios de Publicación.");
|
||||||
|
return Enumerable.Empty<(PrecioHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -28,7 +28,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Id_Seccion AS IdSeccion, Id_Publicacion AS IdPublicacion, Nombre, Estado
|
Id_Seccion AS IdSeccion, Id_Publicacion AS IdPublicacion, Nombre, Estado
|
||||||
FROM dbo.dist_dtPubliSecciones
|
FROM dbo.dist_dtPubliSecciones
|
||||||
WHERE Id_Publicacion = @IdPublicacionParam");
|
WHERE Id_Publicacion = @IdPublicacionParam");
|
||||||
|
|
||||||
if (soloActivas.HasValue)
|
if (soloActivas.HasValue)
|
||||||
{
|
{
|
||||||
sqlBuilder.Append(soloActivas.Value ? " AND Estado = 1" : " AND Estado = 0");
|
sqlBuilder.Append(soloActivas.Value ? " AND Estado = 1" : " AND Estado = 0");
|
||||||
@@ -97,7 +97,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
"SELECT TOP 1 1 FROM dbo.bob_RegPublicaciones WHERE Id_Seccion = @IdSeccionParam",
|
"SELECT TOP 1 1 FROM dbo.bob_RegPublicaciones WHERE Id_Seccion = @IdSeccionParam",
|
||||||
"SELECT TOP 1 1 FROM dbo.bob_StockBobinas WHERE Id_Seccion = @IdSeccionParam"
|
"SELECT TOP 1 1 FROM dbo.bob_StockBobinas WHERE Id_Seccion = @IdSeccionParam"
|
||||||
};
|
};
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
foreach (var query in checkQueries)
|
foreach (var query in checkQueries)
|
||||||
{
|
{
|
||||||
@@ -171,10 +171,10 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
public async Task<bool> DeleteAsync(int idSeccion, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteAsync(int idSeccion, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PubliSeccion>(
|
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<PubliSeccion>(
|
||||||
@"SELECT Id_Seccion AS IdSeccion, Id_Publicacion AS IdPublicacion, Nombre, Estado
|
@"SELECT Id_Seccion AS IdSeccion, Id_Publicacion AS IdPublicacion, Nombre, Estado
|
||||||
FROM dbo.dist_dtPubliSecciones WHERE Id_Seccion = @IdSeccionParam",
|
FROM dbo.dist_dtPubliSecciones WHERE Id_Seccion = @IdSeccionParam",
|
||||||
new { IdSeccionParam = idSeccion }, transaction);
|
new { IdSeccionParam = idSeccion }, transaction);
|
||||||
if (actual == null) throw new KeyNotFoundException("Sección no encontrada para eliminar.");
|
if (actual == null) throw new KeyNotFoundException("Sección no encontrada para eliminar.");
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.dist_dtPubliSecciones WHERE Id_Seccion = @IdSeccionParam";
|
const string sqlDelete = "DELETE FROM dbo.dist_dtPubliSecciones WHERE Id_Seccion = @IdSeccionParam";
|
||||||
@@ -235,5 +235,48 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PubliSeccionHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idSeccionOriginal, int? idPublicacionOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Seccion, h.Id_Publicacion, h.Nombre, h.Estado,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_dtPubliSecciones_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idSeccionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Seccion = @IdSeccionOriginalParam"); parameters.Add("IdSeccionOriginalParam", idSeccionOriginal.Value); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PubliSeccionHistorico, string, (PubliSeccionHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Secciones de Publicación.");
|
||||||
|
return Enumerable.Empty<(PubliSeccionHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -139,32 +139,33 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> IsInUseAsync(int id)
|
public async Task<bool> IsInUseAsync(int idPublicacion)
|
||||||
{
|
{
|
||||||
using var connection = _connectionFactory.CreateConnection();
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
string[] checkQueries = {
|
string[] checkQueries = {
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidas WHERE Id_Publicacion = @IdParam",
|
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidas WHERE Id_Publicacion = @IdParam",
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidasCanillas WHERE Id_Publicacion = @IdParam",
|
"SELECT TOP 1 1 FROM dbo.dist_EntradasSalidasCanillas WHERE Id_Publicacion = @IdParam",
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_Precios WHERE Id_Publicacion = @IdParam",
|
"SELECT TOP 1 1 FROM dbo.dist_SalidasOtrosDestinos WHERE Id_Publicacion = @IdParam",
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_RecargoZona WHERE Id_Publicacion = @IdParam",
|
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_PorcPago WHERE Id_Publicacion = @IdParam",
|
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_PorcMonPagoCanilla WHERE Id_Publicacion = @IdParam",
|
|
||||||
"SELECT TOP 1 1 FROM dbo.dist_dtPubliSecciones WHERE Id_Publicacion = @IdParam",
|
|
||||||
"SELECT TOP 1 1 FROM dbo.bob_RegPublicaciones WHERE Id_Publicacion = @IdParam",
|
"SELECT TOP 1 1 FROM dbo.bob_RegPublicaciones WHERE Id_Publicacion = @IdParam",
|
||||||
"SELECT TOP 1 1 FROM dbo.bob_StockBobinas WHERE Id_Publicacion = @IdParam"
|
"SELECT TOP 1 1 FROM dbo.bob_RegTiradas WHERE Id_Publicacion = @IdParam",
|
||||||
|
"SELECT TOP 1 1 FROM dbo.bob_StockBobinas WHERE Id_Publicacion = @IdParam AND Id_EstadoBobina != 1" // Ejemplo: si una bobina EN USO o DAÑADA está asociada
|
||||||
};
|
};
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
foreach (var query in checkQueries)
|
foreach (var query in checkQueries)
|
||||||
{
|
{
|
||||||
if (await connection.ExecuteScalarAsync<int?>(query, new { IdParam = id }) == 1) return true;
|
if (await connection.ExecuteScalarAsync<int?>(query, new { IdParam = idPublicacion }) == 1)
|
||||||
|
{
|
||||||
|
_logger.LogInformation("Publicacion ID {IdPublicacion} está en uso (Tabla: {Tabla})", idPublicacion, query.Split("FROM")[1].Split("WHERE")[0].Trim());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error en IsInUseAsync para Publicacion ID: {IdPublicacion}", id);
|
_logger.LogError(ex, "Error en IsInUseAsync para Publicacion ID: {IdPublicacion}", idPublicacion);
|
||||||
return true; // Asumir en uso si hay error de BD
|
return true; // Asumir en uso si hay error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +326,48 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
);
|
);
|
||||||
await Task.WhenAll(insertTasks);
|
await Task.WhenAll(insertTasks);
|
||||||
}
|
}
|
||||||
// No se necesita historial para esta tabla de configuración por ahora.
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PublicacionHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPublicacionOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection(); // Asumiendo _connectionFactory
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Publicacion, h.Nombre, h.Observacion, h.Id_Empresa, h.Habilitada,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_dtPublicaciones_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PublicacionHistorico, string, (PublicacionHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Publicaciones (Maestro)."); // Asumiendo _logger
|
||||||
|
return Enumerable.Empty<(PublicacionHistorico, string)>();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ using System;
|
|||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using System.Linq; // Necesario para .Any()
|
using System.Linq; // Necesario para .Any()
|
||||||
|
using System.Text;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||||
@@ -48,6 +49,39 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<bool> IsInUseAsync(int idRecargo, DateTime vigenciaD, DateTime? vigenciaH)
|
||||||
|
{
|
||||||
|
// Similar a Precios, verificar en dist_EntradasSalidas y dist_EntradasSalidasCanillas
|
||||||
|
// si Id_Recargo se usa en movimientos DENTRO del rango de vigencia del recargo.
|
||||||
|
var sql = @"
|
||||||
|
SELECT TOP 1 1
|
||||||
|
FROM (
|
||||||
|
SELECT Id_Recargo, Fecha FROM dbo.dist_EntradasSalidas
|
||||||
|
UNION ALL
|
||||||
|
SELECT Id_Recargo, Fecha FROM dbo.dist_EntradasSalidasCanillas
|
||||||
|
) AS Movimientos
|
||||||
|
WHERE Movimientos.Id_Recargo = @IdRecargoParam
|
||||||
|
AND Movimientos.Fecha >= @VigenciaDParam
|
||||||
|
AND (@VigenciaHParam IS NULL OR Movimientos.Fecha <= @VigenciaHParam);";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var parameters = new
|
||||||
|
{
|
||||||
|
IdRecargoParam = idRecargo,
|
||||||
|
VigenciaDParam = vigenciaD.Date,
|
||||||
|
VigenciaHParam = vigenciaH?.Date
|
||||||
|
};
|
||||||
|
var inUse = await connection.ExecuteScalarAsync<int?>(sql, parameters);
|
||||||
|
return inUse.HasValue && inUse.Value == 1;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error en IsInUseAsync para Recargo ID: {IdRecargo}", idRecargo);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async Task<RecargoZona?> GetByIdAsync(int idRecargo)
|
public async Task<RecargoZona?> GetByIdAsync(int idRecargo)
|
||||||
{
|
{
|
||||||
const string sql = @"
|
const string sql = @"
|
||||||
@@ -67,7 +101,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<RecargoZona?> GetActiveByPublicacionZonaAndDateAsync(int idPublicacion, int idZona, DateTime fecha, IDbTransaction? transaction = null)
|
public async Task<RecargoZona?> GetActiveByPublicacionZonaAndDateAsync(int idPublicacion, int idZona, DateTime fecha, IDbTransaction? transaction = null)
|
||||||
{
|
{
|
||||||
const string sql = @"
|
const string sql = @"
|
||||||
@@ -79,28 +113,28 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD <= @FechaParam
|
AND VigenciaD <= @FechaParam
|
||||||
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
AND (VigenciaH IS NULL OR VigenciaH >= @FechaParam)
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
|
|
||||||
var cn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
var cn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||||
bool ownConnection = transaction == null;
|
bool ownConnection = transaction == null;
|
||||||
RecargoZona? result = null;
|
RecargoZona? result = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn)
|
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn)
|
||||||
{
|
{
|
||||||
await dbConn.OpenAsync();
|
await dbConn.OpenAsync();
|
||||||
}
|
}
|
||||||
result = await cn.QuerySingleOrDefaultAsync<RecargoZona>(sql,
|
result = await cn.QuerySingleOrDefaultAsync<RecargoZona>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, IdZonaParam = idZona, FechaParam = fecha.Date },
|
new { IdPublicacionParam = idPublicacion, IdZonaParam = idZona, FechaParam = fecha.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_logger.LogError(ex, "Error en GetActiveByPublicacionZonaAndDateAsync. IdPublicacion: {IdPublicacion}, IdZona: {IdZona}, Fecha: {Fecha}", idPublicacion, idZona, fecha);
|
_logger.LogError(ex, "Error en GetActiveByPublicacionZonaAndDateAsync. IdPublicacion: {IdPublicacion}, IdZona: {IdZona}, Fecha: {Fecha}", idPublicacion, idZona, fecha);
|
||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Open && cn is System.Data.Common.DbConnection dbConnClose)
|
if (ownConnection && cn.State == ConnectionState.Open && cn is System.Data.Common.DbConnection dbConnClose)
|
||||||
{
|
{
|
||||||
await dbConnClose.CloseAsync();
|
await dbConnClose.CloseAsync();
|
||||||
}
|
}
|
||||||
@@ -120,8 +154,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
AND VigenciaD < @VigenciaDNuevoParam
|
AND VigenciaD < @VigenciaDNuevoParam
|
||||||
AND VigenciaH IS NULL
|
AND VigenciaH IS NULL
|
||||||
ORDER BY VigenciaD DESC;";
|
ORDER BY VigenciaD DESC;";
|
||||||
return await transaction.Connection!.QuerySingleOrDefaultAsync<RecargoZona>(sql,
|
return await transaction.Connection!.QuerySingleOrDefaultAsync<RecargoZona>(sql,
|
||||||
new { IdPublicacionParam = idPublicacion, IdZonaParam = idZona, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
new { IdPublicacionParam = idPublicacion, IdZonaParam = idZona, VigenciaDNuevoParam = vigenciaDNuevo.Date },
|
||||||
transaction);
|
transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,13 +175,13 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdRecargoParam = inserted.IdRecargo,
|
IdRecargoParam = inserted.IdRecargo,
|
||||||
IdPublicacionParam = inserted.IdPublicacion,
|
IdPublicacionParam = inserted.IdPublicacion,
|
||||||
IdZonaParam = inserted.IdZona,
|
IdZonaParam = inserted.IdZona,
|
||||||
VigenciaDParam = inserted.VigenciaD,
|
VigenciaDParam = inserted.VigenciaD,
|
||||||
VigenciaHParam = inserted.VigenciaH,
|
VigenciaHParam = inserted.VigenciaH,
|
||||||
ValorParam = inserted.Valor,
|
ValorParam = inserted.Valor,
|
||||||
Id_UsuarioParam = idUsuario,
|
Id_UsuarioParam = idUsuario,
|
||||||
FechaModParam = DateTime.Now,
|
FechaModParam = DateTime.Now,
|
||||||
TipoModParam = "Creado"
|
TipoModParam = "Creado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
@@ -176,9 +210,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
IdRecargoParam = actual.IdRecargo,
|
IdRecargoParam = actual.IdRecargo,
|
||||||
IdPublicacionParam = actual.IdPublicacion,
|
IdPublicacionParam = actual.IdPublicacion,
|
||||||
IdZonaParam = actual.IdZona,
|
IdZonaParam = actual.IdZona,
|
||||||
VigenciaDParam = actual.VigenciaD,
|
VigenciaDParam = actual.VigenciaD,
|
||||||
VigenciaHParam = actual.VigenciaH,
|
VigenciaHParam = actual.VigenciaH,
|
||||||
ValorParam = actual.Valor,
|
ValorParam = actual.Valor,
|
||||||
Id_UsuarioParam = idUsuario,
|
Id_UsuarioParam = idUsuario,
|
||||||
FechaModParam = DateTime.Now,
|
FechaModParam = DateTime.Now,
|
||||||
TipoModParam = "Actualizado"
|
TipoModParam = "Actualizado"
|
||||||
@@ -236,14 +270,14 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
{
|
{
|
||||||
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
await transaction.Connection!.ExecuteAsync(insertHistoricoSql, new
|
||||||
{
|
{
|
||||||
IdRecargoParam = item.IdRecargo,
|
IdRecargoParam = item.IdRecargo,
|
||||||
IdPublicacionParam = item.IdPublicacion,
|
IdPublicacionParam = item.IdPublicacion,
|
||||||
IdZonaParam = item.IdZona,
|
IdZonaParam = item.IdZona,
|
||||||
VigenciaDParam = item.VigenciaD,
|
VigenciaDParam = item.VigenciaD,
|
||||||
VigenciaHParam = item.VigenciaH,
|
VigenciaHParam = item.VigenciaH,
|
||||||
ValorParam = item.Valor,
|
ValorParam = item.Valor,
|
||||||
Id_UsuarioParam = idUsuarioAuditoria,
|
Id_UsuarioParam = idUsuarioAuditoria,
|
||||||
FechaModParam = DateTime.Now,
|
FechaModParam = DateTime.Now,
|
||||||
TipoModParam = "Eliminado (Cascada)"
|
TipoModParam = "Eliminado (Cascada)"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
}
|
}
|
||||||
@@ -260,5 +294,49 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(RecargoZonaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idRecargoOriginal, int? idPublicacionOriginal, int? idZonaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Recargo, h.Id_Publicacion, h.Id_Zona, h.VigenciaD, h.VigenciaH, h.Valor,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_RecargoZona_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idRecargoOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Recargo = @IdRecargoOriginalParam"); parameters.Add("IdRecargoOriginalParam", idRecargoOriginal.Value); }
|
||||||
|
if (idPublicacionOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionOriginalParam"); parameters.Add("IdPublicacionOriginalParam", idPublicacionOriginal.Value); }
|
||||||
|
if (idZonaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Zona = @IdZonaOriginalParam"); parameters.Add("IdZonaOriginalParam", idZonaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<RecargoZonaHistorico, string, (RecargoZonaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Recargos por Zona.");
|
||||||
|
return Enumerable.Empty<(RecargoZonaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -259,7 +259,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
TipoMod = "Eliminada" // O "Deshabilitada"
|
TipoMod = "Eliminada" // O "Deshabilitada"
|
||||||
}, transaction: transaction);
|
}, transaction: transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
transaction.Commit();
|
transaction.Commit();
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
@@ -301,5 +301,46 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
return true; // Asumir que está en uso si hay error
|
return true; // Asumir que está en uso si hay error
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public async Task<IEnumerable<(ZonaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idZonaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Zona, h.Nombre, h.Descripcion, h.Estado,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.dist_dtZonas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idZonaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Zona = @IdZonaOriginalParam"); parameters.Add("IdZonaOriginalParam", idZonaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<ZonaHistorico, string, (ZonaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Zonas (Maestro).");
|
||||||
|
return Enumerable.Empty<(ZonaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -204,5 +204,47 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(EstadoBobinaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idEstadoBobinaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_EstadoBobina, h.Denominacion, h.Obs,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.bob_dtEstadosBobinas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idEstadoBobinaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_EstadoBobina = @IdEstadoBobinaOriginalParam"); parameters.Add("IdEstadoBobinaOriginalParam", idEstadoBobinaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<EstadoBobinaHistorico, string, (EstadoBobinaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Estados de Bobina.");
|
||||||
|
return Enumerable.Empty<(EstadoBobinaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> ExistsByDenominacionAsync(string denominacion, int? excludeId = null);
|
Task<bool> ExistsByDenominacionAsync(string denominacion, int? excludeId = null);
|
||||||
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas
|
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas
|
||||||
|
Task<IEnumerable<(EstadoBobinaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idEstadoBobinaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction); // Borrado físico con historial
|
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction); // Borrado físico con historial
|
||||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
||||||
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas o bob_RegPublicaciones
|
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas o bob_RegPublicaciones
|
||||||
|
Task<IEnumerable<(PlantaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPlantaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,15 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction); // Si se borra el registro principal
|
Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction); // Si se borra el registro principal
|
||||||
Task<bool> DeleteByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, int idUsuario, IDbTransaction transaction);
|
||||||
Task<RegTirada?> GetByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, IDbTransaction? transaction = null);
|
Task<RegTirada?> GetByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, IDbTransaction? transaction = null);
|
||||||
|
Task<IEnumerable<(RegTiradaHistorico Historial, string NombreUsuarioModifico, string NombrePublicacion, string NombrePlanta)>> GetRegTiradasHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idRegistroOriginal, int? idPublicacionFiltro, int? idPlantaFiltro, DateTime? fechaTiradaFiltro);
|
||||||
|
Task<IEnumerable<(RegPublicacionSeccionHistorico Historial, string NombreUsuarioModifico, string NombrePublicacion, string NombreSeccion, string NombrePlanta)>> GetRegSeccionesTiradaHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idTiradaOriginal, // ID del registro en bob_RegPublicaciones
|
||||||
|
int? idPublicacionFiltro, int? idSeccionFiltro, int? idPlantaFiltro, DateTime? fechaTiradaFiltro);
|
||||||
}
|
}
|
||||||
|
|
||||||
public interface IRegPublicacionSeccionRepository // Para bob_RegPublicaciones
|
public interface IRegPublicacionSeccionRepository // Para bob_RegPublicaciones
|
||||||
|
|||||||
@@ -22,5 +22,9 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Task<StockBobina?> CreateAsync(StockBobina nuevaBobina, int idUsuario, IDbTransaction transaction);
|
Task<StockBobina?> CreateAsync(StockBobina nuevaBobina, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> UpdateAsync(StockBobina bobinaAActualizar, int idUsuario, IDbTransaction transaction, string tipoMod = "Actualizada"); // tipoMod para historial
|
Task<bool> UpdateAsync(StockBobina bobinaAActualizar, int idUsuario, IDbTransaction transaction, string tipoMod = "Actualizada"); // tipoMod para historial
|
||||||
Task<bool> DeleteAsync(int idBobina, int idUsuario, IDbTransaction transaction); // Solo si está en estado "Disponible"
|
Task<bool> DeleteAsync(int idBobina, int idUsuario, IDbTransaction transaction); // Solo si está en estado "Disponible"
|
||||||
|
Task<IEnumerable<(StockBobinaHistorico Historial, string NombreUsuarioModifico, string? NombreTipoBobina, string? NombrePlanta, string? NombreEstadoBobina, string? NombrePublicacion, string? NombreSeccion)>> GetHistorialDetalladoAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idBobinaOriginal, int? idTipoBobinaFiltro, int? idPlantaFiltro, int? idEstadoBobinaFiltro);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,5 +14,9 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction);
|
||||||
Task<bool> ExistsByDenominacionAsync(string denominacion, int? excludeId = null);
|
Task<bool> ExistsByDenominacionAsync(string denominacion, int? excludeId = null);
|
||||||
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas
|
Task<bool> IsInUseAsync(int id); // Verificar si se usa en bob_StockBobinas
|
||||||
|
Task<IEnumerable<(TipoBobinaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idTipoBobinaOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -154,7 +154,7 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
public async Task<bool> UpdateAsync(Planta plantaAActualizar, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> UpdateAsync(Planta plantaAActualizar, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
// El servicio ya verificó que existe. Obtener estado actual para historial dentro de la transacción.
|
// El servicio ya verificó que existe. Obtener estado actual para historial dentro de la transacción.
|
||||||
var connection = transaction.Connection!;
|
var connection = transaction.Connection!;
|
||||||
var plantaActual = await connection.QuerySingleOrDefaultAsync<Planta>(
|
var plantaActual = await connection.QuerySingleOrDefaultAsync<Planta>(
|
||||||
"SELECT Id_Planta AS IdPlanta, Nombre, Detalle FROM dbo.bob_dtPlantas WHERE Id_Planta = @Id",
|
"SELECT Id_Planta AS IdPlanta, Nombre, Detalle FROM dbo.bob_dtPlantas WHERE Id_Planta = @Id",
|
||||||
@@ -225,5 +225,47 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PlantaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPlantaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Planta, h.Nombre, h.Detalle,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.bob_dtPlantas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPlantaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Planta = @IdPlantaOriginalParam"); parameters.Add("IdPlantaOriginalParam", idPlantaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PlantaHistorico, string, (PlantaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Plantas de Impresión.");
|
||||||
|
return Enumerable.Empty<(PlantaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync();
|
if (ownConnection && cn.State == ConnectionState.Closed && cn is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync();
|
||||||
result = await cn.QuerySingleOrDefaultAsync<RegTirada>(sql, new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
result = await cn.QuerySingleOrDefaultAsync<RegTirada>(sql, new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
||||||
}
|
}
|
||||||
finally
|
finally
|
||||||
{
|
{
|
||||||
@@ -69,55 +69,178 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdRegistroParam = inserted.IdRegistro, EjemplaresParam = inserted.Ejemplares, IdPublicacionParam = inserted.IdPublicacion, FechaParam = inserted.Fecha, IdPlantaParam = inserted.IdPlanta,
|
{
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Creado"
|
IdRegistroParam = inserted.IdRegistro,
|
||||||
|
EjemplaresParam = inserted.Ejemplares,
|
||||||
|
IdPublicacionParam = inserted.IdPublicacion,
|
||||||
|
FechaParam = inserted.Fecha,
|
||||||
|
IdPlantaParam = inserted.IdPlanta,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Creado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteAsync(int idRegistro, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
var actual = await GetByIdAsync(idRegistro); // No necesita TX aquí ya que es solo para historial
|
var actual = await GetByIdAsync(idRegistro); // No necesita TX aquí ya que es solo para historial
|
||||||
if (actual == null) throw new KeyNotFoundException("Registro de tirada no encontrado.");
|
if (actual == null) throw new KeyNotFoundException("Registro de tirada no encontrado.");
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.bob_RegTiradas WHERE Id_Registro = @IdRegistroParam";
|
const string sqlDelete = "DELETE FROM dbo.bob_RegTiradas WHERE Id_Registro = @IdRegistroParam";
|
||||||
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdRegistroParam = actual.IdRegistro, EjemplaresParam = actual.Ejemplares, IdPublicacionParam = actual.IdPublicacion, FechaParam = actual.Fecha, IdPlantaParam = actual.IdPlanta,
|
{
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Eliminado"
|
IdRegistroParam = actual.IdRegistro,
|
||||||
|
EjemplaresParam = actual.Ejemplares,
|
||||||
|
IdPublicacionParam = actual.IdPublicacion,
|
||||||
|
FechaParam = actual.Fecha,
|
||||||
|
IdPlantaParam = actual.IdPlanta,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Eliminado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdRegistroParam = idRegistro }, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdRegistroParam = idRegistro }, transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
public async Task<bool> DeleteByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
var tiradasAEliminar = await GetByCriteriaAsync(fecha.Date, idPublicacion, idPlanta); // Obtener antes de borrar para historial
|
var tiradasAEliminar = await GetByCriteriaAsync(fecha.Date, idPublicacion, idPlanta); // Obtener antes de borrar para historial
|
||||||
|
|
||||||
foreach(var actual in tiradasAEliminar)
|
foreach (var actual in tiradasAEliminar)
|
||||||
{
|
{
|
||||||
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
const string sqlHistorico = @"INSERT INTO dbo.bob_RegTiradas_H (Id_Registro, Ejemplares, Id_Publicacion, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdRegistroParam, @EjemplaresParam, @IdPublicacionParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdRegistroParam = actual.IdRegistro, EjemplaresParam = actual.Ejemplares, IdPublicacionParam = actual.IdPublicacion, FechaParam = actual.Fecha, IdPlantaParam = actual.IdPlanta,
|
{
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Eliminado (Por Fecha/Pub/Planta)"
|
IdRegistroParam = actual.IdRegistro,
|
||||||
|
EjemplaresParam = actual.Ejemplares,
|
||||||
|
IdPublicacionParam = actual.IdPublicacion,
|
||||||
|
FechaParam = actual.Fecha,
|
||||||
|
IdPlantaParam = actual.IdPlanta,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Eliminado (Por Fecha/Pub/Planta)"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.bob_RegTiradas WHERE Fecha = @FechaParam AND Id_Publicacion = @IdPublicacionParam AND Id_Planta = @IdPlantaParam";
|
const string sqlDelete = "DELETE FROM dbo.bob_RegTiradas WHERE Fecha = @FechaParam AND Id_Publicacion = @IdPublicacionParam AND Id_Planta = @IdPlantaParam";
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete,
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete,
|
||||||
new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
||||||
return rowsAffected > 0; // Devuelve true si se borró al menos una fila
|
return rowsAffected > 0; // Devuelve true si se borró al menos una fila
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(RegTiradaHistorico Historial, string NombreUsuarioModifico, string NombrePublicacion, string NombrePlanta)>> GetRegTiradasHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idRegistroOriginal, int? idPublicacionFiltro, int? idPlantaFiltro, DateTime? fechaTiradaFiltro)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Registro, h.Ejemplares, h.Id_Publicacion, h.Fecha, h.Id_Planta,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico,
|
||||||
|
pub.Nombre AS NombrePublicacion,
|
||||||
|
p.Nombre AS NombrePlanta
|
||||||
|
FROM dbo.bob_RegTiradas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
JOIN dbo.dist_dtPublicaciones pub ON h.Id_Publicacion = pub.Id_Publicacion
|
||||||
|
JOIN dbo.bob_dtPlantas p ON h.Id_Planta = p.Id_Planta
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idRegistroOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Registro = @IdRegistroOriginalParam"); parameters.Add("IdRegistroOriginalParam", idRegistroOriginal.Value); }
|
||||||
|
if (idPublicacionFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionFiltroParam"); parameters.Add("IdPublicacionFiltroParam", idPublicacionFiltro.Value); }
|
||||||
|
if (idPlantaFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Planta = @IdPlantaFiltroParam"); parameters.Add("IdPlantaFiltroParam", idPlantaFiltro.Value); }
|
||||||
|
if (fechaTiradaFiltro.HasValue) { sqlBuilder.Append(" AND h.Fecha = @FechaTiradaFiltroParam"); parameters.Add("FechaTiradaFiltroParam", fechaTiradaFiltro.Value.Date); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<RegTiradaHistorico, string, string, string, (RegTiradaHistorico, string, string, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userMod, pubNombre, plantaNombre) => (hist, userMod, pubNombre, plantaNombre),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico,NombrePublicacion,NombrePlanta"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Registro de Tiradas.");
|
||||||
|
return Enumerable.Empty<(RegTiradaHistorico, string, string, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(RegPublicacionSeccionHistorico Historial, string NombreUsuarioModifico, string NombrePublicacion, string NombreSeccion, string NombrePlanta)>> GetRegSeccionesTiradaHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idTiradaOriginal, int? idPublicacionFiltro, int? idSeccionFiltro, int? idPlantaFiltro, DateTime? fechaTiradaFiltro)
|
||||||
|
{
|
||||||
|
using var connection = _cf.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Tirada, h.Id_Publicacion, h.Id_Seccion, h.CantPag, h.Fecha, h.Id_Planta,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico,
|
||||||
|
pub.Nombre AS NombrePublicacion,
|
||||||
|
sec.Nombre AS NombreSeccion,
|
||||||
|
p.Nombre AS NombrePlanta
|
||||||
|
FROM dbo.bob_RegPublicaciones_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
JOIN dbo.dist_dtPublicaciones pub ON h.Id_Publicacion = pub.Id_Publicacion
|
||||||
|
JOIN dbo.dist_dtPubliSecciones sec ON h.Id_Seccion = sec.Id_Seccion
|
||||||
|
AND h.Id_Publicacion = sec.Id_Publicacion -- Crucial para el JOIN correcto de sección
|
||||||
|
JOIN dbo.bob_dtPlantas p ON h.Id_Planta = p.Id_Planta
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idTiradaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Tirada = @IdTiradaOriginalParam"); parameters.Add("IdTiradaOriginalParam", idTiradaOriginal.Value); }
|
||||||
|
if (idPublicacionFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Publicacion = @IdPublicacionFiltroParam"); parameters.Add("IdPublicacionFiltroParam", idPublicacionFiltro.Value); }
|
||||||
|
if (idSeccionFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Seccion = @IdSeccionFiltroParam"); parameters.Add("IdSeccionFiltroParam", idSeccionFiltro.Value); }
|
||||||
|
if (idPlantaFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Planta = @IdPlantaFiltroParam"); parameters.Add("IdPlantaFiltroParam", idPlantaFiltro.Value); }
|
||||||
|
if (fechaTiradaFiltro.HasValue) { sqlBuilder.Append(" AND h.Fecha = @FechaTiradaFiltroParam"); parameters.Add("FechaTiradaFiltroParam", fechaTiradaFiltro.Value.Date); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<RegPublicacionSeccionHistorico, string, string, string, string, (RegPublicacionSeccionHistorico, string, string, string, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userMod, pubNombre, secNombre, plantaNombre) => (hist, userMod, pubNombre, secNombre, plantaNombre),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico,NombrePublicacion,NombreSeccion,NombrePlanta"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogError(ex, "Error al obtener historial de Secciones de Tirada.");
|
||||||
|
return Enumerable.Empty<(RegPublicacionSeccionHistorico, string, string, string, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class RegPublicacionSeccionRepository : IRegPublicacionSeccionRepository
|
public class RegPublicacionSeccionRepository : IRegPublicacionSeccionRepository
|
||||||
{
|
{
|
||||||
private readonly DbConnectionFactory _cf;
|
private readonly DbConnectionFactory _cf;
|
||||||
private readonly ILogger<RegPublicacionSeccionRepository> _log;
|
private readonly ILogger<RegPublicacionSeccionRepository> _log;
|
||||||
public RegPublicacionSeccionRepository(DbConnectionFactory cf, ILogger<RegPublicacionSeccionRepository> log){ _cf = cf; _log = log; }
|
public RegPublicacionSeccionRepository(DbConnectionFactory cf, ILogger<RegPublicacionSeccionRepository> log) { _cf = cf; _log = log; }
|
||||||
|
|
||||||
public async Task<IEnumerable<RegPublicacionSeccion>> GetByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta)
|
public async Task<IEnumerable<RegPublicacionSeccion>> GetByFechaPublicacionPlantaAsync(DateTime fecha, int idPublicacion, int idPlanta)
|
||||||
{
|
{
|
||||||
@@ -138,9 +261,17 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
const string sqlHistorico = @"INSERT INTO dbo.bob_RegPublicaciones_H (Id_Tirada, Id_Publicacion, Id_Seccion, CantPag, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
const string sqlHistorico = @"INSERT INTO dbo.bob_RegPublicaciones_H (Id_Tirada, Id_Publicacion, Id_Seccion, CantPag, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdTiradaParam, @IdPublicacionParam, @IdSeccionParam, @CantPagParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdTiradaParam, @IdPublicacionParam, @IdSeccionParam, @CantPagParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdTiradaParam = inserted.IdTirada, IdPublicacionParam = inserted.IdPublicacion, IdSeccionParam = inserted.IdSeccion, CantPagParam = inserted.CantPag, FechaParam = inserted.Fecha, IdPlantaParam = inserted.IdPlanta,
|
{
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Creado"
|
IdTiradaParam = inserted.IdTirada,
|
||||||
|
IdPublicacionParam = inserted.IdPublicacion,
|
||||||
|
IdSeccionParam = inserted.IdSeccion,
|
||||||
|
CantPagParam = inserted.CantPag,
|
||||||
|
FechaParam = inserted.Fecha,
|
||||||
|
IdPlantaParam = inserted.IdPlanta,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Creado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
@@ -149,18 +280,26 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
{
|
{
|
||||||
var seccionesAEliminar = await GetByFechaPublicacionPlantaAsync(fecha.Date, idPublicacion, idPlanta); // No necesita TX, es SELECT
|
var seccionesAEliminar = await GetByFechaPublicacionPlantaAsync(fecha.Date, idPublicacion, idPlanta); // No necesita TX, es SELECT
|
||||||
|
|
||||||
foreach(var actual in seccionesAEliminar)
|
foreach (var actual in seccionesAEliminar)
|
||||||
{
|
{
|
||||||
const string sqlHistorico = @"INSERT INTO dbo.bob_RegPublicaciones_H (Id_Tirada, Id_Publicacion, Id_Seccion, CantPag, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
const string sqlHistorico = @"INSERT INTO dbo.bob_RegPublicaciones_H (Id_Tirada, Id_Publicacion, Id_Seccion, CantPag, Fecha, Id_Planta, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdTiradaParam, @IdPublicacionParam, @IdSeccionParam, @CantPagParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
VALUES (@IdTiradaParam, @IdPublicacionParam, @IdSeccionParam, @CantPagParam, @FechaParam, @IdPlantaParam, @IdUsuarioParam, @FechaModParam, @TipoModParam);";
|
||||||
await transaction.Connection!.ExecuteAsync(sqlHistorico, new {
|
await transaction.Connection!.ExecuteAsync(sqlHistorico, new
|
||||||
IdTiradaParam = actual.IdTirada, IdPublicacionParam = actual.IdPublicacion, IdSeccionParam = actual.IdSeccion, CantPagParam = actual.CantPag, FechaParam = actual.Fecha, IdPlantaParam = actual.IdPlanta,
|
{
|
||||||
IdUsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Eliminado (Por Fecha/Pub/Planta)"
|
IdTiradaParam = actual.IdTirada,
|
||||||
|
IdPublicacionParam = actual.IdPublicacion,
|
||||||
|
IdSeccionParam = actual.IdSeccion,
|
||||||
|
CantPagParam = actual.CantPag,
|
||||||
|
FechaParam = actual.Fecha,
|
||||||
|
IdPlantaParam = actual.IdPlanta,
|
||||||
|
IdUsuarioParam = idUsuario,
|
||||||
|
FechaModParam = DateTime.Now,
|
||||||
|
TipoModParam = "Eliminado (Por Fecha/Pub/Planta)"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
}
|
}
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.bob_RegPublicaciones WHERE Fecha = @FechaParam AND Id_Publicacion = @IdPublicacionParam AND Id_Planta = @IdPlantaParam";
|
const string sqlDelete = "DELETE FROM dbo.bob_RegPublicaciones WHERE Fecha = @FechaParam AND Id_Publicacion = @IdPublicacionParam AND Id_Planta = @IdPlantaParam";
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete,
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete,
|
||||||
new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
new { FechaParam = fecha.Date, IdPublicacionParam = idPublicacion, IdPlantaParam = idPlanta }, transaction);
|
||||||
return rowsAffected >= 0; // Devuelve true incluso si no había nada que borrar (para que no falle la TX si es parte de una cadena)
|
return rowsAffected >= 0; // Devuelve true incluso si no había nada que borrar (para que no falle la TX si es parte de una cadena)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
INSERTED.Id_Planta AS IdPlanta, INSERTED.Id_EstadoBobina AS IdEstadoBobina, INSERTED.Remito, INSERTED.FechaRemito,
|
INSERTED.Id_Planta AS IdPlanta, INSERTED.Id_EstadoBobina AS IdEstadoBobina, INSERTED.Remito, INSERTED.FechaRemito,
|
||||||
INSERTED.FechaEstado, INSERTED.Id_Publicacion AS IdPublicacion, INSERTED.Id_Seccion AS IdSeccion, INSERTED.Obs
|
INSERTED.FechaEstado, INSERTED.Id_Publicacion AS IdPublicacion, INSERTED.Id_Seccion AS IdSeccion, INSERTED.Obs
|
||||||
VALUES (@IdTipoBobina, @NroBobina, @Peso, @IdPlanta, @IdEstadoBobina, @Remito, @FechaRemito, @FechaEstado, @IdPublicacion, @IdSeccion, @Obs);";
|
VALUES (@IdTipoBobina, @NroBobina, @Peso, @IdPlanta, @IdEstadoBobina, @Remito, @FechaRemito, @FechaEstado, @IdPublicacion, @IdSeccion, @Obs);";
|
||||||
|
|
||||||
var inserted = await transaction.Connection!.QuerySingleAsync<StockBobina>(sqlInsert, nuevaBobina, transaction);
|
var inserted = await transaction.Connection!.QuerySingleAsync<StockBobina>(sqlInsert, nuevaBobina, transaction);
|
||||||
if (inserted == null || inserted.IdBobina == 0) throw new DataException("Error al ingresar bobina o ID no generado.");
|
if (inserted == null || inserted.IdBobina == 0) throw new DataException("Error al ingresar bobina o ID no generado.");
|
||||||
|
|
||||||
@@ -147,10 +147,21 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdBobinaHist = inserted.IdBobina, IdTipoBobinaHist = inserted.IdTipoBobina, NroBobinaHist = inserted.NroBobina, PesoHist = inserted.Peso,
|
IdBobinaHist = inserted.IdBobina,
|
||||||
IdPlantaHist = inserted.IdPlanta, IdEstadoBobinaHist = inserted.IdEstadoBobina, RemitoHist = inserted.Remito, FechaRemitoHist = inserted.FechaRemito,
|
IdTipoBobinaHist = inserted.IdTipoBobina,
|
||||||
FechaEstadoHist = inserted.FechaEstado, IdPublicacionHist = inserted.IdPublicacion, IdSeccionHist = inserted.IdSeccion, ObsHist = inserted.Obs,
|
NroBobinaHist = inserted.NroBobina,
|
||||||
IdUsuarioHist = idUsuario, FechaModHist = DateTime.Now, TipoModHist = "Ingreso"
|
PesoHist = inserted.Peso,
|
||||||
|
IdPlantaHist = inserted.IdPlanta,
|
||||||
|
IdEstadoBobinaHist = inserted.IdEstadoBobina,
|
||||||
|
RemitoHist = inserted.Remito,
|
||||||
|
FechaRemitoHist = inserted.FechaRemito,
|
||||||
|
FechaEstadoHist = inserted.FechaEstado,
|
||||||
|
IdPublicacionHist = inserted.IdPublicacion,
|
||||||
|
IdSeccionHist = inserted.IdSeccion,
|
||||||
|
ObsHist = inserted.Obs,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
|
TipoModHist = "Ingreso"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
return inserted;
|
return inserted;
|
||||||
}
|
}
|
||||||
@@ -172,7 +183,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
Id_EstadoBobina = @IdEstadoBobina, Remito = @Remito, FechaRemito = @FechaRemito, FechaEstado = @FechaEstado,
|
Id_EstadoBobina = @IdEstadoBobina, Remito = @Remito, FechaRemito = @FechaRemito, FechaEstado = @FechaEstado,
|
||||||
Id_Publicacion = @IdPublicacion, Id_Seccion = @IdSeccion, Obs = @Obs
|
Id_Publicacion = @IdPublicacion, Id_Seccion = @IdSeccion, Obs = @Obs
|
||||||
WHERE Id_Bobina = @IdBobina;";
|
WHERE Id_Bobina = @IdBobina;";
|
||||||
|
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
INSERT INTO dbo.bob_StockBobinas_H
|
INSERT INTO dbo.bob_StockBobinas_H
|
||||||
(Id_Bobina, Id_TipoBobina, NroBobina, Peso, Id_Planta, Id_EstadoBobina, Remito, FechaRemito, FechaEstado, Id_Publicacion, Id_Seccion, Obs, Id_Usuario, FechaMod, TipoMod)
|
(Id_Bobina, Id_TipoBobina, NroBobina, Peso, Id_Planta, Id_EstadoBobina, Remito, FechaRemito, FechaEstado, Id_Publicacion, Id_Seccion, Obs, Id_Usuario, FechaMod, TipoMod)
|
||||||
@@ -180,10 +191,21 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||||
{
|
{
|
||||||
IdBobinaHist = actual.IdBobina, IdTipoBobinaHist = actual.IdTipoBobina, NroBobinaHist = actual.NroBobina, PesoHist = actual.Peso,
|
IdBobinaHist = actual.IdBobina,
|
||||||
IdPlantaHist = actual.IdPlanta, IdEstadoBobinaHist = actual.IdEstadoBobina, RemitoHist = actual.Remito, FechaRemitoHist = actual.FechaRemito,
|
IdTipoBobinaHist = actual.IdTipoBobina,
|
||||||
FechaEstadoHist = actual.FechaEstado, IdPublicacionHist = actual.IdPublicacion, IdSeccionHist = actual.IdSeccion, ObsHist = actual.Obs,
|
NroBobinaHist = actual.NroBobina,
|
||||||
IdUsuarioHist = idUsuario, FechaModHist = DateTime.Now, TipoModHist = tipoMod // "Actualizada" o "Estado Cambiado"
|
PesoHist = actual.Peso,
|
||||||
|
IdPlantaHist = actual.IdPlanta,
|
||||||
|
IdEstadoBobinaHist = actual.IdEstadoBobina,
|
||||||
|
RemitoHist = actual.Remito,
|
||||||
|
FechaRemitoHist = actual.FechaRemito,
|
||||||
|
FechaEstadoHist = actual.FechaEstado,
|
||||||
|
IdPublicacionHist = actual.IdPublicacion,
|
||||||
|
IdSeccionHist = actual.IdSeccion,
|
||||||
|
ObsHist = actual.Obs,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
|
TipoModHist = tipoMod // "Actualizada" o "Estado Cambiado"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, bobinaAActualizar, transaction);
|
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, bobinaAActualizar, transaction);
|
||||||
@@ -192,41 +214,109 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
|||||||
|
|
||||||
public async Task<bool> DeleteAsync(int idBobina, int idUsuario, IDbTransaction transaction)
|
public async Task<bool> DeleteAsync(int idBobina, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
// Normalmente, una bobina en stock no se "elimina" físicamente si ya tuvo movimientos.
|
var connection = transaction.Connection!; // Asegurar que la conexión no es null
|
||||||
// Este método sería para borrar un ingreso erróneo que aún esté "Disponible".
|
var actual = await connection.QuerySingleOrDefaultAsync<StockBobina>(
|
||||||
var actual = await transaction.Connection!.QuerySingleOrDefaultAsync<StockBobina>(
|
|
||||||
@"SELECT Id_Bobina AS IdBobina, Id_TipoBobina AS IdTipoBobina, NroBobina, Peso,
|
@"SELECT Id_Bobina AS IdBobina, Id_TipoBobina AS IdTipoBobina, NroBobina, Peso,
|
||||||
Id_Planta AS IdPlanta, Id_EstadoBobina AS IdEstadoBobina, Remito, FechaRemito,
|
Id_Planta AS IdPlanta, Id_EstadoBobina AS IdEstadoBobina, Remito, FechaRemito,
|
||||||
FechaEstado, Id_Publicacion AS IdPublicacion, Id_Seccion AS IdSeccion, Obs
|
FechaEstado, Id_Publicacion AS IdPublicacion, Id_Seccion AS IdSeccion, Obs
|
||||||
FROM dbo.bob_StockBobinas WHERE Id_Bobina = @IdBobinaParam",
|
FROM dbo.bob_StockBobinas WHERE Id_Bobina = @IdBobinaParam",
|
||||||
new { IdBobinaParam = idBobina }, transaction);
|
new { IdBobinaParam = idBobina }, transaction);
|
||||||
|
|
||||||
if (actual == null) throw new KeyNotFoundException("Bobina no encontrada para eliminar.");
|
if (actual == null) throw new KeyNotFoundException("Bobina no encontrada para eliminar.");
|
||||||
|
|
||||||
// VALIDACIÓN IMPORTANTE: Solo permitir borrar si está en estado "Disponible" (o el que se defina)
|
// --- INICIO DE CAMBIO EN VALIDACIÓN ---
|
||||||
if (actual.IdEstadoBobina != 1) // Asumiendo 1 = Disponible
|
// Permitir eliminar si está Disponible (1) o Dañada (3)
|
||||||
|
if (actual.IdEstadoBobina != 1 && actual.IdEstadoBobina != 3)
|
||||||
{
|
{
|
||||||
_logger.LogWarning("Intento de eliminar bobina {IdBobina} que no está en estado 'Disponible'. Estado actual: {EstadoActual}", idBobina, actual.IdEstadoBobina);
|
_logger.LogWarning("Intento de eliminar bobina {IdBobina} que no está en estado 'Disponible' o 'Dañada'. Estado actual: {EstadoActual}", idBobina, actual.IdEstadoBobina);
|
||||||
// No lanzar excepción para que la transacción no falle si es una validación de negocio
|
return false; // Devolver false si no cumple la condición para ser eliminada
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
// --- FIN DE CAMBIO EN VALIDACIÓN ---
|
||||||
|
|
||||||
const string sqlDelete = "DELETE FROM dbo.bob_StockBobinas WHERE Id_Bobina = @IdBobinaParam";
|
const string sqlDelete = "DELETE FROM dbo.bob_StockBobinas WHERE Id_Bobina = @IdBobinaParam";
|
||||||
const string sqlInsertHistorico = @"
|
const string sqlInsertHistorico = @"
|
||||||
INSERT INTO dbo.bob_StockBobinas_H
|
INSERT INTO dbo.bob_StockBobinas_H
|
||||||
(Id_Bobina, Id_TipoBobina, NroBobina, Peso, Id_Planta, Id_EstadoBobina, Remito, FechaRemito, FechaEstado, Id_Publicacion, Id_Seccion, Obs, Id_Usuario, FechaMod, TipoMod)
|
(Id_Bobina, Id_TipoBobina, NroBobina, Peso, Id_Planta, Id_EstadoBobina, Remito, FechaRemito, FechaEstado, Id_Publicacion, Id_Seccion, Obs, Id_Usuario, FechaMod, TipoMod)
|
||||||
VALUES (@IdBobinaHist, @IdTipoBobinaHist, @NroBobinaHist, @PesoHist, @IdPlantaHist, @IdEstadoBobinaHist, @RemitoHist, @FechaRemitoHist, @FechaEstadoHist, @IdPublicacionHist, @IdSeccionHist, @ObsHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
VALUES (@IdBobinaHist, @IdTipoBobinaHist, @NroBobinaHist, @PesoHist, @IdPlantaHist, @IdEstadoBobinaHist, @RemitoHist, @FechaRemitoHist, @FechaEstadoHist, @IdPublicacionHist, @IdSeccionHist, @ObsHist, @IdUsuarioHist, @FechaModHist, @TipoModHist);";
|
||||||
|
|
||||||
|
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
|
||||||
{
|
{
|
||||||
IdBobinaHist = actual.IdBobina, IdTipoBobinaHist = actual.IdTipoBobina, NroBobinaHist = actual.NroBobina, PesoHist = actual.Peso,
|
IdBobinaHist = actual.IdBobina,
|
||||||
IdPlantaHist = actual.IdPlanta, IdEstadoBobinaHist = actual.IdEstadoBobina, RemitoHist = actual.Remito, FechaRemitoHist = actual.FechaRemito,
|
IdTipoBobinaHist = actual.IdTipoBobina,
|
||||||
FechaEstadoHist = actual.FechaEstado, IdPublicacionHist = actual.IdPublicacion, IdSeccionHist = actual.IdSeccion, ObsHist = actual.Obs,
|
NroBobinaHist = actual.NroBobina,
|
||||||
IdUsuarioHist = idUsuario, FechaModHist = DateTime.Now, TipoModHist = "Eliminada"
|
PesoHist = actual.Peso,
|
||||||
|
IdPlantaHist = actual.IdPlanta,
|
||||||
|
IdEstadoBobinaHist = actual.IdEstadoBobina,
|
||||||
|
RemitoHist = actual.Remito,
|
||||||
|
FechaRemitoHist = actual.FechaRemito,
|
||||||
|
FechaEstadoHist = actual.FechaEstado,
|
||||||
|
IdPublicacionHist = actual.IdPublicacion,
|
||||||
|
IdSeccionHist = actual.IdSeccion,
|
||||||
|
ObsHist = actual.Obs,
|
||||||
|
IdUsuarioHist = idUsuario,
|
||||||
|
FechaModHist = DateTime.Now,
|
||||||
|
TipoModHist = "Eliminada"
|
||||||
}, transaction);
|
}, transaction);
|
||||||
|
|
||||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlDelete, new { IdBobinaParam = idBobina }, transaction);
|
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { IdBobinaParam = idBobina }, transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(StockBobinaHistorico Historial, string NombreUsuarioModifico, string? NombreTipoBobina, string? NombrePlanta, string? NombreEstadoBobina, string? NombrePublicacion, string? NombreSeccion)>> GetHistorialDetalladoAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idBobinaOriginal, int? idTipoBobinaFiltro, int? idPlantaFiltro, int? idEstadoBobinaFiltro)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_Bobina, h.Id_TipoBobina, h.NroBobina, h.Peso, h.Id_Planta, h.Id_EstadoBobina,
|
||||||
|
h.Remito, h.FechaRemito, h.FechaEstado, h.Id_Publicacion, h.Id_Seccion, h.Obs,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico,
|
||||||
|
tb.Denominacion AS NombreTipoBobina,
|
||||||
|
p.Nombre AS NombrePlanta,
|
||||||
|
eb.Denominacion AS NombreEstadoBobina,
|
||||||
|
pub.Nombre AS NombrePublicacion,
|
||||||
|
sec.Nombre AS NombreSeccion
|
||||||
|
FROM dbo.bob_StockBobinas_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
LEFT JOIN dbo.bob_dtBobinas tb ON h.Id_TipoBobina = tb.Id_TipoBobina
|
||||||
|
LEFT JOIN dbo.bob_dtPlantas p ON h.Id_Planta = p.Id_Planta
|
||||||
|
LEFT JOIN dbo.bob_dtEstadosBobinas eb ON h.Id_EstadoBobina = eb.Id_EstadoBobina
|
||||||
|
LEFT JOIN dbo.dist_dtPublicaciones pub ON h.Id_Publicacion = pub.Id_Publicacion
|
||||||
|
LEFT JOIN dbo.dist_dtPubliSecciones sec ON h.Id_Seccion = sec.Id_Seccion
|
||||||
|
AND h.Id_Publicacion = sec.Id_Publicacion -- Asegurar que la sección pertenezca a la publicación
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idBobinaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_Bobina = @IdBobinaOriginalParam"); parameters.Add("IdBobinaOriginalParam", idBobinaOriginal.Value); }
|
||||||
|
if (idTipoBobinaFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_TipoBobina = @IdTipoBobinaFiltroParam"); parameters.Add("IdTipoBobinaFiltroParam", idTipoBobinaFiltro.Value); }
|
||||||
|
if (idPlantaFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_Planta = @IdPlantaFiltroParam"); parameters.Add("IdPlantaFiltroParam", idPlantaFiltro.Value); }
|
||||||
|
if (idEstadoBobinaFiltro.HasValue) { sqlBuilder.Append(" AND h.Id_EstadoBobina = @IdEstadoBobinaFiltroParam"); parameters.Add("IdEstadoBobinaFiltroParam", idEstadoBobinaFiltro.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<StockBobinaHistorico, string, string, string, string, string, string, (StockBobinaHistorico, string, string?, string?, string?, string?, string?)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userMod, tipoBob, planta, estadoBob, pub, secc) => (hist, userMod, tipoBob, planta, estadoBob, pub, secc),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico,NombreTipoBobina,NombrePlanta,NombreEstadoBobina,NombrePublicacion,NombreSeccion"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial detallado de Stock de Bobinas.");
|
||||||
|
return Enumerable.Empty<(StockBobinaHistorico, string, string?, string?, string?, string?, string?)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -101,8 +101,6 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Métodos de Escritura (USAN TRANSACCIÓN) ---
|
|
||||||
|
|
||||||
public async Task<TipoBobina?> CreateAsync(TipoBobina nuevoTipoBobina, int idUsuario, IDbTransaction transaction)
|
public async Task<TipoBobina?> CreateAsync(TipoBobina nuevoTipoBobina, int idUsuario, IDbTransaction transaction)
|
||||||
{
|
{
|
||||||
const string sqlInsert = @"
|
const string sqlInsert = @"
|
||||||
@@ -199,5 +197,47 @@ namespace GestionIntegral.Api.Data.Repositories.Impresion
|
|||||||
|
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(TipoBobinaHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idTipoBobinaOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.Id_TipoBobina, h.Denominacion,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.bob_dtBobinas_H h -- Nombre de tabla de historial correcto
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idTipoBobinaOriginal.HasValue) { sqlBuilder.Append(" AND h.Id_TipoBobina = @IdTipoBobinaOriginalParam"); parameters.Add("IdTipoBobinaOriginalParam", idTipoBobinaOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<TipoBobinaHistorico, string, (TipoBobinaHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Tipos de Bobina.");
|
||||||
|
return Enumerable.Empty<(TipoBobinaHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,5 +16,14 @@ namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
|||||||
Task<bool> IsInUseAsync(int id);
|
Task<bool> IsInUseAsync(int id);
|
||||||
Task<IEnumerable<int>> GetPermisoIdsByPerfilIdAsync(int idPerfil);
|
Task<IEnumerable<int>> GetPermisoIdsByPerfilIdAsync(int idPerfil);
|
||||||
Task UpdatePermisosByPerfilIdAsync(int idPerfil, IEnumerable<int> nuevosPermisosIds, IDbTransaction transaction);
|
Task UpdatePermisosByPerfilIdAsync(int idPerfil, IEnumerable<int> nuevosPermisosIds, IDbTransaction transaction);
|
||||||
|
Task LogPermisoAsignacionHistorialAsync(int idPerfil, int idPermiso, int idUsuario, string tipoMod, IDbTransaction transaction);
|
||||||
|
Task<IEnumerable<(PerfilHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPerfilOriginal);
|
||||||
|
Task<IEnumerable<(PermisosPerfilesHistorico Historial, string NombreUsuarioModifico, string NombrePerfil, string DescPermiso, string CodAccPermiso)>> GetPermisosAsignadosHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPerfilAfectado, int? idPermisoAfectado);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,5 +15,9 @@ namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
|||||||
Task<bool> ExistsByCodAccAsync(string codAcc, int? excludeId = null);
|
Task<bool> ExistsByCodAccAsync(string codAcc, int? excludeId = null);
|
||||||
Task<bool> IsInUseAsync(int id);
|
Task<bool> IsInUseAsync(int id);
|
||||||
Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids);
|
Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids);
|
||||||
|
Task<IEnumerable<(PermisoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPermisoOriginal);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -240,11 +240,112 @@ namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
|||||||
var permisosParaInsertar = nuevosPermisosIds.Select(idPermiso => new { IdPerfil = idPerfil, IdPermiso = idPermiso });
|
var permisosParaInsertar = nuevosPermisosIds.Select(idPermiso => new { IdPerfil = idPerfil, IdPermiso = idPermiso });
|
||||||
await connection.ExecuteAsync(sqlInsert, permisosParaInsertar, transaction: transaction);
|
await connection.ExecuteAsync(sqlInsert, permisosParaInsertar, transaction: transaction);
|
||||||
}
|
}
|
||||||
// No hay tabla _H para gral_PermisosPerfiles directamente en este diseño.
|
}
|
||||||
// La auditoría de qué usuario cambió los permisos de un perfil se podría registrar
|
|
||||||
// en una tabla de log de acciones más general si fuera necesario, o deducir
|
public async Task LogPermisoAsignacionHistorialAsync(int idPerfil, int idPermiso, int idUsuario, string tipoMod, IDbTransaction transaction)
|
||||||
// indirectamente si la interfaz de usuario solo permite a SuperAdmin hacer esto.
|
{
|
||||||
|
const string sql = @"
|
||||||
|
INSERT INTO dbo.gral_PermisosPerfiles_H (idPerfil, idPermiso, Id_Usuario, FechaMod, TipoMod)
|
||||||
|
VALUES (@IdPerfil, @IdPermiso, @IdUsuario, @FechaMod, @TipoMod);";
|
||||||
|
|
||||||
|
await transaction.Connection!.ExecuteAsync(sql, new
|
||||||
|
{
|
||||||
|
IdPerfil = idPerfil,
|
||||||
|
IdPermiso = idPermiso,
|
||||||
|
IdUsuario = idUsuario,
|
||||||
|
FechaMod = DateTime.Now,
|
||||||
|
TipoMod = tipoMod
|
||||||
|
}, transaction: transaction);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PerfilHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPerfilOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.idPerfil, h.perfil, h.descPerfil, -- Campos de gral_Perfiles_H
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.gral_Perfiles_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPerfilOriginal.HasValue) { sqlBuilder.Append(" AND h.idPerfil = @IdPerfilOriginalParam"); parameters.Add("IdPerfilOriginalParam", idPerfilOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PerfilHistorico, string, (PerfilHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Perfiles.");
|
||||||
|
return Enumerable.Empty<(PerfilHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PermisosPerfilesHistorico Historial, string NombreUsuarioModifico, string NombrePerfil, string DescPermiso, string CodAccPermiso)>> GetPermisosAsignadosHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPerfilAfectado, int? idPermisoAfectado)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.IdHist, h.idPerfil, h.idPermiso,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico,
|
||||||
|
pf.perfil AS NombrePerfil,
|
||||||
|
p.descPermiso AS DescPermiso,
|
||||||
|
p.codAcc AS CodAccPermiso
|
||||||
|
FROM dbo.gral_PermisosPerfiles_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
JOIN dbo.gral_Perfiles pf ON h.idPerfil = pf.id
|
||||||
|
JOIN dbo.gral_Permisos p ON h.idPermiso = p.id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPerfilAfectado.HasValue) { sqlBuilder.Append(" AND h.idPerfil = @IdPerfilAfectadoParam"); parameters.Add("IdPerfilAfectadoParam", idPerfilAfectado.Value); }
|
||||||
|
if (idPermisoAfectado.HasValue) { sqlBuilder.Append(" AND h.idPermiso = @IdPermisoAfectadoParam"); parameters.Add("IdPermisoAfectadoParam", idPermisoAfectado.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PermisosPerfilesHistorico, string, string, string, string, (PermisosPerfilesHistorico, string, string, string, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userMod, perf, desc, cod) => (hist, userMod, perf, desc, cod),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico,NombrePerfil,DescPermiso,CodAccPermiso"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Asignación de Permisos.");
|
||||||
|
return Enumerable.Empty<(PermisosPerfilesHistorico, string, string, string, string)>();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -104,7 +104,7 @@ namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids)
|
public async Task<IEnumerable<Permiso>> GetPermisosByIdsAsync(IEnumerable<int> ids)
|
||||||
{
|
{
|
||||||
if (ids == null || !ids.Any())
|
if (ids == null || !ids.Any())
|
||||||
@@ -227,5 +227,47 @@ namespace GestionIntegral.Api.Data.Repositories.Usuarios
|
|||||||
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction: transaction);
|
var rowsAffected = await connection.ExecuteAsync(sqlDelete, new { Id = id }, transaction: transaction);
|
||||||
return rowsAffected == 1;
|
return rowsAffected == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<(PermisoHistorico Historial, string NombreUsuarioModifico)>> GetHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPermisoOriginal)
|
||||||
|
{
|
||||||
|
using var connection = _connectionFactory.CreateConnection();
|
||||||
|
var sqlBuilder = new StringBuilder(@"
|
||||||
|
SELECT
|
||||||
|
h.IdHist, h.idPermiso, h.modulo, h.descPermiso, h.codAcc,
|
||||||
|
h.Id_Usuario, h.FechaMod, h.TipoMod,
|
||||||
|
u.Nombre + ' ' + u.Apellido AS NombreUsuarioModifico
|
||||||
|
FROM dbo.gral_Permisos_H h
|
||||||
|
JOIN dbo.gral_Usuarios u ON h.Id_Usuario = u.Id
|
||||||
|
WHERE 1=1");
|
||||||
|
|
||||||
|
var parameters = new DynamicParameters();
|
||||||
|
|
||||||
|
if (fechaDesde.HasValue) { sqlBuilder.Append(" AND h.FechaMod >= @FechaDesdeParam"); parameters.Add("FechaDesdeParam", fechaDesde.Value.Date); }
|
||||||
|
if (fechaHasta.HasValue) { sqlBuilder.Append(" AND h.FechaMod <= @FechaHastaParam"); parameters.Add("FechaHastaParam", fechaHasta.Value.Date.AddDays(1).AddTicks(-1)); }
|
||||||
|
if (idUsuarioModifico.HasValue) { sqlBuilder.Append(" AND h.Id_Usuario = @IdUsuarioModificoParam"); parameters.Add("IdUsuarioModificoParam", idUsuarioModifico.Value); }
|
||||||
|
if (!string.IsNullOrWhiteSpace(tipoModificacion)) { sqlBuilder.Append(" AND h.TipoMod = @TipoModParam"); parameters.Add("TipoModParam", tipoModificacion); }
|
||||||
|
if (idPermisoOriginal.HasValue) { sqlBuilder.Append(" AND h.idPermiso = @IdPermisoOriginalParam"); parameters.Add("IdPermisoOriginalParam", idPermisoOriginal.Value); }
|
||||||
|
|
||||||
|
sqlBuilder.Append(" ORDER BY h.FechaMod DESC;");
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await connection.QueryAsync<PermisoHistorico, string, (PermisoHistorico, string)>(
|
||||||
|
sqlBuilder.ToString(),
|
||||||
|
(hist, userName) => (hist, userName),
|
||||||
|
parameters,
|
||||||
|
splitOn: "NombreUsuarioModifico"
|
||||||
|
);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_logger.LogError(ex, "Error al obtener historial de Permisos (Maestro).");
|
||||||
|
return Enumerable.Empty<(PermisoHistorico, string)>();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class ControlDevolucionesHistorico // Corresponde a dist_dtCtrlDevoluciones_H
|
public class ControlDevolucionesHistorico // Corresponde a dist_dtCtrlDevoluciones_H
|
||||||
{
|
{
|
||||||
// No hay PK explícita en _H
|
public int Id_Control { get; set; } // ID del ControlDevoluciones original
|
||||||
public int Id_Control { get; set; } // Coincide con columna en _H
|
|
||||||
public int Id_Empresa { get; set; }
|
public int Id_Empresa { get; set; }
|
||||||
public DateTime Fecha { get; set; }
|
public DateTime Fecha { get; set; }
|
||||||
public int Entrada { get; set; }
|
public int Entrada { get; set; }
|
||||||
|
|||||||
@@ -1,19 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class OtroDestinoHistorico
|
public class OtroDestinoHistorico // Corresponde a dist_dtOtrosDestinos_H
|
||||||
{
|
{
|
||||||
// Columna: Id_Destino (int, FK)
|
public int Id_Destino { get; set; } // ID del OtroDestino original
|
||||||
public int IdDestino { get; set; }
|
|
||||||
|
|
||||||
// Columna: Nombre (varchar(100), NOT NULL)
|
|
||||||
public string Nombre { get; set; } = string.Empty;
|
public string Nombre { get; set; } = string.Empty;
|
||||||
|
|
||||||
// Columna: Obs (varchar(250), NULL)
|
|
||||||
public string? Obs { get; set; }
|
public string? Obs { get; set; }
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
// Columnas de Auditoría
|
|
||||||
public int IdUsuario { get; set; }
|
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2,9 +2,9 @@ using System;
|
|||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class PorcMonCanillaHistorico
|
public class PorcMonCanillaHistorico // Corresponde a dist_PorcMonPagoCanilla_H
|
||||||
{
|
{
|
||||||
public int Id_PorcMon { get; set; } // Coincide con la columna
|
public int Id_PorcMon { get; set; } // ID del PorcMon original
|
||||||
public int Id_Publicacion { get; set; }
|
public int Id_Publicacion { get; set; }
|
||||||
public int Id_Canilla { get; set; }
|
public int Id_Canilla { get; set; }
|
||||||
public DateTime VigenciaD { get; set; }
|
public DateTime VigenciaD { get; set; }
|
||||||
|
|||||||
@@ -1,15 +1,16 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class PorcPagoHistorico
|
public class PorcPagoHistorico // Corresponde a dist_PorcPago_H
|
||||||
{
|
{
|
||||||
public int IdPorcentaje { get; set; } // Id_Porcentaje
|
public int Id_Porcentaje { get; set; } // ID del PorcPago original
|
||||||
public int IdPublicacion { get; set; }
|
public int Id_Publicacion { get; set; }
|
||||||
public int IdDistribuidor { get; set; }
|
public int Id_Distribuidor { get; set; }
|
||||||
public DateTime VigenciaD { get; set; }
|
public DateTime VigenciaD { get; set; } // smalldatetime en BD, DateTime en C# está bien
|
||||||
public DateTime? VigenciaH { get; set; }
|
public DateTime? VigenciaH { get; set; }
|
||||||
public decimal Porcentaje { get; set; }
|
public decimal Porcentaje { get; set; }
|
||||||
public int IdUsuario { get; set; } // Coincide con Id_Usuario en la tabla _H
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class PrecioHistorico
|
public class PrecioHistorico // Corresponde a dist_Precios_H
|
||||||
{
|
{
|
||||||
public int IdPrecio { get; set; } // FK a dist_Precios.Id_Precio
|
public int Id_Precio { get; set; } // ID del Precio original
|
||||||
public int IdPublicacion { get; set; }
|
public int Id_Publicacion { get; set; }
|
||||||
public DateTime VigenciaD { get; set; }
|
public DateTime VigenciaD { get; set; }
|
||||||
public DateTime? VigenciaH { get; set; }
|
public DateTime? VigenciaH { get; set; }
|
||||||
public decimal? Lunes { get; set; }
|
public decimal? Lunes { get; set; }
|
||||||
@@ -13,8 +15,6 @@ namespace GestionIntegral.Api.Models.Distribucion
|
|||||||
public decimal? Viernes { get; set; }
|
public decimal? Viernes { get; set; }
|
||||||
public decimal? Sabado { get; set; }
|
public decimal? Sabado { get; set; }
|
||||||
public decimal? Domingo { get; set; }
|
public decimal? Domingo { get; set; }
|
||||||
|
|
||||||
// Campos de Auditoría
|
|
||||||
public int Id_Usuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
|||||||
@@ -2,10 +2,10 @@ using System;
|
|||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class PubliSeccionHistorico
|
public class PubliSeccionHistorico // Corresponde a dist_dtPubliSecciones_H
|
||||||
{
|
{
|
||||||
public int Id_Seccion { get; set; } // Coincide con la columna
|
public int Id_Seccion { get; set; } // ID de la Sección original
|
||||||
public int Id_Publicacion { get; set; }
|
public int Id_Publicacion { get; set; } // A qué publicación pertenecía en ese momento
|
||||||
public string Nombre { get; set; } = string.Empty;
|
public string Nombre { get; set; } = string.Empty;
|
||||||
public bool Estado { get; set; }
|
public bool Estado { get; set; }
|
||||||
public int Id_Usuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class PublicacionHistorico
|
public class PublicacionHistorico // Corresponde a dist_dtPublicaciones_H
|
||||||
{
|
{
|
||||||
// No hay PK autoincremental explícita en el script de _H
|
public int Id_Publicacion { get; set; } // ID de la Publicacion original
|
||||||
public int IdPublicacion { get; set; }
|
|
||||||
public string Nombre { get; set; } = string.Empty;
|
public string Nombre { get; set; } = string.Empty;
|
||||||
public string? Observacion { get; set; }
|
public string? Observacion { get; set; }
|
||||||
public int IdEmpresa { get; set; }
|
public int Id_Empresa { get; set; }
|
||||||
public bool? Habilitada { get; set; } // Coincide con la tabla _H
|
// public bool CtrlDevoluciones { get; set; } // Parece que no está en _H
|
||||||
|
public bool? Habilitada { get; set; } // Es nullable en _H
|
||||||
// Campos de Auditoría
|
|
||||||
public int Id_Usuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
|||||||
@@ -1,14 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class RecargoZonaHistorico
|
public class RecargoZonaHistorico // Corresponde a dist_RecargoZona_H
|
||||||
{
|
{
|
||||||
public int IdRecargo { get; set; }
|
public int Id_Recargo { get; set; } // ID del Recargo original
|
||||||
public int IdPublicacion { get; set; }
|
public int Id_Publicacion { get; set; }
|
||||||
public int IdZona { get; set; }
|
public int Id_Zona { get; set; }
|
||||||
public DateTime VigenciaD { get; set; }
|
public DateTime VigenciaD { get; set; }
|
||||||
public DateTime? VigenciaH { get; set; }
|
public DateTime? VigenciaH { get; set; }
|
||||||
public decimal Valor { get; set; }
|
public decimal Valor { get; set; }
|
||||||
public int IdUsuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Distribucion
|
namespace GestionIntegral.Api.Models.Distribucion
|
||||||
{
|
{
|
||||||
public class ZonaHistorico
|
public class ZonaHistorico
|
||||||
{
|
{
|
||||||
public int IdZona { get; set; } // NO es IDENTITY
|
public int Id_Zona { get; set; }
|
||||||
public string Nombre { get; set; } = string.Empty;
|
public string Nombre { get; set; } = string.Empty;
|
||||||
public string? Descripcion { get; set; }
|
public string? Descripcion { get; set; }
|
||||||
public bool Estado { get; set; } // Importante para registrar el estado al momento del cambio
|
public bool Estado { get; set; } // El estado de la zona en ese momento del historial
|
||||||
public int IdUsuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Distribucion // O Auditoria
|
||||||
|
{
|
||||||
|
public class CambioParadaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Registro { get; set; }
|
||||||
|
public int Id_Canilla { get; set; }
|
||||||
|
public string NombreCanilla { get; set; } = string.Empty; // Para mostrar
|
||||||
|
public string Parada { get; set; } = string.Empty; // Dirección de la parada en ese momento
|
||||||
|
public DateTime VigenciaD { get; set; }
|
||||||
|
public DateTime? VigenciaH { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Dtos.Auditoria // O Auditoria
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
{
|
{
|
||||||
public class CanillaHistorialDto
|
public class CanillaHistorialDto
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class ControlDevolucionesHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Control { get; set; }
|
||||||
|
public int Id_Empresa { get; set; }
|
||||||
|
// public string NombreEmpresa { get; set; } // Opcional
|
||||||
|
public DateTime Fecha { get; set; } // Fecha original del control
|
||||||
|
public int Entrada { get; set; }
|
||||||
|
public int Sobrantes { get; set; }
|
||||||
|
public string? Detalle { get; set; }
|
||||||
|
public int SinCargo { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Dtos.Auditoria // O Auditoria
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
{
|
{
|
||||||
public class EmpresaHistorialDto
|
public class EmpresaHistorialDto
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class EstadoBobinaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_EstadoBobina { get; set; }
|
||||||
|
public string Denominacion { get; set; } = string.Empty;
|
||||||
|
public string? Obs { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class OtroDestinoHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Destino { get; set; }
|
||||||
|
public string Nombre { get; set; } = string.Empty;
|
||||||
|
public string? Obs { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PerfilHistorialDto
|
||||||
|
{
|
||||||
|
public int IdPerfil { get; set; } // ID del Perfil original
|
||||||
|
public string Perfil { get; set; } = string.Empty; // Nombre del perfil
|
||||||
|
public string? DescPerfil { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; } // Quién hizo el cambio
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
// El IdHist (PK de _H) no es estrictamente necesario en el DTO para mostrar,
|
||||||
|
// pero se puede incluir un identificador único para cada entrada de historial.
|
||||||
|
// public int IdHistorial { get; set;}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PermisoHistorialDto
|
||||||
|
{
|
||||||
|
public int IdPermiso { get; set; } // ID del Permiso original
|
||||||
|
public string Modulo { get; set; } = string.Empty;
|
||||||
|
public string DescPermiso { get; set; } = string.Empty;
|
||||||
|
public string CodAcc { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
// El IdHist de la tabla _H puede ser útil para la key en el frontend
|
||||||
|
public int IdHistorial { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PermisosPerfilesHistorialDto
|
||||||
|
{
|
||||||
|
public int IdHistorial { get; set; } // El ID de la entrada de historial
|
||||||
|
public int IdPerfil { get; set; }
|
||||||
|
public string NombrePerfil { get; set; } = string.Empty;
|
||||||
|
public int IdPermiso { get; set; }
|
||||||
|
public string DescPermiso { get; set; } = string.Empty;
|
||||||
|
public string CodAccPermiso { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty; // "Asignado", "Removido"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PlantaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Planta { get; set; }
|
||||||
|
public string Nombre { get; set; } = string.Empty;
|
||||||
|
public string Detalle { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PorcMonCanillaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_PorcMon { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
// public string NombrePublicacion { get; set; } // Opcional
|
||||||
|
public int Id_Canilla { get; set; }
|
||||||
|
// public string NombreCanilla { get; set; } // Opcional
|
||||||
|
public DateTime VigenciaD { get; set; }
|
||||||
|
public DateTime? VigenciaH { get; set; }
|
||||||
|
public decimal PorcMon { get; set; }
|
||||||
|
public bool EsPorcentaje { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PorcPagoHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Porcentaje { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
// public string NombrePublicacion { get; set; } // Opcional
|
||||||
|
public int Id_Distribuidor { get; set; }
|
||||||
|
// public string NombreDistribuidor { get; set; } // Opcional
|
||||||
|
public DateTime VigenciaD { get; set; }
|
||||||
|
public DateTime? VigenciaH { get; set; }
|
||||||
|
public decimal Porcentaje { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PrecioHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Precio { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
// public string NombrePublicacion { get; set; } // Opcional
|
||||||
|
public DateTime VigenciaD { get; set; }
|
||||||
|
public DateTime? VigenciaH { get; set; }
|
||||||
|
public decimal? Lunes { get; set; }
|
||||||
|
public decimal? Martes { get; set; }
|
||||||
|
public decimal? Miercoles { get; set; }
|
||||||
|
public decimal? Jueves { get; set; }
|
||||||
|
public decimal? Viernes { get; set; }
|
||||||
|
public decimal? Sabado { get; set; }
|
||||||
|
public decimal? Domingo { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PubliSeccionHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Seccion { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
// public string NombrePublicacion { get; set; } // Opcional, si quieres traerlo con JOIN
|
||||||
|
public string Nombre { get; set; } = string.Empty; // Nombre de la sección
|
||||||
|
public bool Estado { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class PublicacionHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
public string Nombre { get; set; } = string.Empty;
|
||||||
|
public string? Observacion { get; set; }
|
||||||
|
public int Id_Empresa { get; set; }
|
||||||
|
// public string NombreEmpresa { get; set; } // Opcional
|
||||||
|
// public bool CtrlDevoluciones { get; set; } // Si la añades a _H y al modelo
|
||||||
|
public bool? Habilitada { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class RecargoZonaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Recargo { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
// public string NombrePublicacion { get; set; } // Opcional
|
||||||
|
public int Id_Zona { get; set; }
|
||||||
|
// public string NombreZona { get; set; } // Opcional
|
||||||
|
public DateTime VigenciaD { get; set; }
|
||||||
|
public DateTime? VigenciaH { get; set; }
|
||||||
|
public decimal Valor { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class RegSeccionTiradaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Tirada { get; set; } // ID del registro original de la sección de la tirada
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
public string NombrePublicacion { get; set; } = string.Empty;
|
||||||
|
public int Id_Seccion { get; set; }
|
||||||
|
public string NombreSeccion { get; set; } = string.Empty;
|
||||||
|
public int CantPag { get; set; }
|
||||||
|
public DateTime Fecha { get; set; } // Fecha original de la tirada
|
||||||
|
public int Id_Planta { get; set; }
|
||||||
|
public string NombrePlanta { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class RegTiradaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Registro { get; set; }
|
||||||
|
public int Ejemplares { get; set; }
|
||||||
|
public int Id_Publicacion { get; set; }
|
||||||
|
public string NombrePublicacion { get; set; } = string.Empty; // Para mostrar
|
||||||
|
public DateTime Fecha { get; set; }
|
||||||
|
public int Id_Planta { get; set; }
|
||||||
|
public string NombrePlanta { get; set; } = string.Empty; // Para mostrar
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class StockBobinaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Bobina { get; set; }
|
||||||
|
public int Id_TipoBobina { get; set; }
|
||||||
|
public string NombreTipoBobina { get; set; } = string.Empty; // Para mostrar
|
||||||
|
public string NroBobina { get; set; } = string.Empty;
|
||||||
|
public int Peso { get; set; }
|
||||||
|
public int Id_Planta { get; set; }
|
||||||
|
public string NombrePlanta { get; set; } = string.Empty; // Para mostrar
|
||||||
|
public int Id_EstadoBobina { get; set; }
|
||||||
|
public string NombreEstadoBobina { get; set; } = string.Empty; // Para mostrar
|
||||||
|
public string Remito { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaRemito { get; set; }
|
||||||
|
public DateTime? FechaEstado { get; set; }
|
||||||
|
public int? Id_Publicacion { get; set; }
|
||||||
|
public string? NombrePublicacion { get; set; } // Para mostrar
|
||||||
|
public int? Id_Seccion { get; set; }
|
||||||
|
public string? NombreSeccion { get; set; } // Para mostrar
|
||||||
|
public string? Obs { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class TipoBobinaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_TipoBobina { get; set; }
|
||||||
|
public string Denominacion { get; set; } = string.Empty;
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Dtos.Auditoria
|
||||||
|
{
|
||||||
|
public class ZonaHistorialDto
|
||||||
|
{
|
||||||
|
public int Id_Zona { get; set; }
|
||||||
|
public string Nombre { get; set; } = string.Empty;
|
||||||
|
public string? Descripcion { get; set; }
|
||||||
|
public bool Estado { get; set; }
|
||||||
|
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public string NombreUsuarioModifico { get; set; } = string.Empty;
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,8 +6,6 @@ namespace GestionIntegral.Api.Dtos.Distribucion
|
|||||||
{
|
{
|
||||||
// IdPublicacion no se puede cambiar una vez creado el precio (se borraría y crearía uno nuevo)
|
// IdPublicacion no se puede cambiar una vez creado el precio (se borraría y crearía uno nuevo)
|
||||||
// VigenciaD tampoco se debería cambiar directamente, se maneja creando nuevos periodos.
|
// VigenciaD tampoco se debería cambiar directamente, se maneja creando nuevos periodos.
|
||||||
|
|
||||||
[Required(ErrorMessage = "La fecha de Vigencia Hasta es obligatoria si se modifica un periodo existente para cerrarlo.")]
|
|
||||||
public DateTime? VigenciaH { get; set; } // Para cerrar un periodo
|
public DateTime? VigenciaH { get; set; } // Para cerrar un periodo
|
||||||
|
|
||||||
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
[Range(0, 999999.99, ErrorMessage = "El precio debe ser un valor positivo.")]
|
||||||
|
|||||||
@@ -1,19 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Impresion
|
namespace GestionIntegral.Api.Models.Impresion
|
||||||
{
|
{
|
||||||
public class EstadoBobinaHistorico
|
public class EstadoBobinaHistorico // Corresponde a bob_dtEstadosBobinas_H
|
||||||
{
|
{
|
||||||
// Columna: Id_EstadoBobina (int, FK)
|
public int Id_EstadoBobina { get; set; } // ID del EstadoBobina original
|
||||||
public int IdEstadoBobina { get; set; }
|
|
||||||
|
|
||||||
// Columna: Denominacion (varchar(50), NOT NULL)
|
|
||||||
public string Denominacion { get; set; } = string.Empty;
|
public string Denominacion { get; set; } = string.Empty;
|
||||||
|
|
||||||
// Columna: Obs (varchar(150), NULL)
|
|
||||||
public string? Obs { get; set; }
|
public string? Obs { get; set; }
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
// Columnas de Auditoría
|
|
||||||
public int IdUsuario { get; set; }
|
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,14 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Impresion
|
namespace GestionIntegral.Api.Models.Impresion
|
||||||
{
|
{
|
||||||
public class PlantaHistorico
|
public class PlantaHistorico // Corresponde a bob_dtPlantas_H
|
||||||
{
|
{
|
||||||
public int IdPlanta { get; set; } // FK a bob_dtPlantas
|
public int Id_Planta { get; set; } // ID de la Planta original
|
||||||
public string Nombre { get; set; } = string.Empty;
|
public string Nombre { get; set; } = string.Empty;
|
||||||
public string Detalle { get; set; } = string.Empty;
|
public string Detalle { get; set; } = string.Empty; // No es nullable en _H
|
||||||
public int IdUsuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,13 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Impresion
|
namespace GestionIntegral.Api.Models.Impresion
|
||||||
{
|
{
|
||||||
public class RegTiradaHistorico
|
public class RegTiradaHistorico // Corresponde a bob_RegTiradas_H
|
||||||
{
|
{
|
||||||
public int Id_Registro { get; set; } // Nombre de columna en _H
|
public int Id_Registro { get; set; } // ID del RegTirada original
|
||||||
public int Ejemplares { get; set; }
|
public int Ejemplares { get; set; }
|
||||||
public int Id_Publicacion { get; set; }
|
public int Id_Publicacion { get; set; }
|
||||||
public DateTime Fecha { get; set; }
|
public DateTime Fecha { get; set; } // Fecha original de la tirada
|
||||||
public int Id_Planta { get; set; }
|
public int Id_Planta { get; set; }
|
||||||
public int Id_Usuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
|
|||||||
@@ -2,9 +2,9 @@ using System;
|
|||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Impresion
|
namespace GestionIntegral.Api.Models.Impresion
|
||||||
{
|
{
|
||||||
public class StockBobinaHistorico
|
public class StockBobinaHistorico // Corresponde a bob_StockBobinas_H
|
||||||
{
|
{
|
||||||
public int Id_Bobina { get; set; } // Columna en _H
|
public int Id_Bobina { get; set; } // ID de la Bobina en Stock original
|
||||||
public int Id_TipoBobina { get; set; }
|
public int Id_TipoBobina { get; set; }
|
||||||
public string NroBobina { get; set; } = string.Empty;
|
public string NroBobina { get; set; } = string.Empty;
|
||||||
public int Peso { get; set; }
|
public int Peso { get; set; }
|
||||||
@@ -16,10 +16,8 @@ namespace GestionIntegral.Api.Models.Impresion
|
|||||||
public int? Id_Publicacion { get; set; }
|
public int? Id_Publicacion { get; set; }
|
||||||
public int? Id_Seccion { get; set; }
|
public int? Id_Seccion { get; set; }
|
||||||
public string? Obs { get; set; }
|
public string? Obs { get; set; }
|
||||||
|
|
||||||
// Auditoría
|
|
||||||
public int Id_Usuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Ingreso", "Estado Cambiado", "Actualizacion", "Eliminada"
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,16 +1,13 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Impresion
|
namespace GestionIntegral.Api.Models.Impresion
|
||||||
{
|
{
|
||||||
public class TipoBobinaHistorico
|
public class TipoBobinaHistorico // Corresponde a bob_dtBobinas_H
|
||||||
{
|
{
|
||||||
// Columna: Id_TipoBobina (int, FK)
|
public int Id_TipoBobina { get; set; } // ID del TipoBobina original
|
||||||
public int IdTipoBobina { get; set; }
|
|
||||||
|
|
||||||
// Columna: Denominacion (varchar(150), NOT NULL)
|
|
||||||
public string Denominacion { get; set; } = string.Empty;
|
public string Denominacion { get; set; } = string.Empty;
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
// Columnas de Auditoría
|
|
||||||
public int IdUsuario { get; set; }
|
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,12 +1,19 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Usuarios
|
namespace GestionIntegral.Api.Models.Usuarios
|
||||||
{
|
{
|
||||||
public class PerfilHistorico
|
public class PerfilHistorico // Corresponde a gral_Perfiles_H
|
||||||
{
|
{
|
||||||
public int IdPerfil { get; set; } // FK a gral_Perfiles.id
|
// La tabla gral_Perfiles_H tiene un Id IDENTITY(1,1) propio,
|
||||||
public string NombrePerfil { get; set; } = string.Empty;
|
// pero también tiene idPerfil que es el FK al perfil original.
|
||||||
public string? Descripcion { get; set; }
|
// Usamos idPerfil para identificar el perfil afectado.
|
||||||
public int IdUsuario { get; set; }
|
// El Id de la tabla _H es más para la unicidad del registro de historial.
|
||||||
public DateTime FechaMod { get; set; }
|
public int Id {get; set;} // PK de la tabla _H
|
||||||
public string TipoMod { get; set; } = string.Empty; // "Insertada", "Modificada", "Eliminada"
|
public int IdPerfil { get; set; } // ID del Perfil original
|
||||||
}
|
public string Perfil { get; set; } = string.Empty; // Nombre del perfil en ese momento
|
||||||
|
public string? DescPerfil { get; set; }
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
namespace GestionIntegral.Api.Models.Usuarios
|
namespace GestionIntegral.Api.Models.Usuarios
|
||||||
{
|
{
|
||||||
public class PermisoHistorico
|
public class PermisoHistorico // Corresponde a gral_Permisos_H
|
||||||
{
|
{
|
||||||
public int IdHist { get; set; } // PK de la tabla de historial
|
public int IdHist { get; set; } // PK de la tabla _H
|
||||||
public int IdPermiso { get; set; } // FK a gral_Permisos.id
|
public int IdPermiso { get; set; } // ID del Permiso original
|
||||||
public string Modulo { get; set; } = string.Empty;
|
public string Modulo { get; set; } = string.Empty;
|
||||||
public string DescPermiso { get; set; } = string.Empty;
|
public string DescPermiso { get; set; } = string.Empty;
|
||||||
public string CodAcc { get; set; } = string.Empty;
|
public string CodAcc { get; set; } = string.Empty;
|
||||||
public int IdUsuario { get; set; }
|
public int Id_Usuario { get; set; }
|
||||||
public DateTime FechaMod { get; set; }
|
public DateTime FechaMod { get; set; }
|
||||||
public string TipoMod { get; set; } = string.Empty;
|
public string TipoMod { get; set; } = string.Empty;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
using System;
|
||||||
|
|
||||||
|
namespace GestionIntegral.Api.Models.Usuarios
|
||||||
|
{
|
||||||
|
public class PermisosPerfilesHistorico // Corresponde a gral_PermisosPerfiles_H
|
||||||
|
{
|
||||||
|
// Esta tabla registra cada asignación individualmente como un evento.
|
||||||
|
// El id de la tabla _H es el identificador único del evento de historial.
|
||||||
|
public int Id { get; set; } // PK de la tabla _H
|
||||||
|
public int idPerfil { get; set; }
|
||||||
|
public int idPermiso { get; set; }
|
||||||
|
public int Id_Usuario { get; set; }
|
||||||
|
public DateTime FechaMod { get; set; }
|
||||||
|
public string TipoMod { get; set; } = string.Empty; // "Asignado", "Removido" (o "Creado"/"Eliminado")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(); } }
|
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,
|
FechaMod = h.Historial.FechaMod,
|
||||||
TipoMod = h.Historial.TipoMod
|
TipoMod = h.Historial.TipoMod
|
||||||
}).ToList();
|
}).ToList();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using GestionIntegral.Api.Data;
|
using GestionIntegral.Api.Data;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -167,5 +168,29 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno: {ex.Message}");
|
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.
|
// 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)> CerrarParadaAsync(int idRegistro, UpdateCambioParadaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarParadaAsync(int idRegistro, int idUsuario); // Si se permite
|
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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(ControlDevolucionesDto? Control, string? Error)> CrearAsync(CreateControlDevolucionesDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idControl, UpdateControlDevolucionesDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idControl, 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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(OtroDestinoDto? Destino, string? Error)> CrearAsync(CreateOtroDestinoDto createDto, int idUsuario);
|
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)> ActualizarAsync(int id, UpdateOtroDestinoDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, 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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(PorcMonCanillaDto? Item, string? Error)> CrearAsync(CreatePorcMonCanillaDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idPorcMon, UpdatePorcMonCanillaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPorcMon, 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.Dtos.Distribucion;
|
||||||
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -12,5 +14,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(PorcPagoDto? PorcPago, string? Error)> CrearAsync(CreatePorcPagoDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idPorcentaje, UpdatePorcPagoDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPorcentaje, 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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(PrecioDto? Precio, string? Error)> CrearAsync(CreatePrecioDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idPrecio, UpdatePrecioDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idPrecio, 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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(PubliSeccionDto? Seccion, string? Error)> CrearAsync(CreatePubliSeccionDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idSeccion, UpdatePubliSeccionDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idSeccion, 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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -15,5 +16,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<IEnumerable<PublicacionDto>> ObtenerPublicacionesPorDiaSemanaAsync(byte diaSemana); // Devolvemos el DTO completo
|
Task<IEnumerable<PublicacionDto>> ObtenerPublicacionesPorDiaSemanaAsync(byte diaSemana); // Devolvemos el DTO completo
|
||||||
Task<(bool Exito, string? Error)> ActualizarConfiguracionDiasAsync(int idPublicacion, UpdatePublicacionDiasSemanaRequestDto requestDto, int idUsuario);
|
Task<(bool Exito, string? Error)> ActualizarConfiguracionDiasAsync(int idPublicacion, UpdatePublicacionDiasSemanaRequestDto requestDto, int idUsuario);
|
||||||
Task<IEnumerable<PublicacionDropdownDto>> ObtenerParaDropdownAsync(bool soloHabilitadas = true);
|
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 GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(RecargoZonaDto? Recargo, string? Error)> CrearAsync(CreateRecargoZonaDto createDto, int idUsuario);
|
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)> ActualizarAsync(int idRecargo, UpdateRecargoZonaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int idRecargo, 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 GestionIntegral.Api.Dtos.Zonas; // Para los DTOs de Zonas
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
Task<(ZonaDto? Zona, string? Error)> CrearAsync(CreateZonaDto createDto, int idUsuario);
|
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)> ActualizarAsync(int id, UpdateZonaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario); // Eliminar lógico (cambiar estado)
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -139,5 +140,24 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno al eliminar el destino: {ex.Message}");
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -44,7 +45,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
PorcMon = data.Item.PorcMon,
|
PorcMon = data.Item.PorcMon,
|
||||||
EsPorcentaje = data.Item.EsPorcentaje
|
EsPorcentaje = data.Item.EsPorcentaje
|
||||||
};
|
};
|
||||||
|
|
||||||
private async Task<PorcMonCanillaDto?> MapToDtoWithLookup(PorcMonCanilla? item)
|
private async Task<PorcMonCanillaDto?> MapToDtoWithLookup(PorcMonCanilla? item)
|
||||||
{
|
{
|
||||||
if (item == null) return null; // Si el item es null, devuelve null
|
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)
|
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
||||||
return (null, "La publicación especificada no existe.");
|
return (null, "La publicación especificada no existe.");
|
||||||
|
|
||||||
var canillaData = await _canillaRepository.GetByIdAsync(createDto.IdCanilla);
|
var canillaData = await _canillaRepository.GetByIdAsync(createDto.IdCanilla);
|
||||||
if (canillaData.Canilla == null) // GetByIdAsync devuelve una tupla
|
if (canillaData.Canilla == null) // GetByIdAsync devuelve una tupla
|
||||||
return (null, "El canillita especificado no existe o no está activo.");
|
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);
|
var itemAnterior = await _porcMonCanillaRepository.GetPreviousActiveAsync(createDto.IdPublicacion, createDto.IdCanilla, nuevoItem.VigenciaD, transaction);
|
||||||
if (itemAnterior != null)
|
if (itemAnterior != null)
|
||||||
{
|
{
|
||||||
if (itemAnterior.VigenciaD.Date >= nuevoItem.VigenciaD.Date)
|
if (itemAnterior.VigenciaD.Date >= nuevoItem.VigenciaD.Date)
|
||||||
{
|
{
|
||||||
transaction.Rollback();
|
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}).");
|
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)
|
if (updateDto.VigenciaH.HasValue && updateDto.VigenciaH.Value.Date < itemExistente.VigenciaD.Date)
|
||||||
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
||||||
|
|
||||||
if (updateDto.VigenciaH.HasValue)
|
if (updateDto.VigenciaH.HasValue)
|
||||||
{
|
{
|
||||||
var itemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemExistente.IdPublicacion);
|
var itemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemExistente.IdPublicacion);
|
||||||
var itemsPosteriores = itemsPubCanillaData
|
var itemsPosteriores = itemsPubCanillaData
|
||||||
.Where(i => i.Item.IdCanilla == itemExistente.IdCanilla &&
|
.Where(i => i.Item.IdCanilla == itemExistente.IdCanilla &&
|
||||||
i.Item.IdPorcMon != idPorcMon &&
|
i.Item.IdPorcMon != idPorcMon &&
|
||||||
i.Item.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
i.Item.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||||
i.Item.VigenciaD.Date > itemExistente.VigenciaD.Date);
|
i.Item.VigenciaD.Date > itemExistente.VigenciaD.Date);
|
||||||
if(itemsPosteriores.Any())
|
if (itemsPosteriores.Any())
|
||||||
{
|
{
|
||||||
return (false, "No se puede cerrar este período porque existen configuraciones posteriores para este canillita que se solaparían.");
|
return (false, "No se puede cerrar este período porque existen configuraciones posteriores para este canillita que se solaparían.");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
itemExistente.PorcMon = updateDto.PorcMon;
|
itemExistente.PorcMon = updateDto.PorcMon;
|
||||||
@@ -200,19 +201,19 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
var itemAEliminar = await _porcMonCanillaRepository.GetByIdAsync(idPorcMon);
|
var itemAEliminar = await _porcMonCanillaRepository.GetByIdAsync(idPorcMon);
|
||||||
if (itemAEliminar == null) return (false, "Registro no encontrado.");
|
if (itemAEliminar == null) return (false, "Registro no encontrado.");
|
||||||
|
|
||||||
if (itemAEliminar.VigenciaH == null)
|
if (itemAEliminar.VigenciaH == null)
|
||||||
{
|
{
|
||||||
var todosItemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemAEliminar.IdPublicacion);
|
var todosItemsPubCanillaData = await _porcMonCanillaRepository.GetByPublicacionIdAsync(itemAEliminar.IdPublicacion);
|
||||||
var todosItemsPubCanilla = todosItemsPubCanillaData
|
var todosItemsPubCanilla = todosItemsPubCanillaData
|
||||||
.Where(i => i.Item.IdCanilla == itemAEliminar.IdCanilla)
|
.Where(i => i.Item.IdCanilla == itemAEliminar.IdCanilla)
|
||||||
.Select(i => i.Item)
|
.Select(i => i.Item)
|
||||||
.OrderByDescending(i => i.VigenciaD).ToList();
|
.OrderByDescending(i => i.VigenciaD).ToList();
|
||||||
|
|
||||||
var indiceActual = todosItemsPubCanilla.FindIndex(i => i.IdPorcMon == idPorcMon);
|
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];
|
var itemAnteriorDirecto = todosItemsPubCanilla[indiceActual + 1];
|
||||||
if(itemAnteriorDirecto.VigenciaH.HasValue &&
|
if (itemAnteriorDirecto.VigenciaH.HasValue &&
|
||||||
itemAnteriorDirecto.VigenciaH.Value.Date == itemAEliminar.VigenciaD.AddDays(-1).Date)
|
itemAnteriorDirecto.VigenciaH.Value.Date == itemAEliminar.VigenciaD.AddDays(-1).Date)
|
||||||
{
|
{
|
||||||
itemAnteriorDirecto.VigenciaH = null;
|
itemAnteriorDirecto.VigenciaH = null;
|
||||||
@@ -236,5 +237,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno: {ex.Message}");
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -43,7 +44,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
VigenciaH = data.PorcPago.VigenciaH?.ToString("yyyy-MM-dd"),
|
VigenciaH = data.PorcPago.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||||
Porcentaje = data.PorcPago.Porcentaje
|
Porcentaje = data.PorcPago.Porcentaje
|
||||||
};
|
};
|
||||||
|
|
||||||
private async Task<PorcPagoDto> MapToDtoWithLookup(PorcPago porcPago)
|
private async Task<PorcPagoDto> MapToDtoWithLookup(PorcPago porcPago)
|
||||||
{
|
{
|
||||||
var distribuidorData = await _distribuidorRepository.GetByIdAsync(porcPago.IdDistribuidor);
|
var distribuidorData = await _distribuidorRepository.GetByIdAsync(porcPago.IdDistribuidor);
|
||||||
@@ -117,7 +118,8 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
|
|
||||||
transaction.Commit();
|
transaction.Commit();
|
||||||
_logger.LogInformation("PorcPago ID {Id} creado por Usuario ID {UserId}.", porcPagoCreado.IdPorcentaje, idUsuario);
|
_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,
|
IdPorcentaje = porcPagoCreado.IdPorcentaje,
|
||||||
IdPublicacion = porcPagoCreado.IdPublicacion,
|
IdPublicacion = porcPagoCreado.IdPublicacion,
|
||||||
IdDistribuidor = porcPagoCreado.IdDistribuidor,
|
IdDistribuidor = porcPagoCreado.IdDistribuidor,
|
||||||
@@ -156,9 +158,9 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
p.PorcPago.IdPorcentaje != idPorcentaje &&
|
p.PorcPago.IdPorcentaje != idPorcentaje &&
|
||||||
p.PorcPago.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
p.PorcPago.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||||
p.PorcPago.VigenciaD.Date > porcPagoExistente.VigenciaD.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);
|
var porcPagoAEliminar = await _porcPagoRepository.GetByIdAsync(idPorcentaje);
|
||||||
if (porcPagoAEliminar == null) return (false, "Porcentaje de pago no encontrado.");
|
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 todosPorcPubDistData = await _porcPagoRepository.GetByPublicacionIdAsync(porcPagoAEliminar.IdPublicacion);
|
||||||
var todosPorcPubDist = todosPorcPubDistData
|
var todosPorcPubDist = todosPorcPubDistData
|
||||||
.Where(p => p.PorcPago.IdDistribuidor == porcPagoAEliminar.IdDistribuidor)
|
.Where(p => p.PorcPago.IdDistribuidor == porcPagoAEliminar.IdDistribuidor)
|
||||||
.Select(p => p.PorcPago)
|
.Select(p => p.PorcPago)
|
||||||
.OrderByDescending(p => p.VigenciaD).ToList();
|
.OrderByDescending(p => p.VigenciaD).ToList();
|
||||||
|
|
||||||
var indiceActual = todosPorcPubDist.FindIndex(p => p.IdPorcentaje == idPorcentaje);
|
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];
|
var porcPagoAnteriorDirecto = todosPorcPubDist[indiceActual + 1];
|
||||||
if(porcPagoAnteriorDirecto.VigenciaH.HasValue &&
|
if (porcPagoAnteriorDirecto.VigenciaH.HasValue &&
|
||||||
porcPagoAnteriorDirecto.VigenciaH.Value.Date == porcPagoAEliminar.VigenciaD.AddDays(-1).Date)
|
porcPagoAnteriorDirecto.VigenciaH.Value.Date == porcPagoAEliminar.VigenciaD.AddDays(-1).Date)
|
||||||
{
|
{
|
||||||
porcPagoAnteriorDirecto.VigenciaH = null;
|
porcPagoAnteriorDirecto.VigenciaH = null;
|
||||||
@@ -230,5 +232,27 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno: {ex.Message}");
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -37,8 +38,13 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
IdPublicacion = precio.IdPublicacion,
|
IdPublicacion = precio.IdPublicacion,
|
||||||
VigenciaD = precio.VigenciaD.ToString("yyyy-MM-dd"),
|
VigenciaD = precio.VigenciaD.ToString("yyyy-MM-dd"),
|
||||||
VigenciaH = precio.VigenciaH?.ToString("yyyy-MM-dd"),
|
VigenciaH = precio.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||||
Lunes = precio.Lunes, Martes = precio.Martes, Miercoles = precio.Miercoles,
|
Lunes = precio.Lunes,
|
||||||
Jueves = precio.Jueves, Viernes = precio.Viernes, Sabado = precio.Sabado, Domingo = precio.Domingo
|
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)
|
public async Task<IEnumerable<PrecioDto>> ObtenerPorPublicacionIdAsync(int idPublicacion)
|
||||||
@@ -73,8 +79,13 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
IdPublicacion = createDto.IdPublicacion,
|
IdPublicacion = createDto.IdPublicacion,
|
||||||
VigenciaD = createDto.VigenciaD.Date, // Asegurar que solo sea fecha
|
VigenciaD = createDto.VigenciaD.Date, // Asegurar que solo sea fecha
|
||||||
VigenciaH = null, // Se establece al crear el siguiente o al cerrar manualmente
|
VigenciaH = null, // Se establece al crear el siguiente o al cerrar manualmente
|
||||||
Lunes = createDto.Lunes ?? 0, Martes = createDto.Martes ?? 0, Miercoles = createDto.Miercoles ?? 0,
|
Lunes = createDto.Lunes ?? 0,
|
||||||
Jueves = createDto.Jueves ?? 0, Viernes = createDto.Viernes ?? 0, Sabado = createDto.Sabado ?? 0, Domingo = createDto.Domingo ?? 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();
|
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.");
|
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
|
// 3. Crear el nuevo registro de precio
|
||||||
@@ -126,91 +137,150 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var precioExistente = await _precioRepository.GetByIdAsync(idPrecio); // Obtener dentro de la TX por si acaso
|
var precioExistente = await _precioRepository.GetByIdAsync(idPrecio); // Obtener dentro de TX
|
||||||
if (precioExistente == null) return (false, "Período de precio no encontrado.");
|
if (precioExistente == null)
|
||||||
|
|
||||||
// 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)
|
|
||||||
{
|
{
|
||||||
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);
|
transaction.Rollback();
|
||||||
if (preciosPosteriores.Any(p => p.IdPrecio != idPrecio && p.VigenciaD.Date <= updateDto.VigenciaH.Value.Date && p.VigenciaD.Date > precioExistente.VigenciaD.Date ))
|
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;
|
// Aplicar actualizaciones
|
||||||
precioExistente.Martes = updateDto.Martes ?? precioExistente.Martes;
|
if (preciosDiasCambiaron)
|
||||||
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
|
|
||||||
{
|
{
|
||||||
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 (seRealizoAlgunaActualizacion)
|
||||||
if (!actualizado) throw new DataException("Error al actualizar el período de precio.");
|
{
|
||||||
|
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();
|
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);
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
try { transaction.Rollback(); } catch {}
|
try { transaction?.Rollback(); } catch { }
|
||||||
_logger.LogError(ex, "Error ActualizarAsync Precio ID: {IdPrecio}", idPrecio);
|
_logger.LogError(ex, "Error ActualizarAsync Precio ID: {IdPrecio}", idPrecio);
|
||||||
return (false, $"Error interno al actualizar el período de precio: {ex.Message}");
|
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)
|
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();
|
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||||
using var transaction = connection.BeginTransaction();
|
using var transaction = connection.BeginTransaction();
|
||||||
try
|
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.");
|
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.
|
// --- VERIFICACIÓN DE USO ---
|
||||||
// Si el precio a eliminar tiene un VigenciaH == null (estaba activo indefinidamente)
|
if (await _precioRepository.IsInUseAsync(idPrecio, precioAEliminar.VigenciaD, precioAEliminar.VigenciaH))
|
||||||
// Y existe un precio anterior para la misma publicación.
|
{
|
||||||
// Entonces, el VigenciaH de ese precio anterior debe volver a ser NULL.
|
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)
|
if (precioAEliminar.VigenciaH == null)
|
||||||
{
|
{
|
||||||
var todosLosPreciosPub = (await _precioRepository.GetByPublicacionIdAsync(precioAEliminar.IdPublicacion))
|
var todosLosPreciosPub = (await _precioRepository.GetByPublicacionIdAsync(precioAEliminar.IdPublicacion))
|
||||||
.OrderByDescending(p => p.VigenciaD).ToList();
|
.OrderByDescending(p => p.VigenciaD).ToList();
|
||||||
|
var indiceActual = todosLosPreciosPub.FindIndex(p => p.IdPrecio == idPrecio);
|
||||||
var indiceActual = todosLosPreciosPub.FindIndex(p=> p.IdPrecio == idPrecio);
|
if (indiceActual != -1 && (indiceActual + 1) < todosLosPreciosPub.Count)
|
||||||
if(indiceActual != -1 && (indiceActual + 1) < todosLosPreciosPub.Count)
|
|
||||||
{
|
{
|
||||||
var precioAnteriorDirecto = todosLosPreciosPub[indiceActual + 1];
|
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;
|
precioAnteriorDirecto.VigenciaH = null;
|
||||||
await _precioRepository.UpdateAsync(precioAnteriorDirecto, idUsuario, transaction); // Usar un ID de auditoría adecuado
|
// Asegurar que UpdateAsync tome la transacción
|
||||||
_logger.LogInformation("Precio anterior ID {IdPrecioAnterior} reabierto (VigenciaH a NULL) tras eliminación de Precio ID {IdPrecioEliminado}.", precioAnteriorDirecto.IdPrecio, idPrecio);
|
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);
|
var eliminado = await _precioRepository.DeleteAsync(idPrecio, idUsuario, transaction);
|
||||||
if (!eliminado) throw new DataException("Error al eliminar el período de precio.");
|
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);
|
_logger.LogInformation("Precio ID {IdPrecio} eliminado por Usuario ID {IdUsuario}.", idPrecio, idUsuario);
|
||||||
return (true, null);
|
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)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
try { transaction.Rollback(); } catch {}
|
try { transaction.Rollback(); } catch { }
|
||||||
_logger.LogError(ex, "Error EliminarAsync Precio ID: {IdPrecio}", idPrecio);
|
_logger.LogError(ex, "Error EliminarAsync Precio ID: {IdPrecio}", idPrecio);
|
||||||
return (false, $"Error interno al eliminar el período de precio: {ex.Message}");
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
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)
|
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();
|
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||||
using var transaction = connection.BeginTransaction();
|
using var transaction = connection.BeginTransaction();
|
||||||
try
|
try
|
||||||
@@ -149,5 +150,26 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno: {ex.Message}");
|
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
|
// src/Services/Distribucion/PublicacionService.cs
|
||||||
using GestionIntegral.Api.Data;
|
using GestionIntegral.Api.Data;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
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}");
|
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;
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Distribucion;
|
using GestionIntegral.Api.Dtos.Distribucion;
|
||||||
using GestionIntegral.Api.Models.Distribucion;
|
using GestionIntegral.Api.Models.Distribucion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -43,7 +44,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
VigenciaH = data.Recargo.VigenciaH?.ToString("yyyy-MM-dd"),
|
VigenciaH = data.Recargo.VigenciaH?.ToString("yyyy-MM-dd"),
|
||||||
Valor = data.Recargo.Valor
|
Valor = data.Recargo.Valor
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper para mapear cuando solo tenemos el RecargoZona y necesitamos buscar NombreZona
|
// Helper para mapear cuando solo tenemos el RecargoZona y necesitamos buscar NombreZona
|
||||||
private async Task<RecargoZonaDto> MapToDtoWithZonaLookup(RecargoZona recargo)
|
private async Task<RecargoZonaDto> MapToDtoWithZonaLookup(RecargoZona recargo)
|
||||||
{
|
{
|
||||||
@@ -74,10 +75,11 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
{
|
{
|
||||||
var recargo = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
var recargo = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||||
if (recargo == null) return null;
|
if (recargo == null) return null;
|
||||||
|
|
||||||
var zona = await _zonaRepository.GetByIdAsync(recargo.IdZona); // Obtiene ZonaDto
|
var zona = await _zonaRepository.GetByIdAsync(recargo.IdZona); // Obtiene ZonaDto
|
||||||
return new RecargoZonaDto {
|
return new RecargoZonaDto
|
||||||
IdRecargo = recargo.IdRecargo,
|
{
|
||||||
|
IdRecargo = recargo.IdRecargo,
|
||||||
IdPublicacion = recargo.IdPublicacion,
|
IdPublicacion = recargo.IdPublicacion,
|
||||||
IdZona = recargo.IdZona,
|
IdZona = recargo.IdZona,
|
||||||
NombreZona = zona?.Nombre ?? "Zona Desconocida/Inactiva",
|
NombreZona = zona?.Nombre ?? "Zona Desconocida/Inactiva",
|
||||||
@@ -92,7 +94,7 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
if (await _publicacionRepository.GetByIdSimpleAsync(createDto.IdPublicacion) == null)
|
||||||
return (null, "La publicación especificada no existe.");
|
return (null, "La publicación especificada no existe.");
|
||||||
var zona = await _zonaRepository.GetByIdAsync(createDto.IdZona); // Devuelve ZonaDto
|
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.");
|
return (null, "La zona especificada no existe o no está activa.");
|
||||||
|
|
||||||
// Usar createDto.VigenciaD directamente que ya es DateTime
|
// 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);
|
var recargoAnterior = await _recargoZonaRepository.GetPreviousActiveRecargoAsync(createDto.IdPublicacion, createDto.IdZona, nuevoRecargo.VigenciaD, transaction);
|
||||||
if (recargoAnterior != null)
|
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();
|
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.");
|
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();
|
transaction.Commit();
|
||||||
_logger.LogInformation("Recargo ID {Id} creado por Usuario ID {UserId}.", recargoCreado.IdRecargo, idUsuario);
|
_logger.LogInformation("Recargo ID {Id} creado por Usuario ID {UserId}.", recargoCreado.IdRecargo, idUsuario);
|
||||||
// Pasar el nombre de la zona ya obtenido
|
// Pasar el nombre de la zona ya obtenido
|
||||||
return (new RecargoZonaDto {
|
return (new RecargoZonaDto
|
||||||
IdRecargo = recargoCreado.IdRecargo, IdPublicacion = recargoCreado.IdPublicacion, IdZona = recargoCreado.IdZona,
|
{
|
||||||
NombreZona = zona.Nombre, VigenciaD = recargoCreado.VigenciaD.ToString("yyyy-MM-dd"),
|
IdRecargo = recargoCreado.IdRecargo,
|
||||||
VigenciaH = recargoCreado.VigenciaH?.ToString("yyyy-MM-dd"), Valor = recargoCreado.Valor
|
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);
|
}, null);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@@ -155,21 +162,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
using var transaction = connection.BeginTransaction();
|
using var transaction = connection.BeginTransaction();
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var recargoExistente = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
var recargoExistente = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||||
if (recargoExistente == null) return (false, "Recargo por zona no encontrado.");
|
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)
|
if (updateDto.VigenciaH.HasValue && updateDto.VigenciaH.Value.Date < recargoExistente.VigenciaD.Date)
|
||||||
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
return (false, "Vigencia Hasta no puede ser anterior a Vigencia Desde.");
|
||||||
|
|
||||||
if (updateDto.VigenciaH.HasValue)
|
if (updateDto.VigenciaH.HasValue)
|
||||||
{
|
{
|
||||||
var recargosDeLaPublicacion = await _recargoZonaRepository.GetByPublicacionIdAsync(recargoExistente.IdPublicacion);
|
var recargosDeLaPublicacion = await _recargoZonaRepository.GetByPublicacionIdAsync(recargoExistente.IdPublicacion);
|
||||||
var recargosPosteriores = recargosDeLaPublicacion
|
var recargosPosteriores = recargosDeLaPublicacion
|
||||||
.Where(r => r.Recargo.IdZona == recargoExistente.IdZona &&
|
.Where(r => r.Recargo.IdZona == recargoExistente.IdZona &&
|
||||||
r.Recargo.IdRecargo != idRecargo &&
|
r.Recargo.IdRecargo != idRecargo &&
|
||||||
r.Recargo.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
r.Recargo.VigenciaD.Date <= updateDto.VigenciaH.Value.Date &&
|
||||||
r.Recargo.VigenciaD.Date > recargoExistente.VigenciaD.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.");
|
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);
|
var recargoAEliminar = await _recargoZonaRepository.GetByIdAsync(idRecargo);
|
||||||
if (recargoAEliminar == null) return (false, "Recargo no encontrado.");
|
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 todosRecargosPubZonaData = await _recargoZonaRepository.GetByPublicacionIdAsync(recargoAEliminar.IdPublicacion);
|
||||||
var todosRecargosPubZona = todosRecargosPubZonaData
|
var todosRecargosPubZona = todosRecargosPubZonaData
|
||||||
.Where(r => r.Recargo.IdZona == recargoAEliminar.IdZona)
|
.Where(r => r.Recargo.IdZona == recargoAEliminar.IdZona)
|
||||||
.Select(r => r.Recargo)
|
.Select(r => r.Recargo)
|
||||||
.OrderByDescending(r => r.VigenciaD).ToList();
|
.OrderByDescending(r => r.VigenciaD).ToList();
|
||||||
|
|
||||||
var indiceActual = todosRecargosPubZona.FindIndex(r => r.IdRecargo == idRecargo);
|
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];
|
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;
|
recargoAnteriorDirecto.VigenciaH = null;
|
||||||
await _recargoZonaRepository.UpdateAsync(recargoAnteriorDirecto, idUsuario, transaction);
|
await _recargoZonaRepository.UpdateAsync(recargoAnteriorDirecto, idUsuario, transaction);
|
||||||
@@ -243,5 +264,28 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, $"Error interno: {ex.Message}");
|
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; // Para IZonaRepository
|
||||||
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
using GestionIntegral.Api.Data.Repositories.Distribucion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Zonas;
|
using GestionIntegral.Api.Dtos.Zonas;
|
||||||
using GestionIntegral.Api.Models.Distribucion; // Para Zona
|
using GestionIntegral.Api.Models.Distribucion; // Para Zona
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
@@ -123,7 +124,8 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
return (false, "Zona no encontrada.");
|
return (false, "Zona no encontrada.");
|
||||||
}
|
}
|
||||||
// Si ya está inactiva, consideramos la operación exitosa (idempotencia)
|
// Si ya está inactiva, consideramos la operación exitosa (idempotencia)
|
||||||
if (!zonaExistente.Estado) {
|
if (!zonaExistente.Estado)
|
||||||
|
{
|
||||||
return (true, null);
|
return (true, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -137,10 +139,30 @@ namespace GestionIntegral.Api.Services.Distribucion
|
|||||||
var eliminado = await _zonaRepository.SoftDeleteAsync(id, idUsuario);
|
var eliminado = await _zonaRepository.SoftDeleteAsync(id, idUsuario);
|
||||||
if (!eliminado)
|
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 (false, "Error al eliminar la zona de la base de datos.");
|
||||||
}
|
}
|
||||||
return (true, null); // Éxito
|
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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using GestionIntegral.Api.Data;
|
using GestionIntegral.Api.Data;
|
||||||
using GestionIntegral.Api.Data.Repositories.Impresion;
|
using GestionIntegral.Api.Data.Repositories.Impresion;
|
||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Impresion;
|
using GestionIntegral.Api.Dtos.Impresion;
|
||||||
using GestionIntegral.Api.Models.Impresion;
|
using GestionIntegral.Api.Models.Impresion;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
@@ -112,10 +113,10 @@ namespace GestionIntegral.Api.Services.Impresion
|
|||||||
{
|
{
|
||||||
// Estados "fijos" como Disponible (1), En Uso (2), Dañada (3) probablemente no deberían eliminarse.
|
// Estados "fijos" como Disponible (1), En Uso (2), Dañada (3) probablemente no deberían eliminarse.
|
||||||
// Podrías añadir una validación aquí o en el repositorio si es necesario.
|
// Podrías añadir una validación aquí o en el repositorio si es necesario.
|
||||||
if (id <= 3) // Asumiendo IDs fijos para los estados base
|
if (id <= 3) // Asumiendo IDs fijos para los estados base
|
||||||
{
|
{
|
||||||
return (false, "Los estados base (Disponible, En Uso, Dañada) no se pueden eliminar.");
|
return (false, "Los estados base (Disponible, En Uso, Dañada) no se pueden eliminar.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await _estadoBobinaRepository.IsInUseAsync(id))
|
if (await _estadoBobinaRepository.IsInUseAsync(id))
|
||||||
{
|
{
|
||||||
@@ -129,7 +130,7 @@ namespace GestionIntegral.Api.Services.Impresion
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
var eliminado = await _estadoBobinaRepository.DeleteAsync(id, idUsuario, transaction);
|
var eliminado = await _estadoBobinaRepository.DeleteAsync(id, idUsuario, transaction);
|
||||||
if (!eliminado) throw new DataException("La operación de eliminación no afectó ninguna fila.");
|
if (!eliminado) throw new DataException("La operación de eliminación no afectó ninguna fila.");
|
||||||
|
|
||||||
transaction.Commit(); // Síncrono
|
transaction.Commit(); // Síncrono
|
||||||
_logger.LogInformation("EstadoBobina ID {IdEstadoBobina} eliminado por Usuario ID {IdUsuario}.", id, idUsuario);
|
_logger.LogInformation("EstadoBobina ID {IdEstadoBobina} eliminado por Usuario ID {IdUsuario}.", id, idUsuario);
|
||||||
@@ -137,16 +138,35 @@ namespace GestionIntegral.Api.Services.Impresion
|
|||||||
}
|
}
|
||||||
catch (KeyNotFoundException knfex)
|
catch (KeyNotFoundException knfex)
|
||||||
{
|
{
|
||||||
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error rollback EliminarAsync EstadoBobina."); }
|
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error rollback EliminarAsync EstadoBobina."); }
|
||||||
_logger.LogWarning(knfex, "Intento de eliminar EstadoBobina ID: {Id} no encontrado.", id);
|
_logger.LogWarning(knfex, "Intento de eliminar EstadoBobina ID: {Id} no encontrado.", id);
|
||||||
return (false, "Estado de bobina no encontrado.");
|
return (false, "Estado de bobina no encontrado.");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error rollback EliminarAsync EstadoBobina."); }
|
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error rollback EliminarAsync EstadoBobina."); }
|
||||||
_logger.LogError(ex, "Error EliminarAsync EstadoBobina ID: {Id}", id);
|
_logger.LogError(ex, "Error EliminarAsync EstadoBobina ID: {Id}", id);
|
||||||
return (false, $"Error interno al eliminar el estado de bobina: {ex.Message}");
|
return (false, $"Error interno al eliminar el estado de bobina: {ex.Message}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<IEnumerable<EstadoBobinaHistorialDto>> ObtenerHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idEstadoBobinaAfectado)
|
||||||
|
{
|
||||||
|
var historialData = await _estadoBobinaRepository.GetHistorialAsync(fechaDesde, fechaHasta, idUsuarioModifico, tipoModificacion, idEstadoBobinaAfectado);
|
||||||
|
|
||||||
|
return historialData.Select(h => new EstadoBobinaHistorialDto
|
||||||
|
{
|
||||||
|
Id_EstadoBobina = h.Historial.Id_EstadoBobina,
|
||||||
|
Denominacion = h.Historial.Denominacion,
|
||||||
|
Obs = h.Historial.Obs,
|
||||||
|
Id_Usuario = h.Historial.Id_Usuario,
|
||||||
|
NombreUsuarioModifico = h.NombreUsuarioModifico,
|
||||||
|
FechaMod = h.Historial.FechaMod,
|
||||||
|
TipoMod = h.Historial.TipoMod
|
||||||
|
}).ToList();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Impresion;
|
using GestionIntegral.Api.Dtos.Impresion;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -11,5 +12,9 @@ namespace GestionIntegral.Api.Services.Impresion
|
|||||||
Task<(EstadoBobinaDto? EstadoBobina, string? Error)> CrearAsync(CreateEstadoBobinaDto createDto, int idUsuario);
|
Task<(EstadoBobinaDto? EstadoBobina, string? Error)> CrearAsync(CreateEstadoBobinaDto createDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateEstadoBobinaDto updateDto, int idUsuario);
|
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateEstadoBobinaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
|
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
|
||||||
|
Task<IEnumerable<EstadoBobinaHistorialDto>> ObtenerHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idEstadoBobinaAfectado);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using GestionIntegral.Api.Dtos.Auditoria;
|
||||||
using GestionIntegral.Api.Dtos.Impresion; // Para los DTOs
|
using GestionIntegral.Api.Dtos.Impresion; // Para los DTOs
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
@@ -12,5 +13,9 @@ namespace GestionIntegral.Api.Services.Impresion
|
|||||||
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdatePlantaDto updateDto, int idUsuario);
|
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdatePlantaDto updateDto, int idUsuario);
|
||||||
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
|
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
|
||||||
Task<IEnumerable<PlantaDropdownDto>> ObtenerParaDropdownAsync();
|
Task<IEnumerable<PlantaDropdownDto>> ObtenerParaDropdownAsync();
|
||||||
|
Task<IEnumerable<PlantaHistorialDto>> ObtenerHistorialAsync(
|
||||||
|
DateTime? fechaDesde, DateTime? fechaHasta,
|
||||||
|
int? idUsuarioModifico, string? tipoModificacion,
|
||||||
|
int? idPlantaAfectada);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user