Lint errors

Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
rodrigo committed 2025-04-12 20:32:39 -03:00
1 parent 9742d62ba2
commit 5acec6b71e
196 files changed
+10885 -6655

No files matched your search

+72 -65
View File
@@ -1,8 +1,10 @@
import puppeteer from 'puppeteer';
import { prisma } from '../prismaClient';
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
import fs from 'fs/promises';
import path from 'path';
import fs from "fs/promises";
import path from "path";
import { PDFDocument, rgb, StandardFonts } from "pdf-lib";
import puppeteer from "puppeteer";
import { prisma } from "../prismaClient";
/**
* Serviço para geração e manipulação de arquivos PDF
@@ -15,7 +17,7 @@ export class PdfService {
async criarDocumento() {
return await PDFDocument.create();
}
/**
* Carrega um documento PDF existente
* @param pdfBytes - Bytes do PDF
@@ -24,7 +26,7 @@ export class PdfService {
async carregarDocumento(pdfBytes: Uint8Array) {
return await PDFDocument.load(pdfBytes);
}
/**
* Adiciona uma página ao documento
* @param doc - Documento PDF
@@ -34,7 +36,7 @@ export class PdfService {
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
return doc.addPage(tamanho);
}
/**
* Salva o documento como buffer
* @param doc - Documento PDF
@@ -44,7 +46,7 @@ export class PdfService {
const pdfBytes = await doc.save();
return Buffer.from(pdfBytes);
}
/**
* Carrega uma fonte padrão
* @param doc - Documento PDF
@@ -54,7 +56,7 @@ export class PdfService {
async carregarFonte(doc: any, fonte: StandardFonts) {
return await doc.embedFont(fonte);
}
/**
* Desenha texto em uma página
* @param pagina - Página do PDF
@@ -72,7 +74,7 @@ export class PdfService {
y: number,
fonte: any,
tamanho: number,
cor = rgb(0, 0, 0)
cor = rgb(0, 0, 0),
) {
pagina.drawText(texto, {
x,
@@ -82,7 +84,7 @@ export class PdfService {
color: cor,
});
}
/**
* Cria um cabeçalho para o documento
* @param pagina - Página do PDF
@@ -97,20 +99,12 @@ export class PdfService {
titulo: string,
fonte: any,
margemSuperior: number,
margem: number
margem: number,
): number {
const yPos = pagina.getHeight() - margemSuperior;
this.desenharTexto(
pagina,
titulo,
margem,
yPos,
fonte,
18,
rgb(0, 0, 0.7)
);
this.desenharTexto(pagina, titulo, margem, yPos, fonte, 18, rgb(0, 0, 0.7));
// Linha separadora
pagina.drawLine({
start: { x: margem, y: yPos - 10 },
@@ -118,10 +112,10 @@ export class PdfService {
thickness: 1,
color: rgb(0, 0, 0.5),
});
return yPos - 30; // Retorna a posição Y após o cabeçalho
}
/**
* Cria um rodapé para o documento
* @param pagina - Página do PDF
@@ -131,7 +125,7 @@ export class PdfService {
*/
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
const yPos = margem / 2;
this.desenharTexto(
pagina,
texto,
@@ -139,7 +133,7 @@ export class PdfService {
yPos,
fonte,
8,
rgb(0.5, 0.5, 0.5)
rgb(0.5, 0.5, 0.5),
);
}
@@ -147,7 +141,7 @@ export class PdfService {
try {
// Buscar configuração ou usar valores padrão
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' },
orderBy: { criadoEm: "desc" },
select: {
id: true,
headerImageUrl: true,
@@ -158,44 +152,48 @@ export class PdfService {
timbradoMarginBottom: true,
timbradoMarginLeft: true,
timbradoMarginRight: true,
criadoEm: true
}
criadoEm: true,
},
});
console.log('Configuração encontrada:', config); // Debug
console.log("Configuração encontrada:", config); // Debug
// Retornar configuração padrão se não existir
return {
cabecalhoHtml: config?.cabecalhoHtml || `
cabecalhoHtml:
config?.cabecalhoHtml ||
`
<div style="text-align: center; padding: 20px;">
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
</div>
`,
rodapeHtml: config?.rodapeHtml || `
rodapeHtml:
config?.rodapeHtml ||
`
<div style="text-align: center; font-size: 10pt;">
{{escritorio.endereco}}<br>
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
</div>
`,
logoUrl: config?.logoUrl || '',
timbradoUrl: config?.timbradoUrl || '',
logoUrl: config?.logoUrl || "",
timbradoUrl: config?.timbradoUrl || "",
timbradoMarginTop: config?.timbradoMarginTop || 100,
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
timbradoMarginRight: config?.timbradoMarginRight || 50
timbradoMarginRight: config?.timbradoMarginRight || 50,
};
} catch (error) {
console.error('Erro ao buscar configuração:', error);
throw new Error('Falha ao buscar configuração');
console.error("Erro ao buscar configuração:", error);
throw new Error("Falha ao buscar configuração");
}
}
private gerarHTML(content: string, config: any) {
const timbradoUrl = config.timbradoUrl
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
: '';
const timbradoUrl = config.timbradoUrl
? `${process.env.BACKEND_URL || "http://localhost:5000"}${config.timbradoUrl}`
: "";
console.log('Gerando PDF com timbrado:', timbradoUrl);
console.log("Gerando PDF com timbrado:", timbradoUrl);
return `
<!DOCTYPE html>
@@ -224,7 +222,7 @@ export class PdfService {
width: 21cm;
min-height: 29.7cm;
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px;
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
background: ${timbradoUrl ? `url('${timbradoUrl}')` : "none"};
background-size: cover;
background-position: center;
background-repeat: no-repeat;
@@ -252,19 +250,21 @@ export class PdfService {
try {
// 1. Buscar configuração do template
const config = await prisma.configuracaoDocumento.findFirst({
orderBy: { criadoEm: 'desc' }
orderBy: { criadoEm: "desc" },
});
// 2. Gerar PDF do conteúdo
const browser = await puppeteer.launch({
headless: 'new',
args: ['--no-sandbox']
headless: "new",
args: ["--no-sandbox"],
});
const page = await browser.newPage();
// Usar template padrão ou fallback para o template básico
const template = config?.templatePadrao || `
const template =
config?.templatePadrao ||
`
<!DOCTYPE html>
<html>
<head>
@@ -298,32 +298,40 @@ export class PdfService {
`;
// Processar o template substituindo variáveis
const templateProcessado = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
return escritorio[key.trim()] || match;
});
const templateProcessado = template.replace(
/\{\{(.+?)\}\}/g,
(match, key) => {
return escritorio[key.trim()] || match;
},
);
await page.setContent(templateProcessado);
const margens = config?.margensTemplate || {
top: '35mm',
bottom: '29mm',
left: '25mm',
right: '25mm'
top: "35mm",
bottom: "29mm",
left: "25mm",
right: "25mm",
};
const contentPdfBuffer = await page.pdf({
format: 'A4',
format: "A4",
margin: margens,
displayHeaderFooter: false,
printBackground: true
printBackground: true,
});
await browser.close();
// 2. Carregar os PDFs
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf');
const templatePath = path.join(
process.cwd(),
"public",
"uploads",
"Timbrado_2025.pdf",
);
const templateBytes = await fs.readFile(templatePath);
const templateDoc = await PDFDocument.load(templateBytes);
const contentDoc = await PDFDocument.load(contentPdfBuffer);
@@ -339,10 +347,10 @@ export class PdfService {
// Primeiro: adicionar template
const page = await pdfDoc.embedPage(templatePage);
const contentPage = await pdfDoc.embedPage(contentPages[i]);
// Segundo: criar nova página
const newPage = pdfDoc.addPage([page.width, page.height]);
// Terceiro: desenhar template e conteúdo
newPage.drawPage(page);
newPage.drawPage(contentPage);
@@ -351,10 +359,9 @@ export class PdfService {
// 6. Gerar PDF final
const pdfBytes = await pdfDoc.save();
return Buffer.from(pdfBytes);
} catch (error) {
console.error('Erro ao gerar PDF:', error);
throw new Error('Falha ao gerar PDF');
console.error("Erro ao gerar PDF:", error);
throw new Error("Falha ao gerar PDF");
}
}
}