Refinamiento de permisos y ajustes en controles. Añade gestión sobre saldos y visualización. Entre otros..

This commit is contained in:
2025-06-06 18:33:09 -03:00
parent 8fb94f8cef
commit 35e24ab7d2
104 changed files with 5917 additions and 1205 deletions

View File

@@ -54,11 +54,11 @@ namespace GestionIntegral.Api.Services.Distribucion
};
}
public async Task<IEnumerable<CanillaDto>> ObtenerTodosAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos)
public async Task<IEnumerable<CanillaDto>> ObtenerTodosAsync(string? nomApeFilter, int? legajoFilter, bool? esAccionista, bool? soloActivos)
{
var canillasData = await _canillaRepository.GetAllAsync(nomApeFilter, legajoFilter, soloActivos);
var data = await _canillaRepository.GetAllAsync(nomApeFilter, legajoFilter, soloActivos, esAccionista);
// Filtrar nulos y asegurar al compilador que no hay nulos en la lista final
return canillasData.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!);
return data.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!);
}
public async Task<CanillaDto?> ObtenerPorIdAsync(int id)
@@ -81,11 +81,11 @@ namespace GestionIntegral.Api.Services.Distribucion
}
if (createDto.Empresa != 0) // Solo validar empresa si no es 0
{
var empresa = await _empresaRepository.GetByIdAsync(createDto.Empresa);
if(empresa == null)
{
var empresa = await _empresaRepository.GetByIdAsync(createDto.Empresa);
if (empresa == null)
{
return (null, "La empresa seleccionada no es válida.");
}
}
}
// CORREGIDO: Usar directamente el valor booleano
@@ -122,7 +122,7 @@ namespace GestionIntegral.Api.Services.Distribucion
if (canillaCreado == null) throw new DataException("Error al crear el canillita.");
transaction.Commit();
// Para el DTO de respuesta, necesitamos NombreZona y NombreEmpresa
string nombreEmpresaParaDto = "N/A (Accionista)";
if (canillaCreado.Empresa != 0)
@@ -131,12 +131,20 @@ namespace GestionIntegral.Api.Services.Distribucion
nombreEmpresaParaDto = empresaData?.Nombre ?? "Empresa Desconocida";
}
var dtoCreado = new CanillaDto {
IdCanilla = canillaCreado.IdCanilla, Legajo = canillaCreado.Legajo, NomApe = canillaCreado.NomApe,
Parada = canillaCreado.Parada, IdZona = canillaCreado.IdZona, NombreZona = zona.Nombre, // Usar nombre de zona ya obtenido
Accionista = canillaCreado.Accionista, Obs = canillaCreado.Obs, Empresa = canillaCreado.Empresa,
NombreEmpresa = nombreEmpresaParaDto,
Baja = canillaCreado.Baja, FechaBaja = null
var dtoCreado = new CanillaDto
{
IdCanilla = canillaCreado.IdCanilla,
Legajo = canillaCreado.Legajo,
NomApe = canillaCreado.NomApe,
Parada = canillaCreado.Parada,
IdZona = canillaCreado.IdZona,
NombreZona = zona.Nombre, // Usar nombre de zona ya obtenido
Accionista = canillaCreado.Accionista,
Obs = canillaCreado.Obs,
Empresa = canillaCreado.Empresa,
NombreEmpresa = nombreEmpresaParaDto,
Baja = canillaCreado.Baja,
FechaBaja = null
};
_logger.LogInformation("Canilla ID {IdCanilla} creado por Usuario ID {IdUsuario}.", canillaCreado.IdCanilla, idUsuario);
@@ -144,7 +152,7 @@ namespace GestionIntegral.Api.Services.Distribucion
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch {}
try { transaction.Rollback(); } catch { }
_logger.LogError(ex, "Error CrearAsync Canilla: {NomApe}", createDto.NomApe);
return (null, $"Error interno al crear el canillita: {ex.Message}");
}
@@ -165,11 +173,11 @@ namespace GestionIntegral.Api.Services.Distribucion
}
if (updateDto.Empresa != 0) // Solo validar empresa si no es 0
{
var empresa = await _empresaRepository.GetByIdAsync(updateDto.Empresa);
if(empresa == null)
{
var empresa = await _empresaRepository.GetByIdAsync(updateDto.Empresa);
if (empresa == null)
{
return (false, "La empresa seleccionada no es válida.");
}
}
}
// Usar directamente el valor booleano para Accionista
@@ -200,18 +208,19 @@ namespace GestionIntegral.Api.Services.Distribucion
try
{
var actualizado = await _canillaRepository.UpdateAsync(canillaExistente, idUsuario, transaction);
if (!actualizado) throw new DataException("Error al actualizar el canillita.");
if (!actualizado) throw new DataException("Error al actualizar el canillita.");
transaction.Commit();
_logger.LogInformation("Canilla ID {IdCanilla} actualizado por Usuario ID {IdUsuario}.", id, idUsuario);
return (true, null);
}
catch (KeyNotFoundException) {
try { transaction.Rollback(); } catch {}
catch (KeyNotFoundException)
{
try { transaction.Rollback(); } catch { }
return (false, "Canillita no encontrado durante la actualización.");
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch {}
try { transaction.Rollback(); } catch { }
_logger.LogError(ex, "Error ActualizarAsync Canilla ID: {IdCanilla}", id);
return (false, $"Error interno al actualizar el canillita: {ex.Message}");
}
@@ -240,13 +249,14 @@ namespace GestionIntegral.Api.Services.Distribucion
_logger.LogInformation("Estado de baja cambiado a {EstadoBaja} para Canilla ID {IdCanilla} por Usuario ID {IdUsuario}.", darDeBaja, id, idUsuario);
return (true, null);
}
catch (KeyNotFoundException) {
try { transaction.Rollback(); } catch {}
catch (KeyNotFoundException)
{
try { transaction.Rollback(); } catch { }
return (false, "Canillita no encontrado durante el cambio de estado de baja.");
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch {}
try { transaction.Rollback(); } catch { }
_logger.LogError(ex, "Error ToggleBajaAsync Canilla ID: {IdCanilla}", id);
return (false, $"Error interno al cambiar estado de baja: {ex.Message}");
}

View File

@@ -66,11 +66,31 @@ namespace GestionIntegral.Api.Services.Distribucion
return data.Select(MapToDto).Where(dto => dto != null).Select(dto => dto!);
}
public async Task<IEnumerable<DistribuidorDropdownDto>> GetAllDropdownAsync()
{
var data = await _distribuidorRepository.GetAllDropdownAsync();
// Asegurar que el resultado no sea nulo y no contiene elementos nulos
if (data == null)
{
return new List<DistribuidorDropdownDto>
{
new DistribuidorDropdownDto { IdDistribuidor = 0, Nombre = "No hay distribuidores disponibles" }
};
}
return data.Where(x => x != null)!;
}
public async Task<DistribuidorDto?> ObtenerPorIdAsync(int id)
{
var data = await _distribuidorRepository.GetByIdAsync(id);
// MapToDto ahora devuelve DistribuidorDto?
return MapToDto(data);
}
public async Task<DistribuidorLookupDto?> ObtenerLookupPorIdAsync(int id)
{
var data = await _distribuidorRepository.ObtenerLookupPorIdAsync(id);
return data;
}
public async Task<(DistribuidorDto? Distribuidor, string? Error)> CrearAsync(CreateDistribuidorDto createDto, int idUsuario)

View File

@@ -42,10 +42,22 @@ namespace GestionIntegral.Api.Services.Distribucion
Detalle = e.Detalle
});
}
public async Task<IEnumerable<EmpresaDropdownDto>> ObtenerParaDropdown()
{
// El repositorio ya devuelve solo las activas si es necesario
var empresas = await _empresaRepository.GetAllDropdownAsync();
// Mapeo Entidad -> DTO
return empresas.Select(e => new EmpresaDropdownDto
{
IdEmpresa = e.IdEmpresa,
Nombre = e.Nombre
});
}
public async Task<EmpresaDto?> ObtenerPorIdAsync(int id)
{
// El repositorio ya devuelve solo las activas si es necesario
// El repositorio ya devuelve solo las activas si es necesario
var empresa = await _empresaRepository.GetByIdAsync(id);
if (empresa == null) return null;
// Mapeo Entidad -> DTO
@@ -57,6 +69,19 @@ namespace GestionIntegral.Api.Services.Distribucion
};
}
public async Task<EmpresaLookupDto?> ObtenerLookupPorIdAsync(int id)
{
// El repositorio ya devuelve solo las activas si es necesario
var empresa = await _empresaRepository.ObtenerLookupPorIdAsync(id);
if (empresa == null) return null;
// Mapeo Entidad -> DTO
return new EmpresaLookupDto
{
IdEmpresa = empresa.IdEmpresa,
Nombre = empresa.Nombre
};
}
public async Task<(EmpresaDto? Empresa, string? Error)> CrearAsync(CreateEmpresaDto createDto, int idUsuario)
{
// Validación de negocio: Nombre duplicado
@@ -234,5 +259,5 @@ namespace GestionIntegral.Api.Services.Distribucion
}
// --- Fin Transacción ---
}
}
}
}

View File

@@ -6,7 +6,7 @@ namespace GestionIntegral.Api.Services.Distribucion
{
public interface ICanillaService
{
Task<IEnumerable<CanillaDto>> ObtenerTodosAsync(string? nomApeFilter, int? legajoFilter, bool? soloActivos);
Task<IEnumerable<CanillaDto>> ObtenerTodosAsync(string? nomApeFilter, int? legajoFilter, bool? esAccionista, bool? soloActivos);
Task<CanillaDto?> ObtenerPorIdAsync(int id);
Task<(CanillaDto? Canilla, string? Error)> CrearAsync(CreateCanillaDto createDto, int idUsuario);
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateCanillaDto updateDto, int idUsuario);

View File

@@ -11,5 +11,7 @@ namespace GestionIntegral.Api.Services.Distribucion
Task<(DistribuidorDto? Distribuidor, string? Error)> CrearAsync(CreateDistribuidorDto createDto, int idUsuario);
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateDistribuidorDto updateDto, int idUsuario);
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
Task<IEnumerable<DistribuidorDropdownDto>> GetAllDropdownAsync();
Task<DistribuidorLookupDto?> ObtenerLookupPorIdAsync(int id);
}
}

View File

@@ -11,5 +11,7 @@ namespace GestionIntegral.Api.Services.Distribucion
Task<(EmpresaDto? Empresa, string? Error)> CrearAsync(CreateEmpresaDto createDto, int idUsuario);
Task<(bool Exito, string? Error)> ActualizarAsync(int id, UpdateEmpresaDto updateDto, int idUsuario);
Task<(bool Exito, string? Error)> EliminarAsync(int id, int idUsuario);
Task<IEnumerable<EmpresaDropdownDto>> ObtenerParaDropdown();
Task<EmpresaLookupDto?> ObtenerLookupPorIdAsync(int id);
}
}

View File

@@ -0,0 +1,19 @@
using GestionIntegral.Api.Dtos.Distribucion;
using GestionIntegral.Api.Dtos.Reportes;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GestionIntegral.Api.Services.Distribucion
{
public interface INovedadCanillaService
{
Task<IEnumerable<NovedadCanillaDto>> ObtenerPorCanillaAsync(int idCanilla, DateTime? fechaDesde, DateTime? fechaHasta);
Task<NovedadCanillaDto?> ObtenerPorIdAsync(int idNovedad);
Task<(NovedadCanillaDto? Novedad, string? Error)> CrearAsync(CreateNovedadCanillaDto createDto, int idUsuario);
Task<(bool Exito, string? Error)> ActualizarAsync(int idNovedad, UpdateNovedadCanillaDto updateDto, int idUsuario);
Task<(bool Exito, string? Error)> EliminarAsync(int idNovedad, int idUsuario);
Task<IEnumerable<NovedadesCanillasReporteDto>> ObtenerReporteNovedadesAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta);
Task<IEnumerable<CanillaGananciaReporteDto>> ObtenerReporteGananciasAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta);
}
}

View File

@@ -0,0 +1,254 @@
// En Services/Distribucion (o donde corresponda)
using GestionIntegral.Api.Data; // Para DbConnectionFactory
using GestionIntegral.Api.Data.Repositories.Distribucion;
using GestionIntegral.Api.Dtos.Distribucion;
using GestionIntegral.Api.Dtos.Reportes;
using GestionIntegral.Api.Models.Distribucion; // Asegúrate que el modelo Canilla tenga NomApe
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Data; // Para IDbTransaction
using System.Linq;
using System.Threading.Tasks;
namespace GestionIntegral.Api.Services.Distribucion
{
public class NovedadCanillaService : INovedadCanillaService
{
private readonly INovedadCanillaRepository _novedadRepository;
private readonly ICanillaRepository _canillaRepository;
private readonly DbConnectionFactory _connectionFactory;
private readonly ILogger<NovedadCanillaService> _logger;
public NovedadCanillaService(
INovedadCanillaRepository novedadRepository,
ICanillaRepository canillaRepository,
DbConnectionFactory connectionFactory,
ILogger<NovedadCanillaService> logger)
{
_novedadRepository = novedadRepository;
_canillaRepository = canillaRepository;
_connectionFactory = connectionFactory;
_logger = logger;
}
private NovedadCanillaDto MapToDto((NovedadCanilla Novedad, string NombreCanilla) data)
{
return new NovedadCanillaDto
{
IdNovedad = data.Novedad.IdNovedad,
IdCanilla = data.Novedad.IdCanilla,
NombreCanilla = data.NombreCanilla, // Viene de la tupla en GetByCanillaAsync
Fecha = data.Novedad.Fecha,
Detalle = data.Novedad.Detalle
};
}
private NovedadCanillaDto MapToDto(NovedadCanilla data, string nombreCanilla)
{
return new NovedadCanillaDto
{
IdNovedad = data.IdNovedad,
IdCanilla = data.IdCanilla,
NombreCanilla = nombreCanilla,
Fecha = data.Fecha,
Detalle = data.Detalle
};
}
public async Task<IEnumerable<NovedadCanillaDto>> ObtenerPorCanillaAsync(int idCanilla, DateTime? fechaDesde, DateTime? fechaHasta)
{
var data = await _novedadRepository.GetByCanillaAsync(idCanilla, fechaDesde, fechaHasta);
return data.Select(MapToDto);
}
public async Task<NovedadCanillaDto?> ObtenerPorIdAsync(int idNovedad)
{
var novedad = await _novedadRepository.GetByIdAsync(idNovedad);
if (novedad == null) return null;
// Asumiendo que _canillaRepository.GetByIdAsync devuelve una tupla (Canilla? Canilla, ...)
// O un DTO CanillaDto que tiene NomApe
var canillaDataResult = await _canillaRepository.GetByIdAsync(novedad.IdCanilla);
// Ajusta esto según lo que realmente devuelva GetByIdAsync
// Si devuelve CanillaDto:
// string nombreCanilla = canillaDataResult?.NomApe ?? "Desconocido";
// Si devuelve la tupla (Canilla? Canilla, string? NombreZona, string? NombreEmpresa):
string nombreCanilla = canillaDataResult.Canilla?.NomApe ?? "Desconocido";
return MapToDto(novedad, nombreCanilla);
}
public async Task<(NovedadCanillaDto? Novedad, string? Error)> CrearAsync(CreateNovedadCanillaDto createDto, int idUsuario)
{
// Asegúrate que GetByIdSimpleAsync devuelva un objeto Canilla o algo con NomApe
var canilla = await _canillaRepository.GetByIdSimpleAsync(createDto.IdCanilla);
if (canilla == null)
{
return (null, "El canillita especificado no existe.");
}
var nuevaNovedad = new NovedadCanilla
{
IdCanilla = createDto.IdCanilla,
Fecha = createDto.Fecha.Date,
Detalle = createDto.Detalle
};
using var connection = _connectionFactory.CreateConnection();
// Abre la conexión explícitamente si no se usa una transacción externa
if (connection is System.Data.Common.DbConnection dbConn && connection.State != ConnectionState.Open)
{
await dbConn.OpenAsync();
}
else if (connection.State != ConnectionState.Open)
{
connection.Open();
}
using var transaction = connection.BeginTransaction();
try
{
var creada = await _novedadRepository.CreateAsync(nuevaNovedad, idUsuario, transaction);
if (creada == null)
{
transaction.Rollback();
return (null, "Error al guardar la novedad en la base de datos.");
}
transaction.Commit();
_logger.LogInformation("Novedad ID {IdNovedad} para Canilla ID {IdCanilla} creada por Usuario ID {UserId}.", creada.IdNovedad, creada.IdCanilla, idUsuario);
// Asegúrate que 'canilla.NomApe' sea accesible. Si GetByIdSimpleAsync devuelve la entidad Canilla, esto está bien.
return (MapToDto(creada, canilla.NomApe ?? "Canilla sin nombre"), null);
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error durante Rollback en CrearAsync NovedadCanilla."); }
_logger.LogError(ex, "Error CrearAsync NovedadCanilla para Canilla ID: {IdCanilla}", createDto.IdCanilla);
return (null, $"Error interno al crear la novedad: {ex.Message}");
}
finally
{
if (connection.State == ConnectionState.Open) connection.Close();
}
}
public async Task<(bool Exito, string? Error)> ActualizarAsync(int idNovedad, UpdateNovedadCanillaDto updateDto, int idUsuario)
{
var existente = await _novedadRepository.GetByIdAsync(idNovedad);
if (existente == null)
{
return (false, "Novedad no encontrada.");
}
existente.Detalle = updateDto.Detalle;
using var connection = _connectionFactory.CreateConnection();
if (connection is System.Data.Common.DbConnection dbConn && connection.State != ConnectionState.Open)
{
await dbConn.OpenAsync();
}
else if (connection.State != ConnectionState.Open)
{
connection.Open();
}
using var transaction = connection.BeginTransaction();
try
{
var actualizado = await _novedadRepository.UpdateAsync(existente, idUsuario, transaction);
if (!actualizado)
{
transaction.Rollback();
return (false, "Error al actualizar la novedad en la base de datos.");
}
transaction.Commit();
_logger.LogInformation("Novedad ID {IdNovedad} actualizada por Usuario ID {UserId}.", idNovedad, idUsuario);
return (true, null);
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error durante Rollback en ActualizarAsync NovedadCanilla."); }
_logger.LogError(ex, "Error ActualizarAsync NovedadCanilla ID: {IdNovedad}", idNovedad);
return (false, $"Error interno al actualizar la novedad: {ex.Message}");
}
finally
{
if (connection.State == ConnectionState.Open) connection.Close();
}
}
public async Task<(bool Exito, string? Error)> EliminarAsync(int idNovedad, int idUsuario)
{
var existente = await _novedadRepository.GetByIdAsync(idNovedad);
if (existente == null)
{
return (false, "Novedad no encontrada.");
}
using var connection = _connectionFactory.CreateConnection();
if (connection is System.Data.Common.DbConnection dbConn && connection.State != ConnectionState.Open)
{
await dbConn.OpenAsync();
}
else if (connection.State != ConnectionState.Open)
{
connection.Open();
}
using var transaction = connection.BeginTransaction();
try
{
var eliminado = await _novedadRepository.DeleteAsync(idNovedad, idUsuario, transaction);
if (!eliminado)
{
transaction.Rollback();
return (false, "Error al eliminar la novedad de la base de datos.");
}
transaction.Commit();
_logger.LogInformation("Novedad ID {IdNovedad} eliminada por Usuario ID {UserId}.", idNovedad, idUsuario);
return (true, null);
}
catch (Exception ex)
{
try { transaction.Rollback(); } catch (Exception rbEx) { _logger.LogError(rbEx, "Error durante Rollback en EliminarAsync NovedadCanilla."); }
_logger.LogError(ex, "Error EliminarAsync NovedadCanilla ID: {IdNovedad}", idNovedad);
return (false, $"Error interno al eliminar la novedad: {ex.Message}");
}
finally
{
if (connection.State == ConnectionState.Open) connection.Close();
}
}
public async Task<IEnumerable<NovedadesCanillasReporteDto>> ObtenerReporteNovedadesAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta)
{
// Podría añadir validaciones o lógica de negocio adicional si fuera necesario
// antes de llamar al repositorio. Por ahora, es una llamada directa.
try
{
return await _novedadRepository.GetReporteNovedadesAsync(idEmpresa, fechaDesde, fechaHasta);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al obtener datos para el reporte de novedades de canillitas. Empresa: {IdEmpresa}, Desde: {FechaDesde}, Hasta: {FechaHasta}", idEmpresa, fechaDesde, fechaHasta);
// Podría relanzar o devolver una lista vacía con un mensaje de error,
// dependiendo de cómo quiera manejar los errores en la capa de servicio.
// Por simplicidad, relanzamos para que el controlador lo maneje.
throw;
}
}
public async Task<IEnumerable<CanillaGananciaReporteDto>> ObtenerReporteGananciasAsync(int idEmpresa, DateTime fechaDesde, DateTime fechaHasta)
{
try
{
return await _novedadRepository.GetReporteGananciasAsync(idEmpresa, fechaDesde, fechaHasta);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al obtener datos para el reporte de ganancias de canillitas. Empresa: {IdEmpresa}, Desde: {FechaDesde}, Hasta: {FechaHasta}", idEmpresa, fechaDesde, fechaHasta);
throw;
}
}
}
}