fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
fa8d5b8346
7 files changed
+696
-172
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(
|
||||
(
|
||||
|
||||
+573
-156
@@ -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,613 @@ 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' }
|
||||
});
|
||||
console.log('Buscando configurações do documento...');
|
||||
const config = await this.getConfiguracao();
|
||||
|
||||
// 2. Gerar PDF do conteúdo
|
||||
const browser = await puppeteer.launch({
|
||||
headless: 'new',
|
||||
args: ['--no-sandbox']
|
||||
});
|
||||
// Verificar se temos um timbrado para usar
|
||||
const temTimbrado = !!config.timbradoUrl;
|
||||
|
||||
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
|
||||
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;
|
||||
// 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));
|
||||
}
|
||||
|
||||
.content {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
min-height: calc(100vh - 58mm);
|
||||
position: relative;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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'
|
||||
// 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
|
||||
};
|
||||
|
||||
const contentPdfBuffer = await page.pdf({
|
||||
format: 'A4',
|
||||
margin: margens,
|
||||
displayHeaderFooter: false,
|
||||
printBackground: true
|
||||
console.log('Usando margens:', margens);
|
||||
|
||||
// Abordagem focada em PDF de alta qualidade com formatação precisa
|
||||
try {
|
||||
console.log('Gerando PDF com formatação avançada...');
|
||||
|
||||
// 1. Primeiro carregar o timbrado se existir
|
||||
let pdfDoc;
|
||||
const fontSize = 11;
|
||||
const lineHeight = fontSize * 1.5; // Espaçamento entre linhas um pouco maior para melhor legibilidade
|
||||
const pageWidth = 595;
|
||||
const pageHeight = 842;
|
||||
|
||||
if (timbradoExists) {
|
||||
console.log('Usando timbrado como base do documento...');
|
||||
// Carregar o arquivo de timbrado
|
||||
const timbradoBytes = await fs.readFile(timbradoPath);
|
||||
try {
|
||||
pdfDoc = await PDFDocument.load(timbradoBytes);
|
||||
console.log('Timbrado carregado com sucesso');
|
||||
|
||||
// Verificar se o timbrado tem páginas
|
||||
if (pdfDoc.getPageCount() === 0) {
|
||||
console.log('Timbrado não contém páginas, adicionando página padrão');
|
||||
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
}
|
||||
} catch (loadError) {
|
||||
console.error('Erro ao carregar timbrado:', loadError);
|
||||
// Se falhar ao carregar o timbrado, criar novo documento
|
||||
pdfDoc = await PDFDocument.create();
|
||||
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
}
|
||||
} else {
|
||||
console.log('Criando novo documento sem timbrado...');
|
||||
pdfDoc = await PDFDocument.create();
|
||||
pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
}
|
||||
|
||||
// 2. Carregar fontes
|
||||
console.log('Carregando fontes...');
|
||||
let font, boldFont, italicFont;
|
||||
|
||||
try {
|
||||
// Verificar se temos a fonte Fira Sans disponível
|
||||
const firaSansPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Regular.ttf');
|
||||
const firaSansBoldPath = path.join(process.cwd(), 'public', 'fonts', 'FiraSans-Bold.ttf');
|
||||
|
||||
// Verificar se o arquivo existe
|
||||
let firaSansExists = false;
|
||||
try {
|
||||
await fs.access(firaSansPath);
|
||||
firaSansExists = true;
|
||||
console.log('Fonte Fira Sans encontrada, utilizando-a para o documento');
|
||||
} catch (e) {
|
||||
console.log('Fonte Fira Sans não encontrada, usando Helvetica como fallback');
|
||||
}
|
||||
|
||||
if (firaSansExists) {
|
||||
// Carregar as fontes Fira Sans
|
||||
try {
|
||||
const firaSansBytes = await fs.readFile(firaSansPath);
|
||||
font = await pdfDoc.embedFont(firaSansBytes);
|
||||
|
||||
try {
|
||||
const firaSansBoldBytes = await fs.readFile(firaSansBoldPath);
|
||||
boldFont = await pdfDoc.embedFont(firaSansBoldBytes);
|
||||
} catch (e) {
|
||||
console.log('Fira Sans Bold não encontrada, usando regular como fallback');
|
||||
boldFont = font;
|
||||
}
|
||||
|
||||
// Não temos itálico, usar regular
|
||||
italicFont = font;
|
||||
} catch (fontError) {
|
||||
console.error('Erro ao carregar Fira Sans:', fontError);
|
||||
throw fontError; // Forçar fallback para Helvetica
|
||||
}
|
||||
} else {
|
||||
throw new Error('Fira Sans não encontrada');
|
||||
}
|
||||
} catch (error) {
|
||||
// Fallback para Helvetica
|
||||
console.log('Usando Helvetica como fallback');
|
||||
font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||
italicFont = await pdfDoc.embedFont(StandardFonts.HelveticaOblique);
|
||||
}
|
||||
|
||||
// 3. Processar e formatar o HTML com preservação de estrutura
|
||||
console.log('Processando HTML com preservação de estrutura...');
|
||||
|
||||
// Processar variáveis
|
||||
const processedContent = this.processarTemplate(conteudo, escritorio);
|
||||
|
||||
const decodeHtmlEntities = (text: string): string => {
|
||||
const entities: Record<string, string> = {
|
||||
" ": " ",
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
""": "\"",
|
||||
"'": "'",
|
||||
"¢": "¢",
|
||||
"£": "£",
|
||||
"¥": "¥",
|
||||
"€": "€",
|
||||
"©": "©",
|
||||
"®": "®",
|
||||
"™": "™",
|
||||
"À": "À",
|
||||
"à": "à",
|
||||
"Á": "Á",
|
||||
"á": "á",
|
||||
"Â": "Â",
|
||||
"â": "â",
|
||||
"Ã": "Ã",
|
||||
"ã": "ã",
|
||||
"Ä": "Ä",
|
||||
"ä": "ä",
|
||||
"Å": "Å",
|
||||
"å": "å",
|
||||
"Æ": "Æ",
|
||||
"æ": "æ",
|
||||
"Ç": "Ç",
|
||||
"ç": "ç",
|
||||
"È": "È",
|
||||
"è": "è",
|
||||
"É": "É",
|
||||
"é": "é",
|
||||
"Ê": "Ê",
|
||||
"ê": "ê",
|
||||
"Ë": "Ë",
|
||||
"ë": "ë",
|
||||
"Ì": "Ì",
|
||||
"ì": "ì",
|
||||
"Í": "Í",
|
||||
"í": "í",
|
||||
"Î": "Î",
|
||||
"î": "î",
|
||||
"Ï": "Ï",
|
||||
"ï": "ï",
|
||||
"Ð": "Ð",
|
||||
"ð": "ð",
|
||||
"Ñ": "Ñ",
|
||||
"ñ": "ñ",
|
||||
"Ò": "Ò",
|
||||
"ò": "ò",
|
||||
"Ó": "Ó",
|
||||
"ó": "ó",
|
||||
"Ô": "Ô",
|
||||
"ô": "ô",
|
||||
"Õ": "Õ",
|
||||
"õ": "õ",
|
||||
"Ö": "Ö",
|
||||
"ö": "ö",
|
||||
"Ø": "Ø",
|
||||
"ø": "ø",
|
||||
"Ù": "Ù",
|
||||
"ù": "ù",
|
||||
"Ú": "Ú",
|
||||
"ú": "ú",
|
||||
"Û": "Û",
|
||||
"û": "û",
|
||||
"Ü": "Ü",
|
||||
"ü": "ü",
|
||||
"Ý": "Ý",
|
||||
"ý": "ý",
|
||||
"ÿ": "ÿ",
|
||||
"ß": "ß",
|
||||
"–": "–",
|
||||
"—": "—",
|
||||
"‘": "'",
|
||||
"’": "'",
|
||||
"‚": "‚",
|
||||
"“": "\"",
|
||||
"”": "\"",
|
||||
"„": "„",
|
||||
"‹": "‹",
|
||||
"›": "›",
|
||||
"«": "«",
|
||||
"»": "»",
|
||||
"…": "…",
|
||||
"•": "•",
|
||||
"·": "·"
|
||||
};
|
||||
|
||||
return text.replace(/&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-fA-F]{1,6});/gi, (match) => {
|
||||
if (entities[match]) {
|
||||
return entities[match];
|
||||
} else if (match.startsWith('&#x')) {
|
||||
const hex = match.substring(3, match.length - 1);
|
||||
try {
|
||||
return String.fromCodePoint(parseInt(hex, 16));
|
||||
} catch (e) {
|
||||
return match;
|
||||
}
|
||||
} else if (match.startsWith('&#')) {
|
||||
const decimal = match.substring(2, match.length - 1);
|
||||
try {
|
||||
return String.fromCodePoint(parseInt(decimal, 10));
|
||||
} catch (e) {
|
||||
return match;
|
||||
}
|
||||
}
|
||||
return match;
|
||||
});
|
||||
};
|
||||
|
||||
const extractStructuredContent = (html: string) => {
|
||||
// Função para detectar e remover conteúdo duplicado
|
||||
const checkForDuplicates = (text: string): string => {
|
||||
// Se for conteúdo muito pequeno, não verificar
|
||||
if (text.length < 500) return text;
|
||||
|
||||
try {
|
||||
// Calcular metade do comprimento
|
||||
const halfLength = Math.floor(text.length / 2);
|
||||
const firstHalf = text.substring(0, halfLength);
|
||||
const secondHalf = text.substring(halfLength);
|
||||
|
||||
// Método simples para verificar duplicação
|
||||
const isDuplicated = text.substring(0, 100).trim() ===
|
||||
text.substring(halfLength, halfLength + 100).trim();
|
||||
|
||||
if (isDuplicated) {
|
||||
console.log('Conteúdo duplicado detectado. Removendo duplicação.');
|
||||
return firstHalf;
|
||||
} else {
|
||||
console.log('Nenhuma duplicação detectada, mantendo conteúdo original');
|
||||
return text;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro ao verificar duplicação:', error);
|
||||
return text; // Em caso de erro, mantenha o conteúdo original
|
||||
}
|
||||
};
|
||||
|
||||
// Aplicar verificação de duplicação
|
||||
html = checkForDuplicates(html);
|
||||
|
||||
// ...existing code...
|
||||
};
|
||||
|
||||
const structuredContent = extractStructuredContent(processedContent);
|
||||
|
||||
console.log(`Renderizando ${structuredContent.length} elementos...`);
|
||||
let currentPage = pdfDoc.getPage(0);
|
||||
let y = pageHeight - margens.top;
|
||||
let pageIndex = 0;
|
||||
let firstPageTemplate = null;
|
||||
if (timbradoExists) {
|
||||
firstPageTemplate = pdfDoc.getPage(0);
|
||||
console.log('Template de timbrado capturado para replicação em novas páginas');
|
||||
}
|
||||
|
||||
const addNewPageIfNeeded = (minSpace: number): boolean => {
|
||||
if (y - minSpace < margens.bottom) {
|
||||
try {
|
||||
let newPage;
|
||||
if (timbradoExists) {
|
||||
try {
|
||||
console.log('Adicionando nova página com timbrado...');
|
||||
newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
|
||||
const firstPage = pdfDoc.getPage(0);
|
||||
newPage.drawPage(firstPage, {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: pageWidth,
|
||||
height: pageHeight,
|
||||
opacity: 1
|
||||
});
|
||||
console.log('Timbrado aplicado à nova página com sucesso');
|
||||
} catch (copyError) {
|
||||
console.error('Erro ao copiar timbrado para nova página:', copyError);
|
||||
newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
}
|
||||
} else {
|
||||
newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
}
|
||||
currentPage = newPage;
|
||||
pageIndex++;
|
||||
y = pageHeight - margens.top;
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Erro ao adicionar nova página:', error);
|
||||
try {
|
||||
const newPage = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
currentPage = newPage;
|
||||
pageIndex++;
|
||||
y = pageHeight - margens.top;
|
||||
return true;
|
||||
} catch (fallbackError) {
|
||||
console.error('Falha crítica ao adicionar página:', fallbackError);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Função para quebrar texto em linhas com boa distribuição
|
||||
const wrapTextToLines = (text: string, maxWidth: number): string[] => {
|
||||
const lines = [];
|
||||
const words = text.split(' ');
|
||||
let currentLine = '';
|
||||
|
||||
// Estimativa de largura (usando proporção aproximada para cada fonte)
|
||||
const getApproxWidth = (text: string): number => {
|
||||
const averageCharWidth = fontSize * 0.55; // Estimativa para Helvetica/Fira Sans
|
||||
return text.length * averageCharWidth;
|
||||
};
|
||||
|
||||
for (const word of words) {
|
||||
const testLine = currentLine ? `${currentLine} ${word}` : word;
|
||||
if (getApproxWidth(testLine) > maxWidth) {
|
||||
if (currentLine) {
|
||||
lines.push(currentLine);
|
||||
currentLine = word;
|
||||
} else {
|
||||
// Palavra muito longa, não quebrar
|
||||
lines.push(word);
|
||||
currentLine = '';
|
||||
}
|
||||
} else {
|
||||
currentLine = testLine;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentLine) {
|
||||
lines.push(currentLine);
|
||||
}
|
||||
|
||||
return lines;
|
||||
};
|
||||
|
||||
// Renderizar todos os elementos estruturados
|
||||
for (const element of structuredContent) {
|
||||
try {
|
||||
const availableWidth = pageWidth - margens.left - margens.right;
|
||||
|
||||
// Garantir que temos conteúdo válido
|
||||
if (!element || !element.content || element.content.trim() === '') {
|
||||
console.log('Ignorando elemento vazio');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Adicionar log para diagnóstico
|
||||
console.log(`Renderizando elemento tipo '${element.type}' com ${element.content.length} caracteres`);
|
||||
|
||||
switch (element.type) {
|
||||
case 'heading': {
|
||||
// Tamanho de fonte para cabeçalhos (h1, h2, h3...)
|
||||
const headingSize = fontSize * (1.8 - (element.level - 1) * 0.2);
|
||||
const headingLines = wrapTextToLines(element.content, availableWidth);
|
||||
|
||||
// Espaço antes do cabeçalho
|
||||
y -= lineHeight * 0.5;
|
||||
|
||||
// Espaço necessário para o cabeçalho completo
|
||||
const headingSpace = headingLines.length * lineHeight * 1.2 + lineHeight;
|
||||
addNewPageIfNeeded(headingSpace);
|
||||
|
||||
// Verificar tipo de alinhamento
|
||||
const alignment = element.alignment || 'left';
|
||||
const centerHeading = alignment === 'center' || element.level <= 2;
|
||||
|
||||
// Desenhar cada linha do cabeçalho
|
||||
for (const line of headingLines) {
|
||||
let xPos = margens.left;
|
||||
|
||||
if (centerHeading) {
|
||||
// Centralizar o texto
|
||||
const estimatedWidth = line.length * (headingSize * 0.55);
|
||||
xPos = Math.max(margens.left, (pageWidth - estimatedWidth) / 2);
|
||||
} else if (alignment === 'right') {
|
||||
// Alinhar à direita
|
||||
const estimatedWidth = line.length * (headingSize * 0.55);
|
||||
xPos = Math.max(margens.left, pageWidth - margens.right - estimatedWidth);
|
||||
}
|
||||
|
||||
currentPage.drawText(line, {
|
||||
x: xPos,
|
||||
y,
|
||||
font: boldFont,
|
||||
size: headingSize
|
||||
});
|
||||
|
||||
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);
|
||||
y -= lineHeight * 1.2;
|
||||
}
|
||||
|
||||
// 6. Gerar PDF final
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
return Buffer.from(pdfBytes);
|
||||
// Espaço adicional após cabeçalho
|
||||
y -= lineHeight * 0.3;
|
||||
break;
|
||||
}
|
||||
case 'paragraph':
|
||||
case 'div': {
|
||||
// Usar o alinhamento detectado
|
||||
const alignment = element.alignment || 'left';
|
||||
|
||||
// Dividir em linhas para respeitar quebras originais
|
||||
const textLines = element.content.split('\n');
|
||||
let firstParagraphLine = true;
|
||||
|
||||
for (const textLine of textLines) {
|
||||
if (!textLine.trim()) {
|
||||
// Linha vazia - adicionar espaço
|
||||
y -= lineHeight * 0.5;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Quebrar a linha para caber na largura
|
||||
const wrappedLines = wrapTextToLines(textLine, availableWidth);
|
||||
|
||||
for (const wrappedLine of wrappedLines) {
|
||||
// Verificar espaço para nova página
|
||||
if (addNewPageIfNeeded(lineHeight)) {
|
||||
// Nova página foi adicionada
|
||||
}
|
||||
|
||||
// Calcular posição X para alinhamento
|
||||
let xPos = margens.left;
|
||||
const trimmedLine = wrappedLine.trim();
|
||||
const estimatedWidth = trimmedLine.length * (fontSize * 0.55);
|
||||
|
||||
if (alignment === 'center') {
|
||||
// Centralizar texto
|
||||
xPos = Math.max(margens.left, (pageWidth - estimatedWidth) / 2);
|
||||
} else if (alignment === 'right') {
|
||||
// Alinhar à direita
|
||||
xPos = Math.max(margens.left, pageWidth - margens.right - estimatedWidth);
|
||||
}
|
||||
|
||||
// Desenhar a linha de texto
|
||||
currentPage.drawText(trimmedLine, {
|
||||
x: xPos,
|
||||
y,
|
||||
font,
|
||||
size: fontSize
|
||||
});
|
||||
|
||||
y -= lineHeight;
|
||||
}
|
||||
|
||||
if (firstParagraphLine) {
|
||||
firstParagraphLine = false;
|
||||
} else {
|
||||
// Espaço extra entre parágrafos distintos
|
||||
y -= lineHeight * 0.2;
|
||||
}
|
||||
}
|
||||
|
||||
// Espaço após parágrafo
|
||||
y -= lineHeight * 0.3;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (renderError) {
|
||||
console.error('Erro ao renderizar elemento:', renderError);
|
||||
// Continuar para o próximo elemento
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Adicionar rodapé (apenas se não houver timbrado ou na última página)
|
||||
if (!timbradoExists && (escritorio.nome || escritorio.endereco || escritorio.telefone || escritorio.email)) {
|
||||
const footerY = margens.bottom - 15;
|
||||
let footerText = '';
|
||||
if (escritorio.nome) footerText += escritorio.nome;
|
||||
if (escritorio.endereco) {
|
||||
if (footerText) footerText += ' | ';
|
||||
footerText += escritorio.endereco;
|
||||
}
|
||||
if (escritorio.telefone) {
|
||||
if (footerText) footerText += ' | ';
|
||||
footerText += `Tel: ${escritorio.telefone}`;
|
||||
}
|
||||
if (escritorio.email) {
|
||||
if (footerText) footerText += ' | ';
|
||||
footerText += escritorio.email;
|
||||
}
|
||||
|
||||
try {
|
||||
currentPage.drawText(footerText, {
|
||||
x: margens.left,
|
||||
y: footerY,
|
||||
font,
|
||||
size: 8,
|
||||
color: rgb(0.5, 0.5, 0.5) // Cinza claro para ser discreto
|
||||
});
|
||||
} catch (footerError) {
|
||||
console.error('Erro ao adicionar rodapé:', footerError);
|
||||
}
|
||||
}
|
||||
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
console.log(`PDF gerado com sucesso: ${pdfBytes.length} bytes`);
|
||||
return Buffer.from(pdfBytes);
|
||||
} catch (error) {
|
||||
console.error('Erro ao gerar PDF:', error);
|
||||
throw new Error('Falha ao gerar PDF');
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
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