Refinamiento de permisos y ajustes en controles. Añade gestión sobre saldos y visualización. Entre otros..
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Generic; // Para IEnumerable
|
||||
using System.Data;
|
||||
using GestionIntegral.Api.Dtos.Contables; // Para SaldoGestionDto si lo usas aquí
|
||||
using GestionIntegral.Api.Models.Contables; // Para Saldo, SaldoAjusteHistorial
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Contables
|
||||
{
|
||||
@@ -15,5 +17,12 @@ namespace GestionIntegral.Api.Data.Repositories.Contables
|
||||
// Método para modificar saldo (lo teníamos como privado antes, ahora en el repo)
|
||||
Task<bool> ModificarSaldoAsync(string destino, int idDestino, int idEmpresa, decimal montoAAgregar, IDbTransaction? transaction = null);
|
||||
Task<bool> CheckIfSaldosExistForEmpresaAsync(int id);
|
||||
|
||||
// Para obtener la lista de saldos para la página de gestión
|
||||
Task<IEnumerable<Saldo>> GetSaldosParaGestionAsync(string? destinoFilter, int? idDestinoFilter, int? idEmpresaFilter);
|
||||
// Para obtener un saldo específico (ya podría existir uno similar, o crearlo si es necesario)
|
||||
Task<Saldo?> GetSaldoAsync(string destino, int idDestino, int idEmpresa, IDbTransaction? transaction = null);
|
||||
// Para registrar el historial de ajuste
|
||||
Task CreateSaldoAjusteHistorialAsync(SaldoAjusteHistorial historialEntry, IDbTransaction transaction);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Data.Repositories;
|
||||
using GestionIntegral.Api.Data.Repositories;
|
||||
using GestionIntegral.Api.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using GestionIntegral.Api.Models.Contables;
|
||||
using System.Text;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Contables
|
||||
{
|
||||
@@ -57,61 +59,64 @@ namespace GestionIntegral.Api.Data.Repositories.Contables
|
||||
|
||||
public async Task<bool> DeleteSaldosByEmpresaAsync(int idEmpresa, IDbTransaction transaction)
|
||||
{
|
||||
var sql = "DELETE FROM dbo.cue_Saldos WHERE Id_Empresa = @IdEmpresa";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(sql, new { IdEmpresa = idEmpresa }, transaction: transaction);
|
||||
return true; // Asumir éxito si no hay excepción
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar saldos para Empresa ID {IdEmpresa}.", idEmpresa);
|
||||
throw;
|
||||
}
|
||||
var sql = "DELETE FROM dbo.cue_Saldos WHERE Id_Empresa = @IdEmpresa";
|
||||
try
|
||||
{
|
||||
await transaction.Connection!.ExecuteAsync(sql, new { IdEmpresa = idEmpresa }, transaction: transaction);
|
||||
return true; // Asumir éxito si no hay excepción
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar saldos para Empresa ID {IdEmpresa}.", idEmpresa);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ModificarSaldoAsync(string destino, int idDestino, int idEmpresa, decimal montoAAgregar, IDbTransaction? transaction = null)
|
||||
{
|
||||
var sql = @"UPDATE dbo.cue_Saldos
|
||||
SET Monto = Monto + @MontoAAgregar
|
||||
WHERE Destino = @Destino AND Id_Destino = @IdDestino AND Id_Empresa = @IdEmpresa;";
|
||||
{
|
||||
var sql = @"UPDATE dbo.cue_Saldos
|
||||
SET Monto = Monto + @MontoAAgregar,
|
||||
FechaUltimaModificacion = @FechaActualizacion -- << AÑADIR
|
||||
WHERE Destino = @Destino AND Id_Destino = @IdDestino AND Id_Empresa = @IdEmpresa;";
|
||||
|
||||
// Usar una variable para la conexión para poder aplicar el '!' si es necesario
|
||||
IDbConnection connection = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
bool ownConnection = transaction == null; // Saber si necesitamos cerrar la conexión nosotros
|
||||
IDbConnection connection = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
bool ownConnection = transaction == null;
|
||||
|
||||
try
|
||||
{
|
||||
if (ownConnection) await (connection as System.Data.Common.DbConnection)!.OpenAsync(); // Abrir solo si no hay transacción externa
|
||||
try
|
||||
{
|
||||
if (ownConnection && connection.State != ConnectionState.Open)
|
||||
{
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else connection.Open();
|
||||
}
|
||||
|
||||
var parameters = new {
|
||||
MontoAAgregar = montoAAgregar,
|
||||
Destino = destino,
|
||||
IdDestino = idDestino,
|
||||
IdEmpresa = idEmpresa
|
||||
};
|
||||
// Aplicar '!' aquí también si viene de la transacción
|
||||
int rowsAffected = await connection.ExecuteAsync(sql, parameters, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al modificar saldo para {Destino} ID {IdDestino}, Empresa ID {IdEmpresa}.", destino, idDestino, idEmpresa);
|
||||
if (transaction != null) throw; // Re-lanzar si estamos en una transacción externa
|
||||
return false; // Devolver false si fue una operación aislada que falló
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Cerrar la conexión solo si la abrimos nosotros (no había transacción externa)
|
||||
if (ownConnection && connection.State == ConnectionState.Open)
|
||||
{
|
||||
await (connection as System.Data.Common.DbConnection)!.CloseAsync();
|
||||
}
|
||||
// Disponer de la conexión si la creamos nosotros
|
||||
if(ownConnection) (connection as IDisposable)?.Dispose();
|
||||
}
|
||||
}
|
||||
public async Task<bool> CheckIfSaldosExistForEmpresaAsync(int idEmpresa)
|
||||
var parameters = new
|
||||
{
|
||||
MontoAAgregar = montoAAgregar,
|
||||
Destino = destino,
|
||||
IdDestino = idDestino,
|
||||
IdEmpresa = idEmpresa,
|
||||
FechaActualizacion = DateTime.Now // O DateTime.UtcNow si prefieres
|
||||
};
|
||||
int rowsAffected = await connection.ExecuteAsync(sql, parameters, transaction: transaction);
|
||||
return rowsAffected == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al modificar saldo para {Destino} ID {IdDestino}, Empresa ID {IdEmpresa}.", destino, idDestino, idEmpresa);
|
||||
if (transaction != null) throw;
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (ownConnection && connection.State == ConnectionState.Open)
|
||||
{
|
||||
if (connection is System.Data.Common.DbConnection dbConn) await dbConn.CloseAsync(); else connection.Close();
|
||||
}
|
||||
if (ownConnection && connection is IDisposable d) d.Dispose(); // Mejorar dispose
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> CheckIfSaldosExistForEmpresaAsync(int idEmpresa)
|
||||
{
|
||||
var sql = "SELECT COUNT(1) FROM dbo.cue_Saldos WHERE Id_Empresa = @IdEmpresa";
|
||||
try
|
||||
@@ -130,5 +135,58 @@ namespace GestionIntegral.Api.Data.Repositories.Contables
|
||||
// O podrías devolver true para ser más conservador si la verificación es crítica.
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<Saldo>> GetSaldosParaGestionAsync(string? destinoFilter, int? idDestinoFilter, int? idEmpresaFilter)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT Id_Saldo AS IdSaldo, Destino, Id_Destino AS IdDestino, Monto, Id_Empresa AS IdEmpresa, FechaUltimaModificacion FROM dbo.cue_Saldos WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(destinoFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND Destino = @Destino");
|
||||
parameters.Add("Destino", destinoFilter);
|
||||
}
|
||||
if (idDestinoFilter.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Destino = @IdDestino");
|
||||
parameters.Add("IdDestino", idDestinoFilter.Value);
|
||||
}
|
||||
if (idEmpresaFilter.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Empresa = @IdEmpresa");
|
||||
parameters.Add("IdEmpresa", idEmpresaFilter.Value);
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY Destino, Id_Empresa, Id_Destino;");
|
||||
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Saldo>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
|
||||
public async Task<Saldo?> GetSaldoAsync(string destino, int idDestino, int idEmpresa, IDbTransaction? transaction = null)
|
||||
{
|
||||
const string sql = "SELECT Id_Saldo AS IdSaldo, Destino, Id_Destino AS IdDestino, Monto, Id_Empresa AS IdEmpresa, FechaUltimaModificacion FROM dbo.cue_Saldos WHERE Destino = @Destino AND Id_Destino = @IdDestino AND Id_Empresa = @IdEmpresa;";
|
||||
var conn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
if (transaction == null && conn.State != ConnectionState.Open) { if (conn is System.Data.Common.DbConnection dbConn) await dbConn.OpenAsync(); else conn.Open(); }
|
||||
|
||||
try
|
||||
{
|
||||
return await conn.QuerySingleOrDefaultAsync<Saldo>(sql, new { Destino = destino, IdDestino = idDestino, IdEmpresa = idEmpresa }, transaction);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (transaction == null && conn.State == ConnectionState.Open) { if (conn is System.Data.Common.DbConnection dbConn) await dbConn.CloseAsync(); else conn.Close(); }
|
||||
}
|
||||
}
|
||||
|
||||
public async Task CreateSaldoAjusteHistorialAsync(SaldoAjusteHistorial historialEntry, IDbTransaction transaction)
|
||||
{
|
||||
const string sql = @"
|
||||
INSERT INTO dbo.cue_SaldoAjustesHistorial
|
||||
(Destino, Id_Destino, Id_Empresa, MontoAjuste, SaldoAnterior, SaldoNuevo, Justificacion, FechaAjuste, Id_UsuarioAjuste)
|
||||
VALUES
|
||||
(@Destino, @IdDestino, @IdEmpresa, @MontoAjuste, @SaldoAnterior, @SaldoNuevo, @Justificacion, @FechaAjuste, @IdUsuarioAjuste);";
|
||||
|
||||
await transaction.Connection!.ExecuteAsync(sql, historialEntry, transaction);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,51 +21,56 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(Canilla Canilla, string NombreZona, string NombreEmpresa)>> GetAllAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos)
|
||||
public async Task<IEnumerable<(Canilla Canilla, string? NombreZona, string? NombreEmpresa)>> GetAllAsync(
|
||||
string? nomApeFilter,
|
||||
int? legajoFilter,
|
||||
bool? esAccionista,
|
||||
bool? soloActivos) // <<-- Parámetro aquí
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT
|
||||
c.Id_Canilla AS IdCanilla, c.Legajo, c.NomApe, c.Parada, c.Id_Zona AS IdZona,
|
||||
c.Accionista, c.Obs, c.Empresa, c.Baja, c.FechaBaja,
|
||||
z.Nombre AS NombreZona,
|
||||
ISNULL(e.Nombre, 'N/A (Accionista)') AS NombreEmpresa
|
||||
FROM dbo.dist_dtCanillas c
|
||||
INNER JOIN dbo.dist_dtZonas z ON c.Id_Zona = z.Id_Zona
|
||||
LEFT JOIN dbo.dist_dtEmpresas e ON c.Empresa = e.Id_Empresa
|
||||
WHERE 1=1");
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var sqlBuilder = new System.Text.StringBuilder(@"
|
||||
SELECT c.Id_Canilla AS IdCanilla, c.Legajo, c.NomApe, c.Parada, c.Id_Zona AS IdZona,
|
||||
c.Accionista, c.Obs, c.Empresa, c.Baja, c.FechaBaja,
|
||||
z.Nombre AS NombreZona,
|
||||
e.Nombre AS NombreEmpresa
|
||||
FROM dbo.dist_dtCanillas c
|
||||
LEFT JOIN dbo.dist_dtZonas z ON c.Id_Zona = z.Id_Zona
|
||||
LEFT JOIN dbo.dist_dtEmpresas e ON c.Empresa = e.Id_Empresa
|
||||
WHERE 1=1 "); // Cláusula base para añadir AND fácilmente
|
||||
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
if (soloActivos.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(soloActivos.Value ? " AND c.Baja = 0" : " AND c.Baja = 1");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(nomApeFilter))
|
||||
{
|
||||
sqlBuilder.Append(" AND c.NomApe LIKE @NomApeParam");
|
||||
parameters.Add("NomApeParam", $"%{nomApeFilter}%");
|
||||
sqlBuilder.Append(" AND c.NomApe LIKE @NomApeFilter ");
|
||||
parameters.Add("NomApeFilter", $"%{nomApeFilter}%");
|
||||
}
|
||||
if (legajoFilter.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND c.Legajo = @LegajoParam");
|
||||
parameters.Add("LegajoParam", legajoFilter.Value);
|
||||
sqlBuilder.Append(" AND c.Legajo = @LegajoFilter ");
|
||||
parameters.Add("LegajoFilter", legajoFilter.Value);
|
||||
}
|
||||
if (soloActivos.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND c.Baja = @BajaStatus ");
|
||||
parameters.Add("BajaStatus", !soloActivos.Value); // Si soloActivos es true, Baja debe ser false
|
||||
}
|
||||
|
||||
if (esAccionista.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND c.Accionista = @EsAccionista ");
|
||||
parameters.Add("EsAccionista", esAccionista.Value); // true para accionistas, false para no accionistas (canillitas)
|
||||
}
|
||||
|
||||
sqlBuilder.Append(" ORDER BY c.NomApe;");
|
||||
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<Canilla, string, string, (Canilla, string, string)>(
|
||||
sqlBuilder.ToString(),
|
||||
(canilla, nombreZona, nombreEmpresa) => (canilla, nombreZona, nombreEmpresa),
|
||||
parameters,
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Canillas. Filtros: NomApe='{NomApeFilter}', Legajo='{LegajoFilter}', SoloActivos='{SoloActivos}'", nomApeFilter, legajoFilter, soloActivos);
|
||||
return Enumerable.Empty<(Canilla, string, string)>();
|
||||
}
|
||||
var result = await connection.QueryAsync<Canilla, string, string, (Canilla, string?, string?)>(
|
||||
sqlBuilder.ToString(),
|
||||
(can, zona, emp) => (can, zona, emp),
|
||||
parameters,
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<(Canilla? Canilla, string? NombreZona, string? NombreEmpresa)> GetByIdAsync(int id)
|
||||
@@ -83,12 +88,12 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var result = await connection.QueryAsync<Canilla, string, string, (Canilla?, string?, string?)>(
|
||||
sql,
|
||||
(canilla, nombreZona, nombreEmpresa) => (canilla, nombreZona, nombreEmpresa),
|
||||
new { IdParam = id },
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
var result = await connection.QueryAsync<Canilla, string, string, (Canilla?, string?, string?)>(
|
||||
sql,
|
||||
(canilla, nombreZona, nombreEmpresa) => (canilla, nombreZona, nombreEmpresa),
|
||||
new { IdParam = id },
|
||||
splitOn: "NombreZona,NombreEmpresa"
|
||||
);
|
||||
return result.SingleOrDefault();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -160,9 +165,19 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdCanillaParam = insertedCanilla.IdCanilla, LegajoParam = insertedCanilla.Legajo, NomApeParam = insertedCanilla.NomApe, ParadaParam = insertedCanilla.Parada, IdZonaParam = insertedCanilla.IdZona,
|
||||
AccionistaParam = insertedCanilla.Accionista, ObsParam = insertedCanilla.Obs, EmpresaParam = insertedCanilla.Empresa, BajaParam = insertedCanilla.Baja, FechaBajaParam = insertedCanilla.FechaBaja,
|
||||
Id_UsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Creado"
|
||||
IdCanillaParam = insertedCanilla.IdCanilla,
|
||||
LegajoParam = insertedCanilla.Legajo,
|
||||
NomApeParam = insertedCanilla.NomApe,
|
||||
ParadaParam = insertedCanilla.Parada,
|
||||
IdZonaParam = insertedCanilla.IdZona,
|
||||
AccionistaParam = insertedCanilla.Accionista,
|
||||
ObsParam = insertedCanilla.Obs,
|
||||
EmpresaParam = insertedCanilla.Empresa,
|
||||
BajaParam = insertedCanilla.Baja,
|
||||
FechaBajaParam = insertedCanilla.FechaBaja,
|
||||
Id_UsuarioParam = idUsuario,
|
||||
FechaModParam = DateTime.Now,
|
||||
TipoModParam = "Creado"
|
||||
}, transaction);
|
||||
return insertedCanilla;
|
||||
}
|
||||
@@ -173,7 +188,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
var canillaActual = await connection.QuerySingleOrDefaultAsync<Canilla>(
|
||||
@"SELECT Id_Canilla AS IdCanilla, Legajo, NomApe, Parada, Id_Zona AS IdZona,
|
||||
Accionista, Obs, Empresa, Baja, FechaBaja
|
||||
FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanillaParam",
|
||||
FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanillaParam",
|
||||
new { IdCanillaParam = canillaAActualizar.IdCanilla }, transaction);
|
||||
if (canillaActual == null) throw new KeyNotFoundException("Canilla no encontrado para actualizar.");
|
||||
|
||||
@@ -187,13 +202,21 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
(Id_Canilla, Legajo, NomApe, Parada, Id_Zona, Accionista, Obs, Empresa, Baja, FechaBaja, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES (@IdCanillaParam, @LegajoParam, @NomApeParam, @ParadaParam, @IdZonaParam, @AccionistaParam, @ObsParam, @EmpresaParam, @BajaParam, @FechaBajaParam, @Id_UsuarioParam, @FechaModParam, @TipoModParam);";
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdCanillaParam = canillaActual.IdCanilla,
|
||||
LegajoParam = canillaActual.Legajo, NomApeParam = canillaActual.NomApe, ParadaParam = canillaActual.Parada, IdZonaParam = canillaActual.IdZona,
|
||||
AccionistaParam = canillaActual.Accionista, ObsParam = canillaActual.Obs, EmpresaParam = canillaActual.Empresa,
|
||||
BajaParam = canillaActual.Baja, FechaBajaParam = canillaActual.FechaBaja,
|
||||
Id_UsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModParam = "Actualizado"
|
||||
LegajoParam = canillaActual.Legajo,
|
||||
NomApeParam = canillaActual.NomApe,
|
||||
ParadaParam = canillaActual.Parada,
|
||||
IdZonaParam = canillaActual.IdZona,
|
||||
AccionistaParam = canillaActual.Accionista,
|
||||
ObsParam = canillaActual.Obs,
|
||||
EmpresaParam = canillaActual.Empresa,
|
||||
BajaParam = canillaActual.Baja,
|
||||
FechaBajaParam = canillaActual.FechaBaja,
|
||||
Id_UsuarioParam = idUsuario,
|
||||
FechaModParam = DateTime.Now,
|
||||
TipoModParam = "Actualizado"
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, canillaAActualizar, transaction);
|
||||
@@ -206,7 +229,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
var canillaActual = await connection.QuerySingleOrDefaultAsync<Canilla>(
|
||||
@"SELECT Id_Canilla AS IdCanilla, Legajo, NomApe, Parada, Id_Zona AS IdZona,
|
||||
Accionista, Obs, Empresa, Baja, FechaBaja
|
||||
FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanillaParam",
|
||||
FROM dbo.dist_dtCanillas WHERE Id_Canilla = @IdCanillaParam",
|
||||
new { IdCanillaParam = id }, transaction);
|
||||
if (canillaActual == null) throw new KeyNotFoundException("Canilla no encontrado para dar de baja/alta.");
|
||||
|
||||
@@ -218,10 +241,19 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
|
||||
await connection.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdCanillaParam = canillaActual.IdCanilla, LegajoParam = canillaActual.Legajo, NomApeParam = canillaActual.NomApe, ParadaParam = canillaActual.Parada, IdZonaParam = canillaActual.IdZona,
|
||||
AccionistaParam = canillaActual.Accionista, ObsParam = canillaActual.Obs, EmpresaParam = canillaActual.Empresa,
|
||||
BajaNuevaParam = darDeBaja, FechaBajaNuevaParam = (darDeBaja ? fechaBaja : null),
|
||||
Id_UsuarioParam = idUsuario, FechaModParam = DateTime.Now, TipoModHistParam = (darDeBaja ? "Baja" : "Alta")
|
||||
IdCanillaParam = canillaActual.IdCanilla,
|
||||
LegajoParam = canillaActual.Legajo,
|
||||
NomApeParam = canillaActual.NomApe,
|
||||
ParadaParam = canillaActual.Parada,
|
||||
IdZonaParam = canillaActual.IdZona,
|
||||
AccionistaParam = canillaActual.Accionista,
|
||||
ObsParam = canillaActual.Obs,
|
||||
EmpresaParam = canillaActual.Empresa,
|
||||
BajaNuevaParam = darDeBaja,
|
||||
FechaBajaNuevaParam = (darDeBaja ? fechaBaja : null),
|
||||
Id_UsuarioParam = idUsuario,
|
||||
FechaModParam = DateTime.Now,
|
||||
TipoModHistParam = (darDeBaja ? "Baja" : "Alta")
|
||||
}, transaction);
|
||||
|
||||
var rowsAffected = await connection.ExecuteAsync(sqlUpdate, new { BajaParam = darDeBaja, FechaBajaParam = (darDeBaja ? fechaBaja : null), IdCanillaParam = id }, transaction);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System; // Añadido para Exception
|
||||
@@ -61,6 +62,30 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
return Enumerable.Empty<(Distribuidor, string?)>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<DistribuidorDropdownDto?>> GetAllDropdownAsync()
|
||||
{
|
||||
var sqlBuilder = new StringBuilder(@"
|
||||
SELECT
|
||||
Id_Distribuidor AS IdDistribuidor, Nombre
|
||||
FROM dbo.dist_dtDistribuidores
|
||||
WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
sqlBuilder.Append(" ORDER BY Nombre;");
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<DistribuidorDropdownDto>(
|
||||
sqlBuilder.ToString(),
|
||||
parameters
|
||||
);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todos los Distribuidores.");
|
||||
return Enumerable.Empty<DistribuidorDropdownDto>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<(Distribuidor? Distribuidor, string? NombreZona)> GetByIdAsync(int id)
|
||||
{
|
||||
@@ -90,6 +115,25 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<DistribuidorLookupDto?> ObtenerLookupPorIdAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
SELECT
|
||||
Id_Distribuidor AS IdDistribuidor, Nombre
|
||||
FROM dbo.dist_dtDistribuidores
|
||||
WHERE Id_Distribuidor = @IdParam";
|
||||
try
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
return await connection.QuerySingleOrDefaultAsync<DistribuidorLookupDto>(sql, new { IdParam = id });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Distribuidor por ID: {IdDistribuidor}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Distribuidor?> GetByIdSimpleAsync(int id)
|
||||
{
|
||||
const string sql = @"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Data.Repositories;
|
||||
using GestionIntegral.Api.Dtos.Empresas;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
@@ -52,6 +53,25 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<EmpresaDropdownDto>> GetAllDropdownAsync()
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT Id_Empresa AS IdEmpresa, Nombre FROM dbo.dist_dtEmpresas WHERE 1=1");
|
||||
var parameters = new DynamicParameters();
|
||||
sqlBuilder.Append(" ORDER BY Nombre;");
|
||||
try
|
||||
{
|
||||
using (var connection = _connectionFactory.CreateConnection())
|
||||
{
|
||||
return await connection.QueryAsync<EmpresaDropdownDto>(sqlBuilder.ToString(), parameters);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener todas las Empresas.");
|
||||
return Enumerable.Empty<EmpresaDropdownDto>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Empresa?> GetByIdAsync(int id)
|
||||
{
|
||||
var sql = "SELECT Id_Empresa AS IdEmpresa, Nombre, Detalle FROM dbo.dist_dtEmpresas WHERE Id_Empresa = @Id";
|
||||
@@ -69,6 +89,23 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Empresa?> ObtenerLookupPorIdAsync(int id)
|
||||
{
|
||||
var sql = "SELECT Id_Empresa AS IdEmpresa, Nombre FROM dbo.dist_dtEmpresas WHERE Id_Empresa = @Id";
|
||||
try
|
||||
{
|
||||
using (var connection = _connectionFactory.CreateConnection())
|
||||
{
|
||||
return await connection.QuerySingleOrDefaultAsync<Empresa>(sql, new { Id = id });
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener Empresa por ID: {IdEmpresa}", id);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null)
|
||||
{
|
||||
var sqlBuilder = new StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtEmpresas WHERE Nombre = @Nombre");
|
||||
@@ -144,7 +181,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
}
|
||||
|
||||
// Insertar en historial
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new {
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdEmpresa = insertedEmpresa.IdEmpresa,
|
||||
insertedEmpresa.Nombre,
|
||||
insertedEmpresa.Detalle,
|
||||
@@ -172,7 +210,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
VALUES (@IdEmpresa, @NombreActual, @DetalleActual, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
|
||||
// Insertar en historial (estado anterior)
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new {
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdEmpresa = empresaActual.IdEmpresa,
|
||||
NombreActual = empresaActual.Nombre,
|
||||
DetalleActual = empresaActual.Detalle,
|
||||
@@ -182,7 +221,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
}, transaction: transaction);
|
||||
|
||||
// Actualizar principal
|
||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, new {
|
||||
var rowsAffected = await transaction.Connection!.ExecuteAsync(sqlUpdate, new
|
||||
{
|
||||
empresaAActualizar.Nombre,
|
||||
empresaAActualizar.Detalle,
|
||||
empresaAActualizar.IdEmpresa
|
||||
@@ -202,7 +242,8 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
VALUES (@IdEmpresa, @Nombre, @Detalle, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
|
||||
// Insertar en historial (estado antes de borrar)
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new {
|
||||
await transaction.Connection!.ExecuteAsync(sqlInsertHistorico, new
|
||||
{
|
||||
IdEmpresa = empresaActual.IdEmpresa,
|
||||
empresaActual.Nombre,
|
||||
empresaActual.Detalle,
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface ICanillaRepository
|
||||
{
|
||||
Task<IEnumerable<(Canilla Canilla, string NombreZona, string NombreEmpresa)>> GetAllAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos);
|
||||
Task<IEnumerable<(Canilla Canilla, string? NombreZona, string? NombreEmpresa)>> GetAllAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos, bool? esAccionista);
|
||||
Task<(Canilla? Canilla, string? NombreZona, string? NombreEmpresa)> GetByIdAsync(int id);
|
||||
Task<Canilla?> GetByIdSimpleAsync(int id); // Para obtener solo la entidad Canilla
|
||||
Task<Canilla?> CreateAsync(Canilla nuevoCanilla, int idUsuario, IDbTransaction transaction);
|
||||
|
||||
@@ -2,6 +2,7 @@ using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data;
|
||||
using GestionIntegral.Api.Dtos.Distribucion;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
@@ -16,5 +17,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
Task<bool> ExistsByNroDocAsync(string nroDoc, int? excludeIdDistribuidor = null);
|
||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeIdDistribuidor = null);
|
||||
Task<bool> IsInUseAsync(int id); // Verificar en dist_EntradasSalidas, cue_PagosDistribuidor, dist_PorcPago
|
||||
Task<IEnumerable<DistribuidorDropdownDto?>> GetAllDropdownAsync();
|
||||
Task<DistribuidorLookupDto?> ObtenerLookupPorIdAsync(int id);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data; // Para IDbTransaction
|
||||
using System.Data;
|
||||
using GestionIntegral.Api.Dtos.Empresas; // Para IDbTransaction
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
@@ -14,5 +15,7 @@ namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
Task<bool> DeleteAsync(int id, int idUsuario, IDbTransaction transaction); // Necesita transacción
|
||||
Task<bool> ExistsByNameAsync(string nombre, int? excludeId = null);
|
||||
Task<bool> IsInUseAsync(int id);
|
||||
Task<IEnumerable<EmpresaDropdownDto>> GetAllDropdownAsync();
|
||||
Task<Empresa?> ObtenerLookupPorIdAsync(int id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using GestionIntegral.Api.Dtos.Reportes;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data; // Para IDbTransaction
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public interface INovedadCanillaRepository
|
||||
{
|
||||
// Para obtener novedades y el nombre del canillita
|
||||
Task<IEnumerable<(NovedadCanilla Novedad, string NombreCanilla)>> GetByCanillaAsync(int idCanilla, DateTime? fechaDesde, DateTime? fechaHasta);
|
||||
Task<NovedadCanilla?> GetByIdAsync(int idNovedad);
|
||||
Task<NovedadCanilla?> CreateAsync(NovedadCanilla novedad, int idUsuario, IDbTransaction? transaction = null);
|
||||
Task<bool> UpdateAsync(NovedadCanilla novedad, int idUsuario, IDbTransaction? transaction = null);
|
||||
Task<bool> DeleteAsync(int idNovedad, int idUsuario, IDbTransaction? transaction = null);
|
||||
// Podrías añadir un método para verificar si existe una novedad para un canillita en una fecha específica si es necesario
|
||||
Task<bool> ExistsByCanillaAndFechaAsync(int idCanilla, DateTime fecha, int? excludeIdNovedad = null);
|
||||
Task<IEnumerable<NovedadesCanillasReporteDto>> GetReporteNovedadesAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta);
|
||||
Task<IEnumerable<CanillaGananciaReporteDto>> GetReporteGananciasAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
using Dapper;
|
||||
using GestionIntegral.Api.Models.Distribucion;
|
||||
using Microsoft.Extensions.Configuration; // Para IConfiguration
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using Microsoft.Data.SqlClient; // O el proveedor de tu BD
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GestionIntegral.Api.Dtos.Reportes;
|
||||
|
||||
namespace GestionIntegral.Api.Data.Repositories.Distribucion
|
||||
{
|
||||
public class NovedadCanillaRepository : INovedadCanillaRepository
|
||||
{
|
||||
private readonly DbConnectionFactory _connectionFactory; // Inyecta tu DbConnectionFactory
|
||||
private readonly ILogger<NovedadCanillaRepository> _logger;
|
||||
|
||||
public NovedadCanillaRepository(DbConnectionFactory connectionFactory, ILogger<NovedadCanillaRepository> logger)
|
||||
{
|
||||
_connectionFactory = connectionFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
private async Task LogHistorialAsync(NovedadCanilla novedadOriginal, int idUsuario, string tipoMod, IDbConnection connection, IDbTransaction? transaction)
|
||||
{
|
||||
var historial = new NovedadCanillaHistorial
|
||||
{
|
||||
IdNovedad = novedadOriginal.IdNovedad,
|
||||
IdCanilla = novedadOriginal.IdCanilla,
|
||||
Fecha = novedadOriginal.Fecha,
|
||||
Detalle = novedadOriginal.Detalle,
|
||||
IdUsuario = idUsuario,
|
||||
FechaMod = DateTime.Now,
|
||||
TipoMod = tipoMod
|
||||
};
|
||||
var sqlHistorial = @"
|
||||
INSERT INTO dbo.dist_dtNovedadesCanillas_H
|
||||
(Id_Novedad, Id_Canilla, Fecha, Detalle, Id_Usuario, FechaMod, TipoMod)
|
||||
VALUES
|
||||
(@IdNovedad, @IdCanilla, @Fecha, @Detalle, @IdUsuario, @FechaMod, @TipoMod);";
|
||||
await connection.ExecuteAsync(sqlHistorial, historial, transaction);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<(NovedadCanilla Novedad, string NombreCanilla)>> GetByCanillaAsync(int idCanilla, DateTime? fechaDesde, DateTime? fechaHasta)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var sqlBuilder = new System.Text.StringBuilder(@"
|
||||
SELECT
|
||||
n.Id_Novedad AS IdNovedad,
|
||||
n.Id_Canilla AS IdCanilla,
|
||||
n.Fecha,
|
||||
n.Detalle,
|
||||
c.NomApe AS NombreCanilla
|
||||
FROM dbo.dist_dtNovedadesCanillas n
|
||||
JOIN dbo.dist_dtCanillas c ON n.Id_Canilla = c.Id_Canilla
|
||||
WHERE n.Id_Canilla = @IdCanilla");
|
||||
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("IdCanilla", idCanilla);
|
||||
|
||||
if (fechaDesde.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND n.Fecha >= @FechaDesde");
|
||||
parameters.Add("FechaDesde", fechaDesde.Value.Date); // Solo fecha, sin hora
|
||||
}
|
||||
if (fechaHasta.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND n.Fecha <= @FechaHasta");
|
||||
// Para incluir todo el día de fechaHasta
|
||||
parameters.Add("FechaHasta", fechaHasta.Value.Date.AddDays(1).AddTicks(-1));
|
||||
}
|
||||
sqlBuilder.Append(" ORDER BY n.Fecha DESC, n.Id_Novedad DESC;");
|
||||
|
||||
var result = await connection.QueryAsync<NovedadCanilla, string, (NovedadCanilla, string)>(
|
||||
sqlBuilder.ToString(),
|
||||
(novedad, nombreCanilla) => (novedad, nombreCanilla),
|
||||
parameters,
|
||||
splitOn: "NombreCanilla"
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
public async Task<NovedadCanilla?> GetByIdAsync(int idNovedad)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var sql = "SELECT Id_Novedad AS IdNovedad, Id_Canilla AS IdCanilla, Fecha, Detalle FROM dbo.dist_dtNovedadesCanillas WHERE Id_Novedad = @IdNovedad;";
|
||||
return await connection.QuerySingleOrDefaultAsync<NovedadCanilla>(sql, new { IdNovedad = idNovedad });
|
||||
}
|
||||
|
||||
public async Task<bool> ExistsByCanillaAndFechaAsync(int idCanilla, DateTime fecha, int? excludeIdNovedad = null)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var sqlBuilder = new System.Text.StringBuilder("SELECT COUNT(1) FROM dbo.dist_dtNovedadesCanillas WHERE Id_Canilla = @IdCanilla AND Fecha = @Fecha");
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("IdCanilla", idCanilla);
|
||||
parameters.Add("Fecha", fecha.Date); // Comparar solo la fecha
|
||||
|
||||
if (excludeIdNovedad.HasValue)
|
||||
{
|
||||
sqlBuilder.Append(" AND Id_Novedad != @ExcludeIdNovedad");
|
||||
parameters.Add("ExcludeIdNovedad", excludeIdNovedad.Value);
|
||||
}
|
||||
|
||||
var count = await connection.ExecuteScalarAsync<int>(sqlBuilder.ToString(), parameters);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
public async Task<NovedadCanilla?> CreateAsync(NovedadCanilla novedad, int idUsuario, IDbTransaction? transaction = null)
|
||||
{
|
||||
var sql = @"
|
||||
INSERT INTO dbo.dist_dtNovedadesCanillas (Id_Canilla, Fecha, Detalle)
|
||||
VALUES (@IdCanilla, @Fecha, @Detalle);
|
||||
SELECT CAST(SCOPE_IDENTITY() as int);";
|
||||
|
||||
IDbConnection conn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
bool manageConnection = transaction == null; // Solo gestionar si no hay transacción externa
|
||||
|
||||
try
|
||||
{
|
||||
if (manageConnection && conn.State != ConnectionState.Open) await (conn as SqlConnection)!.OpenAsync();
|
||||
|
||||
var newId = await conn.QuerySingleAsync<int>(sql, novedad, transaction);
|
||||
novedad.IdNovedad = newId;
|
||||
await LogHistorialAsync(novedad, idUsuario, "Insertada", conn, transaction);
|
||||
return novedad;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al crear NovedadCanilla para Canilla ID: {IdCanilla}", novedad.IdCanilla);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (manageConnection && conn.State == ConnectionState.Open) conn.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> UpdateAsync(NovedadCanilla novedad, int idUsuario, IDbTransaction? transaction = null)
|
||||
{
|
||||
var novedadOriginal = await GetByIdAsync(novedad.IdNovedad); // Necesitamos el estado original para el log
|
||||
if (novedadOriginal == null) return false; // No se encontró
|
||||
|
||||
var sql = @"
|
||||
UPDATE dbo.dist_dtNovedadesCanillas SET
|
||||
Detalle = @Detalle
|
||||
-- No se permite cambiar IdCanilla ni Fecha de una novedad existente
|
||||
WHERE Id_Novedad = @IdNovedad;";
|
||||
|
||||
IDbConnection conn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
bool manageConnection = transaction == null;
|
||||
|
||||
try
|
||||
{
|
||||
if (manageConnection && conn.State != ConnectionState.Open) await (conn as SqlConnection)!.OpenAsync();
|
||||
|
||||
await LogHistorialAsync(novedadOriginal, idUsuario, "Modificada", conn, transaction); // Log con datos ANTES de actualizar
|
||||
var affectedRows = await conn.ExecuteAsync(sql, novedad, transaction);
|
||||
return affectedRows > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar NovedadCanilla ID: {IdNovedad}", novedad.IdNovedad);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (manageConnection && conn.State == ConnectionState.Open) conn.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DeleteAsync(int idNovedad, int idUsuario, IDbTransaction? transaction = null)
|
||||
{
|
||||
var novedadOriginal = await GetByIdAsync(idNovedad);
|
||||
if (novedadOriginal == null) return false;
|
||||
|
||||
var sql = "DELETE FROM dbo.dist_dtNovedadesCanillas WHERE Id_Novedad = @IdNovedad;";
|
||||
|
||||
IDbConnection conn = transaction?.Connection ?? _connectionFactory.CreateConnection();
|
||||
bool manageConnection = transaction == null;
|
||||
|
||||
try
|
||||
{
|
||||
if (manageConnection && conn.State != ConnectionState.Open) await (conn as SqlConnection)!.OpenAsync();
|
||||
|
||||
await LogHistorialAsync(novedadOriginal, idUsuario, "Eliminada", conn, transaction);
|
||||
var affectedRows = await conn.ExecuteAsync(sql, new { IdNovedad = idNovedad }, transaction);
|
||||
return affectedRows > 0;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al eliminar NovedadCanilla ID: {IdNovedad}", idNovedad);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (manageConnection && conn.State == ConnectionState.Open) conn.Close();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<NovedadesCanillasReporteDto>> GetReporteNovedadesAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var parameters = new
|
||||
{
|
||||
idEmpresa,
|
||||
fechaDesde = fechaDesde.Date, // Enviar solo la fecha
|
||||
fechaHasta = fechaHasta.Date.AddDays(1).AddTicks(-1) // Para incluir todo el día hasta las 23:59:59.999...
|
||||
};
|
||||
// El nombre del SP en el archivo es SP_DistCanillasNovedades
|
||||
return await connection.QueryAsync<NovedadesCanillasReporteDto>(
|
||||
"dbo.SP_DistCanillasNovedades", // Asegúrate que el nombre del SP sea exacto
|
||||
parameters,
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<CanillaGananciaReporteDto>> GetReporteGananciasAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta)
|
||||
{
|
||||
using var connection = _connectionFactory.CreateConnection();
|
||||
var parameters = new
|
||||
{
|
||||
idEmpresa,
|
||||
fechaDesde = fechaDesde.Date,
|
||||
fechaHasta = fechaHasta.Date // El SP SP_DistCanillasGanancias maneja el rango inclusivo directamente
|
||||
};
|
||||
return await connection.QueryAsync<CanillaGananciaReporteDto>(
|
||||
"dbo.SP_DistCanillasGanancias", // Nombre del SP
|
||||
parameters,
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,5 +43,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
|
||||
Task<(IEnumerable<ListadoDistribucionDistSimpleDto> Simple, IEnumerable<ListadoDistribucionDistPromedioDiaDto> Promedios, string? Error)> ObtenerListadoDistribucionDistribuidoresAsync(int idDistribuidor, int idPublicacion, DateTime fechaDesde, DateTime fechaHasta);
|
||||
Task<IEnumerable<LiquidacionCanillaDetalleDto>> GetLiquidacionCanillaDetalleAsync(DateTime fecha, int idCanilla);
|
||||
Task<IEnumerable<LiquidacionCanillaGananciaDto>> GetLiquidacionCanillaGananciasAsync(DateTime fecha, int idCanilla);
|
||||
Task<IEnumerable<ListadoDistCanMensualDiariosDto>> GetReporteMensualDiariosAsync(DateTime fechaDesde, DateTime fechaHasta, bool esAccionista);
|
||||
Task<IEnumerable<ListadoDistCanMensualPubDto>> GetReporteMensualPorPublicacionAsync(DateTime fechaDesde, DateTime fechaHasta, bool esAccionista);
|
||||
}
|
||||
}
|
||||
@@ -481,39 +481,71 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<LiquidacionCanillaDetalleDto>> GetLiquidacionCanillaDetalleAsync(DateTime fecha, int idCanilla)
|
||||
{
|
||||
const string spName = "dbo.SP_DistCanillasLiquidacion";
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("@fecha", fecha, DbType.DateTime);
|
||||
parameters.Add("@idCanilla", idCanilla, DbType.Int32);
|
||||
try
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<LiquidacionCanillaDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure);
|
||||
{
|
||||
const string spName = "dbo.SP_DistCanillasLiquidacion";
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("@fecha", fecha, DbType.DateTime);
|
||||
parameters.Add("@idCanilla", idCanilla, DbType.Int32);
|
||||
try
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<LiquidacionCanillaDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error SP {SPName} para Liquidacion Canilla Detalle. Fecha: {Fecha}, Canilla: {IdCanilla}", spName, fecha, idCanilla);
|
||||
return Enumerable.Empty<LiquidacionCanillaDetalleDto>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error SP {SPName} para Liquidacion Canilla Detalle. Fecha: {Fecha}, Canilla: {IdCanilla}", spName, fecha, idCanilla);
|
||||
return Enumerable.Empty<LiquidacionCanillaDetalleDto>();
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<LiquidacionCanillaGananciaDto>> GetLiquidacionCanillaGananciasAsync(DateTime fecha, int idCanilla)
|
||||
{
|
||||
const string spName = "dbo.SP_DistCanillasLiquidacionGanancias";
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("@fecha", fecha, DbType.DateTime);
|
||||
parameters.Add("@idCanilla", idCanilla, DbType.Int32);
|
||||
try
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<LiquidacionCanillaGananciaDto>(spName, parameters, commandType: CommandType.StoredProcedure);
|
||||
public async Task<IEnumerable<LiquidacionCanillaGananciaDto>> GetLiquidacionCanillaGananciasAsync(DateTime fecha, int idCanilla)
|
||||
{
|
||||
const string spName = "dbo.SP_DistCanillasLiquidacionGanancias";
|
||||
var parameters = new DynamicParameters();
|
||||
parameters.Add("@fecha", fecha, DbType.DateTime);
|
||||
parameters.Add("@idCanilla", idCanilla, DbType.Int32);
|
||||
try
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
return await connection.QueryAsync<LiquidacionCanillaGananciaDto>(spName, parameters, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error SP {SPName} para Liquidacion Canilla Ganancias. Fecha: {Fecha}, Canilla: {IdCanilla}", spName, fecha, idCanilla);
|
||||
return Enumerable.Empty<LiquidacionCanillaGananciaDto>();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error SP {SPName} para Liquidacion Canilla Ganancias. Fecha: {Fecha}, Canilla: {IdCanilla}", spName, fecha, idCanilla);
|
||||
return Enumerable.Empty<LiquidacionCanillaGananciaDto>();
|
||||
|
||||
public async Task<IEnumerable<ListadoDistCanMensualDiariosDto>> GetReporteMensualDiariosAsync(DateTime fechaDesde, DateTime fechaHasta, bool esAccionista)
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
var parameters = new
|
||||
{
|
||||
fechaDesde = fechaDesde.Date,
|
||||
fechaHasta = fechaHasta.Date, // El SP parece manejar el rango incluyendo el último día
|
||||
accionista = esAccionista
|
||||
};
|
||||
return await connection.QueryAsync<ListadoDistCanMensualDiariosDto>(
|
||||
"dbo.SP_DistCanillasAccConImporteEntreFechasDiarios",
|
||||
parameters,
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<ListadoDistCanMensualPubDto>> GetReporteMensualPorPublicacionAsync(DateTime fechaDesde, DateTime fechaHasta, bool esAccionista)
|
||||
{
|
||||
using var connection = _dbConnectionFactory.CreateConnection();
|
||||
var parameters = new
|
||||
{
|
||||
fechaDesde = fechaDesde.Date,
|
||||
fechaHasta = fechaHasta.Date,
|
||||
accionista = esAccionista
|
||||
};
|
||||
return await connection.QueryAsync<ListadoDistCanMensualPubDto>(
|
||||
"dbo.SP_DistCanillasAccConImporteEntreFechas",
|
||||
parameters,
|
||||
commandType: CommandType.StoredProcedure
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user