Try con QuestPDF
All checks were successful
Optimized Build and Deploy / remote-build-and-deploy (push) Successful in 7m36s

Se elimina Puppeteer y Chromium. Se utiliza QuestPDF para mayor velocidad y sin Razor.
This commit is contained in:
2025-06-20 19:04:23 -03:00
parent 1373bcf9ca
commit a5bcbefa52
11 changed files with 317 additions and 430 deletions

View File

@@ -0,0 +1,114 @@
using GestionIntegral.Api.Dtos.Reportes.ViewModels;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Linq;
namespace GestionIntegral.Api.Controllers.Reportes.PdfTemplates
{
public class ExistenciaPapelConsolidadoDocument : IDocument
{
public ExistenciaPapelConsolidadoViewModel Model { get; }
public ExistenciaPapelConsolidadoDocument(ExistenciaPapelConsolidadoViewModel model)
{
Model = model;
}
public DocumentMetadata GetMetadata() => DocumentMetadata.Default;
public DocumentSettings GetSettings() => DocumentSettings.Default;
public void Compose(IDocumentContainer container)
{
container
.Page(page =>
{
page.Margin(1.5f, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontFamily("Roboto").FontSize(10));
page.Header().Element(ComposeHeader);
page.Content().Element(ComposeContent);
page.Footer()
.AlignCenter()
.Text(x =>
{
x.Span("Página ");
x.CurrentPageNumber();
});
});
}
void ComposeHeader(IContainer container)
{
container.Column(column =>
{
column.Spacing(5);
column.Item().AlignCenter().Text("Reporte de Existencias de Papel").SemiBold().FontSize(14);
// La versión consolidada no muestra la planta, sino el texto "Consolidado"
column.Item().AlignCenter().Text("Consolidado").FontSize(12);
column.Item().PaddingTop(2, Unit.Millimetre).Row(row =>
{
row.RelativeItem().Column(col =>
{
col.Item().Text(text =>
{
text.Span("Fecha del Reporte: ").SemiBold();
text.Span(Model.FechaReporte);
});
col.Item().Text($"Periodo Consultado: Desde {Model.FechaDesde} Hasta {Model.FechaHasta}");
});
});
});
}
void ComposeContent(IContainer container)
{
container.PaddingTop(1, Unit.Centimetre).Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.ConstantColumn(65);
columns.ConstantColumn(70);
columns.ConstantColumn(85);
columns.ConstantColumn(65);
columns.ConstantColumn(80);
});
table.Header(header =>
{
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).Text("Tipo de Bobina");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Cant. Stock");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Kg. Stock");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Consumo (Kg)");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Días Disp.");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignCenter().Text("Fin Estimado");
});
foreach (var item in Model.Existencias)
{
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).Text(item.TipoBobina);
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.BobinasEnStock?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.TotalKilosEnStock?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.ConsumoAcumulado?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.PromedioDiasDisponibles?.ToString("N0") ?? "N/A");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignCenter().Text(item.FechaEstimacionFinStock?.ToString("dd/MM/yyyy") ?? "N/A");
}
var totalBobinas = Model.Existencias.Sum(e => e.BobinasEnStock ?? 0);
var totalKilos = Model.Existencias.Sum(e => e.TotalKilosEnStock ?? 0);
var totalConsumo = Model.Existencias.Sum(e => e.ConsumoAcumulado ?? 0);
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span("Totales").SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalBobinas.ToString("N0")).SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalKilos.ToString("N0")).SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalConsumo.ToString("N0")).SemiBold());
table.Cell().ColumnSpan(2).BorderTop(1).BorderColor(Colors.Grey.Lighten2);
});
}
}
}

View File

@@ -0,0 +1,117 @@
using GestionIntegral.Api.Dtos.Reportes.ViewModels;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Linq;
namespace GestionIntegral.Api.Controllers.Reportes.PdfTemplates
{
// Usamos una clase parcial para organizar mejor el código, aunque no es estrictamente necesario aquí.
public class ExistenciaPapelDocument : IDocument
{
// Usamos una propiedad pública con 'init' en lugar de un campo privado.
// Esto es más limpio y funciona mejor con el análisis de código.
public ExistenciaPapelViewModel Model { get; }
public ExistenciaPapelDocument(ExistenciaPapelViewModel model)
{
Model = model;
}
public DocumentMetadata GetMetadata() => DocumentMetadata.Default;
public DocumentSettings GetSettings() => DocumentSettings.Default;
public void Compose(IDocumentContainer container)
{
container
.Page(page =>
{
page.Margin(1.5f, Unit.Centimetre);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x.FontFamily("Roboto").FontSize(10));
page.Header().Element(ComposeHeader);
page.Content().Element(ComposeContent);
page.Footer()
.AlignCenter()
.Text(x =>
{
x.Span("Página ");
x.CurrentPageNumber();
});
});
}
// Ahora los métodos usan 'Model' (la propiedad pública) en lugar de '_model'.
void ComposeHeader(IContainer container)
{
container.Column(column =>
{
column.Spacing(5);
column.Item().AlignCenter().Text("Reporte de Existencias de Papel").SemiBold().FontSize(14);
column.Item().AlignCenter().Text($"Planta: {Model.NombrePlanta}").FontSize(12);
column.Item().PaddingTop(2, Unit.Millimetre).Row(row =>
{
row.RelativeItem().Column(col =>
{
col.Item().Text(text =>
{
text.Span("Fecha del Reporte: ").SemiBold();
text.Span(Model.FechaReporte);
});
col.Item().Text($"Periodo Consultado: Desde {Model.FechaDesde} Hasta {Model.FechaHasta}");
});
});
});
}
void ComposeContent(IContainer container)
{
container.PaddingTop(1, Unit.Centimetre).Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.ConstantColumn(65);
columns.ConstantColumn(70);
columns.ConstantColumn(85);
columns.ConstantColumn(65);
columns.ConstantColumn(80);
});
table.Header(header =>
{
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).Text("Tipo de Bobina");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Cant. Stock");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Kg. Stock");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Consumo (Kg)");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignRight().Text("Días Disp.");
header.Cell().Background(Colors.Grey.Lighten3).Padding(4).AlignCenter().Text("Fin Estimado");
});
foreach (var item in Model.Existencias)
{
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).Text(item.TipoBobina);
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.BobinasEnStock?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.TotalKilosEnStock?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.ConsumoAcumulado?.ToString("N0") ?? "0");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(item.PromedioDiasDisponibles?.ToString("N0") ?? "N/A");
table.Cell().BorderBottom(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignCenter().Text(item.FechaEstimacionFinStock?.ToString("dd/MM/yyyy") ?? "N/A");
}
var totalBobinas = Model.Existencias.Sum(e => e.BobinasEnStock ?? 0);
var totalKilos = Model.Existencias.Sum(e => e.TotalKilosEnStock ?? 0);
var totalConsumo = Model.Existencias.Sum(e => e.ConsumoAcumulado ?? 0);
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span("Totales").SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalBobinas.ToString("N0")).SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalKilos.ToString("N0")).SemiBold());
table.Cell().BorderTop(1).BorderColor(Colors.Grey.Lighten2).Padding(4).AlignRight().Text(t => t.Span(totalConsumo.ToString("N0")).SemiBold());
table.Cell().ColumnSpan(2).BorderTop(1).BorderColor(Colors.Grey.Lighten2);
});
}
}
}

View File

@@ -14,6 +14,8 @@ using GestionIntegral.Api.Data.Repositories.Distribucion;
using GestionIntegral.Api.Services.Distribucion;
using GestionIntegral.Api.Services.Pdf;
using GestionIntegral.Api.Dtos.Reportes.ViewModels;
using GestionIntegral.Api.Controllers.Reportes.PdfTemplates;
using QuestPDF.Infrastructure;
namespace GestionIntegral.Api.Controllers
{
@@ -29,7 +31,7 @@ namespace GestionIntegral.Api.Controllers
private readonly IEmpresaRepository _empresaRepository;
private readonly IDistribuidorRepository _distribuidorRepository; // Para obtener el nombre del distribuidor
private readonly INovedadCanillaService _novedadCanillaService;
private readonly IPdfGeneratorService _pdfGeneratorService;
private readonly IQuestPdfGenerator _pdfGenerator;
// Permisos
private const string PermisoVerReporteExistenciaPapel = "RR005";
@@ -51,7 +53,7 @@ namespace GestionIntegral.Api.Controllers
IPublicacionRepository publicacionRepository,
IEmpresaRepository empresaRepository,
IDistribuidorRepository distribuidorRepository,
IPdfGeneratorService pdfGeneratorService)
IQuestPdfGenerator pdfGenerator)
{
_reportesService = reportesService;
_novedadCanillaService = novedadCanillaService;
@@ -60,7 +62,7 @@ namespace GestionIntegral.Api.Controllers
_publicacionRepository = publicacionRepository;
_empresaRepository = empresaRepository;
_distribuidorRepository = distribuidorRepository;
_pdfGeneratorService = pdfGeneratorService;
_pdfGenerator = pdfGenerator;
}
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
@@ -98,76 +100,58 @@ namespace GestionIntegral.Api.Controllers
[ProducesResponseType(StatusCodes.Status403Forbidden)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetReporteExistenciaPapelPdf(
[FromQuery] DateTime fechaDesde,
[FromQuery] DateTime fechaHasta,
[FromQuery] int? idPlanta,
[FromQuery] bool consolidado = false)
[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." });
}
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
{
// Determinar la plantilla y el nombre de la planta
string templatePath;
string nombrePlantaParam = "Consolidado";
IDocument document; // Se declara aquí
if (consolidado)
{
templatePath = "Controllers/Reportes/Templates/ReporteExistenciaPapelConsolidado.cshtml";
var viewModel = new ExistenciaPapelConsolidadoViewModel
{
Existencias = data,
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
document = new ExistenciaPapelConsolidadoDocument(viewModel);
}
else
{
templatePath = "Controllers/Reportes/Templates/ReporteExistenciaPapel.cshtml";
if (idPlanta.HasValue)
if (!idPlanta.HasValue)
{
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
nombrePlantaParam = planta?.Nombre ?? "N/A";
return BadRequest(new { message = "El idPlanta es requerido para reportes no consolidados." });
}
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
var viewModel = new ExistenciaPapelViewModel
{
Existencias = data,
NombrePlanta = planta?.Nombre ?? $"Planta ID {idPlanta.Value}", // Manejo por si no se encuentra
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
document = new ExistenciaPapelDocument(viewModel);
}
// Crear el ViewModel para la plantilla Razor
var viewModel = new ExistenciaPapelViewModel
{
Existencias = data,
NombrePlanta = nombrePlantaParam,
FechaDesde = fechaDesde.ToString("dd/MM/yyyy"),
FechaHasta = fechaHasta.ToString("dd/MM/yyyy")
};
// Configurar opciones de PDF (márgenes, etc.)
var pdfOptions = new PdfGenerationOptions
{
Margin = new PuppeteerSharp.Media.MarginOptions
{
Top = "2cm",
Bottom = "2cm",
Left = "1cm",
Right = "1cm"
},
Format = PuppeteerSharp.Media.PaperFormat.A4,
// Podríamos agregar un encabezado/pie de página aquí si fuera necesario
// FooterTemplate = "<div style='font-size:8px; width:100%; text-align:center;'>Página <span class='pageNumber'></span> de <span class='totalPages'></span></div>"
};
// Generar el PDF
byte[] pdfBytes = await _pdfGeneratorService.GeneratePdfFromRazorTemplateAsync(templatePath, viewModel, pdfOptions);
byte[] pdfBytes = await _pdfGenerator.GeneratePdfAsync(document);
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.");
_logger.LogError(ex, "Error al generar PDF con QuestPDF para Existencia de Papel.");
return StatusCode(StatusCodes.Status500InternalServerError, "Error interno al generar el PDF del reporte.");
}
}

View File

@@ -1,116 +0,0 @@
@using GestionIntegral.Api.Dtos.Reportes.ViewModels
@model ExistenciaPapelViewModel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 10pt;
margin: 0;
padding: 0;
}
.report-container {
width: 100%;
margin: auto;
}
.report-header {
text-align: center;
padding: 10px;
border-bottom: 2px solid #ccc;
margin-bottom: 20px;
}
.report-header h1 {
font-size: 14pt;
margin: 0 0 5px 0;
}
.report-header h2 {
font-size: 12pt;
margin: 0;
font-weight: normal;
}
.report-parameters {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #eee;
background-color: #f9f9f9;
}
.report-parameters p {
margin: 0 0 5px 0;
}
.report-table {
width: 100%;
border-collapse: collapse;
font-size: 9pt;
}
.report-table th, .report-table td {
border: 1px solid #ccc;
padding: 6px;
text-align: left;
}
.report-table th {
background-color: #f2f2f2;
font-weight: bold;
}
.text-right { text-align: right; }
.text-center { text-align: center; }
</style>
</head>
<body>
<div class="report-container">
<div class="report-header">
<h1>Reporte de Existencias de Papel</h1>
<h2>Planta: @Model.NombrePlanta</h2>
</div>
<div class="report-parameters">
<p><strong>Fecha del Reporte:</strong> @Model.FechaReporte</p>
<p><strong>Periodo Consultado:</strong> Desde @Model.FechaDesde Hasta @Model.FechaHasta</p>
</div>
<table class="report-table">
<thead>
<tr>
<th>Tipo Bobina</th>
<th class="text-right">Cant. Stock</th>
<th class="text-right">Kg. Stock</th>
<th class="text-right">Consumo Acumulado (Kg)</th>
<th class="text-right">Días Disponibles</th>
<th class="text-center">Fin Stock Estimado</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Existencias)
{
<tr>
<td>@item.TipoBobina</td>
<td class="text-right">@(item.BobinasEnStock?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.TotalKilosEnStock?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.ConsumoAcumulado?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.PromedioDiasDisponibles?.ToString("N0") ?? "N/A")</td>
<td class="text-center">@(item.FechaEstimacionFinStock?.ToString("dd/MM/yyyy") ?? "N/A")</td>
</tr>
}
</tbody>
<tfoot>
@{
var totalBobinas = Model.Existencias.Sum(e => e.BobinasEnStock ?? 0);
var totalKilos = Model.Existencias.Sum(e => e.TotalKilosEnStock ?? 0);
var totalConsumo = Model.Existencias.Sum(e => e.ConsumoAcumulado ?? 0);
}
<tr style="font-weight: bold;">
<td class="text-right">Totales</td>
<td class="text-right">@totalBobinas.ToString("N0")</td>
<td class="text-right">@totalKilos.ToString("N0")</td>
<td class="text-right">@totalConsumo.ToString("N0")</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>

View File

@@ -1,115 +0,0 @@
@using GestionIntegral.Api.Dtos.Reportes.ViewModels
@model ExistenciaPapelViewModel
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
body {
font-family: 'Roboto', Arial, sans-serif;
font-size: 10pt;
margin: 0;
padding: 0;
}
.report-container {
width: 100%;
margin: auto;
}
.report-header {
text-align: center;
padding: 10px;
border-bottom: 2px solid #ccc;
margin-bottom: 20px;
}
.report-header h1 {
font-size: 14pt;
margin: 0 0 5px 0;
}
.report-header h2 {
font-size: 12pt;
margin: 0;
font-weight: normal;
}
.report-parameters {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #eee;
background-color: #f9f9f9;
}
.report-parameters p {
margin: 0 0 5px 0;
}
.report-table {
width: 100%;
border-collapse: collapse;
font-size: 9pt;
}
.report-table th, .report-table td {
border: 1px solid #ccc;
padding: 6px;
text-align: left;
}
.report-table th {
background-color: #f2f2f2;
font-weight: bold;
}
.text-right { text-align: right; }
.text-center { text-align: center; }
</style>
</head>
<body>
<div class="report-container">
<div class="report-header">
<h1>Reporte de Existencias de Papel</h1>
</div>
<div class="report-parameters">
<p><strong>Fecha del Reporte:</strong> @Model.FechaReporte</p>
<p><strong>Periodo Consultado:</strong> Desde @Model.FechaDesde Hasta @Model.FechaHasta</p>
</div>
<table class="report-table">
<thead>
<tr>
<th>Tipo Bobina</th>
<th class="text-right">Cant. Stock</th>
<th class="text-right">Kg. Stock</th>
<th class="text-right">Consumo Acumulado (Kg)</th>
<th class="text-right">Días Disponibles</th>
<th class="text-center">Fin Stock Estimado</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Existencias)
{
<tr>
<td>@item.TipoBobina</td>
<td class="text-right">@(item.BobinasEnStock?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.TotalKilosEnStock?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.ConsumoAcumulado?.ToString("N0") ?? "0")</td>
<td class="text-right">@(item.PromedioDiasDisponibles?.ToString("N0") ?? "N/A")</td>
<td class="text-center">@(item.FechaEstimacionFinStock?.ToString("dd/MM/yyyy") ?? "N/A")</td>
</tr>
}
</tbody>
<tfoot>
@{
var totalBobinas = Model.Existencias.Sum(e => e.BobinasEnStock ?? 0);
var totalKilos = Model.Existencias.Sum(e => e.TotalKilosEnStock ?? 0);
var totalConsumo = Model.Existencias.Sum(e => e.ConsumoAcumulado ?? 0);
}
<tr style="font-weight: bold;">
<td class="text-right">Totales</td>
<td class="text-right">@totalBobinas.ToString("N0")</td>
<td class="text-right">@totalKilos.ToString("N0")</td>
<td class="text-right">@totalConsumo.ToString("N0")</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</div>
</body>
</html>