Compare commits
53
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8e75018a35 | ||
|
|
a63aaeb655 | ||
|
|
48ea0c7303 | ||
|
|
89b06db89e | ||
|
|
928dfc0443 | ||
|
|
24b5d04fbc | ||
|
|
0750b26208 | ||
|
|
47f2d08b9b | ||
|
|
19f23a540a | ||
|
|
3e561b46bb | ||
|
|
3ae50e75d4 | ||
|
|
d69d5b1b0e | ||
|
|
3f012552e7 | ||
|
|
ae71161860 | ||
|
|
866a3fe539 | ||
|
|
c37a0461bf | ||
|
|
21932e5372 | ||
|
|
626137276f | ||
|
|
fc8e96cd58 | ||
|
|
90a098e7db | ||
|
|
285d829c27 | ||
|
|
0963cab395 | ||
|
|
6300fb98a7 | ||
|
|
0a67f95eaf | ||
|
|
c03c6d1b5a | ||
|
|
061156e5e7 | ||
|
|
71f5a56cbd | ||
|
|
683da3264d | ||
|
|
0475c34d64 | ||
|
|
167766fdfd | ||
|
|
a7c32aa128 | ||
|
|
b3d9ebe999 | ||
|
|
b713e24fbf | ||
|
|
a4206a7611 | ||
|
|
3d919350c8 | ||
|
|
4d22c07151 | ||
|
|
80df7310f3 | ||
|
|
9160939de2 | ||
|
|
9c2df341ea | ||
|
|
3c00956cf4 | ||
|
|
f5fb1e427d | ||
|
|
1e08f559ff | ||
|
|
1ab7bd8f36 | ||
|
|
f782fb36ad | ||
|
|
af2f0ed649 | ||
|
|
6b89a61dd7 | ||
|
|
7e868dbc46 | ||
|
|
b9e7de0ca0 | ||
|
|
0fef046d38 | ||
|
|
8f6b708d51 | ||
|
|
db7446f19a | ||
|
|
59ea762227 | ||
|
|
fe54b55af0 |
No files matched your search
@@ -0,0 +1,24 @@
|
|||||||
|
import express from "express";
|
||||||
|
import cors from "cors";
|
||||||
|
import { PrismaClient } from "@prisma/client";
|
||||||
|
import usuariosRoutes from "./routes/usuarios";
|
||||||
|
import clientesRoutes from "./routes/clientes";
|
||||||
|
import processosRoutes from "./routes/processos";
|
||||||
|
import audienciasRoutes from "./routes/audiencias";
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
const prisma = new PrismaClient();
|
||||||
|
|
||||||
|
app.use(cors());
|
||||||
|
app.use(express.json());
|
||||||
|
|
||||||
|
app.use("/api/usuarios", usuariosRoutes);
|
||||||
|
app.use("/api/clientes", clientesRoutes);
|
||||||
|
app.use("/api/processos", processosRoutes);
|
||||||
|
app.use("/api/audiencias", audienciasRoutes);
|
||||||
|
|
||||||
|
app.get("/", (req, res) => {
|
||||||
|
res.json({ message: "API is running" });
|
||||||
|
});
|
||||||
|
|
||||||
|
export default app;
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Request, Response } from "express";
|
||||||
|
import prisma from "../prisma/client";
|
||||||
|
|
||||||
|
// Lista todas as audiências
|
||||||
|
export async function getAudiencias(req: Request, res: Response) {
|
||||||
|
try {
|
||||||
|
const audiencias = await prisma.audiencia.findMany({
|
||||||
|
orderBy: { data: "asc" },
|
||||||
|
include: {
|
||||||
|
processo: {
|
||||||
|
select: { numero: true, nomeContraparte: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res.json(audiencias);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao buscar audiências:", error);
|
||||||
|
res.status(500).json({ error: "Erro ao buscar audiências" });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
import { getAudiencias } from "../controllers/audienciasController";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// GET /api/audiencias - Lista todas as audiências
|
||||||
|
router.get("/", getAudiencias);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// Adicionar ao schema.prisma existente (não substitui)
|
||||||
|
model SessaoNavegacao {
|
||||||
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
|
titulo String
|
||||||
|
descricao String?
|
||||||
|
status StatusSessao @default(INICIADA)
|
||||||
|
usuarioId String @db.Uuid
|
||||||
|
usuario Usuario @relation(fields: [usuarioId], references: [id])
|
||||||
|
|
||||||
|
// Dados da sessão
|
||||||
|
sessionKey String @unique
|
||||||
|
browserFingerprint Json
|
||||||
|
inicioSessao DateTime @default(now())
|
||||||
|
fimSessao DateTime?
|
||||||
|
duracaoSegundos Int?
|
||||||
|
|
||||||
|
// Arquivos gerados
|
||||||
|
videoPath String?
|
||||||
|
screenshotsPaths String[]
|
||||||
|
metadataPath String?
|
||||||
|
relatorioPdfPath String?
|
||||||
|
|
||||||
|
// Hashes e validação
|
||||||
|
checksumVideo String?
|
||||||
|
checksumMetadata String?
|
||||||
|
timestampProof String?
|
||||||
|
|
||||||
|
// Navegação registrada
|
||||||
|
acoes AcaoNavegacao[]
|
||||||
|
capturas CapturaNavegacao[]
|
||||||
|
|
||||||
|
criadoEm DateTime @default(now())
|
||||||
|
atualizadoEm DateTime @updatedAt
|
||||||
|
|
||||||
|
@@map("sessoes_navegacao")
|
||||||
|
}
|
||||||
|
|
||||||
|
model AcaoNavegacao {
|
||||||
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
|
sessaoId String @db.Uuid
|
||||||
|
sessao SessaoNavegacao @relation(fields: [sessaoId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
timestamp DateTime
|
||||||
|
tipo TipoAcao
|
||||||
|
url String?
|
||||||
|
elemento String?
|
||||||
|
coordenadas Json?
|
||||||
|
valor String?
|
||||||
|
screenshot String?
|
||||||
|
|
||||||
|
metadados Json
|
||||||
|
|
||||||
|
criadoEm DateTime @default(now())
|
||||||
|
|
||||||
|
@@map("acoes_navegacao")
|
||||||
|
}
|
||||||
|
|
||||||
|
model CapturaNavegacao {
|
||||||
|
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
|
||||||
|
sessaoId String @db.Uuid
|
||||||
|
sessao SessaoNavegacao @relation(fields: [sessaoId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
timestamp DateTime
|
||||||
|
url String
|
||||||
|
titulo String?
|
||||||
|
screenshotPath String
|
||||||
|
htmlContent String?
|
||||||
|
checksumHtml String?
|
||||||
|
checksumScreenshot String
|
||||||
|
|
||||||
|
// Metadados da página
|
||||||
|
networkRequests Json[]
|
||||||
|
cookies Json[]
|
||||||
|
localStorage Json?
|
||||||
|
sessionStorage Json?
|
||||||
|
|
||||||
|
criadoEm DateTime @default(now())
|
||||||
|
|
||||||
|
@@map("capturas_navegacao")
|
||||||
|
}
|
||||||
|
|
||||||
|
enum StatusSessao {
|
||||||
|
INICIADA
|
||||||
|
EM_ANDAMENTO
|
||||||
|
FINALIZANDO
|
||||||
|
CONCLUIDA
|
||||||
|
ERRO
|
||||||
|
CANCELADA
|
||||||
|
}
|
||||||
|
|
||||||
|
enum TipoAcao {
|
||||||
|
NAVEGACAO
|
||||||
|
CLIQUE
|
||||||
|
DIGITACAO
|
||||||
|
SCROLL
|
||||||
|
HOVER
|
||||||
|
DOWNLOAD
|
||||||
|
FORMULARIO
|
||||||
|
POPUP
|
||||||
|
REDIRECT
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adicionar relação ao modelo Usuario existente
|
||||||
|
// Usuario {
|
||||||
|
// sessoesNavegacao SessaoNavegacao[]
|
||||||
|
// }
|
||||||
+9
-2
@@ -48,6 +48,8 @@ import { CalculosList } from './components/calculos/CalculosList';
|
|||||||
import { NovoCalculo } from './components/calculos/NovoCalculo';
|
import { NovoCalculo } from './components/calculos/NovoCalculo';
|
||||||
import { DetalhesCalculo } from './components/calculos/DetalhesCalculo';
|
import { DetalhesCalculo } from './components/calculos/DetalhesCalculo';
|
||||||
import { NovoPensaoAlimenticia } from './components/calculos/NovoPensaoAlimenticia';
|
import { NovoPensaoAlimenticia } from './components/calculos/NovoPensaoAlimenticia';
|
||||||
|
import { DetalhePensaoAlimenticia } from './components/calculos/DetalhePensaoAlimenticia';
|
||||||
|
import { IniciarNavegacao } from './components/navegacao/IniciarNavegacao';
|
||||||
|
|
||||||
const queryClient = new QueryClient();
|
const queryClient = new QueryClient();
|
||||||
|
|
||||||
@@ -114,7 +116,7 @@ const router = createBrowserRouter(
|
|||||||
} />
|
} />
|
||||||
|
|
||||||
{/* Rotas para Pensão Alimentícia */}
|
{/* Rotas para Pensão Alimentícia */}
|
||||||
<Route path="/pensao-alimenticia/nova" element={
|
<Route path="/pensao-alimenticia/novo" element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
<NovoPensaoAlimenticia />
|
<NovoPensaoAlimenticia />
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
@@ -122,7 +124,12 @@ const router = createBrowserRouter(
|
|||||||
|
|
||||||
<Route path="/pensao-alimenticia/:id" element={
|
<Route path="/pensao-alimenticia/:id" element={
|
||||||
<ProtectedRoute>
|
<ProtectedRoute>
|
||||||
<DetalhesCalculo />
|
<DetalhePensaoAlimenticia />
|
||||||
|
</ProtectedRoute>
|
||||||
|
} />
|
||||||
|
<Route path="/navegacao/iniciar" element={
|
||||||
|
<ProtectedRoute>
|
||||||
|
<IniciarNavegacao />
|
||||||
</ProtectedRoute>
|
</ProtectedRoute>
|
||||||
} />
|
} />
|
||||||
</Route>
|
</Route>
|
||||||
|
|||||||
@@ -144,12 +144,20 @@ export function CalculosList() {
|
|||||||
<div className="container mx-auto px-4 py-8">
|
<div className="container mx-auto px-4 py-8">
|
||||||
<div className="flex justify-between items-center mb-6">
|
<div className="flex justify-between items-center mb-6">
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Cálculos Judiciais</h1>
|
<h1 className="text-2xl font-bold text-gray-900">Cálculos Judiciais</h1>
|
||||||
<Link
|
<div className="flex gap-3">
|
||||||
to="/calculos/novo"
|
<Link
|
||||||
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
|
to="/calculos/novo"
|
||||||
>
|
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
|
||||||
Novo Cálculo
|
>
|
||||||
</Link>
|
Novo Cálculo Judicial
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
to="/pensao-alimenticia/novo"
|
||||||
|
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||||
|
>
|
||||||
|
Novo Cálculo de Pensão
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Filtros */}
|
{/* Filtros */}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import { useParams } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom'; // Adicionar useNavigate
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
import api from '../../services/api';
|
import api from '../../services/api';
|
||||||
|
|
||||||
@@ -27,17 +27,36 @@ interface CalculoPensao {
|
|||||||
|
|
||||||
export function DetalhePensaoAlimenticia() {
|
export function DetalhePensaoAlimenticia() {
|
||||||
const { id } = useParams<{ id: string }>();
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const navigate = useNavigate(); // Adicionar hook de navegação
|
||||||
const [calculo, setCalculo] = useState<CalculoPensao | null>(null);
|
const [calculo, setCalculo] = useState<CalculoPensao | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
// Verificação extra para garantir que o id está definido
|
||||||
|
if (!id || id === "novo") {
|
||||||
|
setLoading(false);
|
||||||
|
setCalculo(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
const loadCalculo = async () => {
|
const loadCalculo = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await api.get(`/pensao-alimenticia/${id}`);
|
console.log('[DetalhePensaoAlimenticia] Buscando cálculo para id:', id);
|
||||||
|
const response = await api.get(`/api/calculos/pensao-alimenticia/${id}`);
|
||||||
setCalculo(response.data);
|
setCalculo(response.data);
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.error('Erro ao carregar cálculo:', error);
|
// Log detalhado para depuração
|
||||||
toast.error('Falha ao carregar dados do cálculo');
|
console.error('[DetalhePensaoAlimenticia] Erro ao carregar cálculo:', error);
|
||||||
|
|
||||||
|
// Tratamento específico para erro 404 (cálculo não encontrado)
|
||||||
|
if (error?.response?.status === 404) {
|
||||||
|
toast.warn('Cálculo de pensão alimentícia não encontrado.');
|
||||||
|
} else {
|
||||||
|
toast.error(
|
||||||
|
error?.response?.data?.message ||
|
||||||
|
'Falha ao buscar cálculo de pensão alimentícia.'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
setCalculo(null);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
@@ -51,7 +70,17 @@ export function DetalhePensaoAlimenticia() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!calculo) {
|
if (!calculo) {
|
||||||
return <div>Cálculo não encontrado</div>;
|
return (
|
||||||
|
<div className="bg-white shadow-md rounded-lg p-6 flex flex-col items-center">
|
||||||
|
<div className="text-lg mb-4 text-gray-700">Nenhum cálculo de pensão alimentícia encontrado.</div>
|
||||||
|
<button
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded-md shadow hover:bg-blue-700"
|
||||||
|
onClick={() => navigate('/pensao-alimenticia/novo')}
|
||||||
|
>
|
||||||
|
Criar novo cálculo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -90,6 +119,15 @@ export function DetalhePensaoAlimenticia() {
|
|||||||
<p className="text-gray-700">{calculo.observacoes}</p>
|
<p className="text-gray-700">{calculo.observacoes}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<div className="mt-8 flex justify-end">
|
||||||
|
<button
|
||||||
|
className="px-4 py-2 bg-blue-600 text-white rounded-md shadow hover:bg-blue-700"
|
||||||
|
onClick={() => navigate('/pensao-alimenticia/novo')}
|
||||||
|
>
|
||||||
|
Criar novo cálculo
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
import { useNavigate } from 'react-router-dom';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
import { formatarPercentual, parsePercentual } from '../../utils/formatters';
|
import { formatarPercentual, parsePercentual } from '../../utils/formatters';
|
||||||
|
|
||||||
interface ProcessoOption {
|
interface ProcessoOption {
|
||||||
@@ -16,6 +17,7 @@ interface ClienteOption {
|
|||||||
|
|
||||||
export function NovoPensaoAlimenticia() {
|
export function NovoPensaoAlimenticia() {
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const { getToken } = useAuth();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [formData, setFormData] = useState({
|
const [formData, setFormData] = useState({
|
||||||
titulo: '',
|
titulo: '',
|
||||||
@@ -101,13 +103,21 @@ export function NovoPensaoAlimenticia() {
|
|||||||
...formData,
|
...formData,
|
||||||
percentualSalarioMinimo: percentual,
|
percentualSalarioMinimo: percentual,
|
||||||
multaPactuada: formData.multaPactuada ? parsePercentual(formData.multaPactuada) : undefined,
|
multaPactuada: formData.multaPactuada ? parsePercentual(formData.multaPactuada) : undefined,
|
||||||
|
processoId: formData.processoId || undefined, // Corrigir aqui
|
||||||
|
clienteId: formData.clienteId || undefined, // Corrigir aqui
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const token = getToken();
|
||||||
|
if (!token) {
|
||||||
|
throw new Error('Usuário não autenticado. Faça login novamente.');
|
||||||
|
}
|
||||||
|
|
||||||
// Enviar solicitação para criar cálculo
|
// Enviar solicitação para criar cálculo
|
||||||
const response = await fetch('/api/pensao-alimenticia', {
|
const response = await fetch('/api/pensao-alimenticia', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${token}` // Adicionar o token aqui
|
||||||
},
|
},
|
||||||
body: JSON.stringify(dadosParaEnviar),
|
body: JSON.stringify(dadosParaEnviar),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -212,25 +212,24 @@ 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
|
|
||||||
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 || "";
|
||||||
const estado = response.data.uf || "";
|
const estado = response.data.uf || "";
|
||||||
|
|
||||||
// Atualizar valores no formulário
|
// Só preencher endereço/bairro se vier valor da API
|
||||||
setValue("endereco", endereco, { shouldValidate: true });
|
if (endereco) setValue("endereco", endereco, { shouldValidate: true });
|
||||||
setValue("bairro", bairro, { shouldValidate: true });
|
if (bairro) setValue("bairro", bairro, { shouldValidate: true });
|
||||||
setValue("cidade", cidade, { shouldValidate: true });
|
setValue("cidade", cidade, { shouldValidate: true });
|
||||||
setValue("estado", estado, { shouldValidate: true });
|
setValue("estado", estado, { shouldValidate: true });
|
||||||
|
|
||||||
// Atualizar o estado para re-renderização do componente
|
// Atualizar estado apenas para cidade/estado (não controlar endereço/bairro)
|
||||||
setEnderecoState({
|
setEnderecoState({
|
||||||
endereco,
|
endereco: endereco,
|
||||||
bairro,
|
bairro: bairro,
|
||||||
cidade,
|
cidade: cidade,
|
||||||
estado,
|
estado: estado,
|
||||||
preenchido: true,
|
preenchido: false, // Não usar mais para travar campos
|
||||||
});
|
});
|
||||||
|
|
||||||
// Focar no próximo campo apenas se o usuário não estiver digitando ativamente
|
// Focar no próximo campo apenas se o usuário não estiver digitando ativamente
|
||||||
@@ -251,6 +250,18 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
}, 100);
|
}, 100);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Se CEP não encontrado, limpar campos e permitir edição manual
|
||||||
|
setEnderecoState({
|
||||||
|
endereco: "",
|
||||||
|
bairro: "",
|
||||||
|
cidade: "",
|
||||||
|
estado: "",
|
||||||
|
preenchido: false,
|
||||||
|
});
|
||||||
|
setValue("endereco", "");
|
||||||
|
setValue("bairro", "");
|
||||||
|
setValue("cidade", "");
|
||||||
|
setValue("estado", "");
|
||||||
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.");
|
||||||
}
|
}
|
||||||
@@ -622,10 +633,9 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
required: "Endereço é obrigatório",
|
required: "Endereço é obrigatório",
|
||||||
})}
|
})}
|
||||||
error={errors.endereco?.message}
|
error={errors.endereco?.message}
|
||||||
value={enderecoState.preenchido ? enderecoState.endereco : undefined}
|
// Remover value/controlado por enderecoState, deixar react-hook-form controlar
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setValue("endereco", e.target.value);
|
setValue("endereco", e.target.value, { shouldValidate: true });
|
||||||
setEnderecoState(prev => ({...prev, endereco: e.target.value}));
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
@@ -645,10 +655,9 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
required: "Bairro é obrigatório",
|
required: "Bairro é obrigatório",
|
||||||
})}
|
})}
|
||||||
error={errors.bairro?.message}
|
error={errors.bairro?.message}
|
||||||
value={enderecoState.preenchido ? enderecoState.bairro : undefined}
|
// Remover value/controlado por enderecoState, deixar react-hook-form controlar
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setValue("bairro", e.target.value);
|
setValue("bairro", e.target.value, { shouldValidate: true });
|
||||||
setEnderecoState(prev => ({...prev, bairro: e.target.value}));
|
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<FormInput
|
<FormInput
|
||||||
@@ -657,9 +666,9 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
required: "Cidade é obrigatória",
|
required: "Cidade é obrigatória",
|
||||||
})}
|
})}
|
||||||
error={errors.cidade?.message}
|
error={errors.cidade?.message}
|
||||||
value={enderecoState.preenchido ? enderecoState.cidade : undefined}
|
value={typeof watch("cidade") === "string" ? watch("cidade") : enderecoState.cidade}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setValue("cidade", e.target.value);
|
setValue("cidade", e.target.value, { shouldValidate: true });
|
||||||
setEnderecoState(prev => ({...prev, cidade: e.target.value}));
|
setEnderecoState(prev => ({...prev, cidade: e.target.value}));
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
@@ -670,9 +679,9 @@ export const ClienteModal: React.FC<ClienteModalProps> = ({
|
|||||||
})}
|
})}
|
||||||
options={estadosOptions}
|
options={estadosOptions}
|
||||||
error={errors.estado?.message}
|
error={errors.estado?.message}
|
||||||
value={enderecoState.preenchido ? enderecoState.estado : undefined}
|
value={typeof watch("estado") === "string" ? watch("estado") : enderecoState.estado}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
setValue("estado", e.target.value);
|
setValue("estado", e.target.value, { shouldValidate: true });
|
||||||
setEnderecoState(prev => ({...prev, estado: e.target.value}));
|
setEnderecoState(prev => ({...prev, estado: e.target.value}));
|
||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useBenchmarking } from '../../hooks/useBenchmarking';
|
||||||
|
import { CheckCircleIcon, XCircleIcon, FolderOpenIcon } from '@heroicons/react/24/solid';
|
||||||
|
|
||||||
|
export const BenchmarkingEscritorio: React.FC = () => {
|
||||||
|
// Hook para buscar e calcular benchmarking
|
||||||
|
const { data: benchmarking, isLoading, error } = useBenchmarking();
|
||||||
|
|
||||||
|
if (isLoading) return <div>Carregando benchmarking...</div>;
|
||||||
|
if (error) return <div className="text-red-600">Erro ao buscar benchmarking</div>;
|
||||||
|
if (!benchmarking) return null;
|
||||||
|
|
||||||
|
// Cálculo da porcentagem de sucesso das causas
|
||||||
|
const totalCausas = benchmarking.procedentes + benchmarking.improcedentesOuSemMerito;
|
||||||
|
const sucessoPercent = totalCausas > 0 ? Math.round((benchmarking.procedentes / totalCausas) * 100) : 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border rounded-xl p-6 shadow-lg bg-white dark:bg-gray-900 flex flex-col gap-6 max-w-md mx-auto">
|
||||||
|
<div className="grid grid-cols-2 gap-4">
|
||||||
|
<div className="flex items-center gap-2 bg-blue-50 dark:bg-blue-900 rounded-lg p-3">
|
||||||
|
<FolderOpenIcon className="h-7 w-7 text-blue-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Total de processos</div>
|
||||||
|
<div className="text-lg font-bold text-blue-700 dark:text-blue-300">{benchmarking.totalProcessos}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 bg-green-50 dark:bg-green-900 rounded-lg p-3">
|
||||||
|
<CheckCircleIcon className="h-7 w-7 text-green-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Processos ativos</div>
|
||||||
|
<div className="text-lg font-bold text-green-700 dark:text-green-300">{benchmarking.ativos}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 bg-green-50 dark:bg-green-900 rounded-lg p-3">
|
||||||
|
<CheckCircleIcon className="h-7 w-7 text-green-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Julgados procedentes</div>
|
||||||
|
<div className="text-lg font-bold text-green-700 dark:text-green-300">{benchmarking.procedentes}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 bg-red-50 dark:bg-red-900 rounded-lg p-3">
|
||||||
|
<XCircleIcon className="h-7 w-7 text-red-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Improcedentes/Sem mérito</div>
|
||||||
|
<div className="text-lg font-bold text-red-700 dark:text-red-300">{benchmarking.improcedentesOuSemMerito}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 bg-indigo-50 dark:bg-indigo-900 rounded-lg p-3">
|
||||||
|
<FolderOpenIcon className="h-7 w-7 text-indigo-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Ajuizados últimos 7 dias</div>
|
||||||
|
<div className="text-lg font-bold text-indigo-700 dark:text-indigo-300">{benchmarking.ajuizados7dias}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2 bg-teal-50 dark:bg-teal-900 rounded-lg p-3">
|
||||||
|
<CheckCircleIcon className="h-7 w-7 text-teal-600" />
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">% de sucesso das causas</div>
|
||||||
|
<div className="text-lg font-extrabold text-teal-700 dark:text-teal-300">{sucessoPercent}%</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useCalendarioAtendimentos } from '../../hooks/useCalendarioAtendimentos';
|
||||||
|
import { CalendarIcon, UserIcon, PresentationChartBarIcon } from '@heroicons/react/24/outline';
|
||||||
|
|
||||||
|
export const CalendarioAtendimentos: React.FC = () => {
|
||||||
|
const { data: eventos = [], isLoading, error } = useCalendarioAtendimentos();
|
||||||
|
|
||||||
|
// Estado para mês e ano selecionados
|
||||||
|
const hoje = new Date();
|
||||||
|
const [mesSelecionado, setMesSelecionado] = React.useState(hoje.getMonth() + 1);
|
||||||
|
const [anoSelecionado, setAnoSelecionado] = React.useState(hoje.getFullYear());
|
||||||
|
const diasMes = Array.from({ length: new Date(anoSelecionado, mesSelecionado, 0).getDate() }, (_, i) => i + 1);
|
||||||
|
const mesStr = mesSelecionado.toString().padStart(2, '0');
|
||||||
|
const anoStr = anoSelecionado.toString();
|
||||||
|
|
||||||
|
// Atualiza data selecionada ao trocar mês/ano
|
||||||
|
const [dataSelecionada, setDataSelecionada] = React.useState(`${anoStr}-${mesStr}-${hoje.getDate().toString().padStart(2, '0')}`);
|
||||||
|
React.useEffect(() => {
|
||||||
|
setDataSelecionada(`${anoStr}-${mesStr}-${hoje.getDate().toString().padStart(2, '0')}`);
|
||||||
|
}, [mesSelecionado, anoSelecionado]);
|
||||||
|
|
||||||
|
// Separar eventos futuros/próximos e passados considerando ano/mês
|
||||||
|
const hojeStr = `${anoStr}-${mesStr}-${hoje.getDate().toString().padStart(2, '0')}`;
|
||||||
|
const eventosProximos = eventos
|
||||||
|
.filter(ev => ev.data >= hojeStr)
|
||||||
|
.sort((a, b) => a.data.localeCompare(b.data))
|
||||||
|
.slice(0, 10);
|
||||||
|
const eventosPassados = eventos
|
||||||
|
.filter(ev => ev.data < hojeStr)
|
||||||
|
.sort((a, b) => b.data.localeCompare(a.data))
|
||||||
|
.slice(0, 10);
|
||||||
|
|
||||||
|
const eventosDoDia = eventos.filter(e => e.data === dataSelecionada);
|
||||||
|
|
||||||
|
if (isLoading) return <div>Carregando calendário...</div>;
|
||||||
|
if (error) return <div className="text-red-600">Erro ao buscar eventos</div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border rounded-xl p-4 shadow-lg bg-white dark:bg-gray-900 flex flex-col gap-6 max-w-4xl mx-auto">
|
||||||
|
<h2 className="text-lg font-bold text-gray-800 dark:text-gray-100 mb-2 flex items-center gap-2">
|
||||||
|
<CalendarIcon className="h-6 w-6 text-blue-600" /> Calendário de Atendimentos e Audiências
|
||||||
|
</h2>
|
||||||
|
<div className="flex items-center gap-4 mb-2">
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setMesSelecionado(m => m === 1 ? 12 : m - 1)}><</button>
|
||||||
|
<span className="font-semibold text-lg">{mesStr}/{anoStr}</span>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setMesSelecionado(m => m === 12 ? 1 : m + 1)}>></button>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setAnoSelecionado(a => a - 1)}>< Ano</button>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setAnoSelecionado(a => a + 1)}>Ano ></button>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-7 gap-2 mb-4">
|
||||||
|
{diasMes.map((dia) => {
|
||||||
|
const dataStr = `${anoStr}-${mesStr}-${dia.toString().padStart(2, '0')}`;
|
||||||
|
const eventosDia = eventos.filter(e => e.data === dataStr);
|
||||||
|
const selecionado = dataStr === dataSelecionada;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={dia}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setDataSelecionada(dataStr)}
|
||||||
|
className={`h-12 w-full flex flex-col items-center justify-center border rounded-lg shadow-sm transition-all text-[11px] focus:outline-none ${selecionado ? 'ring-2 ring-blue-500 border-blue-500 bg-blue-100 dark:bg-blue-900' : eventosDia.length ? 'bg-blue-50 dark:bg-blue-900 border-blue-400' : 'bg-gray-50 dark:bg-gray-800'}`}
|
||||||
|
>
|
||||||
|
<span className="font-bold text-[11px] text-gray-700 dark:text-gray-200">{dia}</span>
|
||||||
|
{eventosDia.map((ev) => (
|
||||||
|
<span key={ev.id} className={`text-[10px] font-semibold flex items-center gap-1 whitespace-nowrap ${ev.tipo === 'Audiência' ? 'text-red-600' : 'text-blue-700'}`}>
|
||||||
|
{ev.tipo === 'Audiência' ? <PresentationChartBarIcon className="h-3 w-3" /> : <UserIcon className="h-3 w-3" />} {ev.tipo}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
<div className="mb-6">
|
||||||
|
<h3 className="font-semibold mb-2 flex items-center gap-2"><CalendarIcon className="h-5 w-5 text-blue-600" /> Eventos do dia {dataSelecionada.split('-').reverse().join('/')}</h3>
|
||||||
|
<ul className="text-xs divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
{eventosDoDia.length === 0 && <li className="text-gray-400">Não existem eventos no dia selecionado.</li>}
|
||||||
|
{eventosDoDia.map((ev) => (
|
||||||
|
<li key={ev.id} className="py-2 flex flex-wrap items-center gap-3">
|
||||||
|
{ev.tipo === 'Audiência' ? <PresentationChartBarIcon className="h-4 w-4 text-red-600" /> : <UserIcon className="h-4 w-4 text-blue-600" />}
|
||||||
|
<span className="px-2 py-1 rounded text-xs font-semibold bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-200 min-w-[80px] text-center">{ev.tipo}</span>
|
||||||
|
<span className="text-gray-600 dark:text-gray-300 break-words max-w-xs">{ev.descricao}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-2 gap-8">
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2 flex items-center gap-2"><CalendarIcon className="h-5 w-5 text-blue-600" /> Próximos eventos</h3>
|
||||||
|
<ul className="text-xs divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
{eventosProximos.length === 0 && <li className="text-gray-400">Nenhum evento futuro</li>}
|
||||||
|
{eventosProximos.map((ev) => (
|
||||||
|
<li key={ev.id} className="py-2 flex flex-wrap items-center gap-3">
|
||||||
|
{ev.tipo === 'Audiência' ? <PresentationChartBarIcon className="h-4 w-4 text-red-600" /> : <UserIcon className="h-4 w-4 text-blue-600" />}
|
||||||
|
<span className="font-bold min-w-[70px]">{ev.data}</span>
|
||||||
|
<span className="px-2 py-1 rounded text-xs font-semibold bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-200 min-w-[80px] text-center">{ev.tipo}</span>
|
||||||
|
<span className="text-gray-600 dark:text-gray-300 break-words max-w-xs">{ev.descricao}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2 flex items-center gap-2"><CalendarIcon className="h-5 w-5 text-gray-500" /> Últimos eventos</h3>
|
||||||
|
<ul className="text-xs divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
{eventosPassados.length === 0 && <li className="text-gray-400">Nenhum evento anterior</li>}
|
||||||
|
{eventosPassados.map((ev) => (
|
||||||
|
<li key={ev.id} className="py-2 flex flex-wrap items-center gap-3">
|
||||||
|
{ev.tipo === 'Audiência' ? <PresentationChartBarIcon className="h-4 w-4 text-red-600" /> : <UserIcon className="h-4 w-4 text-blue-600" />}
|
||||||
|
<span className="font-bold min-w-[70px]">{ev.data}</span>
|
||||||
|
<span className="px-2 py-1 rounded text-xs font-semibold bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-200 min-w-[80px] text-center">{ev.tipo}</span>
|
||||||
|
<span className="text-gray-600 dark:text-gray-300 break-words max-w-xs">{ev.descricao}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,52 +1,30 @@
|
|||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { useAuth } from '../../contexts/AuthContext';
|
import { WorkflowTarefas } from './WorkflowTarefas';
|
||||||
import { useDashboardStats } from '../../hooks/useDashboardStats';
|
import { CalendarioAtendimentos } from './CalendarioAtendimentos';
|
||||||
import { ProcessosStats } from './stats/ProcessosStats';
|
import { BenchmarkingEscritorio } from './BenchmarkingEscritorio';
|
||||||
import { TarefasStats } from './stats/TarefasStats';
|
import { PainelFinanceiro } from './PainelFinanceiro';
|
||||||
import { AtendimentosStats } from './stats/AtendimentosStats';
|
|
||||||
import { FinanceiroStats } from './stats/FinanceiroStats';
|
|
||||||
import { AlertasPrazos } from './AlertasPrazos';
|
|
||||||
import { AtividadesRecentes } from './AtividadesRecentes';
|
|
||||||
import { TaxaSucessoCard } from './TaxaSucessoCard';
|
|
||||||
import { KPIsFinanceiros } from './stats/KPIsFinanceiros';
|
|
||||||
|
|
||||||
export const DashboardLayout: React.FC = () => {
|
export const DashboardLayout: React.FC = () => {
|
||||||
const { user } = useAuth();
|
|
||||||
const {
|
|
||||||
processosStats,
|
|
||||||
tarefasStats,
|
|
||||||
atendimentosStats,
|
|
||||||
financeiroStats,
|
|
||||||
proximosPrazos,
|
|
||||||
atividades
|
|
||||||
} = useDashboardStats();
|
|
||||||
|
|
||||||
const isAdminOrAdvogado = ['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user?.perfil || '');
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6 p-6">
|
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6 p-6">
|
||||||
{/* Stats Cards */}
|
{/* Coluna 1: Workflow de Tarefas */}
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
<div className="space-y-6">
|
||||||
{processosStats.data && <ProcessosStats data={processosStats.data} />}
|
<h2 className="text-xl font-bold">Workflow de Tarefas</h2>
|
||||||
{tarefasStats.data && <TarefasStats data={tarefasStats.data} />}
|
<WorkflowTarefas />
|
||||||
{atendimentosStats.data && <AtendimentosStats data={atendimentosStats.data} />}
|
|
||||||
{isAdminOrAdvogado && financeiroStats.data && (
|
|
||||||
<FinanceiroStats data={financeiroStats.data} />
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
{/* Coluna 2: Calendário de Atendimentos, Compromissos e Diligências */}
|
||||||
{/* Coluna da esquerda */}
|
<div className="space-y-6">
|
||||||
<div className="lg:col-span-2 space-y-6">
|
<h2 className="text-xl font-bold">Calendário</h2>
|
||||||
<TaxaSucessoCard />
|
<CalendarioAtendimentos />
|
||||||
{isAdminOrAdvogado && <KPIsFinanceiros />}
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Coluna da direita */}
|
{/* Coluna 3: Benchmarking do Escritório */}
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<AlertasPrazos />
|
<h2 className="text-xl font-bold">Benchmarking do Escritório</h2>
|
||||||
<AtividadesRecentes />
|
<BenchmarkingEscritorio />
|
||||||
</div>
|
<PainelFinanceiro />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useFinanceiroPainel } from '../../hooks/useFinanceiroPainel';
|
||||||
|
import { CurrencyDollarIcon, ArrowDownCircleIcon, ArrowUpCircleIcon } from '@heroicons/react/24/solid';
|
||||||
|
|
||||||
|
export const PainelFinanceiro: React.FC = () => {
|
||||||
|
const hoje = new Date();
|
||||||
|
const [mes, setMes] = React.useState(hoje.getMonth() + 1);
|
||||||
|
const [ano, setAno] = React.useState(hoje.getFullYear());
|
||||||
|
const { data, isLoading, error } = useFinanceiroPainel(mes, ano);
|
||||||
|
|
||||||
|
const mesesNomes = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border rounded-xl p-6 shadow-lg bg-white dark:bg-gray-900 flex flex-col gap-6 max-w-4xl mx-auto mt-8">
|
||||||
|
<h2 className="text-lg font-bold text-gray-800 dark:text-gray-100 mb-2 flex items-center gap-2">
|
||||||
|
<CurrencyDollarIcon className="h-6 w-6 text-green-600" /> Painel Financeiro
|
||||||
|
</h2>
|
||||||
|
<div className="flex items-center gap-4 mb-2">
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setMes(m => m === 1 ? 12 : m - 1)}><</button>
|
||||||
|
<span className="font-semibold text-lg">{mesesNomes[mes - 1]}/{ano}</span>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setMes(m => m === 12 ? 1 : m + 1)}>></button>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setAno(a => a - 1)}>< Ano</button>
|
||||||
|
<button type="button" className="px-2 py-1 rounded bg-gray-100 dark:bg-gray-800" onClick={() => setAno(a => a + 1)}>Ano ></button>
|
||||||
|
</div>
|
||||||
|
{isLoading && <div>Carregando dados financeiros...</div>}
|
||||||
|
{error && <div className="text-red-600">Erro ao buscar dados financeiros</div>}
|
||||||
|
{data && (
|
||||||
|
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
|
||||||
|
<div className="flex flex-col items-center bg-green-50 dark:bg-green-900 rounded-lg p-4">
|
||||||
|
<CurrencyDollarIcon className="h-7 w-7 text-green-600 mb-1" />
|
||||||
|
<span className="text-xs text-gray-500">Honorários a receber</span>
|
||||||
|
<span className="text-lg font-bold text-green-700 dark:text-green-300">R$ {data.honorariosAReceber.toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center bg-blue-50 dark:bg-blue-900 rounded-lg p-4">
|
||||||
|
<ArrowUpCircleIcon className="h-7 w-7 text-blue-600 mb-1" />
|
||||||
|
<span className="text-xs text-gray-500">Honorários recebidos no mês</span>
|
||||||
|
<span className="text-lg font-bold text-blue-700 dark:text-blue-300">R$ {data.honorariosRecebidosMes.toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center bg-red-50 dark:bg-red-900 rounded-lg p-4">
|
||||||
|
<ArrowDownCircleIcon className="h-7 w-7 text-red-600 mb-1" />
|
||||||
|
<span className="text-xs text-gray-500">Custas a pagar</span>
|
||||||
|
<span className="text-lg font-bold text-red-700 dark:text-red-300">R$ {data.custasAPagar.toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col items-center bg-teal-50 dark:bg-teal-900 rounded-lg p-4">
|
||||||
|
<ArrowUpCircleIcon className="h-7 w-7 text-teal-600 mb-1" />
|
||||||
|
<span className="text-xs text-gray-500">Custas pagas no mês</span>
|
||||||
|
<span className="text-lg font-bold text-teal-700 dark:text-teal-300">R$ {data.custasPagasMes.toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{data && (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2 text-green-700 dark:text-green-300">Honorários recebidos no mês</h3>
|
||||||
|
<ul className="text-xs divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
{data.detalhesHonorarios.length === 0 && <li className="text-gray-400">Nenhum recebimento registrado neste mês.</li>}
|
||||||
|
{data.detalhesHonorarios.map((item, idx) => (
|
||||||
|
<li key={idx} className="py-2 flex flex-col">
|
||||||
|
<span className="font-bold">Contrato: {item.contrato?.processoId || 'N/A'}</span>
|
||||||
|
<span>Parcela: {item.parcela?.numeroParcela || 'N/A'} - Valor: R$ {Number(item.parcela?.valorPago || item.parcela?.valor || 0).toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
<span className="text-gray-500">Pago em: {item.parcela?.dataPagamento ? new Date(item.parcela.dataPagamento).toLocaleDateString('pt-br') : '-'}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold mb-2 text-red-700 dark:text-red-300">Custas pagas no mês</h3>
|
||||||
|
<ul className="text-xs divide-y divide-gray-200 dark:divide-gray-700">
|
||||||
|
{data.detalhesCustas.length === 0 && <li className="text-gray-400">Nenhuma custa paga neste mês.</li>}
|
||||||
|
{data.detalhesCustas.map((c, idx) => (
|
||||||
|
<li key={idx} className="py-2 flex flex-col">
|
||||||
|
<span className="font-bold">Processo: {c.processoId || 'N/A'}</span>
|
||||||
|
<span>Tipo: {c.tipo || 'N/A'} - Valor: R$ {Number(c.valor || 0).toLocaleString('pt-br', { minimumFractionDigits: 2 })}</span>
|
||||||
|
<span className="text-gray-500">Pago em: {c.dataPagamento ? new Date(c.dataPagamento).toLocaleDateString('pt-br') : '-'}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useAuth } from '../../contexts/AuthContext';
|
||||||
|
import { useTarefas } from '../../hooks/useTarefas';
|
||||||
|
import { Tarefa } from '../../types/entities';
|
||||||
|
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||||
|
|
||||||
|
export const WorkflowTarefas: React.FC = () => {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { tarefas, isLoading, deleteTarefa } = useTarefas();
|
||||||
|
|
||||||
|
const canDelete = user && ['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user.perfil);
|
||||||
|
|
||||||
|
const handleEdit = (tarefa: Tarefa) => {
|
||||||
|
// Implemente a lógica de edição conforme necessário
|
||||||
|
alert(`Editar tarefa: ${tarefa.titulo}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id: string) => {
|
||||||
|
if (!window.confirm('Tem certeza que deseja excluir esta tarefa?')) return;
|
||||||
|
try {
|
||||||
|
await deleteTarefa.mutateAsync(id);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao excluir tarefa:', error);
|
||||||
|
alert('Erro ao excluir tarefa');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-4 text-center text-gray-500 dark:text-gray-400">
|
||||||
|
Carregando tarefas...
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tarefas || tarefas.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-4 text-center text-gray-500 dark:text-gray-400">
|
||||||
|
Nenhuma tarefa encontrada.
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exibir apenas tarefas que não estão concluídas ou canceladas
|
||||||
|
const tarefasAtivas = tarefas.filter((t: Tarefa) => t.status !== 'CONCLUIDA' && t.status !== 'CANCELADA');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
{tarefasAtivas.map((tarefa: Tarefa) => (
|
||||||
|
<div key={tarefa.id} className="border rounded-lg p-4 shadow flex flex-col gap-2 bg-white dark:bg-gray-800">
|
||||||
|
<div className="flex flex-col md:flex-row md:justify-between md:items-center gap-2">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<span className="font-medium text-lg text-gray-900 dark:text-white">{tarefa.titulo}</span>
|
||||||
|
{/* Exibe o grau de prioridade com cor */}
|
||||||
|
<span className={`px-2 py-1 rounded text-xs font-semibold border ${
|
||||||
|
tarefa.prioridade === 'URGENTE' ? 'bg-red-100 text-red-700 border-red-300' :
|
||||||
|
tarefa.prioridade === 'ALTA' ? 'bg-orange-100 text-orange-700 border-orange-300' :
|
||||||
|
tarefa.prioridade === 'MEDIA' ? 'bg-yellow-100 text-yellow-700 border-yellow-300' :
|
||||||
|
'bg-green-100 text-green-700 border-green-300'
|
||||||
|
}`}>
|
||||||
|
{tarefa.prioridade === 'URGENTE' ? 'Urgente' : tarefa.prioridade === 'ALTA' ? 'Alta' : tarefa.prioridade === 'MEDIA' ? 'Média' : 'Baixa'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
{/* Status da tarefa */}
|
||||||
|
<span className={`px-2 py-1 rounded text-xs font-semibold border ${
|
||||||
|
tarefa.status === 'CONCLUIDA' ? 'bg-green-100 text-green-700 border-green-300' :
|
||||||
|
tarefa.status === 'EM_ANDAMENTO' ? 'bg-blue-100 text-blue-700 border-blue-300' :
|
||||||
|
tarefa.status === 'PENDENTE' ? 'bg-gray-100 text-gray-700 border-gray-300' :
|
||||||
|
'bg-red-100 text-red-700 border-red-300'
|
||||||
|
}`}>
|
||||||
|
{tarefa.status.replace('_', ' ')}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
onClick={() => handleEdit(tarefa)}
|
||||||
|
className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300"
|
||||||
|
title="Editar"
|
||||||
|
>
|
||||||
|
<PencilIcon className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
{canDelete && (
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(tarefa.id)}
|
||||||
|
className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300"
|
||||||
|
title="Excluir"
|
||||||
|
>
|
||||||
|
<TrashIcon className="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{/* Listagem das subtarefas vinculadas */}
|
||||||
|
{tarefa.subtarefas && tarefa.subtarefas.length > 0 && (
|
||||||
|
<ul className="mt-2 ml-2 list-disc text-sm text-gray-700 dark:text-gray-300">
|
||||||
|
{tarefa.subtarefas.map((sub) => (
|
||||||
|
<li key={sub.id} className={sub.concluida ? 'line-through text-gray-400' : ''}>
|
||||||
|
{sub.titulo} {sub.concluida ? '(Concluída)' : ''}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import React, { useState } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { toast } from 'react-toastify';
|
||||||
|
import {
|
||||||
|
Container,
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
Typography,
|
||||||
|
TextField,
|
||||||
|
Button,
|
||||||
|
Box,
|
||||||
|
Alert,
|
||||||
|
CircularProgress
|
||||||
|
} from '@mui/material';
|
||||||
|
|
||||||
|
export const IniciarNavegacao: React.FC = () => {
|
||||||
|
const [titulo, setTitulo] = useState('');
|
||||||
|
const [descricao, setDescricao] = useState('');
|
||||||
|
const [iniciando, setIniciando] = useState(false);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const handleIniciar = async () => {
|
||||||
|
if (!titulo.trim()) {
|
||||||
|
toast.error('Título é obrigatório');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIniciando(true);
|
||||||
|
|
||||||
|
const response = await fetch('/api/navegacao/iniciar', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ titulo, descricao })
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error('Erro ao iniciar sessão');
|
||||||
|
}
|
||||||
|
|
||||||
|
const resultado = await response.json();
|
||||||
|
|
||||||
|
toast.success('Sessão de navegação iniciada!');
|
||||||
|
navigate(`/navegacao/sessao/${resultado.sessaoId}`);
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro:', error);
|
||||||
|
toast.error('Erro ao iniciar sessão de navegação');
|
||||||
|
} finally {
|
||||||
|
setIniciando(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Container maxWidth="md">
|
||||||
|
<Box mt={4}>
|
||||||
|
<Card>
|
||||||
|
<CardContent>
|
||||||
|
<Typography variant="h4" gutterBottom>
|
||||||
|
Nova Sessão de Coleta de Provas
|
||||||
|
</Typography>
|
||||||
|
|
||||||
|
<Alert severity="info" sx={{ mb: 3 }}>
|
||||||
|
<Typography variant="body2">
|
||||||
|
Este sistema criará uma sessão controlada de navegação onde todas as ações
|
||||||
|
serão gravadas e registradas para fins de coleta de provas digitais.
|
||||||
|
</Typography>
|
||||||
|
</Alert>
|
||||||
|
|
||||||
|
<Box component="form" sx={{ mt: 2 }}>
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label="Título da Sessão"
|
||||||
|
value={titulo}
|
||||||
|
onChange={(e) => setTitulo(e.target.value)}
|
||||||
|
margin="normal"
|
||||||
|
required
|
||||||
|
helperText="Descreva brevemente o objetivo desta coleta"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<TextField
|
||||||
|
fullWidth
|
||||||
|
label="Descrição (opcional)"
|
||||||
|
value={descricao}
|
||||||
|
onChange={(e) => setDescricao(e.target.value)}
|
||||||
|
margin="normal"
|
||||||
|
multiline
|
||||||
|
rows={3}
|
||||||
|
helperText="Informações adicionais sobre o que será coletado"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Box mt={3} display="flex" gap={2}>
|
||||||
|
<Button
|
||||||
|
variant="contained"
|
||||||
|
color="primary"
|
||||||
|
onClick={handleIniciar}
|
||||||
|
disabled={iniciando || !titulo.trim()}
|
||||||
|
startIcon={iniciando ? <CircularProgress size={20} /> : null}
|
||||||
|
>
|
||||||
|
{iniciando ? 'Iniciando...' : 'Iniciar Coleta'}
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
variant="outlined"
|
||||||
|
onClick={() => navigate('/navegacao')}
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</Button>
|
||||||
|
</Box>
|
||||||
|
</Box>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</Box>
|
||||||
|
</Container>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -3,6 +3,8 @@ import { useNavigate } from 'react-router-dom';
|
|||||||
import { useDropzone } from 'react-dropzone';
|
import { useDropzone } from 'react-dropzone';
|
||||||
import { toast } from 'react-toastify';
|
import { toast } from 'react-toastify';
|
||||||
|
|
||||||
|
// Página pública: NÃO requer autenticação do usuário
|
||||||
|
|
||||||
export function ClientProvaUpload() {
|
export function ClientProvaUpload() {
|
||||||
const [file, setFile] = useState<File | null>(null);
|
const [file, setFile] = useState<File | null>(null);
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
@@ -43,9 +45,31 @@ export function ClientProvaUpload() {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Validação extra do arquivo antes do upload
|
||||||
|
function validateFile(file: File | null): string | null {
|
||||||
|
if (!file) return 'Nenhum arquivo selecionado.';
|
||||||
|
const allowedTypes = [
|
||||||
|
'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf'
|
||||||
|
];
|
||||||
|
if (!allowedTypes.includes(file.type)) {
|
||||||
|
return 'Tipo de arquivo não suportado. Use JPG, PNG, GIF, WEBP ou PDF.';
|
||||||
|
}
|
||||||
|
if (file.size > 10 * 1024 * 1024) {
|
||||||
|
return 'Arquivo excede o tamanho máximo de 10MB.';
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
const onDrop = useCallback(async (acceptedFiles: File[]) => {
|
const onDrop = useCallback(async (acceptedFiles: File[]) => {
|
||||||
if (acceptedFiles.length > 0) {
|
if (acceptedFiles.length > 0) {
|
||||||
const selectedFile = acceptedFiles[0];
|
const selectedFile = acceptedFiles[0];
|
||||||
|
const validationError = validateFile(selectedFile);
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError);
|
||||||
|
setFile(null);
|
||||||
|
setFilePreview(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
setFile(selectedFile);
|
setFile(selectedFile);
|
||||||
|
|
||||||
// Criar preview para imagens
|
// Criar preview para imagens
|
||||||
@@ -77,6 +101,12 @@ export function ClientProvaUpload() {
|
|||||||
toast.error('Por favor, selecione um arquivo primeiro');
|
toast.error('Por favor, selecione um arquivo primeiro');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
// Validação extra antes do envio
|
||||||
|
const validationError = validateFile(file);
|
||||||
|
if (validationError) {
|
||||||
|
toast.error(validationError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
setUploadProgress(0);
|
setUploadProgress(0);
|
||||||
@@ -120,7 +150,7 @@ export function ClientProvaUpload() {
|
|||||||
// Adicionar timestamp preciso do cliente
|
// Adicionar timestamp preciso do cliente
|
||||||
formData.append('client_timestamp', new Date().toISOString());
|
formData.append('client_timestamp', new Date().toISOString());
|
||||||
|
|
||||||
// Criar simulação de progresso
|
// Simulação de progresso
|
||||||
const progressInterval = setInterval(() => {
|
const progressInterval = setInterval(() => {
|
||||||
setUploadProgress(prev => {
|
setUploadProgress(prev => {
|
||||||
if (prev >= 95) {
|
if (prev >= 95) {
|
||||||
@@ -131,10 +161,18 @@ export function ClientProvaUpload() {
|
|||||||
});
|
});
|
||||||
}, 300);
|
}, 300);
|
||||||
|
|
||||||
const response = await fetch('/api/provas/upload', {
|
// Upload sem autenticação (página pública)
|
||||||
method: 'POST',
|
let response: Response;
|
||||||
body: formData,
|
try {
|
||||||
});
|
response = await fetch('/api/provas/upload', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
} catch (networkError) {
|
||||||
|
clearInterval(progressInterval);
|
||||||
|
setUploadProgress(0);
|
||||||
|
throw new Error('Erro de conexão. Verifique sua internet e tente novamente.');
|
||||||
|
}
|
||||||
|
|
||||||
clearInterval(progressInterval);
|
clearInterval(progressInterval);
|
||||||
setUploadProgress(100);
|
setUploadProgress(100);
|
||||||
@@ -155,9 +193,14 @@ export function ClientProvaUpload() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Ler o corpo da resposta
|
// Ler o corpo da resposta
|
||||||
const result = await response.json();
|
let result: any;
|
||||||
|
try {
|
||||||
if (result.id) {
|
result = await response.json();
|
||||||
|
} catch {
|
||||||
|
throw new Error('Resposta inesperada do servidor.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result && result.id) {
|
||||||
toast.success('Arquivo enviado com sucesso!');
|
toast.success('Arquivo enviado com sucesso!');
|
||||||
// Navegar para a página de status
|
// Navegar para a página de status
|
||||||
navigate(`/public/provas/status/${result.id}`);
|
navigate(`/public/provas/status/${result.id}`);
|
||||||
@@ -165,10 +208,10 @@ export function ClientProvaUpload() {
|
|||||||
throw new Error('ID do documento não encontrado na resposta');
|
throw new Error('ID do documento não encontrado na resposta');
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error: any) {
|
||||||
console.error('Erro detalhado no upload:', error);
|
console.error('Erro detalhado no upload:', error);
|
||||||
setError(error.message || 'Erro ao enviar arquivo. Por favor, tente novamente.');
|
setError(error.message || 'Erro ao enviar arquivo. Por favor, tente novamente.');
|
||||||
toast.error('Falha no upload: ' + error.message);
|
toast.error('Falha no upload: ' + (error.message || 'Erro desconhecido'));
|
||||||
} finally {
|
} finally {
|
||||||
setUploading(false);
|
setUploading(false);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -168,6 +168,18 @@ export const TarefaModal: React.FC<TarefaModalProps> = ({ isOpen, onClose, taref
|
|||||||
<option value="URGENTE">Urgente</option>
|
<option value="URGENTE">Urgente</option>
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
{/* Campo para alterar o status da tarefa conforme banco de dados */}
|
||||||
|
<select
|
||||||
|
{...register('status')}
|
||||||
|
className="w-full p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||||
|
>
|
||||||
|
<option value="PENDENTE">Pendente</option>
|
||||||
|
{/* Exibe 'Em andamento' sem underline */}
|
||||||
|
<option value="EM_ANDAMENTO">Em andamento</option>
|
||||||
|
<option value="CONCLUIDA">Concluída</option>
|
||||||
|
<option value="CANCELADA">Cancelada</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
<select
|
<select
|
||||||
{...register('responsavelId')}
|
{...register('responsavelId')}
|
||||||
className="w-full p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
className="w-full p-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { useMutation, useQueryClient } from "react-query";
|
import { useMutation, useQuery, useQueryClient } from "react-query";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
|
import api from "../services/api";
|
||||||
|
|
||||||
export function useAudiencias(processoId: string) {
|
export function useAudiencias(processoId: string) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -49,9 +50,15 @@ export function useAudiencias(processoId: string) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const { data: audiencias } = useQuery("audiencias", async () => {
|
||||||
|
const { data } = await api.get("/audiencias");
|
||||||
|
return data;
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
addAudiencia: addAudiencia.mutateAsync,
|
addAudiencia: addAudiencia.mutateAsync,
|
||||||
updateAudiencia: updateAudiencia.mutateAsync,
|
updateAudiencia: updateAudiencia.mutateAsync,
|
||||||
deleteAudiencia: deleteAudiencia.mutateAsync,
|
deleteAudiencia: deleteAudiencia.mutateAsync,
|
||||||
|
audiencias,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { useQuery } from 'react-query';
|
||||||
|
import { Processo } from '../types/entities';
|
||||||
|
import api from '../services/api';
|
||||||
|
|
||||||
|
interface Benchmarking {
|
||||||
|
totalProcessos: number;
|
||||||
|
ativos: number;
|
||||||
|
procedentes: number;
|
||||||
|
improcedentesOuSemMerito: number;
|
||||||
|
ajuizados7dias: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hook para calcular benchmarking do escritório
|
||||||
|
export function useBenchmarking() {
|
||||||
|
return useQuery<Benchmarking>('benchmarking', async () => {
|
||||||
|
// Buscar todos os processos
|
||||||
|
const res = await api.get<Processo[]>('/processos');
|
||||||
|
const processos = res.data;
|
||||||
|
|
||||||
|
// Total de processos
|
||||||
|
const totalProcessos = processos.length;
|
||||||
|
// Total de processos ativos
|
||||||
|
const ativos = processos.filter(p => p.statusAtividade === 'ATIVO').length;
|
||||||
|
// Julgados procedentes
|
||||||
|
const procedentes = processos.filter(p => p.resultado === 'PROCEDENTE').length;
|
||||||
|
// Julgados improcedentes ou sem análise de mérito
|
||||||
|
const improcedentesOuSemMerito = processos.filter(p => p.resultado === 'IMPROCEDENTE' || p.resultado === 'SEM_ANALISE_MERITO').length;
|
||||||
|
// Processos ajuizados nos últimos 7 dias
|
||||||
|
const seteDiasAtras = new Date();
|
||||||
|
seteDiasAtras.setDate(seteDiasAtras.getDate() - 7);
|
||||||
|
const ajuizados7dias = processos.filter(p => {
|
||||||
|
const criacao = p.dataCriacao ? new Date(p.dataCriacao) : null;
|
||||||
|
return criacao && criacao >= seteDiasAtras;
|
||||||
|
}).length;
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalProcessos,
|
||||||
|
ativos,
|
||||||
|
procedentes,
|
||||||
|
improcedentesOuSemMerito,
|
||||||
|
ajuizados7dias,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { useQuery } from 'react-query';
|
||||||
|
import api from '../services/api';
|
||||||
|
|
||||||
|
export interface EventoCalendario {
|
||||||
|
id: string;
|
||||||
|
data: string;
|
||||||
|
tipo: string;
|
||||||
|
descricao: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hook para buscar atendimentos e audiências do calendário
|
||||||
|
export function useCalendarioAtendimentos() {
|
||||||
|
return useQuery<EventoCalendario[]>('calendarioAtendimentos', async () => {
|
||||||
|
// Buscar atendimentos
|
||||||
|
const atendimentosRes = await api.get('/atendimentos');
|
||||||
|
const atendimentos = atendimentosRes.data.map((a: any) => ({
|
||||||
|
id: a.id,
|
||||||
|
data: a.dataAtendimento?.slice(0, 10),
|
||||||
|
tipo: 'Atendimento',
|
||||||
|
descricao: a.titulo || 'Atendimento',
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Buscar audiências, tratar erro 404
|
||||||
|
let audiencias: EventoCalendario[] = [];
|
||||||
|
try {
|
||||||
|
const audienciasRes = await api.get('/audiencias');
|
||||||
|
audiencias = audienciasRes.data.map((a: any) => ({
|
||||||
|
id: a.id,
|
||||||
|
data: a.data?.slice(0, 10),
|
||||||
|
tipo: 'Audiência',
|
||||||
|
descricao: a.tipo || 'Audiência',
|
||||||
|
}));
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error?.response?.status !== 404) throw error;
|
||||||
|
// Se for 404, ignora audiências
|
||||||
|
}
|
||||||
|
|
||||||
|
// Junta todos eventos
|
||||||
|
return [...atendimentos, ...audiencias];
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { useQuery } from 'react-query';
|
||||||
|
import api from '../services/api';
|
||||||
|
|
||||||
|
export interface FinanceiroResumo {
|
||||||
|
honorariosAReceber: number;
|
||||||
|
honorariosRecebidosMes: number;
|
||||||
|
custasAPagar: number;
|
||||||
|
custasPagasMes: number;
|
||||||
|
detalhesHonorarios: any[];
|
||||||
|
detalhesCustas: any[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hook para buscar dados financeiros do painel diretamente do backend
|
||||||
|
export function useFinanceiroPainel(mes: number, ano: number) {
|
||||||
|
return useQuery<FinanceiroResumo>(['financeiroPainel', mes, ano], async () => {
|
||||||
|
try {
|
||||||
|
const res = await api.get(`/financeiro-painel?mes=${mes}&ano=${ano}`);
|
||||||
|
return res.data;
|
||||||
|
} catch (error: any) {
|
||||||
|
// Se der erro, retorna tudo zerado
|
||||||
|
return {
|
||||||
|
honorariosAReceber: 0,
|
||||||
|
honorariosRecebidosMes: 0,
|
||||||
|
custasAPagar: 0,
|
||||||
|
custasPagasMes: 0,
|
||||||
|
detalhesHonorarios: [],
|
||||||
|
detalhesCustas: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
import express from 'express';
|
|
||||||
import bodyParser from 'body-parser';
|
|
||||||
import cors from 'cors';
|
|
||||||
import dotenv from 'dotenv';
|
|
||||||
import path from 'path';
|
|
||||||
import { PrismaClient } from '@prisma/client';
|
|
||||||
import provasRoutes from './routes/provas';
|
|
||||||
import calculosJudiciaisRoutes from './routes/calculosJudiciais';
|
|
||||||
import indicesMonetariosRoutes from './routes/indicesMonetarios';
|
|
||||||
import pensaoAlimenticiaRoutes from './routes/pensaoAlimenticia';
|
|
||||||
|
|
||||||
dotenv.config();
|
|
||||||
|
|
||||||
const app = express();
|
|
||||||
const prisma = new PrismaClient();
|
|
||||||
|
|
||||||
// Configurar para confiar em proxies, permitindo a leitura de X-Forwarded-For
|
|
||||||
// Isso é necessário se sua aplicação estiver atrás de um balanceador de carga,
|
|
||||||
// proxy reverso ou Cloudflare
|
|
||||||
app.set('trust proxy', true);
|
|
||||||
|
|
||||||
app.use(cors());
|
|
||||||
app.use(bodyParser.json());
|
|
||||||
app.use(bodyParser.urlencoded({ extended: true }));
|
|
||||||
|
|
||||||
app.use('/api/provas', provasRoutes);
|
|
||||||
app.use('/api/calculos', calculosJudiciaisRoutes);
|
|
||||||
app.use('/api/indices', indicesMonetariosRoutes);
|
|
||||||
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRoutes);
|
|
||||||
|
|
||||||
app.use(express.static(path.join(__dirname, 'public')));
|
|
||||||
app.set('trust proxy', true); // Importante para obter o IP real em ambientes com proxy
|
|
||||||
|
|
||||||
const PORT = process.env.PORT || 5000;
|
|
||||||
|
|
||||||
app.listen(PORT, () => {
|
|
||||||
console.log(`Server is running on port ${PORT}`);
|
|
||||||
});
|
|
||||||
|
|
||||||
export { app, prisma };
|
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { Request, Response } from "express";
|
||||||
|
import { prisma } from "../prismaClient";
|
||||||
|
|
||||||
|
// Função para listar todas as audiências
|
||||||
|
export async function getAudiencias(req: Request, res: Response) {
|
||||||
|
try {
|
||||||
|
const audiencias = await prisma.audiencia.findMany({
|
||||||
|
orderBy: { data: "asc" },
|
||||||
|
include: {
|
||||||
|
processo: {
|
||||||
|
select: { numero: true, nomeContraparte: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res.json(audiencias);
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Erro ao buscar audiências:", error);
|
||||||
|
res.status(500).json({ error: "Erro ao buscar audiências" });
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-3
@@ -24,7 +24,11 @@ import processosAdministrativosRoutes from './routes/processosAdministrativos';
|
|||||||
import provasRouter from './routes/provas';
|
import provasRouter from './routes/provas';
|
||||||
import calculosJudiciaisRoutes from './routes/calculosJudiciais';
|
import calculosJudiciaisRoutes from './routes/calculosJudiciais';
|
||||||
import indicesMonetariosRoutes from './routes/indicesMonetarios';
|
import indicesMonetariosRoutes from './routes/indicesMonetarios';
|
||||||
import pensaoAlimenticiaRoutes from './routes/pensaoAlimenticia';
|
import pensaoAlimenticiaRouter from './routes/pensaoAlimenticia'; // Importar router de pensão alimentícia
|
||||||
|
import financeiroPainelRoutes from './routes/financeiroPainel'; // Importar rotas do financeiro painel
|
||||||
|
import audienciasRoutes from './routes/audiencias'; // Importar rotas de audiências
|
||||||
|
import navegacaoRoutes from './routes/navegacao'; // Adicionar esta importação
|
||||||
|
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = process.env.PORT || 5000;
|
const port = process.env.PORT || 5000;
|
||||||
@@ -47,7 +51,8 @@ app.use((req, res, next) => {
|
|||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json({ limit: '20mb' }));
|
||||||
|
app.use(express.urlencoded({ extended: true, limit: '20mb' }));
|
||||||
|
|
||||||
const clienteRepository = new ClienteRepository();
|
const clienteRepository = new ClienteRepository();
|
||||||
const processoRepository = new ProcessoRepository();
|
const processoRepository = new ProcessoRepository();
|
||||||
@@ -1475,4 +1480,7 @@ app.use('/api/documentos-modelos', documentosModelosRouter);
|
|||||||
app.use('/api/processos-administrativos', processosAdministrativosRoutes);
|
app.use('/api/processos-administrativos', processosAdministrativosRoutes);
|
||||||
app.use('/api/calculos', calculosJudiciaisRoutes);
|
app.use('/api/calculos', calculosJudiciaisRoutes);
|
||||||
app.use('/api/indices', indicesMonetariosRoutes);
|
app.use('/api/indices', indicesMonetariosRoutes);
|
||||||
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRoutes);
|
app.use('/api/pensao-alimenticia', pensaoAlimenticiaRouter);
|
||||||
|
app.use('/api/financeiro-painel', financeiroPainelRoutes); // Adicionar uso das rotas do financeiro painel
|
||||||
|
app.use('/api/audiencias', audienciasRoutes); // Adicionar uso das rotas de audiências
|
||||||
|
app.use('/api/navegacao', navegacaoRoutes); // Adicionar esta linha junto com as outras rotas
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { Router } from "express";
|
||||||
|
import { getAudiencias } from "../controllers/audienciasController";
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// GET /api/audiencias - Lista todas as audiências
|
||||||
|
router.get("/", getAudiencias);
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -83,11 +83,9 @@ router.get('/:id', async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
const calculo = await calculoService.buscarCalculo(id);
|
const calculo = await calculoService.buscarCalculo(id);
|
||||||
|
|
||||||
if (!calculo) {
|
if (!calculo) {
|
||||||
return res.status(404).json({ error: 'Cálculo não encontrado' });
|
return res.status(404).json({ error: 'Cálculo não encontrado' });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json(calculo);
|
res.json(calculo);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao buscar cálculo:', error);
|
console.error('Erro ao buscar cálculo:', error);
|
||||||
|
|||||||
@@ -0,0 +1,99 @@
|
|||||||
|
import express from 'express';
|
||||||
|
import { prisma } from '../prismaClient';
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
// GET /api/financeiro-painel?mes=6&ano=2024
|
||||||
|
router.get('/', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const mes = parseInt(req.query.mes as string) || (new Date().getMonth() + 1);
|
||||||
|
const ano = parseInt(req.query.ano as string) || (new Date().getFullYear());
|
||||||
|
if (isNaN(mes) || isNaN(ano)) {
|
||||||
|
return res.status(400).json({ error: 'Parâmetros de mês e ano inválidos.' });
|
||||||
|
}
|
||||||
|
// Datas para filtro
|
||||||
|
const dataInicio = new Date(ano, mes - 1, 1);
|
||||||
|
const dataFim = new Date(ano, mes, 1);
|
||||||
|
|
||||||
|
// Honorários a receber: parcelas pendentes ou vencidas
|
||||||
|
const honorariosAReceber = await prisma.parcelaHonorario.aggregate({
|
||||||
|
_sum: { valor: true },
|
||||||
|
where: {
|
||||||
|
OR: [{ status: 'PENDENTE' }, { status: 'VENCIDO' }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Honorários recebidos no mês
|
||||||
|
const honorariosRecebidosMes = await prisma.parcelaHonorario.aggregate({
|
||||||
|
_sum: { valorPago: true },
|
||||||
|
where: {
|
||||||
|
status: 'PAGO',
|
||||||
|
dataPagamento: {
|
||||||
|
gte: dataInicio,
|
||||||
|
lt: dataFim,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Detalhes das parcelas recebidas no mês
|
||||||
|
const detalhesHonorarios = await prisma.parcelaHonorario.findMany({
|
||||||
|
where: {
|
||||||
|
status: 'PAGO',
|
||||||
|
dataPagamento: {
|
||||||
|
gte: dataInicio,
|
||||||
|
lt: dataFim,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
include: { honorario: true },
|
||||||
|
orderBy: { dataPagamento: 'desc' },
|
||||||
|
take: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Custas a pagar
|
||||||
|
const custasAPagar = await prisma.custaProcessual.aggregate({
|
||||||
|
_sum: { valor: true },
|
||||||
|
where: {
|
||||||
|
OR: [{ status: 'PENDENTE' }, { status: 'VENCIDO' }],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Custas pagas no mês
|
||||||
|
const custasPagasMes = await prisma.custaProcessual.aggregate({
|
||||||
|
_sum: { valor: true },
|
||||||
|
where: {
|
||||||
|
status: 'PAGO',
|
||||||
|
dataPagamento: {
|
||||||
|
gte: dataInicio,
|
||||||
|
lt: dataFim,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Detalhes das custas pagas no mês
|
||||||
|
const detalhesCustas = await prisma.custaProcessual.findMany({
|
||||||
|
where: {
|
||||||
|
status: 'PAGO',
|
||||||
|
dataPagamento: {
|
||||||
|
gte: dataInicio,
|
||||||
|
lt: dataFim,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
orderBy: { dataPagamento: 'desc' },
|
||||||
|
take: 10,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
honorariosAReceber: honorariosAReceber._sum.valor || 0,
|
||||||
|
honorariosRecebidosMes: honorariosRecebidosMes._sum.valorPago || 0,
|
||||||
|
custasAPagar: custasAPagar._sum.valor || 0,
|
||||||
|
custasPagasMes: custasPagasMes._sum.valor || 0,
|
||||||
|
detalhesHonorarios,
|
||||||
|
detalhesCustas,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro no financeiroPainel:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao buscar dados financeiros.' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import { Router } from 'express';
|
||||||
|
import { NavegacaoService } from '../services/NavegacaoService';
|
||||||
|
import { authMiddleware } from '../../middleware/auth';
|
||||||
|
import { prisma } from '../prismaClient';
|
||||||
|
|
||||||
|
const router = Router();
|
||||||
|
|
||||||
|
// Aplicar middleware de autenticação
|
||||||
|
router.use(authMiddleware);
|
||||||
|
|
||||||
|
// Iniciar nova sessão de navegação
|
||||||
|
router.post('/iniciar', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { titulo, descricao } = req.body;
|
||||||
|
|
||||||
|
if (!req.user?.id) {
|
||||||
|
return res.status(401).json({ error: 'Usuário não autenticado' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const navegacaoService = new NavegacaoService();
|
||||||
|
const resultado = await navegacaoService.iniciarSessao(
|
||||||
|
req.user.id,
|
||||||
|
titulo,
|
||||||
|
descricao
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json(resultado);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao iniciar navegação:', error);
|
||||||
|
res.status(500).json({
|
||||||
|
error: 'Erro ao iniciar sessão de navegação',
|
||||||
|
details: error.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Navegar para URL específica
|
||||||
|
router.post('/:sessaoId/navegar', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { sessaoId } = req.params;
|
||||||
|
const { url } = req.body;
|
||||||
|
|
||||||
|
// Verificar se a sessão pertence ao usuário
|
||||||
|
const sessao = await prisma.sessaoNavegacao.findFirst({
|
||||||
|
where: {
|
||||||
|
id: sessaoId,
|
||||||
|
usuarioId: req.user!.id
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sessao) {
|
||||||
|
return res.status(404).json({ error: 'Sessão não encontrada' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const navegacaoService = new NavegacaoService();
|
||||||
|
await navegacaoService.navegarPara(url);
|
||||||
|
|
||||||
|
res.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro na navegação:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao navegar' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Finalizar sessão
|
||||||
|
router.post('/:sessaoId/finalizar', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { sessaoId } = req.params;
|
||||||
|
|
||||||
|
const sessao = await prisma.sessaoNavegacao.findFirst({
|
||||||
|
where: {
|
||||||
|
id: sessaoId,
|
||||||
|
usuarioId: req.user!.id
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sessao) {
|
||||||
|
return res.status(404).json({ error: 'Sessão não encontrada' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const navegacaoService = new NavegacaoService();
|
||||||
|
await navegacaoService.finalizarSessao();
|
||||||
|
|
||||||
|
res.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao finalizar sessão:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao finalizar sessão' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Listar sessões do usuário
|
||||||
|
router.get('/sessoes', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const sessoes = await prisma.sessaoNavegacao.findMany({
|
||||||
|
where: { usuarioId: req.user!.id },
|
||||||
|
include: {
|
||||||
|
acoes: {
|
||||||
|
select: { id: true, timestamp: true, tipo: true }
|
||||||
|
},
|
||||||
|
capturas: {
|
||||||
|
select: { id: true, timestamp: true, url: true }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
orderBy: { criadoEm: 'desc' }
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json(sessoes);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao listar sessões:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao listar sessões' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Detalhes de uma sessão
|
||||||
|
router.get('/sessoes/:sessaoId', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { sessaoId } = req.params;
|
||||||
|
|
||||||
|
const sessao = await prisma.sessaoNavegacao.findFirst({
|
||||||
|
where: {
|
||||||
|
id: sessaoId,
|
||||||
|
usuarioId: req.user!.id
|
||||||
|
},
|
||||||
|
include: {
|
||||||
|
acoes: {
|
||||||
|
orderBy: { timestamp: 'asc' }
|
||||||
|
},
|
||||||
|
capturas: {
|
||||||
|
orderBy: { timestamp: 'asc' }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sessao) {
|
||||||
|
return res.status(404).json({ error: 'Sessão não encontrada' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(sessao);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao buscar sessão:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao buscar detalhes da sessão' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Download do relatório
|
||||||
|
router.get('/sessoes/:sessaoId/relatorio', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { sessaoId } = req.params;
|
||||||
|
|
||||||
|
const sessao = await prisma.sessaoNavegacao.findFirst({
|
||||||
|
where: {
|
||||||
|
id: sessaoId,
|
||||||
|
usuarioId: req.user!.id
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!sessao || !sessao.relatorioPdfPath) {
|
||||||
|
return res.status(404).json({ error: 'Relatório não encontrado' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.download(sessao.relatorioPdfPath);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao baixar relatório:', error);
|
||||||
|
res.status(500).json({ error: 'Erro ao baixar relatório' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
||||||
@@ -55,7 +55,7 @@ router.post('/', async (req, res) => {
|
|||||||
router.get('/:id', async (req, res) => {
|
router.get('/:id', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { id } = req.params;
|
const { id } = req.params;
|
||||||
|
console.log('[pensaoAlimenticia] Buscando cálculo por ID:', id); // Log para depuração
|
||||||
const calculo = await prisma.calculoPensaoAlimenticia.findUnique({
|
const calculo = await prisma.calculoPensaoAlimenticia.findUnique({
|
||||||
where: { id },
|
where: { id },
|
||||||
include: {
|
include: {
|
||||||
@@ -70,15 +70,14 @@ router.get('/:id', async (req, res) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!calculo) {
|
if (!calculo) {
|
||||||
|
console.warn('[pensaoAlimenticia] Cálculo não encontrado para ID:', id); // Log para depuração
|
||||||
return res.status(404).json({ error: 'Cálculo não encontrado' });
|
return res.status(404).json({ error: 'Cálculo não encontrado' });
|
||||||
}
|
}
|
||||||
|
|
||||||
res.json(calculo);
|
res.json(calculo);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao buscar cálculo:', error);
|
console.error('[pensaoAlimenticia] Erro ao buscar cálculo:', error);
|
||||||
res.status(500).json({ error: 'Falha ao buscar cálculo' });
|
res.status(500).json({ error: 'Falha ao buscar cálculo', details: error.message });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,634 +0,0 @@
|
|||||||
import puppeteer from 'puppeteer';
|
|
||||||
import { prisma } from '../prismaClient';
|
|
||||||
import { PDFDocument, rgb, StandardFonts } from 'pdf-lib';
|
|
||||||
import fs from 'fs/promises';
|
|
||||||
import path from 'path';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Serviço para geração e manipulação de arquivos PDF
|
|
||||||
*/
|
|
||||||
export class PdfService {
|
|
||||||
/**
|
|
||||||
* Cria um documento PDF básico
|
|
||||||
* @returns Documento PDF
|
|
||||||
*/
|
|
||||||
async criarDocumento() {
|
|
||||||
return await PDFDocument.create();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Carrega um documento PDF existente
|
|
||||||
* @param pdfBytes - Bytes do PDF
|
|
||||||
* @returns Documento PDF
|
|
||||||
*/
|
|
||||||
async carregarDocumento(pdfBytes: Uint8Array) {
|
|
||||||
return await PDFDocument.load(pdfBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Adiciona uma página ao documento
|
|
||||||
* @param doc - Documento PDF
|
|
||||||
* @param tamanho - Tamanho da página (padrão: A4)
|
|
||||||
* @returns Página adicionada
|
|
||||||
*/
|
|
||||||
adicionarPagina(doc: any, tamanho = [595.28, 841.89]) {
|
|
||||||
return doc.addPage(tamanho);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Salva o documento como buffer
|
|
||||||
* @param doc - Documento PDF
|
|
||||||
* @returns Buffer do PDF
|
|
||||||
*/
|
|
||||||
async salvarComoBuffer(doc: any): Promise<Buffer> {
|
|
||||||
const pdfBytes = await doc.save();
|
|
||||||
return Buffer.from(pdfBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Carrega uma fonte padrão
|
|
||||||
* @param doc - Documento PDF
|
|
||||||
* @param fonte - Nome da fonte padrão
|
|
||||||
* @returns Fonte carregada
|
|
||||||
*/
|
|
||||||
async carregarFonte(doc: any, fonte: StandardFonts) {
|
|
||||||
return await doc.embedFont(fonte);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Desenha texto em uma página
|
|
||||||
* @param pagina - Página do PDF
|
|
||||||
* @param texto - Texto a ser desenhado
|
|
||||||
* @param x - Posição X
|
|
||||||
* @param y - Posição Y
|
|
||||||
* @param fonte - Fonte a ser usada
|
|
||||||
* @param tamanho - Tamanho da fonte
|
|
||||||
* @param cor - Cor do texto (padrão: preto)
|
|
||||||
*/
|
|
||||||
desenharTexto(
|
|
||||||
pagina: any,
|
|
||||||
texto: string,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
fonte: any,
|
|
||||||
tamanho: number,
|
|
||||||
cor = rgb(0, 0, 0)
|
|
||||||
) {
|
|
||||||
pagina.drawText(texto, {
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
font: fonte,
|
|
||||||
size: tamanho,
|
|
||||||
color: cor,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria um cabeçalho para o documento
|
|
||||||
* @param pagina - Página do PDF
|
|
||||||
* @param titulo - Título do cabeçalho
|
|
||||||
* @param fonte - Fonte a ser usada
|
|
||||||
* @param margemSuperior - Margem superior
|
|
||||||
* @param margem - Margem lateral
|
|
||||||
* @returns Posição Y após o cabeçalho
|
|
||||||
*/
|
|
||||||
criarCabecalho(
|
|
||||||
pagina: any,
|
|
||||||
titulo: string,
|
|
||||||
fonte: any,
|
|
||||||
margemSuperior: number,
|
|
||||||
margem: number
|
|
||||||
): number {
|
|
||||||
const yPos = pagina.getHeight() - margemSuperior;
|
|
||||||
|
|
||||||
this.desenharTexto(
|
|
||||||
pagina,
|
|
||||||
titulo,
|
|
||||||
margem,
|
|
||||||
yPos,
|
|
||||||
fonte,
|
|
||||||
18,
|
|
||||||
rgb(0, 0, 0.7)
|
|
||||||
);
|
|
||||||
|
|
||||||
// Linha separadora
|
|
||||||
pagina.drawLine({
|
|
||||||
start: { x: margem, y: yPos - 10 },
|
|
||||||
end: { x: pagina.getWidth() - margem, y: yPos - 10 },
|
|
||||||
thickness: 1,
|
|
||||||
color: rgb(0, 0, 0.5),
|
|
||||||
});
|
|
||||||
|
|
||||||
return yPos - 30; // Retorna a posição Y após o cabeçalho
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Cria um rodapé para o documento
|
|
||||||
* @param pagina - Página do PDF
|
|
||||||
* @param texto - Texto do rodapé
|
|
||||||
* @param fonte - Fonte a ser usada
|
|
||||||
* @param margem - Margem
|
|
||||||
*/
|
|
||||||
criarRodape(pagina: any, texto: string, fonte: any, margem: number) {
|
|
||||||
const yPos = margem / 2;
|
|
||||||
|
|
||||||
this.desenharTexto(
|
|
||||||
pagina,
|
|
||||||
texto,
|
|
||||||
margem,
|
|
||||||
yPos,
|
|
||||||
fonte,
|
|
||||||
8,
|
|
||||||
rgb(0.5, 0.5, 0.5)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getConfiguracao() {
|
|
||||||
try {
|
|
||||||
// Buscar configuração ou usar valores padrão
|
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
|
||||||
orderBy: { criadoEm: 'desc' },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
timbradoUrl: true,
|
|
||||||
timbradoMarginTop: true,
|
|
||||||
timbradoMarginBottom: true,
|
|
||||||
timbradoMarginLeft: true,
|
|
||||||
timbradoMarginRight: true,
|
|
||||||
templatePadrao: true,
|
|
||||||
margensTemplate: true,
|
|
||||||
criadoEm: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
console.log('Configuração encontrada:', config); // Debug
|
|
||||||
|
|
||||||
// Retornar configuração padrão se não existir
|
|
||||||
return {
|
|
||||||
// Valores padrão
|
|
||||||
cabecalhoHtml: `
|
|
||||||
<div style="text-align: center; padding: 20px;">
|
|
||||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
rodapeHtml: `
|
|
||||||
<div style="text-align: center; font-size: 10pt;">
|
|
||||||
{{escritorio.endereco}}<br>
|
|
||||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
// Campos que existem no modelo
|
|
||||||
timbradoUrl: config?.timbradoUrl || '',
|
|
||||||
timbradoMarginTop: config?.timbradoMarginTop || 100,
|
|
||||||
timbradoMarginBottom: config?.timbradoMarginBottom || 50,
|
|
||||||
timbradoMarginLeft: config?.timbradoMarginLeft || 50,
|
|
||||||
timbradoMarginRight: config?.timbradoMarginRight || 50,
|
|
||||||
templatePadrao: config?.templatePadrao || null,
|
|
||||||
margensTemplate: config?.margensTemplate || null
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao buscar configuração:', error);
|
|
||||||
// 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
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gera um PDF a partir do conteúdo HTML simples (apenas texto) e dados do escritório,
|
|
||||||
* encaixando o texto sobre o timbrado (PDF de fundo) em todas as páginas.
|
|
||||||
* Não usa Puppeteer, apenas PDF-LIB.
|
|
||||||
*/
|
|
||||||
async gerarPDF(conteudo: string, escritorio: any = {}): Promise<Buffer> {
|
|
||||||
try {
|
|
||||||
console.log('Buscando configurações do documento...');
|
|
||||||
const config = await this.getConfiguracao();
|
|
||||||
|
|
||||||
// Verificar se temos um timbrado para usar
|
|
||||||
const temTimbrado = !!config.timbradoUrl;
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
await fs.access(timbradoPath);
|
|
||||||
timbradoExists = true;
|
|
||||||
} catch (e) {
|
|
||||||
timbradoExists = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Margens
|
|
||||||
const margens = config.margensTemplate || {
|
|
||||||
top: config.timbradoMarginTop || 100,
|
|
||||||
left: config.timbradoMarginLeft || 50,
|
|
||||||
right: config.timbradoMarginRight || 50,
|
|
||||||
bottom: config.timbradoMarginBottom || 50
|
|
||||||
};
|
|
||||||
|
|
||||||
// Parâmetros de página
|
|
||||||
const PAGE_WIDTH = 595.28; // A4
|
|
||||||
const PAGE_HEIGHT = 841.89; // A4
|
|
||||||
const FONT_SIZE = 12;
|
|
||||||
const LINE_HEIGHT = FONT_SIZE * 1.5;
|
|
||||||
const MAX_WIDTH = PAGE_WIDTH - margens.left - margens.right;
|
|
||||||
|
|
||||||
// Crie o PDFDocument ANTES de tentar usar pdfDoc para embedFont!
|
|
||||||
let pdfDoc: PDFDocument = await PDFDocument.create();
|
|
||||||
|
|
||||||
// Fonte padrão do pdf-lib: TimesRoman, TimesBold, TimesItalic
|
|
||||||
const font = await pdfDoc.embedFont('Times-Roman');
|
|
||||||
const fontBold = await pdfDoc.embedFont('Times-Bold');
|
|
||||||
const fontItalic = await pdfDoc.embedFont('Times-Italic');
|
|
||||||
const fontBoldItalic = fontBold;
|
|
||||||
|
|
||||||
// Função para decodificar entidades HTML comuns (acentuação, símbolos, º, etc)
|
|
||||||
function decodeHtmlEntities(str: string): string {
|
|
||||||
if (!str) return '';
|
|
||||||
return str
|
|
||||||
// Acentos minúsculos e maiúsculos
|
|
||||||
.replace(/Á/g, 'Á').replace(/á/g, 'á')
|
|
||||||
.replace(/É/g, 'É').replace(/é/g, 'é')
|
|
||||||
.replace(/Í/g, 'Í').replace(/í/g, 'í')
|
|
||||||
.replace(/Ó/g, 'Ó').replace(/ó/g, 'ó')
|
|
||||||
.replace(/Ú/g, 'Ú').replace(/ú/g, 'ú')
|
|
||||||
.replace(/À/g, 'À').replace(/à/g, 'à')
|
|
||||||
.replace(/È/g, 'È').replace(/è/g, 'è')
|
|
||||||
.replace(/Ì/g, 'Ì').replace(/ì/g, 'ì')
|
|
||||||
.replace(/Ò/g, 'Ò').replace(/ò/g, 'ò')
|
|
||||||
.replace(/Ù/g, 'Ù').replace(/ù/g, 'ù')
|
|
||||||
.replace(/Â/g, 'Â').replace(/â/g, 'â')
|
|
||||||
.replace(/Ê/g, 'Ê').replace(/ê/g, 'ê')
|
|
||||||
.replace(/Î/g, 'Î').replace(/î/g, 'î')
|
|
||||||
.replace(/Ô/g, 'Ô').replace(/ô/g, 'ô')
|
|
||||||
.replace(/Û/g, 'Û').replace(/û/g, 'û')
|
|
||||||
.replace(/Ã/g, 'Ã').replace(/ã/g, 'ã')
|
|
||||||
.replace(/Õ/g, 'Õ').replace(/õ/g, 'õ')
|
|
||||||
.replace(/Ç/g, 'Ç').replace(/ç/g, 'ç')
|
|
||||||
.replace(/Ñ/g, 'Ñ').replace(/ñ/g, 'ñ')
|
|
||||||
.replace(/Ü/g, 'Ü').replace(/ü/g, 'ü')
|
|
||||||
// Símbolos comuns
|
|
||||||
.replace(/º/gi, 'º')
|
|
||||||
.replace(/ª/gi, 'ª')
|
|
||||||
.replace(/§/gi, '§')
|
|
||||||
.replace(/°/gi, '°')
|
|
||||||
.replace(/©/gi, '©')
|
|
||||||
.replace(/®/gi, '®')
|
|
||||||
.replace(/¶/gi, '¶')
|
|
||||||
.replace(/•/gi, '•')
|
|
||||||
.replace(/–/gi, '–')
|
|
||||||
.replace(/—/gi, '—')
|
|
||||||
.replace(/«/gi, '«')
|
|
||||||
.replace(/»/gi, '»')
|
|
||||||
.replace(/‘/gi, '‘')
|
|
||||||
.replace(/’/gi, '’')
|
|
||||||
.replace(/“/gi, '“')
|
|
||||||
.replace(/”/gi, '”')
|
|
||||||
.replace(/€/gi, '€')
|
|
||||||
.replace(/¥/gi, '¥')
|
|
||||||
.replace(/£/gi, '£')
|
|
||||||
.replace(/¢/gi, '¢')
|
|
||||||
.replace(/ /gi, ' ')
|
|
||||||
.replace(/&/gi, '&')
|
|
||||||
.replace(/"/gi, '"')
|
|
||||||
.replace(/'/g, "'")
|
|
||||||
.replace(/</gi, '<')
|
|
||||||
.replace(/>/gi, '>')
|
|
||||||
// Numéricos
|
|
||||||
.replace(/&#(\d+);/g, (m, code) => String.fromCharCode(code));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Função para remover todas as tags HTML, exceto as de formatação suportadas
|
|
||||||
function stripUnsupportedTags(html: string): string {
|
|
||||||
// Remove todas as tags, exceto <b>, <strong>, <i>, <em>, <u>, <br>, <p>, <span style="text-indent:2em;">, <span style="text-align:center;">
|
|
||||||
// Remove atributos de <span> exceto text-indent e text-align
|
|
||||||
return html
|
|
||||||
// Mantém apenas <span> com text-indent ou text-align:center
|
|
||||||
.replace(/<span\b(?:(?!text-indent|text-align)[^>])*?>/gi, '')
|
|
||||||
// Remove atributos de <b>, <strong>, <i>, <em>, <u>, <p>
|
|
||||||
.replace(/<(b|strong|i|em|u|p)[^>]*>/gi, '<$1>')
|
|
||||||
// Remove todas as outras tags e atributos
|
|
||||||
.replace(/<(?!\/?(b|strong|i|em|u|br|p|span)[ >])[^>]+>/gi, '')
|
|
||||||
// Remove spans sem text-indent ou text-align
|
|
||||||
.replace(/<span>(.*?)<\/span>/gi, '$1')
|
|
||||||
// Remove comentários HTML
|
|
||||||
.replace(/<!--[\s\S]*?-->/g, '');
|
|
||||||
}
|
|
||||||
|
|
||||||
// Função para renderizar texto com formatação inline (negrito, itálico, sublinhado) e controle de quebra de linha e recuo
|
|
||||||
function renderInlineFormattedParagraph(
|
|
||||||
page,
|
|
||||||
text: string,
|
|
||||||
x: number,
|
|
||||||
y: number,
|
|
||||||
font,
|
|
||||||
fontBold,
|
|
||||||
fontItalic,
|
|
||||||
fontBoldItalic,
|
|
||||||
fontSize: number,
|
|
||||||
color,
|
|
||||||
align: string,
|
|
||||||
maxWidth: number,
|
|
||||||
indent: boolean,
|
|
||||||
topMargin: number,
|
|
||||||
bottomMargin: number,
|
|
||||||
pageHeight: number
|
|
||||||
) {
|
|
||||||
let regex = /(<\/?(b|strong|i|em|u)>)/gi;
|
|
||||||
let tokens: { text: string, bold: boolean, italic: boolean, underline: boolean }[] = [];
|
|
||||||
let lastIndex = 0;
|
|
||||||
let match;
|
|
||||||
let currentStyle = { bold: false, italic: false, underline: false };
|
|
||||||
while ((match = regex.exec(text)) !== null) {
|
|
||||||
if (match.index > lastIndex) {
|
|
||||||
tokens.push({
|
|
||||||
text: text.substring(lastIndex, match.index),
|
|
||||||
bold: currentStyle.bold,
|
|
||||||
italic: currentStyle.italic,
|
|
||||||
underline: currentStyle.underline
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (/^<(b|strong)>$/i.test(match[0])) currentStyle.bold = true;
|
|
||||||
if (/^<\/(b|strong)>$/i.test(match[0])) currentStyle.bold = false;
|
|
||||||
if (/^<(i|em)>$/i.test(match[0])) currentStyle.italic = true;
|
|
||||||
if (/^<\/(i|em)>$/i.test(match[0])) currentStyle.italic = false;
|
|
||||||
if (/^<u>$/i.test(match[0])) currentStyle.underline = true;
|
|
||||||
if (/^<\/u>$/i.test(match[0])) currentStyle.underline = false;
|
|
||||||
lastIndex = regex.lastIndex;
|
|
||||||
}
|
|
||||||
if (lastIndex < text.length) {
|
|
||||||
tokens.push({
|
|
||||||
text: text.substring(lastIndex),
|
|
||||||
bold: currentStyle.bold,
|
|
||||||
italic: currentStyle.italic,
|
|
||||||
underline: currentStyle.underline
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let words: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
|
|
||||||
for (const token of tokens) {
|
|
||||||
let usedFont = font;
|
|
||||||
if (token.bold && token.italic) usedFont = fontBoldItalic;
|
|
||||||
else if (token.bold) usedFont = fontBold;
|
|
||||||
else if (token.italic) usedFont = fontItalic;
|
|
||||||
// Corrige: split por espaço, mas preserva espaços como tokens separados
|
|
||||||
const split = token.text.split(/(\s+)/);
|
|
||||||
for (const part of split) {
|
|
||||||
words.push({ text: part, font: usedFont, underline: token.underline, bold: token.bold, italic: token.italic });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let lines: { tokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] }[] = [];
|
|
||||||
let currentTokens: { text: string, font: any, underline: boolean, bold: boolean, italic: boolean }[] = [];
|
|
||||||
let currentWidth = 0;
|
|
||||||
|
|
||||||
for (const [i, word] of words.entries()) {
|
|
||||||
const wordWidth = word.font.widthOfTextAtSize(word.text, fontSize);
|
|
||||||
if (currentWidth + wordWidth > maxWidth && currentTokens.length > 0) {
|
|
||||||
lines.push({ tokens: currentTokens });
|
|
||||||
currentTokens = [word];
|
|
||||||
currentWidth = wordWidth;
|
|
||||||
} else {
|
|
||||||
currentTokens.push(word);
|
|
||||||
currentWidth += wordWidth;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (currentTokens.length > 0) {
|
|
||||||
lines.push({ tokens: currentTokens });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ajuste: Força alinhamento consistente para todas as linhas do parágrafo
|
|
||||||
// Se align === 'center', todas as linhas centralizadas
|
|
||||||
// Se align === 'justify', todas as linhas justificadas (exceto a última ou linhas curtas)
|
|
||||||
// Se align === 'left' ou outro, todas à esquerda
|
|
||||||
|
|
||||||
for (let i = 0; i < lines.length; i++) {
|
|
||||||
if (y < bottomMargin + fontSize * 1.5) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
let line = lines[i];
|
|
||||||
let drawX = x;
|
|
||||||
|
|
||||||
// Remove espaços no início e fim da linha para não justificar esses espaços
|
|
||||||
let trimmedTokens = [...line.tokens];
|
|
||||||
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[0].text)) trimmedTokens.shift();
|
|
||||||
while (trimmedTokens.length && /^\s+$/.test(trimmedTokens[trimmedTokens.length - 1].text)) trimmedTokens.pop();
|
|
||||||
|
|
||||||
let totalWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
|
|
||||||
|
|
||||||
// Corrige centralização: centraliza a linha inteira, inclusive se for a única linha do parágrafo
|
|
||||||
if (align === 'center') {
|
|
||||||
drawX = x + (maxWidth - totalWidth) / 2;
|
|
||||||
for (const t of trimmedTokens) {
|
|
||||||
page.drawText(t.text, {
|
|
||||||
x: drawX,
|
|
||||||
y,
|
|
||||||
size: fontSize,
|
|
||||||
font: t.font,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
if (t.underline && t.text.trim() !== '') {
|
|
||||||
const underlineY = y - 1.5;
|
|
||||||
page.drawLine({
|
|
||||||
start: { x: drawX, y: underlineY },
|
|
||||||
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
|
|
||||||
thickness: 0.75,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
}
|
|
||||||
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
|
|
||||||
}
|
|
||||||
} else if (align === 'justify' && i < lines.length - 1 && trimmedTokens.length > 2) {
|
|
||||||
// Justify: distribui espaço entre palavras, exceto na última linha ou linhas curtas
|
|
||||||
const spaces = trimmedTokens.filter(t => /^\s+$/.test(t.text));
|
|
||||||
const numSpaces = spaces.length;
|
|
||||||
const lineTextWidth = trimmedTokens.reduce((acc, t) => acc + t.font.widthOfTextAtSize(t.text, fontSize), 0);
|
|
||||||
const extraSpace = maxWidth - lineTextWidth;
|
|
||||||
let spaceWidth = 0;
|
|
||||||
// Só justifica se houver pelo menos 2 espaços e a linha não for muito curta
|
|
||||||
if (numSpaces > 0 && extraSpace > 0) {
|
|
||||||
spaceWidth = extraSpace / numSpaces;
|
|
||||||
}
|
|
||||||
let localDrawX = x;
|
|
||||||
for (const t of trimmedTokens) {
|
|
||||||
page.drawText(t.text, {
|
|
||||||
x: localDrawX,
|
|
||||||
y,
|
|
||||||
size: fontSize,
|
|
||||||
font: t.font,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
if (t.underline && t.text.trim() !== '') {
|
|
||||||
const underlineY = y - 1.5;
|
|
||||||
page.drawLine({
|
|
||||||
start: { x: localDrawX, y: underlineY },
|
|
||||||
end: { x: localDrawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
|
|
||||||
thickness: 0.75,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
}
|
|
||||||
if (/^\s+$/.test(t.text) && spaceWidth > 0) {
|
|
||||||
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize) + spaceWidth;
|
|
||||||
} else {
|
|
||||||
localDrawX += t.font.widthOfTextAtSize(t.text, fontSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// Alinhamento à esquerda (padrão) ou última linha de parágrafo justificado
|
|
||||||
for (const t of trimmedTokens) {
|
|
||||||
page.drawText(t.text, {
|
|
||||||
x: drawX,
|
|
||||||
y,
|
|
||||||
size: fontSize,
|
|
||||||
font: t.font,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
if (t.underline && t.text.trim() !== '') {
|
|
||||||
const underlineY = y - 1.5;
|
|
||||||
page.drawLine({
|
|
||||||
start: { x: drawX, y: underlineY },
|
|
||||||
end: { x: drawX + t.font.widthOfTextAtSize(t.text, fontSize), y: underlineY },
|
|
||||||
thickness: 0.75,
|
|
||||||
color
|
|
||||||
});
|
|
||||||
}
|
|
||||||
drawX += t.font.widthOfTextAtSize(t.text, fontSize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
y -= fontSize * 1.5;
|
|
||||||
}
|
|
||||||
return y;
|
|
||||||
}
|
|
||||||
|
|
||||||
const texto = decodeHtmlEntities(
|
|
||||||
stripUnsupportedTags(
|
|
||||||
this.processarTemplate(conteudo, escritorio)
|
|
||||||
.replace(/<br\s*\/?>/gi, '\n')
|
|
||||||
.replace(/<\/p>/gi, '\n\n')
|
|
||||||
.replace(/<p[^>]*>/gi, '')
|
|
||||||
.replace(/<span[^>]*text-indent[^>]*>/gi, '§§INDENT§§')
|
|
||||||
.replace(/<span[^>]*text-align\s*:\s*center[^>]*>/gi, '§§CENTER§§')
|
|
||||||
.replace(/<\/span>/gi, '')
|
|
||||||
.replace(/\r\n/g, '\n')
|
|
||||||
.replace(/\r/g, '\n')
|
|
||||||
.replace(/\n{3,}/g, '\n\n')
|
|
||||||
.trim()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
|
|
||||||
const paragrafos = texto.split(/\n{2,}/).map(p => p.trim()).filter(Boolean);
|
|
||||||
|
|
||||||
let timbradoPdf: PDFDocument | null = null;
|
|
||||||
let timbradoPageCount = 0;
|
|
||||||
let timbradoPages: any[] = [];
|
|
||||||
if (timbradoExists) {
|
|
||||||
const timbradoBytes = await fs.readFile(timbradoPath);
|
|
||||||
timbradoPdf = await PDFDocument.load(timbradoBytes);
|
|
||||||
timbradoPageCount = timbradoPdf.getPageCount();
|
|
||||||
timbradoPages = [];
|
|
||||||
for (let i = 0; i < timbradoPageCount; i++) {
|
|
||||||
const [embedded] = await pdfDoc.embedPages([timbradoPdf.getPage(i)]);
|
|
||||||
timbradoPages.push(embedded);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let currentPar = 0;
|
|
||||||
let pageIndex = 0;
|
|
||||||
while (currentPar < paragrafos.length) {
|
|
||||||
let page = pdfDoc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
|
|
||||||
if (timbradoPages.length > 0) {
|
|
||||||
const embedded = timbradoPages[pageIndex % timbradoPages.length];
|
|
||||||
page.drawPage(embedded, {
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
width: PAGE_WIDTH,
|
|
||||||
height: PAGE_HEIGHT
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let y = PAGE_HEIGHT - margens.top;
|
|
||||||
while (currentPar < paragrafos.length) {
|
|
||||||
let indent = paragrafos[currentPar].startsWith('§§INDENT§§');
|
|
||||||
let center = paragrafos[currentPar].startsWith('§§CENTER§§');
|
|
||||||
let align: 'center' | 'justify' | 'left' = center ? 'center' : 'justify';
|
|
||||||
let text = paragrafos[currentPar].replace(/^§§INDENT§§/, '').replace(/^§§CENTER§§/, '').trim();
|
|
||||||
|
|
||||||
// Se o parágrafo for centralizado, força alinhamento center e ignora recuo
|
|
||||||
if (center) {
|
|
||||||
indent = false;
|
|
||||||
align = 'center';
|
|
||||||
}
|
|
||||||
|
|
||||||
text = decodeHtmlEntities(text);
|
|
||||||
|
|
||||||
let x = margens.left;
|
|
||||||
let parWidth = MAX_WIDTH;
|
|
||||||
|
|
||||||
let yAfter = renderInlineFormattedParagraph(
|
|
||||||
page,
|
|
||||||
text,
|
|
||||||
x,
|
|
||||||
y,
|
|
||||||
font,
|
|
||||||
fontBold,
|
|
||||||
fontItalic,
|
|
||||||
fontBoldItalic,
|
|
||||||
FONT_SIZE,
|
|
||||||
rgb(0, 0, 0),
|
|
||||||
align,
|
|
||||||
parWidth,
|
|
||||||
indent,
|
|
||||||
margens.top,
|
|
||||||
margens.bottom,
|
|
||||||
PAGE_HEIGHT
|
|
||||||
);
|
|
||||||
if (yAfter === null) {
|
|
||||||
pageIndex++;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
y = yAfter - FONT_SIZE * 0.5;
|
|
||||||
currentPar++;
|
|
||||||
if (y < margens.bottom + FONT_SIZE * 1.5) break;
|
|
||||||
}
|
|
||||||
pageIndex++;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pdfBytes = await pdfDoc.save();
|
|
||||||
return Buffer.from(pdfBytes);
|
|
||||||
} 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;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,219 +0,0 @@
|
|||||||
import puppeteer from 'puppeteer';
|
|
||||||
import { PDFDocument } from 'pdf-lib';
|
|
||||||
import fs from 'fs/promises';
|
|
||||||
import path from 'path';
|
|
||||||
import { prisma } from '../prismaClient';
|
|
||||||
|
|
||||||
// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm)
|
|
||||||
function pxToMm(px: number | null | undefined): string {
|
|
||||||
if (!px) return '0mm';
|
|
||||||
return (px * 0.264583).toFixed(2) + 'mm';
|
|
||||||
}
|
|
||||||
|
|
||||||
export class PdfService {
|
|
||||||
// Busca configuração do documento, usando apenas campos válidos do schema
|
|
||||||
private async getConfiguracao() {
|
|
||||||
try {
|
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
|
||||||
orderBy: { criadoEm: 'desc' },
|
|
||||||
select: {
|
|
||||||
id: true,
|
|
||||||
timbradoUrl: true,
|
|
||||||
timbradoMarginTop: true,
|
|
||||||
timbradoMarginBottom: true,
|
|
||||||
timbradoMarginLeft: true,
|
|
||||||
timbradoMarginRight: true,
|
|
||||||
templatePadrao: true,
|
|
||||||
margensTemplate: true,
|
|
||||||
criadoEm: true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// Extrai recuo de primeira linha se existir em margensTemplate
|
|
||||||
let firstLineIndent = '0mm';
|
|
||||||
if (config?.margensTemplate) {
|
|
||||||
try {
|
|
||||||
const margens = typeof config.margensTemplate === 'string' ? JSON.parse(config.margensTemplate) : config.margensTemplate;
|
|
||||||
if (margens && margens.firstLineIndent) {
|
|
||||||
firstLineIndent = `${margens.firstLineIndent}mm`;
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
// Se der erro, ignora e usa padrão
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
timbradoUrl: config?.timbradoUrl || '',
|
|
||||||
timbradoMarginTop: config?.timbradoMarginTop ?? 100,
|
|
||||||
timbradoMarginBottom: config?.timbradoMarginBottom ?? 50,
|
|
||||||
timbradoMarginLeft: config?.timbradoMarginLeft ?? 50,
|
|
||||||
timbradoMarginRight: config?.timbradoMarginRight ?? 50,
|
|
||||||
templatePadrao: config?.templatePadrao || '',
|
|
||||||
firstLineIndent
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao buscar configuração:', error);
|
|
||||||
throw new Error('Falha ao buscar configuração');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gera HTML com timbrado e margens
|
|
||||||
private gerarHTML(content: string, config: any) {
|
|
||||||
// Limpa espaços, quebras de linha e tags vazias do final do conteúdo
|
|
||||||
let cleanContent = content
|
|
||||||
.replace(/(\s|<br\s*\/?>|<p>\s*<\/p>)+$/gi, '')
|
|
||||||
.replace(/(<p>\s*<\/p>)+/gi, '');
|
|
||||||
const timbradoUrl = config.timbradoUrl
|
|
||||||
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
|
||||||
: '';
|
|
||||||
// Adiciona log para debug
|
|
||||||
if (timbradoUrl) {
|
|
||||||
console.log('[PDF] Timbrado inserido no HTML:', 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-top: ${pxToMm(config.timbradoMarginTop)};
|
|
||||||
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
|
|
||||||
margin-left: ${pxToMm(config.timbradoMarginLeft)};
|
|
||||||
margin-right: ${pxToMm(config.timbradoMarginRight)};
|
|
||||||
size: A4;
|
|
||||||
}
|
|
||||||
html, body {
|
|
||||||
height: 100%;
|
|
||||||
margin: 0;
|
|
||||||
padding: 0;
|
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
|
||||||
font-size: 11pt;
|
|
||||||
line-height: 1.5;
|
|
||||||
background: none;
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
position: relative;
|
|
||||||
min-height: 100vh;
|
|
||||||
/* Remove background-image do body para evitar problemas no Puppeteer */
|
|
||||||
}
|
|
||||||
.timbrado-bg {
|
|
||||||
position: fixed;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100vw;
|
|
||||||
height: 100vh;
|
|
||||||
z-index: 0;
|
|
||||||
${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
|
|
||||||
pointer-events: none;
|
|
||||||
}
|
|
||||||
.content {
|
|
||||||
position: relative;
|
|
||||||
z-index: 1;
|
|
||||||
box-sizing: border-box;
|
|
||||||
width: 100%;
|
|
||||||
/* Removido padding-top e padding-bottom para evitar recuo duplo com as margens do PDF */
|
|
||||||
padding-left: ${pxToMm(config.timbradoMarginLeft)};
|
|
||||||
padding-right: ${pxToMm(config.timbradoMarginRight)};
|
|
||||||
overflow-wrap: break-word;
|
|
||||||
word-break: break-word;
|
|
||||||
/* Permite múltiplas páginas e evita corte de conteúdo */
|
|
||||||
break-inside: auto;
|
|
||||||
page-break-inside: auto;
|
|
||||||
}
|
|
||||||
.content p {
|
|
||||||
text-indent: ${config.firstLineIndent || '0mm'};
|
|
||||||
}
|
|
||||||
/* Corrige recuo exagerado apenas na primeira linha do primeiro parágrafo da primeira página */
|
|
||||||
.content p:first-child {
|
|
||||||
text-indent: 0mm !important;
|
|
||||||
}
|
|
||||||
/* Corrige recuo exagerado apenas na última linha do último parágrafo da última página */
|
|
||||||
.content p:last-child {
|
|
||||||
margin-bottom: 0 !important;
|
|
||||||
padding-bottom: 0 !important;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
|
|
||||||
<div class="content">
|
|
||||||
${cleanContent}
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
`;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
|
|
||||||
async gerarPDF(conteudo: string) {
|
|
||||||
try {
|
|
||||||
const config = await this.getConfiguracao();
|
|
||||||
// Usa templatePadrao se não houver conteúdo
|
|
||||||
const html = this.gerarHTML(conteudo || config.templatePadrao, config);
|
|
||||||
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
|
|
||||||
const page = await browser.newPage();
|
|
||||||
await page.setContent(html, {
|
|
||||||
waitUntil: ['networkidle0', 'load'],
|
|
||||||
timeout: 30000
|
|
||||||
});
|
|
||||||
const margin = {
|
|
||||||
top: pxToMm(config.timbradoMarginTop),
|
|
||||||
bottom: pxToMm(config.timbradoMarginBottom),
|
|
||||||
left: pxToMm(config.timbradoMarginLeft),
|
|
||||||
right: pxToMm(config.timbradoMarginRight)
|
|
||||||
};
|
|
||||||
const pdfBuffer = await page.pdf({
|
|
||||||
format: 'A4',
|
|
||||||
printBackground: true,
|
|
||||||
margin,
|
|
||||||
preferCSSPageSize: true
|
|
||||||
});
|
|
||||||
await browser.close();
|
|
||||||
|
|
||||||
// Se não houver timbrado, retorna direto
|
|
||||||
if (!config.timbradoUrl) {
|
|
||||||
return Buffer.from(pdfBuffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Caminho absoluto do PDF de timbrado
|
|
||||||
const timbradoPath = config.timbradoUrl.startsWith('/uploads')
|
|
||||||
? path.join(process.cwd(), 'public', config.timbradoUrl)
|
|
||||||
: path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
|
|
||||||
let timbradoBytes: Buffer;
|
|
||||||
try {
|
|
||||||
timbradoBytes = await fs.readFile(timbradoPath);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Timbrado não encontrado:', timbradoPath);
|
|
||||||
return Buffer.from(pdfBuffer);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mescla cada página do PDF gerado com o timbrado
|
|
||||||
const pdfDoc = await PDFDocument.load(pdfBuffer);
|
|
||||||
const timbradoDoc = await PDFDocument.load(timbradoBytes);
|
|
||||||
const timbradoPage = timbradoDoc.getPage(0);
|
|
||||||
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
|
|
||||||
const pageCount = pdfDoc.getPageCount();
|
|
||||||
for (let i = 0; i < pageCount; i++) {
|
|
||||||
const page = pdfDoc.getPage(i);
|
|
||||||
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
|
||||||
}
|
|
||||||
// Remove última página se estiver vazia (sem conteúdo visível)
|
|
||||||
if (pdfDoc.getPageCount() > 1) {
|
|
||||||
const lastPage = pdfDoc.getPage(pdfDoc.getPageCount() - 1);
|
|
||||||
const textContent = lastPage.getTextContent ? await lastPage.getTextContent() : null;
|
|
||||||
// pdf-lib não tem getTextContent, então alternativa: verifica se altura do conteúdo é mínima
|
|
||||||
if (lastPage.getHeight && lastPage.getWidth && lastPage.getHeight() > 0 && lastPage.getWidth() > 0) {
|
|
||||||
// Heurística: verifica se a página tem apenas o timbrado (sem outros objetos)
|
|
||||||
if (lastPage.node.Contents().size() === 0) {
|
|
||||||
pdfDoc.removePage(pdfDoc.getPageCount() - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const mergedPdf = await pdfDoc.save();
|
|
||||||
return Buffer.from(mergedPdf);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Erro ao gerar PDF:', error);
|
|
||||||
throw new Error('Falha ao gerar PDF');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,47 +1,53 @@
|
|||||||
import puppeteer from 'puppeteer';
|
import puppeteer from 'puppeteer';
|
||||||
|
import { PDFDocument } from 'pdf-lib';
|
||||||
|
import fs from 'fs/promises';
|
||||||
|
import path from 'path';
|
||||||
import { prisma } from '../prismaClient';
|
import { prisma } from '../prismaClient';
|
||||||
|
|
||||||
|
// Função utilitária para converter pixels em milímetros (1px ≈ 0.264583 mm)
|
||||||
|
function pxToMm(px: number | null | undefined): string {
|
||||||
|
if (!px) return '0mm';
|
||||||
|
return (px * 0.264583).toFixed(2) + 'mm';
|
||||||
|
}
|
||||||
|
|
||||||
export class PdfService {
|
export class PdfService {
|
||||||
|
// Busca configuração do documento, usando apenas campos válidos do schema
|
||||||
private async getConfiguracao() {
|
private async getConfiguracao() {
|
||||||
try {
|
try {
|
||||||
// Buscar configuração ou usar valores padrão
|
|
||||||
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,
|
||||||
|
templatePadrao: true,
|
||||||
|
margensTemplate: true,
|
||||||
criadoEm: true
|
criadoEm: true
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
// Extrai recuo de primeira linha se existir em margensTemplate
|
||||||
console.log('Configuração encontrada:', config); // Debug
|
let firstLineIndent = '0mm';
|
||||||
|
if (config?.margensTemplate) {
|
||||||
// Retornar configuração padrão se não existir
|
try {
|
||||||
|
const margens = typeof config.margensTemplate === 'string' ? JSON.parse(config.margensTemplate) : config.margensTemplate;
|
||||||
|
if (margens && margens.firstLineIndent) {
|
||||||
|
firstLineIndent = `${margens.firstLineIndent}mm`;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// Se der erro, ignora e usa padrão
|
||||||
|
}
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
cabecalhoHtml: config?.cabecalhoHtml || `
|
|
||||||
<div style="text-align: center; padding: 20px;">
|
|
||||||
<h2 style="margin:0;font-size:14pt">{{escritorio.nome}}</h2>
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
rodapeHtml: config?.rodapeHtml || `
|
|
||||||
<div style="text-align: center; font-size: 10pt;">
|
|
||||||
{{escritorio.endereco}}<br>
|
|
||||||
Tel: {{escritorio.telefone}} | Email: {{escritorio.email}}
|
|
||||||
</div>
|
|
||||||
`,
|
|
||||||
logoUrl: config?.logoUrl || '',
|
|
||||||
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 || '',
|
||||||
|
firstLineIndent
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao buscar configuração:', error);
|
console.error('Erro ao buscar configuração:', error);
|
||||||
@@ -49,13 +55,19 @@ export class PdfService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Gera HTML com timbrado e margens
|
||||||
private gerarHTML(content: string, config: any) {
|
private gerarHTML(content: string, config: any) {
|
||||||
const timbradoUrl = config.timbradoUrl
|
// Limpa espaços, quebras de linha e tags vazias do final do conteúdo
|
||||||
? `${process.env.BACKEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
let cleanContent = content
|
||||||
|
.replace(/(\s|<br\s*\/?>|<p>\s*<\/p>)+$/gi, '')
|
||||||
|
.replace(/(<p>\s*<\/p>)+/gi, '');
|
||||||
|
const timbradoUrl = config.timbradoUrl
|
||||||
|
? `${process.env.FRONTEND_URL || 'http://localhost:5000'}${config.timbradoUrl}`
|
||||||
: '';
|
: '';
|
||||||
|
// Adiciona log para debug
|
||||||
console.log('Gerando PDF com timbrado:', timbradoUrl);
|
if (timbradoUrl) {
|
||||||
|
console.log('[PDF] Timbrado inserido no HTML:', timbradoUrl);
|
||||||
|
}
|
||||||
return `
|
return `
|
||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
@@ -63,91 +75,162 @@ export class PdfService {
|
|||||||
<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">
|
<link href="https://fonts.googleapis.com/css2?family=Fira+Sans:wght@400;500;600&display=swap" rel="stylesheet">
|
||||||
<style>
|
<style>
|
||||||
@page {
|
@page {
|
||||||
margin: 0;
|
margin-top: ${pxToMm(config.timbradoMarginTop)};
|
||||||
|
margin-bottom: ${pxToMm(config.timbradoMarginBottom)};
|
||||||
|
margin-left: ${pxToMm(config.timbradoMarginLeft)};
|
||||||
|
margin-right: ${pxToMm(config.timbradoMarginRight)};
|
||||||
size: A4;
|
size: A4;
|
||||||
}
|
}
|
||||||
|
html, body {
|
||||||
body {
|
height: 100%;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
font-family: 'Fira Sans', Arial, sans-serif;
|
font-family: 'Fira Sans', Arial, sans-serif;
|
||||||
font-size: 11pt;
|
font-size: 11pt;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
|
background: none;
|
||||||
|
}
|
||||||
|
body {
|
||||||
position: relative;
|
position: relative;
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
|
/* Remove background-image do body para evitar problemas no Puppeteer */
|
||||||
}
|
}
|
||||||
|
.timbrado-bg {
|
||||||
.page {
|
position: fixed;
|
||||||
position: relative;
|
top: 0;
|
||||||
width: 21cm;
|
left: 0;
|
||||||
min-height: 29.7cm;
|
width: 100vw;
|
||||||
padding: ${config.timbradoMarginTop || 100}px ${config.timbradoMarginRight || 50}px ${config.timbradoMarginBottom || 50}px ${config.timbradoMarginLeft || 50}px;
|
height: 100vh;
|
||||||
background: ${timbradoUrl ? `url('${timbradoUrl}')` : 'none'};
|
z-index: 0;
|
||||||
background-size: cover;
|
${timbradoUrl ? `background-image: url('${timbradoUrl}'); background-size: cover; background-position: center; background-repeat: no-repeat;` : ''}
|
||||||
background-position: center;
|
pointer-events: none;
|
||||||
background-repeat: no-repeat;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.content {
|
.content {
|
||||||
position: relative;
|
position: relative;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
/* Removido padding-top e padding-bottom para evitar recuo duplo com as margens do PDF */
|
||||||
|
padding-left: ${pxToMm(config.timbradoMarginLeft)};
|
||||||
|
padding-right: ${pxToMm(config.timbradoMarginRight)};
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
word-break: break-word;
|
||||||
|
/* Permite múltiplas páginas e evita corte de conteúdo */
|
||||||
|
break-inside: auto;
|
||||||
|
page-break-inside: auto;
|
||||||
|
}
|
||||||
|
.content p {
|
||||||
|
text-indent: ${config.firstLineIndent || '0mm'};
|
||||||
|
}
|
||||||
|
/* Corrige recuo exagerado apenas na primeira linha do primeiro parágrafo da primeira página */
|
||||||
|
.content p:first-child {
|
||||||
|
text-indent: 0mm !important;
|
||||||
|
}
|
||||||
|
/* Corrige recuo exagerado apenas na última linha do último parágrafo da última página */
|
||||||
|
.content p:last-child {
|
||||||
|
margin-bottom: 0 !important;
|
||||||
|
padding-bottom: 0 !important;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="page">
|
${timbradoUrl ? '<div class="timbrado-bg"></div>' : ''}
|
||||||
<div class="content">
|
<div class="content">
|
||||||
${content}
|
${cleanContent}
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async gerarPDF(conteudo: string, escritorio: any) {
|
// Gera PDF a partir do HTML, depois sobrepõe o timbrado em cada página
|
||||||
|
async gerarPDF(conteudo: string) {
|
||||||
try {
|
try {
|
||||||
const config = await prisma.configuracaoDocumento.findFirst({
|
const config = await this.getConfiguracao();
|
||||||
orderBy: { criadoEm: 'desc' }
|
// Usa templatePadrao se não houver conteúdo
|
||||||
});
|
const html = this.gerarHTML(conteudo || config.templatePadrao, config);
|
||||||
|
const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox'] });
|
||||||
console.log('Configuração do PDF:', config);
|
|
||||||
|
|
||||||
const html = this.gerarHTML(conteudo, config);
|
|
||||||
|
|
||||||
const browser = await puppeteer.launch({
|
|
||||||
headless: 'new',
|
|
||||||
args: ['--no-sandbox']
|
|
||||||
});
|
|
||||||
|
|
||||||
const page = await browser.newPage();
|
const page = await browser.newPage();
|
||||||
|
await page.setContent(html, {
|
||||||
await page.setViewport({
|
|
||||||
width: 794, // A4 width in pixels (72 dpi)
|
|
||||||
height: 1123,
|
|
||||||
deviceScaleFactor: 2
|
|
||||||
});
|
|
||||||
|
|
||||||
await page.setContent(html, {
|
|
||||||
waitUntil: ['networkidle0', 'load'],
|
waitUntil: ['networkidle0', 'load'],
|
||||||
timeout: 30000
|
timeout: 30000
|
||||||
});
|
});
|
||||||
|
const margin = {
|
||||||
|
top: pxToMm(config.timbradoMarginTop),
|
||||||
|
bottom: pxToMm(config.timbradoMarginBottom),
|
||||||
|
left: pxToMm(config.timbradoMarginLeft),
|
||||||
|
right: pxToMm(config.timbradoMarginRight)
|
||||||
|
};
|
||||||
const pdfBuffer = await page.pdf({
|
const pdfBuffer = await page.pdf({
|
||||||
format: 'A4',
|
format: 'A4',
|
||||||
printBackground: true,
|
printBackground: true,
|
||||||
margin: { top: '0', right: '0', bottom: '0', left: '0' },
|
margin,
|
||||||
preferCSSPageSize: true
|
preferCSSPageSize: true
|
||||||
});
|
});
|
||||||
|
|
||||||
await browser.close();
|
await browser.close();
|
||||||
return Buffer.from(pdfBuffer);
|
|
||||||
|
|
||||||
|
// Se não houver timbrado, retorna direto
|
||||||
|
if (!config.timbradoUrl) {
|
||||||
|
return Buffer.from(pdfBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Caminho absoluto do PDF de timbrado
|
||||||
|
const timbradoPath = config.timbradoUrl.startsWith('/uploads')
|
||||||
|
? path.join(process.cwd(), 'public', config.timbradoUrl)
|
||||||
|
: path.join(process.cwd(), 'public', 'uploads', path.basename(config.timbradoUrl));
|
||||||
|
let timbradoBytes: Buffer;
|
||||||
|
try {
|
||||||
|
timbradoBytes = await fs.readFile(timbradoPath);
|
||||||
|
} catch (e) {
|
||||||
|
console.error('Timbrado não encontrado:', timbradoPath);
|
||||||
|
return Buffer.from(pdfBuffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mescla cada página do PDF gerado com o timbrado
|
||||||
|
const pdfDoc = await PDFDocument.load(pdfBuffer);
|
||||||
|
const timbradoDoc = await PDFDocument.load(timbradoBytes);
|
||||||
|
const timbradoPage = timbradoDoc.getPage(0);
|
||||||
|
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
|
||||||
|
const pageCount = pdfDoc.getPageCount();
|
||||||
|
for (let i = 0; i < pageCount; i++) {
|
||||||
|
const page = pdfDoc.getPage(i);
|
||||||
|
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
||||||
|
}
|
||||||
|
// Após mesclar o timbrado
|
||||||
|
const pageCountBefore = pdfDoc.getPageCount();
|
||||||
|
if (pageCountBefore > 1) {
|
||||||
|
// Heurística aprimorada: remove a última página apenas se estiver realmente vazia (sem texto, imagens ou gráficos)
|
||||||
|
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
||||||
|
let isBlank = true;
|
||||||
|
// Verifica se há texto
|
||||||
|
const annotations = lastPage.node.Annots;
|
||||||
|
if (annotations && annotations.length > 0) {
|
||||||
|
isBlank = false;
|
||||||
|
}
|
||||||
|
// Verifica se há objetos gráficos (imagens, paths, etc.)
|
||||||
|
if (isBlank && typeof lastPage.node?.Resources === 'function') {
|
||||||
|
const resourcesDict = lastPage.node.Resources();
|
||||||
|
if (resourcesDict && typeof resourcesDict === 'object') {
|
||||||
|
// Corrige: usa PDFName para acessar o XObject
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||||
|
const { PDFName } = require('pdf-lib');
|
||||||
|
const xObject = resourcesDict.get(PDFName.of('XObject'));
|
||||||
|
if (xObject && typeof xObject === 'object' && Object.keys(xObject).length > 0) {
|
||||||
|
isBlank = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Só remove se realmente não houver nada
|
||||||
|
if (isBlank) {
|
||||||
|
pdfDoc.removePage(pageCountBefore - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const mergedPdf = await pdfDoc.save();
|
||||||
|
return Buffer.from(mergedPdf);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Erro ao gerar PDF:', error);
|
console.error('Erro ao gerar PDF:', error);
|
||||||
throw new Error('Falha ao gerar PDF');
|
throw new Error('Falha ao gerar PDF');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,8 +187,32 @@ export class PdfService {
|
|||||||
return Buffer.from(pdfBuffer);
|
return Buffer.from(pdfBuffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Mescla cada página do PDF gerado com o timbrado
|
// Remove página vazia do final ANTES de mesclar o timbrado
|
||||||
const pdfDoc = await PDFDocument.load(pdfBuffer);
|
let pdfDoc = await PDFDocument.load(pdfBuffer);
|
||||||
|
let pageCountBefore = pdfDoc.getPageCount();
|
||||||
|
if (pageCountBefore > 1) {
|
||||||
|
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
||||||
|
const contentStreams = (lastPage as any).node.Contents?.();
|
||||||
|
let isBlank = false;
|
||||||
|
|
||||||
|
if (!contentStreams) {
|
||||||
|
isBlank = true;
|
||||||
|
} else if (Array.isArray(contentStreams)) {
|
||||||
|
isBlank = contentStreams.every(
|
||||||
|
(stream: any) =>
|
||||||
|
!stream.contents ||
|
||||||
|
(typeof stream.contents.length === 'number' && stream.contents.length < 5)
|
||||||
|
);
|
||||||
|
} else if (contentStreams.contents && typeof contentStreams.contents.length === 'number') {
|
||||||
|
isBlank = contentStreams.contents.length < 5;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isBlank) {
|
||||||
|
pdfDoc.removePage(pageCountBefore - 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Agora sim, mescle o timbrado nas páginas restantes
|
||||||
const timbradoDoc = await PDFDocument.load(timbradoBytes);
|
const timbradoDoc = await PDFDocument.load(timbradoBytes);
|
||||||
const timbradoPage = timbradoDoc.getPage(0);
|
const timbradoPage = timbradoDoc.getPage(0);
|
||||||
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
|
const [timbradoEmbed] = await pdfDoc.embedPages([timbradoPage]);
|
||||||
@@ -197,16 +221,7 @@ export class PdfService {
|
|||||||
const page = pdfDoc.getPage(i);
|
const page = pdfDoc.getPage(i);
|
||||||
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
page.drawPage(timbradoEmbed, { x: 0, y: 0, width: page.getWidth(), height: page.getHeight() });
|
||||||
}
|
}
|
||||||
// Após mesclar o timbrado
|
|
||||||
const pageCountBefore = pdfDoc.getPageCount();
|
|
||||||
if (pageCountBefore > 1) {
|
|
||||||
// Heurística: remove a última página se ela estiver completamente em branco (sem texto)
|
|
||||||
const lastPage = pdfDoc.getPage(pageCountBefore - 1);
|
|
||||||
const text = await lastPage.getTextContent?.();
|
|
||||||
if (!text || (Array.isArray(text.items) && text.items.length === 0)) {
|
|
||||||
pdfDoc.removePage(pageCountBefore - 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
const mergedPdf = await pdfDoc.save();
|
const mergedPdf = await pdfDoc.save();
|
||||||
return Buffer.from(mergedPdf);
|
return Buffer.from(mergedPdf);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import { prisma } from '../config/database';
|
||||||
|
import puppeteer from 'puppeteer-extra';
|
||||||
|
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
|
||||||
|
import { createHash } from 'crypto';
|
||||||
|
import * as path from 'path';
|
||||||
|
import * as fs from 'fs/promises';
|
||||||
|
import { Browser, Page } from 'puppeteer';
|
||||||
|
import * as OpenTimestamps from 'opentimestamps';
|
||||||
|
|
||||||
|
puppeteer.use(StealthPlugin());
|
||||||
|
|
||||||
|
export class NavegacaoService {
|
||||||
|
private browser: Browser | null = null;
|
||||||
|
private page: Page | null = null;
|
||||||
|
private sessaoId: string | null = null;
|
||||||
|
private recording: boolean = false;
|
||||||
|
private recordingInterval: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
async iniciarSessao(usuarioId: string, titulo: string, descricao?: string) {
|
||||||
|
try {
|
||||||
|
// Criar sessão no banco
|
||||||
|
const sessionKey = this.generateSessionKey();
|
||||||
|
|
||||||
|
const sessao = await prisma.sessaoNavegacao.create({
|
||||||
|
data: {
|
||||||
|
titulo,
|
||||||
|
descricao,
|
||||||
|
usuarioId,
|
||||||
|
sessionKey,
|
||||||
|
status: 'INICIADA',
|
||||||
|
browserFingerprint: await this.getBrowserFingerprint()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.sessaoId = sessao.id;
|
||||||
|
|
||||||
|
// Inicializar browser controlado
|
||||||
|
await this.setupBrowser();
|
||||||
|
|
||||||
|
return {
|
||||||
|
sessaoId: sessao.id,
|
||||||
|
sessionKey: sessao.sessionKey,
|
||||||
|
browserWsEndpoint: this.browser?.wsEndpoint()
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao iniciar sessão:', error);
|
||||||
|
throw new Error('Falha ao iniciar sessão de navegação');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async setupBrowser() {
|
||||||
|
this.browser = await puppeteer.launch({
|
||||||
|
headless: false,
|
||||||
|
devtools: true,
|
||||||
|
defaultViewport: null,
|
||||||
|
args: [
|
||||||
|
'--no-sandbox',
|
||||||
|
'--disable-setuid-sandbox',
|
||||||
|
'--enable-webrtc-logs',
|
||||||
|
'--use-fake-ui-for-media-stream',
|
||||||
|
'--autoplay-policy=no-user-gesture-required'
|
||||||
|
]
|
||||||
|
});
|
||||||
|
|
||||||
|
this.page = await this.browser.newPage();
|
||||||
|
|
||||||
|
// Configurar interceptadores
|
||||||
|
await this.setupPageInterceptors();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async setupPageInterceptors() {
|
||||||
|
if (!this.page) return;
|
||||||
|
|
||||||
|
// Interceptar requests de rede
|
||||||
|
await this.page.setRequestInterception(true);
|
||||||
|
|
||||||
|
this.page.on('request', async (request) => {
|
||||||
|
await this.registrarAcao('NAVEGACAO', {
|
||||||
|
url: request.url(),
|
||||||
|
method: request.method(),
|
||||||
|
headers: request.headers(),
|
||||||
|
postData: request.postData()
|
||||||
|
});
|
||||||
|
request.continue();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Interceptar cliques
|
||||||
|
await this.page.evaluateOnNewDocument(() => {
|
||||||
|
document.addEventListener('click', (event) => {
|
||||||
|
window.postMessage({
|
||||||
|
type: 'NAVEGACAO_ACTION',
|
||||||
|
action: 'CLIQUE',
|
||||||
|
data: {
|
||||||
|
x: event.clientX,
|
||||||
|
y: event.clientY,
|
||||||
|
target: event.target?.tagName,
|
||||||
|
targetId: event.target?.id,
|
||||||
|
targetClass: event.target?.className
|
||||||
|
}
|
||||||
|
}, '*');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Escutar mensagens do frontend
|
||||||
|
this.page.on('console', async (msg) => {
|
||||||
|
if (msg.text().includes('NAVEGACAO_ACTION')) {
|
||||||
|
const data = JSON.parse(msg.text().replace('NAVEGACAO_ACTION:', ''));
|
||||||
|
await this.registrarAcao(data.action, data.data);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async navegarPara(url: string) {
|
||||||
|
if (!this.page || !this.sessaoId) {
|
||||||
|
throw new Error('Sessão não iniciada');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.page.goto(url, { waitUntil: 'networkidle2' });
|
||||||
|
|
||||||
|
// Capturar estado atual
|
||||||
|
await this.capturarEstadoAtual();
|
||||||
|
|
||||||
|
// Atualizar status
|
||||||
|
await prisma.sessaoNavegacao.update({
|
||||||
|
where: { id: this.sessaoId },
|
||||||
|
data: { status: 'EM_ANDAMENTO' }
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro na navegação:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async capturarEstadoAtual() {
|
||||||
|
if (!this.page || !this.sessaoId) return;
|
||||||
|
|
||||||
|
const url = this.page.url();
|
||||||
|
const titulo = await this.page.title();
|
||||||
|
const timestamp = new Date();
|
||||||
|
|
||||||
|
// Screenshot
|
||||||
|
const screenshotBuffer = await this.page.screenshot({ fullPage: true });
|
||||||
|
const screenshotPath = await this.salvarArquivo(
|
||||||
|
screenshotBuffer,
|
||||||
|
`screenshot_${Date.now()}.png`
|
||||||
|
);
|
||||||
|
|
||||||
|
// HTML content
|
||||||
|
const htmlContent = await this.page.content();
|
||||||
|
const checksumHtml = createHash('sha256').update(htmlContent).digest('hex');
|
||||||
|
const checksumScreenshot = createHash('sha256').update(screenshotBuffer).digest('hex');
|
||||||
|
|
||||||
|
// Cookies e storage
|
||||||
|
const cookies = await this.page.cookies();
|
||||||
|
const localStorage = await this.page.evaluate(() =>
|
||||||
|
JSON.stringify(window.localStorage)
|
||||||
|
);
|
||||||
|
const sessionStorage = await this.page.evaluate(() =>
|
||||||
|
JSON.stringify(window.sessionStorage)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Salvar captura
|
||||||
|
await prisma.capturaNavegacao.create({
|
||||||
|
data: {
|
||||||
|
sessaoId: this.sessaoId,
|
||||||
|
timestamp,
|
||||||
|
url,
|
||||||
|
titulo,
|
||||||
|
screenshotPath,
|
||||||
|
htmlContent,
|
||||||
|
checksumHtml,
|
||||||
|
checksumScreenshot,
|
||||||
|
networkRequests: [], // Será preenchido pelos interceptadores
|
||||||
|
cookies,
|
||||||
|
localStorage: localStorage ? JSON.parse(localStorage) : null,
|
||||||
|
sessionStorage: sessionStorage ? JSON.parse(sessionStorage) : null
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async registrarAcao(tipo: string, dados: any) {
|
||||||
|
if (!this.sessaoId) return;
|
||||||
|
|
||||||
|
const screenshot = this.page ? await this.page.screenshot({ encoding: 'base64' }) : null;
|
||||||
|
|
||||||
|
await prisma.acaoNavegacao.create({
|
||||||
|
data: {
|
||||||
|
sessaoId: this.sessaoId,
|
||||||
|
timestamp: new Date(),
|
||||||
|
tipo: tipo as any,
|
||||||
|
url: this.page?.url(),
|
||||||
|
elemento: dados.target,
|
||||||
|
coordenadas: dados.x && dados.y ? { x: dados.x, y: dados.y } : null,
|
||||||
|
valor: dados.value,
|
||||||
|
screenshot: screenshot ? `data:image/png;base64,${screenshot}` : null,
|
||||||
|
metadados: dados
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async finalizarSessao() {
|
||||||
|
if (!this.sessaoId) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await prisma.sessaoNavegacao.update({
|
||||||
|
where: { id: this.sessaoId },
|
||||||
|
data: {
|
||||||
|
status: 'FINALIZANDO',
|
||||||
|
fimSessao: new Date()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Gerar relatório final
|
||||||
|
await this.gerarRelatorioFinal();
|
||||||
|
|
||||||
|
if (this.browser) {
|
||||||
|
await this.browser.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.sessaoNavegacao.update({
|
||||||
|
where: { id: this.sessaoId },
|
||||||
|
data: { status: 'CONCLUIDA' }
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Erro ao finalizar sessão:', error);
|
||||||
|
await prisma.sessaoNavegacao.update({
|
||||||
|
where: { id: this.sessaoId },
|
||||||
|
data: { status: 'ERRO' }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async gerarRelatorioFinal() {
|
||||||
|
// Implementar geração do relatório PDF com todas as evidências
|
||||||
|
// Compilar screenshots, metadados, timestamps, etc.
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSessionKey(): string {
|
||||||
|
return createHash('sha256')
|
||||||
|
.update(`${Date.now()}_${Math.random()}_${process.pid}`)
|
||||||
|
.digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getBrowserFingerprint() {
|
||||||
|
return {
|
||||||
|
userAgent: 'Controlled Browser',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
nodeVersion: process.version
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async salvarArquivo(buffer: Buffer, filename: string): Promise<string> {
|
||||||
|
const dir = path.join(process.cwd(), 'storage', 'navegacao', this.sessaoId!);
|
||||||
|
await fs.mkdir(dir, { recursive: true });
|
||||||
|
|
||||||
|
const filepath = path.join(dir, filename);
|
||||||
|
await fs.writeFile(filepath, buffer);
|
||||||
|
|
||||||
|
return filepath;
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user