fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
c5f994dbb3
7 files changed
+310
-134
No files matched your search
+181
-112
@@ -146,19 +146,19 @@ export class PdfService {
|
||||
private async getConfiguracao() {
|
||||
try {
|
||||
// Buscar configuração ou usar valores padrão
|
||||
// Removendo campos que não existem no modelo
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
headerImageUrl: true,
|
||||
footerImageUrl: true,
|
||||
logoUrl: true,
|
||||
timbradoUrl: true,
|
||||
timbradoMarginTop: true,
|
||||
timbradoMarginBottom: true,
|
||||
timbradoMarginLeft: true,
|
||||
timbradoMarginRight: true,
|
||||
criadoEm: true
|
||||
criadoEm: true,
|
||||
templatePadrao: true,
|
||||
margensTemplate: true
|
||||
}
|
||||
});
|
||||
|
||||
@@ -166,44 +166,60 @@ export class PdfService {
|
||||
|
||||
// Retornar configuração padrão se não existir
|
||||
return {
|
||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
||||
// Valores padrão para campos que não existem mais no modelo
|
||||
cabecalhoHtml: `
|
||||
<div style="text-align: center; padding: 20px;">
|
||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
||||
</div>
|
||||
`,
|
||||
rodapeHtml: config?.rodapeHtml || `
|
||||
rodapeHtml: `
|
||||
<div style="text-align: center; font-size: 10pt;">
|
||||
{{escritorio.endereco}}<br>
|
||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
||||
</div>
|
||||
`,
|
||||
logoUrl: config?.logoUrl || '',
|
||||
// Campos que existem no modelo
|
||||
timbradoUrl: config?.timbradoUrl || '',
|
||||
timbradoMarginTop: config?.timbradoMarginTop || 100,
|
||||
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
|
||||
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
|
||||
timbradoMarginRight: config?.timbradoMarginRight || 50
|
||||
timbradoMarginRight: config?.timbradoMarginRight || 50,
|
||||
templatePadrao: config?.templatePadrao || false,
|
||||
margensTemplate: config?.margensTemplate || false
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar configuração:', error);
|
||||
throw new Error('Falha ao buscar configuração');
|
||||
// Returnar configuração padrão em caso de erro para não interromper o fluxo
|
||||
return {
|
||||
cabecalhoHtml: `<div style="text-align: center; padding: 20px;"><h2 style="margin:0;font-size:14pt">Documento</h2></div>`,
|
||||
rodapeHtml: `<div style="text-align: center; font-size: 10pt;">Documento gerado pelo sistema</div>`,
|
||||
timbradoUrl: '',
|
||||
timbradoMarginTop: 113,
|
||||
timbradoMarginBottom: 35,
|
||||
timbradoMarginLeft: 35,
|
||||
timbradoMarginRight: 00,
|
||||
templatePadrao: false,
|
||||
margensTemplate: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private gerarHTML(content: string, config: any) {
|
||||
// Corrigir a URL do timbrado para garantir o caminho completo sem importar o ambiente
|
||||
const timbradoUrl = config.timbradoUrl
|
||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
||||
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl.startsWith('/') ? '' : '/'}${config.timbradoUrl}`
|
||||
: '';
|
||||
|
||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
||||
console.log('Gerando PDF com timbrado (URL completa):', timbradoUrl);
|
||||
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
@import url('https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap');
|
||||
|
||||
@page {
|
||||
margin: 0;
|
||||
size: A4;
|
||||
@@ -212,7 +228,7 @@ export class PdfService {
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'Fira Sans', Arial, sans-serif;
|
||||
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
position: relative;
|
||||
@@ -224,16 +240,22 @@ 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'};
|
||||
box-sizing: border-box;
|
||||
background-image: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
|
||||
background-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||
}
|
||||
|
||||
/* Garantir que todos os elementos herdam a fonte */
|
||||
* {
|
||||
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
@@ -248,113 +270,160 @@ export class PdfService {
|
||||
`;
|
||||
}
|
||||
|
||||
async gerarPDF(conteudo: string, escritorio: any) {
|
||||
async gerarPDF(html: string): Promise<Buffer> {
|
||||
try {
|
||||
// 1. Buscar configuração do template
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' }
|
||||
console.log('Buscando configurações do documento...');
|
||||
const config = await this.getConfiguracao();
|
||||
console.log('Configurações aplicadas:', {
|
||||
timbradoUrl: config.timbradoUrl,
|
||||
margens: {
|
||||
top: config.timbradoMarginTop,
|
||||
bottom: config.timbradoMarginBottom,
|
||||
left: config.timbradoMarginLeft,
|
||||
right: config.timbradoMarginRight
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Gerar PDF do conteúdo
|
||||
|
||||
// Gerar HTML com as configurações
|
||||
const htmlCompleto = this.gerarHTML(html, config);
|
||||
|
||||
console.log('Iniciando geração de PDF com Chromium...');
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
headless: 'new',
|
||||
args: ['--no-sandbox']
|
||||
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
|
||||
headless: true,
|
||||
args: [
|
||||
'--no-sandbox',
|
||||
'--disable-setuid-sandbox',
|
||||
'--disable-dev-shm-usage',
|
||||
'--disable-gpu',
|
||||
'--font-render-hinting=medium',
|
||||
'--enable-font-antialiasing'
|
||||
],
|
||||
ignoreHTTPSErrors: true
|
||||
});
|
||||
|
||||
const page = await browser.newPage();
|
||||
console.log('Navegador iniciado com sucesso');
|
||||
|
||||
// Usar template padrão ou fallback para o template básico
|
||||
const template = config?.templatePadrao || `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Fira Sans', Arial, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.3;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: calc(100vh - 58mm);
|
||||
position: relative;
|
||||
}
|
||||
|
||||
p { margin: 0.7em 0; }
|
||||
h1, h2, h3 { margin: 0.8em 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
${conteudo}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
// Processar o template substituindo variáveis
|
||||
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'
|
||||
};
|
||||
|
||||
const contentPdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
margin: margens,
|
||||
displayHeaderFooter: false,
|
||||
printBackground: true
|
||||
});
|
||||
|
||||
await browser.close();
|
||||
|
||||
// 2. Carregar os PDFs
|
||||
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);
|
||||
|
||||
// 3. Criar documento final
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
|
||||
// 4. Copiar template e conteúdo
|
||||
const [templatePage] = await templateDoc.copyPages(templateDoc, [0]);
|
||||
const contentPages = await contentDoc.getPages();
|
||||
|
||||
// 5. Para cada página do conteúdo
|
||||
for (let i = 0; i < contentPages.length; i++) {
|
||||
// Primeiro: adicionar template
|
||||
const page = await pdfDoc.embedPage(templatePage);
|
||||
const contentPage = await pdfDoc.embedPage(contentPages[i]);
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
|
||||
// Segundo: criar nova página
|
||||
const newPage = pdfDoc.addPage([page.width, page.height]);
|
||||
// Garantir que fontes externas sejam carregadas
|
||||
await page.setExtraHTTPHeaders({
|
||||
'Accept-Language': 'pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7'
|
||||
});
|
||||
|
||||
// Terceiro: desenhar template e conteúdo
|
||||
newPage.drawPage(page);
|
||||
newPage.drawPage(contentPage);
|
||||
// Viewport A4
|
||||
await page.setViewport({
|
||||
width: 1240,
|
||||
height: 1754,
|
||||
deviceScaleFactor: 1.5
|
||||
});
|
||||
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
|
||||
console.log('Carregando conteúdo HTML...');
|
||||
|
||||
// Configurar avaliação de JavaScript
|
||||
await page.setJavaScriptEnabled(true);
|
||||
|
||||
// Esperar que o conteúdo e recursos sejam carregados
|
||||
await page.setContent(htmlCompleto, {
|
||||
waitUntil: 'networkidle0',
|
||||
timeout: 60000
|
||||
});
|
||||
|
||||
// Espera adicional para garantir carregamento de fontes e imagens
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
|
||||
// Injetar CSS adicional para forçar a fonte
|
||||
await page.addStyleTag({
|
||||
content: `
|
||||
@import url('https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap');
|
||||
body, * { font-family: 'Fira Sans', Arial, sans-serif !important; }
|
||||
`
|
||||
});
|
||||
|
||||
console.log('Gerando PDF...');
|
||||
const pdf = await page.pdf({
|
||||
format: 'A4',
|
||||
printBackground: true,
|
||||
margin: {
|
||||
top: '10mm',
|
||||
right: '10mm',
|
||||
bottom: '10mm',
|
||||
left: '10mm'
|
||||
},
|
||||
preferCSSPageSize: true,
|
||||
displayHeaderFooter: false
|
||||
});
|
||||
|
||||
console.log('PDF gerado com sucesso!');
|
||||
return Buffer.from(pdf);
|
||||
} finally {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
await browser.close();
|
||||
console.log('Navegador fechado com segurança');
|
||||
}
|
||||
|
||||
// 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 detalhado ao gerar PDF:', error);
|
||||
try {
|
||||
console.log('Tentando gerar PDF alternativo com pdf-lib...');
|
||||
|
||||
// Criar um documento PDF simples com o conteúdo
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
const page = pdfDoc.addPage([595, 842]); // A4
|
||||
|
||||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
|
||||
// Adicionar texto informativo
|
||||
page.drawText('Não foi possível gerar o PDF com o layout desejado', {
|
||||
x: 50,
|
||||
y: 800,
|
||||
size: 16,
|
||||
font
|
||||
});
|
||||
|
||||
page.drawText('Por favor, entre em contato com o suporte.', {
|
||||
x: 50,
|
||||
y: 750,
|
||||
size: 12,
|
||||
font
|
||||
});
|
||||
|
||||
// Adicionar parte do HTML como texto simples (até 1000 caracteres)
|
||||
const plainText = html.replace(/<[^>]*>/g, ' ').slice(0, 1000) + '...';
|
||||
|
||||
page.drawText('Conteúdo original (parcial):', {
|
||||
x: 50,
|
||||
y: 700,
|
||||
size: 10,
|
||||
font
|
||||
});
|
||||
|
||||
// Quebrar o texto em linhas
|
||||
const linhas = [];
|
||||
for (let i = 0; i < plainText.length; i += 80) {
|
||||
linhas.push(plainText.substring(i, i + 80));
|
||||
}
|
||||
|
||||
// Adicionar no máximo 30 linhas
|
||||
linhas.slice(0, 30).forEach((linha, index) => {
|
||||
page.drawText(linha, {
|
||||
x: 50,
|
||||
y: 670 - (index * 15),
|
||||
size: 8,
|
||||
font
|
||||
});
|
||||
});
|
||||
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
return Buffer.from(pdfBytes);
|
||||
|
||||
} catch (fallbackError) {
|
||||
console.error('Erro também no método alternativo:', fallbackError);
|
||||
throw new Error('Falha ao gerar PDF: não foi possível criar o documento');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user