fix atendimentos.ts
Signed-off-by: Rodrigo Martins <rodrigo.sousa.577@gmail.com>
This commit is contained in:
1 parent
33d9fe8688
commit
915818b519
7 files changed
+309
-129
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(
|
||||||
(
|
(
|
||||||
|
|||||||
+180
-107
@@ -146,19 +146,19 @@ export class PdfService {
|
|||||||
private async getConfiguracao() {
|
private async getConfiguracao() {
|
||||||
try {
|
try {
|
||||||
// Buscar configuração ou usar valores padrão
|
// Buscar configuração ou usar valores padrão
|
||||||
|
// Removendo campos que não existem no modelo
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
const config = await prisma.configuracaoDocumento.findFirst({
|
||||||
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,
|
||||||
criadoEm: true
|
criadoEm: true,
|
||||||
|
templatePadrao: true,
|
||||||
|
margensTemplate: true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -166,44 +166,81 @@ 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 para campos que não existem mais no modelo
|
||||||
|
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 || false,
|
||||||
|
margensTemplate: config?.margensTemplate || false
|
||||||
};
|
};
|
||||||
} 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');
|
// Returnar configuração padrão em caso de erro para não interromper o fluxo
|
||||||
|
return {
|
||||||
|
cabecalhoHtml: `<div style="text-align: center; padding: 20px;"><h2 style="margin:0;font-size:14pt">Documento</h2></div>`,
|
||||||
|
rodapeHtml: `<div style="text-align: center; font-size: 10pt;">Documento gerado pelo sistema</div>`,
|
||||||
|
timbradoUrl: '',
|
||||||
|
timbradoMarginTop: 113,
|
||||||
|
timbradoMarginBottom: 35,
|
||||||
|
timbradoMarginLeft: 35,
|
||||||
|
timbradoMarginRight: 90,
|
||||||
|
templatePadrao: false,
|
||||||
|
margensTemplate: false
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private gerarHTML(content: string, config: any) {
|
private gerarHTML(content: string, config: any) {
|
||||||
|
// Usar a URL absoluta correta para o timbrado - ajustar para usar o BACKEND_URL
|
||||||
const timbradoUrl = config.timbradoUrl
|
const timbradoUrl = config.timbradoUrl
|
||||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl.startsWith('/') ? '' : '/'}${config.timbradoUrl}`
|
||||||
: '';
|
: '';
|
||||||
|
|
||||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
console.log('Gerando PDF com timbrado (URL completa):', timbradoUrl);
|
||||||
|
|
||||||
|
// Usar as margens do template se disponíveis, caso contrário usar as margens padrão
|
||||||
|
const margens = config.margensTemplate || {
|
||||||
|
top: config.timbradoMarginTop || 100,
|
||||||
|
left: config.timbradoMarginLeft || 50,
|
||||||
|
right: config.timbradoMarginRight || 50,
|
||||||
|
bottom: config.timbradoMarginBottom || 50
|
||||||
|
};
|
||||||
|
|
||||||
|
// Aplicar margens do objeto margensTemplate
|
||||||
|
const margemTopo = margens.top;
|
||||||
|
const margemEsquerda = margens.left;
|
||||||
|
const margemDireita = margens.right;
|
||||||
|
const margemInferior = margens.bottom;
|
||||||
|
|
||||||
|
console.log('Margens aplicadas do objeto margensTemplate:', {
|
||||||
|
margemTopo,
|
||||||
|
margemDireita,
|
||||||
|
margemEsquerda,
|
||||||
|
margemInferior
|
||||||
|
});
|
||||||
|
|
||||||
return `
|
return `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
|
||||||
<style>
|
<style>
|
||||||
|
@import url('https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap');
|
||||||
|
|
||||||
@page {
|
@page {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
size: A4;
|
size: A4;
|
||||||
@@ -212,7 +249,7 @@ export class PdfService {
|
|||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||||
font-size: 11pt;
|
font-size: 11pt;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -221,10 +258,10 @@ export class PdfService {
|
|||||||
|
|
||||||
.page {
|
.page {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 21cm;
|
width: 100%;
|
||||||
min-height: 29.7cm;
|
min-height: 100vh;
|
||||||
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px;
|
padding: ${margemTopo}px ${margemDireita}px ${margemInferior}px ${margemEsquerda}px;
|
||||||
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
|
background-image: url('${timbradoUrl}');
|
||||||
background-size: cover;
|
background-size: cover;
|
||||||
background-position: center;
|
background-position: center;
|
||||||
background-repeat: no-repeat;
|
background-repeat: no-repeat;
|
||||||
@@ -234,6 +271,12 @@ export class PdfService {
|
|||||||
.content {
|
.content {
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
|
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Garantir que todos os elementos herdam a fonte */
|
||||||
|
* {
|
||||||
|
font-family: 'Fira Sans', Arial, sans-serif !important;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
@@ -248,113 +291,143 @@ export class PdfService {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async gerarPDF(conteudo: string, escritorio: any) {
|
async gerarPDF(html: string): Promise<Buffer> {
|
||||||
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' }
|
|
||||||
});
|
// Log detalhado da configuração
|
||||||
|
console.log('Configurações detalhadas:', JSON.stringify(config, null, 2));
|
||||||
|
|
||||||
|
// Gerar HTML com as configurações
|
||||||
|
const htmlCompleto = this.gerarHTML(html, config);
|
||||||
|
|
||||||
|
console.log('Iniciando geração de PDF com Chromium...');
|
||||||
|
|
||||||
// 2. Gerar PDF do conteúdo
|
|
||||||
const browser = await puppeteer.launch({
|
const browser = await puppeteer.launch({
|
||||||
headless: 'new',
|
executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser',
|
||||||
args: ['--no-sandbox']
|
headless: true,
|
||||||
|
args: [
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-setuid-sandbox',
|
||||||
|
'--disable-dev-shm-usage',
|
||||||
|
'--disable-gpu',
|
||||||
|
'--allow-file-access-from-files',
|
||||||
|
'--enable-local-file-accesses'
|
||||||
|
],
|
||||||
|
ignoreHTTPSErrors: true
|
||||||
});
|
});
|
||||||
|
|
||||||
const page = await browser.newPage();
|
console.log('Navegador iniciado com sucesso');
|
||||||
|
|
||||||
// Usar template padrão ou fallback para o template básico
|
try {
|
||||||
const template = config?.templatePadrao || `
|
const page = await browser.newPage();
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;700&display=swap" rel="stylesheet">
|
|
||||||
<style>
|
|
||||||
body {
|
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
|
||||||
font-size: 11pt;
|
|
||||||
line-height: 1.3;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.content {
|
// Autorizar carregar recursos de qualquer origem
|
||||||
margin: 0;
|
await page.setBypassCSP(true);
|
||||||
padding: 0;
|
|
||||||
min-height: calc(100vh - 58mm);
|
|
||||||
position: relative;
|
|
||||||
}
|
|
||||||
|
|
||||||
p { margin: 0.7em 0; }
|
// Viewport A4 preciso
|
||||||
h1, h2, h3 { margin: 0.8em 0; }
|
await page.setViewport({
|
||||||
</style>
|
width: 794, // A4 em pixels a 96 DPI
|
||||||
</head>
|
height: 1123,
|
||||||
<body>
|
deviceScaleFactor: 2.0 // Alta resolução
|
||||||
<div class="content">
|
});
|
||||||
${conteudo}
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
`;
|
|
||||||
|
|
||||||
// Processar o template substituindo variáveis
|
// Interceptar requisições para depuração
|
||||||
const templateProcessado = template.replace(/\{\{(.+?)\}\}/g, (match, key) => {
|
await page.setRequestInterception(true);
|
||||||
return escritorio[key.trim()] || match;
|
page.on('request', request => {
|
||||||
});
|
if (request.url().includes('timbrado')) {
|
||||||
|
console.log('Interceptado request de timbrado:', request.url());
|
||||||
|
}
|
||||||
|
request.continue();
|
||||||
|
});
|
||||||
|
|
||||||
await page.setContent(templateProcessado);
|
console.log('Carregando conteúdo HTML...');
|
||||||
|
|
||||||
const margens = config?.margensTemplate || {
|
// Carregar conteúdo com todos os recursos
|
||||||
top: '35mm',
|
await page.setContent(htmlCompleto, {
|
||||||
bottom: '29mm',
|
waitUntil: ['load', 'networkidle0'],
|
||||||
left: '25mm',
|
timeout: 30000
|
||||||
right: '25mm'
|
});
|
||||||
};
|
|
||||||
|
|
||||||
const contentPdfBuffer = await page.pdf({
|
// Usar setTimeout em vez de waitForTimeout
|
||||||
format: 'A4',
|
await new Promise(resolve => setTimeout(resolve, 3000));
|
||||||
margin: margens,
|
|
||||||
displayHeaderFooter: false,
|
|
||||||
printBackground: true
|
|
||||||
});
|
|
||||||
|
|
||||||
await browser.close();
|
console.log('Gerando PDF...');
|
||||||
|
|
||||||
// 2. Carregar os PDFs
|
// Configurações precisas do PDF
|
||||||
const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf');
|
const pdf = await page.pdf({
|
||||||
const templateBytes = await fs.readFile(templatePath);
|
format: 'A4',
|
||||||
|
printBackground: true,
|
||||||
|
margin: { top: 0, right: 0, bottom: 0, left: 0 }, // Sem margens para preservar o layout
|
||||||
|
preferCSSPageSize: true
|
||||||
|
});
|
||||||
|
|
||||||
const templateDoc = await PDFDocument.load(templateBytes);
|
console.log('PDF gerado com sucesso!');
|
||||||
const contentDoc = await PDFDocument.load(contentPdfBuffer);
|
return pdf;
|
||||||
|
} finally {
|
||||||
// 3. Criar documento final
|
await browser.close();
|
||||||
const pdfDoc = await PDFDocument.create();
|
console.log('Navegador fechado com segurança');
|
||||||
|
|
||||||
// 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 detalhado ao gerar PDF:', error);
|
||||||
throw new Error('Falha ao gerar PDF');
|
try {
|
||||||
|
console.log('Tentando gerar PDF alternativo com pdf-lib...');
|
||||||
|
|
||||||
|
// Criar um documento PDF simples com o conteúdo
|
||||||
|
const pdfDoc = await PDFDocument.create();
|
||||||
|
const page = pdfDoc.addPage([595, 842]); // A4
|
||||||
|
|
||||||
|
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||||
|
|
||||||
|
// Adicionar texto informativo
|
||||||
|
page.drawText('Não foi possível gerar o PDF com o layout desejado', {
|
||||||
|
x: 50,
|
||||||
|
y: 800,
|
||||||
|
size: 16,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
page.drawText('Por favor, entre em contato com o suporte.', {
|
||||||
|
x: 50,
|
||||||
|
y: 750,
|
||||||
|
size: 12,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Adicionar parte do HTML como texto simples (até 1000 caracteres)
|
||||||
|
const plainText = html.replace(/<[^>]*>/g, ' ').slice(0, 1000) + '...';
|
||||||
|
|
||||||
|
page.drawText('Conteúdo original (parcial):', {
|
||||||
|
x: 50,
|
||||||
|
y: 700,
|
||||||
|
size: 10,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
|
||||||
|
// Quebrar o texto em linhas
|
||||||
|
const linhas = [];
|
||||||
|
for (let i = 0; i < plainText.length; i += 80) {
|
||||||
|
linhas.push(plainText.substring(i, i + 80));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adicionar no máximo 30 linhas
|
||||||
|
linhas.slice(0, 30).forEach((linha, index) => {
|
||||||
|
page.drawText(linha, {
|
||||||
|
x: 50,
|
||||||
|
y: 670 - (index * 15),
|
||||||
|
size: 8,
|
||||||
|
font
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const pdfBytes = await pdfDoc.save();
|
||||||
|
return Buffer.from(pdfBytes);
|
||||||
|
|
||||||
|
} catch (fallbackError) {
|
||||||
|
console.error('Erro também no método alternativo:', fallbackError);
|
||||||
|
throw new Error('Falha ao gerar PDF: não foi possível criar o documento');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user