diff --git a/Dockerfile b/Dockerfile index 2cae6d4..2f108ab 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e97489f --- /dev/null +++ b/docker-compose.yml @@ -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 diff --git a/package.json b/package.json index 37fcf7c..d1cd598 100644 --- a/package.json +++ b/package.json @@ -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" - } } } diff --git a/scripts/fix-uuid.sql b/scripts/fix-uuid.sql new file mode 100644 index 0000000..0ec4191 --- /dev/null +++ b/scripts/fix-uuid.sql @@ -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}$'; diff --git a/src/components/clientes/ClienteModal.tsx b/src/components/clientes/ClienteModal.tsx index c17000a..e4c0c7e 100644 --- a/src/components/clientes/ClienteModal.tsx +++ b/src/components/clientes/ClienteModal.tsx @@ -200,7 +200,7 @@ export const ClienteModal: React.FC = ({ // 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 = ({ 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 = ({ 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 = ({ preenchido: true, }); - // Focar no próximo campo - setTimeout(() => { - const numeroInput = document.querySelector( - 'input[name="numero"]' - ) as HTMLInputElement; - if (numeroInput) numeroInput.focus(); - }, 100); + // 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."); diff --git a/src/server/index.ts b/src/server/index.ts index a017f0a..8ae74ed 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -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( ( diff --git a/src/server/services/PdfService.ts b/src/server/services/PdfService.ts index c5342cb..6ec169b 100644 --- a/src/server/services/PdfService.ts +++ b/src/server/services/PdfService.ts @@ -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,453 @@ export class PdfService { // Retornar configuração padrão se não existir return { - cabecalhoHtml: config?.cabecalhoHtml || ` + // Valores padrão + cabecalhoHtml: `

{{escritorio.nome}}

`, - rodapeHtml: config?.rodapeHtml || ` + rodapeHtml: `
{{escritorio.endereco}}
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
`, - 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: `

Documento

`, + rodapeHtml: `
Documento gerado pelo sistema
`, + 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 ` - - - - - - - - -
-
- ${content} -
-
- - - `; - } - - 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 { try { - // 1. Buscar configuração do template - const config = await prisma.configuracaoDocumento.findFirst({ - orderBy: { criadoEm: 'desc' } - }); - - // 2. Gerar PDF do conteúdo - const browser = await puppeteer.launch({ - headless: 'new', - args: ['--no-sandbox'] - }); - - const page = await browser.newPage(); + console.log('Buscando configurações do documento...'); + const config = await this.getConfiguracao(); - // Usar template padrão ou fallback para o template básico - const template = config?.templatePadrao || ` - - + // Verificar se temos um timbrado para usar + const temTimbrado = !!config.timbradoUrl; + + console.log(`Iniciando geração de PDF ${temTimbrado ? 'com' : 'sem'} timbrado...`); + + // Se temos timbrado, vamos primeiro verificar se ele existe + let timbradoPath = ''; + let timbradoExists = false; + + if (temTimbrado) { + if (config.timbradoUrl.startsWith('/uploads')) { + timbradoPath = path.join(process.cwd(), 'public', config.timbradoUrl); + } else { + timbradoPath = path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl)); + } + + console.log('Verificando timbrado em:', timbradoPath); + + try { + await fs.access(timbradoPath); + timbradoExists = true; + console.log('Timbrado encontrado'); + } catch (e) { + console.error('Timbrado não encontrado:', e); + } + } + + // Abordagem híbrida: + // 1. Primeiro renderizar HTML com Puppeteer para preservar formatação + // 2. Depois combinar com timbrado usando pdf-lib + + // 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); + + // Tentar com abordagem mais simples, sem verificações de assinatura que possam falhar + try { + // 1. Gerar PDF do conteúdo diretamente com Puppeteer + console.log('Iniciando geração simplificada com Puppeteer...'); + + // Processar o template com dados do escritório + const processedContent = this.processarTemplate(conteudo, escritorio); + + // HTML básico sem muitas complexidades + const htmlSimples = ` + + - + - -
- ${conteudo} -
- - - `; - - // 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' - }; - - const contentPdfBuffer = await page.pdf({ - format: 'A4', - margin: margens, - displayHeaderFooter: false, - printBackground: true - }); - - await browser.close(); - - // 2. Carregar os PDFs - const templatePath = path.join(process.cwd(), 'public', 'uploads', 'Timbrado_2025.pdf'); - const templateBytes = await fs.readFile(templatePath); - - const templateDoc = await PDFDocument.load(templateBytes); - const contentDoc = await PDFDocument.load(contentPdfBuffer); - - // 3. Criar documento final - const pdfDoc = await PDFDocument.create(); - - // 4. Copiar template e conteúdo - const [templatePage] = await templateDoc.copyPages(templateDoc, [0]); - const contentPages = await contentDoc.getPages(); - - // 5. Para cada página do conteúdo - for (let i = 0; i < contentPages.length; i++) { - // Primeiro: adicionar template - const page = await pdfDoc.embedPage(templatePage); - const contentPage = await pdfDoc.embedPage(contentPages[i]); + ${processedContent} + + `; - // Segundo: criar nova página - const newPage = pdfDoc.addPage([page.width, page.height]); + // Configurações simplificadas para o Puppeteer + const browser = await puppeteer.launch({ + executablePath: process.env.PUPPETEER_EXECUTABLE_PATH || '/usr/bin/chromium-browser', + headless: true, + args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage'] + }); - // Terceiro: desenhar template e conteúdo - newPage.drawPage(page); - newPage.drawPage(contentPage); + // Gerar o conteúdo em PDF + let contentPdfBuffer; + try { + const page = await browser.newPage(); + page.setDefaultNavigationTimeout(0); + + // Carregar o conteúdo de forma simples + await page.setContent(htmlSimples, { waitUntil: 'networkidle0' }); + + // Gerar o PDF com margens zero para maximizar compatibilidade + contentPdfBuffer = await page.pdf({ + format: 'A4', + printBackground: true, + margin: { top: '0', right: '0', bottom: '0', left: '0' } + }); + + console.log(`PDF do conteúdo gerado: ${contentPdfBuffer.length} bytes`); + } finally { + await browser.close(); + console.log('Navegador fechado'); + } + + // 2. Se temos um timbrado, tentar combinar - abordagem baseada em arquivo para maior confiabilidade + if (timbradoExists) { + try { + console.log('Tentando mesclar PDFs com abordagem baseada em arquivos temporários...'); + + // 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) { + console.log('Diretório temp já existe ou erro:', mkdirErr); + } + + // Gerar nomes de arquivo únicos + const timestamp = Date.now(); + const contentTempPath = path.join(tmpDir, `content-${timestamp}.pdf`); + const outputTempPath = path.join(tmpDir, `output-${timestamp}.pdf`); + + // Salvar o conteúdo em arquivo temporário + await fs.writeFile(contentTempPath, contentPdfBuffer); + console.log('Arquivo temporário de conteúdo salvo:', contentTempPath); + + // Tentar usar pdftk se disponível (mais confiável para PDFs complexos) + try { + const { exec } = require('child_process'); + + console.log('Executando pdftk para mesclar PDFs...'); + console.log(`Comando: pdftk ${timbradoPath} stamp ${contentTempPath} output ${outputTempPath}`); + + // Executar pdftk de forma síncrona + await new Promise((resolve, reject) => { + exec(`pdftk ${timbradoPath} stamp ${contentTempPath} output ${outputTempPath}`, (error, stdout, stderr) => { + if (error) { + console.error(`Erro pdftk: ${error.message}`); + console.error(`stderr: ${stderr}`); + reject(error); + } else { + console.log(`stdout: ${stdout}`); + resolve(stdout); + } + }); + }); + + // Ler o arquivo mesclado + const mergedPdf = await fs.readFile(outputTempPath); + console.log(`PDF mesclado lido: ${mergedPdf.length} bytes`); + + // Limpar arquivos temporários + await fs.unlink(contentTempPath).catch(() => {}); + await fs.unlink(outputTempPath).catch(() => {}); + + return mergedPdf; + } catch (pdftError) { + console.error('Erro com pdftk, tentando pdf-lib:', pdftError); + + // Fallback para pdf-lib + try { + // Ler os PDFs diretamente dos arquivos + const timbradoBytes = await fs.readFile(timbradoPath); + const contentBytes = await fs.readFile(contentTempPath); + + // Carregar os documentos + const timbradoDoc = await PDFDocument.load(timbradoBytes); + const contentDoc = await PDFDocument.load(contentBytes); + + // Mesclar os documentos (aproximação) + const mergedDoc = await PDFDocument.create(); + + // Copiar a primeira página do timbrado para cada página do conteúdo + const contentPages = contentDoc.getPageCount(); + + for (let i = 0; i < contentPages; i++) { + // Adicionar página do timbrado + const [timbradoPage] = await mergedDoc.copyPages(timbradoDoc, [0]); + mergedDoc.addPage(timbradoPage); + + // Adicionar conteúdo sobre o timbrado + const [contentPage] = await mergedDoc.copyPages(contentDoc, [i]); + const currentPage = mergedDoc.getPages()[i]; + + try { + currentPage.drawPage(contentPage); + } catch (e) { + console.error(`Erro ao desenhar página ${i}:`, e); + } + } + + // Salvar o documento mesclado + const mergedPdfBytes = await mergedDoc.save(); + const mergedBuffer = Buffer.from(mergedPdfBytes); + + // Limpar arquivos temporários + await fs.unlink(contentTempPath).catch(() => {}); + + return mergedBuffer; + } catch (pdfLibError) { + console.error('Erro com pdf-lib, retornando apenas conteúdo:', pdfLibError); + // Se falhar, retornar apenas o conteúdo + await fs.unlink(contentTempPath).catch(() => {}); + return contentPdfBuffer; + } + } + } catch (mergeError) { + console.error('Erro ao mesclar PDFs:', mergeError); + return contentPdfBuffer; + } + } else { + // Se não houver timbrado, retornar apenas o conteúdo + return contentPdfBuffer; + } + } catch (mainError) { + console.error('Erro na abordagem principal:', mainError); + + // Fallback para método extremamente simples usando apenas pdf-lib + try { + console.log('Usando método de emergência com pdf-lib...'); + + 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); + + // Título + page.drawText('Documento', { + x: 50, + y: 800, + font: boldFont, + size: 16 + }); + + // Data + const currentDate = new Date().toLocaleDateString('pt-BR'); + page.drawText(`Data: ${currentDate}`, { + x: 50, + y: 770, + font, + size: 11 + }); + + // Extrair texto do HTML + const textContent = conteudo + .replace(//gi, '\n') + .replace(/]*>(.*?)<\/p>/gi, '$1\n\n') + .replace(/]*>(.*?)<\/h[1-6]>/gi, '$1\n\n') + .replace(/]*>(.*?)<\/li>/gi, '• $1\n') + .replace(/<[^>]*>/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + + // Dividir em linhas curtas + const lines = []; + const words = textContent.split(' '); + let currentLine = ''; + + for (const word of words) { + const testLine = currentLine ? `${currentLine} ${word}` : word; + if (testLine.length > 80) { + lines.push(currentLine); + currentLine = word; + } else { + currentLine = testLine; + } + } + + if (currentLine) { + lines.push(currentLine); + } + + // Adicionar linhas ao PDF + let y = 740; + const lineHeight = 14; + + for (let i = 0; i < Math.min(lines.length, 50); i++) { + page.drawText(lines[i], { + x: 50, + y, + font, + size: 10 + }); + + y -= lineHeight; + + // Adicionar nova página se necessário + if (y < 50 && i < Math.min(lines.length, 50) - 1) { + const newPage = pdfDoc.addPage([595, 842]); + y = 800; + } + } + + // Rodapé com dados do escritório + if (escritorio?.nome) { + page.drawText(escritorio.nome, { + x: 50, + y: 40, + font, + size: 8 + }); + } + + const pdfBytes = await pdfDoc.save(); + return Buffer.from(pdfBytes); + } catch (fallbackError) { + console.error('Erro no método de emergência:', fallbackError); + + // Último recurso: PDF mínimo apenas com mensagem de erro + const pdfDoc = await PDFDocument.create(); + const page = pdfDoc.addPage([595, 842]); + const font = await pdfDoc.embedFont(StandardFonts.Helvetica); + + page.drawText('Erro ao gerar documento. Contate o suporte.', { + x: 50, + y: 500, + size: 14, + font + }); + + const pdfBytes = await pdfDoc.save(); + return Buffer.from(pdfBytes); + } } - - // 6. Gerar PDF final - const pdfBytes = await pdfDoc.save(); - return Buffer.from(pdfBytes); - } catch (error) { - console.error('Erro ao gerar PDF:', error); - throw new Error('Falha ao gerar PDF'); + console.error('Erro geral ao gerar PDF:', error); + + // 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'); + } } } + + /** + * 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; + }); + } }