fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
419af2a2e4
7 files changed
+509
-123
No files matched your search
+10
-3
@@ -1,11 +1,18 @@
|
||||
FROM node:20-slim
|
||||
|
||||
# Configurar Puppeteer para usar o Chromium do sistema
|
||||
ENV PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
|
||||
ENV PUPPETEER_EXECUTABLE_PATH=/usr/bin/chromium-browser
|
||||
|
||||
# Instalar dependências do sistema
|
||||
RUN apt-get update && apt-get install -y \
|
||||
chromium \
|
||||
RUN apt-get update && apt-get install -y chromium \
|
||||
libgconf-2-4 \
|
||||
postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& ln -sf /usr/bin/chromium /usr/bin/chromium-browser
|
||||
|
||||
# Verificar a instalação do Chromium
|
||||
RUN chromium --version
|
||||
|
||||
# Criar diretório da aplicação
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
version: '3.8'
|
||||
services:
|
||||
backend:
|
||||
build: .
|
||||
ports:
|
||||
- "5000:5000"
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- CHROME_BIN=/usr/bin/google-chrome-stable
|
||||
# ... outras variáveis de ambiente existentes ...
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
- /usr/src/app/node_modules
|
||||
+1
-6
@@ -49,6 +49,7 @@
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"opentimestamps-javascript": "^1.0.1",
|
||||
"pdf-lib": "^1.17.1",
|
||||
"pdfkit": "^0.13.0",
|
||||
"puppeteer": "^24.5.0",
|
||||
"qrcode": "^1.5.3",
|
||||
"react": "^18.2.0",
|
||||
@@ -111,11 +112,5 @@
|
||||
"--disable-gpu",
|
||||
"--window-size=1920x1080"
|
||||
]
|
||||
},
|
||||
"puppeteerOptions": {
|
||||
"browserFetcher": {
|
||||
"platform": "win32",
|
||||
"downloadPath": ".cache/puppeteer"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Identificar registros com UUID inválido
|
||||
SELECT id, uuid_column
|
||||
FROM atendimento
|
||||
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
|
||||
|
||||
-- Atualizar registros com UUID inválido
|
||||
UPDATE atendimento
|
||||
SET uuid_column = gen_random_uuid()
|
||||
WHERE uuid_column !~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$';
|
||||
@@ -200,7 +200,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
||||
// Monitorar o valor do CEP para autopreenchimento
|
||||
const cepValue = watch("cep");
|
||||
|
||||
// Função para buscar dados do CEP - versão com gerenciamento de estados do componente
|
||||
// Função para buscar dados do CEP - versão corrigida
|
||||
const fetchAddressByCep = useCallback(async (cep: string) => {
|
||||
if (!cep || cep.length !== 8) return;
|
||||
|
||||
@@ -213,7 +213,6 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
||||
|
||||
if (response.data && !response.data.erro) {
|
||||
// Usar estado local para garantir re-renderização imediata
|
||||
// Forçar preenchimento dos campos e atualização da interface
|
||||
const endereco = response.data.logradouro || "";
|
||||
const bairro = response.data.bairro || "";
|
||||
const cidade = response.data.localidade || "";
|
||||
@@ -225,8 +224,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
||||
setValue("cidade", cidade, { shouldValidate: true });
|
||||
setValue("estado", estado, { shouldValidate: true });
|
||||
|
||||
// Garantir re-renderização do componente
|
||||
// Esta é a parte crucial: forçar o componente a re-renderizar com novo estado
|
||||
// Atualizar o estado para re-renderização do componente
|
||||
setEnderecoState({
|
||||
endereco,
|
||||
bairro,
|
||||
@@ -235,13 +233,23 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
||||
preenchido: true,
|
||||
});
|
||||
|
||||
// Focar no próximo campo
|
||||
// Focar no próximo campo apenas se o usuário não estiver digitando ativamente
|
||||
// Esta alteração evita interromper o fluxo natural de preenchimento
|
||||
const activeElement = document.activeElement;
|
||||
const isUserTyping =
|
||||
activeElement &&
|
||||
(activeElement.tagName === 'INPUT' || activeElement.tagName === 'SELECT') &&
|
||||
activeElement !== document.querySelector('input[name="cep"]');
|
||||
|
||||
// Só focar no campo número se o usuário não estiver digitando em outro campo
|
||||
if (!isUserTyping) {
|
||||
setTimeout(() => {
|
||||
const numeroInput = document.querySelector(
|
||||
'input[name="numero"]'
|
||||
) as HTMLInputElement;
|
||||
if (numeroInput) numeroInput.focus();
|
||||
}, 100);
|
||||
}
|
||||
} else {
|
||||
console.error("CEP não encontrado");
|
||||
alert("CEP não encontrado. Por favor, verifique o CEP informado.");
|
||||
|
||||
+77
-2
@@ -55,6 +55,13 @@ const orgaoJulgadorRepository = new OrgaoJulgadorRepository();
|
||||
const custaProcessualRepository = new CustaProcessualRepository();
|
||||
const honorarioRepository = new HonorarioRepository();
|
||||
|
||||
// Atualizar a função isValidUUID para ser mais robusta
|
||||
const isValidUUID = (uuid: string | null | undefined): boolean => {
|
||||
if (!uuid) return false;
|
||||
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||
return uuidRegex.test(uuid);
|
||||
};
|
||||
|
||||
// Middleware para extrair usuário do token
|
||||
// Remover este middleware pois já temos o auth.ts
|
||||
// const extractUser = (req: any, res: any, next: any) => { ... }
|
||||
@@ -1000,9 +1007,9 @@ app.post("/api/atendimentos", authMiddleware, async (req, res) => {
|
||||
conteudo,
|
||||
cliente: { connect: { id: clienteId } },
|
||||
usuario: { connect: { id: req.user!.id } },
|
||||
...(processoId && { processo: { connect: { id: processoId } } }),
|
||||
...(processoId && { processo: { connect: { id: processoId } } }), // Adicionar vírgula aqui
|
||||
status: 'ATIVO',
|
||||
dataAtualizacao: new Date(),
|
||||
dataAtualizacao: new Date()
|
||||
},
|
||||
include: {
|
||||
cliente: true,
|
||||
@@ -1337,6 +1344,74 @@ app.delete("/api/agendamentos/:id", authMiddleware, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Atualizar a rota de agendamentos
|
||||
app.get("/api/atendimentos/agendamentos", async (req, res) => {
|
||||
try {
|
||||
const { data } = req.query;
|
||||
|
||||
if (!data || typeof data !== 'string') {
|
||||
return res.status(400).json({ error: 'Data inválida' });
|
||||
}
|
||||
|
||||
const dataConsulta = new Date(data);
|
||||
|
||||
// Validar se a data é válida
|
||||
if (isNaN(dataConsulta.getTime())) {
|
||||
return res.status(400).json({ error: 'Formato de data inválido' });
|
||||
}
|
||||
|
||||
// Definir início e fim do dia
|
||||
const inicioDia = new Date(dataConsulta.setHours(0, 0, 0, 0));
|
||||
const fimDia = new Date(dataConsulta.setHours(23, 59, 59, 999));
|
||||
|
||||
// Buscar na tabela correta com filtros apropriados
|
||||
const agendamentos = await prisma.agendamentoAtendimento.findMany({
|
||||
where: {
|
||||
data: {
|
||||
gte: inicioDia,
|
||||
lte: fimDia
|
||||
}
|
||||
},
|
||||
include: {
|
||||
cliente: {
|
||||
select: {
|
||||
id: true,
|
||||
nome: true,
|
||||
cpfCnpj: true,
|
||||
telefone: true
|
||||
}
|
||||
},
|
||||
usuario: {
|
||||
select: {
|
||||
id: true,
|
||||
nome: true
|
||||
}
|
||||
}
|
||||
},
|
||||
orderBy: {
|
||||
data: 'asc'
|
||||
}
|
||||
});
|
||||
|
||||
// Filtrar apenas agendamentos com UUIDs válidos
|
||||
const validAgendamentos = agendamentos.filter(agendamento =>
|
||||
isValidUUID(agendamento.id) &&
|
||||
isValidUUID(agendamento.clienteId) &&
|
||||
isValidUUID(agendamento.usuarioId)
|
||||
);
|
||||
|
||||
console.log(`Encontrados ${validAgendamentos.length} agendamentos válidos para ${data}`);
|
||||
|
||||
res.json(validAgendamentos);
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar agendamentos:', error);
|
||||
res.status(500).json({
|
||||
error: 'Erro ao buscar agendamentos',
|
||||
details: error instanceof Error ? error.message : 'Erro desconhecido'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Erro handling middleware
|
||||
app.use(
|
||||
(
|
||||
|
||||
+386
-107
@@ -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,475 @@ 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}`
|
||||
: '';
|
||||
/**
|
||||
* 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 {
|
||||
console.log('Buscando configurações do documento...');
|
||||
const config = await this.getConfiguracao();
|
||||
|
||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
||||
// Verificar se temos um timbrado para usar
|
||||
const temTimbrado = !!config.timbradoUrl;
|
||||
|
||||
return `
|
||||
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);
|
||||
|
||||
/**
|
||||
* Método alternativo para gerar PDF com timbrado sem usar drawPage
|
||||
* Esta abordagem renderiza duas vezes o PDF - uma para o timbrado, outra para o conteúdo
|
||||
* @param content O conteúdo HTML processado
|
||||
* @param pageW A largura da página
|
||||
* @param pageH A altura da página
|
||||
* @param margins As margens do documento
|
||||
* @param usesTimbrado Se o timbrado existe
|
||||
* @param timbradoFilePath O caminho para o arquivo de timbrado
|
||||
* @returns Buffer contendo o PDF gerado
|
||||
*/
|
||||
const gerarPdfComTimbrado = async (
|
||||
content: string,
|
||||
pageW: number,
|
||||
pageH: number,
|
||||
margins: any,
|
||||
usesTimbrado: boolean,
|
||||
timbradoFilePath: string
|
||||
): Promise<Buffer> => {
|
||||
console.log('Usando método alternativo para gerar PDF com timbrado (sem drawPage)...');
|
||||
|
||||
try {
|
||||
// 1. Configurar margens para o documento com o timbrado
|
||||
// Nota: estas margens são para o conteúdo, não afetam o timbrado
|
||||
const margensConteudo = {
|
||||
top: `${margins.top}px`,
|
||||
right: `${margins.right}px`,
|
||||
bottom: `${margins.bottom}px`,
|
||||
left: `${margins.left}px`
|
||||
};
|
||||
|
||||
// 2. Preparar HTML completo com estilos
|
||||
const htmlCompleto = `
|
||||
<!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">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
@page {
|
||||
margin: 0;
|
||||
size: A4;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: 'Fira Sans', Arial, sans-serif;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
position: relative;
|
||||
min-height: 100vh;
|
||||
margin: ${margins.top}px ${margins.right}px ${margins.bottom}px ${margins.left}px;
|
||||
text-align: justify;
|
||||
}
|
||||
|
||||
.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;
|
||||
.timbrado-wrapper {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
.content {
|
||||
.timbrado-img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
}
|
||||
.content-wrapper {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
p {
|
||||
margin: 0 0 0.5em 0;
|
||||
text-align: justify;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
margin-top: 1em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
strong, b {
|
||||
font-weight: bold;
|
||||
}
|
||||
em, i {
|
||||
font-style: italic;
|
||||
}
|
||||
u {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.justify {
|
||||
text-align: justify;
|
||||
}
|
||||
.indent {
|
||||
text-indent: 2em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="page">
|
||||
<div class="content">
|
||||
<div class="content-wrapper">
|
||||
${content}
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
|
||||
async gerarPDF(conteudo: string, escritorio: any) {
|
||||
try {
|
||||
// 1. Buscar configuração do template
|
||||
const config = await prisma.configuracaoDocumento.findFirst({
|
||||
orderBy: { criadoEm: 'desc' }
|
||||
});
|
||||
|
||||
// 2. Gerar PDF do conteúdo
|
||||
// 3. Iniciar o navegador Puppeteer
|
||||
const browser = await puppeteer.launch({
|
||||
headless: 'new',
|
||||
args: ['--no-sandbox']
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'],
|
||||
headless: true
|
||||
});
|
||||
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
|
||||
// Usar template padrão ou fallback para o template básico
|
||||
const template = config?.templatePadrao || `
|
||||
// 4. Configurar a página para renderização em PDF
|
||||
await page.setContent(htmlCompleto, { waitUntil: 'networkidle0' });
|
||||
await page.setViewport({ width: pageW, height: pageH });
|
||||
|
||||
// 5. Primeira renderização: documento sem timbrado
|
||||
const contentPdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
printBackground: true,
|
||||
margin: margensConteudo
|
||||
});
|
||||
|
||||
// Se não temos timbrado, então retornamos o PDF apenas com o conteúdo
|
||||
if (!usesTimbrado) {
|
||||
console.log('Documento gerado sem timbrado.');
|
||||
return contentPdfBuffer;
|
||||
}
|
||||
|
||||
// 6. Se temos timbrado, converter para base64 para incluir diretamente no HTML
|
||||
try {
|
||||
// Ler timbrado como base64
|
||||
const timbradoBase64 = await fs.readFile(timbradoFilePath, { encoding: 'base64' });
|
||||
const timbradoDataUrl = `data:application/pdf;base64,${timbradoBase64}`;
|
||||
|
||||
// Converter o timbrado para imagem usando Puppeteer
|
||||
const timbradoPage = await browser.newPage();
|
||||
await timbradoPage.goto('about:blank');
|
||||
|
||||
// Criar uma página HTML que irá renderizar o PDF como imagem
|
||||
const timbradoHtml = `
|
||||
<!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;
|
||||
body, html {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.content {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: calc(100vh - 58mm);
|
||||
position: relative;
|
||||
#pdfContainer {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
p { margin: 0.7em 0; }
|
||||
h1, h2, h3 { margin: 0.8em 0; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<object id="pdfContainer" data="${timbradoDataUrl}" type="application/pdf"></object>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
await timbradoPage.setContent(timbradoHtml, { waitUntil: 'networkidle0' });
|
||||
await timbradoPage.setViewport({ width: pageW, height: pageH });
|
||||
|
||||
// Capturar o timbrado como uma imagem PNG
|
||||
const timbradoImgBuffer = await timbradoPage.screenshot({
|
||||
type: 'png',
|
||||
omitBackground: true,
|
||||
fullPage: true
|
||||
});
|
||||
|
||||
// Converter para base64
|
||||
const timbradoImgBase64 = timbradoImgBuffer.toString('base64');
|
||||
const timbradoImgDataUrl = `data:image/png;base64,${timbradoImgBase64}`;
|
||||
|
||||
// 7. Agora criar um HTML que combina o timbrado como imagem de fundo e o conteúdo
|
||||
const combinedHtml = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<style>
|
||||
@page {
|
||||
margin: 0;
|
||||
size: A4;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
font-size: 11pt;
|
||||
line-height: 1.5;
|
||||
position: relative;
|
||||
}
|
||||
.background {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 1;
|
||||
background-image: url(${timbradoImgDataUrl});
|
||||
background-position: center;
|
||||
background-size: cover;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
.content {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 2;
|
||||
padding: ${margins.top}px ${margins.right}px ${margins.bottom}px ${margins.left}px;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
p {
|
||||
margin: 0 0 0.5em 0;
|
||||
text-align: justify;
|
||||
}
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
margin-top: 1em;
|
||||
margin-bottom: 0.5em;
|
||||
}
|
||||
strong, b { font-weight: bold; }
|
||||
em, i { font-style: italic; }
|
||||
u { text-decoration: underline; }
|
||||
.justify { text-align: justify; }
|
||||
.indent { text-indent: 2em; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="background"></div>
|
||||
<div class="content">
|
||||
${conteudo}
|
||||
${content}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
// Processar o template substituindo variáveis
|
||||
const templateProcessado = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
|
||||
return escritorio[key.trim()] || match;
|
||||
// 8. Renderizar o HTML combinado para PDF
|
||||
const combinedPage = await browser.newPage();
|
||||
await combinedPage.setContent(combinedHtml, { waitUntil: 'networkidle0' });
|
||||
await combinedPage.setViewport({ width: pageW, height: pageH });
|
||||
|
||||
const combinedPdfBuffer = await combinedPage.pdf({
|
||||
format: 'A4',
|
||||
printBackground: true,
|
||||
margin: {
|
||||
top: '0',
|
||||
right: '0',
|
||||
bottom: '0',
|
||||
left: '0'
|
||||
}
|
||||
});
|
||||
|
||||
await page.setContent(templateProcessado);
|
||||
console.log('PDF com timbrado gerado com sucesso usando método alternativo.');
|
||||
return combinedPdfBuffer;
|
||||
|
||||
const margens = config?.margensTemplate || {
|
||||
top: '35mm',
|
||||
bottom: '29mm',
|
||||
left: '25mm',
|
||||
right: '25mm'
|
||||
} catch (timbradoError) {
|
||||
console.error('Erro ao processar timbrado como imagem:', timbradoError);
|
||||
// Falha ao processar timbrado, retornar apenas o conteúdo
|
||||
return contentPdfBuffer;
|
||||
}
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro no método alternativo de geração do PDF:', error);
|
||||
// Cair para o método de fallback abaixo
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const contentPdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
margin: margens,
|
||||
displayHeaderFooter: false,
|
||||
printBackground: true
|
||||
try {
|
||||
// Usar o novo método que não depende de drawPage, passando todos os parâmetros necessários
|
||||
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 (finalError) {
|
||||
console.error('Todas as tentativas de gerar PDF falharam:', finalError);
|
||||
|
||||
try {
|
||||
// Método de último recurso - gerar PDF extremamente simples
|
||||
console.log('Gerando PDF extremamente simples como último recurso...');
|
||||
const simplePdf = await PDFDocument.create();
|
||||
const page = simplePdf.addPage([pageWidth, pageHeight]);
|
||||
const helvetica = await simplePdf.embedFont(StandardFonts.Helvetica);
|
||||
const helveticaBold = await simplePdf.embedFont(StandardFonts.HelveticaBold);
|
||||
|
||||
// Título
|
||||
page.drawText('Documento gerado pelo sistema', {
|
||||
x: 50,
|
||||
y: page.getHeight() - 50,
|
||||
font: helveticaBold,
|
||||
size: 14
|
||||
});
|
||||
|
||||
await browser.close();
|
||||
// Conteúdo simplificado
|
||||
const textContent = conteudo.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
const maxChars = Math.min(textContent.length, 1000);
|
||||
const truncatedText = textContent.substring(0, maxChars) + (textContent.length > maxChars ? '...' : '');
|
||||
|
||||
// 2. Carregar os PDFs
|
||||
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf');
|
||||
const templateBytes = await fs.readFile(templatePath);
|
||||
// Adicionar conteúdo em linhas
|
||||
const fontSize = 10;
|
||||
const lineHeight = fontSize * 1.5;
|
||||
const maxLineLength = 80;
|
||||
let currentY = page.getHeight() - 100;
|
||||
|
||||
const templateDoc = await PDFDocument.load(templateBytes);
|
||||
const contentDoc = await PDFDocument.load(contentPdfBuffer);
|
||||
for (let i = 0; i < truncatedText.length; i += maxLineLength) {
|
||||
const line = truncatedText.substring(i, i + maxLineLength);
|
||||
|
||||
// 3. Criar documento final
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
page.drawText(line, {
|
||||
x: 50,
|
||||
y: currentY,
|
||||
font: helvetica,
|
||||
size: fontSize
|
||||
});
|
||||
|
||||
// 4. Copiar template e conteúdo
|
||||
const [templatePage] = await templateDoc.copyPages(templateDoc, [0]);
|
||||
const contentPages = await contentDoc.getPages();
|
||||
currentY -= lineHeight;
|
||||
|
||||
// 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);
|
||||
// Verificar se precisa de nova página
|
||||
if (currentY < 50) {
|
||||
const newPage = simplePdf.addPage([pageWidth, pageHeight]);
|
||||
currentY = newPage.getHeight() - 50;
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Gerar PDF final
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
return Buffer.from(pdfBytes);
|
||||
// Informações adicionais
|
||||
page.drawText(`Gerado em: ${new Date().toLocaleString('pt-BR')}`, {
|
||||
x: 50,
|
||||
y: 30,
|
||||
font: helvetica,
|
||||
size: 8,
|
||||
color: rgb(0.5, 0.5, 0.5)
|
||||
});
|
||||
|
||||
const simpleBytes = await simplePdf.save();
|
||||
return Buffer.from(simpleBytes);
|
||||
} catch (criticalError) {
|
||||
console.error('Falha crítica na geração do PDF simples:', criticalError);
|
||||
|
||||
// Se tudo falhar, retornar um PDF mínimo
|
||||
const minimalBytes = Buffer.from(
|
||||
'%PDF-1.4\n1 0 obj\n<</Type/Catalog/Pages 2 0 R>>\nendobj\n2 0 obj\n<</Type/Pages/Kids[3 0 R]/Count 1>>\nendobj\n3 0 obj\n<</Type/Page/MediaBox[0 0 595 842]/Parent 2 0 R/Resources<<>>>>\nendobj\nxref\n0 4\n0000000000 65535 f\n0000000015 00000 n\n0000000060 00000 n\n0000000111 00000 n\ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n190\n%%EOF'
|
||||
);
|
||||
return minimalBytes;
|
||||
}
|
||||
}
|
||||
} 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