114 lines
5.2 KiB
C#
114 lines
5.2 KiB
C#
using GestionIntegral.Api.Services.Reportes;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.Reporting.NETCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Threading.Tasks;
|
|
using GestionIntegral.Api.Dtos.Reportes;
|
|
using GestionIntegral.Api.Data.Repositories.Impresion; // Para ExistenciaPapelDto
|
|
|
|
namespace GestionIntegral.Api.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
[Authorize]
|
|
public class ReportesController : ControllerBase
|
|
{
|
|
private readonly IReportesService _reportesService;
|
|
private readonly ILogger<ReportesController> _logger;
|
|
private readonly IPlantaRepository _plantaRepository;
|
|
|
|
// Asumimos un permiso genérico para reportes o uno específico
|
|
private const string PermisoVerReporteExistenciaPapel = "RR005";
|
|
|
|
public ReportesController(IReportesService reportesService, ILogger<ReportesController> logger, IPlantaRepository plantaRepository)
|
|
{
|
|
_reportesService = reportesService;
|
|
_logger = logger;
|
|
_plantaRepository = plantaRepository;
|
|
}
|
|
|
|
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
|
|
|
|
// GET: api/reportes/existencia-papel
|
|
[HttpGet("existencia-papel")]
|
|
[ProducesResponseType(typeof(IEnumerable<ExistenciaPapelDto>), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
|
public async Task<IActionResult> GetReporteExistenciaPapel(
|
|
[FromQuery] DateTime fechaDesde,
|
|
[FromQuery] DateTime fechaHasta,
|
|
[FromQuery] int? idPlanta, // Opcional
|
|
[FromQuery] bool consolidado = false) // Por defecto no consolidado
|
|
{
|
|
if (!TienePermiso(PermisoVerReporteExistenciaPapel))
|
|
{
|
|
_logger.LogWarning("Acceso denegado a GetReporteExistenciaPapel. Usuario: {User}", User.Identity?.Name ?? "Desconocido");
|
|
return Forbid();
|
|
}
|
|
|
|
var (data, error) = await _reportesService.ObtenerExistenciaPapelAsync(fechaDesde, fechaHasta, idPlanta, consolidado);
|
|
|
|
if (error != null)
|
|
{
|
|
return BadRequest(new { message = error });
|
|
}
|
|
return Ok(data);
|
|
}
|
|
|
|
// Nuevo endpoint para PDF
|
|
[HttpGet("existencia-papel/pdf")]
|
|
[ProducesResponseType(typeof(FileContentResult), StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status403Forbidden)]
|
|
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
|
|
public async Task<IActionResult> GetReporteExistenciaPapelPdf(
|
|
[FromQuery] DateTime fechaDesde,
|
|
[FromQuery] DateTime fechaHasta,
|
|
[FromQuery] int? idPlanta,
|
|
[FromQuery] bool consolidado = false)
|
|
{
|
|
if (!TienePermiso(PermisoVerReporteExistenciaPapel)) return Forbid();
|
|
|
|
var (data, error) = await _reportesService.ObtenerExistenciaPapelAsync(fechaDesde, fechaHasta, idPlanta, consolidado);
|
|
|
|
if (error != null)
|
|
{
|
|
return BadRequest(new { message = error });
|
|
}
|
|
if (data == null || !data.Any())
|
|
{
|
|
return NotFound(new { message = "No hay datos para generar el PDF con los parámetros seleccionados." });
|
|
}
|
|
|
|
try
|
|
{
|
|
LocalReport report = new LocalReport();
|
|
using (var fs = new FileStream("Controllers/Reportes/RDLC/ReporteExistenciaPapel.rdlc", FileMode.Open)) // Ruta a tu .rdlc
|
|
{
|
|
report.LoadReportDefinition(fs);
|
|
}
|
|
report.DataSources.Add(new ReportDataSource("DSConsumoBobinas", data)); // Nombre del DataSet en el RDLC
|
|
|
|
var parameters = new ReportParameter[3];
|
|
parameters[0] = new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy"));
|
|
parameters[1] = new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy"));
|
|
var planta = idPlanta.HasValue ? await _plantaRepository.GetByIdAsync(idPlanta.Value) : null;
|
|
parameters[2] = new ReportParameter("NomPlanta", consolidado ? "Consolidado" : planta?.Nombre ?? "N/A");
|
|
report.SetParameters(parameters);
|
|
|
|
byte[] pdfBytes = report.Render("PDF");
|
|
string fileName = $"ExistenciaPapel_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}_{(consolidado ? "Consolidado" : $"Planta{idPlanta}")}.pdf";
|
|
return File(pdfBytes, "application/pdf", fileName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "Error al generar PDF para Existencia de Papel.");
|
|
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al generar el PDF del reporte.");
|
|
}
|
|
}
|
|
}
|
|
} |