fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
c77110989c
7 files changed
+571
-169
No files matched your search
+10
-3
@@ -1,11 +1,18 @@
|
|||||||
FROM node:20-slim
|
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
|
# Instalar dependências do sistema
|
||||||
RUN apt-get update && apt-get install -y \
|
RUN apt-get update && apt-get install -y chromium \
|
||||||
chromium \
|
|
||||||
libgconf-2-4 \
|
libgconf-2-4 \
|
||||||
postgresql-client \
|
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
|
# Criar diretório da aplicação
|
||||||
WORKDIR /usr/src/app
|
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",
|
"multer": "^1.4.5-lts.1",
|
||||||
"opentimestamps-javascript": "^1.0.1",
|
"opentimestamps-javascript": "^1.0.1",
|
||||||
"pdf-lib": "^1.17.1",
|
"pdf-lib": "^1.17.1",
|
||||||
|
"pdfkit": "^0.13.0",
|
||||||
"puppeteer": "^24.5.0",
|
"puppeteer": "^24.5.0",
|
||||||
"qrcode": "^1.5.3",
|
"qrcode": "^1.5.3",
|
||||||
"react": "^18.2.0",
|
"react": "^18.2.0",
|
||||||
@@ -111,11 +112,5 @@
|
|||||||
"--disable-gpu",
|
"--disable-gpu",
|
||||||
"--window-size=1920x1080"
|
"--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
|
// Monitorar o valor do CEP para autopreenchimento
|
||||||
const cepValue = watch("cep");
|
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) => {
|
const fetchAddressByCep = useCallback(async (cep: string) => {
|
||||||
if (!cep || cep.length !== 8) return;
|
if (!cep || cep.length !== 8) return;
|
||||||
|
|
||||||
@@ -213,7 +213,6 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
|
|
||||||
if (response.data && !response.data.erro) {
|
if (response.data && !response.data.erro) {
|
||||||
// Usar estado local para garantir re-renderização imediata
|
// 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 endereco = response.data.logradouro || "";
|
||||||
const bairro = response.data.bairro || "";
|
const bairro = response.data.bairro || "";
|
||||||
const cidade = response.data.localidade || "";
|
const cidade = response.data.localidade || "";
|
||||||
@@ -225,8 +224,7 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
setValue("cidade", cidade, { shouldValidate: true });
|
setValue("cidade", cidade, { shouldValidate: true });
|
||||||
setValue("estado", estado, { shouldValidate: true });
|
setValue("estado", estado, { shouldValidate: true });
|
||||||
|
|
||||||
// Garantir re-renderização do componente
|
// Atualizar o estado para re-renderização do componente
|
||||||
// Esta é a parte crucial: forçar o componente a re-renderizar com novo estado
|
|
||||||
setEnderecoState({
|
setEnderecoState({
|
||||||
endereco,
|
endereco,
|
||||||
bairro,
|
bairro,
|
||||||
@@ -235,13 +233,23 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
preenchido: true,
|
preenchido: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Focar no próximo campo
|
// Focar no próximo campo apenas se o usuário não estiver digitando ativamente
|
||||||
setTimeout(() => {
|
// Esta alteração evita interromper o fluxo natural de preenchimento
|
||||||
const numeroInput = document.querySelector(
|
const activeElement = document.activeElement;
|
||||||
'input[name="numero"]'
|
const isUserTyping =
|
||||||
) as HTMLInputElement;
|
activeElement &&
|
||||||
if (numeroInput) numeroInput.focus();
|
(activeElement.tagName === 'INPUT' || activeElement.tagName === 'SELECT') &&
|
||||||
}, 100);
|
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 {
|
} else {
|
||||||
console.error("CEP não encontrado");
|
console.error("CEP não encontrado");
|
||||||
alert("CEP não encontrado. Por favor, verifique o CEP informado.");
|
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 custaProcessualRepository = new CustaProcessualRepository();
|
||||||
const honorarioRepository = new HonorarioRepository();
|
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
|
// Middleware para extrair usuário do token
|
||||||
// Remover este middleware pois já temos o auth.ts
|
// Remover este middleware pois já temos o auth.ts
|
||||||
// const extractUser = (req: any, res: any, next: any) => { ... }
|
// const extractUser = (req: any, res: any, next: any) => { ... }
|
||||||
@@ -1000,9 +1007,9 @@ app.post("/api/atendimentos", authMiddleware, async (req, res) => {
|
|||||||
conteudo,
|
conteudo,
|
||||||
cliente: { connect: { id: clienteId } },
|
cliente: { connect: { id: clienteId } },
|
||||||
usuario: { connect: { id: req.user!.id } },
|
usuario: { connect: { id: req.user!.id } },
|
||||||
...(processoId && { processo: { connect: { id: processoId } } }),
|
...(processoId && { processo: { connect: { id: processoId } } }), // Adicionar vírgula aqui
|
||||||
status: 'ATIVO',
|
status: 'ATIVO',
|
||||||
dataAtualizacao: new Date(),
|
dataAtualizacao: new Date()
|
||||||
},
|
},
|
||||||
include: {
|
include: {
|
||||||
cliente: true,
|
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
|
// Erro handling middleware
|
||||||
app.use(
|
app.use(
|
||||||
(
|
(
|
||||||
|
|||||||
+442
-147
@@ -150,14 +150,13 @@ export class PdfService {
|
|||||||
orderBy: { criadoEm: 'desc' },
|
orderBy: { criadoEm: 'desc' },
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
headerImageUrl: true,
|
|
||||||
footerImageUrl: true,
|
|
||||||
logoUrl: true,
|
|
||||||
timbradoUrl: true,
|
timbradoUrl: true,
|
||||||
timbradoMarginTop: true,
|
timbradoMarginTop: true,
|
||||||
timbradoMarginBottom: true,
|
timbradoMarginBottom: true,
|
||||||
timbradoMarginLeft: true,
|
timbradoMarginLeft: true,
|
||||||
timbradoMarginRight: true,
|
timbradoMarginRight: true,
|
||||||
|
templatePadrao: true,
|
||||||
|
margensTemplate: true,
|
||||||
criadoEm: true
|
criadoEm: true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -166,195 +165,491 @@ export class PdfService {
|
|||||||
|
|
||||||
// Retornar configuração padrão se não existir
|
// Retornar configuração padrão se não existir
|
||||||
return {
|
return {
|
||||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
// Valores padrão
|
||||||
|
cabecalhoHtml: `
|
||||||
<div style="text-align: center; padding: 20px;">
|
<div style="text-align: center; padding: 20px;">
|
||||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
rodapeHtml: config?.rodapeHtml || `
|
rodapeHtml: `
|
||||||
<div style="text-align: center; font-size: 10pt;">
|
<div style="text-align: center; font-size: 10pt;">
|
||||||
{{escritorio.endereco}}<br>
|
{{escritorio.endereco}}<br>
|
||||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
||||||
</div>
|
</div>
|
||||||
`,
|
`,
|
||||||
logoUrl: config?.logoUrl || '',
|
// Campos que existem no modelo
|
||||||
timbradoUrl: config?.timbradoUrl || '',
|
timbradoUrl: config?.timbradoUrl || '',
|
||||||
timbradoMarginTop: config?.timbradoMarginTop || 100,
|
timbradoMarginTop: config?.timbradoMarginTop || 100,
|
||||||
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
|
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
|
||||||
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
|
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
|
||||||
timbradoMarginRight: config?.timbradoMarginRight || 50
|
timbradoMarginRight: config?.timbradoMarginRight || 50,
|
||||||
|
templatePadrao: config?.templatePadrao || null,
|
||||||
|
margensTemplate: config?.margensTemplate || null
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao buscar configuração:', 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
|
* Gera um PDF a partir do conteúdo HTML e dados do escritório
|
||||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
* @param conteudo - Conteúdo HTML para o PDF
|
||||||
: '';
|
* @param escritorio - Dados do escritório para substituir no template
|
||||||
|
* @returns Buffer contendo o PDF gerado
|
||||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
*/
|
||||||
|
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
|
||||||
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) {
|
|
||||||
try {
|
try {
|
||||||
// 1. Buscar configuração do template
|
console.log('Buscando configurações do documento...');
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
const config = await this.getConfiguracao();
|
||||||
orderBy: { criadoEm: 'desc' }
|
|
||||||
});
|
|
||||||
|
|
||||||
// 2. Gerar PDF do conteúdo
|
// Verificar se temos um timbrado para usar
|
||||||
const browser = await puppeteer.launch({
|
const temTimbrado = !!config.timbradoUrl;
|
||||||
headless: 'new',
|
|
||||||
args: ['--no-sandbox']
|
|
||||||
});
|
|
||||||
|
|
||||||
const page = await browser.newPage();
|
console.log(`Iniciando geração de PDF ${temTimbrado ? 'com' : 'sem'} timbrado...`);
|
||||||
|
|
||||||
// Usar template padrão ou fallback para o template básico
|
// Se temos timbrado, vamos primeiro verificar se ele existe
|
||||||
const template = config?.templatePadrao || `
|
let timbradoPath = '';
|
||||||
<!DOCTYPE html>
|
let timbradoExists = false;
|
||||||
<html>
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
// Abordagem absolutamente básica e direta
|
||||||
|
try {
|
||||||
|
console.log('Gerando PDF básico...');
|
||||||
|
|
||||||
|
// Processar o template com dados do escritório
|
||||||
|
const processedContent = this.processarTemplate(conteudo, escritorio);
|
||||||
|
|
||||||
|
// HTML muito simples
|
||||||
|
const htmlBasico = `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
|
<meta charset="UTF-8">
|
||||||
<style>
|
<style>
|
||||||
|
@page { size: A4; margin: 0; }
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
font-family: Arial, sans-serif;
|
||||||
font-size: 11pt;
|
font-size: 11pt;
|
||||||
line-height: 1.3;
|
line-height: 1.5;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: ${margens.top}px ${margens.right}px ${margens.bottom}px ${margens.left}px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
h1, h2, h3 { margin: 0.8em 0 0.4em 0; }
|
||||||
margin: 0;
|
p { margin: 0.4em 0; }
|
||||||
padding: 0;
|
|
||||||
min-height: calc(100vh - 58mm);
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
p { margin: 0.7em 0; }
|
table { border-collapse: collapse; width: 100%; }
|
||||||
h1, h2, h3 { margin: 0.8em 0; }
|
th, td { border: 1px solid #ddd; padding: 4px; }
|
||||||
|
|
||||||
|
.header { margin-bottom: 20px; font-weight: bold; }
|
||||||
|
.footer { margin-top: 20px; font-size: 9pt; color: #666; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="content">
|
<div class="header">${escritorio.nome || 'Documento'}</div>
|
||||||
${conteudo}
|
${processedContent}
|
||||||
</div>
|
<div class="footer">Gerado em: ${new Date().toLocaleDateString('pt-BR')}</div>
|
||||||
</body>
|
</body>
|
||||||
|
</html>
|
||||||
|
`;
|
||||||
|
|
||||||
|
// Tentar diretamente com pdf-lib para evitar problemas com Puppeteer
|
||||||
|
try {
|
||||||
|
console.log('Tentando gerar PDF com pdf-lib diretamente...');
|
||||||
|
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]); // A4
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||||
|
|
||||||
|
// Cabeçalho
|
||||||
|
page.drawText(escritorio.nome || 'Documento', {
|
||||||
|
x: margens.left,
|
||||||
|
y: 842 - margens.top,
|
||||||
|
size: 14,
|
||||||
|
font: boldFont
|
||||||
|
});
|
||||||
|
|
||||||
|
// Data
|
||||||
|
const currentDate = new Date().toLocaleDateString('pt-BR');
|
||||||
|
page.drawText(`Data: ${currentDate}`, {
|
||||||
|
x: margens.left,
|
||||||
|
y: 842 - margens.top - 20,
|
||||||
|
size: 11,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Processar conteúdo HTML para texto simples
|
||||||
|
const textContent = conteudo
|
||||||
|
.replace(/<br\s*\/?>/gi, '\n')
|
||||||
|
.replace(/<p[^>]*>(.*?)<\/p>/gi, '$1\n\n')
|
||||||
|
.replace(/<h[1-6][^>]*>(.*?)<\/h[1-6]>/gi, '$1\n\n')
|
||||||
|
.replace(/<li[^>]*>(.*?)<\/li>/gi, '• $1\n')
|
||||||
|
.replace(/<[^>]*>/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
// Quebrar texto em linhas com largura apropriada
|
||||||
|
const maxWidth = 595 - margens.left - margens.right;
|
||||||
|
const charWidth = 5.5; // Estimativa para fonte tamanho 10
|
||||||
|
const maxCharsPerLine = Math.floor(maxWidth / charWidth);
|
||||||
|
|
||||||
|
const lines = [];
|
||||||
|
const words = textContent.split(' ');
|
||||||
|
let currentLine = '';
|
||||||
|
|
||||||
|
for (const word of words) {
|
||||||
|
const testLine = currentLine ? `${currentLine} ${word}` : word;
|
||||||
|
if (testLine.length > maxCharsPerLine) {
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
currentLine = word;
|
||||||
|
} else {
|
||||||
|
lines.push(word);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
currentLine = testLine;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentLine) {
|
||||||
|
lines.push(currentLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adicionar linhas ao PDF
|
||||||
|
let y = 842 - margens.top - 50; // Posição inicial após cabeçalho
|
||||||
|
const lineHeight = 14;
|
||||||
|
let currentPage = page;
|
||||||
|
|
||||||
|
// Adicionar linhas, criando novas páginas quando necessário
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
// Verificar se precisamos de nova página
|
||||||
|
if (y < margens.bottom) {
|
||||||
|
currentPage = pdfDoc.addPage([595, 842]);
|
||||||
|
y = 842 - margens.top;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentPage.drawText(lines[i], {
|
||||||
|
x: margens.left,
|
||||||
|
y,
|
||||||
|
size: 10,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
y -= lineHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adicionar rodapé na última página
|
||||||
|
if (escritorio.endereco) {
|
||||||
|
currentPage.drawText(escritorio.endereco, {
|
||||||
|
x: margens.left,
|
||||||
|
y: margens.bottom - 20,
|
||||||
|
size: 8,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (escritorio.telefone || escritorio.email) {
|
||||||
|
let contactInfo = '';
|
||||||
|
if (escritorio.telefone) contactInfo += `Tel: ${escritorio.telefone}`;
|
||||||
|
if (escritorio.telefone && escritorio.email) contactInfo += ' | ';
|
||||||
|
if (escritorio.email) contactInfo += `Email: ${escritorio.email}`;
|
||||||
|
|
||||||
|
currentPage.drawText(contactInfo, {
|
||||||
|
x: margens.left,
|
||||||
|
y: margens.bottom - 30,
|
||||||
|
size: 8,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Salvar PDF
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
console.log('PDF gerado com pdf-lib com sucesso');
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
} catch (pdfLibError) {
|
||||||
|
console.error('Erro ao gerar com pdf-lib:', pdfLibError);
|
||||||
|
// Tentar com Puppeteer como backup
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se falhar com pdf-lib, tentar com Puppeteer como backup
|
||||||
|
console.log('Tentando gerar com Puppeteer como backup...');
|
||||||
|
|
||||||
|
// Configuração básica do Puppeteer
|
||||||
|
const browser = await puppeteer.launch({
|
||||||
|
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
|
||||||
|
headless: true,
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const page = await browser.newPage();
|
||||||
|
|
||||||
|
// Configurações simplificadas
|
||||||
|
await page.setDefaultNavigationTimeout(0);
|
||||||
|
await page.setContent(htmlBasico, { waitUntil: 'networkidle0' });
|
||||||
|
|
||||||
|
// Gerar PDF com configurações mínimas
|
||||||
|
const pdfBuffer = await page.pdf({
|
||||||
|
format: 'A4',
|
||||||
|
printBackground: true
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`PDF gerado com Puppeteer: ${pdfBuffer.length} bytes`);
|
||||||
|
return pdfBuffer;
|
||||||
|
} finally {
|
||||||
|
await browser.close();
|
||||||
|
console.log('Navegador fechado');
|
||||||
|
}
|
||||||
|
} catch (mainError) {
|
||||||
|
console.error('Erro na geração principal:', mainError);
|
||||||
|
|
||||||
|
// Fallback extremamente básico
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]);
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
|
||||||
|
page.drawText('Documento', {
|
||||||
|
x: 50,
|
||||||
|
y: 800,
|
||||||
|
size: 14,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Extrair texto básico do HTML
|
||||||
|
const plainText = conteudo
|
||||||
|
.replace(/<[^>]*>/g, ' ')
|
||||||
|
.replace(/\s+/g, ' ')
|
||||||
|
.trim()
|
||||||
|
.slice(0, 2000);
|
||||||
|
|
||||||
|
// Quebrar em linhas de 70 caracteres
|
||||||
|
for (let i = 0, y = 770; i < plainText.length && y > 50; i += 70, y -= 12) {
|
||||||
|
const line = plainText.substring(i, i + 70);
|
||||||
|
page.drawText(line, {
|
||||||
|
x: 50,
|
||||||
|
y,
|
||||||
|
size: 9,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
console.log('Gerado PDF de emergência');
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro geral ao gerar PDF:', error);
|
||||||
|
|
||||||
|
// Método de fallback extremamente básico
|
||||||
|
try {
|
||||||
|
console.log('Usando método de fallback simples...');
|
||||||
|
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]);
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
|
||||||
|
// Título
|
||||||
|
page.drawText('Documento de Emergência', {
|
||||||
|
x: 50,
|
||||||
|
y: 800,
|
||||||
|
size: 16,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mensagem de erro
|
||||||
|
page.drawText('Este documento foi gerado em modo de emergência.', {
|
||||||
|
x: 50,
|
||||||
|
y: 760,
|
||||||
|
size: 10,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Adicionar parte do conteúdo como texto plano
|
||||||
|
const plainText = conteudo.replace(/<[^>]*>/g, ' ').slice(0, 1000);
|
||||||
|
|
||||||
|
// Quebrar em linhas
|
||||||
|
const lines = [];
|
||||||
|
for (let i = 0; i < plainText.length; i += 70) {
|
||||||
|
lines.push(plainText.substring(i, i + 70));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adicionar no máximo 30 linhas
|
||||||
|
lines.slice(0, 30).forEach((line, index) => {
|
||||||
|
page.drawText(line, {
|
||||||
|
x: 50,
|
||||||
|
y: 720 - (index * 12),
|
||||||
|
size: 8,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
} catch (fallbackError) {
|
||||||
|
console.error('Falha no fallback:', fallbackError);
|
||||||
|
throw new Error('Falha completa ao gerar PDF');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Método alternativo para aplicar timbrado quando pdf-lib falha
|
||||||
|
* @param contentPdfBuffer Buffer do PDF de conteúdo
|
||||||
|
* @param timbradoPath Caminho do arquivo de timbrado
|
||||||
|
* @returns Buffer do PDF combinado
|
||||||
|
*/
|
||||||
|
private async aplicarTimbradoAlternativo(contentPdfBuffer: Buffer, timbradoPath: string): Promise<Buffer> {
|
||||||
|
console.log('Tentando método alternativo para aplicar timbrado...');
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Criar diretório temporário se não existir
|
||||||
|
const tmpDir = path.join(process.cwd(), 'tmp');
|
||||||
|
try {
|
||||||
|
await fs.mkdir(tmpDir, { recursive: true });
|
||||||
|
} catch (mkdirErr) {
|
||||||
|
// Ignorar erro se o diretório já existir
|
||||||
|
}
|
||||||
|
|
||||||
|
// Criar arquivos temporários
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const contentTempPath = path.join(tmpDir, `content-${timestamp}.pdf`);
|
||||||
|
const outputTempPath = path.join(tmpDir, `output-${timestamp}.pdf`);
|
||||||
|
|
||||||
|
// Salvar conteúdo em arquivo temporário
|
||||||
|
await fs.writeFile(contentTempPath, contentPdfBuffer);
|
||||||
|
|
||||||
|
// Tentar gerar um novo PDF a partir de um HTML que inclui o conteúdo em um iframe
|
||||||
|
// e o timbrado como uma imagem de fundo
|
||||||
|
const relativeTimbradoPath = path.relative(process.cwd(), timbradoPath);
|
||||||
|
const htmlWithTimbrado = `
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<style>
|
||||||
|
body, html { margin: 0; padding: 0; height: 100%; }
|
||||||
|
.timbrado {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
.content {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<img class="timbrado" src="file://${relativeTimbradoPath}" />
|
||||||
|
<iframe class="content" src="file://${contentTempPath}" frameborder="0"></iframe>
|
||||||
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Processar o template substituindo variáveis
|
const htmlTempPath = path.join(tmpDir, `combined-${timestamp}.html`);
|
||||||
const templateProcessado = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
|
await fs.writeFile(htmlTempPath, htmlWithTimbrado);
|
||||||
return escritorio[key.trim()] || match;
|
|
||||||
|
// Gerar PDF com Puppeteer
|
||||||
|
const browser = await puppeteer.launch({
|
||||||
|
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
|
||||||
|
headless: true,
|
||||||
|
args: ['--no-sandbox', '--disable-setuid-sandbox']
|
||||||
});
|
});
|
||||||
|
|
||||||
await page.setContent(templateProcessado);
|
try {
|
||||||
|
const page = await browser.newPage();
|
||||||
|
await page.goto(`file://${htmlTempPath}`, { waitUntil: 'networkidle0' });
|
||||||
|
|
||||||
const margens = config?.margensTemplate || {
|
const pdf = await page.pdf({
|
||||||
top: '35mm',
|
format: 'A4',
|
||||||
bottom: '29mm',
|
printBackground: true
|
||||||
left: '25mm',
|
});
|
||||||
right: '25mm'
|
|
||||||
};
|
|
||||||
|
|
||||||
const contentPdfBuffer = await page.pdf({
|
// Limpar arquivos temporários
|
||||||
format: 'A4',
|
await fs.unlink(contentTempPath).catch(() => {});
|
||||||
margin: margens,
|
await fs.unlink(htmlTempPath).catch(() => {});
|
||||||
displayHeaderFooter: false,
|
|
||||||
printBackground: true
|
|
||||||
});
|
|
||||||
|
|
||||||
await browser.close();
|
return pdf;
|
||||||
|
} finally {
|
||||||
// 2. Carregar os PDFs
|
await browser.close();
|
||||||
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);
|
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao gerar PDF:', error);
|
console.error('Erro no método alternativo:', error);
|
||||||
throw new Error('Falha ao gerar PDF');
|
// Retornar apenas o conteúdo em caso de falha
|
||||||
|
return contentPdfBuffer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Processa um template HTML substituindo variáveis pelos valores do objeto
|
||||||
|
* @param template - Template HTML com variáveis no formato {{variavel}}
|
||||||
|
* @param dados - Objeto com valores para substituir
|
||||||
|
* @returns Template processado
|
||||||
|
*/
|
||||||
|
private processarTemplate(template: string, dados: any): string {
|
||||||
|
return template.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
|
||||||
|
const keyParts = key.trim().split('.');
|
||||||
|
let value = dados;
|
||||||
|
|
||||||
|
// Acessar propriedades aninhadas (ex: escritorio.nome)
|
||||||
|
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