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

@@ -11,6 +11,7 @@ using GestionIntegral.Api.Data.Repositories.Impresion;
using System.IO;
using System.Linq;
using GestionIntegral.Api.Data.Repositories.Distribucion;
using GestionIntegral.Api.Services.Distribucion;
namespace GestionIntegral.Api.Controllers
{
@@ -25,6 +26,7 @@ namespace GestionIntegral.Api.Controllers
private readonly IPublicacionRepository _publicacionRepository;
private readonly IEmpresaRepository _empresaRepository;
private readonly IDistribuidorRepository _distribuidorRepository; // Para obtener el nombre del distribuidor
private readonly INovedadCanillaService _novedadCanillaService;
// Permisos
@@ -36,22 +38,25 @@ namespace GestionIntegral.Api.Controllers
private const string PermisoVerBalanceCuentas = "RR001";
private const string PermisoVerReporteTiradas = "RR008";
private const string PermisoVerReporteConsumoBobinas = "RR007";
private const string PermisoVerReporteNovedadesCanillas = "RR004";
private const string PermisoVerReporteListadoDistMensual = "RR009";
public ReportesController(
IReportesService reportesService, // <--- CORREGIDO
IReportesService reportesService,
INovedadCanillaService novedadCanillaService,
ILogger<ReportesController> logger,
IPlantaRepository plantaRepository,
IPublicacionRepository publicacionRepository,
IEmpresaRepository empresaRepository,
IDistribuidorRepository distribuidorRepository) // Añadido
IDistribuidorRepository distribuidorRepository)
{
_reportesService = reportesService; // <--- CORREGIDO
_reportesService = reportesService;
_novedadCanillaService = novedadCanillaService;
_logger = logger;
_plantaRepository = plantaRepository;
_publicacionRepository = publicacionRepository;
_empresaRepository = empresaRepository;
_distribuidorRepository = distribuidorRepository; // Añadido
_distribuidorRepository = distribuidorRepository;
}
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
@@ -1457,5 +1462,277 @@ namespace GestionIntegral.Api.Controllers
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al generar el PDF del ticket.");
}
}
// GET: api/reportes/novedades-canillas
// Obtiene los datos para el reporte de novedades de canillitas
[HttpGet("novedades-canillas")]
[ProducesResponseType(typeof(IEnumerable<NovedadesCanillasReporteDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)] // Si no hay datos
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetReporteNovedadesCanillasData(
[FromQuery] int idEmpresa,
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta)
{
if (!TienePermiso(PermisoVerReporteNovedadesCanillas))
{
_logger.LogWarning("Acceso denegado a GetReporteNovedadesCanillasData. Usuario: {User}", User.Identity?.Name ?? "Desconocido");
return Forbid();
}
if (fechaDesde > fechaHasta)
{
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
}
try
{
var reporteData = await _novedadCanillaService.ObtenerReporteNovedadesAsync(idEmpresa, fechaDesde, fechaHasta);
if (reporteData == null || !reporteData.Any())
{
// Devolver Ok con array vacío en lugar de NotFound para que el frontend pueda manejarlo como "sin datos"
return Ok(Enumerable.Empty<NovedadesCanillasReporteDto>());
}
return Ok(reporteData);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al generar datos para el reporte de novedades de canillitas. Empresa: {IdEmpresa}, Desde: {FechaDesde}, Hasta: {FechaHasta}", idEmpresa, fechaDesde, fechaHasta);
return StatusCode(StatusCodes.Status500InternalServerError, new { message = "Error interno al generar el reporte de novedades." });
}
}
// GET: api/reportes/novedades-canillas/pdf
// Genera el PDF del reporte de novedades de canillitas
[HttpGet("novedades-canillas/pdf")]
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetReporteNovedadesCanillasPdf(
[FromQuery] int idEmpresa,
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta)
{
if (!TienePermiso(PermisoVerReporteNovedadesCanillas)) // RR004
{
_logger.LogWarning("Acceso denegado a GetReporteNovedadesCanillasPdf. Usuario: {User}", User.Identity?.Name ?? "Desconocido");
return Forbid();
}
if (fechaDesde > fechaHasta)
{
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
}
try
{
// Obtener datos para AMBOS datasets
var novedadesData = await _novedadCanillaService.ObtenerReporteNovedadesAsync(idEmpresa, fechaDesde, fechaHasta);
var gananciasData = await _novedadCanillaService.ObtenerReporteGananciasAsync(idEmpresa, fechaDesde, fechaHasta); // << OBTENER DATOS DE GANANCIAS
// Verificar si hay datos en *alguno* de los datasets necesarios para el reporte
if ((novedadesData == null || !novedadesData.Any()) && (gananciasData == null || !gananciasData.Any()))
{
return NotFound(new { message = "No hay datos para generar el PDF con los parámetros seleccionados." });
}
var empresa = await _empresaRepository.GetByIdAsync(idEmpresa);
LocalReport report = new LocalReport();
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoNovedadesCanillas.rdlc");
if (!System.IO.File.Exists(rdlcPath))
{
_logger.LogError("Archivo RDLC no encontrado en la ruta: {RdlcPath}", rdlcPath);
return StatusCode(StatusCodes.Status500InternalServerError, "Archivo de definición de reporte no encontrado.");
}
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
report.LoadReportDefinition(fs);
}
// Nombre del DataSet en RDLC para SP_DistCanillasNovedades (detalles)
report.DataSources.Add(new ReportDataSource("DSNovedadesCanillasDetalles", novedadesData ?? new List<NovedadesCanillasReporteDto>()));
// Nombre del DataSet en RDLC para SP_DistCanillasGanancias (ganancias/resumen)
report.DataSources.Add(new ReportDataSource("DSNovedadesCanillas", gananciasData ?? new List<CanillaGananciaReporteDto>()));
var parameters = new List<ReportParameter>
{
new ReportParameter("NomEmp", empresa?.Nombre ?? "N/A"),
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy"))
};
report.SetParameters(parameters);
byte[] pdfBytes = report.Render("PDF");
string fileName = $"ReporteNovedadesCanillas_Emp{idEmpresa}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf";
return File(pdfBytes, "application/pdf", fileName);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al generar PDF para el reporte de novedades de canillitas. Empresa: {IdEmpresa}", idEmpresa);
return StatusCode(StatusCodes.Status500InternalServerError, new { message = $"Error interno al generar el PDF: {ex.Message}" });
}
}
// GET: api/reportes/novedades-canillas-ganancias
[HttpGet("novedades-canillas-ganancias")]
[ProducesResponseType(typeof(IEnumerable<CanillaGananciaReporteDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetReporteGananciasCanillasData(
[FromQuery] int idEmpresa,
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta)
{
if (!TienePermiso(PermisoVerReporteNovedadesCanillas)) return Forbid(); // RR004
if (fechaDesde > fechaHasta)
{
return BadRequest(new { message = "La fecha 'desde' no puede ser posterior a la fecha 'hasta'." });
}
try
{
var gananciasData = await _novedadCanillaService.ObtenerReporteGananciasAsync(idEmpresa, fechaDesde, fechaHasta);
if (gananciasData == null || !gananciasData.Any())
{
return Ok(Enumerable.Empty<CanillaGananciaReporteDto>());
}
return Ok(gananciasData);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al obtener datos de ganancias para el reporte de novedades. Empresa: {IdEmpresa}", idEmpresa);
return StatusCode(StatusCodes.Status500InternalServerError, new { message = "Error interno al obtener datos de ganancias." });
}
}
// GET: api/reportes/listado-distribucion-mensual/diarios
[HttpGet("listado-distribucion-mensual/diarios")]
[ProducesResponseType(typeof(IEnumerable<ListadoDistCanMensualDiariosDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> GetListadoDistMensualDiarios(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] bool esAccionista)
{
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
var (data, error) = await _reportesService.ObtenerReporteMensualDiariosAsync(fechaDesde, fechaHasta, esAccionista);
if (error != null) return BadRequest(new { message = error });
return Ok(data ?? Enumerable.Empty<ListadoDistCanMensualDiariosDto>());
}
[HttpGet("listado-distribucion-mensual/diarios/pdf")]
public async Task<IActionResult> GetListadoDistMensualDiariosPdf(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] bool esAccionista)
{
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
var (data, error) = await _reportesService.ObtenerReporteMensualDiariosAsync(fechaDesde, fechaHasta, esAccionista);
if (error != null) return BadRequest(new { message = error });
if (data == null || !data.Any()) return NotFound(new { message = "No hay datos para generar el PDF." });
try
{
LocalReport report = new LocalReport();
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoDistribucionCanMensualDiarios.rdlc");
if (!System.IO.File.Exists(rdlcPath))
{
_logger.LogError("Archivo RDLC no encontrado: {Path}", rdlcPath);
return StatusCode(StatusCodes.Status500InternalServerError, $"Archivo de reporte no encontrado: {Path.GetFileName(rdlcPath)}");
}
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
report.LoadReportDefinition(fs);
}
report.DataSources.Add(new ReportDataSource("DSListadoDistribucionCanMensualDiarios", data));
var parameters = new List<ReportParameter>
{
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy")),
new ReportParameter("CanAcc", esAccionista ? "1" : "0") // El RDLC espera un Integer para CanAcc
};
report.SetParameters(parameters);
byte[] pdfBytes = report.Render("PDF");
string tipoDesc = esAccionista ? "Accionistas" : "Canillitas";
return File(pdfBytes, "application/pdf", $"ListadoDistMensualDiarios_{tipoDesc}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf");
}
catch (Exception ex) { _logger.LogError(ex, "Error PDF ListadoDistMensualDiarios"); return StatusCode(500, "Error interno."); }
}
// GET: api/reportes/listado-distribucion-mensual/publicaciones
[HttpGet("listado-distribucion-mensual/publicaciones")]
[ProducesResponseType(typeof(IEnumerable<ListadoDistCanMensualPubDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status403Forbidden)]
public async Task<IActionResult> GetListadoDistMensualPorPublicacion(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] bool esAccionista)
{
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
var (data, error) = await _reportesService.ObtenerReporteMensualPorPublicacionAsync(fechaDesde, fechaHasta, esAccionista);
if (error != null) return BadRequest(new { message = error });
return Ok(data ?? Enumerable.Empty<ListadoDistCanMensualPubDto>());
}
[HttpGet("listado-distribucion-mensual/publicaciones/pdf")]
public async Task<IActionResult> GetListadoDistMensualPorPublicacionPdf(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] bool esAccionista)
{
if (!TienePermiso(PermisoVerReporteListadoDistMensual)) return Forbid();
if (fechaDesde > fechaHasta) return BadRequest(new { message = "Fecha Desde no puede ser mayor a Fecha Hasta." });
var (data, error) = await _reportesService.ObtenerReporteMensualPorPublicacionAsync(fechaDesde, fechaHasta, esAccionista);
if (error != null) return BadRequest(new { message = error });
if (data == null || !data.Any()) return NotFound(new { message = "No hay datos para generar el PDF." });
try
{
LocalReport report = new LocalReport();
string rdlcPath = Path.Combine("Controllers", "Reportes", "RDLC", "ReporteListadoDistribucionCanMensual.rdlc");
if (!System.IO.File.Exists(rdlcPath))
{
_logger.LogError("Archivo RDLC no encontrado: {Path}", rdlcPath);
return StatusCode(StatusCodes.Status500InternalServerError, $"Archivo de reporte no encontrado: {Path.GetFileName(rdlcPath)}");
}
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
report.LoadReportDefinition(fs);
}
report.DataSources.Add(new ReportDataSource("DSListadoDistribucionCanMensual", data));
var parameters = new List<ReportParameter>
{
new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")),
new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy")),
new ReportParameter("CanAcc", esAccionista ? "1" : "0")
};
report.SetParameters(parameters);
byte[] pdfBytes = report.Render("PDF");
string tipoDesc = esAccionista ? "Accionistas" : "Canillitas";
return File(pdfBytes, "application/pdf", $"ListadoDistMensualPub_{tipoDesc}_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}.pdf");
}
catch (Exception ex) { _logger.LogError(ex, "Error PDF ListadoDistMensualPorPublicacion"); return StatusCode(500, "Error interno."); }
}
}
}