Test Reportes con Razor y Puppeteer
All checks were successful
Build and Deploy / remote-build-and-deploy (push) Successful in 28m23s

This commit is contained in:
2025-06-19 14:47:43 -03:00
parent 8591945eb4
commit 975a1e6d26
11 changed files with 493 additions and 86 deletions

View File

@@ -12,6 +12,8 @@ using System.IO;
using System.Linq;
using GestionIntegral.Api.Data.Repositories.Distribucion;
using GestionIntegral.Api.Services.Distribucion;
using GestionIntegral.Api.Services.Pdf;
using GestionIntegral.Api.Dtos.Reportes.ViewModels;
namespace GestionIntegral.Api.Controllers
{
@@ -27,7 +29,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;
// Permisos
private const string PermisoVerReporteExistenciaPapel = "RR005";
@@ -48,7 +50,8 @@ namespace GestionIntegral.Api.Controllers
IPlantaRepository plantaRepository,
IPublicacionRepository publicacionRepository,
IEmpresaRepository empresaRepository,
IDistribuidorRepository distribuidorRepository)
IDistribuidorRepository distribuidorRepository,
IPdfGeneratorService pdfGeneratorService)
{
_reportesService = reportesService;
_novedadCanillaService = novedadCanillaService;
@@ -57,6 +60,7 @@ namespace GestionIntegral.Api.Controllers
_publicacionRepository = publicacionRepository;
_empresaRepository = empresaRepository;
_distribuidorRepository = distribuidorRepository;
_pdfGeneratorService = pdfGeneratorService;
}
private bool TienePermiso(string codAcc) => User.IsInRole("SuperAdmin") || User.HasClaim(c => c.Type == "permission" && c.Value == codAcc);
@@ -94,14 +98,14 @@ 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); // <--- CORREGIDO
var (data, error) = await _reportesService.ObtenerExistenciaPapelAsync(fechaDesde, fechaHasta, idPlanta, consolidado);
if (error != null)
{
@@ -114,43 +118,50 @@ namespace GestionIntegral.Api.Controllers
try
{
LocalReport report = new LocalReport();
string rdlcPath = consolidado ? "Controllers/Reportes/RDLC/ReporteExistenciaPapelConsolidado.rdlc" : "Controllers/Reportes/RDLC/ReporteExistenciaPapel.rdlc";
using (var fs = new FileStream(rdlcPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
report.LoadReportDefinition(fs);
}
report.DataSources.Add(new ReportDataSource("DSConsumoBobinas", data));
var parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("FechaDesde", fechaDesde.ToString("dd/MM/yyyy")));
parameters.Add(new ReportParameter("FechaHasta", fechaHasta.ToString("dd/MM/yyyy")));
// Determinar la plantilla y el nombre de la planta
string templatePath;
string nombrePlantaParam = "Consolidado";
if (!consolidado && idPlanta.HasValue)
if (consolidado)
{
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
nombrePlantaParam = planta?.Nombre ?? "N/A";
}
else if (consolidado)
{
// Para el consolidado, el RDLC ReporteExistenciaPapelConsolidado.txt NO espera NomPlanta
templatePath = Path.Combine("Controllers", "Reportes", "Templates", "ReporteExistenciaPapelConsolidado.cshtml");
}
else
{ // No consolidado pero idPlanta es NULL (aunque el servicio ya valida esto)
nombrePlantaParam = "N/A";
}
// Solo añadir NomPlanta si NO es consolidado, porque el RDLC consolidado no lo tiene.
if (!consolidado)
{
parameters.Add(new ReportParameter("NomPlanta", nombrePlantaParam));
templatePath = Path.Combine("Controllers", "Reportes", "Templates", "ReporteExistenciaPapel.cshtml");
if (idPlanta.HasValue)
{
var planta = await _plantaRepository.GetByIdAsync(idPlanta.Value);
nombrePlantaParam = planta?.Nombre ?? "N/A";
}
}
// 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")
};
report.SetParameters(parameters);
// 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 = report.Render("PDF");
string fileName = $"ExistenciaPapel_{fechaDesde:yyyyMMdd}_{fechaHasta:yyyyMMdd}_{(consolidado ? "Consolidado" : $"Planta{idPlanta}")}.pdf";
return File(pdfBytes, "application/pdf", fileName);
}

View File

@@ -0,0 +1,116 @@
@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

@@ -0,0 +1,115 @@
@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>

View File

@@ -44,7 +44,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
var result = await connection.QueryAsync<ExistenciaPapelDto>(spName, parameters, commandType: CommandType.StoredProcedure);
var result = await connection.QueryAsync<ExistenciaPapelDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
_logger.LogInformation("SP {SPName} ejecutado, {Count} filas devueltas.", spName, result.Count());
return result;
}
@@ -68,7 +68,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
return await connection.QueryAsync<MovimientoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<MovimientoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -84,7 +84,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
return await conn.QueryAsync<DevueltosOtrosDiasDto>(
"SP_DistCanillasCantidadEntradaSalidaOtrosDias",
parametros,
commandType: CommandType.StoredProcedure
commandType: CommandType.StoredProcedure, commandTimeout: 120
);
}
@@ -101,7 +101,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
return await connection.QueryAsync<MovimientoBobinaEstadoDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<MovimientoBobinaEstadoDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -123,7 +123,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
return await connection.QueryAsync<MovimientoBobinaEstadoTotalDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<MovimientoBobinaEstadoTotalDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -140,7 +140,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@Mes", fechaDesde.Month, DbType.Int32);
parameters.Add("@Anio", fechaDesde.Year, DbType.Int32);
// El SP no usa fechaHasta explícitamente, calcula el fin de mes internamente
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionGeneralResumenDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionGeneralResumenDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ListadoDistribucionGeneralResumenDto>(); }
}
@@ -151,7 +151,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@Id_Publicacion", idPublicacion, DbType.Int32);
parameters.Add("@Mes", fechaDesde.Month, DbType.Int32);
parameters.Add("@Anio", fechaDesde.Year, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionGeneralPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionGeneralPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ListadoDistribucionGeneralPromedioDiaDto>(); }
}
@@ -162,7 +162,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@idPublicacion", idPublicacion, DbType.Int32);
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasSimpleDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasSimpleDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ListadoDistribucionCanillasSimpleDto>(); }
}
@@ -173,7 +173,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@idPublicacion", idPublicacion, DbType.Int32);
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ListadoDistribucionCanillasPromedioDiaDto>(); }
}
@@ -185,7 +185,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
parameters.Add("@accionista", esAccionista, DbType.Boolean);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasImporteDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ListadoDistribucionCanillasImporteDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ListadoDistribucionCanillasImporteDto>(); }
}
@@ -195,7 +195,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaElDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaElDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<VentaMensualSecretariaElDiaDto>(); }
}
@@ -205,7 +205,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaElPlataDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaElPlataDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<VentaMensualSecretariaElPlataDto>(); }
}
@@ -215,7 +215,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaTirDevoDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<VentaMensualSecretariaTirDevoDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<VentaMensualSecretariaTirDevoDto>(); }
}
@@ -225,7 +225,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fecha, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<DetalleDistribucionCanillaDto>(); }
}
@@ -235,7 +235,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fecha, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<DetalleDistribucionCanillaDto>(); }
}
@@ -245,7 +245,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fecha, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaAllDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaAllDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<DetalleDistribucionCanillaAllDto>(); }
}
@@ -255,7 +255,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fechaLiquidacion, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<DetalleDistribucionCanillaDto>(); }
}
@@ -265,7 +265,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fechaLiquidacion, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<DetalleDistribucionCanillaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<DetalleDistribucionCanillaDto>(); }
}
@@ -275,7 +275,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@Fecha", fecha, DbType.DateTime);
parameters.Add("@IdEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ObtenerCtrlDevolucionesDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ObtenerCtrlDevolucionesDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ObtenerCtrlDevolucionesDto>(); }
}
@@ -285,7 +285,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@fecha", fecha, DbType.DateTime);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ControlDevolucionesReporteDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ControlDevolucionesReporteDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ControlDevolucionesReporteDto>(); }
}
@@ -297,7 +297,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@FechaInicio", fechaDesde, DbType.Date);
parameters.Add("@FechaFin", fechaHasta, DbType.Date);
parameters.Add("@IdPlanta", idPlanta, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<TiradasPublicacionesSeccionesDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<TiradasPublicacionesSeccionesDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<TiradasPublicacionesSeccionesDto>(); }
}
@@ -308,7 +308,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@IdPublicacion", idPublicacion, DbType.Int32);
parameters.Add("@FechaInicio", fechaDesde, DbType.Date);
parameters.Add("@FechaFin", fechaHasta, DbType.Date);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<TiradasPublicacionesSeccionesDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<TiradasPublicacionesSeccionesDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<TiradasPublicacionesSeccionesDto>(); }
}
@@ -319,7 +319,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@FechaInicio", fechaDesde, DbType.DateTime2);
parameters.Add("@FechaFin", fechaHasta, DbType.DateTime2);
parameters.Add("@idPlanta", idPlanta, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasSeccionDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasSeccionDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ConsumoBobinasSeccionDto>(); }
}
@@ -329,7 +329,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@FechaInicio", fechaDesde, DbType.DateTime2);
parameters.Add("@FechaFin", fechaHasta, DbType.DateTime2);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasSeccionDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasSeccionDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ConsumoBobinasSeccionDto>(); }
}
@@ -339,7 +339,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
var parameters = new DynamicParameters();
parameters.Add("@FechaInicio", fechaDesde, DbType.DateTime2);
parameters.Add("@FechaFin", fechaHasta, DbType.DateTime2);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasPublicacionDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ConsumoBobinasPublicacionDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ConsumoBobinasPublicacionDto>(); }
}
@@ -352,7 +352,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@FechaInicioMesB", fechaInicioMesB, DbType.Date);
parameters.Add("@FechaFinMesB", fechaFinMesB, DbType.Date);
parameters.Add("@IdPlanta", idPlanta, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ComparativaConsumoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ComparativaConsumoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ComparativaConsumoBobinasDto>(); }
}
@@ -364,7 +364,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@FechaFinMesA", fechaFinMesA, DbType.Date);
parameters.Add("@FechaInicioMesB", fechaInicioMesB, DbType.Date);
parameters.Add("@FechaFinMesB", fechaFinMesB, DbType.Date);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ComparativaConsumoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<ComparativaConsumoBobinasDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<ComparativaConsumoBobinasDto>(); }
}
@@ -377,7 +377,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaDistDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaDistDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<BalanceCuentaDistDto>(); }
}
@@ -390,7 +390,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaDebCredDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaDebCredDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<BalanceCuentaDebCredDto>(); }
}
@@ -403,7 +403,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
parameters.Add("@fechaDesde", fechaDesde, DbType.DateTime);
parameters.Add("@fechaHasta", fechaHasta, DbType.DateTime);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaPagosDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<BalanceCuentaPagosDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<BalanceCuentaPagosDto>(); }
}
@@ -415,7 +415,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
parameters.Add("@Destino", destino, DbType.String);
parameters.Add("@idDestino", idDestino, DbType.Int32);
parameters.Add("@idEmpresa", idEmpresa, DbType.Int32);
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<SaldoDto>(spName, parameters, commandType: CommandType.StoredProcedure); }
try { using var connection = _dbConnectionFactory.CreateConnection(); return await connection.QueryAsync<SaldoDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120); }
catch (Exception ex) { _logger.LogError(ex, "Error SP {SPName}", spName); return Enumerable.Empty<SaldoDto>(); }
}
@@ -430,7 +430,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection(); // <--- CORREGIDO AQUÍ
return await connection.QueryAsync<ListadoDistribucionDistSimpleDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<ListadoDistribucionDistSimpleDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -450,7 +450,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection(); // <--- CORREGIDO AQUÍ
return await connection.QueryAsync<ListadoDistribucionDistPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<ListadoDistribucionDistPromedioDiaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -489,7 +489,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
return await connection.QueryAsync<LiquidacionCanillaDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<LiquidacionCanillaDetalleDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -507,7 +507,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
try
{
using var connection = _dbConnectionFactory.CreateConnection();
return await connection.QueryAsync<LiquidacionCanillaGananciaDto>(spName, parameters, commandType: CommandType.StoredProcedure);
return await connection.QueryAsync<LiquidacionCanillaGananciaDto>(spName, parameters, commandType: CommandType.StoredProcedure, commandTimeout: 120);
}
catch (Exception ex)
{
@@ -528,7 +528,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
return await connection.QueryAsync<ListadoDistCanMensualDiariosDto>(
"dbo.SP_DistCanillasAccConImporteEntreFechasDiarios",
parameters,
commandType: CommandType.StoredProcedure
commandType: CommandType.StoredProcedure, commandTimeout: 120
);
}
@@ -544,7 +544,7 @@ namespace GestionIntegral.Api.Data.Repositories.Reportes
return await connection.QueryAsync<ListadoDistCanMensualPubDto>(
"dbo.SP_DistCanillasAccConImporteEntreFechas",
parameters,
commandType: CommandType.StoredProcedure
commandType: CommandType.StoredProcedure, commandTimeout: 120
);
}
}

View File

@@ -27,22 +27,20 @@ RUN dotnet publish "GestionIntegral.Api.csproj" -c Release -o /app/publish /p:Us
# Usamos la imagen de runtime de ASP.NET, que es mucho más ligera que el SDK.
FROM mcr.microsoft.com/dotnet/aspnet:9.0
WORKDIR /app
# Instalamos libgdiplus + sus deps mínimas y creamos el symlink que .NET espera.
RUN apt-get update \
&& apt-get install -y --no-install-recommends \
libgdiplus \
libc6-dev \
libx11-dev \
libxrender1 \
libxtst6 \
libxi6 \
fontconfig \
&& ln -s /usr/lib/libgdiplus.so /usr/lib/gdiplus.dll \
&& rm -rf /var/lib/apt/lists/*
COPY --from=publish /app/publish .
# Instalar dependencias de Chromium en la imagen de ASP.NET (basada en Debian)
RUN apt-get update && apt-get install -y \
libgconf-2-4 \
libgdk-pixbuf2.0-0 \
libgtk-3-0 \
libnss3 \
libxss1 \
libasound2 \
libxtst6 \
--no-install-recommends && \
rm -rf /var/lib/apt/lists/*
# El puerto en el que la API escuchará DENTRO del contenedor.
# Usaremos 8080 para evitar conflictos si en el futuro corres algo en el puerto 80.
EXPOSE 8080

View File

@@ -4,14 +4,18 @@
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.66" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.3" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.8.0" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="6.0.2" />
<PackageReference Include="NPOI" Version="2.7.3" />
<PackageReference Include="PuppeteerSharp" Version="20.1.3" />
<PackageReference Include="RazorLight" Version="2.3.1" />
<PackageReference Include="ReportViewerCore.NETCore" Version="15.1.26" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.9.0" />

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
namespace GestionIntegral.Api.Dtos.Reportes.ViewModels
{
public class ExistenciaPapelConsolidadoViewModel
{
public IEnumerable<ExistenciaPapelDto> Existencias { get; set; } = new List<ExistenciaPapelDto>();
public string FechaDesde { get; set; } = string.Empty;
public string FechaHasta { get; set; } = string.Empty;
public string FechaReporte { get; set; } = DateTime.Now.ToString("dd/MM/yyyy");
}
}

View File

@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
namespace GestionIntegral.Api.Dtos.Reportes.ViewModels
{
public class ExistenciaPapelViewModel
{
public IEnumerable<ExistenciaPapelDto> Existencias { get; set; } = new List<ExistenciaPapelDto>();
public string NombrePlanta { get; set; } = string.Empty;
public string FechaDesde { get; set; } = string.Empty;
public string FechaHasta { get; set; } = string.Empty;
public string FechaReporte { get; set; } = DateTime.Now.ToString("dd/MM/yyyy");
}
}

View File

@@ -15,6 +15,7 @@ using GestionIntegral.Api.Data.Repositories.Usuarios;
using Microsoft.OpenApi.Models;
using GestionIntegral.Api.Data.Repositories.Reportes;
using GestionIntegral.Api.Services.Reportes;
using GestionIntegral.Api.Services.Pdf;
var builder = WebApplication.CreateBuilder(args);
@@ -92,6 +93,8 @@ builder.Services.AddScoped<ISaldoService, SaldoService>();
builder.Services.AddScoped<IReportesRepository, ReportesRepository>();
// Servicios de Reportes
builder.Services.AddScoped<IReportesService, ReportesService>();
// Servicio de PDF
builder.Services.AddScoped<IPdfGeneratorService, PuppeteerPdfGenerator>();
// --- Configuración de Autenticación JWT ---
var jwtSettings = builder.Configuration.GetSection("Jwt");

View File

@@ -0,0 +1,35 @@
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using PuppeteerSharp.Media;
namespace GestionIntegral.Api.Services.Pdf
{
/// <summary>
/// Define las opciones de configuración para la generación de un PDF.
/// </summary>
public class PdfGenerationOptions
{
public PaperFormat? Format { get; set; } = PaperFormat.A4;
public MarginOptions? Margin { get; set; }
public string? HeaderTemplate { get; set; }
public string? FooterTemplate { get; set; }
public bool PrintBackground { get; set; } = true;
public bool Landscape { get; set; } = false;
}
/// <summary>
/// Servicio para generar documentos PDF a partir de plantillas Razor.
/// </summary>
public interface IPdfGeneratorService
{
/// <summary>
/// Genera un archivo PDF a partir de una plantilla Razor y un modelo de datos.
/// </summary>
/// <typeparam name="T">El tipo del modelo de datos.</typeparam>
/// <param name="templatePath">La ruta relativa de la plantilla Razor (ej: "Controllers/Reportes/Templates/MiReporte.cshtml").</param>
/// <param name="model">El objeto con los datos para rellenar la plantilla.</param>
/// <param name="options">Opciones de configuración para el PDF (márgenes, formato, etc.).</param>
/// <returns>Un array de bytes representando el archivo PDF generado.</returns>
Task<byte[]> GeneratePdfFromRazorTemplateAsync<T>(string templatePath, T model, PdfGenerationOptions? options = null);
}
}

View File

@@ -0,0 +1,98 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PuppeteerSharp;
using PuppeteerSharp.Media;
using RazorLight;
using System;
using System.Threading.Tasks;
namespace GestionIntegral.Api.Services.Pdf
{
public class PuppeteerPdfGenerator : IPdfGeneratorService
{
private readonly IRazorLightEngine _razorEngine;
private readonly ILogger<PuppeteerPdfGenerator> _logger;
public PuppeteerPdfGenerator(IHostEnvironment hostEnvironment, ILogger<PuppeteerPdfGenerator> logger)
{
_logger = logger;
var rootPath = hostEnvironment.ContentRootPath;
_razorEngine = new RazorLightEngineBuilder()
.UseFileSystemProject(rootPath)
.UseMemoryCachingProvider()
.Build();
_logger.LogInformation("Verificando caché de Chromium…");
new BrowserFetcher().DownloadAsync().Wait();
_logger.LogInformation("Chromium listo en caché.");
}
public async Task<byte[]> GeneratePdfFromRazorTemplateAsync<T>(string templatePath, T model, PdfGenerationOptions? options = null)
{
if (string.IsNullOrEmpty(templatePath))
throw new ArgumentNullException(nameof(templatePath), "La ruta de la plantilla no puede ser nula o vacía.");
if (model == null)
throw new ArgumentNullException(nameof(model), "El modelo de datos no puede ser nulo.");
options ??= new PdfGenerationOptions();
string htmlContent;
try
{
htmlContent = await _razorEngine.CompileRenderAsync(templatePath, model);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error al compilar la plantilla Razor: {TemplatePath}", templatePath);
throw new InvalidOperationException($"No se pudo renderizar la plantilla Razor '{templatePath}'.", ex);
}
IBrowser? browser = null;
try
{
var launchOptions = new LaunchOptions
{
Headless = true,
Args = new[] { "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage" }
};
_logger.LogInformation("Lanzando Chromium headless…");
browser = await Puppeteer.LaunchAsync(launchOptions);
await using var page = await browser.NewPageAsync();
_logger.LogInformation("Estableciendo contenido HTML en la página.");
await page.SetContentAsync(htmlContent, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
_logger.LogInformation("Generando PDF…");
var pdfOptions = new PdfOptions
{
Format = options.Format,
HeaderTemplate = options.HeaderTemplate,
FooterTemplate = options.FooterTemplate,
PrintBackground = options.PrintBackground,
Landscape = options.Landscape,
MarginOptions = options.Margin ?? new MarginOptions()
};
var pdfBytes = await page.PdfDataAsync(pdfOptions);
_logger.LogInformation("PDF generado exitosamente ({Length} bytes).", pdfBytes.Length);
return pdfBytes;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error durante la generación del PDF con PuppeteerSharp.");
throw;
}
finally
{
if (browser is not null && !browser.IsClosed)
{
await browser.CloseAsync();
_logger.LogInformation("Navegador cerrado.");
}
}
}
}
}