fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
4c4591fee5
7 files changed
+326
-187
No files matched your search
+197
-165
@@ -150,14 +150,13 @@ export class PdfService {
|
||||
orderBy: { criadoEm: 'desc' },
|
||||
select: {
|
||||
id: true,
|
||||
headerImageUrl: true,
|
||||
footerImageUrl: true,
|
||||
logoUrl: true,
|
||||
timbradoUrl: true,
|
||||
timbradoMarginTop: true,
|
||||
timbradoMarginBottom: true,
|
||||
timbradoMarginLeft: true,
|
||||
timbradoMarginRight: true,
|
||||
templatePadrao: true,
|
||||
margensTemplate: true,
|
||||
criadoEm: true
|
||||
}
|
||||
});
|
||||
@@ -166,195 +165,228 @@ export class PdfService {
|
||||
|
||||
// Retornar configuração padrão se não existir
|
||||
return {
|
||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
||||
// Valores padrão
|
||||
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 || null,
|
||||
margensTemplate: config?.margensTemplate || null
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar configuração:', error);
|
||||
throw new Error('Falha ao buscar configuração');
|
||||
// Retornar configuração padrão 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: 100,
|
||||
timbradoMarginBottom: 50,
|
||||
timbradoMarginLeft: 50,
|
||||
timbradoMarginRight: 50,
|
||||
templatePadrao: null,
|
||||
margensTemplate: null
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private gerarHTML(content: string, config: any) {
|
||||
const timbradoUrl = config.timbradoUrl
|
||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
||||
: '';
|
||||
|
||||
console.log('Gerando PDF com timbrado:', 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>
|
||||
@page {
|
||||
margin: 0;
|
||||
size: A4;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'Fira Sans', Arial, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.page {
|
||||
position: relative;
|
||||
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-size: cover;
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.content {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="content">
|
||||
${content}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
async gerarPDF(conteudo: string, escritorio: any) {
|
||||
/**
|
||||
* Gera um PDF a partir do conteúdo HTML e dados do escritório
|
||||
* @param conteudo - Conteúdo HTML para o PDF
|
||||
* @param escritorio - Dados do escritório para substituir no template
|
||||
* @returns Buffer contendo o PDF gerado
|
||||
*/
|
||||
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
|
||||
try {
|
||||
// 1. Buscar configuração do template
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' }
|
||||
});
|
||||
|
||||
// 2. Gerar PDF do conteúdo
|
||||
const browser = await puppeteer.launch({
|
||||
headless: 'new',
|
||||
args: ['--no-sandbox']
|
||||
});
|
||||
|
||||
const page = await browser.newPage();
|
||||
console.log('Buscando configurações do documento...');
|
||||
const config = await this.getConfiguracao();
|
||||
|
||||
// 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;
|
||||
// Verificar se temos um timbrado para usar
|
||||
const temTimbrado = !!config.timbradoUrl;
|
||||
|
||||
console.log(`Iniciando geração de PDF ${temTimbrado ? 'com' : 'sem'} timbrado...`);
|
||||
|
||||
// Se temos timbrado, vamos primeiro verificar se ele existe
|
||||
let timbradoPath = '';
|
||||
let timbradoExists = false;
|
||||
|
||||
if (temTimbrado) {
|
||||
if (config.timbradoUrl.startsWith('/uploads')) {
|
||||
timbradoPath = path.join(process.cwd(), 'public', config.timbradoUrl);
|
||||
} else {
|
||||
timbradoPath = path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
|
||||
}
|
||||
|
||||
console.log('Verificando timbrado em:', timbradoPath);
|
||||
|
||||
try {
|
||||
await fs.access(timbradoPath);
|
||||
timbradoExists = true;
|
||||
console.log('Timbrado encontrado');
|
||||
} catch (e) {
|
||||
console.error('Timbrado não encontrado:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Margens definidas no template ou padrão
|
||||
const margens = config.margensTemplate || {
|
||||
top: config.timbradoMarginTop || 100,
|
||||
left: config.timbradoMarginLeft || 50,
|
||||
right: config.timbradoMarginRight || 50,
|
||||
bottom: config.timbradoMarginBottom || 50
|
||||
};
|
||||
|
||||
console.log('Usando margens:', margens);
|
||||
|
||||
/**
|
||||
* Gera o PDF final combinando o timbrado com o conteúdo
|
||||
*/
|
||||
const gerarPdfComTimbrado = async (
|
||||
content: string,
|
||||
pageW: number,
|
||||
pageH: number,
|
||||
margins: any,
|
||||
usesTimbrado: boolean,
|
||||
timbradoFilePath: string
|
||||
): Promise<Buffer> => {
|
||||
console.log('Gerando PDF com timbrado...');
|
||||
|
||||
const browser = await puppeteer.launch({
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
||||
headless: true
|
||||
});
|
||||
|
||||
try {
|
||||
// Gerar primeiro o PDF do conteúdo
|
||||
const page = await browser.newPage();
|
||||
await page.setContent(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<style>
|
||||
@page { size: A4; margin: 0; }
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
padding: ${margins.top}px ${margins.right}px ${margins.bottom}px ${margins.left}px;
|
||||
text-align: justify;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>${content}</body>
|
||||
</html>
|
||||
`, { waitUntil: 'networkidle0' });
|
||||
|
||||
const contentPdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
printBackground: true
|
||||
});
|
||||
|
||||
if (!usesTimbrado) {
|
||||
return contentPdfBuffer;
|
||||
}
|
||||
|
||||
try {
|
||||
// Carregar os PDFs
|
||||
const timbradoPdf = await PDFDocument.load(await fs.readFile(timbradoFilePath));
|
||||
const contentPdf = await PDFDocument.load(contentPdfBuffer);
|
||||
|
||||
// Criar documento final
|
||||
const finalPdf = await PDFDocument.create();
|
||||
|
||||
// Obter a primeira página do timbrado como template
|
||||
const [timbradoPage] = await finalPdf.copyPages(timbradoPdf, [0]);
|
||||
const contentPages = await finalPdf.copyPages(contentPdf, contentPdf.getPageIndices());
|
||||
|
||||
// Para cada página do conteúdo
|
||||
for (const contentPage of contentPages) {
|
||||
// 1. Adicionar nova página
|
||||
const newPage = finalPdf.addPage([pageW, pageH]);
|
||||
|
||||
// 2. Copiar conteúdo do timbrado para a nova página
|
||||
try {
|
||||
newPage.drawPage(timbradoPage, {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: pageW,
|
||||
height: pageH
|
||||
});
|
||||
|
||||
// 3. Copiar o conteúdo sobre o timbrado
|
||||
newPage.drawPage(contentPage, {
|
||||
x: margins.left,
|
||||
y: margins.bottom,
|
||||
width: pageW - margins.left - margins.right,
|
||||
height: pageH - margins.top - margins.bottom
|
||||
});
|
||||
} catch (pageError) {
|
||||
console.error('Erro ao processar página:', pageError);
|
||||
}
|
||||
}
|
||||
|
||||
p { margin: 0.7em 0; }
|
||||
h1, h2, h3 { margin: 0.8em 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="content">
|
||||
${conteudo}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
// Salvar o documento final
|
||||
const finalPdfBytes = await finalPdf.save();
|
||||
return Buffer.from(finalPdfBytes);
|
||||
|
||||
// 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'
|
||||
} catch (mergeError) {
|
||||
console.error('Erro ao mesclar PDFs:', mergeError);
|
||||
return contentPdfBuffer; // Retorna conteúdo original em caso de erro
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
};
|
||||
|
||||
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]);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 6. Gerar PDF final
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
return Buffer.from(pdfBytes);
|
||||
|
||||
// Processar o conteúdo e gerar o PDF
|
||||
const processedContent = this.processarTemplate(conteudo, escritorio);
|
||||
const pageWidth = 595;
|
||||
const pageHeight = 842;
|
||||
const pdfBytes = await gerarPdfComTimbrado(
|
||||
processedContent,
|
||||
pageWidth,
|
||||
pageHeight,
|
||||
margens,
|
||||
timbradoExists,
|
||||
timbradoPath
|
||||
);
|
||||
console.log(`PDF gerado com sucesso: ${pdfBytes.length} bytes`);
|
||||
return pdfBytes;
|
||||
} catch (error) {
|
||||
console.error('Erro ao gerar PDF:', error);
|
||||
throw new Error('Falha ao gerar PDF');
|
||||
console.error('Erro geral ao gerar PDF:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private processarTemplate(template: string, dados: any): string {
|
||||
return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
|
||||
const keyParts = key.trim().split('.');
|
||||
let value = dados;
|
||||
|
||||
for (const part of keyParts) {
|
||||
if (value && typeof value === 'object' && part in value) {
|
||||
value = value[part];
|
||||
} else {
|
||||
value = undefined;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return value !== undefined ? value : match;
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user