first commit
This commit is contained in:
commit
c9fb67e751
423 files changed
+53287
No files matched your search
+149
@@ -0,0 +1,149 @@
|
||||
import React from "react";
|
||||
import {
|
||||
createBrowserRouter,
|
||||
RouterProvider,
|
||||
createRoutesFromElements,
|
||||
Route,
|
||||
Navigate
|
||||
} from "react-router-dom";
|
||||
import { LoginPage } from "./components/LoginPage";
|
||||
import { Dashboard } from "./components/Dashboard";
|
||||
import { MainLayout } from "./components/layouts/MainLayout";
|
||||
import { PrivateRoute } from "./components/PrivateRoute";
|
||||
import { AuthProvider } from "./contexts/AuthContext";
|
||||
import { ClientesPage } from "./components/clientes/ClientesPage";
|
||||
import { QueryClient, QueryClientProvider } from "react-query";
|
||||
import { ClienteDetalhes } from "./components/clientes/ClienteDetalhes";
|
||||
import { ProcessosPage } from "./components/processos/ProcessosPage";
|
||||
import { ProcessoDetalhes } from "./components/processos/ProcessoDetalhes";
|
||||
import { UsuariosPage } from "./components/usuarios/UsuariosPage";
|
||||
import { AdminRoute } from "./components/AdminRoute";
|
||||
import { PerfilPage } from "./components/perfil/PerfilPage";
|
||||
import { AtendimentosPage } from "./components/atendimentos/AtendimentosPage";
|
||||
import { AtendimentoDetalhes } from "./components/atendimentos/AtendimentoDetalhes";
|
||||
import { LocalizationProvider } from '@mui/x-date-pickers';
|
||||
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { ThemeProvider } from './contexts/ThemeContext';
|
||||
import { TarefasPage } from "./components/tarefas/TarefasPage";
|
||||
import { DocumentosPage } from './components/DocumentosPage';
|
||||
import { ToastContainer } from 'react-toastify';
|
||||
import 'react-toastify/dist/ReactToastify.css';
|
||||
import { GerenciarTemplates } from './components/documentos/GerenciarTemplates';
|
||||
import { ConfiguracaoDocumento } from './components/documentos/ConfiguracaoDocumento';
|
||||
import { ProcessoAdministrativoList } from './components/processosAdministrativos/ProcessoAdministrativoList';
|
||||
import { ProcessoAdminDetalhes } from './components/processosAdministrativos/ProcessoAdminDetalhes';
|
||||
import { ProtectedRoute } from './components/ProtectedRoute';
|
||||
import { ProvaUpload } from './components/provas/ProvaUpload';
|
||||
import { ProvaStatus } from './components/provas/ProvaStatus';
|
||||
import { AdminProvas } from './components/provas/AdminProvas';
|
||||
import { VerificarProva } from './components/provas/VerificarProva';
|
||||
import { ErrorBoundary } from './components/ErrorBoundary';
|
||||
import { PublicVerificarProva } from './components/provas/PublicVerificarProva';
|
||||
import { ClientProvaUpload } from './components/provas/ClientProvaUpload';
|
||||
import { PublicProvaStatus } from './components/provas/PublicProvaStatus';
|
||||
|
||||
// Importar os componentes de cálculos
|
||||
import { CalculosList } from './components/calculos/CalculosList';
|
||||
import { NovoCalculo } from './components/calculos/NovoCalculo';
|
||||
import { DetalhesCalculo } from './components/calculos/DetalhesCalculo';
|
||||
import { NovoPensaoAlimenticia } from './components/calculos/NovoPensaoAlimenticia';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const router = createBrowserRouter(
|
||||
createRoutesFromElements(
|
||||
<>
|
||||
<Route path="/" element={<Navigate to="/dashboard" />} errorElement={<ErrorBoundary />} />
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
|
||||
{/* Rotas públicas para validação digital */}
|
||||
<Route path="/public/verificar/:hash" element={<PublicVerificarProva />} errorElement={<ErrorBoundary />} />
|
||||
<Route path="/public/provas/upload" element={<ClientProvaUpload />} errorElement={<ErrorBoundary />} />
|
||||
<Route path="/public/provas/status/:id" element={<PublicProvaStatus />} errorElement={<ErrorBoundary />} />
|
||||
|
||||
<Route element={<PrivateRoute />}>
|
||||
<Route element={<MainLayout />}>
|
||||
<Route path="dashboard" element={<Dashboard />} />
|
||||
<Route path="documentos" element={<DocumentosPage />} />
|
||||
<Route path="documentos/templates" element={<GerenciarTemplates />} />
|
||||
<Route path="documentos/:id" element={<DocumentosPage />} />
|
||||
<Route path="documentos/configuracoes" element={<ConfiguracaoDocumento />} />
|
||||
<Route path="processos/:processoId/documentos" element={<DocumentosPage />} />
|
||||
<Route path="atendimentos/:atendimentoId/documentos" element={<DocumentosPage />} />
|
||||
<Route path="/processos" element={<ProcessosPage />} />
|
||||
<Route path="/processos/:id" element={<ProcessoDetalhes />} />
|
||||
<Route path="/clientes" element={<ClientesPage />} />
|
||||
<Route path="/clientes/:id" element={<ClienteDetalhes />} />
|
||||
<Route path="/perfil" element={<PerfilPage />} />
|
||||
<Route path="/atendimentos" element={<AtendimentosPage />} />
|
||||
<Route path="/atendimentos/:id" element={<AtendimentoDetalhes />} />
|
||||
<Route path="/tarefas" element={<TarefasPage />} />
|
||||
<Route path="/processos-administrativos" element={<ProtectedRoute roles={['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE']}><ProcessoAdministrativoList /></ProtectedRoute>} />
|
||||
<Route path="/processos-administrativos/:id" element={<ProtectedRoute roles={['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE']}><ProcessoAdminDetalhes /></ProtectedRoute>} />
|
||||
<Route path="/provas/upload" element={<ProvaUpload />} />
|
||||
<Route path="/provas/status/:id" element={<ProvaStatus />} />
|
||||
<Route path="/provas/admin" element={
|
||||
<ProtectedRoute roles={['ADVOGADO_ADMIN']}>
|
||||
<AdminProvas />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
<Route
|
||||
path="/provas/verificar/:hash"
|
||||
element={<VerificarProva />}
|
||||
errorElement={<ErrorBoundary />}
|
||||
/>
|
||||
{/* Rotas para Cálculos Judiciais */}
|
||||
<Route path="/calculos" element={
|
||||
<ProtectedRoute>
|
||||
<CalculosList />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/calculos/novo" element={
|
||||
<ProtectedRoute>
|
||||
<NovoCalculo />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/calculos/:id" element={
|
||||
<ProtectedRoute>
|
||||
<DetalhesCalculo />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Rotas para Pensão Alimentícia */}
|
||||
<Route path="/pensao-alimenticia/nova" element={
|
||||
<ProtectedRoute>
|
||||
<NovoPensaoAlimenticia />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/pensao-alimenticia/:id" element={
|
||||
<ProtectedRoute>
|
||||
<DetalhesCalculo />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
</Route>
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/login" />} />
|
||||
</>
|
||||
)
|
||||
);
|
||||
|
||||
export const App: React.FC = () => {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<LocalizationProvider dateAdapter={AdapterDateFns} adapterLocale={ptBR}>
|
||||
<AuthProvider>
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
<ToastContainer />
|
||||
</ThemeProvider>
|
||||
</AuthProvider>
|
||||
</LocalizationProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { Navigate, Outlet } from "react-router-dom";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
import { PerfilUsuario } from "../types/usuario";
|
||||
|
||||
export function AdminRoute() {
|
||||
const { user } = useAuth();
|
||||
|
||||
// Debug log
|
||||
console.log("AdminRoute - User:", user);
|
||||
console.log("AdminRoute - User perfil:", user?.perfil);
|
||||
console.log("AdminRoute - Expected perfil:", PerfilUsuario.ADVOGADO_ADMIN);
|
||||
console.log(
|
||||
"AdminRoute - Is admin?:",
|
||||
user?.perfil === PerfilUsuario.ADVOGADO_ADMIN,
|
||||
);
|
||||
|
||||
// Aguardar o usuário ser carregado
|
||||
if (!user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Verificar se o perfil é ADVOGADO_ADMIN
|
||||
if (user.perfil !== "ADVOGADO_ADMIN") {
|
||||
return <Navigate to="/dashboard" replace />;
|
||||
}
|
||||
|
||||
return <Outlet />;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import React from 'react';
|
||||
import { DashboardLayout } from './dashboard/DashboardLayout';
|
||||
|
||||
export const Dashboard: React.FC = () => {
|
||||
return <DashboardLayout />;
|
||||
};
|
||||
@@ -0,0 +1,364 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||
import { DocumentIcon, PlusIcon, TrashIcon, EyeIcon, XMarkIcon, DocumentArrowDownIcon } from '@heroicons/react/24/outline';
|
||||
import { DocumentoEditor } from './documentos/DocumentoEditor';
|
||||
import { api } from '../lib/api';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { DocumentoViewer } from './documentos/DocumentoViewer';
|
||||
|
||||
interface Documento {
|
||||
id: string;
|
||||
nome: string;
|
||||
conteudo: string;
|
||||
processoId?: string;
|
||||
atendimentoId?: string;
|
||||
criadoEm: string;
|
||||
}
|
||||
|
||||
interface DocumentoPayload {
|
||||
nome: string;
|
||||
conteudo: string;
|
||||
processoId?: string;
|
||||
atendimentoId?: string;
|
||||
}
|
||||
|
||||
export function DocumentosPage() {
|
||||
const [isEditorOpen, setIsEditorOpen] = useState(false);
|
||||
const [documentos, setDocumentos] = useState([]);
|
||||
const [modelos, setModelos] = useState([]);
|
||||
const [tabValue, setTabValue] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { processoId, atendimentoId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { user, signOut } = useAuth();
|
||||
const [isVisualizadorOpen, setVisualizadorOpen] = useState(false);
|
||||
const [documentoVisualizado, setDocumentoVisualizado] = useState(null);
|
||||
const [documentoEmEdicao, setDocumentoEmEdicao] = useState(null);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
if (!user) {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await Promise.all([loadDocumentos(), loadModelos()]);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
if (error?.response?.status === 401) {
|
||||
signOut(); // Usar a função do AuthContext
|
||||
navigate('/login');
|
||||
} else {
|
||||
toast.error('Erro ao carregar dados');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user, navigate, signOut]); // Adicionar signOut nas dependências
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData, processoId, atendimentoId]);
|
||||
|
||||
const loadDocumentos = async () => {
|
||||
const params = {};
|
||||
if (processoId) params.processoId = processoId;
|
||||
if (atendimentoId) params.atendimentoId = atendimentoId;
|
||||
|
||||
const response = await api.get('/documentos', { params });
|
||||
setDocumentos(response.data);
|
||||
};
|
||||
|
||||
const loadModelos = async () => {
|
||||
const response = await api.get('/documentos-modelos');
|
||||
setModelos(response.data);
|
||||
};
|
||||
|
||||
const handleSave = async (data: DocumentoPayload) => {
|
||||
try {
|
||||
const payload = {
|
||||
nome: data.nome.trim(),
|
||||
conteudo: data.conteudo.trim(),
|
||||
tipo: documentoEmEdicao?.tipo || 'OUTROS',
|
||||
modeloId: documentoEmEdicao?.modeloId,
|
||||
processoId: data.processoId || processoId,
|
||||
atendimentoId: data.atendimentoId || atendimentoId
|
||||
};
|
||||
|
||||
if (documentoEmEdicao?.id) {
|
||||
await api.put(`/documentos/${documentoEmEdicao.id}`, payload);
|
||||
toast.success('Documento atualizado com sucesso');
|
||||
} else {
|
||||
await api.post('/documentos', payload);
|
||||
toast.success('Documento criado com sucesso');
|
||||
}
|
||||
|
||||
await loadDocumentos();
|
||||
setIsEditorOpen(false);
|
||||
setDocumentoEmEdicao(null);
|
||||
} catch (error: any) {
|
||||
console.error('Erro ao salvar documento:', error);
|
||||
toast.error(error?.response?.data?.message || 'Erro ao salvar documento');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteDocumento = async (id) => {
|
||||
try {
|
||||
await api.delete(`/documentos/${id}`);
|
||||
toast.success('Documento excluído com sucesso');
|
||||
await loadDocumentos();
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir documento:', error);
|
||||
if (error?.response?.status === 401) {
|
||||
toast.error('Sessão expirada. Por favor, faça login novamente.');
|
||||
} else {
|
||||
toast.error('Erro ao excluir documento');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleVisualizar = async (doc) => {
|
||||
try {
|
||||
setDocumentoVisualizado(doc); // Simplificar para usar o documento diretamente
|
||||
setVisualizadorOpen(true);
|
||||
} catch (error) {
|
||||
console.error('Erro ao visualizar documento:', error);
|
||||
toast.error('Erro ao visualizar documento');
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportPDF = async (documento) => {
|
||||
try {
|
||||
const configRes = await api.get('/documentos/configuracoes');
|
||||
const response = await api.post('/documentos/exportar-pdf', {
|
||||
nome: documento.nome,
|
||||
conteudo: documento.conteudo,
|
||||
escritorio: configRes.data
|
||||
}, { responseType: 'blob' });
|
||||
|
||||
// Criar URL do blob e fazer download
|
||||
const url = window.URL.createObjectURL(new Blob([response.data]));
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${documento.nome}.pdf`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
link.parentNode.removeChild(link);
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
toast.success('PDF gerado com sucesso!');
|
||||
} catch (error) {
|
||||
console.error('Erro ao gerar PDF:', error);
|
||||
toast.error('Erro ao gerar PDF');
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (documento) => {
|
||||
// Garantir que todos os campos necessários estejam presentes
|
||||
setDocumentoEmEdicao({
|
||||
id: documento.id,
|
||||
nome: documento.nome,
|
||||
conteudo: documento.conteudo,
|
||||
tipo: documento.tipo || 'OUTROS',
|
||||
modeloId: documento.modeloId,
|
||||
processoId: documento.processoId || processoId,
|
||||
atendimentoId: documento.atendimentoId || atendimentoId
|
||||
});
|
||||
setVisualizadorOpen(false);
|
||||
setIsEditorOpen(true);
|
||||
};
|
||||
|
||||
const handleUseModelo = (modelo) => {
|
||||
setDocumentoEmEdicao({
|
||||
nome: modelo.nome,
|
||||
conteudo: modelo.conteudo,
|
||||
modeloId: modelo.id,
|
||||
tipo: 'OUTROS',
|
||||
processoId: processoId,
|
||||
atendimentoId: atendimentoId
|
||||
});
|
||||
setIsEditorOpen(true);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Carregando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">Documentos</h1>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setIsEditorOpen(true)}
|
||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
Novo Documento
|
||||
</button>
|
||||
{user?.perfil === 'ADVOGADO_ADMIN' && (
|
||||
<button
|
||||
onClick={() => navigate('/documentos/templates')}
|
||||
className="inline-flex items-center px-4 py-2 border border-blue-600 text-blue-600 rounded-md hover:bg-blue-50 transition-colors"
|
||||
>
|
||||
<DocumentIcon className="w-5 h-5 mr-2" />
|
||||
Gerenciar Templates
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-b border-gray-200">
|
||||
<nav className="flex -mb-px">
|
||||
<button
|
||||
onClick={() => setTabValue(0)}
|
||||
className={`px-4 py-2 font-medium text-sm border-b-2 transition-colors duration-200 ${
|
||||
tabValue === 0
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
Documentos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTabValue(1)}
|
||||
className={`ml-8 px-4 py-2 font-medium text-sm border-b-2 transition-colors duration-200 ${
|
||||
tabValue === 1
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
Modelos
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{tabValue === 0 && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{documentos.map((doc) => (
|
||||
<div key={doc.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4">
|
||||
<div className="p-4 min-h-[180px] flex flex-col justify-between"> {/* Ajustado min-height e layout */}
|
||||
<div>
|
||||
<div className="flex items-center mb-3">
|
||||
<DocumentIcon className="w-6 h-6 text-gray-500 mr-2 flex-shrink-0" />
|
||||
<h3 className="font-semibold text-gray-900 dark:text-gray-100 line-clamp-2">{doc.nome}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Criado em: {new Date(doc.criadoEm).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Botões em flex-wrap para melhor responsividade */}
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
<button
|
||||
onClick={() => handleVisualizar(doc)}
|
||||
className="flex-1 min-w-[120px] inline-flex items-center justify-center px-3 py-1.5 text-sm text-blue-600 border border-blue-200 rounded-md hover:bg-blue-50"
|
||||
>
|
||||
<EyeIcon className="w-4 h-4 mr-1" />
|
||||
Visualizar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleExportPDF(doc)}
|
||||
className="flex-1 min-w-[120px] inline-flex items-center justify-center px-3 py-1.5 text-sm text-blue-600 border border-blue-200 rounded-md hover:bg-blue-50"
|
||||
>
|
||||
<DocumentArrowDownIcon className="w-4 h-4 mr-1" />
|
||||
Exportar PDF
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteDocumento(doc.id)}
|
||||
className="flex-1 min-w-[120px] inline-flex items-center justify-center px-3 py-1.5 text-sm text-red-600 dark:text-red-400 border border-red-200 dark:border-red-900 rounded-md hover:bg-red-50 dark:hover:bg-red-900/20"
|
||||
>
|
||||
<TrashIcon className="w-4 h-4 mr-1" />
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tabValue === 1 && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{modelos.map((modelo) => (
|
||||
<div key={modelo.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||
<div className="p-4">
|
||||
<div className="flex items-center mb-3">
|
||||
<DocumentIcon className="w-6 h-6 text-gray-500 mr-2" />
|
||||
<h3 className="font-semibold text-gray-900 dark:text-gray-100">{modelo.nome}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{modelo.descricao}</p>
|
||||
<button
|
||||
onClick={() => handleUseModelo(modelo)}
|
||||
className="w-full inline-flex items-center justify-center px-4 py-2 text-sm border border-blue-600 text-blue-600 rounded-md hover:bg-blue-50 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
Usar Modelo
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Dialog
|
||||
open={isVisualizadorOpen}
|
||||
onClose={() => setVisualizadorOpen(false)}
|
||||
className="relative z-50"
|
||||
>
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-4xl bg-white rounded-lg shadow-xl">
|
||||
<div className="flex items-center justify-between p-4 border-b">
|
||||
<Dialog.Title className="text-lg font-semibold">
|
||||
{documentoVisualizado?.nome}
|
||||
</Dialog.Title>
|
||||
<button
|
||||
onClick={() => setVisualizadorOpen(false)}
|
||||
className="p-2 rounded hover:bg-gray-100"
|
||||
>
|
||||
<XMarkIcon className="w-6 h-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="p-6 max-h-[70vh] overflow-y-auto">
|
||||
<div
|
||||
className="prose max-w-none"
|
||||
dangerouslySetInnerHTML={{ __html: documentoVisualizado?.conteudo }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between p-4 border-t bg-gray-50">
|
||||
<div className="text-sm text-gray-500">
|
||||
Criado em: {documentoVisualizado && new Date(documentoVisualizado.criadoEm).toLocaleDateString()}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => handleEdit(documentoVisualizado)}
|
||||
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700"
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
<DocumentoEditor
|
||||
isOpen={isEditorOpen}
|
||||
onClose={() => {
|
||||
setIsEditorOpen(false);
|
||||
setDocumentoEmEdicao(null);
|
||||
}}
|
||||
onSave={handleSave}
|
||||
processoId={processoId}
|
||||
atendimentoId={atendimentoId}
|
||||
documento={documentoEmEdicao} // Passando o documento em edição
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import React from 'react';
|
||||
import { Card } from './ui/Card';
|
||||
import { isRouteErrorResponse, useRouteError } from 'react-router-dom';
|
||||
|
||||
export function ErrorBoundary() {
|
||||
const error = useRouteError();
|
||||
console.error(error);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<Card>
|
||||
<div className="p-6 text-center">
|
||||
<h2 className="text-2xl font-bold text-red-600 mb-4">
|
||||
Ocorreu um erro
|
||||
</h2>
|
||||
|
||||
<div className="mt-4 p-4 bg-red-50 rounded-lg text-left">
|
||||
{isRouteErrorResponse(error) ? (
|
||||
<div>
|
||||
<p><strong>Status:</strong> {error.status}</p>
|
||||
<p><strong>Mensagem:</strong> {error.data.message || error.statusText}</p>
|
||||
</div>
|
||||
) : error instanceof Error ? (
|
||||
<div>
|
||||
<p><strong>Erro:</strong> {error.message}</p>
|
||||
{error.stack && (
|
||||
<details className="mt-2">
|
||||
<summary className="cursor-pointer text-sm">Ver detalhes técnicos</summary>
|
||||
<pre className="mt-2 whitespace-pre-wrap text-xs">
|
||||
{error.stack}
|
||||
</pre>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p>Ocorreu um erro desconhecido.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6">
|
||||
<a
|
||||
href="/"
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
|
||||
>
|
||||
Voltar para a página inicial
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useNavigate, useLocation } from "react-router-dom";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
|
||||
export const LoginPage: React.FC = () => {
|
||||
const [email, setEmail] = useState("");
|
||||
const [senha, setSenha] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
const { signIn, isAuthenticated } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) {
|
||||
const from = location.state?.from?.pathname || "/dashboard";
|
||||
navigate(from, { replace: true });
|
||||
}
|
||||
}, [isAuthenticated, navigate, location]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
setLoading(true);
|
||||
console.log("Tentando login com:", { email, senha }); // Debug
|
||||
await signIn(email, senha);
|
||||
navigate("/dashboard");
|
||||
} catch (error) {
|
||||
console.error("Erro detalhado:", error); // Debug detalhado
|
||||
setError("Email ou senha inválidos");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col items-center justify-center bg-gradient-to-br from-blue-900 via-blue-800 to-blue-900">
|
||||
{/* Círculos decorativos */}
|
||||
<div className="absolute top-0 left-0 w-96 h-96 bg-blue-700 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob"></div>
|
||||
<div className="absolute top-0 right-0 w-96 h-96 bg-blue-800 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-2000"></div>
|
||||
<div className="absolute bottom-0 left-0 w-96 h-96 bg-blue-900 rounded-full mix-blend-multiply filter blur-xl opacity-20 animate-blob animation-delay-4000"></div>
|
||||
|
||||
{/* Logo */}
|
||||
<div className="mb-8 text-center">
|
||||
<h1 className="text-5xl font-bold text-white mb-2">AdvX</h1>
|
||||
<div className="h-1 w-20 bg-blue-400 mx-auto rounded-full"></div>
|
||||
</div>
|
||||
|
||||
{/* Card de Login */}
|
||||
<div className="w-full max-w-md bg-white/10 backdrop-blur-lg rounded-2xl shadow-2xl p-8 space-y-6 relative z-10 border border-white/20">
|
||||
<div className="text-center space-y-2 mb-8">
|
||||
<h2 className="text-2xl font-semibold text-white">
|
||||
Bem-vindo de volta
|
||||
</h2>
|
||||
<p className="text-blue-200">Entre com suas credenciais</p>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-500/10 border border-red-500/50 text-red-100 px-4 py-3 rounded-lg text-center">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm font-medium text-blue-100 block mb-2">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 text-white placeholder-blue-200 focus:ring-2 focus:ring-blue-400 focus:border-transparent transition duration-200"
|
||||
placeholder="seu@email.com"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm font-medium text-blue-100 block mb-2">
|
||||
Senha
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={senha}
|
||||
onChange={(e) => setSenha(e.target.value)}
|
||||
className="w-full px-4 py-3 rounded-lg bg-white/10 border border-white/20 text-white placeholder-blue-200 focus:ring-2 focus:ring-blue-400 focus:border-transparent transition duration-200"
|
||||
placeholder="••••••••"
|
||||
required
|
||||
disabled={loading}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className={`w-full bg-blue-500 text-white py-3 rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-blue-800 transition duration-200 font-medium ${
|
||||
loading ? "opacity-50 cursor-not-allowed" : ""
|
||||
}`}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="flex items-center justify-center">
|
||||
<svg
|
||||
className="animate-spin -ml-1 mr-3 h-5 w-5 text-white"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
></circle>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
></path>
|
||||
</svg>
|
||||
Entrando...
|
||||
</span>
|
||||
) : (
|
||||
"Entrar"
|
||||
)}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div className="text-center">
|
||||
<p className="text-sm text-blue-200">
|
||||
Problemas com acesso? Contate o administrador
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import React from "react";
|
||||
import { Navigate, Outlet, useLocation } from "react-router-dom";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
|
||||
export const PrivateRoute: React.FC = () => {
|
||||
const { isAuthenticated } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
return isAuthenticated ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<Navigate to="/login" state={{ from: location }} replace />
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: React.ReactNode;
|
||||
roles?: string[];
|
||||
}
|
||||
|
||||
export function ProtectedRoute({ children, roles }: ProtectedRouteProps) {
|
||||
const { user } = useAuth();
|
||||
const location = useLocation();
|
||||
|
||||
console.log('ProtectedRoute - Current Path:', location.pathname);
|
||||
console.log('ProtectedRoute - Required Roles:', roles);
|
||||
console.log('ProtectedRoute - User:', user);
|
||||
|
||||
if (!user) {
|
||||
console.log('ProtectedRoute - No user, redirecting to login');
|
||||
return <Navigate to="/login" />;
|
||||
}
|
||||
|
||||
if (!roles || roles.length === 0) {
|
||||
console.log('ProtectedRoute - No roles required, allowing access');
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
if (!roles.includes(user.perfil)) {
|
||||
console.log('ProtectedRoute - Access denied');
|
||||
console.log('Required roles:', roles);
|
||||
console.log('User role:', user.perfil);
|
||||
return <Navigate to="/dashboard" replace state={{ from: location }} />;
|
||||
}
|
||||
|
||||
console.log('ProtectedRoute - Access granted');
|
||||
return <>{children}</>;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import {
|
||||
HomeIcon,
|
||||
ScaleIcon,
|
||||
UserGroupIcon,
|
||||
UserIcon,
|
||||
ClipboardDocumentCheckIcon,
|
||||
DocumentTextIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
export function useNavigation() {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
return [
|
||||
{ name: 'Dashboard', href: '/dashboard', icon: HomeIcon },
|
||||
{ name: 'Processos', href: '/processos', icon: ScaleIcon },
|
||||
{ name: 'Clientes', href: '/clientes', icon: UserGroupIcon },
|
||||
{ name: 'Atendimentos', href: '/atendimentos', icon: UserIcon },
|
||||
{ name: 'Tarefas', href: '/tarefas', icon: ClipboardDocumentCheckIcon },
|
||||
{ name: 'Documentos', href: '/documentos', icon: DocumentTextIcon },
|
||||
].map(item => ({
|
||||
...item,
|
||||
current: pathname === item.href
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { format, startOfWeek, addDays, isSameDay, parseISO, getHours } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { AgendamentoForm } from './AgendamentoForm';
|
||||
import { AtendimentoForm } from './AtendimentoForm';
|
||||
import api from '../../services/api';
|
||||
|
||||
interface Agendamento {
|
||||
id: string;
|
||||
data: string;
|
||||
cliente: {
|
||||
id: string;
|
||||
nome: string;
|
||||
};
|
||||
status: string;
|
||||
tipo?: string;
|
||||
observacoes?: string;
|
||||
}
|
||||
|
||||
export function AgendamentoCalendario() {
|
||||
const [selectedDate, setSelectedDate] = useState(new Date());
|
||||
const [agendamentos, setAgendamentos] = useState([]);
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [selectedAgendamento, setSelectedAgendamento] = useState<Agendamento | null>(null);
|
||||
const [atendimentoFormOpen, setAtendimentoFormOpen] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadAgendamentos(selectedDate);
|
||||
}, [selectedDate]);
|
||||
|
||||
const loadAgendamentos = async (date: Date) => {
|
||||
try {
|
||||
const response = await api.get('/agendamentos', {
|
||||
params: { data: date.toISOString() }
|
||||
});
|
||||
setAgendamentos(response.data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar agendamentos:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const weekDays = [...Array(7)].map((_, i) => {
|
||||
const day = addDays(startOfWeek(selectedDate, { locale: ptBR }), i);
|
||||
return format(day, 'EEEE', { locale: ptBR });
|
||||
});
|
||||
|
||||
const timeSlots = [...Array(9)].map((_, i) => {
|
||||
const hour = i + 9; // Começa às 9h
|
||||
return `${hour}:00`;
|
||||
});
|
||||
|
||||
const getAgendamentosForSlot = (dayIndex: number, hour: number) => {
|
||||
return agendamentos.filter((agendamento: Agendamento) => {
|
||||
const agendamentoDate = parseISO(agendamento.data);
|
||||
const slotDate = addDays(startOfWeek(selectedDate, { locale: ptBR }), dayIndex);
|
||||
|
||||
return isSameDay(agendamentoDate, slotDate) && getHours(agendamentoDate) === hour;
|
||||
});
|
||||
};
|
||||
|
||||
const handleAgendamentoClick = async (agendamento: Agendamento) => {
|
||||
try {
|
||||
// Buscar atendimento inicial se o tipo não for INICIAL
|
||||
if (agendamento.tipo !== 'INICIAL') {
|
||||
const response = await api.get(`/atendimentos/iniciais/${agendamento.cliente.id}`);
|
||||
const atendimentosIniciais = response.data;
|
||||
|
||||
// Pegar o atendimento inicial mais recente
|
||||
const atendimentoInicial = atendimentosIniciais[0];
|
||||
|
||||
setSelectedAgendamento({
|
||||
...agendamento,
|
||||
atendimentoInicial: atendimentoInicial
|
||||
});
|
||||
} else {
|
||||
setSelectedAgendamento(agendamento);
|
||||
}
|
||||
setAtendimentoFormOpen(true);
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar atendimento inicial:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditAgendamento = async (agendamento: Agendamento) => {
|
||||
try {
|
||||
// Editar agendamento existente
|
||||
setSelectedAgendamento(agendamento);
|
||||
setFormOpen(true);
|
||||
} catch (error) {
|
||||
console.error('Erro ao editar agendamento:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAgendamento = async (id: string) => {
|
||||
if (window.confirm('Tem certeza que deseja excluir este agendamento?')) {
|
||||
try {
|
||||
await api.delete(`/agendamentos/${id}`);
|
||||
await loadAgendamentos(selectedDate);
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir agendamento:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-xl font-semibold">Agenda de Atendimentos</h2>
|
||||
<button
|
||||
onClick={() => setFormOpen(true)}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700"
|
||||
>
|
||||
Novo Agendamento
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-8 gap-4">
|
||||
{/* Coluna de horários */}
|
||||
<div className="col-span-1">
|
||||
<div className="h-10" /> {/* Espaço para alinhar com cabeçalho */}
|
||||
{timeSlots.map(time => (
|
||||
<div key={time} className="h-20 flex items-center justify-center text-sm text-gray-500">
|
||||
{time}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Colunas dos dias */}
|
||||
{weekDays.map((day, dayIndex) => (
|
||||
<div key={dayIndex} className="col-span-1">
|
||||
<div className="h-10 flex items-center justify-center font-medium text-gray-700">
|
||||
{day}
|
||||
</div>
|
||||
{timeSlots.map((time, i) => {
|
||||
const hour = i + 9;
|
||||
const slotsAgendamentos = getAgendamentosForSlot(dayIndex, hour);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={time}
|
||||
className="h-20 border border-gray-200 rounded-lg p-2 hover:bg-gray-50 relative"
|
||||
onClick={() => setFormOpen(true)}
|
||||
>
|
||||
{slotsAgendamentos.map((agendamento: Agendamento) => (
|
||||
<div
|
||||
key={agendamento.id}
|
||||
className={`absolute inset-x-1 p-1 rounded text-sm ${getStatusColor(agendamento.status)}`}
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="font-medium truncate">{agendamento.cliente.nome}</div>
|
||||
<div className="flex space-x-1">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleEditAgendamento(agendamento);
|
||||
}}
|
||||
className="p-1 hover:bg-white/20 rounded"
|
||||
title="Editar"
|
||||
>
|
||||
✏️
|
||||
</button>
|
||||
{agendamento.status !== 'REALIZADO' && (
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleDeleteAgendamento(agendamento.id);
|
||||
}}
|
||||
className="p-1 hover:bg-white/20 rounded"
|
||||
title="Excluir"
|
||||
>
|
||||
🗑️
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleAgendamentoClick(agendamento);
|
||||
}}
|
||||
className="p-1 hover:bg-white/20 rounded"
|
||||
title="Realizar Atendimento"
|
||||
>
|
||||
📝
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-xs truncate">
|
||||
{format(parseISO(agendamento.data), 'HH:mm')}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<AgendamentoForm
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
onSave={() => {
|
||||
loadAgendamentos(selectedDate);
|
||||
setFormOpen(false);
|
||||
}}
|
||||
/>
|
||||
|
||||
{selectedAgendamento && (
|
||||
<AtendimentoForm
|
||||
open={atendimentoFormOpen}
|
||||
onClose={() => {
|
||||
setAtendimentoFormOpen(false);
|
||||
setSelectedAgendamento(null);
|
||||
}}
|
||||
onSave={async () => {
|
||||
await loadAgendamentos(selectedDate);
|
||||
setAtendimentoFormOpen(false);
|
||||
setSelectedAgendamento(null);
|
||||
}}
|
||||
clienteId={selectedAgendamento.cliente.id}
|
||||
initialData={{
|
||||
titulo: `Atendimento - ${selectedAgendamento.cliente.nome}`,
|
||||
agendamentoId: selectedAgendamento.id,
|
||||
tipo: selectedAgendamento.tipo || 'INICIAL',
|
||||
atendimentoInicialId: selectedAgendamento.atendimentoInicial?.id
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getStatusColor(status: string) {
|
||||
switch (status) {
|
||||
case 'AGENDADO':
|
||||
return 'bg-blue-100 text-blue-800';
|
||||
case 'CONFIRMADO':
|
||||
return 'bg-green-100 text-green-800';
|
||||
case 'CANCELADO':
|
||||
return 'bg-red-100 text-red-800';
|
||||
case 'REALIZADO':
|
||||
return 'bg-purple-100 text-purple-800';
|
||||
case 'NAO_COMPARECEU':
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
default:
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { DateTimePicker } from '@mui/x-date-pickers';
|
||||
import api from '../../services/api';
|
||||
|
||||
// Implementar debounce
|
||||
function debounce(fn: Function, ms = 300) {
|
||||
let timeoutId: ReturnType<typeof setTimeout>;
|
||||
return function (this: any, ...args: any[]) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => fn.apply(this, args), ms);
|
||||
};
|
||||
}
|
||||
|
||||
interface AgendamentoFormProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: () => void;
|
||||
clienteId?: string;
|
||||
agendamento?: {
|
||||
id: string;
|
||||
data: string;
|
||||
cliente: {
|
||||
id: string;
|
||||
nome: string;
|
||||
};
|
||||
tipo: string;
|
||||
observacoes?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function AgendamentoForm({ open, onClose, onSave, clienteId: defaultClienteId, agendamento }: AgendamentoFormProps) {
|
||||
const [data, setData] = useState<Date | null>(null);
|
||||
const [observacoes, setObservacoes] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [tipo, setTipo] = useState('');
|
||||
|
||||
// Adicionar estados para busca de cliente
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<any[]>([]);
|
||||
const [selectedClient, setSelectedClient] = useState<any>(null);
|
||||
const [clienteId, setClienteId] = useState(defaultClienteId || '');
|
||||
|
||||
// Preencher form quando editar
|
||||
useEffect(() => {
|
||||
if (agendamento) {
|
||||
setData(new Date(agendamento.data));
|
||||
setClienteId(agendamento.cliente.id);
|
||||
setSearchTerm(agendamento.cliente.nome);
|
||||
setTipo(agendamento.tipo || '');
|
||||
setObservacoes(agendamento.observacoes || '');
|
||||
}
|
||||
}, [agendamento]);
|
||||
|
||||
// Busca de clientes com debounce
|
||||
const searchClients = useCallback(
|
||||
debounce(async (term: string) => {
|
||||
if (term.length < 3) return;
|
||||
try {
|
||||
const response = await api.get(`/clientes/search?q=${term}`);
|
||||
setSearchResults(response.data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar clientes:', error);
|
||||
}
|
||||
}, 300),
|
||||
[]
|
||||
);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!data || !clienteId) {
|
||||
setError('Data e cliente são obrigatórios');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
if (agendamento) {
|
||||
// Atualizar agendamento existente
|
||||
await api.put(`/agendamentos/${agendamento.id}`, {
|
||||
clienteId,
|
||||
data: data.toISOString(),
|
||||
observacoes,
|
||||
tipo,
|
||||
});
|
||||
} else {
|
||||
// Criar novo agendamento
|
||||
await api.post('/agendamentos', {
|
||||
clienteId,
|
||||
data: data.toISOString(),
|
||||
observacoes,
|
||||
tipo,
|
||||
});
|
||||
}
|
||||
onSave();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
setError(agendamento ? 'Erro ao atualizar agendamento' : 'Erro ao criar agendamento');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`fixed inset-0 bg-gray-500 bg-opacity-75 ${open ? 'flex' : 'hidden'} z-50`}>
|
||||
<div className="relative bg-white rounded-lg max-w-md w-full m-auto p-6">
|
||||
<h2 className="text-xl font-bold mb-6">Agendar Atendimento</h2>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
{/* Busca de Cliente */}
|
||||
<div className="relative">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Cliente
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
searchClients(e.target.value);
|
||||
}}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="Buscar cliente..."
|
||||
/>
|
||||
|
||||
{searchResults.length > 0 && (
|
||||
<div className="absolute z-20 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg">
|
||||
{searchResults.map(client => (
|
||||
<div
|
||||
key={client.id}
|
||||
className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
|
||||
onClick={() => {
|
||||
setSelectedClient(client);
|
||||
setClienteId(client.id);
|
||||
setSearchTerm(client.nome);
|
||||
setSearchResults([]);
|
||||
}}
|
||||
>
|
||||
<div className="font-medium">{client.nome}</div>
|
||||
<div className="text-sm text-gray-500">{client.cpfCnpj}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<DateTimePicker
|
||||
label="Data e Hora"
|
||||
value={data}
|
||||
onChange={setData}
|
||||
className="w-full"
|
||||
minDate={new Date()} // Não permitir datas passadas
|
||||
minutesStep={30} // Intervalos de 30 minutos
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Campo de Tipo de Atendimento */}
|
||||
<div>
|
||||
<select
|
||||
value={tipo}
|
||||
onChange={(e) => setTipo(e.target.value)}
|
||||
className="w-full p-2 border rounded-lg"
|
||||
>
|
||||
<option value="">Selecione o tipo</option>
|
||||
<option value="INICIAL">Inicial</option>
|
||||
<option value="RETORNO">Retorno</option>
|
||||
<option value="ORIENTACAO">Orientação</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<textarea
|
||||
value={observacoes}
|
||||
onChange={(e) => setObservacoes(e.target.value)}
|
||||
placeholder="Observações"
|
||||
className="w-full p-2 border rounded-lg"
|
||||
rows={4}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 border-l-4 border-red-500 text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end space-x-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSaving}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
|
||||
>
|
||||
{isSaving ? 'Salvando...' : 'Agendar'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import api from '../../services/api';
|
||||
import { format, parseISO } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
|
||||
// Função auxiliar para formatar data com validação
|
||||
const formatDate = (date: string | Date | null | undefined, formatStr: string): string => {
|
||||
if (!date) return 'Data não disponível';
|
||||
try {
|
||||
const dateObj = typeof date === 'string' ? parseISO(date) : date;
|
||||
return format(dateObj, formatStr, { locale: ptBR });
|
||||
} catch (error) {
|
||||
console.error('Erro ao formatar data:', error);
|
||||
return 'Data inválida';
|
||||
}
|
||||
};
|
||||
|
||||
export function AtendimentoDetalhes() {
|
||||
const { id } = useParams();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [cancelModalOpen, setCancelModalOpen] = useState(false);
|
||||
const [justificativa, setJustificativa] = useState('');
|
||||
const [isCancelling, setIsCancelling] = useState(false);
|
||||
|
||||
const { data: atendimento, refetch } = useQuery(['atendimento', id], async () => {
|
||||
const response = await api.get(`/atendimentos/${id}`);
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const handleCancelar = async () => {
|
||||
if (!justificativa.trim()) {
|
||||
alert('A justificativa é obrigatória');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsCancelling(true);
|
||||
await api.patch(`/atendimentos/${id}/status`, {
|
||||
status: 'CANCELADO',
|
||||
justificativa
|
||||
});
|
||||
await refetch();
|
||||
setCancelModalOpen(false);
|
||||
} catch (error) {
|
||||
console.error('Erro ao cancelar atendimento:', error);
|
||||
alert('Erro ao cancelar atendimento');
|
||||
} finally {
|
||||
setIsCancelling(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!atendimento) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto p-6 space-y-6">
|
||||
{/* Cabeçalho */}
|
||||
<div className="bg-white rounded-lg shadow-lg overflow-hidden">
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 px-6 py-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">{atendimento.titulo}</h1>
|
||||
<p className="text-blue-100">Protocolo: {atendimento.protocolo}</p>
|
||||
</div>
|
||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${
|
||||
atendimento.tipo === 'INICIAL' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800'
|
||||
}`}>
|
||||
{atendimento.tipo}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Informações do Atendimento */}
|
||||
<div className="p-6">
|
||||
<div className="grid grid-cols-2 gap-6 mb-6">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-500">Cliente</h3>
|
||||
<p className="mt-1 text-sm text-gray-900">{atendimento.cliente.nome}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-500">Data do Atendimento</h3>
|
||||
<p className="mt-1 text-sm text-gray-900">
|
||||
{formatDate(atendimento.dataAtendimento, "PPpp")}
|
||||
</p>
|
||||
</div>
|
||||
{atendimento.processo && (
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-500">Processo Vinculado</h3>
|
||||
<Link
|
||||
to={`/processos/${atendimento.processo.id}`}
|
||||
className="mt-1 text-sm text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
{atendimento.processo.numero}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<h3 className="text-sm font-medium text-gray-500">Responsável</h3>
|
||||
<p className="mt-1 text-sm text-gray-900">{atendimento.usuario.nome}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Conteúdo do Atendimento */}
|
||||
<div className="prose max-w-none">
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">Conteúdo</h3>
|
||||
<div
|
||||
className="bg-gray-50 rounded-lg p-6"
|
||||
dangerouslySetInnerHTML={{ __html: atendimento.conteudo }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Anexos */}
|
||||
{atendimento.anexos?.length > 0 && (
|
||||
<div className="mt-8">
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">Anexos</h3>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{atendimento.anexos.map((anexo: any) => (
|
||||
<div key={anexo.id} className="flex items-center p-4 bg-gray-50 rounded-lg">
|
||||
<svg className="w-6 h-6 text-gray-400 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
|
||||
</svg>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-gray-900 truncate">
|
||||
{anexo.nome}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
{formatDate(anexo.dataCriacao, "PP")}
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
window.open(anexo.url, '_blank', 'noopener,noreferrer');
|
||||
}}
|
||||
className="ml-4 text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
Visualizar
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Adicionar botão de cancelar próximo ao cabeçalho */}
|
||||
{atendimento.status !== 'CANCELADO' && (
|
||||
<button
|
||||
onClick={() => setCancelModalOpen(true)}
|
||||
className="bg-red-100 text-red-600 px-4 py-2 rounded-lg hover:bg-red-200"
|
||||
>
|
||||
Cancelar Atendimento
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Modal de Cancelamento */}
|
||||
{cancelModalOpen && (
|
||||
<div className="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center p-4">
|
||||
<div className="bg-white rounded-lg max-w-md w-full p-6">
|
||||
<h3 className="text-lg font-medium mb-4">Cancelar Atendimento</h3>
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
Esta ação não pode ser desfeita. O atendimento será marcado como cancelado, mas manterá seu protocolo e histórico.
|
||||
</p>
|
||||
<textarea
|
||||
value={justificativa}
|
||||
onChange={(e) => setJustificativa(e.target.value)}
|
||||
placeholder="Insira a justificativa do cancelamento"
|
||||
className="w-full p-2 border rounded-lg mb-4"
|
||||
rows={4}
|
||||
required
|
||||
/>
|
||||
<div className="flex justify-end space-x-4">
|
||||
<button
|
||||
onClick={() => setCancelModalOpen(false)}
|
||||
className="px-4 py-2 text-gray-600 hover:text-gray-800"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCancelar}
|
||||
disabled={isCancelling || !justificativa.trim()}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 disabled:opacity-50"
|
||||
>
|
||||
{isCancelling ? 'Cancelando...' : 'Confirmar Cancelamento'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Exibir informação de cancelamento se aplicável */}
|
||||
{atendimento.status === 'CANCELADO' && (
|
||||
<div className="mt-4 p-4 bg-red-50 border-l-4 border-red-500 rounded-r-lg">
|
||||
<h4 className="text-red-800 font-medium">Atendimento Cancelado</h4>
|
||||
<p className="text-red-600 mt-1">{atendimento.justificativaCancelamento}</p>
|
||||
<p className="text-sm text-red-500 mt-1">
|
||||
Cancelado em: {formatDate(atendimento.dataAtualizacao, "PPpp")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { Dialog, DialogTitle, DialogContent, DialogActions, Button, TextField, FormControl, InputLabel, Select, MenuItem, Alert } from '@mui/material';
|
||||
import { useEditor, EditorContent } from '@tiptap/react';
|
||||
import StarterKit from '@tiptap/starter-kit';
|
||||
import Link from '@tiptap/extension-link';
|
||||
import { TipoAtendimento } from '@prisma/client';
|
||||
import api from '../../services/api'; // Adicionar esta importação
|
||||
import { XMarkIcon, PaperClipIcon } from '@heroicons/react/24/outline'; // Alterado para v2
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { uploadFile } from '../../services/upload';
|
||||
|
||||
// Implementar debounce manualmente ao invés de usar lodash
|
||||
function debounce(fn: Function, ms = 300) {
|
||||
let timeoutId: ReturnType<typeof setTimeout>;
|
||||
return function (this: any, ...args: any[]) {
|
||||
clearTimeout(timeoutId);
|
||||
timeoutId = setTimeout(() => fn.apply(this, args), ms);
|
||||
};
|
||||
}
|
||||
|
||||
interface AtendimentoFormProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => Promise<void>;
|
||||
clienteId?: string;
|
||||
processoId?: string;
|
||||
initialData?: {
|
||||
titulo?: string;
|
||||
agendamentoId?: string;
|
||||
tipo?: string;
|
||||
atendimentoInicialId?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AnexoTemp {
|
||||
id?: string;
|
||||
file: File;
|
||||
nome: string;
|
||||
progresso: number;
|
||||
erro?: string;
|
||||
}
|
||||
|
||||
export function AtendimentoForm({ open, onClose, onSave, clienteId, processoId, initialData }: AtendimentoFormProps) {
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [searchResults, setSearchResults] = useState<any[]>([]);
|
||||
const [selectedClient, setSelectedClient] = useState<any>(null);
|
||||
const [atendimentoInicial, setAtendimentoInicial] = useState<any>(null);
|
||||
const [atendimentosIniciais, setAtendimentosIniciais] = useState<any[]>([]);
|
||||
const [formData, setFormData] = useState({
|
||||
titulo: '',
|
||||
tipo: TipoAtendimento.INICIAL,
|
||||
conteudo: '',
|
||||
clienteId: clienteId || '',
|
||||
processoId: processoId || '',
|
||||
atendimentoInicialId: '',
|
||||
});
|
||||
const [anexos, setAnexos] = useState<AnexoTemp[]>([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
// Resetar form ao abrir
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setFormData({
|
||||
titulo: '',
|
||||
tipo: TipoAtendimento.INICIAL,
|
||||
conteudo: '',
|
||||
clienteId: clienteId || '',
|
||||
processoId: processoId || '',
|
||||
atendimentoInicialId: '',
|
||||
});
|
||||
}
|
||||
}, [open, clienteId, processoId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (open && initialData) {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
titulo: initialData.titulo || prev.titulo,
|
||||
clienteId: clienteId || prev.clienteId,
|
||||
processoId: processoId || prev.processoId,
|
||||
tipo: initialData.tipo || prev.tipo,
|
||||
atendimentoInicialId: initialData.atendimentoInicialId || prev.atendimentoInicialId
|
||||
}));
|
||||
}
|
||||
}, [open, initialData, clienteId, processoId]);
|
||||
|
||||
const [clientes, setClientes] = useState<any[]>([]);
|
||||
const [error, setError] = useState('');
|
||||
const [isSaving, setIsSaving] = useState(false); // Adicionar estado para prevenir múltiplos submits
|
||||
|
||||
// Buscar lista de clientes
|
||||
useEffect(() => {
|
||||
const fetchClientes = async () => {
|
||||
try {
|
||||
const response = await api.get('/clientes');
|
||||
setClientes(response.data);
|
||||
} catch (err) {
|
||||
console.error('Erro ao carregar clientes:', err);
|
||||
}
|
||||
};
|
||||
fetchClientes();
|
||||
}, []);
|
||||
|
||||
// Busca de clientes
|
||||
const searchClients = useCallback(
|
||||
debounce(async (term: string) => {
|
||||
if (term.length < 3) return;
|
||||
try {
|
||||
const response = await api.get(`/clientes/search?q=${term}`);
|
||||
setSearchResults(response.data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar clientes:', error);
|
||||
}
|
||||
}, 300),
|
||||
[]
|
||||
);
|
||||
|
||||
// Carregar atendimentos iniciais quando selecionar cliente
|
||||
useEffect(() => {
|
||||
if (formData.clienteId && formData.tipo !== TipoAtendimento.INICIAL) {
|
||||
api.get(`/atendimentos/iniciais/${formData.clienteId}`)
|
||||
.then(response => setAtendimentosIniciais(response.data))
|
||||
.catch(error => console.error('Erro ao carregar atendimentos:', error));
|
||||
}
|
||||
}, [formData.clienteId, formData.tipo]);
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Link.configure({
|
||||
openOnClick: false,
|
||||
}),
|
||||
],
|
||||
content: '',
|
||||
onUpdate: ({ editor }) => {
|
||||
setFormData(prev => ({ ...prev, conteudo: editor.getHTML() }));
|
||||
},
|
||||
});
|
||||
|
||||
const onDrop = useCallback((acceptedFiles: File[]) => {
|
||||
const novosAnexos = acceptedFiles.map(file => ({
|
||||
file,
|
||||
nome: file.name,
|
||||
progresso: 0
|
||||
}));
|
||||
setAnexos(prev => [...prev, ...novosAnexos]);
|
||||
}, []);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop,
|
||||
maxSize: 10485760 // 10MB
|
||||
});
|
||||
|
||||
const handleRemoveAnexo = (index: number) => {
|
||||
setAnexos(prev => prev.filter((_, i) => i !== index));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (isSaving) return;
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setError('');
|
||||
|
||||
if (!formData.clienteId) {
|
||||
setError('Selecione um cliente');
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Buscar dados do cliente caso não esteja selecionado
|
||||
if (!selectedClient) {
|
||||
try {
|
||||
const response = await api.get(`/clientes/${formData.clienteId}`);
|
||||
setSelectedClient(response.data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar cliente:', error);
|
||||
setError('Erro ao buscar dados do cliente');
|
||||
setIsSaving(false);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Criar atendimento primeiro para ter o protocolo
|
||||
const response = await api.post('/atendimentos', {
|
||||
...formData,
|
||||
agendamentoId: initialData?.agendamentoId,
|
||||
});
|
||||
|
||||
const atendimentoId = response.data.id;
|
||||
const protocolo = response.data.protocolo;
|
||||
|
||||
// Upload dos anexos com protocolo
|
||||
if (anexos.length > 0) {
|
||||
const anexosPromises = anexos.map(async (anexo) => {
|
||||
try {
|
||||
const clienteNome = selectedClient?.nome || 'cliente';
|
||||
return await uploadFile(
|
||||
anexo.file,
|
||||
clienteNome,
|
||||
'atendimento',
|
||||
protocolo
|
||||
);
|
||||
} catch (error) {
|
||||
console.error('Erro no upload:', error);
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
const anexosUpload = await Promise.all(anexosPromises);
|
||||
const anexosSalvos = anexosUpload.filter(Boolean);
|
||||
|
||||
if (anexosSalvos.length > 0) {
|
||||
await api.patch(`/atendimentos/${atendimentoId}`, {
|
||||
anexos: anexosSalvos
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Limpar form e fechar modal
|
||||
setFormData({
|
||||
titulo: '',
|
||||
tipo: TipoAtendimento.INICIAL,
|
||||
conteudo: '',
|
||||
clienteId: '',
|
||||
processoId: '',
|
||||
atendimentoInicialId: '',
|
||||
});
|
||||
|
||||
await onSave(response.data);
|
||||
onClose();
|
||||
|
||||
} catch (err) {
|
||||
console.error('Erro ao salvar atendimento:', err);
|
||||
setError(err.response?.data?.error || 'Erro ao criar atendimento');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`fixed inset-0 bg-gray-500 bg-opacity-75 ${open ? 'flex' : 'hidden'} z-50`}>
|
||||
<div className="relative bg-white rounded-lg max-w-4xl w-full m-auto p-6 overflow-y-auto max-h-[90vh]">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900">Novo Atendimento</h2>
|
||||
<button onClick={onClose} className="text-gray-400 hover:text-gray-500">
|
||||
<XMarkIcon className="h-6 w-6" /> {/* Alterado para XMarkIcon */}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Busca de Cliente */}
|
||||
<div className="relative">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Cliente
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={searchTerm}
|
||||
onChange={(e) => {
|
||||
setSearchTerm(e.target.value);
|
||||
searchClients(e.target.value);
|
||||
}}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
placeholder="Buscar cliente..."
|
||||
/>
|
||||
|
||||
{searchResults.length > 0 && (
|
||||
<div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-lg shadow-lg">
|
||||
{searchResults.map(client => (
|
||||
<div
|
||||
key={client.id}
|
||||
className="px-4 py-2 hover:bg-gray-100 cursor-pointer"
|
||||
onClick={() => {
|
||||
setSelectedClient(client);
|
||||
setFormData(prev => ({ ...prev, clienteId: client.id }));
|
||||
setSearchTerm(client.nome);
|
||||
setSearchResults([]);
|
||||
}}
|
||||
>
|
||||
<div className="font-medium">{client.nome}</div>
|
||||
<div className="text-sm text-gray-500">{client.cpfCnpj}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tipo de Atendimento */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Tipo de Atendimento
|
||||
</label>
|
||||
<select
|
||||
value={formData.tipo}
|
||||
onChange={(e) => setFormData({ ...formData, tipo: e.target.value as TipoAtendimento })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
>
|
||||
{Object.values(TipoAtendimento).map((tipo) => (
|
||||
<option key={tipo} value={tipo}>
|
||||
{tipo.replace('_', ' ')}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Atendimento Inicial (apenas para tipos diferentes de INICIAL) */}
|
||||
{formData.tipo !== TipoAtendimento.INICIAL && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Atendimento Inicial
|
||||
</label>
|
||||
<select
|
||||
value={formData.atendimentoInicialId}
|
||||
onChange={(e) => setFormData({ ...formData, atendimentoInicialId: e.target.value })}
|
||||
className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
required={formData.tipo !== TipoAtendimento.INICIAL}
|
||||
>
|
||||
<option value="">Selecione um atendimento inicial</option>
|
||||
{atendimentosIniciais.map((atend) => (
|
||||
<option key={atend.id} value={atend.id}>
|
||||
{atend.protocolo} - {atend.titulo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Título do Atendimento"
|
||||
value={formData.titulo}
|
||||
onChange={(e) => setFormData({ ...formData, titulo: e.target.value })}
|
||||
required
|
||||
/>
|
||||
|
||||
{/* Editor de rich text */}
|
||||
<div className="prose max-w-none">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Conteúdo do Atendimento
|
||||
</label>
|
||||
<div className="min-h-[200px] border rounded-lg">
|
||||
<div className="border-b p-2 space-x-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => editor?.chain().focus().toggleBold().run()}
|
||||
className={`px-2 py-1 rounded ${editor?.isActive('bold') ? 'bg-gray-200' : 'hover:bg-gray-100'}`}
|
||||
>
|
||||
Negrito
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => editor?.chain().focus().toggleItalic().run()}
|
||||
className={`px-2 py-1 rounded ${editor?.isActive('italic') ? 'bg-gray-200' : 'hover:bg-gray-100'}`}
|
||||
>
|
||||
Itálico
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
<EditorContent editor={editor} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Upload de anexos */}
|
||||
<div className="mt-4">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-2">
|
||||
Anexos
|
||||
</label>
|
||||
<div
|
||||
{...getRootProps()}
|
||||
className={`mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-md ${
|
||||
isDragActive ? 'border-blue-400 bg-blue-50' : 'border-gray-300'
|
||||
}`}
|
||||
>
|
||||
<div className="space-y-1 text-center">
|
||||
<PaperClipIcon className="mx-auto h-12 w-12 text-gray-400" />
|
||||
<div className="flex text-sm text-gray-600">
|
||||
<input {...getInputProps()} />
|
||||
<p className="pl-1">Arraste arquivos aqui ou clique para selecionar</p>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">Máximo 10MB por arquivo</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Lista de Anexos */}
|
||||
{anexos.length > 0 && (
|
||||
<div className="mt-4">
|
||||
<h4 className="text-sm font-medium text-gray-700">Arquivos para upload</h4>
|
||||
<ul className="mt-2 divide-y divide-gray-200">
|
||||
{anexos.map((anexo, index) => (
|
||||
<li key={index} className="py-3 flex justify-between items-center">
|
||||
<div className="flex items-center">
|
||||
<PaperClipIcon className="h-5 w-5 text-gray-400 mr-2" />
|
||||
<span className="text-sm text-gray-900">{anexo.nome}</span>
|
||||
</div>
|
||||
<div className="flex items-center">
|
||||
{anexo.erro && (
|
||||
<span className="text-xs text-red-500 mr-2">{anexo.erro}</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleRemoveAnexo(index)}
|
||||
className="text-red-500 hover:text-red-700"
|
||||
>
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="p-4 bg-red-50 border-l-4 border-red-500 text-red-700">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Botões de ação dentro do form */}
|
||||
<div className="flex justify-end space-x-4 mt-6 pt-4 border-t">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isSaving}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isSaving ? 'Salvando...' : 'Salvar'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Whitespace-only changes.
@@ -0,0 +1,169 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import api from '../../services/api';
|
||||
import { AtendimentoForm } from './AtendimentoForm';
|
||||
import { AgendamentoCalendario } from './AgendamentoCalendario'; // Adicionar esta importação
|
||||
import { formatRelative } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { TextField, FormControl, InputLabel, Select, MenuItem } from '@mui/material';
|
||||
import { DatePicker } from '@mui/x-date-pickers';
|
||||
import { TipoAtendimento } from '@prisma/client';
|
||||
|
||||
export const AtendimentosPage = () => {
|
||||
const navigate = useNavigate();
|
||||
const [formOpen, setFormOpen] = useState(false);
|
||||
const [filtros, setFiltros] = useState({
|
||||
protocolo: '',
|
||||
dataInicio: null,
|
||||
dataFim: null,
|
||||
tipo: '',
|
||||
clienteId: '',
|
||||
processoId: '',
|
||||
});
|
||||
|
||||
const { data: atendimentos, refetch } = useQuery(['atendimentos', filtros], async () => {
|
||||
const params = new URLSearchParams();
|
||||
if (filtros.protocolo) params.append('protocolo', filtros.protocolo);
|
||||
if (filtros.dataInicio) params.append('dataInicio', filtros.dataInicio.toISOString());
|
||||
if (filtros.dataFim) params.append('dataFim', filtros.dataFim.toISOString());
|
||||
if (filtros.tipo) params.append('tipo', filtros.tipo);
|
||||
if (filtros.clienteId) params.append('clienteId', filtros.clienteId);
|
||||
if (filtros.processoId) params.append('processoId', filtros.processoId);
|
||||
|
||||
const response = await api.get(`/atendimentos?${params}`);
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const handleSave = async (data: any) => {
|
||||
try {
|
||||
await refetch();
|
||||
setFormOpen(false);
|
||||
} catch (error) {
|
||||
console.error('Erro ao atualizar lista:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-7xl mx-auto">
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">Atendimentos</h1>
|
||||
<button
|
||||
onClick={() => setFormOpen(true)}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 dark:hover:bg-blue-500 transition-colors"
|
||||
>
|
||||
Novo Atendimento
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Adicionar Calendário */}
|
||||
<div className="mb-8">
|
||||
<AgendamentoCalendario />
|
||||
</div>
|
||||
|
||||
{/* Filtros */}
|
||||
<div className="bg-white rounded-lg shadow p-6 mb-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<TextField
|
||||
label="Protocolo"
|
||||
value={filtros.protocolo}
|
||||
onChange={(e) => setFiltros({ ...filtros, protocolo: e.target.value })}
|
||||
size="small"
|
||||
/>
|
||||
|
||||
<DatePicker
|
||||
label="Data Início"
|
||||
value={filtros.dataInicio}
|
||||
onChange={(date) => setFiltros({ ...filtros, dataInicio: date })}
|
||||
slotProps={{ textField: { size: 'small' } }}
|
||||
/>
|
||||
|
||||
<DatePicker
|
||||
label="Data Fim"
|
||||
value={filtros.dataFim}
|
||||
onChange={(date) => setFiltros({ ...filtros, dataFim: date })}
|
||||
slotProps={{ textField: { size: 'small' } }}
|
||||
/>
|
||||
|
||||
<FormControl size="small">
|
||||
<InputLabel>Tipo</InputLabel>
|
||||
<Select
|
||||
value={filtros.tipo}
|
||||
label="Tipo"
|
||||
onChange={(e) => setFiltros({ ...filtros, tipo: e.target.value })}
|
||||
>
|
||||
<MenuItem value="">Todos</MenuItem>
|
||||
{Object.values(TipoAtendimento).map((tipo) => (
|
||||
<MenuItem key={tipo} value={tipo}>
|
||||
{tipo.replace('_', ' ')}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{atendimentos?.map((atendimento: any) => (
|
||||
<div
|
||||
key={atendimento.id}
|
||||
className={`bg-white dark:bg-gray-800 rounded-lg shadow p-6 cursor-pointer hover:shadow-lg transition-shadow ${
|
||||
atendimento.status === 'CANCELADO' ? 'border-l-4 border-red-500' : ''
|
||||
}`}
|
||||
onClick={() => navigate(`/atendimentos/${atendimento.id}`)}
|
||||
>
|
||||
<div className="flex justify-between items-start">
|
||||
<div>
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-lg font-medium text-gray-900 dark:text-white">{atendimento.titulo}</h2>
|
||||
{atendimento.status === 'CANCELADO' && (
|
||||
<span className="px-2 py-1 bg-red-100 text-red-800 text-xs rounded-full">
|
||||
Cancelado
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Protocolo: {atendimento.protocolo}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`px-3 py-1 rounded-full text-sm font-medium ${
|
||||
atendimento.tipo === 'INICIAL' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
|
||||
}`}>
|
||||
{atendimento.tipo}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-4 prose max-w-none" dangerouslySetInnerHTML={{ __html: atendimento.conteudo }} />
|
||||
<div className="mt-4 flex justify-between items-center text-sm text-gray-500 dark:text-gray-400">
|
||||
<span>
|
||||
{formatRelative(new Date(atendimento.dataAtendimento), new Date(), { locale: ptBR })}
|
||||
</span>
|
||||
<div className="flex items-center gap-4">
|
||||
{atendimento.status === 'CANCELADO' && (
|
||||
<span className="text-red-600 text-sm">
|
||||
Motivo: {atendimento.justificativaCancelamento}
|
||||
</span>
|
||||
)}
|
||||
{atendimento.anexos?.length > 0 && (
|
||||
<span className="flex items-center">
|
||||
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
|
||||
</svg>
|
||||
{atendimento.anexos.length} anexos
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<AtendimentoForm
|
||||
open={formOpen}
|
||||
onClose={() => setFormOpen(false)}
|
||||
onSave={handleSave}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,274 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { format } from 'date-fns';
|
||||
import ptBR from 'date-fns/locale/pt-BR';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
|
||||
interface Calculo {
|
||||
id: string;
|
||||
titulo: string;
|
||||
status: string;
|
||||
valorBase: string;
|
||||
valorFinal: string;
|
||||
dataBase: string;
|
||||
dataCalculo: string;
|
||||
criadoEm: string;
|
||||
usuario: {
|
||||
nome: string;
|
||||
};
|
||||
processo?: {
|
||||
numero: string;
|
||||
titulo: string;
|
||||
};
|
||||
cliente?: {
|
||||
nome: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function CalculosList() {
|
||||
const { user, isAuthenticated, getToken } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [calculos, setCalculos] = useState<Calculo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [filtro, setFiltro] = useState({
|
||||
titulo: '',
|
||||
status: '',
|
||||
processoId: '',
|
||||
clienteId: ''
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Verificar autenticação antes de carregar os dados
|
||||
if (isAuthenticated) {
|
||||
carregarCalculos();
|
||||
} else {
|
||||
// Redirecionar para login caso não esteja autenticado
|
||||
navigate('/login');
|
||||
}
|
||||
}, [isAuthenticated, navigate]);
|
||||
|
||||
const carregarCalculos = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Construir query string baseado nos filtros
|
||||
const queryParams = new URLSearchParams();
|
||||
if (filtro.titulo) queryParams.append('titulo', filtro.titulo);
|
||||
if (filtro.status) queryParams.append('status', filtro.status);
|
||||
if (filtro.processoId) queryParams.append('processoId', filtro.processoId);
|
||||
if (filtro.clienteId) queryParams.append('clienteId', filtro.clienteId);
|
||||
|
||||
// Obter token de autenticação usando o contexto
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
throw new Error('Usuário não autenticado. Faça login novamente.');
|
||||
}
|
||||
|
||||
// Incluir o token no cabeçalho da requisição
|
||||
const response = await fetch(`/api/calculos?${queryParams.toString()}`, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
// Se receber 401, o token pode estar expirado
|
||||
navigate('/login');
|
||||
throw new Error('Sessão expirada. Por favor, faça login novamente.');
|
||||
}
|
||||
throw new Error('Erro ao carregar cálculos');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setCalculos(data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar cálculos:', error);
|
||||
toast.error(`Falha ao carregar os cálculos: ${error.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFiltroChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFiltro(prev => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
const handleSubmitFiltro = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
carregarCalculos();
|
||||
};
|
||||
|
||||
// Função para formatar valores monetários
|
||||
const formatarValor = (valor: string) => {
|
||||
return new Intl.NumberFormat('pt-BR', {
|
||||
style: 'currency',
|
||||
currency: 'BRL'
|
||||
}).format(parseFloat(valor));
|
||||
};
|
||||
|
||||
// Função para formatar datas
|
||||
const formatarData = (data: string) => {
|
||||
try {
|
||||
return format(new Date(data), 'dd/MM/yyyy', { locale: ptBR });
|
||||
} catch (error) {
|
||||
return 'Data inválida';
|
||||
}
|
||||
};
|
||||
|
||||
// Status Badge
|
||||
const StatusBadge = ({ status }: { status: string }) => {
|
||||
const getStatusColor = () => {
|
||||
switch (status) {
|
||||
case 'RASCUNHO':
|
||||
return 'bg-yellow-100 text-yellow-800';
|
||||
case 'FINALIZADO':
|
||||
return 'bg-green-100 text-green-800';
|
||||
case 'ARQUIVADO':
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
default:
|
||||
return 'bg-blue-100 text-blue-800';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor()}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container mx-auto px-4 py-8">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Cálculos Judiciais</h1>
|
||||
<Link
|
||||
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>
|
||||
</div>
|
||||
|
||||
{/* Filtros */}
|
||||
<div className="bg-white shadow rounded-lg mb-6 p-4">
|
||||
<h2 className="text-lg font-medium text-gray-700 mb-3">Filtros</h2>
|
||||
<form onSubmit={handleSubmitFiltro} className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
<div>
|
||||
<label htmlFor="titulo" className="block text-sm font-medium text-gray-700">
|
||||
Título
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
name="titulo"
|
||||
id="titulo"
|
||||
value={filtro.titulo}
|
||||
onChange={handleFiltroChange}
|
||||
className="mt-1 focus:ring-blue-500 focus:border-blue-500 block w-full shadow-sm sm:text-sm border-gray-300 rounded-md"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="status" className="block text-sm font-medium text-gray-700">
|
||||
Status
|
||||
</label>
|
||||
<select
|
||||
id="status"
|
||||
name="status"
|
||||
value={filtro.status}
|
||||
onChange={handleFiltroChange}
|
||||
className="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Todos</option>
|
||||
<option value="RASCUNHO">Rascunho</option>
|
||||
<option value="FINALIZADO">Finalizado</option>
|
||||
<option value="ARQUIVADO">Arquivado</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="sm:col-span-2 flex justify-end items-end">
|
||||
<button
|
||||
type="submit"
|
||||
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"
|
||||
>
|
||||
Filtrar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Lista de Cálculos */}
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="spinner-border animate-spin inline-block w-8 h-8 border-4 rounded-full text-blue-600" role="status">
|
||||
<span className="visually-hidden">Carregando...</span>
|
||||
</div>
|
||||
</div>
|
||||
) : calculos.length === 0 ? (
|
||||
<div className="bg-white shadow rounded-lg p-8 text-center">
|
||||
<h3 className="text-lg font-medium text-gray-900">Nenhum cálculo encontrado</h3>
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Para criar um novo cálculo, clique no botão "Novo Cálculo".
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white shadow overflow-hidden sm:rounded-md">
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{calculos.map((calculo) => (
|
||||
<li key={calculo.id}>
|
||||
<Link to={`/calculos/${calculo.id}`} className="block hover:bg-gray-50">
|
||||
<div className="px-4 py-4 sm:px-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<p className="text-base font-medium text-blue-600 truncate">
|
||||
{calculo.titulo}
|
||||
</p>
|
||||
<StatusBadge status={calculo.status} />
|
||||
</div>
|
||||
<div className="ml-2 flex-shrink-0 flex">
|
||||
<p className="px-2 inline-flex text-sm leading-5 font-medium rounded-full bg-blue-100 text-blue-800">
|
||||
{formatarValor(calculo.valorFinal)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-2 sm:flex sm:justify-between">
|
||||
<div className="sm:flex">
|
||||
<p className="flex items-center text-sm text-gray-500">
|
||||
Base: {formatarValor(calculo.valorBase)}
|
||||
</p>
|
||||
<p className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0 sm:ml-6">
|
||||
Data Base: {formatarData(calculo.dataBase)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="mt-2 flex items-center text-sm text-gray-500 sm:mt-0">
|
||||
<p>
|
||||
Criado em: {formatarData(calculo.criadoEm)} por {calculo.usuario.nome}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{calculo.processo && (
|
||||
<div className="mt-2">
|
||||
<p className="text-sm text-gray-600">
|
||||
Processo: {calculo.processo.numero} - {calculo.processo.titulo}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
{calculo.cliente && (
|
||||
<div className="mt-1">
|
||||
<p className="text-sm text-gray-600">
|
||||
Cliente: {calculo.cliente.nome}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { toast } from 'react-toastify';
|
||||
import api from '../../services/api';
|
||||
|
||||
interface CalculoPensao {
|
||||
id: string;
|
||||
titulo: string;
|
||||
descricao?: string;
|
||||
dataInicial: string;
|
||||
dataFinal?: string;
|
||||
percentualSalarioMinimo: number;
|
||||
multaPactuada?: number;
|
||||
tipoAtualizacao: string;
|
||||
valorCalculado: number;
|
||||
valorMulta: number;
|
||||
valorTotal: number;
|
||||
observacoes?: string;
|
||||
processo?: {
|
||||
numero: string;
|
||||
titulo: string;
|
||||
};
|
||||
cliente?: {
|
||||
nome: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function DetalhePensaoAlimenticia() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [calculo, setCalculo] = useState<CalculoPensao | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const loadCalculo = async () => {
|
||||
try {
|
||||
const response = await api.get(`/pensao-alimenticia/${id}`);
|
||||
setCalculo(response.data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar cálculo:', error);
|
||||
toast.error('Falha ao carregar dados do cálculo');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadCalculo();
|
||||
}, [id]);
|
||||
|
||||
if (loading) {
|
||||
return <div>Carregando...</div>;
|
||||
}
|
||||
|
||||
if (!calculo) {
|
||||
return <div>Cálculo não encontrado</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white shadow-md rounded-lg p-6">
|
||||
<h1 className="text-2xl font-bold mb-4">{calculo.titulo}</h1>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-2">Dados do Cálculo</h2>
|
||||
<div className="space-y-2">
|
||||
<p><span className="font-medium">Data Inicial:</span> {new Date(calculo.dataInicial).toLocaleDateString()}</p>
|
||||
{calculo.dataFinal && (
|
||||
<p><span className="font-medium">Data Final:</span> {new Date(calculo.dataFinal).toLocaleDateString()}</p>
|
||||
)}
|
||||
<p><span className="font-medium">Percentual:</span> {calculo.percentualSalarioMinimo}%</p>
|
||||
{calculo.multaPactuada && (
|
||||
<p><span className="font-medium">Multa:</span> {calculo.multaPactuada}%</p>
|
||||
)}
|
||||
<p><span className="font-medium">Índice:</span> {calculo.tipoAtualizacao}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold mb-2">Valores</h2>
|
||||
<div className="space-y-2">
|
||||
<p><span className="font-medium">Valor Base:</span> R$ {calculo.valorCalculado.toFixed(2)}</p>
|
||||
<p><span className="font-medium">Valor Multa:</span> R$ {calculo.valorMulta.toFixed(2)}</p>
|
||||
<p><span className="font-medium">Valor Total:</span> R$ {calculo.valorTotal.toFixed(2)}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{calculo.observacoes && (
|
||||
<div className="mt-6">
|
||||
<h2 className="text-lg font-semibold mb-2">Observações</h2>
|
||||
<p className="text-gray-700">{calculo.observacoes}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,315 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { toast } from 'react-toastify';
|
||||
import { formatarMoeda, parseMoeda } from '../../utils/formatters';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
|
||||
interface ProcessoOption {
|
||||
id: string;
|
||||
numero: string;
|
||||
titulo: string;
|
||||
}
|
||||
|
||||
interface ClienteOption {
|
||||
id: string;
|
||||
nome: string;
|
||||
}
|
||||
|
||||
export function NovoCalculo() {
|
||||
const navigate = useNavigate();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { getToken } = useAuth();
|
||||
const valorBaseRef = useRef<HTMLInputElement>(null);
|
||||
const [formData, setFormData] = useState({
|
||||
titulo: '',
|
||||
descricao: '',
|
||||
dataBase: new Date().toISOString().split('T')[0],
|
||||
valorBase: '',
|
||||
processoId: '',
|
||||
clienteId: '',
|
||||
});
|
||||
|
||||
const [processos, setProcessos] = useState<ProcessoOption[]>([]);
|
||||
const [clientes, setClientes] = useState<ClienteOption[]>([]);
|
||||
|
||||
// Carregar processos e clientes ao montar o componente
|
||||
useEffect(() => {
|
||||
const carregarDados = async () => {
|
||||
try {
|
||||
// Carregar processos
|
||||
const processosResponse = await fetch('/api/processos');
|
||||
if (processosResponse.ok) {
|
||||
const processosData = await processosResponse.json();
|
||||
setProcessos(processosData);
|
||||
}
|
||||
|
||||
// Carregar clientes
|
||||
const clientesResponse = await fetch('/api/clientes');
|
||||
if (clientesResponse.ok) {
|
||||
const clientesData = await clientesResponse.json();
|
||||
setClientes(clientesData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
toast.error('Falha ao carregar dados auxiliares');
|
||||
}
|
||||
};
|
||||
|
||||
carregarDados();
|
||||
}, []);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Handler específico para campos monetários com controle de cursor
|
||||
const handleMoneyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
|
||||
// Salvar a posição atual do cursor antes da formatação
|
||||
const cursorPosition = e.target.selectionStart;
|
||||
const prevLength = e.target.value.length;
|
||||
|
||||
// Remover caracteres não numéricos, exceto vírgula e ponto
|
||||
const numericValue = value.replace(/[^\d.,]/g, '');
|
||||
|
||||
// Formatar como moeda
|
||||
const formattedValue = formatarMoeda(numericValue);
|
||||
|
||||
setFormData(prev => ({ ...prev, [name]: formattedValue }));
|
||||
|
||||
// Usar setTimeout para ajustar a posição do cursor após a atualização do DOM
|
||||
setTimeout(() => {
|
||||
if (valorBaseRef.current) {
|
||||
// Calcular a nova posição considerando a mudança no comprimento
|
||||
const lengthDifference = formattedValue.length - prevLength;
|
||||
const newPosition = Math.max(0, (cursorPosition || 0) + lengthDifference);
|
||||
|
||||
// Definir o cursor na posição calculada
|
||||
valorBaseRef.current.setSelectionRange(newPosition, newPosition);
|
||||
}
|
||||
}, 0);
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
// Validar dados
|
||||
if (!formData.titulo || !formData.dataBase || !formData.valorBase) {
|
||||
toast.error('Preencha todos os campos obrigatórios');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Converter valor para número
|
||||
const valorBaseNumerico = parseMoeda(formData.valorBase);
|
||||
if (isNaN(valorBaseNumerico) || valorBaseNumerico <= 0) {
|
||||
toast.error('Valor base inválido. Informe um valor maior que zero');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Preparar dados para envio
|
||||
const dadosParaEnviar = {
|
||||
...formData,
|
||||
valorBase: valorBaseNumerico
|
||||
};
|
||||
|
||||
// Obter token de autenticação usando o contexto
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
throw new Error('Usuário não autenticado. Faça login novamente.');
|
||||
}
|
||||
|
||||
// Enviar solicitação para criar cálculo com cabeçalho de autorização
|
||||
const response = await fetch('/api/calculos', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${token}`
|
||||
},
|
||||
body: JSON.stringify(dadosParaEnviar),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Erro ao criar cálculo');
|
||||
}
|
||||
|
||||
const resultado = await response.json();
|
||||
|
||||
toast.success('Cálculo criado com sucesso!');
|
||||
|
||||
// Redirecionar para a página do cálculo criado
|
||||
navigate(`/calculos/${resultado.id}`);
|
||||
} catch (error) {
|
||||
console.error('Erro ao criar cálculo:', error);
|
||||
toast.error(`Falha ao criar cálculo: ${error.message}`);
|
||||
|
||||
if (error.message?.includes('autenticação') ||
|
||||
error.message?.includes('não autenticado') ||
|
||||
error.response?.status === 401) {
|
||||
// Se for erro de autenticação, redirecionar para login
|
||||
navigate('/login');
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto bg-white shadow-md rounded-lg overflow-hidden">
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 px-6 py-4 text-white">
|
||||
<h1 className="text-xl font-bold">Novo Cálculo Judicial</h1>
|
||||
<p className="text-sm text-blue-100 mt-1">Preencha os dados básicos para criar um novo cálculo</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Título */}
|
||||
<div className="col-span-2">
|
||||
<label htmlFor="titulo" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Título <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="titulo"
|
||||
name="titulo"
|
||||
value={formData.titulo}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="Ex: Cálculo de Danos Morais - Processo nº 12345"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Data Base */}
|
||||
<div>
|
||||
<label htmlFor="dataBase" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Data Base <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
id="dataBase"
|
||||
name="dataBase"
|
||||
value={formData.dataBase}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
required
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">Data de referência para iniciar o cálculo</p>
|
||||
</div>
|
||||
|
||||
{/* Valor Base */}
|
||||
<div>
|
||||
<label htmlFor="valorBase" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Valor Base <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
|
||||
<span className="text-gray-500 sm:text-sm">R$</span>
|
||||
</div>
|
||||
<input
|
||||
type="text"
|
||||
id="valorBase"
|
||||
name="valorBase"
|
||||
value={formData.valorBase}
|
||||
onChange={handleMoneyChange}
|
||||
ref={valorBaseRef}
|
||||
className="block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="0,00"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">Valor inicial para o cálculo</p>
|
||||
</div>
|
||||
|
||||
{/* Processo */}
|
||||
<div>
|
||||
<label htmlFor="processoId" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Processo
|
||||
</label>
|
||||
<select
|
||||
id="processoId"
|
||||
name="processoId"
|
||||
value={formData.processoId}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Selecione um processo (opcional)</option>
|
||||
{processos.map(processo => (
|
||||
<option key={processo.id} value={processo.id}>
|
||||
{processo.numero} - {processo.titulo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Cliente */}
|
||||
<div>
|
||||
<label htmlFor="clienteId" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Cliente
|
||||
</label>
|
||||
<select
|
||||
id="clienteId"
|
||||
name="clienteId"
|
||||
value={formData.clienteId}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Selecione um cliente (opcional)</option>
|
||||
{clientes.map(cliente => (
|
||||
<option key={cliente.id} value={cliente.id}>
|
||||
{cliente.nome}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Descrição */}
|
||||
<div className="col-span-2">
|
||||
<label htmlFor="descricao" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Descrição
|
||||
</label>
|
||||
<textarea
|
||||
id="descricao"
|
||||
name="descricao"
|
||||
value={formData.descricao}
|
||||
onChange={handleChange}
|
||||
rows={4}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="Descrição detalhada do cálculo (opcional)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/calculos')}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 flex items-center"
|
||||
>
|
||||
{loading && (
|
||||
<svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)}
|
||||
{loading ? 'Criando...' : 'Criar Cálculo'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { toast } from 'react-toastify';
|
||||
import { formatarPercentual, parsePercentual } from '../../utils/formatters';
|
||||
|
||||
interface ProcessoOption {
|
||||
id: string;
|
||||
numero: string;
|
||||
titulo: string;
|
||||
}
|
||||
|
||||
interface ClienteOption {
|
||||
id: string;
|
||||
nome: string;
|
||||
}
|
||||
|
||||
export function NovoPensaoAlimenticia() {
|
||||
const navigate = useNavigate();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
titulo: '',
|
||||
descricao: '',
|
||||
dataInicial: new Date().toISOString().split('T')[0],
|
||||
dataFinal: '',
|
||||
percentualSalarioMinimo: '',
|
||||
multaPactuada: '',
|
||||
tipoAtualizacao: 'INPC',
|
||||
processoId: '',
|
||||
clienteId: '',
|
||||
observacoes: '',
|
||||
});
|
||||
|
||||
const [processos, setProcessos] = useState<ProcessoOption[]>([]);
|
||||
const [clientes, setClientes] = useState<ClienteOption[]>([]);
|
||||
|
||||
// Carregar processos e clientes ao montar o componente
|
||||
useEffect(() => {
|
||||
const carregarDados = async () => {
|
||||
try {
|
||||
// Carregar processos
|
||||
const processosResponse = await fetch('/api/processos');
|
||||
if (processosResponse.ok) {
|
||||
const processosData = await processosResponse.json();
|
||||
setProcessos(processosData);
|
||||
}
|
||||
|
||||
// Carregar clientes
|
||||
const clientesResponse = await fetch('/api/clientes');
|
||||
if (clientesResponse.ok) {
|
||||
const clientesData = await clientesResponse.json();
|
||||
setClientes(clientesData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
toast.error('Falha ao carregar dados auxiliares');
|
||||
}
|
||||
};
|
||||
|
||||
carregarDados();
|
||||
}, []);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData(prev => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Handler para campos percentuais
|
||||
const handlePercentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
// Remover caracteres não numéricos, exceto vírgula e ponto
|
||||
const numericValue = value.replace(/[^\d.,]/g, '');
|
||||
// Formatar como percentual
|
||||
const formattedValue = formatarPercentual(numericValue);
|
||||
setFormData(prev => ({ ...prev, [name]: formattedValue }));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
// Validar dados
|
||||
if (!formData.titulo || !formData.dataInicial || !formData.percentualSalarioMinimo) {
|
||||
toast.error('Preencha todos os campos obrigatórios');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Converter percentual para decimal (formato 0.XX)
|
||||
const percentual = parsePercentual(formData.percentualSalarioMinimo);
|
||||
|
||||
// Verificar se percentual é válido
|
||||
if (isNaN(percentual) || percentual <= 0 || percentual > 1) {
|
||||
toast.error('Percentual do salário mínimo deve ser maior que 0 e menor ou igual a 100%');
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Preparar dados para envio
|
||||
const dadosParaEnviar = {
|
||||
...formData,
|
||||
percentualSalarioMinimo: percentual,
|
||||
multaPactuada: formData.multaPactuada ? parsePercentual(formData.multaPactuada) : undefined,
|
||||
};
|
||||
|
||||
// Enviar solicitação para criar cálculo
|
||||
const response = await fetch('/api/pensao-alimenticia', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(dadosParaEnviar),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || 'Erro ao criar cálculo de pensão alimentícia');
|
||||
}
|
||||
|
||||
const resultado = await response.json();
|
||||
|
||||
toast.success('Cálculo de pensão alimentícia criado com sucesso!');
|
||||
|
||||
// Redirecionar para a página do cálculo criado
|
||||
navigate(`/pensao-alimenticia/${resultado.id}`);
|
||||
} catch (error) {
|
||||
console.error('Erro ao criar cálculo de pensão:', error);
|
||||
toast.error(`Falha ao criar cálculo: ${error.message}`);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-4xl mx-auto bg-white shadow-md rounded-lg overflow-hidden">
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 px-6 py-4 text-white">
|
||||
<h1 className="text-xl font-bold">Novo Cálculo de Pensão Alimentícia</h1>
|
||||
<p className="text-sm text-blue-100 mt-1">Preencha os dados para criar um novo cálculo de pensão alimentícia</p>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="p-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
{/* Título */}
|
||||
<div className="col-span-2">
|
||||
<label htmlFor="titulo" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Título <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
id="titulo"
|
||||
name="titulo"
|
||||
value={formData.titulo}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="Ex: Pensão Alimentícia - João da Silva"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Índice de Atualização */}
|
||||
<div>
|
||||
<label htmlFor="tipoAtualizacao" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Índice de Atualização Monetária
|
||||
</label>
|
||||
<select
|
||||
id="tipoAtualizacao"
|
||||
name="tipoAtualizacao"
|
||||
value={formData.tipoAtualizacao}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="INPC">INPC (Índice Nacional de Preços ao Consumidor)</option>
|
||||
<option value="IPCA">IPCA (Índice Nacional de Preços ao Consumidor Amplo)</option>
|
||||
<option value="IGPM">IGP-M (Índice Geral de Preços do Mercado)</option>
|
||||
<option value="SELIC">SELIC (Sistema Especial de Liquidação e Custódia)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Percentual do Salário Mínimo */}
|
||||
<div>
|
||||
<label htmlFor="percentualSalarioMinimo" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Percentual do Salário Mínimo <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
id="percentualSalarioMinimo"
|
||||
name="percentualSalarioMinimo"
|
||||
value={formData.percentualSalarioMinimo}
|
||||
onChange={handlePercentChange}
|
||||
className="block w-full pr-10 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="30,00%"
|
||||
required
|
||||
/>
|
||||
<div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
|
||||
<span className="text-gray-500 sm:text-sm">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">Ex: 30% = 30,00%</p>
|
||||
</div>
|
||||
|
||||
{/* Data Inicial */}
|
||||
<div>
|
||||
<label htmlFor="dataInicial" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Data Inicial <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
id="dataInicial"
|
||||
name="dataInicial"
|
||||
value={formData.dataInicial}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
required
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">Data de início da pensão</p>
|
||||
</div>
|
||||
|
||||
{/* Data Final */}
|
||||
<div>
|
||||
<label htmlFor="dataFinal" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Data Final
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
id="dataFinal"
|
||||
name="dataFinal"
|
||||
value={formData.dataFinal}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
/>
|
||||
<p className="mt-1 text-xs text-gray-500">Deixe em branco se a pensão não tem data final</p>
|
||||
</div>
|
||||
|
||||
{/* Multa Pactuada */}
|
||||
<div>
|
||||
<label htmlFor="multaPactuada" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Multa Pactuada por Atraso
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
id="multaPactuada"
|
||||
name="multaPactuada"
|
||||
value={formData.multaPactuada}
|
||||
onChange={handlePercentChange}
|
||||
className="block w-full pr-10 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="10,00%"
|
||||
/>
|
||||
<div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
|
||||
<span className="text-gray-500 sm:text-sm">%</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-gray-500">Ex: 10% = 10,00%. Deixe em branco se não houver.</p>
|
||||
</div>
|
||||
|
||||
{/* Processo */}
|
||||
<div>
|
||||
<label htmlFor="processoId" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Processo
|
||||
</label>
|
||||
<select
|
||||
id="processoId"
|
||||
name="processoId"
|
||||
value={formData.processoId}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Selecione um processo (opcional)</option>
|
||||
{processos.map(processo => (
|
||||
<option key={processo.id} value={processo.id}>
|
||||
{processo.numero} - {processo.titulo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Cliente */}
|
||||
<div>
|
||||
<label htmlFor="clienteId" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Cliente
|
||||
</label>
|
||||
<select
|
||||
id="clienteId"
|
||||
name="clienteId"
|
||||
value={formData.clienteId}
|
||||
onChange={handleChange}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
>
|
||||
<option value="">Selecione um cliente (opcional)</option>
|
||||
{clientes.map(cliente => (
|
||||
<option key={cliente.id} value={cliente.id}>
|
||||
{cliente.nome}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Observações */}
|
||||
<div className="col-span-2">
|
||||
<label htmlFor="observacoes" className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Observações
|
||||
</label>
|
||||
<textarea
|
||||
id="observacoes"
|
||||
name="observacoes"
|
||||
value={formData.observacoes}
|
||||
onChange={handleChange}
|
||||
rows={4}
|
||||
className="block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
|
||||
placeholder="Informações adicionais sobre o cálculo (opcional)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate('/calculos')}
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 flex items-center"
|
||||
>
|
||||
{loading && (
|
||||
<svg className="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
)}
|
||||
{loading ? 'Criando...' : 'Criar Cálculo de Pensão'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import React, { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useClientes } from "../../hooks/useClientes";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
PencilIcon,
|
||||
UserIcon,
|
||||
HomeIcon,
|
||||
BanknotesIcon,
|
||||
UserGroupIcon,
|
||||
DocumentTextIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ClienteModal } from "./ClienteModal";
|
||||
import {
|
||||
formatCPF,
|
||||
formatTelefone,
|
||||
formatNome,
|
||||
formatEmail,
|
||||
formatMoeda,
|
||||
formatTextoSimples,
|
||||
formatData,
|
||||
} from "../../utils/formatters";
|
||||
|
||||
function classNames(...classes: string[]) {
|
||||
return classes.filter(Boolean).join(" ");
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ id: "info", name: "Informações Básicas", icon: UserIcon },
|
||||
{ id: "endereco", name: "Endereço", icon: HomeIcon },
|
||||
{ id: "financeiro", name: "Informações Financeiras", icon: BanknotesIcon },
|
||||
{ id: "familia", name: "Informações Familiares", icon: UserGroupIcon },
|
||||
{ id: "processos", name: "Processos", icon: DocumentTextIcon },
|
||||
];
|
||||
|
||||
interface InfoItemProps {
|
||||
label: string;
|
||||
value: string;
|
||||
onEdit?: () => void;
|
||||
isEditable?: boolean;
|
||||
}
|
||||
|
||||
const InfoItem: React.FC<InfoItemProps> = ({
|
||||
label,
|
||||
value,
|
||||
onEdit,
|
||||
isEditable = true,
|
||||
}) => (
|
||||
<div className="relative group">
|
||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900 flex items-center justify-between">
|
||||
<span>{value}</span>
|
||||
{isEditable && (
|
||||
<button
|
||||
onClick={onEdit}
|
||||
className="opacity-0 group-hover:opacity-100 transition-opacity p-1 hover:bg-gray-100 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4 text-blue-600" />
|
||||
</button>
|
||||
)}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const ClienteDetalhes: React.FC = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { clientes, isLoading } = useClientes();
|
||||
const [selectedTab, setSelectedTab] = useState(0);
|
||||
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
|
||||
const [editingField, setEditingField] = useState<string | null>(null);
|
||||
const cliente = clientes.find((c) => c.id === id);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!cliente) {
|
||||
return <div>Cliente não encontrado</div>;
|
||||
}
|
||||
|
||||
// Funções de formatação simplificadas
|
||||
const formataCurrency = (valor: any): string => {
|
||||
if (!valor) return "Não informado";
|
||||
try {
|
||||
return new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(Number(valor));
|
||||
} catch {
|
||||
return "Não informado";
|
||||
}
|
||||
};
|
||||
|
||||
const formataTexto = (texto: any): string => {
|
||||
if (!texto && texto !== false) return "Não informado";
|
||||
if (typeof texto === "boolean") return texto ? "Sim" : "Não";
|
||||
return String(texto);
|
||||
};
|
||||
|
||||
const getTabForField = (field: string | null) => {
|
||||
switch (field) {
|
||||
case "nome":
|
||||
case "cpfCnpj":
|
||||
case "rg":
|
||||
case "email":
|
||||
case "telefone":
|
||||
case "instagram":
|
||||
case "estadoCivil":
|
||||
case "dataNascimento":
|
||||
return 0;
|
||||
case "cep":
|
||||
case "endereco":
|
||||
case "complemento":
|
||||
case "bairro":
|
||||
case "cidade":
|
||||
case "estado":
|
||||
return 1;
|
||||
case "profissao":
|
||||
case "vinculoEmpregaticio":
|
||||
case "renda":
|
||||
case "declaraIR":
|
||||
case "tipoPrevidencia":
|
||||
case "contribuiPrevidencia":
|
||||
return 2;
|
||||
case "nomePai":
|
||||
case "nomeMae":
|
||||
case "conjugeNome":
|
||||
case "conjugeCpf":
|
||||
return 3;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<button
|
||||
onClick={() => navigate("/clientes")}
|
||||
className="p-2 hover:bg-gray-100 rounded-full"
|
||||
>
|
||||
<ArrowLeftIcon className="h-5 w-5 text-gray-500" />
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold text-gray-800">
|
||||
{formatNome(cliente.nome)}
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">
|
||||
Cadastrado em {new Date(cliente.dataCriacao).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setIsEditModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4 mr-2" />
|
||||
Editar
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<Tab.Group selectedIndex={selectedTab} onChange={setSelectedTab}>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-blue-900/20 p-1">
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
key={tab.id}
|
||||
className={({ selected }) =>
|
||||
classNames(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5",
|
||||
"flex items-center justify-center",
|
||||
selected
|
||||
? "bg-white text-blue-700 shadow"
|
||||
: "text-gray-600 hover:bg-white/[0.12] hover:text-blue-600",
|
||||
)
|
||||
}
|
||||
>
|
||||
<tab.icon className="h-4 w-4 mr-2" />
|
||||
{tab.name}
|
||||
</Tab>
|
||||
))}
|
||||
</Tab.List>
|
||||
<Tab.Panels className="mt-2">
|
||||
{/* Informações Básicas */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<InfoItem
|
||||
label="Nome"
|
||||
value={formatNome(cliente.nome)}
|
||||
onEdit={() => {
|
||||
setEditingField("nome");
|
||||
setIsEditModalOpen(true);
|
||||
}}
|
||||
/>
|
||||
<InfoItem
|
||||
label="CPF/CNPJ"
|
||||
value={formatCPF(cliente.cpfCnpj)}
|
||||
onEdit={() => {
|
||||
setEditingField("cpfCnpj");
|
||||
setIsEditModalOpen(true);
|
||||
}}
|
||||
/>
|
||||
<InfoItem label="RG" value={formatTextoSimples(cliente.rg)} />
|
||||
<InfoItem label="Email" value={formatEmail(cliente.email)} />
|
||||
<InfoItem
|
||||
label="Telefone"
|
||||
value={formatTelefone(cliente.telefone)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Instagram"
|
||||
value={formatTextoSimples(cliente.instagram)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Estado Civil"
|
||||
value={formatTextoSimples(cliente.estadoCivil)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Data de Nascimento"
|
||||
value={formatData(cliente.dataNascimento)}
|
||||
/>
|
||||
</dl>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Endereço */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<InfoItem label="CEP" value={formataTexto(cliente.cep)} />
|
||||
<InfoItem
|
||||
label="Endereço"
|
||||
value={formataTexto(`${cliente.endereco}, ${cliente.numero}`)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Complemento"
|
||||
value={formataTexto(cliente.complemento)}
|
||||
/>
|
||||
<InfoItem label="Bairro" value={formataTexto(cliente.bairro)} />
|
||||
<InfoItem label="Cidade" value={formataTexto(cliente.cidade)} />
|
||||
<InfoItem label="Estado" value={formataTexto(cliente.estado)} />
|
||||
</dl>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Informações Financeiras */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<InfoItem
|
||||
label="Profissão"
|
||||
value={formatTextoSimples(cliente.profissao)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Vínculo"
|
||||
value={formatTextoSimples(cliente.vinculoEmpregaticio)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Renda Mensal"
|
||||
value={formatMoeda(Number(cliente.renda))}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Declara IR"
|
||||
value={cliente.declaraIR ? "Sim" : "Não"}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Tipo Previdência"
|
||||
value={formatTextoSimples(cliente.tipoPrevidencia)}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Contribui Previdência"
|
||||
value={cliente.contribuiPrevidencia ? "Sim" : "Não"}
|
||||
/>
|
||||
</dl>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Informações Familiares */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<InfoItem
|
||||
label="Nome do Pai"
|
||||
value={formatNome(cliente.nomePai || "")}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Nome da Mãe"
|
||||
value={formatNome(cliente.nomeMae || "")}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Nome do Cônjuge"
|
||||
value={formatNome(cliente.conjugeNome || "")}
|
||||
/>
|
||||
<InfoItem
|
||||
label="CPF do Cônjuge"
|
||||
value={
|
||||
cliente.conjugeCpf
|
||||
? formatCPF(cliente.conjugeCpf)
|
||||
: "Não informado"
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Lista de Filhos */}
|
||||
<div>
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Filhos
|
||||
</h3>
|
||||
{cliente.filhos && cliente.filhos.length > 0 ? (
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{cliente.filhos.map((filho) => (
|
||||
<li key={filho.id} className="py-3">
|
||||
<p className="text-sm font-medium text-gray-900">
|
||||
{filho.nome}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Nascimento:{" "}
|
||||
{new Date(filho.dataNascimento).toLocaleDateString()}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum filho cadastrado
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Processos */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
{cliente.processos && cliente.processos.length > 0 ? (
|
||||
<ul className="divide-y divide-gray-200">
|
||||
{cliente.processos.map((processo) => (
|
||||
<li key={processo.id} className="py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900">
|
||||
{processo.titulo}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
Nº {processo.numero}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className={classNames(
|
||||
"px-2 py-1 text-xs rounded-full",
|
||||
processo.status === "em_andamento"
|
||||
? "bg-blue-100 text-blue-800"
|
||||
: processo.status === "concluido"
|
||||
? "bg-green-100 text-green-800"
|
||||
: "bg-gray-100 text-gray-800",
|
||||
)}
|
||||
>
|
||||
{processo.status}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
Nenhum processo cadastrado
|
||||
</p>
|
||||
)}
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
|
||||
{/* Modal de Edição */}
|
||||
<ClienteModal
|
||||
isOpen={isEditModalOpen}
|
||||
cliente={cliente}
|
||||
onClose={() => {
|
||||
setIsEditModalOpen(false);
|
||||
setEditingField(null);
|
||||
}}
|
||||
onSuccess={() => {
|
||||
setIsEditModalOpen(false);
|
||||
setEditingField(null);
|
||||
}}
|
||||
initialTab={getTabForField(editingField)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,611 @@
|
||||
import React, {
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
forwardRef,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { Dialog, Transition } from "@headlessui/react";
|
||||
import { XMarkIcon } from "@heroicons/react/24/outline";
|
||||
import { useForm } from "react-hook-form";
|
||||
import axios from "axios";
|
||||
import { Cliente } from "../../types/entities";
|
||||
import { useClientes } from "../../hooks/useClientes";
|
||||
import { ORGAOS_EMISSORES, PREVIDENCIA_OPTIONS } from "../../utils/constants";
|
||||
|
||||
const estadosCivis = [
|
||||
{ value: "solteiro", label: "Solteiro(a)" },
|
||||
{ value: "casado", label: "Casado(a)" },
|
||||
{ value: "divorciado", label: "Divorciado(a)" },
|
||||
{ value: "uniao_estavel", label: "União Estável" },
|
||||
{ value: "viuvo", label: "Viúvo(a)" },
|
||||
];
|
||||
|
||||
const estados = [
|
||||
"AC",
|
||||
"AL",
|
||||
"AP",
|
||||
"AM",
|
||||
"BA",
|
||||
"CE",
|
||||
"DF",
|
||||
"ES",
|
||||
"GO",
|
||||
"MA",
|
||||
"MT",
|
||||
"MS",
|
||||
"MG",
|
||||
"PA",
|
||||
"PB",
|
||||
"PR",
|
||||
"PE",
|
||||
"PI",
|
||||
"RJ",
|
||||
"RN",
|
||||
"RS",
|
||||
"RO",
|
||||
"RR",
|
||||
"SC",
|
||||
"SP",
|
||||
"SE",
|
||||
"TO",
|
||||
];
|
||||
|
||||
const VINCULOS_EMPREGATICIO = [
|
||||
{ value: "mei", label: "MEI" },
|
||||
{ value: "pj", label: "Pessoa Jurídica" },
|
||||
{ value: "clt", label: "CLT" },
|
||||
{ value: "autonomo", label: "Autônomo" },
|
||||
{ value: "servidor_publico", label: "Servidor Público" },
|
||||
];
|
||||
|
||||
// Atualizar estados para o formato de options
|
||||
const estadosOptions = estados.map((uf) => ({ value: uf, label: uf }));
|
||||
|
||||
// Componente de input com forwardRef
|
||||
const FormInput = forwardRef<HTMLInputElement, any>(
|
||||
({ label, error, className = "", ...props }, ref) => (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<input
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg
|
||||
border border-gray-300
|
||||
bg-white text-gray-900
|
||||
transition duration-150 ease-in-out
|
||||
placeholder-gray-400
|
||||
focus:ring-2 focus:ring-blue-500 focus:border-transparent
|
||||
hover:border-gray-400
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
/>
|
||||
{error && (
|
||||
<div className="absolute -bottom-5 left-0">
|
||||
<p className="text-xs text-red-500">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
// Componente de select com forwardRef
|
||||
const FormSelect = forwardRef<HTMLSelectElement, any>(
|
||||
({ label, error, options, className = "", ...props }, ref) => (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<select
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg
|
||||
border border-gray-300
|
||||
bg-white text-gray-900
|
||||
transition duration-150 ease-in-out
|
||||
focus:ring-2 focus:ring-blue-500 focus:border-transparent
|
||||
hover:border-gray-400
|
||||
appearance-none
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
>
|
||||
<option value="">Selecione...</option>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{error && (
|
||||
<div className="absolute -bottom-5 left-0">
|
||||
<p className="text-xs text-red-500">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
// Componente de checkbox com forwardRef
|
||||
const FormCheckbox = forwardRef<HTMLInputElement, any>(
|
||||
({ label, ...props }, ref) => (
|
||||
<label className="flex items-center space-x-3 cursor-pointer group">
|
||||
<input
|
||||
type="checkbox"
|
||||
ref={ref}
|
||||
className="
|
||||
w-5 h-5 rounded
|
||||
border-gray-300 text-blue-600
|
||||
focus:ring-2 focus:ring-blue-500
|
||||
transition duration-150 ease-in-out
|
||||
cursor-pointer
|
||||
"
|
||||
{...props}
|
||||
/>
|
||||
<span className="text-sm text-gray-700 group-hover:text-gray-900">
|
||||
{label}
|
||||
</span>
|
||||
</label>
|
||||
),
|
||||
);
|
||||
|
||||
// Adicionar displayName para os componentes
|
||||
FormInput.displayName = "FormInput";
|
||||
FormSelect.displayName = "FormSelect";
|
||||
FormCheckbox.displayName = "FormCheckbox";
|
||||
|
||||
interface ClienteModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
cliente: Cliente | null;
|
||||
onSuccess?: () => void;
|
||||
initialTab?: number;
|
||||
}
|
||||
|
||||
export const ClienteModal: React.FC<ClienteModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
cliente,
|
||||
onSuccess,
|
||||
initialTab = 0,
|
||||
}) => {
|
||||
const [activeTab, setActiveTab] = useState(initialTab);
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
reset,
|
||||
setValue,
|
||||
watch,
|
||||
} = useForm();
|
||||
const { createCliente, updateCliente } = useClientes();
|
||||
const formPopulated = useRef(false);
|
||||
|
||||
// Função para preencher o formulário com os dados do cliente
|
||||
const populateForm = useCallback(
|
||||
(clienteData: Cliente) => {
|
||||
console.log("Populando formulário com:", clienteData);
|
||||
Object.keys(clienteData).forEach((key) => {
|
||||
if (key === "dataNascimento" && clienteData[key]) {
|
||||
// Formatar a data para o formato YYYY-MM-DD esperado pelo input type="date"
|
||||
const data = new Date(clienteData[key]);
|
||||
setValue(key, data.toISOString().split("T")[0]);
|
||||
} else if (
|
||||
key !== "id" &&
|
||||
key !== "dataCriacao" &&
|
||||
key !== "processos" &&
|
||||
key !== "filhos"
|
||||
) {
|
||||
setValue(key, clienteData[key]);
|
||||
}
|
||||
});
|
||||
},
|
||||
[setValue],
|
||||
);
|
||||
|
||||
// Efeito para carregar os dados quando o modal abrir ou o cliente mudar
|
||||
useEffect(() => {
|
||||
if (isOpen && cliente && !formPopulated.current) {
|
||||
console.log("Populando formulário com:", cliente);
|
||||
Object.keys(cliente).forEach((key) => {
|
||||
if (key === "dataNascimento" && cliente[key]) {
|
||||
const data = new Date(cliente[key]);
|
||||
setValue(key, data.toISOString().split("T")[0]);
|
||||
} else if (
|
||||
key !== "id" &&
|
||||
key !== "dataCriacao" &&
|
||||
key !== "processos" &&
|
||||
key !== "filhos"
|
||||
) {
|
||||
setValue(key, cliente[key]);
|
||||
}
|
||||
});
|
||||
formPopulated.current = true;
|
||||
}
|
||||
|
||||
if (!isOpen) {
|
||||
formPopulated.current = false;
|
||||
reset();
|
||||
}
|
||||
}, [isOpen, cliente, setValue, reset]);
|
||||
|
||||
const onSubmit = async (data: Partial<Cliente>) => {
|
||||
try {
|
||||
// Converter nome para maiúsculas
|
||||
const cleanData = Object.fromEntries(
|
||||
Object.entries(data).filter(([_, value]) => {
|
||||
if (value === "") return false;
|
||||
if (value === null) return false;
|
||||
if (value === undefined) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
// Formatar campos específicos e converter nome para maiúsculas
|
||||
const formattedData = {
|
||||
...cleanData,
|
||||
nome: cleanData.nome?.toUpperCase(),
|
||||
nomeMae: cleanData.nomeMae?.toUpperCase(),
|
||||
nomePai: cleanData.nomePai?.toUpperCase(),
|
||||
conjugeNome: cleanData.conjugeNome?.toUpperCase(),
|
||||
// Converter campos numéricos
|
||||
renda: cleanData.renda ? Number(cleanData.renda) : null,
|
||||
// Formatar data de nascimento para ISO String
|
||||
dataNascimento: cleanData.dataNascimento
|
||||
? new Date(cleanData.dataNascimento).toISOString()
|
||||
: null,
|
||||
// Garantir campos obrigatórios
|
||||
email: cleanData.email,
|
||||
telefone: cleanData.telefone,
|
||||
cpfCnpj: cleanData.cpfCnpj,
|
||||
endereco: cleanData.endereco,
|
||||
cep: cleanData.cep,
|
||||
numero: cleanData.numero,
|
||||
bairro: cleanData.bairro,
|
||||
cidade: cleanData.cidade,
|
||||
estado: cleanData.estado,
|
||||
// Converter booleanos
|
||||
declaraIR: Boolean(cleanData.declaraIR),
|
||||
contribuiPrevidencia: Boolean(cleanData.contribuiPrevidencia),
|
||||
usaDNI: Boolean(cleanData.usaDNI),
|
||||
possuiFilhos: Boolean(cleanData.possuiFilhos),
|
||||
};
|
||||
|
||||
console.log("Dados enviados:", formattedData); // Debug
|
||||
|
||||
if (cliente) {
|
||||
await updateCliente({
|
||||
id: cliente.id,
|
||||
data: formattedData,
|
||||
});
|
||||
} else {
|
||||
await createCliente(formattedData);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error("Erro detalhado:", error);
|
||||
if (axios.isAxiosError(error)) {
|
||||
alert(error.response?.data?.error || "Erro ao salvar cliente");
|
||||
} else {
|
||||
alert("Erro ao salvar cliente");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Reset form on modal close
|
||||
const handleClose = () => {
|
||||
reset();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const tabs = [
|
||||
{ id: "pessoal", label: "Dados Pessoais" },
|
||||
{ id: "endereco", label: "Endereço" },
|
||||
{ id: "financeiro", label: "Dados Financeiros" },
|
||||
{ id: "familia", label: "Filiação" },
|
||||
];
|
||||
|
||||
return (
|
||||
<Transition show={isOpen} as={React.Fragment}>
|
||||
<Dialog onClose={handleClose} className="relative z-50">
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0"
|
||||
enterTo="opacity-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100"
|
||||
leaveTo="opacity-0"
|
||||
>
|
||||
<div className="fixed inset-0 bg-black/30 backdrop-blur-sm" />
|
||||
</Transition.Child>
|
||||
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<Transition.Child
|
||||
enter="ease-out duration-300"
|
||||
enterFrom="opacity-0 scale-95"
|
||||
enterTo="opacity-100 scale-100"
|
||||
leave="ease-in duration-200"
|
||||
leaveFrom="opacity-100 scale-100"
|
||||
leaveTo="opacity-0 scale-95"
|
||||
>
|
||||
<Dialog.Panel className="mx-auto max-w-4xl w-full bg-white dark:bg-gray-800 rounded-xl shadow-2xl">
|
||||
{/* Header com abas */}
|
||||
<div className="border-b border-gray-200 dark:border-gray-700 p-6 bg-gray-50 dark:bg-gray-900 rounded-t-xl">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<Dialog.Title className="text-2xl font-bold text-gray-900 dark:text-white">
|
||||
{cliente ? "Editar Cliente" : "Novo Cliente"}
|
||||
</Dialog.Title>
|
||||
<button
|
||||
onClick={handleClose}
|
||||
className="text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400"
|
||||
>
|
||||
<XMarkIcon className="h-6 w-6" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex space-x-1">
|
||||
{tabs.map((tab, idx) => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(idx)}
|
||||
className={`
|
||||
flex items-center px-6 py-3 text-sm font-medium rounded-t-lg
|
||||
transition-all duration-200 ease-in-out
|
||||
${
|
||||
activeTab === idx
|
||||
? "bg-white text-blue-600 border-t-2 border-blue-600 shadow-sm"
|
||||
: "text-gray-500 hover:text-gray-700 hover:bg-gray-100"
|
||||
}
|
||||
`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Formulário */}
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="p-6 bg-white dark:bg-gray-800">
|
||||
<div className="space-y-8 mb-8">
|
||||
{/* Conteúdo das abas */}
|
||||
{activeTab === 0 && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label="Nome"
|
||||
{...register("nome", {
|
||||
required: "Nome é obrigatório",
|
||||
})}
|
||||
error={errors.nome?.message}
|
||||
/>
|
||||
<FormInput
|
||||
label="CPF/CNPJ"
|
||||
{...register("cpfCnpj", {
|
||||
required: "CPF/CNPJ é obrigatório",
|
||||
})}
|
||||
error={errors.cpfCnpj?.message}
|
||||
/>
|
||||
<div className="col-span-2 mb-4">
|
||||
<FormCheckbox
|
||||
label="Usar DNI (Documento Nacional de Identidade)"
|
||||
{...register("usaDNI")}
|
||||
onChange={(e) => {
|
||||
if (e.target.checked) {
|
||||
setValue("rg", watch("cpfCnpj"));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
label="RG"
|
||||
{...register("rg")}
|
||||
disabled={watch("usaDNI")}
|
||||
/>
|
||||
<div className="col-span-2 grid grid-cols-2 gap-4">
|
||||
<FormSelect
|
||||
label="Órgão Emissor"
|
||||
{...register("orgaoEmissor")}
|
||||
options={ORGAOS_EMISSORES}
|
||||
/>
|
||||
<FormSelect
|
||||
label="Estado do RG"
|
||||
{...register("estadoRg")}
|
||||
options={estadosOptions}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
label="Email"
|
||||
type="email"
|
||||
{...register("email", {
|
||||
required: "Email é obrigatório",
|
||||
})}
|
||||
error={errors.email?.message}
|
||||
/>
|
||||
<FormInput
|
||||
label="Telefone"
|
||||
{...register("telefone", {
|
||||
required: "Telefone é obrigatório",
|
||||
})}
|
||||
error={errors.telefone?.message}
|
||||
/>
|
||||
<FormSelect
|
||||
label="Estado Civil"
|
||||
{...register("estadoCivil")}
|
||||
options={estadosCivis}
|
||||
/>
|
||||
<FormInput
|
||||
label="Instagram"
|
||||
{...register("instagram")}
|
||||
placeholder="@"
|
||||
/>
|
||||
<FormInput
|
||||
label="Profissão"
|
||||
{...register("profissao")}
|
||||
/>
|
||||
<FormInput
|
||||
label="Data de Nascimento"
|
||||
type="date"
|
||||
{...register("dataNascimento")}
|
||||
max={new Date().toISOString().split("T")[0]} // Impede datas futuras
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 1 && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label="CEP"
|
||||
{...register("cep", {
|
||||
required: "CEP é obrigatório",
|
||||
})}
|
||||
error={errors.cep?.message}
|
||||
/>
|
||||
<FormInput
|
||||
className="md:col-span-2"
|
||||
label="Endereço"
|
||||
{...register("endereco", {
|
||||
required: "Endereço é obrigatório",
|
||||
})}
|
||||
error={errors.endereco?.message}
|
||||
/>
|
||||
<FormInput
|
||||
label="Número"
|
||||
{...register("numero", {
|
||||
required: "Número é obrigatório",
|
||||
})}
|
||||
error={errors.numero?.message}
|
||||
/>
|
||||
<FormInput
|
||||
label="Complemento"
|
||||
{...register("complemento")}
|
||||
/>
|
||||
<FormInput
|
||||
label="Bairro"
|
||||
{...register("bairro", {
|
||||
required: "Bairro é obrigatório",
|
||||
})}
|
||||
error={errors.bairro?.message}
|
||||
/>
|
||||
<FormInput
|
||||
label="Cidade"
|
||||
{...register("cidade", {
|
||||
required: "Cidade é obrigatória",
|
||||
})}
|
||||
error={errors.cidade?.message}
|
||||
/>
|
||||
<FormSelect
|
||||
label="Estado"
|
||||
{...register("estado", {
|
||||
required: "Estado é obrigatório",
|
||||
})}
|
||||
options={estadosOptions}
|
||||
error={errors.estado?.message}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 2 && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSelect
|
||||
label="Vínculo Empregatício"
|
||||
{...register("vinculoEmpregaticio")}
|
||||
options={VINCULOS_EMPREGATICIO}
|
||||
/>
|
||||
<FormInput
|
||||
label="Renda Mensal"
|
||||
type="number"
|
||||
step="0.01"
|
||||
{...register("renda")}
|
||||
/>
|
||||
<div className="col-span-2">
|
||||
<FormCheckbox
|
||||
label="Declara Imposto de Renda"
|
||||
{...register("declaraIR")}
|
||||
/>
|
||||
</div>
|
||||
<FormSelect
|
||||
label="Tipo de Previdência"
|
||||
{...register("tipoPrevidencia")}
|
||||
options={PREVIDENCIA_OPTIONS}
|
||||
/>
|
||||
<div className="col-span-2">
|
||||
<FormCheckbox
|
||||
label="Contribui para Previdência"
|
||||
{...register("contribuiPrevidencia")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 3 && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="col-span-2 mb-4">
|
||||
<FormCheckbox
|
||||
label="Possui Filhos?"
|
||||
{...register("possuiFilhos")}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
label="Nome do Pai"
|
||||
{...register("nomePai")}
|
||||
/>
|
||||
<FormInput
|
||||
label="Nome da Mãe"
|
||||
{...register("nomeMae")}
|
||||
/>
|
||||
<FormInput
|
||||
label="Nome do Cônjuge"
|
||||
{...register("conjugeNome")}
|
||||
/>
|
||||
<FormInput
|
||||
label="CPF do Cônjuge"
|
||||
{...register("conjugeCpf")}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Botões de ação */}
|
||||
<div className="flex justify-end space-x-3 pt-6 border-t">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClose}
|
||||
className="
|
||||
px-6 py-2.5 text-sm font-medium
|
||||
text-gray-700 bg-white
|
||||
border border-gray-300 rounded-lg
|
||||
hover:bg-gray-50
|
||||
focus:outline-none focus:ring-2 focus:ring-gray-200
|
||||
transition duration-200
|
||||
"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="
|
||||
px-6 py-2.5 text-sm font-medium
|
||||
text-white bg-blue-600 rounded-lg
|
||||
hover:bg-blue-700
|
||||
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2
|
||||
transition duration-200
|
||||
"
|
||||
>
|
||||
{cliente ? "Salvar" : "Criar"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</Transition.Child>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,146 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { PencilIcon } from '@heroicons/react/24/outline';
|
||||
import api from '../../services/api';
|
||||
import { formatCPF, formatTelefone } from '../../utils/formatters';
|
||||
|
||||
interface ClientesListProps {
|
||||
searchTerm: string;
|
||||
onEdit: (cliente: any) => void;
|
||||
}
|
||||
|
||||
export const ClientesList: React.FC<ClientesListProps> = ({ searchTerm, onEdit }) => {
|
||||
const navigate = useNavigate();
|
||||
const [debouncedTerm, setDebouncedTerm] = useState(searchTerm);
|
||||
|
||||
// Implementar debounce para a busca
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedTerm(searchTerm);
|
||||
}, 300); // 300ms de delay
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchTerm]);
|
||||
|
||||
const { data: clientes = [], isLoading } = useQuery(
|
||||
['clientes', debouncedTerm],
|
||||
async () => {
|
||||
const response = await api.get('/clientes', {
|
||||
params: {
|
||||
search: debouncedTerm.toUpperCase()
|
||||
}
|
||||
});
|
||||
|
||||
// Filtrar localmente para melhor resposta
|
||||
let filteredClientes = response.data;
|
||||
if (debouncedTerm) {
|
||||
const searchTerms = debouncedTerm.toUpperCase().split(' ');
|
||||
filteredClientes = response.data.filter((cliente: any) =>
|
||||
searchTerms.every(term =>
|
||||
cliente.nome.includes(term) ||
|
||||
cliente.cpfCnpj.includes(term) ||
|
||||
cliente.email?.includes(term.toLowerCase())
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Ordenar por nome
|
||||
return filteredClientes.sort((a: any, b: any) =>
|
||||
a.nome.localeCompare(b.nome)
|
||||
);
|
||||
},
|
||||
{
|
||||
staleTime: 1000 * 60, // 1 minuto
|
||||
cacheTime: 1000 * 60 * 5, // 5 minutos
|
||||
keepPreviousData: true // Manter dados anteriores enquanto carrega novos
|
||||
}
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 shadow rounded-lg p-6">
|
||||
<div className="animate-pulse flex space-x-4">
|
||||
<div className="flex-1 space-y-4">
|
||||
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4"></div>
|
||||
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
|
||||
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-5/6"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden">
|
||||
{clientes.length === 0 ? (
|
||||
<div className="p-6 text-center text-gray-500 dark:text-gray-400">
|
||||
Nenhum cliente encontrado
|
||||
</div>
|
||||
) : (
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Nome
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
CPF/CNPJ
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Telefone
|
||||
</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Email
|
||||
</th>
|
||||
<th className="relative px-6 py-3">
|
||||
<span className="sr-only">Ações</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{clientes.map((cliente: any) => (
|
||||
<tr
|
||||
key={cliente.id}
|
||||
className="hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer bg-white dark:bg-gray-800"
|
||||
onClick={() => navigate(`/clientes/${cliente.id}`)}
|
||||
>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{cliente.nome}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{formatCPF(cliente.cpfCnpj)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{formatTelefone(cliente.telefone)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{cliente.email}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEdit(cliente);
|
||||
}}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300"
|
||||
>
|
||||
<PencilIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import React, { useState } from "react";
|
||||
import { PlusIcon, MagnifyingGlassIcon } from "@heroicons/react/24/outline";
|
||||
import { ClientesList } from "./ClientesList.tsx";
|
||||
import { ClienteModal } from "./ClienteModal.tsx";
|
||||
import { Cliente } from "../../types/entities";
|
||||
|
||||
export const ClientesPage: React.FC = () => {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [selectedCliente, setSelectedCliente] = useState<Cliente | null>(null);
|
||||
|
||||
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setSearchTerm(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="relative flex-1 max-w-md">
|
||||
<MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400 dark:text-gray-500" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Buscar clientes..."
|
||||
value={searchTerm}
|
||||
onChange={handleSearchChange}
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg
|
||||
border border-gray-300 dark:border-gray-600
|
||||
bg-white dark:bg-gray-700
|
||||
text-gray-900 dark:text-white
|
||||
placeholder-gray-400 dark:placeholder-gray-500
|
||||
focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400
|
||||
focus:border-transparent"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedCliente(null);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg
|
||||
hover:bg-blue-700 dark:hover:bg-blue-500 transition-colors"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5 mr-2" />
|
||||
Novo Cliente
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ClientesList
|
||||
searchTerm={searchTerm}
|
||||
onEdit={(cliente) => {
|
||||
setSelectedCliente(cliente);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ClienteModal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedCliente(null);
|
||||
}}
|
||||
cliente={selectedCliente}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { format, differenceInDays } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { ExclamationTriangleIcon } from '@heroicons/react/24/outline';
|
||||
import api from '../../services/api';
|
||||
|
||||
export const AlertasPrazos: React.FC = () => {
|
||||
const { data: prazos = [] } = useQuery('prazosFuturos', async () => {
|
||||
const response = await api.get('/dashboard/prazos/proximos');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const getPrioridadeStyle = (dias: number) => {
|
||||
if (dias <= 3) return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
|
||||
if (dias <= 7) return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
|
||||
return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
Prazos Próximos
|
||||
</h2>
|
||||
<ExclamationTriangleIcon className="h-5 w-5 text-yellow-500" />
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{prazos.map((prazo: any) => {
|
||||
const dias = differenceInDays(new Date(prazo.dataLimite), new Date());
|
||||
return (
|
||||
<div key={prazo.id} className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{prazo.descricao}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
Processo: {prazo.processo.numero}
|
||||
</p>
|
||||
</div>
|
||||
<span className={`px-2 py-1 rounded-full text-xs ${getPrioridadeStyle(dias)}`}>
|
||||
{format(new Date(prazo.dataLimite), 'dd/MM/yyyy', { locale: ptBR })}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import api from '../../services/api';
|
||||
|
||||
export const AtividadesRecentes: React.FC = () => {
|
||||
const { data: atividades = [] } = useQuery('atividades', async () => {
|
||||
const response = await api.get('/dashboard/atividades');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const formatData = (data: string | Date | null) => {
|
||||
if (!data) return '';
|
||||
try {
|
||||
return format(new Date(data), "dd 'de' MMMM 'às' HH:mm", { locale: ptBR });
|
||||
} catch (error) {
|
||||
console.error('Erro ao formatar data:', error);
|
||||
return 'Data inválida';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Atividades Recentes
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{atividades.map((atividade: any) => (
|
||||
<div key={atividade.id} className="flex items-start space-x-3">
|
||||
<span className="text-2xl">{atividade.tipo === 'PROCESSO' ? '⚖️' : '📋'}</span>
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-gray-900 dark:text-white">
|
||||
{atividade.descricao}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{formatData(atividade.data)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
ArrowUpIcon,
|
||||
ArrowDownIcon,
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
interface CardProps {
|
||||
title: string;
|
||||
value: string | number;
|
||||
trend?: number;
|
||||
trendLabel?: string;
|
||||
icon?: string;
|
||||
color?: 'blue' | 'green' | 'red' | 'yellow' | 'purple';
|
||||
items?: Array<{ label: string; value: string | number }>;
|
||||
type?: 'default' | 'list';
|
||||
}
|
||||
|
||||
export const Card: React.FC<CardProps> = ({
|
||||
title,
|
||||
value,
|
||||
trend,
|
||||
trendLabel,
|
||||
icon,
|
||||
color = 'blue',
|
||||
items,
|
||||
type = 'default'
|
||||
}) => {
|
||||
const colorClasses = {
|
||||
blue: 'text-blue-600',
|
||||
green: 'text-green-600',
|
||||
red: 'text-red-600',
|
||||
yellow: 'text-yellow-600',
|
||||
purple: 'text-purple-600'
|
||||
};
|
||||
|
||||
const bgColorClasses = {
|
||||
blue: 'bg-blue-50',
|
||||
green: 'bg-green-50',
|
||||
red: 'bg-red-50',
|
||||
yellow: 'bg-yellow-50',
|
||||
purple: 'bg-purple-50'
|
||||
};
|
||||
|
||||
if (type === 'list' && items) {
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<h3 className="text-sm font-medium text-gray-900 mb-4">{title}</h3>
|
||||
<div className="space-y-2">
|
||||
{items.map((item, index) => (
|
||||
<div key={index} className="flex justify-between items-center">
|
||||
<span className="text-sm text-gray-500">{item.label}</span>
|
||||
<span className="text-sm font-medium text-gray-900">{item.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex justify-between items-start">
|
||||
<h3 className="text-sm font-medium text-gray-900">{title}</h3>
|
||||
{icon && (
|
||||
<div className={`p-2 rounded-lg ${bgColorClasses[color]}`}>
|
||||
{/* Renderizar ícone dinamicamente */}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="mt-2 flex items-baseline">
|
||||
<p className={`text-2xl font-semibold ${colorClasses[color]}`}>
|
||||
{value}
|
||||
</p>
|
||||
{trend !== undefined && (
|
||||
<div className={`ml-2 flex items-center text-sm ${trend >= 0 ? 'text-green-600' : 'text-red-600'}`}>
|
||||
{trend >= 0 ? (
|
||||
<ArrowUpIcon className="h-4 w-4" />
|
||||
) : (
|
||||
<ArrowDownIcon className="h-4 w-4" />
|
||||
)}
|
||||
<span className="ml-1">{Math.abs(trend)}%</span>
|
||||
{trendLabel && (
|
||||
<span className="ml-1 text-gray-500">
|
||||
{trendLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,53 @@
|
||||
import React from 'react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { useDashboardStats } from '../../hooks/useDashboardStats';
|
||||
import { ProcessosStats } from './stats/ProcessosStats';
|
||||
import { TarefasStats } from './stats/TarefasStats';
|
||||
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 = () => {
|
||||
const { user } = useAuth();
|
||||
const {
|
||||
processosStats,
|
||||
tarefasStats,
|
||||
atendimentosStats,
|
||||
financeiroStats,
|
||||
proximosPrazos,
|
||||
atividades
|
||||
} = useDashboardStats();
|
||||
|
||||
const isAdminOrAdvogado = ['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user?.perfil || '');
|
||||
|
||||
return (
|
||||
<div className="space-y-6 p-6">
|
||||
{/* Stats Cards */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
|
||||
{processosStats.data && <ProcessosStats data={processosStats.data} />}
|
||||
{tarefasStats.data && <TarefasStats data={tarefasStats.data} />}
|
||||
{atendimentosStats.data && <AtendimentosStats data={atendimentosStats.data} />}
|
||||
{isAdminOrAdvogado && financeiroStats.data && (
|
||||
<FinanceiroStats data={financeiroStats.data} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
{/* Coluna da esquerda */}
|
||||
<div className="lg:col-span-2 space-y-6">
|
||||
<TaxaSucessoCard />
|
||||
{isAdminOrAdvogado && <KPIsFinanceiros />}
|
||||
</div>
|
||||
|
||||
{/* Coluna da direita */}
|
||||
<div className="space-y-6">
|
||||
<AlertasPrazos />
|
||||
<AtividadesRecentes />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,66 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import api from '../../services/api';
|
||||
|
||||
export const KPIsAdvogados: React.FC = () => {
|
||||
const { data: kpis } = useQuery('advogadosKpis', async () => {
|
||||
const response = await api.get('/dashboard/advogados/kpis');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
|
||||
<div className="p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Produtividade da Equipe
|
||||
</h2>
|
||||
</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Advogado
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Tarefas Concluídas
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Processos Concluídos
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Produtividade
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{kpis?.map((kpi: any) => (
|
||||
<tr key={kpi.id}>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900 dark:text-white">
|
||||
{kpi.nome}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
||||
{kpi.tarefasConcluidas} / {kpi.tarefasCriadas}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
|
||||
{kpi.processosConcluidos}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5 dark:bg-gray-700">
|
||||
<div
|
||||
className="bg-blue-600 h-2.5 rounded-full"
|
||||
style={{ width: `${kpi.produtividade}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{kpi.produtividade}%
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import api from '../../services/api';
|
||||
|
||||
export const TaxaSucessoCard: React.FC = () => {
|
||||
const { data: stats } = useQuery('taxa-sucesso', async () => {
|
||||
const response = await api.get('/dashboard/processos/taxa-sucesso');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
if (!stats) return null;
|
||||
|
||||
const estatisticas = stats || [];
|
||||
const total = estatisticas.reduce((acc: number, curr: any) => acc + (curr._count || 0), 0);
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">Taxa de Sucesso</h3>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-3xl font-bold text-green-600">
|
||||
{estatisticas.find((s: any) => s.resultado === 'PROCEDENTE')?._count
|
||||
? Math.round((estatisticas.find((s: any) => s.resultado === 'PROCEDENTE')._count / total) * 100)
|
||||
: 0}%
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
Total julgados: {total}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 space-y-2">
|
||||
{estatisticas.map((item: any) => (
|
||||
<div key={item.resultado} className="flex justify-between">
|
||||
<span className="text-sm text-gray-600">{item.resultado}</span>
|
||||
<span className="text-sm font-medium">{Math.round((item._count / total) * 100)}%</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import api from '../../../services/api';
|
||||
|
||||
export const MapaCalor: React.FC = () => {
|
||||
const { data: atividadesDiarias } = useQuery('atividadesDiarias', async () => {
|
||||
const response = await api.get('/dashboard/atividades/diarias');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const intensidadeCor = (quantidade: number) => {
|
||||
if (quantidade === 0) return 'bg-gray-100 dark:bg-gray-800';
|
||||
if (quantidade <= 3) return 'bg-blue-100 dark:bg-blue-900';
|
||||
if (quantidade <= 6) return 'bg-blue-300 dark:bg-blue-700';
|
||||
return 'bg-blue-500 dark:bg-blue-500';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Mapa de Atividades
|
||||
</h2>
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
{atividadesDiarias?.map((dia: any) => (
|
||||
<div
|
||||
key={dia.data}
|
||||
className={`aspect-square rounded-sm ${intensidadeCor(dia.quantidade)}`}
|
||||
title={`${format(new Date(dia.data), "dd 'de' MMMM", { locale: ptBR })}: ${dia.quantidade} atividades`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import api from '../../../services/api';
|
||||
import { useAuth } from '../../../contexts/AuthContext';
|
||||
import { formatCurrency } from '../../../utils/formatters';
|
||||
|
||||
export const PrevisaoReceitasChart: React.FC = () => {
|
||||
const { user } = useAuth();
|
||||
|
||||
if (!['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user?.perfil || '')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { data: previsao } = useQuery('previsaoReceitas', async () => {
|
||||
const response = await api.get('/dashboard/financeiro/previsao');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Previsão de Receitas
|
||||
</h2>
|
||||
<div className="h-80">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={previsao}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="mes" />
|
||||
<YAxis tickFormatter={(value) => formatCurrency(value)} />
|
||||
<Tooltip formatter={(value) => formatCurrency(value)} />
|
||||
<Bar dataKey="honorarios" name="Honorários" fill="#10B981" />
|
||||
<Bar dataKey="custas" name="Custas" fill="#6366F1" />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { useAuth } from '../../../contexts/AuthContext';
|
||||
import { ProcessosEvolucao } from './ProcessosEvolucao';
|
||||
import { TaxaSucessoChart } from './TaxaSucessoChart';
|
||||
import { PrevisaoReceitasChart } from './PrevisaoReceitasChart';
|
||||
|
||||
export const ProcessosCharts: React.FC = () => {
|
||||
const { user } = useAuth();
|
||||
const isAdminOrAdvogado = user?.perfil === 'ADVOGADO_ADMIN' || user?.perfil === 'ADVOGADO';
|
||||
|
||||
return (
|
||||
<>
|
||||
<ProcessosEvolucao />
|
||||
<TaxaSucessoChart />
|
||||
{isAdminOrAdvogado && <PrevisaoReceitasChart />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
|
||||
import api from '../../../services/api';
|
||||
|
||||
export const ProcessosEvolucao: React.FC = () => {
|
||||
const { data: evolucao } = useQuery('processosEvolucao', async () => {
|
||||
const response = await api.get('/dashboard/processos/evolucao');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Evolução de Processos
|
||||
</h2>
|
||||
<div className="h-80">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<LineChart data={evolucao}>
|
||||
<CartesianGrid strokeDasharray="3 3" />
|
||||
<XAxis dataKey="mes" />
|
||||
<YAxis />
|
||||
<Tooltip />
|
||||
<Line type="monotone" dataKey="novos" stroke="#3B82F6" name="Novos" />
|
||||
<Line type="monotone" dataKey="concluidos" stroke="#10B981" name="Concluídos" />
|
||||
</LineChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, Legend, Tooltip } from 'recharts';
|
||||
import api from '../../../services/api';
|
||||
|
||||
export const TaxaSucessoChart: React.FC = () => {
|
||||
const { data: stats } = useQuery('taxaSucesso', async () => {
|
||||
const response = await api.get('/dashboard/processos/taxa-sucesso');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const COLORS = ['#10B981', '#EF4444', '#F59E0B'];
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Taxa de Sucesso em Processos
|
||||
</h2>
|
||||
<div className="h-80">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={stats}
|
||||
dataKey="valor"
|
||||
nameKey="categoria"
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
outerRadius={80}
|
||||
label
|
||||
>
|
||||
{stats?.map((entry: any, index: number) => (
|
||||
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip />
|
||||
<Legend />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,35 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { Card } from '../Card';
|
||||
import api from '../../../services/api';
|
||||
|
||||
export const AtendimentosStats: React.FC = () => {
|
||||
const { data: stats } = useQuery('atendimentosStats', async () => {
|
||||
const response = await api.get('/dashboard/atendimentos/stats');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Card
|
||||
title="Atendimentos Hoje"
|
||||
value={stats?.hoje || 0}
|
||||
icon="Calendar"
|
||||
color="blue"
|
||||
/>
|
||||
<Card
|
||||
title="Próximos 7 dias"
|
||||
value={stats?.proximaSemana || 0}
|
||||
icon="CalendarDays"
|
||||
color="purple"
|
||||
/>
|
||||
<Card
|
||||
title="Total no Mês"
|
||||
value={stats?.totalMes || 0}
|
||||
trend={stats?.crescimentoMes}
|
||||
icon="ChartBar"
|
||||
color="green"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { Card } from '../Card';
|
||||
import api from '../../../services/api';
|
||||
import { formatCurrency } from '../../../utils/formatters';
|
||||
|
||||
export const FinanceiroStats: React.FC = () => {
|
||||
const { data: stats } = useQuery('financeiroStats', async () => {
|
||||
const response = await api.get('/dashboard/financeiro/stats');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Card
|
||||
title="Honorários a Receber"
|
||||
value={formatCurrency(stats?.honorariosReceber || 0)}
|
||||
icon="BanknotesIcon"
|
||||
color="green"
|
||||
/>
|
||||
<Card
|
||||
title="Custas do Mês"
|
||||
value={formatCurrency(stats?.custasMes || 0)}
|
||||
trend={stats?.variacaoCustas}
|
||||
icon="ReceiptPercentIcon"
|
||||
color="red"
|
||||
/>
|
||||
<Card
|
||||
title="Receitas (Mês)"
|
||||
value={formatCurrency(stats?.receitasMes || 0)}
|
||||
trend={stats?.crescimentoReceitas}
|
||||
icon="CurrencyDollarIcon"
|
||||
color="blue"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useAuth } from '../../../contexts/AuthContext';
|
||||
import { Card } from '../../dashboard/Card';
|
||||
import api from '../../../services/api';
|
||||
import { formatCurrency } from '../../../utils/formatters';
|
||||
|
||||
export const KPIsFinanceiros: React.FC = () => {
|
||||
const { user } = useAuth();
|
||||
|
||||
if (!['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user?.perfil || '')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { data: stats } = useQuery('financeiroKPIs', async () => {
|
||||
const response = await api.get('/dashboard/financeiro/stats');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Card
|
||||
title="Faturamento Previsto"
|
||||
value={formatCurrency(stats?.previsaoFaturamento || 0)}
|
||||
trend={stats?.crescimentoFaturamento}
|
||||
icon="BanknotesIcon"
|
||||
color="green"
|
||||
/>
|
||||
<Card
|
||||
title="Taxa de Sucesso"
|
||||
value={`${stats?.taxaSucesso || 0}%`}
|
||||
trend={stats?.crescimentoTaxaSucesso}
|
||||
icon="ChartBarIcon"
|
||||
color="blue"
|
||||
/>
|
||||
<Card
|
||||
title="Custas em Aberto"
|
||||
value={formatCurrency(stats?.custasEmAberto || 0)}
|
||||
icon="ExclamationTriangleIcon"
|
||||
color="yellow"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import api from '../../../services/api';
|
||||
import { Card } from '../Card';
|
||||
|
||||
export const ProcessosStats: React.FC = () => {
|
||||
const { data: stats } = useQuery('processosStats', async () => {
|
||||
const response = await api.get('/dashboard/processos/stats');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Card
|
||||
title="Total de Processos"
|
||||
value={stats?.total || 0}
|
||||
trend={stats?.crescimento || 0}
|
||||
icon="DocumentText"
|
||||
/>
|
||||
<Card
|
||||
title="Por Tribunal"
|
||||
items={stats?.porTribunal || []}
|
||||
type="list"
|
||||
/>
|
||||
<Card
|
||||
title="Por Status"
|
||||
items={stats?.porStatus || []}
|
||||
type="list"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,61 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { Card } from '../Card';
|
||||
import api from '../../../services/api';
|
||||
|
||||
export const TarefasStats: React.FC = () => {
|
||||
const { data: stats } = useQuery('tarefasStats', async () => {
|
||||
try {
|
||||
const response = await api.get('/dashboard/tarefas/stats');
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error('Erro ao buscar estatísticas:', error);
|
||||
return {
|
||||
pendentes: 0,
|
||||
atrasadas: 0,
|
||||
concluidas: 0,
|
||||
total: 0,
|
||||
taxaConclusao: 0,
|
||||
porStatus: { PENDENTE: 0 }
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
const defaultStats = {
|
||||
pendentes: 0,
|
||||
atrasadas: 0,
|
||||
concluidas: 0,
|
||||
total: 0,
|
||||
taxaConclusao: 0,
|
||||
porStatus: { PENDENTE: 0 }
|
||||
};
|
||||
|
||||
const safeStats = stats || defaultStats;
|
||||
|
||||
return (
|
||||
<div className="grid gap-4">
|
||||
<Card
|
||||
title="Tarefas Pendentes"
|
||||
value={safeStats.porStatus?.PENDENTE || 0}
|
||||
trend={safeStats.atrasadas}
|
||||
trendLabel="atrasadas"
|
||||
icon="ClipboardDocumentList"
|
||||
color="yellow"
|
||||
/>
|
||||
<Card
|
||||
title="Para Hoje"
|
||||
value={safeStats.pendentes || 0}
|
||||
icon="Clock"
|
||||
color="blue"
|
||||
/>
|
||||
<Card
|
||||
title="Concluídas (Mês)"
|
||||
value={safeStats.concluidas || 0}
|
||||
trend={safeStats.taxaConclusao}
|
||||
trendLabel="taxa de conclusão"
|
||||
icon="CheckCircle"
|
||||
color="green"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,344 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { api } from '../../lib/api';
|
||||
import { toast } from 'react-toastify';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { DocumentArrowUpIcon } from '@heroicons/react/24/outline';
|
||||
import { Editor } from '@tinymce/tinymce-react';
|
||||
import { DOCUMENT_VARIABLES } from '../../utils/documentVariables';
|
||||
|
||||
// Definir interface para o estado
|
||||
interface ConfigState {
|
||||
timbradoUrl: string;
|
||||
timbradoMarginTop: number;
|
||||
timbradoMarginBottom: number;
|
||||
timbradoMarginLeft: number;
|
||||
timbradoMarginRight: number;
|
||||
templatePadrao: string;
|
||||
margensTemplate: {
|
||||
top: number;
|
||||
bottom: number;
|
||||
left: number;
|
||||
right: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function ConfiguracaoDocumento() {
|
||||
const [config, setConfig] = useState<ConfigState>({
|
||||
timbradoUrl: '',
|
||||
timbradoMarginTop: 100,
|
||||
timbradoMarginBottom: 50,
|
||||
timbradoMarginLeft: 50,
|
||||
timbradoMarginRight: 50,
|
||||
templatePadrao: '',
|
||||
margensTemplate: {
|
||||
top: 35,
|
||||
bottom: 29,
|
||||
left: 25,
|
||||
right: 25
|
||||
}
|
||||
});
|
||||
|
||||
const [isPreviewOpen, setPreviewOpen] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadConfig();
|
||||
}, []);
|
||||
|
||||
const loadConfig = async () => {
|
||||
try {
|
||||
const response = await api.get('/documentos/configuracoes');
|
||||
console.log('Configurações carregadas:', response.data); // Debug
|
||||
if (response.data) {
|
||||
setConfig({
|
||||
timbradoUrl: response.data.timbradoUrl || '',
|
||||
timbradoMarginTop: response.data.timbradoMarginTop || 100,
|
||||
timbradoMarginBottom: response.data.timbradoMarginBottom || 50,
|
||||
timbradoMarginLeft: response.data.timbradoMarginLeft || 50,
|
||||
timbradoMarginRight: response.data.timbradoMarginRight || 50,
|
||||
templatePadrao: response.data.templatePadrao || '',
|
||||
margensTemplate: {
|
||||
top: response.data.margensTemplate?.top || 35,
|
||||
bottom: response.data.margensTemplate?.bottom || 29,
|
||||
left: response.data.margensTemplate?.left || 25,
|
||||
right: response.data.margensTemplate?.right || 25
|
||||
}
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar configurações:', error);
|
||||
toast.error('Erro ao carregar configurações');
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
// Atualizado para aceitar PDF
|
||||
if (!['image/png', 'image/svg+xml', 'application/pdf'].includes(file.type)) {
|
||||
toast.error('Por favor, use apenas arquivos PDF, PNG ou SVG');
|
||||
return;
|
||||
}
|
||||
|
||||
if (file.size > 5 * 1024 * 1024) { // Aumentado para 5MB para acomodar PDFs
|
||||
toast.error('O arquivo deve ter no máximo 5MB');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('timbrado', file);
|
||||
|
||||
const response = await api.post('/documentos/upload-timbrado', formData);
|
||||
setConfig(prev => ({ ...prev, timbradoUrl: response.data.url }));
|
||||
toast.success('Timbrado atualizado com sucesso');
|
||||
} catch (error) {
|
||||
toast.error('Erro ao fazer upload do timbrado');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
setIsSaving(true);
|
||||
await api.post('/documentos/configuracoes', config);
|
||||
toast.success('Configurações salvas com sucesso');
|
||||
} catch (error) {
|
||||
toast.error('Erro ao salvar configurações');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditorSetup = (editor: any) => {
|
||||
editor.ui.registry.addMenuButton('variables', {
|
||||
text: 'Variáveis',
|
||||
fetch: (callback: Function) => {
|
||||
const items = Object.entries(DOCUMENT_VARIABLES).flatMap(([category, vars]) =>
|
||||
Object.entries(vars).map(([name, value]) => ({
|
||||
type: 'menuitem',
|
||||
text: `${category} - ${name.replace(/_/g, ' ')}`,
|
||||
onAction: () => editor.insertContent(value as string)
|
||||
}))
|
||||
);
|
||||
callback(items);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Modificar a configuração do TinyMCE para remover o plugin 'template'
|
||||
const editorConfig = {
|
||||
height: 400,
|
||||
menubar: true,
|
||||
plugins: [
|
||||
'code', 'preview' // Removido 'template'
|
||||
],
|
||||
toolbar: 'variables | undo redo | formatselect | ' +
|
||||
'bold italic | alignleft aligncenter alignright | ' +
|
||||
'code preview',
|
||||
setup: handleEditorSetup
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 bg-white dark:bg-gray-800 rounded-lg shadow">
|
||||
<h2 className="text-xl font-bold mb-6">Configuração do Papel Timbrado</h2>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Upload do Timbrado */}
|
||||
<div>
|
||||
<label className="block mb-2">Papel Timbrado</label>
|
||||
<div className="flex items-center gap-4">
|
||||
<label className="flex items-center px-4 py-2 bg-blue-600 text-white rounded cursor-pointer hover:bg-blue-700">
|
||||
<DocumentArrowUpIcon className="w-5 h-5 mr-2" />
|
||||
Fazer Upload
|
||||
<input
|
||||
type="file"
|
||||
className="hidden"
|
||||
accept=".pdf,.png,.svg"
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
</label>
|
||||
{config.timbradoUrl && (
|
||||
<button
|
||||
onClick={() => setPreviewOpen(true)}
|
||||
className="text-blue-600 hover:underline"
|
||||
>
|
||||
Visualizar
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-2 text-sm text-gray-500">
|
||||
Use arquivos PDF, PNG ou SVG. Tamanho máximo: 5MB
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Margens */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block mb-2">Margem Superior (px)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.timbradoMarginTop}
|
||||
onChange={e => setConfig(prev => ({ ...prev, timbradoMarginTop: Number(e.target.value) }))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Inferior (px)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.timbradoMarginBottom}
|
||||
onChange={e => setConfig(prev => ({ ...prev, timbradoMarginBottom: Number(e.target.value) }))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Esquerda (px)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.timbradoMarginLeft}
|
||||
onChange={e => setConfig(prev => ({ ...prev, timbradoMarginLeft: Number(e.target.value) }))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Direita (px)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.timbradoMarginRight}
|
||||
onChange={e => setConfig(prev => ({ ...prev, timbradoMarginRight: Number(e.target.value) }))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Template Padrão */}
|
||||
<div className="mt-6">
|
||||
<label className="block mb-2">Template Padrão</label>
|
||||
<Editor
|
||||
apiKey={import.meta.env.VITE_TINYMCE_API_KEY}
|
||||
value={config.templatePadrao}
|
||||
onEditorChange={(content) => setConfig(prev => ({ ...prev, templatePadrao: content }))}
|
||||
init={editorConfig}
|
||||
/>
|
||||
<div className="mt-2 p-4 bg-gray-50 rounded border">
|
||||
<h4 className="font-medium mb-2">Variáveis Disponíveis:</h4>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{Object.entries(DOCUMENT_VARIABLES).map(([category, vars]) => (
|
||||
<div key={category}>
|
||||
<h5 className="font-medium text-sm text-gray-700">{category}</h5>
|
||||
<ul className="mt-1 space-y-1">
|
||||
{Object.entries(vars).map(([name, value]) => (
|
||||
<li key={name} className="text-xs text-gray-600">
|
||||
{value as string}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Margens do Template */}
|
||||
<div className="mt-6 grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block mb-2">Margem Superior (mm)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.margensTemplate.top}
|
||||
onChange={e => setConfig(prev => ({
|
||||
...prev,
|
||||
margensTemplate: {
|
||||
...prev.margensTemplate,
|
||||
top: Number(e.target.value)
|
||||
}
|
||||
}))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Inferior (mm)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.margensTemplate.bottom}
|
||||
onChange={e => setConfig(prev => ({
|
||||
...prev,
|
||||
margensTemplate: {
|
||||
...prev.margensTemplate,
|
||||
bottom: Number(e.target.value)
|
||||
}
|
||||
}))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Esquerda (mm)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.margensTemplate.left}
|
||||
onChange={e => setConfig(prev => ({
|
||||
...prev,
|
||||
margensTemplate: {
|
||||
...prev.margensTemplate,
|
||||
left: Number(e.target.value)
|
||||
}
|
||||
}))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block mb-2">Margem Direita (mm)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={config.margensTemplate.right}
|
||||
onChange={e => setConfig(prev => ({
|
||||
...prev,
|
||||
margensTemplate: {
|
||||
...prev.margensTemplate,
|
||||
right: Number(e.target.value)
|
||||
}
|
||||
}))}
|
||||
className="w-full p-2 border rounded"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving}
|
||||
className={`px-4 py-2 ${
|
||||
isSaving
|
||||
? 'bg-gray-400 cursor-not-allowed'
|
||||
: 'bg-blue-600 hover:bg-blue-700'
|
||||
} text-white rounded`}
|
||||
>
|
||||
{isSaving ? 'Salvando...' : 'Salvar Configurações'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Modal de Preview */}
|
||||
<Dialog open={isPreviewOpen} onClose={() => setPreviewOpen(false)}>
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-3xl bg-white rounded-lg shadow-xl p-6">
|
||||
<h3 className="text-lg font-semibold mb-4">Preview do Timbrado</h3>
|
||||
<div className="border rounded p-4 bg-gray-50">
|
||||
<img
|
||||
src={config.timbradoUrl}
|
||||
alt="Timbrado"
|
||||
className="max-w-full h-auto"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setPreviewOpen(false)}
|
||||
className="mt-4 px-4 py-2 bg-gray-200 rounded hover:bg-gray-300"
|
||||
>
|
||||
Fechar
|
||||
</button>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Editor } from '@tinymce/tinymce-react';
|
||||
import { Button, Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
|
||||
import { Save as SaveIcon } from '@mui/icons-material';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { toast } from 'react-toastify'; // Adicionar esta importação
|
||||
import { api } from '../../lib/api'; // Adicionar esta importação
|
||||
import { DocumentoService } from '../../services/DocumentoService'; // Adicionar esta importação
|
||||
|
||||
interface DocumentoEditorProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => Promise<void>;
|
||||
initialData?: any;
|
||||
processoId?: string;
|
||||
atendimentoId?: string;
|
||||
documento?: any; // Adicionar esta prop
|
||||
}
|
||||
|
||||
interface TemplateVariables {
|
||||
cliente: any;
|
||||
advogado: any;
|
||||
escritorio: any;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
const preencherTemplate = (template: string, variables: TemplateVariables) => {
|
||||
let result = template;
|
||||
Object.entries(variables).forEach(([key, value]) => {
|
||||
const regex = new RegExp(`{{${key}}}`, 'g');
|
||||
result = result.replace(regex, value);
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
export function DocumentoEditor({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
initialData,
|
||||
processoId,
|
||||
atendimentoId,
|
||||
documento // Recuperar a prop
|
||||
}: DocumentoEditorProps) {
|
||||
const [content, setContent] = useState('');
|
||||
const [nome, setNome] = useState('');
|
||||
const [tipo, setTipo] = useState('OUTROS');
|
||||
const [selectedTemplate, setSelectedTemplate] = useState(null);
|
||||
const [selectedAtendimento, setSelectedAtendimento] = useState(null);
|
||||
const [atendimentos, setAtendimentos] = useState([]);
|
||||
const [templates, setTemplates] = useState([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialData) {
|
||||
setContent(initialData.conteudo || '');
|
||||
setNome(initialData.nome || '');
|
||||
setTipo(initialData.tipo || 'OUTROS');
|
||||
}
|
||||
}, [initialData]);
|
||||
|
||||
useEffect(() => {
|
||||
const loadData = async () => {
|
||||
try {
|
||||
const [atendimentosRes, templatesRes] = await Promise.all([
|
||||
api.get('/atendimentos'),
|
||||
api.get('/documentos-modelos')
|
||||
]);
|
||||
setAtendimentos(atendimentosRes.data);
|
||||
setTemplates(templatesRes.data);
|
||||
} catch (error) {
|
||||
toast.error('Erro ao carregar dados');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
loadData();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (documento) {
|
||||
setContent(documento.conteudo || '');
|
||||
setNome(documento.nome || '');
|
||||
setTipo(documento.tipo || 'OUTROS');
|
||||
}
|
||||
}, [documento]);
|
||||
|
||||
const handleTemplateSelect = async (templateId) => {
|
||||
try {
|
||||
const template = templates.find(t => t.id === templateId);
|
||||
if (!template) return;
|
||||
|
||||
const atendimento = atendimentos.find(a => a.id === selectedAtendimento);
|
||||
if (!atendimento) return;
|
||||
|
||||
// Buscar dados do atendimento com as relações necessárias
|
||||
const [atendimentoDetalhado, usuarioRes, configRes] = await Promise.all([
|
||||
api.get(`/atendimentos/${atendimento.id}`),
|
||||
api.get('/auth/me'),
|
||||
api.get('/documentos/configuracoes')
|
||||
]);
|
||||
|
||||
// Formatar endereço completo e outros dados do cliente
|
||||
const cliente = atendimentoDetalhado.data.cliente;
|
||||
const enderecoCompleto = `${cliente.endereco}, ${cliente.numero}${cliente.complemento ? `, ${cliente.complemento}` : ''}, ${cliente.bairro}, ${cliente.cidade}/${cliente.estado}, CEP: ${cliente.cep}`;
|
||||
|
||||
// Formatar data extenso corretamente
|
||||
const formatadorData = new Intl.DateTimeFormat('pt-BR', {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric'
|
||||
});
|
||||
|
||||
// Preparar variáveis com dados formatados
|
||||
const variables = {
|
||||
cliente: {
|
||||
...cliente,
|
||||
enderecoCompleto,
|
||||
nome: cliente.nome || '',
|
||||
cpf: cliente.cpfCnpj || '', // Adicionar cpf como alias para cpfCnpj
|
||||
cpfCnpj: cliente.cpfCnpj || '', // Manter cpfCnpj também
|
||||
rg: cliente.rg || '',
|
||||
estadoCivil: cliente.estadoCivil || '',
|
||||
profissao: cliente.profissao || '',
|
||||
nacionalidade: cliente.nacionalidade || 'brasileiro(a)',
|
||||
nomePai: cliente.nomePai || '',
|
||||
nomeMae: cliente.nomeMae || ''
|
||||
},
|
||||
atendimento: atendimentoDetalhado.data,
|
||||
processo: atendimentoDetalhado.data.processo,
|
||||
advogado: {
|
||||
...usuarioRes.data,
|
||||
oabCompleta: `${usuarioRes.data.oab}/${usuarioRes.data.oabUF}`
|
||||
},
|
||||
escritorio: configRes.data,
|
||||
data: {
|
||||
atual: new Date().toLocaleDateString('pt-BR'),
|
||||
atualExtenso: formatadorData.format(new Date()), // Formatar a data corretamente
|
||||
dia: new Date().getDate().toString(),
|
||||
mes: (new Date().getMonth() + 1).toString(),
|
||||
mesExtenso: new Intl.DateTimeFormat('pt-BR', { month: 'long' }).format(new Date()),
|
||||
ano: new Date().getFullYear().toString()
|
||||
}
|
||||
};
|
||||
|
||||
// Teste para debug
|
||||
console.log('Data por extenso:', variables.data.atualExtenso);
|
||||
|
||||
// Preencher template
|
||||
const conteudoPreenchido = template.conteudo.replace(/\{\{([^}]+)\}\}/g, (match, path) => {
|
||||
try {
|
||||
const valor = path.split('.').reduce((obj, key) => obj?.[key], variables);
|
||||
return valor !== undefined ? valor : match;
|
||||
} catch (error) {
|
||||
console.warn(`Erro ao processar variável ${path}:`, error);
|
||||
return match;
|
||||
}
|
||||
});
|
||||
|
||||
setContent(conteudoPreenchido);
|
||||
setNome(`${template.nome} - ${cliente.nome}`);
|
||||
setTipo(template.tipo);
|
||||
|
||||
// Debug para verificar substituições
|
||||
console.log('Template original:', template.conteudo);
|
||||
console.log('Conteúdo processado:', conteudoPreenchido);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar template:', error);
|
||||
toast.error('Erro ao carregar template. Verifique se o atendimento possui um cliente vinculado.');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
// Verificação de atendimento apenas para novos documentos
|
||||
if (!documento && !selectedAtendimento) {
|
||||
toast.error('Selecione um atendimento');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSaving(true);
|
||||
await onSave({
|
||||
nome,
|
||||
tipo,
|
||||
conteudo: content,
|
||||
atendimentoId: documento?.atendimentoId || selectedAtendimento,
|
||||
processoId: documento?.processoId || processoId
|
||||
});
|
||||
toast.success('Documento salvo com sucesso');
|
||||
onClose();
|
||||
} catch (error) {
|
||||
toast.error('Erro ao salvar documento');
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} maxWidth="lg" fullWidth>
|
||||
<DialogTitle className="sticky top-0 bg-white z-10 border-b">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex gap-4">
|
||||
<select
|
||||
value={selectedAtendimento || ''}
|
||||
onChange={(e) => setSelectedAtendimento(e.target.value)}
|
||||
className="flex-1 p-2 border rounded"
|
||||
>
|
||||
<option value="">Selecione um atendimento</option>
|
||||
{atendimentos.map(atendimento => (
|
||||
<option key={atendimento.id} value={atendimento.id}>
|
||||
{atendimento.protocolo} - {atendimento.cliente.nome}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<select
|
||||
value={selectedTemplate || ''}
|
||||
onChange={(e) => handleTemplateSelect(e.target.value)}
|
||||
className="flex-1 p-2 border rounded"
|
||||
>
|
||||
<option value="">Selecione um template</option>
|
||||
{templates.map(template => (
|
||||
<option key={template.id} value={template.id}>
|
||||
{template.nome}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
value={nome}
|
||||
onChange={(e) => setNome(e.target.value)}
|
||||
placeholder="Nome do documento"
|
||||
className="w-full px-2 py-1 border border-gray-300 rounded"
|
||||
/>
|
||||
</div>
|
||||
<select
|
||||
value={tipo}
|
||||
onChange={(e) => setTipo(e.target.value)}
|
||||
className="ml-4 px-2 py-1 border border-gray-300 rounded"
|
||||
>
|
||||
<option value="PETICAO">Petição</option>
|
||||
<option value="CONTRATO">Contrato</option>
|
||||
<option value="PROCURACAO">Procuração</option>
|
||||
<option value="DECLARACAO">Declaração</option>
|
||||
<option value="OUTROS">Outros</option>
|
||||
</select>
|
||||
</div>
|
||||
</DialogTitle>
|
||||
|
||||
<DialogContent className="max-h-[80vh] overflow-y-auto">
|
||||
<Editor
|
||||
apiKey={import.meta.env.VITE_TINYMCE_API_KEY}
|
||||
init={{
|
||||
height: 500,
|
||||
menubar: true,
|
||||
plugins: [
|
||||
'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
|
||||
'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
|
||||
'insertdatetime', 'media', 'table', 'help', 'wordcount'
|
||||
],
|
||||
toolbar: 'undo redo | formatselect | ' +
|
||||
'bold italic backcolor | alignleft aligncenter ' +
|
||||
'alignright alignjustify | bullist numlist outdent indent | ' +
|
||||
'removeformat | help',
|
||||
language: 'pt_BR', // Adicionar configuração de idioma
|
||||
language_url: '/tinymce/langs/pt_BR.js', // Adicionar URL do arquivo de idioma
|
||||
content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
|
||||
// Adicionar estas configurações
|
||||
promotion: false,
|
||||
branding: false,
|
||||
preview_styles: false,
|
||||
referrer_policy: 'origin',
|
||||
disable_stats: true // Desabilitar estatísticas
|
||||
}}
|
||||
value={content}
|
||||
onEditorChange={setContent}
|
||||
/>
|
||||
</DialogContent>
|
||||
|
||||
<DialogActions className="sticky bottom-0 bg-white z-10 border-t px-4 py-3">
|
||||
<Button onClick={onClose} startIcon={<XMarkIcon className="w-4 h-4" />}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={isSaving || !nome}
|
||||
startIcon={<SaveIcon className="w-4 h-4" />}
|
||||
variant="contained"
|
||||
>
|
||||
Salvar
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { XMarkIcon, PrinterIcon, DocumentArrowDownIcon } from '@heroicons/react/24/outline';
|
||||
import { api } from '../../lib/api';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface DocumentoViewerProps {
|
||||
documento: any;
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export function DocumentoViewer({ documento, isOpen, onClose }: DocumentoViewerProps) {
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
const handlePrint = () => {
|
||||
const printWindow = window.open('', '_blank');
|
||||
if (!printWindow) return;
|
||||
|
||||
const html = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>${documento?.nome || 'Documento'}</title>
|
||||
<style>
|
||||
@page {
|
||||
size: A4;
|
||||
margin: 3cm 2cm 2cm 3cm;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: white;
|
||||
font-size: 12pt;
|
||||
}
|
||||
|
||||
.header {
|
||||
position: running(header);
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.footer {
|
||||
position: running(footer);
|
||||
width: 100%;
|
||||
text-align: center;
|
||||
font-size: 10pt;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid #ccc;
|
||||
}
|
||||
|
||||
@page {
|
||||
@top-center { content: element(header) }
|
||||
@bottom-center { content: element(footer) }
|
||||
}
|
||||
|
||||
.content {
|
||||
margin: 0 auto;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 16pt;
|
||||
text-align: center;
|
||||
margin: 2em 0;
|
||||
}
|
||||
|
||||
p {
|
||||
text-align: justify;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
.assinatura {
|
||||
margin-top: 4em;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.local-data {
|
||||
text-align: right;
|
||||
margin: 3em 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="header">
|
||||
<h2 style="margin:0;font-size:14pt">${documento?.escritorio?.nome || ''}</h2>
|
||||
</div>
|
||||
|
||||
<div class="content">
|
||||
${documento?.conteudo || ''}
|
||||
</div>
|
||||
|
||||
<div class="footer">
|
||||
${documento?.escritorio?.endereco || ''}<br>
|
||||
Tel: ${documento?.escritorio?.telefone || ''} | Email: ${documento?.escritorio?.email || ''}
|
||||
</div>
|
||||
|
||||
<script>
|
||||
window.onload = function() {
|
||||
window.print();
|
||||
setTimeout(window.close, 500);
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
|
||||
printWindow.document.write(html);
|
||||
printWindow.document.close();
|
||||
};
|
||||
|
||||
const handleExportPDF = async () => {
|
||||
try {
|
||||
setIsExporting(true);
|
||||
toast.info('Gerando PDF, aguarde...', { autoClose: false, toastId: 'generating-pdf' });
|
||||
|
||||
// Buscar configurações atualizadas do escritório
|
||||
const response = await api.post('/documentos/exportar-pdf', {
|
||||
conteudo: documento.conteudo,
|
||||
escritorio: documento.escritorio
|
||||
}, {
|
||||
responseType: 'blob',
|
||||
headers: {
|
||||
'Accept': 'application/pdf'
|
||||
}
|
||||
});
|
||||
|
||||
// Criar e baixar o arquivo
|
||||
const blob = new Blob([response.data], { type: 'application/pdf' });
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.setAttribute('download', `${documento.nome || 'documento'}.pdf`);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
|
||||
// Limpeza
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(link);
|
||||
|
||||
toast.dismiss('generating-pdf');
|
||||
toast.success('PDF gerado com sucesso!');
|
||||
} catch (error) {
|
||||
console.error('Erro ao gerar PDF:', error);
|
||||
toast.dismiss('generating-pdf');
|
||||
toast.error('Erro ao gerar o PDF');
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={isOpen}
|
||||
onClose={onClose}
|
||||
className="relative z-50"
|
||||
>
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-4xl bg-white rounded-lg shadow-xl">
|
||||
<div className="flex items-center justify-between p-4 border-b">
|
||||
<Dialog.Title className="text-lg font-semibold">
|
||||
{documento?.nome}
|
||||
</Dialog.Title>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={handleExportPDF}
|
||||
disabled={isExporting}
|
||||
className={`inline-flex items-center px-3 py-2 ${
|
||||
isExporting
|
||||
? 'bg-blue-400 cursor-not-allowed'
|
||||
: 'bg-blue-600 hover:bg-blue-700'
|
||||
} text-white rounded`}
|
||||
>
|
||||
{isExporting ? (
|
||||
<>
|
||||
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Gerando PDF...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<DocumentArrowDownIcon className="w-5 h-5 mr-2" />
|
||||
Exportar PDF
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="inline-flex items-center px-3 py-2 bg-gray-100 text-gray-600 rounded hover:bg-gray-200"
|
||||
>
|
||||
<XMarkIcon className="w-5 h-5 mr-2" />
|
||||
Fechar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-6 max-h-[70vh] overflow-y-auto">
|
||||
<div className="max-w-[21cm] mx-auto bg-white shadow-lg p-8">
|
||||
<div className="text-center mb-8 pb-4 border-b">
|
||||
<h2 className="text-xl font-bold">
|
||||
{documento?.escritorio?.nome || 'Nome do Escritório'}
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="prose max-w-none"
|
||||
dangerouslySetInnerHTML={{ __html: documento?.conteudo }}
|
||||
/>
|
||||
|
||||
<div className="text-center mt-8 pt-4 border-t text-sm text-gray-600">
|
||||
{documento?.escritorio?.endereco}<br/>
|
||||
{documento?.escritorio?.telefone} | {documento?.escritorio?.email}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||
import { DocumentIcon, PlusIcon, TrashIcon, EyeIcon, CogIcon } from '@heroicons/react/24/outline';
|
||||
import { DocumentoEditor } from './DocumentoEditor';
|
||||
import { api } from '../lib/api';
|
||||
import { toast } from 'react-toastify';
|
||||
import { useAuth } from '../contexts/AuthContext';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { DocumentoViewer } from './DocumentoViewer';
|
||||
|
||||
export function DocumentosPage() {
|
||||
const [isEditorOpen, setIsEditorOpen] = useState(false);
|
||||
const [documentos, setDocumentos] = useState([]);
|
||||
const [modelos, setModelos] = useState([]);
|
||||
const [tabValue, setTabValue] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { processoId, atendimentoId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const { user, signOut } = useAuth();
|
||||
const [documentoVisualizado, setDocumentoVisualizado] = useState(null);
|
||||
const [isVisualizadorOpen, setVisualizadorOpen] = useState(false);
|
||||
|
||||
const loadData = useCallback(async () => {
|
||||
if (!user) {
|
||||
navigate('/login');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsLoading(true);
|
||||
await Promise.all([loadDocumentos(), loadModelos()]);
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar dados:', error);
|
||||
if (error?.response?.status === 401) {
|
||||
signOut(); // Usar a função do AuthContext
|
||||
navigate('/login');
|
||||
} else {
|
||||
toast.error('Erro ao carregar dados');
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [user, navigate, signOut]); // Adicionar signOut nas dependências
|
||||
|
||||
useEffect(() => {
|
||||
loadData();
|
||||
}, [loadData, processoId, atendimentoId]);
|
||||
|
||||
const loadDocumentos = async () => {
|
||||
const params = {};
|
||||
if (processoId) params.processoId = processoId;
|
||||
if (atendimentoId) params.atendimentoId = atendimentoId;
|
||||
|
||||
const response = await api.get('/documentos', { params });
|
||||
setDocumentos(response.data);
|
||||
};
|
||||
|
||||
const loadModelos = async () => {
|
||||
const response = await api.get('/documentos-modelos');
|
||||
setModelos(response.data);
|
||||
};
|
||||
|
||||
const handleSave = async (data) => {
|
||||
try {
|
||||
if (processoId) data.processoId = processoId;
|
||||
if (atendimentoId) data.atendimentoId = atendimentoId;
|
||||
|
||||
await api.post('/documentos', data);
|
||||
toast.success('Documento salvo com sucesso');
|
||||
await loadDocumentos();
|
||||
setIsEditorOpen(false);
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar documento:', error);
|
||||
if (error?.response?.status === 401) {
|
||||
toast.error('Sessão expirada. Por favor, faça login novamente.');
|
||||
} else {
|
||||
toast.error('Erro ao salvar documento');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteDocumento = async (id) => {
|
||||
try {
|
||||
await api.delete(`/documentos/${id}`);
|
||||
toast.success('Documento excluído com sucesso');
|
||||
await loadDocumentos();
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir documento:', error);
|
||||
if (error?.response?.status === 401) {
|
||||
toast.error('Sessão expirada. Por favor, faça login novamente.');
|
||||
} else {
|
||||
toast.error('Erro ao excluir documento');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleVisualizar = async (documento) => {
|
||||
try {
|
||||
const configRes = await api.get('/documentos/configuracoes');
|
||||
|
||||
setDocumentoVisualizado({
|
||||
...documento,
|
||||
escritorio: configRes.data
|
||||
});
|
||||
setVisualizadorOpen(true);
|
||||
} catch (error) {
|
||||
console.error('Erro ao visualizar documento:', error);
|
||||
toast.error('Erro ao visualizar documento');
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Carregando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-bold">Documentos</h1>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => setIsEditorOpen(true)}
|
||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
Novo Documento
|
||||
</button>
|
||||
{user?.perfil === 'ADVOGADO_ADMIN' && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => navigate('/documentos/templates')}
|
||||
className="inline-flex items-center px-4 py-2 border border-blue-600 text-blue-600 rounded-md hover:bg-blue-50 transition-colors"
|
||||
>
|
||||
<DocumentIcon className="w-5 h-5 mr-2" />
|
||||
Gerenciar Templates
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigate('/documentos/configuracoes')}
|
||||
className="inline-flex items-center px-4 py-2 border border-blue-600 text-blue-600 rounded-md hover:bg-blue-50 transition-colors"
|
||||
>
|
||||
<CogIcon className="w-5 h-5 mr-2" />
|
||||
Configurar Timbrado
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-b border-gray-200">
|
||||
<nav className="flex -mb-px">
|
||||
<button
|
||||
onClick={() => setTabValue(0)}
|
||||
className={`px-4 py-2 font-medium text-sm border-b-2 transition-colors duration-200 ${
|
||||
tabValue === 0
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
Documentos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setTabValue(1)}
|
||||
className={`ml-8 px-4 py-2 font-medium text-sm border-b-2 transition-colors duration-200 ${
|
||||
tabValue === 1
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
|
||||
}`}
|
||||
>
|
||||
Modelos
|
||||
</button>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{tabValue === 0 && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{documentos.map((doc) => (
|
||||
<div key={doc.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||
<div className="p-4">
|
||||
<div className="flex items-center mb-3">
|
||||
<DocumentIcon className="w-6 h-6 text-gray-500 mr-2" />
|
||||
<h3 className="font-semibold text-gray-900 dark:text-gray-100">{doc.nome}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400">
|
||||
Criado em: {new Date(doc.criadoEm).toLocaleDateString()}
|
||||
</p>
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button
|
||||
onClick={() => handleVisualizar(doc)}
|
||||
className="inline-flex items-center px-3 py-1.5 text-sm text-blue-600 border border-blue-200 rounded-md hover:bg-blue-50"
|
||||
>
|
||||
<EyeIcon className="w-4 h-4 mr-1" />
|
||||
Visualizar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteDocumento(doc.id)}
|
||||
className="inline-flex items-center px-3 py-1.5 text-sm text-red-600 dark:text-red-400 border border-red-200 dark:border-red-900 rounded-md hover:bg-red-50 dark:hover:bg-red-900/20"
|
||||
>
|
||||
<TrashIcon className="w-4 h-4 mr-1" />
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tabValue === 1 && (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{modelos.map((modelo) => (
|
||||
<div key={modelo.id} className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
|
||||
<div className="p-4">
|
||||
<div className="flex items-center mb-3">
|
||||
<DocumentIcon className="w-6 h-6 text-gray-500 mr-2" />
|
||||
<h3 className="font-semibold text-gray-900 dark:text-gray-100">{modelo.nome}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{modelo.descricao}</p>
|
||||
<button
|
||||
className="w-full inline-flex items-center justify-center px-4 py-2 text-sm border border-blue-600 text-blue-600 rounded-md hover:bg-blue-50 dark:hover:bg-blue-900/20"
|
||||
>
|
||||
Usar Modelo
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DocumentoEditor
|
||||
isOpen={isEditorOpen}
|
||||
onClose={() => setIsEditorOpen(false)}
|
||||
onSave={handleSave}
|
||||
processoId={processoId}
|
||||
atendimentoId={atendimentoId}
|
||||
/>
|
||||
|
||||
<DocumentoViewer
|
||||
documento={documentoVisualizado}
|
||||
isOpen={isVisualizadorOpen}
|
||||
onClose={() => setVisualizadorOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { api } from '../../lib/api';
|
||||
import { Editor } from '@tinymce/tinymce-react';
|
||||
import { toast } from 'react-toastify';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { DocumentIcon, PencilIcon, TrashIcon, PlusIcon } from '@heroicons/react/24/outline';
|
||||
import { DOCUMENT_VARIABLES } from '../../utils/documentVariables';
|
||||
|
||||
export function GerenciarTemplates() {
|
||||
const [templates, setTemplates] = useState([]);
|
||||
const [editingTemplate, setEditingTemplate] = useState(null);
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [isEditorModalOpen, setEditorModalOpen] = useState(false);
|
||||
const [formData, setFormData] = useState({
|
||||
nome: '',
|
||||
tipo: 'OUTROS',
|
||||
descricao: '',
|
||||
conteudo: '',
|
||||
variaveis: []
|
||||
});
|
||||
|
||||
const loadTemplates = async () => {
|
||||
try {
|
||||
const response = await api.get('/documentos-modelos');
|
||||
setTemplates(response.data);
|
||||
} catch (error) {
|
||||
toast.error('Erro ao carregar templates');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
loadTemplates();
|
||||
}, []);
|
||||
|
||||
const handleSaveTemplate = async (data) => {
|
||||
try {
|
||||
if (editingTemplate) {
|
||||
await api.put(`/documentos-modelos/${editingTemplate.id}`, data);
|
||||
toast.success('Template atualizado com sucesso');
|
||||
} else {
|
||||
await api.post('/documentos-modelos', data);
|
||||
toast.success('Template criado com sucesso');
|
||||
}
|
||||
loadTemplates();
|
||||
setIsModalOpen(false);
|
||||
} catch (error) {
|
||||
toast.error('Erro ao salvar template');
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
// Verifica se está editando ou criando novo
|
||||
if (editingTemplate) {
|
||||
await api.put(`/documentos-modelos/${editingTemplate.id}`, {
|
||||
...formData,
|
||||
id: editingTemplate.id // Garantir que o ID seja enviado
|
||||
});
|
||||
toast.success('Template atualizado com sucesso');
|
||||
} else {
|
||||
await api.post('/documentos-modelos', formData);
|
||||
toast.success('Template criado com sucesso');
|
||||
}
|
||||
|
||||
setEditorModalOpen(false);
|
||||
setEditingTemplate(null);
|
||||
await loadTemplates(); // Recarregar a lista após salvar
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar template:', error);
|
||||
toast.error('Erro ao salvar template');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (templateId: string) => {
|
||||
if (!window.confirm('Tem certeza que deseja excluir este template?')) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await api.delete(`/documentos-modelos/${templateId}`);
|
||||
toast.success('Template excluído com sucesso');
|
||||
loadTemplates();
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir template:', error);
|
||||
toast.error('Erro ao excluir template');
|
||||
}
|
||||
};
|
||||
|
||||
const insertVariable = (variable: string) => {
|
||||
const editor = window.tinymce.activeEditor;
|
||||
if (editor) {
|
||||
editor.insertContent(variable);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (template) => {
|
||||
setEditingTemplate(template); // Guardar o template completo
|
||||
setFormData({
|
||||
...template,
|
||||
id: template.id // Garantir que o ID seja mantido
|
||||
});
|
||||
setEditorModalOpen(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h1 className="text-2xl font-bold">Gerenciar Templates</h1>
|
||||
<button
|
||||
onClick={() => {
|
||||
setFormData({
|
||||
nome: '',
|
||||
tipo: 'OUTROS',
|
||||
descricao: '',
|
||||
conteudo: '',
|
||||
variaveis: []
|
||||
});
|
||||
setEditorModalOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
||||
>
|
||||
<PlusIcon className="w-5 h-5 mr-2" />
|
||||
Novo Template
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{templates.map((template) => (
|
||||
<div key={template.id} className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
|
||||
<div className="flex items-center mb-3">
|
||||
<DocumentIcon className="w-6 h-6 text-gray-500 mr-2" />
|
||||
<h3 className="font-semibold">{template.nome}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">{template.descricao}</p>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
onClick={() => handleEdit(template)}
|
||||
className="inline-flex items-center px-3 py-1.5 text-sm text-blue-600 border border-blue-200 rounded-md hover:bg-blue-50"
|
||||
>
|
||||
<PencilIcon className="w-4 h-4 mr-1" />
|
||||
Editar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(template.id)}
|
||||
className="inline-flex items-center px-3 py-1.5 text-sm text-red-600 border border-red-200 rounded-md hover:bg-red-50"
|
||||
>
|
||||
<TrashIcon className="w-4 h-4 mr-1" />
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Modal de Edição */}
|
||||
<Dialog open={isEditorModalOpen} onClose={() => setEditorModalOpen(false)} className="relative z-50">
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4 overflow-y-auto">
|
||||
<Dialog.Panel className="w-full max-w-4xl bg-white rounded-lg shadow-xl my-4">
|
||||
<div className="max-h-[90vh] overflow-y-auto">
|
||||
<form onSubmit={handleSubmit} className="p-6">
|
||||
<h2 className="text-xl font-bold mb-4">
|
||||
{editingTemplate ? 'Editar Template' : 'Novo Template'}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block mb-1">Nome</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.nome}
|
||||
onChange={(e) => setFormData({...formData, nome: e.target.value})}
|
||||
className="w-full p-2 border rounded"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-1">Tipo</label>
|
||||
<select
|
||||
value={formData.tipo}
|
||||
onChange={(e) => setFormData({...formData, tipo: e.target.value})}
|
||||
className="w-full p-2 border rounded"
|
||||
>
|
||||
<option value="PETICAO">Petição</option>
|
||||
<option value="CONTRATO">Contrato</option>
|
||||
<option value="PROCURACAO">Procuração</option>
|
||||
<option value="DECLARACAO">Declaração</option>
|
||||
<option value="OUTROS">Outros</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-1">Descrição</label>
|
||||
<textarea
|
||||
value={formData.descricao}
|
||||
onChange={(e) => setFormData({...formData, descricao: e.target.value})}
|
||||
className="w-full p-2 border rounded"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-4">
|
||||
<label className="block mb-1">Variáveis Disponíveis</label>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2 p-2 border rounded bg-gray-50">
|
||||
{Object.entries(DOCUMENT_VARIABLES).map(([category, variables]) => (
|
||||
<div key={category} className="space-y-1">
|
||||
<h4 className="font-bold text-sm text-gray-700">{category}</h4>
|
||||
{Object.entries(variables).map(([name, variable]) => (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
onClick={() => insertVariable(variable)}
|
||||
className="text-xs text-blue-600 hover:text-blue-800 block"
|
||||
>
|
||||
{name.replace(/_/g, ' ')}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block mb-1">Conteúdo</label>
|
||||
<Editor
|
||||
apiKey={import.meta.env.VITE_TINYMCE_API_KEY}
|
||||
value={formData.conteudo}
|
||||
onEditorChange={(content) => setFormData({...formData, conteudo: content})}
|
||||
init={{
|
||||
height: 400,
|
||||
menubar: true,
|
||||
plugins: [
|
||||
'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
|
||||
'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
|
||||
'insertdatetime', 'media', 'table', 'help', 'wordcount'
|
||||
],
|
||||
toolbar: 'variables | undo redo | formatselect | bold italic | alignleft aligncenter alignright',
|
||||
setup: (editor) => {
|
||||
editor.ui.registry.addMenuButton('variables', {
|
||||
text: 'Variáveis',
|
||||
fetch: (callback) => {
|
||||
const items = Object.entries(DOCUMENT_VARIABLES).flatMap(([category, vars]) =>
|
||||
Object.entries(vars).map(([name, value]) => ({
|
||||
type: 'menuitem',
|
||||
text: `${category} - ${name.replace(/_/g, ' ')}`,
|
||||
onAction: () => editor.insertContent(value)
|
||||
}))
|
||||
);
|
||||
callback(items);
|
||||
}
|
||||
});
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 mt-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setEditorModalOpen(false)}
|
||||
className="px-4 py-2 text-gray-600 border rounded-md hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useState } from 'react';
|
||||
import { DocumentoService } from '../../services/DocumentoService';
|
||||
import { TIPOS_DOCUMENTO } from '../../utils/documentTemplates';
|
||||
|
||||
export function NovoDocumento() {
|
||||
const [tipo, setTipo] = useState(TIPOS_DOCUMENTO.PROCURACAO);
|
||||
|
||||
const handleGerar = async () => {
|
||||
// 1. Buscar dados necessários
|
||||
const cliente = await api.get(`/clientes/${clienteId}`);
|
||||
const advogado = await api.get('/usuarios/me');
|
||||
|
||||
// 2. Preparar variáveis
|
||||
const variaveis = {
|
||||
cliente: cliente.data,
|
||||
advogado: advogado.data,
|
||||
cidade: 'São Paulo',
|
||||
data: new Date().toLocaleDateString()
|
||||
};
|
||||
|
||||
// 3. Buscar configurações do escritório
|
||||
const config = await api.get('/configuracoes');
|
||||
|
||||
// 4. Gerar documento
|
||||
const documento = DocumentoService.gerarDocumento({
|
||||
tipo,
|
||||
variaveis,
|
||||
config: config.data
|
||||
});
|
||||
|
||||
// 5. Salvar ou exibir
|
||||
console.log(documento);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<select value={tipo} onChange={e => setTipo(e.target.value)}>
|
||||
<option value={TIPOS_DOCUMENTO.PROCURACAO}>Procuração</option>
|
||||
<option value={TIPOS_DOCUMENTO.CONTRATO}>Contrato</option>
|
||||
{/* ... */}
|
||||
</select>
|
||||
|
||||
<button onClick={handleGerar}>
|
||||
Gerar Documento
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import React, { forwardRef } from "react";
|
||||
|
||||
interface FormCheckboxProps
|
||||
extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const FormCheckbox = forwardRef<HTMLInputElement, FormCheckboxProps>(
|
||||
({ label, ...props }, ref) => (
|
||||
<label className="flex items-center space-x-3 cursor-pointer group">
|
||||
<input
|
||||
type="checkbox"
|
||||
ref={ref}
|
||||
className="
|
||||
w-5 h-5 rounded
|
||||
border-gray-300 text-blue-600
|
||||
focus:ring-2 focus:ring-blue-500
|
||||
transition duration-150 ease-in-out
|
||||
cursor-pointer
|
||||
"
|
||||
{...props}
|
||||
/>
|
||||
<span className="text-sm text-gray-700 group-hover:text-gray-900">
|
||||
{label}
|
||||
</span>
|
||||
</label>
|
||||
),
|
||||
);
|
||||
|
||||
FormCheckbox.displayName = "FormCheckbox";
|
||||
@@ -0,0 +1,43 @@
|
||||
import React, { forwardRef } from "react";
|
||||
|
||||
interface FormInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
label: string;
|
||||
error?: string;
|
||||
multiline?: boolean;
|
||||
}
|
||||
|
||||
export const FormInput = forwardRef<HTMLInputElement, FormInputProps>(
|
||||
({ label, error, className = "", multiline, ...props }, ref) => {
|
||||
const Component = multiline ? 'textarea' : 'input';
|
||||
|
||||
return (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<Component
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg
|
||||
border border-gray-300
|
||||
bg-white text-gray-900
|
||||
transition duration-150 ease-in-out
|
||||
placeholder-gray-400
|
||||
focus:ring-2 focus:ring-blue-500 focus:border-transparent
|
||||
hover:border-gray-400
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
/>
|
||||
{error && (
|
||||
<div className="absolute -bottom-5 left-0">
|
||||
<p className="text-xs text-red-500">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
FormInput.displayName = "FormInput";
|
||||
@@ -0,0 +1,52 @@
|
||||
import React, { forwardRef } from "react";
|
||||
|
||||
interface Option {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface FormSelectProps
|
||||
extends React.SelectHTMLAttributes<HTMLSelectElement> {
|
||||
label: string;
|
||||
error?: string;
|
||||
options: Option[];
|
||||
}
|
||||
|
||||
export const FormSelect = forwardRef<HTMLSelectElement, FormSelectProps>(
|
||||
({ label, error, options, className = "", ...props }, ref) => (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<select
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg
|
||||
border border-gray-300
|
||||
bg-white text-gray-900
|
||||
transition duration-150 ease-in-out
|
||||
focus:ring-2 focus:ring-blue-500 focus:border-transparent
|
||||
hover:border-gray-400
|
||||
appearance-none
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
>
|
||||
<option value="">Selecione...</option>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{error && (
|
||||
<div className="absolute -bottom-5 left-0">
|
||||
<p className="text-xs text-red-500">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
FormSelect.displayName = "FormSelect";
|
||||
@@ -0,0 +1,3 @@
|
||||
export { FormInput } from "./FormInput";
|
||||
export { FormSelect } from "./FormSelect";
|
||||
export { FormCheckbox } from "./FormCheckbox";
|
||||
@@ -0,0 +1,71 @@
|
||||
import React, { forwardRef } from 'react';
|
||||
|
||||
export const FormInput = forwardRef<HTMLInputElement, any>(
|
||||
({ label, error, className = "", ...props }, ref) => (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<input
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-2 rounded-lg
|
||||
border border-gray-300 dark:border-gray-600
|
||||
bg-white dark:bg-gray-700
|
||||
text-gray-900 dark:text-white
|
||||
placeholder-gray-400 dark:placeholder-gray-500
|
||||
focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400
|
||||
focus:border-transparent
|
||||
transition-colors
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
/>
|
||||
{error && (
|
||||
<p className="mt-1 text-sm text-red-600 dark:text-red-400">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
|
||||
export const FormSelect = forwardRef<HTMLSelectElement, any>(
|
||||
({ label, error, options, className = "", ...props }, ref) => (
|
||||
<div className={`${className} relative`}>
|
||||
<label className="block text-sm font-semibold text-gray-700 dark:text-gray-300 mb-2">
|
||||
{label}
|
||||
{props.required && <span className="text-red-500 ml-1">*</span>}
|
||||
</label>
|
||||
<select
|
||||
ref={ref}
|
||||
className={`
|
||||
w-full px-4 py-3 rounded-lg
|
||||
border border-gray-300 dark:border-gray-600
|
||||
bg-white dark:bg-gray-700
|
||||
text-gray-900 dark:text-white
|
||||
transition duration-150 ease-in-out
|
||||
focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400
|
||||
focus:border-transparent
|
||||
hover:border-gray-400 dark:hover:border-gray-500
|
||||
appearance-none
|
||||
${error ? "border-red-300 focus:ring-red-500" : ""}
|
||||
`}
|
||||
{...props}
|
||||
>
|
||||
<option value="" className="dark:bg-gray-700">Selecione...</option>
|
||||
{options?.map((opt: any) => (
|
||||
<option key={opt.value} value={opt.value} className="dark:bg-gray-700">
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{error && (
|
||||
<div className="absolute -bottom-5 left-0">
|
||||
<p className="text-xs text-red-500 dark:text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
|
||||
// Adicione classes dark mode similares para outros componentes de formulário
|
||||
@@ -0,0 +1,319 @@
|
||||
import React, { useState, Fragment, useEffect } from "react";
|
||||
import { Outlet, Link, useLocation } from "react-router-dom";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
import {
|
||||
BellIcon,
|
||||
ChevronDownIcon,
|
||||
MoonIcon,
|
||||
SunIcon,
|
||||
HomeIcon,
|
||||
ScaleIcon,
|
||||
UserGroupIcon,
|
||||
UserIcon,
|
||||
ClipboardDocumentCheckIcon,
|
||||
DocumentTextIcon,
|
||||
DocumentCheckIcon,
|
||||
ArrowUpTrayIcon,
|
||||
ShieldCheckIcon,
|
||||
CurrencyDollarIcon,
|
||||
CalculatorIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import api from "../../services/api";
|
||||
import { useTheme } from "../../contexts/ThemeContext";
|
||||
|
||||
// Importando o ícone para cálculos judiciais
|
||||
import CalculateIcon from '@mui/icons-material/Calculate';
|
||||
// Importar ícones específicos para subcategorias de cálculos
|
||||
import MoneyIcon from '@mui/icons-material/Money';
|
||||
import ChildCareIcon from '@mui/icons-material/ChildCare';
|
||||
|
||||
export const MainLayout: React.FC = () => {
|
||||
const [isSidebarOpen, setSidebarOpen] = useState(true);
|
||||
const location = useLocation();
|
||||
const { user, signOut } = useAuth();
|
||||
const [userProfile, setUserProfile] = useState<any>(null);
|
||||
const { isDarkMode, toggleDarkMode } = useTheme();
|
||||
|
||||
// Adicionar efeito para buscar perfil do usuário
|
||||
useEffect(() => {
|
||||
const getUserProfile = async () => {
|
||||
try {
|
||||
const response = await api.get("/auth/me"); // Removido o /api pois já está no baseURL
|
||||
console.log("Response data:", response.data); // Debug log
|
||||
setUserProfile(response.data);
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar perfil:", error);
|
||||
}
|
||||
};
|
||||
getUserProfile();
|
||||
}, []);
|
||||
|
||||
// Console log para debug
|
||||
useEffect(() => {
|
||||
console.log("Perfil do usuário:", userProfile);
|
||||
}, [userProfile]);
|
||||
|
||||
const menuItems = [
|
||||
{ path: "/dashboard", label: "Dashboard", icon: HomeIcon },
|
||||
{ path: "/processos", label: "Processos", icon: ScaleIcon },
|
||||
{ path: "/processos-administrativos", label: "Proc.Adm", icon: ScaleIcon },
|
||||
{
|
||||
path: null,
|
||||
label: "Provas",
|
||||
icon: DocumentCheckIcon,
|
||||
subitems: [
|
||||
{
|
||||
path: '/provas/upload',
|
||||
label: 'Upload',
|
||||
roles: [],
|
||||
icon: ArrowUpTrayIcon
|
||||
},
|
||||
{
|
||||
path: '/provas/admin',
|
||||
label: 'Admin',
|
||||
roles: ['ADVOGADO_ADMIN'],
|
||||
icon: ShieldCheckIcon
|
||||
}
|
||||
]
|
||||
},
|
||||
{ path: "/clientes", label: "Clientes", icon: UserGroupIcon },
|
||||
{ path: "/atendimentos", label: "Atendimentos", icon: UserIcon },
|
||||
{ path: "/tarefas", label: "Tarefas", icon: ClipboardDocumentCheckIcon },
|
||||
{ path: "/documentos", label: "Documentos", icon: DocumentTextIcon },
|
||||
{
|
||||
path: null,
|
||||
label: "Cálculos",
|
||||
icon: CalculateIcon,
|
||||
roles: ['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE'],
|
||||
subitems: [
|
||||
{
|
||||
path: '/calculos',
|
||||
label: 'Dashboard',
|
||||
roles: ['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE'],
|
||||
icon: HomeIcon
|
||||
},
|
||||
{
|
||||
path: '/calculos/pensao-alimenticia',
|
||||
label: 'Pensão Alimentícia',
|
||||
roles: ['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE'],
|
||||
icon: ChildCareIcon
|
||||
},
|
||||
{
|
||||
path: '/calculos/trabalhistas',
|
||||
label: 'Trabalhistas',
|
||||
roles: ['ADVOGADO_ADMIN', 'ADVOGADO', 'ASSISTENTE'],
|
||||
icon: MoneyIcon
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
// Função para verificar se o caminho atual corresponde ao item do menu
|
||||
const isCurrentPath = (path: string) => {
|
||||
return location.pathname.startsWith(path);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-screen bg-gray-100 dark:bg-gray-900">
|
||||
{/* Sidebar com barra de rolagem */}
|
||||
<div className="w-20 flex flex-col bg-gradient-to-b from-blue-900 via-blue-800 to-blue-900 dark:from-blue-950 dark:via-blue-900 dark:to-blue-950 text-white">
|
||||
{/* Logo - fixo no topo */}
|
||||
<div className="h-16 flex-shrink-0 flex items-center justify-center border-b border-white/10">
|
||||
<span className="text-xl font-bold">A</span>
|
||||
</div>
|
||||
|
||||
{/* Menu de navegação vertical com scroll */}
|
||||
<nav className="flex-1 overflow-y-auto">
|
||||
<div className="py-4">
|
||||
{menuItems.map((item) => (
|
||||
<div key={item.path || item.label} className="px-2 mb-2">
|
||||
{!item.subitems ? (
|
||||
<Link
|
||||
to={item.path}
|
||||
className={`flex flex-col items-center justify-center p-3 rounded-lg transition-colors ${
|
||||
isCurrentPath(item.path)
|
||||
? "bg-white/20"
|
||||
: "hover:bg-white/10"
|
||||
}`}
|
||||
title={item.label}
|
||||
>
|
||||
<item.icon className="h-6 w-6 text-white opacity-80" />
|
||||
<span className="text-xs mt-1 text-white/80">{item.label}</span>
|
||||
</Link>
|
||||
) : (
|
||||
<div className="relative group">
|
||||
<div
|
||||
className="flex flex-col items-center justify-center p-3 rounded-lg transition-colors hover:bg-white/10 cursor-pointer"
|
||||
title={item.label}
|
||||
>
|
||||
<item.icon className="h-6 w-6 text-white opacity-80" />
|
||||
<span className="text-xs mt-1 text-white/80">{item.label}</span>
|
||||
</div>
|
||||
|
||||
{/* Submenu reposicionado */}
|
||||
<div
|
||||
className="fixed z-50"
|
||||
style={{
|
||||
left: '5rem', // w-20 = 80px
|
||||
top: '50%',
|
||||
transform: 'translateY(-50%)'
|
||||
}}
|
||||
>
|
||||
<div className="opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">
|
||||
<div className="bg-blue-800/95 backdrop-blur-sm rounded-lg py-2 px-1 shadow-xl w-[100px] ml-2">
|
||||
{item.subitems.filter(subitem =>
|
||||
!subitem.roles.length ||
|
||||
(userProfile?.perfil && subitem.roles.includes(userProfile.perfil))
|
||||
).map((subitem) => (
|
||||
<Link
|
||||
key={subitem.path}
|
||||
to={subitem.path}
|
||||
className="block px-3 py-2 hover:bg-white/10 rounded-lg transition-colors"
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<subitem.icon className="h-6 w-6 text-white opacity-80" />
|
||||
<span className="text-xs mt-1 text-white/80">{subitem.label}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
</div>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 flex flex-col">
|
||||
{/* Header */}
|
||||
<header className="h-16 bg-white dark:bg-gray-800 shadow-sm">
|
||||
<div className="h-full px-4 flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold text-gray-800 dark:text-gray-200">
|
||||
{menuItems.find((item) => item.path === location.pathname)
|
||||
?.label || "Dashboard"}
|
||||
</h1>
|
||||
<div className="flex items-center space-x-4">
|
||||
{/* Adicionar botão de toggle do tema antes do menu do usuário */}
|
||||
<button
|
||||
onClick={toggleDarkMode}
|
||||
className="p-2 rounded-lg text-gray-500 hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-gray-400"
|
||||
title={isDarkMode ? "Modo claro" : "Modo escuro"}
|
||||
>
|
||||
{isDarkMode ? (
|
||||
<SunIcon className="h-5 w-5" />
|
||||
) : (
|
||||
<MoonIcon className="h-5 w-5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Notificações */}
|
||||
<button className="text-gray-600 hover:text-gray-800 relative">
|
||||
<BellIcon className="h-6 w-6" />
|
||||
<span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-4 h-4 flex items-center justify-center">
|
||||
3
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Menu do usuário */}
|
||||
<Menu as="div" className="relative">
|
||||
<Menu.Button className="flex items-center space-x-3 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg p-2 transition-colors">
|
||||
<img
|
||||
src={`https://ui-avatars.com/api/?name=${user?.nome || "User"}&background=0D8ABC&color=fff`}
|
||||
alt={user?.nome}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
<div className="text-left hidden sm:block">
|
||||
<div className="text-sm font-medium text-gray-700 dark:text-gray-200">
|
||||
{user?.nome}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400">{user?.cargo}</div>
|
||||
</div>
|
||||
<ChevronDownIcon className="w-4 h-4 text-gray-500 dark:text-gray-400" />
|
||||
</Menu.Button>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items className="absolute right-0 mt-2 w-48 rounded-md bg-white dark:bg-gray-800 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
|
||||
<div className="py-1">
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
to="/perfil"
|
||||
className={`${
|
||||
active ? "bg-gray-100 dark:bg-gray-700" : ""
|
||||
} block px-4 py-2 text-sm text-gray-700 dark:text-gray-200`}
|
||||
>
|
||||
Meu Perfil
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
|
||||
{/* Novo item - visível apenas para ADMIN */}
|
||||
{userProfile?.perfil === "ADVOGADO_ADMIN" && (
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
to="/usuarios"
|
||||
className={`${
|
||||
active ? "bg-gray-100 dark:bg-gray-700" : ""
|
||||
} block px-4 py-2 text-sm text-gray-700 dark:text-gray-200`}
|
||||
>
|
||||
Gerenciar Usuários
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
)}
|
||||
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<a
|
||||
href="#configuracoes"
|
||||
className={`${
|
||||
active ? "bg-gray-100 dark:bg-gray-700" : ""
|
||||
} block px-4 py-2 text-sm text-gray-700 dark:text-gray-200`}
|
||||
>
|
||||
Configurações
|
||||
</a>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
onClick={signOut}
|
||||
className={`${
|
||||
active ? "bg-gray-100 dark:bg-gray-700" : ""
|
||||
} block w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400`}
|
||||
>
|
||||
Sair
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content */}
|
||||
<main className="flex-1 overflow-auto p-6 bg-gray-100 dark:bg-gray-900">
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,437 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useAuth } from "../../contexts/AuthContext";
|
||||
import { Usuario } from "../../types/usuario";
|
||||
import api from "../../services/api";
|
||||
import { UF_BRASIL } from "../../utils/constants/estados";
|
||||
|
||||
export function PerfilPage() {
|
||||
const { user } = useAuth();
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [formData, setFormData] = useState<Partial<Usuario>>(user || {});
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
const [senhaForm, setSenhaForm] = useState({
|
||||
senhaAtual: "",
|
||||
novaSenha: "",
|
||||
confirmarSenha: "",
|
||||
});
|
||||
const [senhaError, setSenhaError] = useState("");
|
||||
const [senhaSuccess, setSenhaSuccess] = useState("");
|
||||
const [loadingSenha, setLoadingSenha] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const loadProfile = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await api.get(`/usuarios/${user?.id}`);
|
||||
setFormData(response.data);
|
||||
setError("");
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar perfil:", error);
|
||||
setError("Erro ao carregar perfil");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (user?.id) {
|
||||
loadProfile();
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
setSuccess("");
|
||||
|
||||
try {
|
||||
await api.put(`/usuarios/${user?.id}`, formData);
|
||||
setSuccess("Perfil atualizado com sucesso!");
|
||||
setIsEditing(false);
|
||||
} catch (error) {
|
||||
setError("Erro ao atualizar perfil");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [field]: value }));
|
||||
};
|
||||
|
||||
const handleSenhaSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (senhaForm.novaSenha !== senhaForm.confirmarSenha) {
|
||||
setSenhaError("As senhas não coincidem");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoadingSenha(true);
|
||||
setSenhaError("");
|
||||
setSenhaSuccess("");
|
||||
|
||||
try {
|
||||
await api.post(`/usuarios/${user?.id}/alterar-senha`, {
|
||||
senhaAtual: senhaForm.senhaAtual,
|
||||
novaSenha: senhaForm.novaSenha,
|
||||
});
|
||||
setSenhaSuccess("Senha alterada com sucesso!");
|
||||
setSenhaForm({ senhaAtual: "", novaSenha: "", confirmarSenha: "" });
|
||||
} catch (error) {
|
||||
setSenhaError("Erro ao alterar senha. Verifique sua senha atual.");
|
||||
} finally {
|
||||
setLoadingSenha(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="max-w-5xl mx-auto space-y-6">
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center h-64">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-white rounded-lg shadow-lg overflow-hidden">
|
||||
{/* Cabeçalho */}
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 px-8 py-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="h-20 w-20 rounded-full bg-white/20 flex items-center justify-center text-white text-2xl font-bold">
|
||||
{formData.nome?.charAt(0)}
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-white">
|
||||
{formData.nome}
|
||||
</h1>
|
||||
<p className="text-blue-100">{formData.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
{!isEditing ? (
|
||||
<button
|
||||
onClick={() => setIsEditing(true)}
|
||||
className="bg-white text-blue-600 px-6 py-2 rounded-lg hover:bg-blue-50 transition-colors duration-200 font-medium shadow-sm"
|
||||
>
|
||||
Editar Perfil
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Alertas */}
|
||||
{error && (
|
||||
<div className="mx-8 mt-6 p-4 bg-red-50 border-l-4 border-red-500 text-red-700 rounded">
|
||||
<div className="flex items-center">
|
||||
<svg
|
||||
className="h-5 w-5 mr-2"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{error}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="mx-8 mt-6 p-4 bg-green-50 border-l-4 border-green-500 text-green-700 rounded">
|
||||
<div className="flex items-center">
|
||||
<svg
|
||||
className="h-5 w-5 mr-2"
|
||||
fill="currentColor"
|
||||
viewBox="0 0 20 20"
|
||||
>
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
</svg>
|
||||
{success}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Formulário */}
|
||||
<form onSubmit={handleSubmit} className="p-8">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||
{/* Dados Pessoais */}
|
||||
<div className="space-y-6">
|
||||
<div className="border-b border-gray-200 pb-4">
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-6">
|
||||
Dados Pessoais
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Nome Completo
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.nome || ""}
|
||||
onChange={(e) => handleChange("nome", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email || ""}
|
||||
onChange={(e) => handleChange("email", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
CPF
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.cpf || ""}
|
||||
disabled={true}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 bg-gray-50 text-gray-500"
|
||||
/>
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
O CPF não pode ser alterado
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
RG
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.rg || ""}
|
||||
onChange={(e) => handleChange("rg", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dados Profissionais */}
|
||||
<div className="space-y-6">
|
||||
<div className="border-b border-gray-200 pb-4">
|
||||
<h2 className="text-xl font-semibold text-gray-800 mb-6">
|
||||
Dados Profissionais
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
OAB
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.oab || ""}
|
||||
onChange={(e) => handleChange("oab", e.target.value)}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
UF
|
||||
</label>
|
||||
<select
|
||||
value={formData.oabUF || ""}
|
||||
onChange={(e) =>
|
||||
handleChange("oabUF", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
>
|
||||
<option value="">Selecione</option>
|
||||
{UF_BRASIL.map((uf) => (
|
||||
<option key={uf.value} value={uf.value}>
|
||||
{uf.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Telefone
|
||||
</label>
|
||||
<input
|
||||
type="tel"
|
||||
value={formData.telefone || ""}
|
||||
onChange={(e) =>
|
||||
handleChange("telefone", e.target.value)
|
||||
}
|
||||
disabled={!isEditing}
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-50 disabled:text-gray-500 transition-colors duration-200"
|
||||
placeholder="(00) 00000-0000"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Botões de ação */}
|
||||
{isEditing && (
|
||||
<div className="mt-8 flex justify-end space-x-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsEditing(false)}
|
||||
className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors duration-200 font-medium"
|
||||
disabled={loading}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200 font-medium disabled:opacity-50"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<span className="flex items-center space-x-2">
|
||||
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
fill="none"
|
||||
/>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
/>
|
||||
</svg>
|
||||
<span>Salvando...</span>
|
||||
</span>
|
||||
) : (
|
||||
"Salvar Alterações"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Formulário de Alteração de Senha */}
|
||||
<div className="bg-white rounded-lg shadow-lg overflow-hidden">
|
||||
<div className="bg-gradient-to-r from-blue-600 to-blue-800 px-8 py-4">
|
||||
<h2 className="text-xl font-semibold text-white">Alterar Senha</h2>
|
||||
</div>
|
||||
|
||||
{senhaError && (
|
||||
<div className="mx-8 mt-6 p-4 bg-red-50 border-l-4 border-red-500 text-red-700 rounded">
|
||||
{senhaError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{senhaSuccess && (
|
||||
<div className="mx-8 mt-6 p-4 bg-green-50 border-l-4 border-green-500 text-green-700 rounded">
|
||||
{senhaSuccess}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSenhaSubmit} className="p-8">
|
||||
<div className="space-y-4 max-w-md">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Senha Atual
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={senhaForm.senhaAtual}
|
||||
onChange={(e) =>
|
||||
setSenhaForm({ ...senhaForm, senhaAtual: e.target.value })
|
||||
}
|
||||
required
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Nova Senha
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={senhaForm.novaSenha}
|
||||
onChange={(e) =>
|
||||
setSenhaForm({ ...senhaForm, novaSenha: e.target.value })
|
||||
}
|
||||
required
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Confirmar Nova Senha
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
value={senhaForm.confirmarSenha}
|
||||
onChange={(e) =>
|
||||
setSenhaForm({ ...senhaForm, confirmarSenha: e.target.value })
|
||||
}
|
||||
required
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="pt-4">
|
||||
<button
|
||||
type="submit"
|
||||
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors duration-200 font-medium disabled:opacity-50"
|
||||
disabled={loadingSenha}
|
||||
>
|
||||
{loadingSenha ? (
|
||||
<span className="flex items-center space-x-2">
|
||||
<svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
|
||||
<circle
|
||||
className="opacity-25"
|
||||
cx="12"
|
||||
cy="12"
|
||||
r="10"
|
||||
stroke="currentColor"
|
||||
strokeWidth="4"
|
||||
fill="none"
|
||||
/>
|
||||
<path
|
||||
className="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
|
||||
/>
|
||||
</svg>
|
||||
<span>Alterando senha...</span>
|
||||
</span>
|
||||
) : (
|
||||
"Alterar Senha"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
import { useState, lazy, Suspense, useEffect } from "react";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import { PlusIcon, PencilIcon, TrashIcon } from "@heroicons/react/24/outline";
|
||||
import { formatCurrency, formatDate } from "../../utils/format";
|
||||
import { useCustasProcessuais } from "../../hooks/useCustasProcessuais";
|
||||
import { useHonorarios } from "../../hooks/useHonorarios";
|
||||
import { useProcessoContext } from "../../context/ProcessoContext";
|
||||
import api from "../../services/api"; // Adicionar esta importação
|
||||
|
||||
// Corrigir importações lazy
|
||||
const DialogCustaProcessual = lazy(() =>
|
||||
import("./dialogs/DialogCustaProcessual").then((module) => ({
|
||||
default: module.default,
|
||||
})),
|
||||
);
|
||||
const DialogHonorario = lazy(() =>
|
||||
import("./dialogs/DialogHonorario").then((module) => ({
|
||||
default: module.default,
|
||||
})),
|
||||
);
|
||||
const DialogParcela = lazy(() =>
|
||||
import("./dialogs/DialogParcela").then((module) => ({
|
||||
default: module.DialogParcela, // Usar .DialogParcela em vez de .default
|
||||
})),
|
||||
);
|
||||
|
||||
const getParcelaStatus = (parcela: any) => {
|
||||
if (parcela.status === "PAGO") return "PAGO";
|
||||
if (parcela.valorPago && parcela.valorPago > 0) return "PARCIALMENTE_PAGO";
|
||||
return parcela.status;
|
||||
};
|
||||
|
||||
export default function AbaFinanceiro() {
|
||||
const { processo, refreshProcesso } = useProcessoContext();
|
||||
|
||||
// Verificar se processo existe antes de usar
|
||||
useEffect(() => {
|
||||
if (!processo) {
|
||||
refreshProcesso();
|
||||
}
|
||||
}, [processo, refreshProcesso]);
|
||||
|
||||
// Restante do estado
|
||||
const [tabValue, setTabValue] = useState(0);
|
||||
const [custaDialogOpen, setCustaDialogOpen] = useState(false);
|
||||
const [honorarioDialogOpen, setHonorarioDialogOpen] = useState(false);
|
||||
const [editingCusta, setEditingCusta] = useState(null);
|
||||
const [editingHonorario, setEditingHonorario] = useState(null);
|
||||
const [confirmDelete, setConfirmDelete] = useState({
|
||||
show: false,
|
||||
type: null,
|
||||
id: null,
|
||||
});
|
||||
const [editingParcela, setEditingParcela] = useState<any>(null);
|
||||
const [parcelaDialogOpen, setParcelaDialogOpen] = useState(false);
|
||||
const [parcelaTipo, setParcelaTipo] = useState<"honorario" | "custa">(
|
||||
"honorario",
|
||||
);
|
||||
|
||||
// Inicializar hooks com ID do processo
|
||||
const { addCusta, updateCusta, deleteCusta } = useCustasProcessuais(
|
||||
processo?.id,
|
||||
);
|
||||
const { addHonorario, updateHonorario, deleteHonorario } = useHonorarios(
|
||||
processo?.id,
|
||||
);
|
||||
|
||||
// Se não houver processo, mostrar loading
|
||||
if (!processo) {
|
||||
return <div className="flex justify-center p-8">Carregando...</div>;
|
||||
}
|
||||
|
||||
const handleSaveCusta = async (data: any) => {
|
||||
try {
|
||||
if (editingCusta) {
|
||||
await updateCusta({ id: editingCusta.id, data });
|
||||
} else {
|
||||
await addCusta(data);
|
||||
}
|
||||
setCustaDialogOpen(false);
|
||||
setEditingCusta(null);
|
||||
await refreshProcesso(); // Use refreshProcesso instead of window.location.reload()
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar custa:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveHonorario = async (data: any) => {
|
||||
try {
|
||||
if (editingHonorario) {
|
||||
await updateHonorario({ id: editingHonorario.id, data });
|
||||
} else {
|
||||
await addHonorario(data);
|
||||
}
|
||||
setHonorarioDialogOpen(false);
|
||||
setEditingHonorario(null);
|
||||
await refreshProcesso(); // Use refreshProcesso instead of window.location.reload()
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar honorário:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
if (confirmDelete.type === "custa") {
|
||||
await deleteCusta(confirmDelete.id);
|
||||
} else if (confirmDelete.type === "honorario") {
|
||||
await deleteHonorario(confirmDelete.id);
|
||||
}
|
||||
setConfirmDelete({ show: false, type: null, id: null });
|
||||
await refreshProcesso(); // Use refreshProcesso instead of window.location.reload()
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdateParcela = async (data: any) => {
|
||||
try {
|
||||
if (parcelaTipo === "honorario") {
|
||||
// Remover /api do início pois já está configurado no baseURL do axios
|
||||
await api.put(`/honorarios/parcelas/${editingParcela.id}`, {
|
||||
status: data.status,
|
||||
dataPagamento: data.dataPagamento,
|
||||
valorPago: Number(data.valorPago),
|
||||
comprovante: data.comprovante,
|
||||
observacoes: data.observacoes,
|
||||
});
|
||||
}
|
||||
|
||||
setParcelaDialogOpen(false);
|
||||
setEditingParcela(null);
|
||||
await refreshProcesso();
|
||||
} catch (error) {
|
||||
console.error("Erro ao atualizar parcela:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const getStatusBadgeClasses = (status: string) => {
|
||||
const baseClasses = "px-2 py-1 text-xs font-medium rounded-full";
|
||||
switch (status) {
|
||||
case "PENDENTE":
|
||||
return `${baseClasses} bg-yellow-100 text-yellow-800`;
|
||||
case "PAGO":
|
||||
return `${baseClasses} bg-green-100 text-green-800`;
|
||||
case "VENCIDO":
|
||||
return `${baseClasses} bg-red-100 text-red-800`;
|
||||
case "CANCELADO":
|
||||
return `${baseClasses} bg-gray-100 text-gray-800`;
|
||||
default:
|
||||
return `${baseClasses} bg-gray-100 text-gray-800`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="py-4">
|
||||
<Tab.Group>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-blue-900/20 p-1">
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
`w-full rounded-lg py-2.5 text-sm font-medium leading-5 ${
|
||||
selected
|
||||
? "bg-white text-blue-700 shadow"
|
||||
: "text-gray-600 hover:bg-white/[0.12] hover:text-blue-600"
|
||||
}`
|
||||
}
|
||||
>
|
||||
Custas Processuais
|
||||
</Tab>
|
||||
<Tab
|
||||
className={({ selected }) =>
|
||||
`w-full rounded-lg py-2.5 text-sm font-medium leading-5 ${
|
||||
selected
|
||||
? "bg-white text-blue-700 shadow"
|
||||
: "text-gray-600 hover:bg-white/[0.12] hover:text-blue-600"
|
||||
}`
|
||||
}
|
||||
>
|
||||
Honorários
|
||||
</Tab>
|
||||
</Tab.List>
|
||||
|
||||
<Tab.Panels className="mt-4">
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Custas Processuais
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingCusta(null);
|
||||
setCustaDialogOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4 mr-2" />
|
||||
Nova Custa
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{processo.custas?.length > 0 ? (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Tipo
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Descrição
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Valor
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Ações
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{processo.custas.map((custa) => (
|
||||
<tr key={custa.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
|
||||
{custa.tipo.replace(/_/g, " ")}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
|
||||
{custa.descricao}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900 text-right">
|
||||
{formatCurrency(custa.valor)}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap">
|
||||
<span className={getStatusBadgeClasses(custa.status)}>
|
||||
{custa.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-right">
|
||||
<div className="flex justify-end space-x-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingCusta(custa);
|
||||
setCustaDialogOpen(true);
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() =>
|
||||
setConfirmDelete({
|
||||
show: true,
|
||||
type: "custa",
|
||||
id: custa.id,
|
||||
})
|
||||
}
|
||||
className="p-1 text-red-600 hover:bg-red-50 rounded"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-8 text-gray-500">
|
||||
Nenhuma custa processual registrada
|
||||
</div>
|
||||
)}
|
||||
</Tab.Panel>
|
||||
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-lg font-medium text-gray-900">Honorários</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingHonorario(null);
|
||||
setHonorarioDialogOpen(true);
|
||||
}}
|
||||
className="inline-flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4 mr-2" />
|
||||
Novo Honorário
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{processo.honorarios?.map((honorario) => (
|
||||
<div
|
||||
key={honorario.id}
|
||||
className="mb-6 p-4 bg-white rounded-lg shadow"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<h4 className="text-lg font-medium text-gray-900">
|
||||
{honorario.formaPagamento === "VISTA"
|
||||
? "Pagamento à Vista"
|
||||
: honorario.formaPagamento === "PARCELADO"
|
||||
? `Parcelado em ${honorario.numeroParcelas}x`
|
||||
: "Percentual da Causa"}
|
||||
</h4>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className={getStatusBadgeClasses(honorario.status)}>
|
||||
{honorario.status}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingHonorario(honorario);
|
||||
setHonorarioDialogOpen(true);
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() =>
|
||||
setConfirmDelete({
|
||||
show: true,
|
||||
type: "honorario",
|
||||
id: honorario.id,
|
||||
})
|
||||
}
|
||||
className="p-1 text-red-600 hover:bg-red-50 rounded"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<p className="text-sm text-gray-700">
|
||||
{honorario.valorFixo
|
||||
? `Valor: ${formatCurrency(honorario.valorFixo)}`
|
||||
: `Percentual: ${honorario.percentualCausa}%`}
|
||||
</p>
|
||||
{honorario.formaPagamento === "PARCELADO" && (
|
||||
<>
|
||||
<p className="text-sm text-gray-700">
|
||||
Entrada: {formatCurrency(honorario.valorEntrada)}
|
||||
</p>
|
||||
<p className="text-sm text-gray-700">
|
||||
Parcelas: {honorario.numeroParcelas}x de{" "}
|
||||
{formatCurrency(honorario.valorParcela)}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
<p className="text-sm text-gray-500">
|
||||
Vencimento: {formatDate(honorario.dataVencimento)}
|
||||
</p>
|
||||
</div>
|
||||
{honorario.parcelas && (
|
||||
<div className="mt-4 overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200">
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Parcela
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Valor
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Vencimento
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Ações
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
|
||||
>
|
||||
Valor Pago
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white divide-y divide-gray-200">
|
||||
{honorario.parcelas.map((parcela) => (
|
||||
<tr key={parcela.id} className="hover:bg-gray-50">
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
|
||||
{parcela.numeroParcela}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900 text-right">
|
||||
{formatCurrency(parcela.valor)}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-sm text-gray-900">
|
||||
{formatDate(parcela.vencimento)}
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap">
|
||||
<span
|
||||
className={getStatusBadgeClasses(
|
||||
parcela.status,
|
||||
)}
|
||||
>
|
||||
{parcela.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-right">
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingParcela(parcela);
|
||||
setParcelaTipo("honorario");
|
||||
setParcelaDialogOpen(true);
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2 whitespace-nowrap text-xs text-gray-500">
|
||||
{parcela.valorPago > 0 &&
|
||||
parcela.valorPago < parcela.valor &&
|
||||
`Pago: ${formatCurrency(parcela.valorPago)}`}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
|
||||
{confirmDelete.show && (
|
||||
<div className="fixed inset-0 z-50 overflow-y-auto">
|
||||
<div className="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center">
|
||||
<div className="fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75"></div>
|
||||
<div className="relative inline-block p-6 bg-white rounded-lg text-left shadow-xl">
|
||||
<div className="sm:flex sm:items-start">
|
||||
<div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0">
|
||||
<TrashIcon className="h-6 w-6 text-red-600" />
|
||||
</div>
|
||||
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Confirmar exclusão
|
||||
</h3>
|
||||
<div className="mt-2">
|
||||
<p className="text-sm text-gray-500">
|
||||
Tem certeza que deseja excluir este{" "}
|
||||
{confirmDelete.type === "custa"
|
||||
? "registro de custa"
|
||||
: "honorário"}
|
||||
? Esta ação não pode ser desfeita.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDelete}
|
||||
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 sm:ml-3 sm:w-auto sm:text-sm"
|
||||
>
|
||||
Excluir
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() =>
|
||||
setConfirmDelete({ show: false, type: null, id: null })
|
||||
}
|
||||
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 sm:mt-0 sm:w-auto sm:text-sm"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Suspense
|
||||
fallback={<div className="flex justify-center p-8">Carregando...</div>}
|
||||
>
|
||||
{custaDialogOpen && (
|
||||
<DialogCustaProcessual
|
||||
key="custa-dialog" // Adicionar key única
|
||||
open={custaDialogOpen}
|
||||
onClose={() => {
|
||||
setCustaDialogOpen(false);
|
||||
setEditingCusta(null);
|
||||
}}
|
||||
onSave={handleSaveCusta}
|
||||
editingCusta={editingCusta}
|
||||
/>
|
||||
)}
|
||||
|
||||
{honorarioDialogOpen && (
|
||||
<DialogHonorario
|
||||
key="honorario-dialog" // Adicionar key única
|
||||
open={honorarioDialogOpen}
|
||||
onClose={() => {
|
||||
setHonorarioDialogOpen(false);
|
||||
setEditingHonorario(null);
|
||||
}}
|
||||
onSave={handleSaveHonorario}
|
||||
editingHonorario={editingHonorario}
|
||||
/>
|
||||
)}
|
||||
|
||||
{parcelaDialogOpen && (
|
||||
<DialogParcela
|
||||
key="parcela-dialog" // Adicionar key única
|
||||
isOpen={parcelaDialogOpen}
|
||||
onClose={() => {
|
||||
setParcelaDialogOpen(false);
|
||||
setEditingParcela(null);
|
||||
}}
|
||||
onSave={handleUpdateParcela}
|
||||
parcela={editingParcela}
|
||||
tipo={parcelaTipo}
|
||||
/>
|
||||
)}
|
||||
</Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import { useProcessoContext } from "../../context/ProcessoContext";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
|
||||
export function AbaInformacoes() {
|
||||
const { processo } = useProcessoContext();
|
||||
|
||||
if (!processo) {
|
||||
return <div>Carregando...</div>;
|
||||
}
|
||||
|
||||
// Encontrar próxima audiência
|
||||
const proximaAudiencia = processo.dadosDatajud?.movimentos?.find((mov) => {
|
||||
const isAudiencia =
|
||||
mov.nome.toLowerCase().includes("audiência") &&
|
||||
mov.complementosTabelados?.some((c) => c.nome === "designada");
|
||||
if (!isAudiencia) return false;
|
||||
|
||||
const dataAudiencia = new Date(mov.dataHora);
|
||||
return dataAudiencia > new Date();
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="bg-white rounded-xl p-6">
|
||||
<h3 className="text-lg font-medium text-gray-900 mb-4">
|
||||
Informações do Processo
|
||||
</h3>
|
||||
|
||||
{/* Informações Básicas */}
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<InfoItem label="Número do Processo" value={processo.numero} />
|
||||
<InfoItem label="Natureza" value={processo.natureza} />
|
||||
<InfoItem label="Classe" value={processo.classeProcessual} />
|
||||
<InfoItem label="Órgão Julgador" value={processo.orgaoJulgador} />
|
||||
<InfoItem
|
||||
label="Tribunal"
|
||||
value={`${processo.tribunal} (${processo.tribunalUF})`}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Valor da Causa"
|
||||
value={
|
||||
processo.valorCausa
|
||||
? new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(processo.valorCausa)
|
||||
: "Não informado"
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Dados do DataJud */}
|
||||
<div className="mt-6 p-4 bg-gray-50 rounded-lg">
|
||||
<h3 className="text-md font-medium text-gray-900 mb-4">
|
||||
Dados do DataJud
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<InfoItem
|
||||
label="Classe"
|
||||
value={processo.dadosDatajud?.classe?.nome}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Data de Ajuizamento"
|
||||
value={
|
||||
processo.dataAjuizamento
|
||||
? format(new Date(processo.dataAjuizamento), "dd/MM/yyyy", {
|
||||
locale: ptBR,
|
||||
})
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<InfoItem label="Grau" value={processo.dadosDatajud?.grau} />
|
||||
<InfoItem
|
||||
label="Formato"
|
||||
value={processo.dadosDatajud?.formato?.nome}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Sistema"
|
||||
value={processo.dadosDatajud?.sistema?.nome}
|
||||
/>
|
||||
<InfoItem
|
||||
label="Órgão Julgador"
|
||||
value={processo.dadosDatajud?.orgaoJulgador?.nome}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Assuntos do DataJud */}
|
||||
{processo.dadosDatajud?.assuntos &&
|
||||
processo.dadosDatajud.assuntos.length > 0 && (
|
||||
<div className="mt-4">
|
||||
<h4 className="text-sm font-medium text-gray-900 mb-2">
|
||||
Assuntos
|
||||
</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{processo.dadosDatajud.assuntos.map((assunto) => (
|
||||
<span
|
||||
key={assunto.codigo}
|
||||
className="inline-flex items-center px-3 py-1 rounded-full text-sm
|
||||
bg-blue-50 text-blue-700 border border-blue-200"
|
||||
>
|
||||
{assunto.nome}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Próxima Audiência */}
|
||||
<div className="mt-6 p-4 bg-gray-50 rounded-lg">
|
||||
<h4 className="font-medium text-gray-900 mb-2">Próxima Audiência</h4>
|
||||
{proximaAudiencia ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-gray-900">
|
||||
<span className="font-medium">Tipo:</span>{" "}
|
||||
{proximaAudiencia.nome}
|
||||
</p>
|
||||
<p className="text-sm text-gray-900">
|
||||
<span className="font-medium">Data:</span>{" "}
|
||||
{format(
|
||||
new Date(proximaAudiencia.dataHora),
|
||||
"dd/MM/yyyy 'às' HH:mm",
|
||||
{ locale: ptBR },
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">Nenhuma audiência agendada</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoItem({
|
||||
label,
|
||||
value,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | null | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">{value || "Não informado"}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useProcessoContext } from "../../context/ProcessoContext";
|
||||
import { useProcessoMovimentacoes } from "../../hooks/useProcessoMovimentacoes";
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import { ClockIcon, DocumentIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
export default function AbaMovimentacoes() {
|
||||
const { processo } = useProcessoContext();
|
||||
const { movimentacoes, loading, error } = useProcessoMovimentacoes(processo);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex justify-center p-8">Carregando movimentações...</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center p-8 text-red-600">
|
||||
<span>Erro ao carregar movimentações</span>
|
||||
<span className="text-sm">{error}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-white rounded-xl p-6">
|
||||
<div className="flow-root">
|
||||
<ul role="list" className="-mb-8">
|
||||
{movimentacoes.map((movimentacao, idx) => {
|
||||
// Criar um identificador único usando todas as informações disponíveis
|
||||
const movId = `${movimentacao.codigo}-${movimentacao.nome.slice(0, 10)}-${movimentacao.dataHora}-${idx}`;
|
||||
|
||||
return (
|
||||
<li key={movId}>
|
||||
<div className="relative pb-8">
|
||||
{idx !== movimentacoes.length - 1 && (
|
||||
<span
|
||||
className="absolute left-4 top-4 -ml-px h-full w-0.5 bg-gray-200"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
<div className="relative flex space-x-3">
|
||||
<div>
|
||||
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-50">
|
||||
{movimentacao.complementosTabelados?.length > 0 ? (
|
||||
<DocumentIcon className="h-5 w-5 text-blue-600" />
|
||||
) : (
|
||||
<ClockIcon className="h-5 w-5 text-blue-600" />
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4 pt-1.5">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900">
|
||||
{movimentacao.nome}
|
||||
</p>
|
||||
{movimentacao.complementosTabelados?.map(
|
||||
(complemento) => (
|
||||
<p
|
||||
key={complemento.codigo}
|
||||
className="mt-0.5 text-sm text-gray-500"
|
||||
>
|
||||
{complemento.nome}
|
||||
</p>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-right text-sm text-gray-500">
|
||||
{format(
|
||||
new Date(movimentacao.dataHora),
|
||||
"dd/MM/yyyy 'às' HH:mm",
|
||||
{
|
||||
locale: ptBR,
|
||||
},
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import React from "react";
|
||||
import { Dialog } from "@headlessui/react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { FormSelect, FormInput } from "../forms";
|
||||
|
||||
const TIPOS_AUDIENCIA = [
|
||||
{ value: "INSTRUCAO", label: "Instrução" },
|
||||
{ value: "INSTRUCAO_JULGAMENTO", label: "Instrução e Julgamento" },
|
||||
{ value: "CONCILIACAO", label: "Conciliação" },
|
||||
{ value: "PERICIA", label: "Perícia" },
|
||||
{ value: "ESTUDO_PSICOPEDAGOGICO", label: "Estudo Psicopedagógico" },
|
||||
{ value: "MEDIACAO", label: "Mediação" },
|
||||
];
|
||||
|
||||
interface AudienciaModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => void;
|
||||
editingAudiencia?: any;
|
||||
isFinalizacao?: boolean; // Nova prop
|
||||
}
|
||||
|
||||
export const AudienciaModal: React.FC<AudienciaModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
editingAudiencia,
|
||||
isFinalizacao = false,
|
||||
}) => {
|
||||
const { register, handleSubmit } = useForm({
|
||||
defaultValues: editingAudiencia || {},
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} className="relative z-50">
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-md bg-white rounded-lg p-6">
|
||||
<Dialog.Title className="text-lg font-medium mb-4">
|
||||
{isFinalizacao
|
||||
? "Finalizar Audiência"
|
||||
: editingAudiencia
|
||||
? "Editar Audiência"
|
||||
: "Nova Audiência"}
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit(onSave)} className="space-y-4">
|
||||
{!isFinalizacao ? (
|
||||
<>
|
||||
<FormSelect
|
||||
label="Tipo de Audiência"
|
||||
{...register("tipo")}
|
||||
options={TIPOS_AUDIENCIA}
|
||||
required
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Data e Hora"
|
||||
type="datetime-local"
|
||||
{...register("data")}
|
||||
required
|
||||
/>
|
||||
|
||||
<FormInput label="Local" {...register("local")} required />
|
||||
|
||||
<FormSelect
|
||||
label="Modalidade"
|
||||
{...register("modalidade")}
|
||||
options={[
|
||||
{ value: "PRESENCIAL", label: "Presencial" },
|
||||
{ value: "VIRTUAL", label: "Virtual" },
|
||||
]}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Link (para audiência virtual)"
|
||||
{...register("linkVirtual")}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Observações"
|
||||
{...register("observacoes")}
|
||||
as="textarea"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="bg-gray-50 p-4 rounded-lg mb-4">
|
||||
<h3 className="font-medium text-gray-900">
|
||||
Informações da Audiência
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
Tipo: {editingAudiencia?.tipo}
|
||||
<br />
|
||||
Data: {new Date(editingAudiencia?.data).toLocaleString()}
|
||||
<br />
|
||||
Local: {editingAudiencia?.local}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
label="Relatório da Audiência"
|
||||
{...register("relatorio")}
|
||||
as="textarea"
|
||||
rows={6}
|
||||
placeholder="Descreva o que ocorreu na audiência..."
|
||||
required
|
||||
/>
|
||||
|
||||
<FormSelect
|
||||
label="Status Final"
|
||||
{...register("status")}
|
||||
options={[
|
||||
{ value: "REALIZADA", label: "Realizada" },
|
||||
{ value: "CANCELADA", label: "Cancelada" },
|
||||
{ value: "REDESIGNADA", label: "Redesignada" },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end space-x-2 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-50 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className={`px-4 py-2 text-sm text-white rounded-lg
|
||||
${
|
||||
isFinalizacao
|
||||
? "bg-green-600 hover:bg-green-700"
|
||||
: "bg-blue-600 hover:bg-blue-700"
|
||||
}`}
|
||||
>
|
||||
{isFinalizacao ? "Finalizar" : "Salvar"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
Dialog,
|
||||
TextField,
|
||||
MenuItem,
|
||||
Button,
|
||||
Box,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useState, useEffect } from "react";
|
||||
import { TipoCustaProcessual, StatusPagamento } from "@prisma/client";
|
||||
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
|
||||
interface DialogCustaProcessualProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => Promise<void>;
|
||||
editingCusta?: any;
|
||||
}
|
||||
|
||||
export function DialogCustaProcessual({
|
||||
open,
|
||||
onClose,
|
||||
onSave,
|
||||
editingCusta,
|
||||
}: DialogCustaProcessualProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
tipo: "",
|
||||
descricao: "",
|
||||
valor: "",
|
||||
percentual: "",
|
||||
status: "PENDENTE",
|
||||
vencimento: null as Date | null,
|
||||
dataPagamento: null as Date | null,
|
||||
observacoes: "",
|
||||
numeroParcelas: 1,
|
||||
parcelaAtual: 1,
|
||||
comprovante: "",
|
||||
});
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
// Atualizar form quando o editingCusta muda
|
||||
useEffect(() => {
|
||||
if (editingCusta) {
|
||||
setFormData({
|
||||
tipo: editingCusta.tipo || "",
|
||||
descricao: editingCusta.descricao || "",
|
||||
valor: editingCusta.valor?.toString() || "",
|
||||
percentual: editingCusta.percentual?.toString() || "",
|
||||
status: editingCusta.status || "PENDENTE",
|
||||
vencimento: editingCusta.vencimento
|
||||
? new Date(editingCusta.vencimento)
|
||||
: null,
|
||||
dataPagamento: editingCusta.dataPagamento
|
||||
? new Date(editingCusta.dataPagamento)
|
||||
: null,
|
||||
observacoes: editingCusta.observacoes || "",
|
||||
numeroParcelas: editingCusta.numeroParcelas || 1,
|
||||
parcelaAtual: editingCusta.parcelaAtual || 1,
|
||||
comprovante: editingCusta.comprovante || "",
|
||||
});
|
||||
} else {
|
||||
// Reset para os valores padrão
|
||||
setFormData({
|
||||
tipo: "",
|
||||
descricao: "",
|
||||
valor: "",
|
||||
percentual: "",
|
||||
status: "PENDENTE",
|
||||
vencimento: null,
|
||||
dataPagamento: null,
|
||||
observacoes: "",
|
||||
numeroParcelas: 1,
|
||||
parcelaAtual: 1,
|
||||
comprovante: "",
|
||||
});
|
||||
}
|
||||
}, [editingCusta, open]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
// Validar campos obrigatórios
|
||||
if (!formData.tipo) {
|
||||
setFormError("Selecione o tipo da custa");
|
||||
return;
|
||||
}
|
||||
if (!formData.descricao) {
|
||||
setFormError("Informe a descrição da custa");
|
||||
return;
|
||||
}
|
||||
if (!formData.valor) {
|
||||
setFormError("Informe o valor da custa");
|
||||
return;
|
||||
}
|
||||
|
||||
// Preparar dados
|
||||
const preparedData = {
|
||||
...formData,
|
||||
valor: Number(formData.valor),
|
||||
percentual: formData.percentual ? Number(formData.percentual) : null,
|
||||
numeroParcelas: Number(formData.numeroParcelas),
|
||||
parcelaAtual: Number(formData.parcelaAtual),
|
||||
};
|
||||
|
||||
await onSave(preparedData);
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
console.error("Erro ao salvar custa:", error);
|
||||
setFormError(error.message || "Erro ao salvar custa. Tente novamente.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<Box component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
|
||||
<h2 className="text-lg font-semibold mb-4">
|
||||
{editingCusta ? "Editar Custa Processual" : "Nova Custa Processual"}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Tipo"
|
||||
value={formData.tipo}
|
||||
onChange={(e) => setFormData({ ...formData, tipo: e.target.value })}
|
||||
required
|
||||
>
|
||||
{Object.values(TipoCustaProcessual).map((tipo) => (
|
||||
<MenuItem key={tipo} value={tipo}>
|
||||
{tipo.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Descrição"
|
||||
value={formData.descricao}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, descricao: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor"
|
||||
type="number"
|
||||
value={formData.valor}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valor: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual (se aplicável)"
|
||||
type="number"
|
||||
value={formData.percentual}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentual: e.target.value })
|
||||
}
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDateFns}
|
||||
adapterLocale={ptBR}
|
||||
>
|
||||
<DatePicker
|
||||
label="Vencimento"
|
||||
value={formData.vencimento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, vencimento: date })
|
||||
}
|
||||
sx={{ width: "100%", mb: 2 }}
|
||||
/>
|
||||
|
||||
{formData.status === "PAGO" && (
|
||||
<DatePicker
|
||||
label="Data de Pagamento"
|
||||
value={formData.dataPagamento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, dataPagamento: date })
|
||||
}
|
||||
sx={{ width: "100%" }}
|
||||
/>
|
||||
)}
|
||||
</LocalizationProvider>
|
||||
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Status"
|
||||
value={formData.status}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, status: e.target.value })
|
||||
}
|
||||
required
|
||||
>
|
||||
{Object.values(StatusPagamento).map((status) => (
|
||||
<MenuItem key={status} value={status}>
|
||||
{status.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Número de Parcelas"
|
||||
type="number"
|
||||
value={formData.numeroParcelas}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
numeroParcelas: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Observações"
|
||||
multiline
|
||||
rows={3}
|
||||
value={formData.observacoes}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, observacoes: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<Box sx={{ mt: 2, p: 2, bgcolor: "error.light", borderRadius: 1 }}>
|
||||
<Typography color="error">{formError}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{ mt: 3, display: "flex", justifyContent: "flex-end", gap: 2 }}
|
||||
>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button type="submit" variant="contained" color="primary">
|
||||
Salvar
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default DialogCustaProcessual;
|
||||
@@ -0,0 +1,347 @@
|
||||
import {
|
||||
Dialog,
|
||||
TextField,
|
||||
MenuItem,
|
||||
Button,
|
||||
Box,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useState, useEffect } from "react";
|
||||
import { FormaPagamento, StatusPagamento } from "@prisma/client";
|
||||
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
import { IHonorario, IHonorarioCreate } from "../types/financeiro";
|
||||
|
||||
interface DialogHonorarioProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: Partial<IHonorarioCreate>) => Promise<void>;
|
||||
editingHonorario?: IHonorario;
|
||||
}
|
||||
|
||||
export function DialogHonorario({
|
||||
open,
|
||||
onClose,
|
||||
onSave,
|
||||
editingHonorario,
|
||||
}: DialogHonorarioProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
formaPagamento: "VISTA",
|
||||
valorFixo: "",
|
||||
percentualCausa: "",
|
||||
percentualExito: "",
|
||||
valorEntrada: "",
|
||||
numeroParcelas: 1,
|
||||
valorParcela: "",
|
||||
diaVencimento: 10,
|
||||
status: "PENDENTE",
|
||||
dataVencimento: new Date(),
|
||||
observacoes: "",
|
||||
});
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
// Atualizar form quando o editingHonorario muda
|
||||
useEffect(() => {
|
||||
if (editingHonorario) {
|
||||
setFormData({
|
||||
formaPagamento: editingHonorario.formaPagamento,
|
||||
valorFixo: editingHonorario.valorFixo || "",
|
||||
percentualCausa: editingHonorario.percentualCausa || "",
|
||||
percentualExito: editingHonorario.percentualExito || "",
|
||||
valorEntrada: editingHonorario.valorEntrada || "",
|
||||
numeroParcelas: editingHonorario.numeroParcelas || 1,
|
||||
valorParcela: editingHonorario.valorParcela || "",
|
||||
diaVencimento: editingHonorario.diaVencimento || 10,
|
||||
status: editingHonorario.status,
|
||||
dataVencimento: editingHonorario.dataVencimento
|
||||
? new Date(editingHonorario.dataVencimento)
|
||||
: new Date(),
|
||||
observacoes: editingHonorario.observacoes || "",
|
||||
});
|
||||
} else {
|
||||
// Reset para os valores padrão
|
||||
setFormData({
|
||||
formaPagamento: "VISTA",
|
||||
valorFixo: "",
|
||||
percentualCausa: "",
|
||||
percentualExito: "",
|
||||
valorEntrada: "",
|
||||
numeroParcelas: 1,
|
||||
valorParcela: "",
|
||||
diaVencimento: 10,
|
||||
status: "PENDENTE",
|
||||
dataVencimento: new Date(),
|
||||
observacoes: "",
|
||||
});
|
||||
}
|
||||
}, [editingHonorario, open]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
// Validações básicas
|
||||
const validationError = validateFormData(formData);
|
||||
if (validationError) {
|
||||
setFormError(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
// Converter strings numéricas
|
||||
const preparedData = {
|
||||
...formData,
|
||||
valorFixo: formData.valorFixo ? Number(formData.valorFixo) : null,
|
||||
percentualCausa: formData.percentualCausa
|
||||
? Number(formData.percentualCausa)
|
||||
: null,
|
||||
percentualExito: formData.percentualExito
|
||||
? Number(formData.percentualExito)
|
||||
: null,
|
||||
valorEntrada: formData.valorEntrada
|
||||
? Number(formData.valorEntrada)
|
||||
: null,
|
||||
valorParcela: formData.valorParcela
|
||||
? Number(formData.valorParcela)
|
||||
: null,
|
||||
};
|
||||
|
||||
await onSave(preparedData);
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
console.error("Erro ao salvar honorário:", error);
|
||||
setFormError(
|
||||
error.message || "Erro ao salvar honorário. Tente novamente.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const validateFormData = (data: any): string | null => {
|
||||
if (!data.formaPagamento) {
|
||||
return "Forma de pagamento é obrigatória";
|
||||
}
|
||||
|
||||
switch (data.formaPagamento) {
|
||||
case "VISTA":
|
||||
if (!data.valorFixo) {
|
||||
return "Informe o valor do honorário";
|
||||
}
|
||||
break;
|
||||
case "PERCENTUAL_CAUSA":
|
||||
if (!data.percentualCausa) {
|
||||
return "Informe o percentual da causa";
|
||||
}
|
||||
break;
|
||||
case "PERCENTUAL_EXITO":
|
||||
if (!data.percentualExito) {
|
||||
return "Informe o percentual do êxito";
|
||||
}
|
||||
break;
|
||||
case "PARCELADO":
|
||||
case "ENTRADA_MAIS_PARCELAS":
|
||||
if (!data.valorParcela) {
|
||||
return "Informe o valor da parcela";
|
||||
}
|
||||
if (!data.numeroParcelas || data.numeroParcelas < 1) {
|
||||
return "Informe o número de parcelas";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<Box component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
|
||||
<h2 className="text-lg font-semibold mb-4">
|
||||
{editingHonorario ? "Editar Honorário" : "Novo Honorário"}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Forma de Pagamento</InputLabel>
|
||||
<Select
|
||||
value={formData.formaPagamento}
|
||||
label="Forma de Pagamento"
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, formaPagamento: e.target.value })
|
||||
}
|
||||
>
|
||||
{Object.values(FormaPagamento).map((forma) => (
|
||||
<MenuItem key={forma} value={forma}>
|
||||
{forma.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{formData.formaPagamento === "VISTA" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor"
|
||||
type="number"
|
||||
value={formData.valorFixo}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorFixo: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{formData.formaPagamento === "PERCENTUAL_CAUSA" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual da Causa"
|
||||
type="number"
|
||||
value={formData.percentualCausa}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentualCausa: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{formData.formaPagamento === "PERCENTUAL_EXITO" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual do Êxito"
|
||||
type="number"
|
||||
value={formData.percentualExito}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentualExito: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(formData.formaPagamento === "PARCELADO" ||
|
||||
formData.formaPagamento === "ENTRADA_MAIS_PARCELAS") && (
|
||||
<>
|
||||
{formData.formaPagamento === "ENTRADA_MAIS_PARCELAS" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor da Entrada"
|
||||
type="number"
|
||||
value={formData.valorEntrada}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorEntrada: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Número de Parcelas"
|
||||
type="number"
|
||||
value={formData.numeroParcelas}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
numeroParcelas: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
required
|
||||
inputProps={{ min: "1" }}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor da Parcela"
|
||||
type="number"
|
||||
value={formData.valorParcela}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorParcela: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Dia do Vencimento"
|
||||
type="number"
|
||||
value={formData.diaVencimento}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
diaVencimento: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
inputProps={{ min: 1, max: 31 }}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Status"
|
||||
value={formData.status}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, status: e.target.value })
|
||||
}
|
||||
required
|
||||
>
|
||||
{Object.values(StatusPagamento).map((status) => (
|
||||
<MenuItem key={status} value={status}>
|
||||
{status.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDateFns}
|
||||
adapterLocale={ptBR}
|
||||
>
|
||||
<DatePicker
|
||||
label="Data de Vencimento"
|
||||
value={formData.dataVencimento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, dataVencimento: date || new Date() })
|
||||
}
|
||||
sx={{ width: "100%" }}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Observações"
|
||||
multiline
|
||||
rows={3}
|
||||
value={formData.observacoes}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, observacoes: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<Box sx={{ mt: 2, p: 2, bgcolor: "error.light", borderRadius: 1 }}>
|
||||
<Typography color="error">{formError}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{ mt: 3, display: "flex", justifyContent: "flex-end", gap: 2 }}
|
||||
>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button type="submit" variant="contained" color="primary">
|
||||
Salvar
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default DialogHonorario;
|
||||
@@ -0,0 +1,72 @@
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import { useProcessoMovimentacoes } from "../../hooks/useProcessoMovimentacoes";
|
||||
|
||||
interface MovimentacoesTimelineProps {
|
||||
numeroProcesso: string;
|
||||
tribunal: string;
|
||||
}
|
||||
|
||||
export function MovimentacoesTimeline({
|
||||
numeroProcesso,
|
||||
tribunal,
|
||||
}: MovimentacoesTimelineProps) {
|
||||
const { movimentacoes, loading, error } = useProcessoMovimentacoes(
|
||||
numeroProcesso,
|
||||
tribunal,
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return <div className="text-center p-4">Carregando movimentações...</div>;
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center p-4 text-red-600">
|
||||
Erro ao carregar movimentações
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!movimentacoes?.length) {
|
||||
return (
|
||||
<div className="text-center p-4">Nenhuma movimentação encontrada</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flow-root">
|
||||
<ul role="list" className="-mb-8">
|
||||
{movimentacoes.map((mov, idx) => (
|
||||
<li key={`${mov.codigo}-${mov.dataHora}`}>
|
||||
<div className="relative pb-8">
|
||||
{idx !== movimentacoes.length - 1 ? (
|
||||
<span className="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200" />
|
||||
) : null}
|
||||
<div className="relative flex space-x-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-100">
|
||||
<span className="text-xs text-gray-500">{mov.codigo}</span>
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-1 justify-between space-x-4 pt-1.5">
|
||||
<div>
|
||||
<p className="text-sm text-gray-900">{mov.nome}</p>
|
||||
{mov.complementosTabelados?.map((comp: any) => (
|
||||
<p key={comp.codigo} className="text-sm text-gray-500">
|
||||
{comp.nome}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
<div className="whitespace-nowrap text-right text-sm text-gray-500">
|
||||
{format(new Date(mov.dataHora), "dd/MM/yyyy 'às' HH:mm", {
|
||||
locale: ptBR,
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import React, { useState } from "react";
|
||||
import { Dialog } from "@headlessui/react";
|
||||
import { useClientes } from "../../hooks/useClientes";
|
||||
import { FormSelect, FormInput } from "../forms";
|
||||
import { useForm } from "react-hook-form";
|
||||
|
||||
interface ParteProcessoModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => void;
|
||||
tipo: "AUTOR" | "REU";
|
||||
editingParte?: any;
|
||||
}
|
||||
|
||||
export const ParteProcessoModal: React.FC<ParteProcessoModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
tipo,
|
||||
editingParte,
|
||||
}) => {
|
||||
const { register, handleSubmit, setValue, watch } = useForm({
|
||||
defaultValues: editingParte || {
|
||||
tipo, // Já estava aqui, mas precisamos garantir que está sendo enviado
|
||||
principal: false,
|
||||
},
|
||||
});
|
||||
const { clientes } = useClientes();
|
||||
const [useExistingClient, setUseExistingClient] = useState(
|
||||
!!editingParte?.clienteId,
|
||||
);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
const filteredClientes = clientes.filter(
|
||||
(cliente) =>
|
||||
cliente.nome.toLowerCase().includes(searchTerm.toLowerCase()) ||
|
||||
cliente.cpfCnpj.includes(searchTerm),
|
||||
);
|
||||
|
||||
const onSubmit = (data: any) => {
|
||||
const parteData = {
|
||||
...data,
|
||||
tipo, // Garantir que o tipo está sendo enviado
|
||||
nome: useExistingClient
|
||||
? clientes.find((c) => c.id === data.clienteId)?.nome
|
||||
: data.nome,
|
||||
cpfCnpj: useExistingClient
|
||||
? clientes.find((c) => c.id === data.clienteId)?.cpfCnpj
|
||||
: data.cpfCnpj,
|
||||
clienteId: useExistingClient ? data.clienteId : undefined,
|
||||
principal: data.principal || false,
|
||||
};
|
||||
|
||||
console.log("Enviando dados:", parteData); // Debug
|
||||
onSave(parteData);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} className="relative z-50">
|
||||
{/* ... dialog backdrop ... */}
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-md bg-white rounded-lg p-6">
|
||||
<Dialog.Title className="text-lg font-medium mb-4">
|
||||
Adicionar {tipo === "AUTOR" ? "Autor" : "Réu"}
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
{/* Adicionar campo oculto para o tipo */}
|
||||
<input type="hidden" {...register("tipo")} value={tipo} />
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={useExistingClient}
|
||||
onChange={(e) => setUseExistingClient(e.target.checked)}
|
||||
className="rounded border-gray-300"
|
||||
/>
|
||||
<label className="text-sm">Usar cliente existente</label>
|
||||
</div>
|
||||
|
||||
{useExistingClient ? (
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Buscar Cliente
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-md"
|
||||
placeholder="Digite nome ou CPF/CNPJ..."
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
<div className="mt-2 max-h-60 overflow-y-auto border border-gray-200 rounded-lg">
|
||||
{filteredClientes.map((cliente) => (
|
||||
<label
|
||||
key={cliente.id}
|
||||
className="flex items-center p-2 hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
{...register("clienteId")}
|
||||
value={cliente.id}
|
||||
className="mr-2"
|
||||
/>
|
||||
<div>
|
||||
<div className="font-medium">{cliente.nome}</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
{cliente.cpfCnpj}
|
||||
</div>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<FormInput label="Nome" {...register("nome")} required />
|
||||
<FormInput label="CPF/CNPJ" {...register("cpfCnpj")} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<FormInput
|
||||
label="Observações"
|
||||
{...register("observacoes")}
|
||||
as="textarea"
|
||||
/>
|
||||
|
||||
<div className="flex justify-end space-x-2 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-50 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
Whitespace-only changes.
@@ -0,0 +1,58 @@
|
||||
import React from 'react';
|
||||
import { Processo } from '../../types/entities';
|
||||
|
||||
interface ProcessoCardProps {
|
||||
processo: Processo;
|
||||
}
|
||||
|
||||
const resultadoLabel = {
|
||||
NAO_JULGADO: 'Não Julgado',
|
||||
PROCEDENTE: 'Procedente',
|
||||
PARCIALMENTE_PROCEDENTE: 'Parcialmente Procedente',
|
||||
IMPROCEDENTE: 'Improcedente',
|
||||
SEM_ANALISE_MERITO: 'Sem Análise de Mérito'
|
||||
};
|
||||
|
||||
const resultadoColor = {
|
||||
NAO_JULGADO: 'bg-gray-100 text-gray-800',
|
||||
PROCEDENTE: 'bg-green-100 text-green-800',
|
||||
PARCIALMENTE_PROCEDENTE: 'bg-yellow-100 text-yellow-800',
|
||||
IMPROCEDENTE: 'bg-red-100 text-red-800',
|
||||
SEM_ANALISE_MERITO: 'bg-gray-100 text-gray-800'
|
||||
};
|
||||
|
||||
export const ProcessoCard: React.FC<ProcessoCardProps> = ({ processo }) => {
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-4">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
|
||||
{processo.numero}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{processo.cliente.nome}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{processo.nomeContraparte}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{processo.natureza}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{processo.status}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{processo.valorCausa?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{new Date(processo.dataCriacao).toLocaleDateString('pt-BR')}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{new Date(processo.dataAtualizacao).toLocaleDateString('pt-BR')}
|
||||
</p>
|
||||
<div className="mt-2">
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${resultadoColor[processo.resultado]}`}>
|
||||
{resultadoLabel[processo.resultado]}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,646 @@
|
||||
import React, { useState, useEffect, lazy, Suspense } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useProcessos } from "../../hooks/useProcessos";
|
||||
import api from "../../services/api"; // Adicionar esta importação
|
||||
import { Tab, Dialog } from "@headlessui/react";
|
||||
import { TrashIcon } from "@heroicons/react/24/outline";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
ClockIcon,
|
||||
DocumentTextIcon,
|
||||
UserGroupIcon,
|
||||
BanknotesIcon, // Alterado de BalanceIcon para BanknotesIcon
|
||||
CalendarIcon,
|
||||
PencilIcon,
|
||||
ExclamationTriangleIcon,
|
||||
PlusIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { ProcessoModal } from "./ProcessoModal.tsx";
|
||||
import { formatNumeroProcesso, formatCPF } from "../../utils/formatters";
|
||||
import { ParteProcessoModal } from "./ParteProcessoModal";
|
||||
import { usePartesProcesso } from "../../hooks/usePartesProcesso";
|
||||
import { useAudiencias } from "../../hooks/useAudiencias";
|
||||
import { AudienciaModal } from "./AudienciaModal";
|
||||
import AbaFinanceiro from "./AbaFinanceiro";
|
||||
import { ProcessoProvider } from "../../context/ProcessoContext";
|
||||
|
||||
// Adicionar lazy import para AbaMovimentacoes
|
||||
const AbaMovimentacoes = lazy(() => import("./AbaMovimentacoes"));
|
||||
|
||||
function classNames(...classes: string[]) {
|
||||
return classes.filter(Boolean).join(" ");
|
||||
}
|
||||
|
||||
const tabs = [
|
||||
{ id: "geral", name: "Geral", icon: DocumentTextIcon },
|
||||
{ id: "partes", name: "Partes", icon: UserGroupIcon },
|
||||
{ id: "movimentacoes", name: "Movimentações", icon: ClockIcon },
|
||||
{ id: "audiencias", name: "Audiências", icon: CalendarIcon },
|
||||
{ id: "financeiro", name: "Financeiro", icon: BanknotesIcon }, // Atualizado aqui também
|
||||
];
|
||||
|
||||
export const ProcessoDetalhes: React.FC = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const { getProcesso, isLoading, deleteProcesso } = useProcessos();
|
||||
const [processo, setProcesso] = useState<Processo | null>(null);
|
||||
const [selectedTab, setSelectedTab] = useState(0);
|
||||
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [editingParte, setEditingParte] = useState<any>(null);
|
||||
const [parteModalConfig, setParteModalConfig] = useState<{
|
||||
isOpen: boolean;
|
||||
tipo: "AUTOR" | "REU" | null;
|
||||
}>({ isOpen: false, tipo: null });
|
||||
const [isAudienciaModalOpen, setIsAudienciaModalOpen] = useState(false);
|
||||
const [editingAudiencia, setEditingAudiencia] = useState<any>(null);
|
||||
const [isFinalizacao, setIsFinalizacao] = useState(false); // Movido para cá
|
||||
|
||||
// Carregar processo com partes
|
||||
useEffect(() => {
|
||||
const loadProcesso = async () => {
|
||||
if (!id) return;
|
||||
try {
|
||||
const data = await getProcesso(id);
|
||||
// Só atualizar se os dados forem diferentes
|
||||
if (JSON.stringify(data) !== JSON.stringify(processo)) {
|
||||
setProcesso(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar processo:", error);
|
||||
}
|
||||
};
|
||||
|
||||
loadProcesso();
|
||||
}, [id, getProcesso]); // Remover processo da dependency list
|
||||
|
||||
const { addParte, updateParte, deleteParte } = usePartesProcesso(id!);
|
||||
|
||||
const handleSaveParte = async (data: any) => {
|
||||
try {
|
||||
if (editingParte) {
|
||||
await updateParte({ id: editingParte.id, data });
|
||||
} else {
|
||||
await addParte(data);
|
||||
}
|
||||
setParteModalConfig({ isOpen: false, tipo: null });
|
||||
setEditingParte(null);
|
||||
// Recarregar processo após salvar
|
||||
const updatedProcesso = await getProcesso(id!);
|
||||
setProcesso(updatedProcesso);
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar parte:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteParte = async (parteId: string) => {
|
||||
if (window.confirm("Tem certeza que deseja remover esta parte?")) {
|
||||
try {
|
||||
await deleteParte(parteId);
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir parte:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const { addAudiencia, updateAudiencia, deleteAudiencia } = useAudiencias(id!);
|
||||
|
||||
const handleSaveAudiencia = async (data: any) => {
|
||||
try {
|
||||
if (editingAudiencia) {
|
||||
await updateAudiencia({ id: editingAudiencia.id, data });
|
||||
} else {
|
||||
await addAudiencia(data);
|
||||
}
|
||||
setIsAudienciaModalOpen(false);
|
||||
setEditingAudiencia(null);
|
||||
// Recarregar processo após salvar
|
||||
const updatedProcesso = await getProcesso(id!);
|
||||
setProcesso(updatedProcesso);
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar audiência:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAudiencia = async (audienciaId: string) => {
|
||||
if (window.confirm("Tem certeza que deseja remover esta audiência?")) {
|
||||
try {
|
||||
await deleteAudiencia(audienciaId);
|
||||
// Recarregar processo
|
||||
const updatedProcesso = await getProcesso(id!);
|
||||
setProcesso(updatedProcesso);
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir audiência:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="animate-pulse">Carregando...</div>;
|
||||
}
|
||||
|
||||
if (!processo) {
|
||||
return <div>Processo não encontrado</div>;
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await deleteProcesso.mutateAsync(id!);
|
||||
navigate("/processos");
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir processo:", error);
|
||||
alert("Erro ao excluir processo");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<button
|
||||
onClick={() => navigate("/processos")}
|
||||
className="p-2 hover:bg-gray-100 rounded-full"
|
||||
>
|
||||
<ArrowLeftIcon className="h-5 w-5 text-gray-500" />
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">
|
||||
{formatNumeroProcesso(processo.numero)}
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">{processo.natureza}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
{/* Status Badge */}
|
||||
<span
|
||||
className={classNames(
|
||||
"px-3 py-1 rounded-full text-sm font-medium",
|
||||
processo.status === "INICIAL"
|
||||
? "bg-yellow-100 text-yellow-800"
|
||||
: processo.status === "EM_ANDAMENTO"
|
||||
? "bg-blue-100 text-blue-800"
|
||||
: processo.status === "SUSPENSO"
|
||||
? "bg-gray-100 text-gray-800"
|
||||
: processo.status === "CONCLUSO"
|
||||
? "bg-green-100 text-green-800"
|
||||
: "bg-red-100 text-red-800",
|
||||
)}
|
||||
>
|
||||
{processo.status}
|
||||
</span>
|
||||
|
||||
{/* Adicionar o botão de resultado aqui */}
|
||||
<select
|
||||
value={processo.resultado || 'NAO_JULGADO'}
|
||||
onChange={async (e) => {
|
||||
try {
|
||||
await api.patch(`/processos/${processo.id}/resultado`, {
|
||||
resultado: e.target.value
|
||||
});
|
||||
// Recarregar dados após atualização
|
||||
const updated = await getProcesso(processo.id);
|
||||
setProcesso(updated);
|
||||
} catch (error) {
|
||||
console.error('Erro ao atualizar resultado:', error);
|
||||
alert('Erro ao atualizar resultado do processo');
|
||||
}
|
||||
}}
|
||||
className="rounded-lg border-gray-300 text-sm"
|
||||
>
|
||||
<option value="NAO_JULGADO">Não Julgado</option>
|
||||
<option value="PROCEDENTE">Procedente</option>
|
||||
<option value="PARCIALMENTE_PROCEDENTE">Parcialmente Procedente</option>
|
||||
<option value="IMPROCEDENTE">Improcedente</option>
|
||||
<option value="SEM_ANALISE_MERITO">Sem Análise de Mérito</option>
|
||||
</select>
|
||||
</div>
|
||||
{/* Adicionar botão de edição */}
|
||||
<button
|
||||
onClick={() => setIsEditModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4 mr-2" />
|
||||
Editar Processo
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsDeleteModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-lg"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4 mr-2" />
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
{processo && (
|
||||
<ProcessoProvider processoId={processo.id}>
|
||||
<Tab.Group selectedIndex={selectedTab} onChange={setSelectedTab}>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-blue-900/20 p-1">
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
key={tab.id}
|
||||
className={({ selected }) =>
|
||||
classNames(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5",
|
||||
"flex items-center justify-center",
|
||||
selected
|
||||
? "bg-white text-blue-700 shadow"
|
||||
: "text-gray-600 hover:bg-white/[0.12] hover:text-blue-600",
|
||||
)
|
||||
}
|
||||
>
|
||||
<tab.icon className="h-4 w-4 mr-2" />
|
||||
{tab.name}
|
||||
</Tab>
|
||||
))}
|
||||
</Tab.List>
|
||||
|
||||
<Tab.Panels className="mt-2">
|
||||
{/* Informações Gerais */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Número do Processo
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{formatNumeroProcesso(processo.numero)}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Natureza
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{processo.natureza}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Órgão Julgador
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{processo.orgaoJulgador}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Valor da Causa
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{new Intl.NumberFormat("pt-BR", {
|
||||
style: "currency",
|
||||
currency: "BRL",
|
||||
}).format(processo.valorCausa || 0)}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Partes do Processo */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="space-y-8">
|
||||
{/* Autores */}
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Autores
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingParte(null);
|
||||
setParteModalConfig({ isOpen: true, tipo: "AUTOR" });
|
||||
}}
|
||||
className="text-sm text-blue-600 hover:text-blue-700"
|
||||
>
|
||||
+ Adicionar Autor
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{processo.partes
|
||||
?.filter((p) => p.tipo === "AUTOR")
|
||||
.map((parte) => (
|
||||
<div
|
||||
key={parte.id}
|
||||
className="flex justify-between items-center p-4 bg-gray-50 rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<h4 className="font-medium">{parte.nome}</h4>
|
||||
{parte.cpfCnpj && (
|
||||
<p className="text-sm text-gray-500">
|
||||
{formatCPF(parte.cpfCnpj)}
|
||||
</p>
|
||||
)}
|
||||
{parte.observacoes && (
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{parte.observacoes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingParte(parte);
|
||||
setParteModalConfig({
|
||||
isOpen: true,
|
||||
tipo: "AUTOR",
|
||||
});
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteParte(parte.id)}
|
||||
className="p-1 text-red-600 hover:bg-red-50 rounded"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Réus */}
|
||||
<div>
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Réus
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingParte(null);
|
||||
setParteModalConfig({ isOpen: true, tipo: "REU" });
|
||||
}}
|
||||
className="text-sm text-blue-600 hover:text-blue-700"
|
||||
>
|
||||
+ Adicionar Réu
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-4">
|
||||
{processo.partes
|
||||
?.filter((p) => p.tipo === "REU")
|
||||
.map((parte) => (
|
||||
<div
|
||||
key={parte.id}
|
||||
className="flex justify-between items-center p-4 bg-gray-50 rounded-lg"
|
||||
>
|
||||
<div>
|
||||
<h4 className="font-medium">{parte.nome}</h4>
|
||||
{parte.cpfCnpj && (
|
||||
<p className="text-sm text-gray-500">
|
||||
{formatCPF(parte.cpfCnpj)}
|
||||
</p>
|
||||
)}
|
||||
{parte.observacoes && (
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
{parte.observacoes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingParte(parte);
|
||||
setParteModalConfig({
|
||||
isOpen: true,
|
||||
tipo: "REU",
|
||||
});
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDeleteParte(parte.id)}
|
||||
className="p-1 text-red-600 hover:bg-red-50 rounded"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ParteProcessoModal
|
||||
isOpen={parteModalConfig.isOpen}
|
||||
onClose={() =>
|
||||
setParteModalConfig({ isOpen: false, tipo: null })
|
||||
}
|
||||
onSave={handleSaveParte}
|
||||
tipo={parteModalConfig.tipo}
|
||||
editingParte={editingParte}
|
||||
/>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Movimentações */}
|
||||
<Tab.Panel className="bg-white rounded-xl">
|
||||
<Suspense
|
||||
fallback={
|
||||
<div className="flex justify-center p-8">Carregando...</div>
|
||||
}
|
||||
>
|
||||
<AbaMovimentacoes />
|
||||
</Suspense>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Audiências */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="space-y-4">
|
||||
{/* Header com botão de adicionar */}
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<h3 className="text-lg font-medium text-gray-900">
|
||||
Audiências
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingAudiencia(null);
|
||||
setIsAudienciaModalOpen(true);
|
||||
}}
|
||||
className="flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PlusIcon className="h-4 w-4 mr-2" />
|
||||
Nova Audiência
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Lista de Audiências */}
|
||||
{processo.audiencias && processo.audiencias.length > 0 ? (
|
||||
<div className="divide-y divide-gray-200">
|
||||
{processo.audiencias.map((audiencia) => (
|
||||
<div key={audiencia.id} className="py-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 className="text-lg font-medium text-gray-900">
|
||||
{audiencia.tipo}
|
||||
</h4>
|
||||
<div className="mt-1 text-sm text-gray-500">
|
||||
<p>
|
||||
Data:{" "}
|
||||
{new Date(audiencia.data).toLocaleString()}
|
||||
</p>
|
||||
<p>Local: {audiencia.local}</p>
|
||||
{audiencia.modalidade === "VIRTUAL" && (
|
||||
<p>
|
||||
Link:{" "}
|
||||
<a
|
||||
href={audiencia.linkVirtual}
|
||||
className="text-blue-600 hover:underline"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Acessar
|
||||
</a>
|
||||
</p>
|
||||
)}
|
||||
{audiencia.relatorio && (
|
||||
<div className="mt-2 p-3 bg-gray-50 rounded-lg">
|
||||
<p className="font-medium text-sm">
|
||||
Relatório:
|
||||
</p>
|
||||
<p className="text-sm mt-1">
|
||||
{audiencia.relatorio}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
Finalizada em:{" "}
|
||||
{new Date(
|
||||
audiencia.dataFinalizacao,
|
||||
).toLocaleString()}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
{audiencia.status === "AGENDADA" && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingAudiencia(audiencia);
|
||||
setIsAudienciaModalOpen(true);
|
||||
setIsFinalizacao(true);
|
||||
}}
|
||||
className="px-3 py-1 text-sm text-green-600 hover:bg-green-50 rounded-lg border border-green-600"
|
||||
>
|
||||
Finalizar
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => {
|
||||
setEditingAudiencia(audiencia);
|
||||
setIsAudienciaModalOpen(true);
|
||||
}}
|
||||
className="p-1 text-blue-600 hover:bg-blue-50 rounded"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() =>
|
||||
handleDeleteAudiencia(audiencia.id)
|
||||
}
|
||||
className="p-1 text-red-600 hover:bg-red-50 rounded"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500 text-center py-4">
|
||||
Nenhuma audiência agendada
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Financeiro */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<ProcessoProvider processoId={processo?.id}>
|
||||
<AbaFinanceiro />
|
||||
</ProcessoProvider>
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
</ProcessoProvider>
|
||||
)}
|
||||
|
||||
{/* Modal de Edição */}
|
||||
<ProcessoModal
|
||||
isOpen={isEditModalOpen}
|
||||
processo={processo}
|
||||
onClose={() => setIsEditModalOpen(false)}
|
||||
onSuccess={() => {
|
||||
setIsEditModalOpen(false);
|
||||
// Recarregar dados após edição
|
||||
window.location.reload();
|
||||
}}
|
||||
/>
|
||||
|
||||
{/* Modal de Confirmação de Exclusão */}
|
||||
<Dialog
|
||||
open={isDeleteModalOpen}
|
||||
onClose={() => setIsDeleteModalOpen(false)}
|
||||
className="relative z-50"
|
||||
>
|
||||
<div
|
||||
className="fixed inset-0 bg-black/30 backdrop-blur-sm"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="mx-auto max-w-sm rounded-lg bg-white p-6 shadow-xl">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex-shrink-0">
|
||||
<ExclamationTriangleIcon className="h-10 w-10 text-red-500" />
|
||||
</div>
|
||||
<div>
|
||||
<Dialog.Title className="text-lg font-medium text-gray-900">
|
||||
Confirmar exclusão
|
||||
</Dialog.Title>
|
||||
<Dialog.Description className="mt-2 text-sm text-gray-500">
|
||||
Tem certeza que deseja excluir este processo? Esta ação não
|
||||
poderá ser desfeita.
|
||||
</Dialog.Description>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsDeleteModalOpen(false)}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDelete}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
|
||||
{/* Adicionar Modal de Audiência */}
|
||||
<AudienciaModal
|
||||
isOpen={isAudienciaModalOpen}
|
||||
onClose={() => {
|
||||
setIsAudienciaModalOpen(false);
|
||||
setEditingAudiencia(null);
|
||||
setIsFinalizacao(false);
|
||||
}}
|
||||
onSave={handleSaveAudiencia}
|
||||
editingAudiencia={editingAudiencia}
|
||||
isFinalizacao={isFinalizacao}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
import React from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { Processo } from '../../types/entities';
|
||||
|
||||
interface ProcessoFormProps {
|
||||
onSubmit: (data: Partial<Processo>) => void;
|
||||
initialData?: Partial<Processo>;
|
||||
}
|
||||
|
||||
const resultadoOptions = [
|
||||
{ value: 'NAO_JULGADO', label: 'Não Julgado' },
|
||||
{ value: 'PROCEDENTE', label: 'Procedente' },
|
||||
{ value: 'PARCIALMENTE_PROCEDENTE', label: 'Parcialmente Procedente' },
|
||||
{ value: 'IMPROCEDENTE', label: 'Improcedente' },
|
||||
{ value: 'SEM_ANALISE_MERITO', label: 'Sem Análise de Mérito' }
|
||||
];
|
||||
|
||||
export const ProcessoForm: React.FC<ProcessoFormProps> = ({ onSubmit, initialData }) => {
|
||||
const { register, handleSubmit, reset } = useForm<Partial<Processo>>({
|
||||
defaultValues: initialData,
|
||||
});
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Número do Processo
|
||||
</label>
|
||||
<input
|
||||
{...register('numero')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Natureza
|
||||
</label>
|
||||
<select
|
||||
{...register('natureza')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
>
|
||||
<option value="CIVEL">Cível</option>
|
||||
<option value="CRIMINAL">Criminal</option>
|
||||
<option value="PREVIDENCIARIO">Previdenciário</option>
|
||||
<option value="TRABALHISTA">Trabalhista</option>
|
||||
<option value="FAMILIA">Família</option>
|
||||
<option value="TRIBUTARIO">Tributário</option>
|
||||
<option value="ADMINISTRATIVO">Administrativo</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Status
|
||||
</label>
|
||||
<select
|
||||
{...register('status')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
>
|
||||
<option value="INICIAL">Inicial</option>
|
||||
<option value="EM_ANDAMENTO">Em Andamento</option>
|
||||
<option value="SUSPENSO">Suspenso</option>
|
||||
<option value="RECURSO">Recurso</option>
|
||||
<option value="CONCLUSO">Concluso</option>
|
||||
<option value="ARQUIVADO">Arquivado</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Resultado do Julgamento
|
||||
</label>
|
||||
<select
|
||||
{...register('resultado')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
>
|
||||
{resultadoOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Cliente
|
||||
</label>
|
||||
<input
|
||||
{...register('clienteId')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Valor da Causa
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
{...register('valorCausa')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Órgão Julgador
|
||||
</label>
|
||||
<input
|
||||
{...register('orgaoJulgador')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Nome da Contraparte
|
||||
</label>
|
||||
<input
|
||||
{...register('nomeContraparte')}
|
||||
className="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => reset()}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,54 @@
|
||||
import { format } from "date-fns";
|
||||
import { ptBR } from "date-fns/locale";
|
||||
import { DatajudProcesso } from "../../types/datajud";
|
||||
|
||||
interface ProcessoInfoProps {
|
||||
data: DatajudProcesso;
|
||||
}
|
||||
|
||||
export const ProcessoInfo = ({ data }: ProcessoInfoProps) => {
|
||||
return (
|
||||
<div className="bg-white rounded-lg shadow p-6 space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<InfoItem label="Classe" value={data.classe.nome} />
|
||||
<InfoItem
|
||||
label="Data de Ajuizamento"
|
||||
value={format(new Date(data.dataAjuizamento), "dd/MM/yyyy", {
|
||||
locale: ptBR,
|
||||
})}
|
||||
/>
|
||||
<InfoItem label="Grau" value={data.grau} />
|
||||
<InfoItem label="Formato" value={data.formato.nome} />
|
||||
<InfoItem label="Sistema" value={data.sistema.nome} />
|
||||
<InfoItem label="Órgão Julgador" value={data.orgaoJulgador.nome} />
|
||||
</div>
|
||||
|
||||
{data.assuntos.length > 0 && (
|
||||
<div className="mt-4">
|
||||
<h4 className="font-medium text-gray-700 mb-2">Assuntos</h4>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{data.assuntos.map((assunto) => (
|
||||
<span
|
||||
key={assunto.codigo}
|
||||
className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800"
|
||||
>
|
||||
{assunto.nome}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
function InfoItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProcessoInfo;
|
||||
@@ -0,0 +1,443 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { Dialog, Transition, Combobox } from "@headlessui/react";
|
||||
import {
|
||||
XMarkIcon,
|
||||
MagnifyingGlassIcon,
|
||||
CheckIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { Processo, NaturezaProcesso, TipoParte } from "../../types/entities";
|
||||
import { useProcessos } from "../../hooks/useProcessos";
|
||||
import { useClientes } from "../../hooks/useClientes";
|
||||
import { FormInput, FormSelect, FormCheckbox } from "../forms";
|
||||
import axios from "axios";
|
||||
import { UF_BRASIL, TRIBUNAIS } from "../../utils/constants/tribunais";
|
||||
import { useDatajud } from "../../hooks/useDatajud";
|
||||
import { ProcessoInfo } from "./ProcessoInfo"; // Adicionar import
|
||||
import { DatajudProcesso } from "../../types/datajud";
|
||||
|
||||
interface ProcessoModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
processo: Processo | null;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
interface OrgaoJulgadorOption {
|
||||
id: string;
|
||||
nome: string;
|
||||
}
|
||||
|
||||
interface OrgaoSugestao {
|
||||
id: string;
|
||||
nome: string;
|
||||
}
|
||||
|
||||
export const ProcessoModal: React.FC<ProcessoModalProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
processo,
|
||||
onSuccess,
|
||||
}) => {
|
||||
const [copiarOrgaoJulgador, setCopiarOrgaoJulgador] = useState(false);
|
||||
const { register, handleSubmit, setValue, watch, reset } = useForm();
|
||||
const { createProcesso, updateProcesso } = useProcessos();
|
||||
const { clientes } = useClientes(); // Adicionar hook de clientes
|
||||
const [clienteSearch, setClienteSearch] = useState("");
|
||||
const [selectedOrgao, setSelectedOrgao] =
|
||||
useState<OrgaoJulgadorOption | null>(null);
|
||||
const [orgaos, setOrgaos] = useState<string[]>([]);
|
||||
const [orgaoQuery, setOrgaoQuery] = useState("");
|
||||
const [selectedUF, setSelectedUF] = useState(processo?.tribunalUF || "");
|
||||
const [availableTribunais, setAvailableTribunais] = useState<any[]>([]);
|
||||
const { consultarProcesso } = useDatajud();
|
||||
const [dadosDatajud, setDadosDatajud] = useState<DatajudProcesso | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const orgaoJulgador = watch("orgaoJulgador");
|
||||
|
||||
useEffect(() => {
|
||||
if (copiarOrgaoJulgador) {
|
||||
setValue("orgaoOrigem", orgaoJulgador);
|
||||
}
|
||||
}, [orgaoJulgador, copiarOrgaoJulgador, setValue]);
|
||||
|
||||
// Adicionar useEffect para popular form quando editando
|
||||
useEffect(() => {
|
||||
if (isOpen && processo) {
|
||||
console.log("Populando formulário com:", processo);
|
||||
Object.keys(processo).forEach((key) => {
|
||||
if (
|
||||
key !== "id" &&
|
||||
key !== "dataCriacao" &&
|
||||
key !== "dataAtualizacao"
|
||||
) {
|
||||
setValue(key, processo[key]);
|
||||
}
|
||||
});
|
||||
if (processo.orgaoJulgadorRef) {
|
||||
setSelectedOrgao(processo.orgaoJulgadorRef);
|
||||
setValue("orgaoJulgador", processo.orgaoJulgadorRef.nome);
|
||||
}
|
||||
// Definir UF e tribunal ao editar
|
||||
setSelectedUF(processo.tribunalUF || "");
|
||||
setValue("tribunal", processo.tribunal || "");
|
||||
} else {
|
||||
reset({
|
||||
numero: "",
|
||||
natureza: "",
|
||||
tipoParteCliente: "",
|
||||
valorCausa: "",
|
||||
orgaoJulgador: "",
|
||||
orgaoOrigem: "",
|
||||
nomeContraparte: "",
|
||||
clienteId: "",
|
||||
tribunalUF: "",
|
||||
tribunal: "",
|
||||
});
|
||||
setSelectedUF("");
|
||||
}
|
||||
}, [isOpen, processo, setValue, reset]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// Tentar buscar órgãos existentes
|
||||
const loadOrgaos = async () => {
|
||||
try {
|
||||
const response = await axios.get<string[]>("/api/processos/orgaos");
|
||||
if (Array.isArray(response.data)) {
|
||||
setOrgaos(response.data.filter(Boolean));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao carregar órgãos:", error);
|
||||
setOrgaos([]); // Em caso de erro, inicializar com array vazio
|
||||
}
|
||||
};
|
||||
loadOrgaos();
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedUF) {
|
||||
setAvailableTribunais(TRIBUNAIS[selectedUF] || []);
|
||||
} else {
|
||||
setAvailableTribunais([]);
|
||||
}
|
||||
}, [selectedUF]);
|
||||
|
||||
const onSubmit = async (data: any) => {
|
||||
try {
|
||||
const processData = {
|
||||
...data,
|
||||
numero: data.numero.replace(/\D/g, ""),
|
||||
tribunalUF: selectedUF,
|
||||
tribunal: data.tribunal,
|
||||
dadosDatajud: dadosDatajud,
|
||||
valorCausa: data.valorCausa ? Number(data.valorCausa) : undefined,
|
||||
};
|
||||
|
||||
if (processo) {
|
||||
await updateProcesso.mutateAsync({
|
||||
id: processo.id,
|
||||
data: processData
|
||||
});
|
||||
} else {
|
||||
await createProcesso.mutateAsync(processData);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar processo:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Filtrar clientes baseado na busca
|
||||
const filteredClientes = clientes.filter(
|
||||
(cliente) =>
|
||||
cliente.nome.toLowerCase().includes(clienteSearch.toLowerCase()) ||
|
||||
cliente.cpfCnpj.includes(clienteSearch),
|
||||
);
|
||||
|
||||
// Filtrar órgãos baseado na busca
|
||||
const filteredOrgaos =
|
||||
orgaoQuery === ""
|
||||
? orgaos
|
||||
: orgaos.filter((orgao) =>
|
||||
orgao.toLowerCase().includes(orgaoQuery.toLowerCase()),
|
||||
);
|
||||
|
||||
const handleOrgaoSelect = (orgao: OrgaoJulgadorOption | null) => {
|
||||
setSelectedOrgao(orgao);
|
||||
if (orgao) {
|
||||
setValue("orgaoJulgador", orgao.nome);
|
||||
setValue("orgaoJulgadorId", orgao.id);
|
||||
}
|
||||
};
|
||||
|
||||
// Função para buscar dados do DataJud
|
||||
const buscarDadosDatajud = async (numero: string, tribunal: string) => {
|
||||
try {
|
||||
const dados = await consultarProcesso(numero, tribunal);
|
||||
if (dados) {
|
||||
setDadosDatajud(dados);
|
||||
// Preencher campos do formulário
|
||||
setValue("orgaoJulgador", dados.orgaoJulgador.nome);
|
||||
setValue("natureza", inferirNatureza(dados.classe.nome));
|
||||
// Outros campos conforme necessário
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Erro ao buscar dados do DataJud:", error);
|
||||
}
|
||||
};
|
||||
|
||||
// Função auxiliar para inferir natureza do processo
|
||||
const inferirNatureza = (classeNome: string): string => {
|
||||
const nome = classeNome.toLowerCase();
|
||||
if (nome.includes("cível")) return "CIVEL";
|
||||
if (nome.includes("criminal")) return "CRIMINAL";
|
||||
if (nome.includes("trabalh")) return "TRABALHISTA";
|
||||
// ... outras regras
|
||||
return "CIVEL";
|
||||
};
|
||||
|
||||
// Adicionar evento no campo de número do processo
|
||||
useEffect(() => {
|
||||
const numero = watch("numero");
|
||||
const tribunal = watch("tribunal");
|
||||
|
||||
if (numero?.length >= 20 && tribunal) {
|
||||
// Número CNJ completo
|
||||
buscarDadosDatajud(numero, tribunal);
|
||||
}
|
||||
}, [watch("numero"), watch("tribunal")]);
|
||||
|
||||
return (
|
||||
<Transition show={isOpen} as={React.Fragment}>
|
||||
<Dialog onClose={onClose} className="relative z-50">
|
||||
{/* ...existing modal backdrop code... */}
|
||||
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<Dialog.Panel className="mx-auto max-w-4xl w-full bg-white rounded-xl shadow-2xl">
|
||||
<div className="p-6">
|
||||
<div className="flex justify-between items-center mb-6">
|
||||
<Dialog.Title className="text-2xl font-bold text-gray-900">
|
||||
{processo ? "Editar Processo" : "Novo Processo"}
|
||||
</Dialog.Title>
|
||||
<button onClick={onClose}>
|
||||
<XMarkIcon className="h-6 w-6 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
{/* Substituir o FormSelect por uma busca customizada */}
|
||||
<div className="col-span-2 space-y-2">
|
||||
<label className="block text-sm font-semibold text-gray-700">
|
||||
Cliente <span className="text-red-500">*</span>
|
||||
</label>
|
||||
|
||||
{/* Campo de busca */}
|
||||
<div className="relative">
|
||||
<MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Buscar cliente por nome ou CPF..."
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500 focus:border-transparent"
|
||||
value={clienteSearch}
|
||||
onChange={(e) => setClienteSearch(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Lista de clientes filtrada */}
|
||||
<div className="mt-2 max-h-40 overflow-y-auto border border-gray-200 rounded-lg">
|
||||
{filteredClientes.length > 0 ? (
|
||||
<div className="divide-y divide-gray-200">
|
||||
{filteredClientes.map((cliente) => (
|
||||
<label
|
||||
key={cliente.id}
|
||||
className="flex items-center p-3 hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
{...register("clienteId", {
|
||||
required: "Cliente é obrigatório",
|
||||
})}
|
||||
value={cliente.id}
|
||||
className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300"
|
||||
/>
|
||||
<div className="ml-3">
|
||||
<p className="text-sm font-medium text-gray-900">
|
||||
{cliente.nome}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
CPF: {cliente.cpfCnpj}
|
||||
</p>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 text-center text-gray-500">
|
||||
Nenhum cliente encontrado
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
label="Número do Processo"
|
||||
{...register("numero")}
|
||||
placeholder="0000000-00.0000.000.0000"
|
||||
required
|
||||
/>
|
||||
<FormSelect
|
||||
label="Natureza"
|
||||
{...register("natureza")}
|
||||
options={Object.values(NaturezaProcesso).map((value) => ({
|
||||
value,
|
||||
label: value.charAt(0) + value.slice(1).toLowerCase(),
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
<FormSelect
|
||||
label="Tipo de Parte"
|
||||
{...register("tipoParteCliente")}
|
||||
options={Object.values(TipoParte).map((value) => ({
|
||||
value,
|
||||
label: value.charAt(0) + value.slice(1).toLowerCase(),
|
||||
}))}
|
||||
required
|
||||
/>
|
||||
<FormInput
|
||||
label="Valor da Causa"
|
||||
type="number"
|
||||
step="0.01"
|
||||
{...register("valorCausa")}
|
||||
/>
|
||||
<FormSelect
|
||||
label="UF do Tribunal"
|
||||
value={selectedUF || ""} // Garantir que nunca seja null
|
||||
onChange={(e) => {
|
||||
const value = e.target.value;
|
||||
setSelectedUF(value);
|
||||
setValue("tribunal", ""); // Limpar tribunal ao mudar UF
|
||||
}}
|
||||
required
|
||||
options={UF_BRASIL}
|
||||
/>
|
||||
|
||||
<FormSelect
|
||||
label="Tribunal"
|
||||
value={watch("tribunal") || ""} // Garantir que nunca seja null
|
||||
onChange={(e) => setValue("tribunal", e.target.value)}
|
||||
required
|
||||
options={availableTribunais}
|
||||
disabled={!selectedUF}
|
||||
/>
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-semibold text-gray-700 mb-2">
|
||||
Órgão Julgador <span className="text-red-500">*</span>
|
||||
</label>
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:ring-2 focus:ring-blue-500"
|
||||
{...register("orgaoJulgador", { required: true })}
|
||||
onChange={(e) => {
|
||||
setValue("orgaoJulgador", e.target.value);
|
||||
setOrgaoQuery(e.target.value);
|
||||
}}
|
||||
autoComplete="off"
|
||||
placeholder="Digite o órgão julgador..."
|
||||
/>
|
||||
{/* Lista de sugestões */}
|
||||
{orgaoQuery && (
|
||||
<ul className="absolute z-10 w-full mt-1 bg-white border border-gray-200 rounded-md shadow-lg max-h-60 overflow-auto">
|
||||
{filteredOrgaos.map((orgao, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className="px-4 py-2 hover:bg-blue-50 cursor-pointer"
|
||||
onClick={() => {
|
||||
setValue("orgaoJulgador", orgao);
|
||||
setOrgaoQuery("");
|
||||
}}
|
||||
>
|
||||
{orgao}
|
||||
</li>
|
||||
))}
|
||||
{filteredOrgaos.length === 0 && (
|
||||
<li className="px-4 py-2 text-gray-500 italic">
|
||||
Pressione Enter para adicionar "{orgaoQuery}"
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<FormInput
|
||||
label="Órgão de Origem"
|
||||
{...register("orgaoOrigem")}
|
||||
disabled={copiarOrgaoJulgador}
|
||||
/>
|
||||
<FormCheckbox
|
||||
label="Mesmo que Órgão Julgador"
|
||||
checked={copiarOrgaoJulgador}
|
||||
onChange={(e) =>
|
||||
setCopiarOrgaoJulgador(e.target.checked)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<FormInput
|
||||
label="Nome da Contraparte"
|
||||
{...register("nomeContraparte")}
|
||||
required
|
||||
/>
|
||||
<FormSelect
|
||||
label="Status de Atividade"
|
||||
{...register("statusAtividade")}
|
||||
options={[
|
||||
{ value: "ATIVO", label: "Ativo" },
|
||||
{ value: "BAIXADO", label: "Baixado" },
|
||||
{ value: "SUSPENSO", label: "Suspenso" },
|
||||
]}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
{dadosDatajud && (
|
||||
<div className="mt-4 p-4 bg-blue-50 rounded-lg">
|
||||
<h3 className="text-sm font-medium text-blue-800 mb-2">
|
||||
Dados encontrados no DataJud
|
||||
</h3>
|
||||
<ProcessoInfo data={dadosDatajud} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end space-x-3 pt-6">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-lg hover:bg-blue-700"
|
||||
>
|
||||
{processo ? "Salvar" : "Criar"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,169 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import api from '../../services/api';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { Processo } from '../../types/entities';
|
||||
|
||||
const resultadoOptions = [
|
||||
{ value: 'NAO_JULGADO', label: 'Não Julgado' },
|
||||
{ value: 'PROCEDENTE', label: 'Procedente' },
|
||||
{ value: 'PARCIALMENTE_PROCEDENTE', label: 'Parcialmente Procedente' },
|
||||
{ value: 'IMPROCEDENTE', label: 'Improcedente' },
|
||||
{ value: 'SEM_ANALISE_MERITO', label: 'Sem Análise de Mérito' }
|
||||
];
|
||||
|
||||
const getResultadoLabel = (valor: string) => {
|
||||
return resultadoOptions.find(opt => opt.value === valor)?.label || valor;
|
||||
};
|
||||
|
||||
const getResultadoColor = (resultado: string) => {
|
||||
switch (resultado) {
|
||||
case 'PROCEDENTE': return 'bg-green-100 text-green-800';
|
||||
case 'PARCIALMENTE_PROCEDENTE': return 'bg-yellow-100 text-yellow-800';
|
||||
case 'IMPROCEDENTE': return 'bg-red-100 text-red-800';
|
||||
case 'SEM_ANALISE_MERITO': return 'bg-gray-100 text-gray-800';
|
||||
default: return 'bg-blue-100 text-blue-800';
|
||||
}
|
||||
};
|
||||
|
||||
export const ProcessoView: React.FC = () => {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
|
||||
const { data: processo, refetch, isLoading, isError } = useQuery<Processo>(
|
||||
['processo', id],
|
||||
async () => {
|
||||
const response = await api.get(`/processos/${id}`); // remover /api
|
||||
return response.data;
|
||||
}
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
return <div>Carregando...</div>;
|
||||
}
|
||||
|
||||
if (isError || !processo) {
|
||||
return <div>Erro ao carregar processo. Processo não encontrado.</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Status e Resultado do Processo */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white">Status do Processo</h3>
|
||||
|
||||
{/* Botão de Julgamento */}
|
||||
<div className="flex items-center space-x-4">
|
||||
<span className="text-sm text-gray-500">Processo julgado?</span>
|
||||
<select
|
||||
value={processo.resultado}
|
||||
onChange={async (e) => {
|
||||
try {
|
||||
await api.patch(`/processos/${processo.id}/resultado`, {
|
||||
resultado: e.target.value
|
||||
});
|
||||
refetch();
|
||||
} catch (error) {
|
||||
console.error('Erro ao atualizar resultado:', error);
|
||||
alert('Erro ao atualizar resultado do processo');
|
||||
}
|
||||
}}
|
||||
className="rounded-lg border-gray-300 text-sm dark:bg-gray-700 dark:border-gray-600"
|
||||
>
|
||||
{resultadoOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm font-medium text-gray-500">Status:</span>
|
||||
<span className="px-2 py-1 text-sm rounded-full bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
|
||||
{processo.status}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm font-medium text-gray-500">Resultado:</span>
|
||||
<span className={`px-2 py-1 text-sm rounded-full ${getResultadoColor(processo.resultado)}`}>
|
||||
{getResultadoLabel(processo.resultado)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Resto das informações do processo */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h2 className="text-2xl font-semibold text-gray-900 dark:text-white mb-4">
|
||||
Processo {processo.numero}
|
||||
</h2>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Cliente</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{processo.cliente.nome}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Contraparte</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{processo.nomeContraparte}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Natureza</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{processo.natureza}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Status</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{processo.status}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Valor da Causa</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{processo.valorCausa?.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' })}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Data de Criação</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{format(new Date(processo.dataCriacao), 'dd/MM/yyyy', { locale: ptBR })}</p>
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-medium">Última Atualização</h3>
|
||||
<p className="text-gray-700 dark:text-gray-300">{format(new Date(processo.dataAtualizacao), 'dd/MM/yyyy', { locale: ptBR })}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<h3 className="text-lg font-medium mb-4">Resultado</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className={`px-2 py-1 text-sm rounded-full ${getResultadoColor(processo.resultado)}`}>
|
||||
{getResultadoLabel(processo.resultado)}
|
||||
</span>
|
||||
<select
|
||||
value={processo.resultado}
|
||||
onChange={async (e) => {
|
||||
try {
|
||||
await api.patch(`/processos/${processo.id}/resultado`, {
|
||||
resultado: e.target.value
|
||||
});
|
||||
refetch(); // Atualizar dados do processo
|
||||
} catch (error) {
|
||||
console.error('Erro ao atualizar resultado:', error);
|
||||
alert('Erro ao atualizar resultado do processo');
|
||||
}
|
||||
}}
|
||||
className="rounded-lg border-gray-300 text-sm"
|
||||
>
|
||||
{resultadoOptions.map(option => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,176 @@
|
||||
import React from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Processo } from "../../types/entities";
|
||||
import { useProcessos } from "../../hooks/useProcessos";
|
||||
import { formatNumeroProcesso } from "../../utils/formatters";
|
||||
import { DocumentTextIcon, ClockIcon } from "@heroicons/react/24/outline";
|
||||
|
||||
interface ProcessosListProps {
|
||||
searchTerm: string;
|
||||
onEdit: (processo: Processo) => void;
|
||||
}
|
||||
|
||||
const resultadoLabel = {
|
||||
NAO_JULGADO: 'Não Julgado',
|
||||
PROCEDENTE: 'Procedente',
|
||||
PARCIALMENTE_PROCEDENTE: 'Parcialmente Procedente',
|
||||
IMPROCEDENTE: 'Improcedente',
|
||||
SEM_ANALISE_MERITO: 'Sem Análise de Mérito'
|
||||
};
|
||||
|
||||
const resultadoColor = {
|
||||
NAO_JULGADO: 'bg-gray-100 text-gray-800',
|
||||
PROCEDENTE: 'bg-green-100 text-green-800',
|
||||
PARCIALMENTE_PROCEDENTE: 'bg-yellow-100 text-yellow-800',
|
||||
IMPROCEDENTE: 'bg-red-100 text-red-800',
|
||||
SEM_ANALISE_MERITO: 'bg-gray-100 text-gray-800'
|
||||
};
|
||||
|
||||
const getResultadoColor = (resultado: string) => {
|
||||
return resultadoColor[resultado as keyof typeof resultadoColor] || 'bg-gray-100 text-gray-800';
|
||||
};
|
||||
|
||||
export const ProcessosList: React.FC<ProcessosListProps> = ({
|
||||
searchTerm,
|
||||
onEdit,
|
||||
}) => {
|
||||
const navigate = useNavigate();
|
||||
const { processos, isLoading } = useProcessos();
|
||||
|
||||
const filteredProcessos = processos.filter(
|
||||
(processo) =>
|
||||
processo.numero.includes(searchTerm) ||
|
||||
processo.nomeContraparte
|
||||
?.toLowerCase()
|
||||
.includes(searchTerm.toLowerCase()),
|
||||
);
|
||||
|
||||
const getResultadoDisplay = (processo: Processo) => {
|
||||
if (!processo.resultado || !resultadoLabel[processo.resultado as keyof typeof resultadoLabel]) {
|
||||
return (
|
||||
<span className="px-2 py-1 text-xs rounded-full bg-gray-100 text-gray-800">
|
||||
Não Julgado
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${getResultadoColor(processo.resultado)}`}>
|
||||
{resultadoLabel[processo.resultado as keyof typeof resultadoLabel]}
|
||||
</span>
|
||||
);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="animate-pulse">Carregando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"
|
||||
>
|
||||
Processo
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"
|
||||
>
|
||||
Natureza
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"
|
||||
>
|
||||
Parte
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"
|
||||
>
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase"
|
||||
>
|
||||
Próximos Prazos
|
||||
</th>
|
||||
<th
|
||||
scope="col"
|
||||
className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider"
|
||||
>
|
||||
Resultado
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200">
|
||||
{filteredProcessos.map((processo) => (
|
||||
<tr
|
||||
key={processo.id}
|
||||
onClick={() => navigate(`/processos/${processo.id}`)}
|
||||
className="hover:bg-gray-50 cursor-pointer"
|
||||
>
|
||||
<td className="px-6 py-4">
|
||||
<div className="flex items-center">
|
||||
<DocumentTextIcon className="h-10 w-10 text-gray-400" />
|
||||
<div className="ml-4">
|
||||
<div className="text-sm font-medium text-gray-900">
|
||||
{formatNumeroProcesso(processo.numero)}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
{processo.orgaoJulgador}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">
|
||||
{processo.natureza}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<div className="text-sm text-gray-900">
|
||||
{processo.tipoParteCliente === "AUTOR" ? "Autor" : "Réu"}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500">
|
||||
{processo.nomeContraparte}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
<span
|
||||
className={`px-2 py-1 text-xs rounded-full ${
|
||||
processo.statusAtividade === "ATIVO"
|
||||
? "bg-green-100 text-green-800"
|
||||
: processo.statusAtividade === "BAIXADO"
|
||||
? "bg-blue-100 text-blue-800"
|
||||
: processo.statusAtividade === "SUSPENSO"
|
||||
? "bg-yellow-100 text-yellow-800"
|
||||
: "bg-gray-100 text-gray-800"
|
||||
}`}
|
||||
>
|
||||
{processo.statusAtividade}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{processo.diligencias?.length > 0 ? (
|
||||
<div className="flex items-center text-sm text-gray-500">
|
||||
<ClockIcon className="h-4 w-4 mr-1" />
|
||||
{processo.diligencias.length} prazos
|
||||
</div>
|
||||
) : (
|
||||
<span className="text-sm text-gray-500">Sem prazos</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
{getResultadoDisplay(processo)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import React, { useState } from "react";
|
||||
import { PlusIcon, MagnifyingGlassIcon } from "@heroicons/react/24/outline";
|
||||
import { ProcessosList } from "./ProcessosList";
|
||||
import { ProcessoModal } from "./ProcessoModal";
|
||||
import { Processo } from "../../types/entities";
|
||||
|
||||
export const ProcessosPage: React.FC = () => {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [selectedProcesso, setSelectedProcesso] = useState<Processo | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="relative">
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Buscar processos..."
|
||||
className="w-full pl-10 pr-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600
|
||||
bg-white dark:bg-gray-700 text-gray-900 dark:text-white
|
||||
focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400 focus:border-transparent"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedProcesso(null);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg
|
||||
hover:bg-blue-700 dark:hover:bg-blue-500 transition-colors"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5 mr-2" />
|
||||
Novo Processo
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Lista de Processos */}
|
||||
<div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
{/* ...headers... */}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{/* ...rows... */}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<ProcessosList
|
||||
searchTerm={searchTerm}
|
||||
onEdit={(processo) => {
|
||||
setSelectedProcesso(processo);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
/>
|
||||
|
||||
<ProcessoModal
|
||||
isOpen={isModalOpen}
|
||||
processo={selectedProcesso}
|
||||
onClose={() => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedProcesso(null);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,262 @@
|
||||
import {
|
||||
Dialog,
|
||||
TextField,
|
||||
MenuItem,
|
||||
Button,
|
||||
Box,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useState, useEffect } from "react";
|
||||
import { TipoCustaProcessual, StatusPagamento } from "@prisma/client";
|
||||
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
|
||||
interface DialogCustaProcessualProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => Promise<void>;
|
||||
editingCusta?: any;
|
||||
}
|
||||
|
||||
export function DialogCustaProcessual({
|
||||
open,
|
||||
onClose,
|
||||
onSave,
|
||||
editingCusta,
|
||||
}: DialogCustaProcessualProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
tipo: "",
|
||||
descricao: "",
|
||||
valor: "",
|
||||
percentual: "",
|
||||
status: "PENDENTE",
|
||||
vencimento: null as Date | null,
|
||||
dataPagamento: null as Date | null,
|
||||
observacoes: "",
|
||||
numeroParcelas: 1,
|
||||
parcelaAtual: 1,
|
||||
comprovante: "",
|
||||
});
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
// Atualizar form quando o editingCusta muda
|
||||
useEffect(() => {
|
||||
if (editingCusta) {
|
||||
setFormData({
|
||||
tipo: editingCusta.tipo || "",
|
||||
descricao: editingCusta.descricao || "",
|
||||
valor: editingCusta.valor?.toString() || "",
|
||||
percentual: editingCusta.percentual?.toString() || "",
|
||||
status: editingCusta.status || "PENDENTE",
|
||||
vencimento: editingCusta.vencimento
|
||||
? new Date(editingCusta.vencimento)
|
||||
: null,
|
||||
dataPagamento: editingCusta.dataPagamento
|
||||
? new Date(editingCusta.dataPagamento)
|
||||
: null,
|
||||
observacoes: editingCusta.observacoes || "",
|
||||
numeroParcelas: editingCusta.numeroParcelas || 1,
|
||||
parcelaAtual: editingCusta.parcelaAtual || 1,
|
||||
comprovante: editingCusta.comprovante || "",
|
||||
});
|
||||
} else {
|
||||
// Reset para os valores padrão
|
||||
setFormData({
|
||||
tipo: "",
|
||||
descricao: "",
|
||||
valor: "",
|
||||
percentual: "",
|
||||
status: "PENDENTE",
|
||||
vencimento: null,
|
||||
dataPagamento: null,
|
||||
observacoes: "",
|
||||
numeroParcelas: 1,
|
||||
parcelaAtual: 1,
|
||||
comprovante: "",
|
||||
});
|
||||
}
|
||||
}, [editingCusta, open]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
// Validar campos obrigatórios
|
||||
if (!formData.tipo) {
|
||||
setFormError("Selecione o tipo da custa");
|
||||
return;
|
||||
}
|
||||
if (!formData.descricao) {
|
||||
setFormError("Informe a descrição da custa");
|
||||
return;
|
||||
}
|
||||
if (!formData.valor) {
|
||||
setFormError("Informe o valor da custa");
|
||||
return;
|
||||
}
|
||||
|
||||
// Preparar dados
|
||||
const preparedData = {
|
||||
...formData,
|
||||
valor: Number(formData.valor),
|
||||
percentual: formData.percentual ? Number(formData.percentual) : null,
|
||||
numeroParcelas: Number(formData.numeroParcelas),
|
||||
parcelaAtual: Number(formData.parcelaAtual),
|
||||
};
|
||||
|
||||
await onSave(preparedData);
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
console.error("Erro ao salvar custa:", error);
|
||||
setFormError(error.message || "Erro ao salvar custa. Tente novamente.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<Box component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
|
||||
<h2 className="text-lg font-semibold mb-4">
|
||||
{editingCusta ? "Editar Custa Processual" : "Nova Custa Processual"}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Tipo"
|
||||
value={formData.tipo}
|
||||
onChange={(e) => setFormData({ ...formData, tipo: e.target.value })}
|
||||
required
|
||||
>
|
||||
{Object.values(TipoCustaProcessual).map((tipo) => (
|
||||
<MenuItem key={tipo} value={tipo}>
|
||||
{tipo.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Descrição"
|
||||
value={formData.descricao}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, descricao: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor"
|
||||
type="number"
|
||||
value={formData.valor}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valor: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual (se aplicável)"
|
||||
type="number"
|
||||
value={formData.percentual}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentual: e.target.value })
|
||||
}
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDateFns}
|
||||
adapterLocale={ptBR}
|
||||
>
|
||||
<DatePicker
|
||||
label="Vencimento"
|
||||
value={formData.vencimento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, vencimento: date })
|
||||
}
|
||||
sx={{ width: "100%", mb: 2 }}
|
||||
/>
|
||||
|
||||
{formData.status === "PAGO" && (
|
||||
<DatePicker
|
||||
label="Data de Pagamento"
|
||||
value={formData.dataPagamento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, dataPagamento: date })
|
||||
}
|
||||
sx={{ width: "100%" }}
|
||||
/>
|
||||
)}
|
||||
</LocalizationProvider>
|
||||
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Status"
|
||||
value={formData.status}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, status: e.target.value })
|
||||
}
|
||||
required
|
||||
>
|
||||
{Object.values(StatusPagamento).map((status) => (
|
||||
<MenuItem key={status} value={status}>
|
||||
{status.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Número de Parcelas"
|
||||
type="number"
|
||||
value={formData.numeroParcelas}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
numeroParcelas: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Observações"
|
||||
multiline
|
||||
rows={3}
|
||||
value={formData.observacoes}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, observacoes: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<Box sx={{ mt: 2, p: 2, bgcolor: "error.light", borderRadius: 1 }}>
|
||||
<Typography color="error">{formError}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{ mt: 3, display: "flex", justifyContent: "flex-end", gap: 2 }}
|
||||
>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button type="submit" variant="contained" color="primary">
|
||||
Salvar
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
export default DialogCustaProcessual;
|
||||
@@ -0,0 +1,353 @@
|
||||
import {
|
||||
Dialog,
|
||||
TextField,
|
||||
MenuItem,
|
||||
Button,
|
||||
Box,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { useState, useEffect } from "react";
|
||||
import { FormaPagamento, StatusPagamento } from "@prisma/client";
|
||||
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
import { IHonorario, IHonorarioCreate } from "../types/financeiro";
|
||||
|
||||
interface DialogHonorarioProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: Partial<IHonorarioCreate>) => Promise<void>;
|
||||
editingHonorario?: IHonorario;
|
||||
}
|
||||
|
||||
const DialogHonorario: React.FC<DialogHonorarioProps> = ({
|
||||
open,
|
||||
onClose,
|
||||
onSave,
|
||||
editingHonorario,
|
||||
}) => {
|
||||
const [formData, setFormData] = useState({
|
||||
formaPagamento: "VISTA",
|
||||
valorFixo: "",
|
||||
percentualCausa: "",
|
||||
percentualExito: "",
|
||||
valorEntrada: "",
|
||||
numeroParcelas: 1,
|
||||
valorParcela: "",
|
||||
diaVencimento: 10,
|
||||
status: "PENDENTE",
|
||||
dataVencimento: new Date(),
|
||||
observacoes: "",
|
||||
});
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
// Atualizar form quando o editingHonorario muda
|
||||
useEffect(() => {
|
||||
if (editingHonorario) {
|
||||
setFormData({
|
||||
formaPagamento: editingHonorario.formaPagamento,
|
||||
valorFixo: editingHonorario.valorFixo || "",
|
||||
percentualCausa: editingHonorario.percentualCausa || "",
|
||||
percentualExito: editingHonorario.percentualExito || "",
|
||||
valorEntrada: editingHonorario.valorEntrada || "",
|
||||
numeroParcelas: editingHonorario.numeroParcelas || 1,
|
||||
valorParcela: editingHonorario.valorParcela || "",
|
||||
diaVencimento: editingHonorario.diaVencimento || 10,
|
||||
status: editingHonorario.status,
|
||||
dataVencimento: editingHonorario.dataVencimento
|
||||
? new Date(editingHonorario.dataVencimento)
|
||||
: new Date(),
|
||||
observacoes: editingHonorario.observacoes || "",
|
||||
});
|
||||
} else {
|
||||
// Reset para os valores padrão
|
||||
setFormData({
|
||||
formaPagamento: "VISTA",
|
||||
valorFixo: "",
|
||||
percentualCausa: "",
|
||||
percentualExito: "",
|
||||
valorEntrada: "",
|
||||
numeroParcelas: 1,
|
||||
valorParcela: "",
|
||||
diaVencimento: 10,
|
||||
status: "PENDENTE",
|
||||
dataVencimento: new Date(),
|
||||
observacoes: "",
|
||||
});
|
||||
}
|
||||
}, [editingHonorario, open]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
// Validações básicas
|
||||
const validationError = validateFormData(formData);
|
||||
if (validationError) {
|
||||
setFormError(validationError);
|
||||
return;
|
||||
}
|
||||
|
||||
// Converter strings numéricas
|
||||
const preparedData = {
|
||||
...formData,
|
||||
valorFixo: formData.valorFixo ? Number(formData.valorFixo) : null,
|
||||
percentualCausa: formData.percentualCausa
|
||||
? Number(formData.percentualCausa)
|
||||
: null,
|
||||
percentualExito: formData.percentualExito
|
||||
? Number(formData.percentualExito)
|
||||
: null,
|
||||
valorEntrada: formData.valorEntrada
|
||||
? Number(formData.valorEntrada)
|
||||
: null,
|
||||
valorParcela: formData.valorParcela
|
||||
? Number(formData.valorParcela)
|
||||
: null,
|
||||
};
|
||||
|
||||
await onSave(preparedData);
|
||||
onClose();
|
||||
} catch (error: any) {
|
||||
console.error("Erro ao salvar honorário:", error);
|
||||
setFormError(
|
||||
error.message || "Erro ao salvar honorário. Tente novamente.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const validateFormData = (data: any): string | null => {
|
||||
if (!data.formaPagamento) {
|
||||
return "Forma de pagamento é obrigatória";
|
||||
}
|
||||
|
||||
switch (data.formaPagamento) {
|
||||
case "VISTA":
|
||||
if (!data.valorFixo) {
|
||||
return "Informe o valor do honorário";
|
||||
}
|
||||
break;
|
||||
case "PERCENTUAL_CAUSA":
|
||||
if (!data.percentualCausa) {
|
||||
return "Informe o percentual da causa";
|
||||
}
|
||||
break;
|
||||
case "PERCENTUAL_EXITO":
|
||||
if (!data.percentualExito) {
|
||||
return "Informe o percentual do êxito";
|
||||
}
|
||||
break;
|
||||
case "PARCELADO":
|
||||
case "ENTRADA_MAIS_PARCELAS":
|
||||
if (!data.valorParcela) {
|
||||
return "Informe o valor da parcela";
|
||||
}
|
||||
if (!data.numeroParcelas || data.numeroParcelas < 1) {
|
||||
return "Informe o número de parcelas";
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// Mostrar campos de entrada quando for percentual com entrada
|
||||
const showEntrada =
|
||||
formData.formaPagamento === "ENTRADA_MAIS_PARCELAS" ||
|
||||
formData.formaPagamento === "PERCENTUAL_CAUSA_COM_ENTRADA";
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
|
||||
<Box component="form" onSubmit={handleSubmit} sx={{ p: 3 }}>
|
||||
<h2 className="text-lg font-semibold mb-4">
|
||||
{editingHonorario ? "Editar Honorário" : "Novo Honorário"}
|
||||
</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>Forma de Pagamento</InputLabel>
|
||||
<Select
|
||||
value={formData.formaPagamento}
|
||||
label="Forma de Pagamento"
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, formaPagamento: e.target.value })
|
||||
}
|
||||
>
|
||||
{Object.values(FormaPagamento).map((forma) => (
|
||||
<MenuItem key={forma} value={forma}>
|
||||
{forma.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
|
||||
{formData.formaPagamento === "VISTA" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor"
|
||||
type="number"
|
||||
value={formData.valorFixo}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorFixo: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(formData.formaPagamento === "PERCENTUAL_CAUSA" ||
|
||||
formData.formaPagamento === "PERCENTUAL_CAUSA_COM_ENTRADA") && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual da Causa"
|
||||
type="number"
|
||||
value={formData.percentualCausa}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentualCausa: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{formData.formaPagamento === "PERCENTUAL_EXITO" && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Percentual do Êxito"
|
||||
type="number"
|
||||
value={formData.percentualExito}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, percentualExito: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01", min: "0", max: "100" }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(formData.formaPagamento === "PARCELADO" ||
|
||||
formData.formaPagamento === "ENTRADA_MAIS_PARCELAS") && (
|
||||
<>
|
||||
{showEntrada && (
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor da Entrada"
|
||||
type="number"
|
||||
value={formData.valorEntrada}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorEntrada: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
)}
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Número de Parcelas"
|
||||
type="number"
|
||||
value={formData.numeroParcelas}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
numeroParcelas: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
required
|
||||
inputProps={{ min: "1" }}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Valor da Parcela"
|
||||
type="number"
|
||||
value={formData.valorParcela}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, valorParcela: e.target.value })
|
||||
}
|
||||
required
|
||||
inputProps={{ step: "0.01" }}
|
||||
/>
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Dia do Vencimento"
|
||||
type="number"
|
||||
value={formData.diaVencimento}
|
||||
onChange={(e) =>
|
||||
setFormData({
|
||||
...formData,
|
||||
diaVencimento: parseInt(e.target.value),
|
||||
})
|
||||
}
|
||||
inputProps={{ min: 1, max: 31 }}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<TextField
|
||||
select
|
||||
fullWidth
|
||||
label="Status"
|
||||
value={formData.status}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, status: e.target.value })
|
||||
}
|
||||
required
|
||||
>
|
||||
{Object.values(StatusPagamento).map((status) => (
|
||||
<MenuItem key={status} value={status}>
|
||||
{status.replace(/_/g, " ")}
|
||||
</MenuItem>
|
||||
))}
|
||||
</TextField>
|
||||
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDateFns}
|
||||
adapterLocale={ptBR}
|
||||
>
|
||||
<DatePicker
|
||||
label="Data de Vencimento"
|
||||
value={formData.dataVencimento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, dataVencimento: date || new Date() })
|
||||
}
|
||||
sx={{ width: "100%" }}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
|
||||
<TextField
|
||||
fullWidth
|
||||
label="Observações"
|
||||
multiline
|
||||
rows={3}
|
||||
value={formData.observacoes}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, observacoes: e.target.value })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<Box sx={{ mt: 2, p: 2, bgcolor: "error.light", borderRadius: 1 }}>
|
||||
<Typography color="error">{formError}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box
|
||||
sx={{ mt: 3, display: "flex", justifyContent: "flex-end", gap: 2 }}
|
||||
>
|
||||
<Button onClick={onClose}>Cancelar</Button>
|
||||
<Button type="submit" variant="contained" color="primary">
|
||||
Salvar
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default DialogHonorario;
|
||||
@@ -0,0 +1,213 @@
|
||||
import { Fragment, useState } from "react";
|
||||
import { Dialog, Transition } from "@headlessui/react";
|
||||
import { XMarkIcon } from "@heroicons/react/24/outline";
|
||||
import { DatePicker } from "@mui/x-date-pickers";
|
||||
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import ptBR from "date-fns/locale/pt-BR";
|
||||
import { formatCurrency } from "../../../utils/format";
|
||||
import { StatusPagamento } from "@prisma/client";
|
||||
|
||||
interface ParcelaHonorario {
|
||||
id: string;
|
||||
honorarioId: string;
|
||||
numeroParcela: number;
|
||||
valor: number;
|
||||
valorPago?: number | null;
|
||||
vencimento: Date;
|
||||
dataPagamento?: Date | null;
|
||||
status: StatusPagamento;
|
||||
comprovante?: string | null;
|
||||
observacoes?: string | null;
|
||||
}
|
||||
|
||||
interface DialogParcelaProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (data: any) => Promise<void>;
|
||||
parcela: ParcelaHonorario;
|
||||
tipo: "honorario" | "custa";
|
||||
}
|
||||
|
||||
export function DialogParcela({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
parcela,
|
||||
tipo,
|
||||
}: DialogParcelaProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
status: parcela?.status || "PENDENTE",
|
||||
dataPagamento: parcela?.dataPagamento
|
||||
? new Date(parcela?.dataPagamento)
|
||||
: null,
|
||||
valorPago: parcela?.valorPago || "",
|
||||
comprovante: parcela?.comprovante || "",
|
||||
observacoes: parcela?.observacoes || "",
|
||||
});
|
||||
|
||||
const handleValorPagoChange = (valor: string) => {
|
||||
const valorPago = Number(valor);
|
||||
const valorParcela = Number(parcela.valor);
|
||||
|
||||
let novoStatus = "PENDENTE";
|
||||
if (valorPago >= valorParcela) {
|
||||
novoStatus = "PAGO";
|
||||
} else if (valorPago > 0) {
|
||||
novoStatus = "PARCIALMENTE_PAGO";
|
||||
}
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
valorPago: valor,
|
||||
status: novoStatus,
|
||||
dataPagamento: novoStatus === "PAGO" ? new Date() : prev.dataPagamento,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
await onSave(formData);
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Transition appear show={isOpen} as={Fragment}>
|
||||
<Dialog as="div" className="relative z-50" onClose={onClose}>
|
||||
<div className="fixed inset-0 bg-black/30 backdrop-blur-sm" />
|
||||
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
|
||||
<Dialog.Title
|
||||
as="div"
|
||||
className="flex items-center justify-between mb-4"
|
||||
>
|
||||
<h3 className="text-lg font-medium leading-6 text-gray-900">
|
||||
Atualizar Parcela {parcela?.numeroParcela}
|
||||
</h3>
|
||||
<button
|
||||
type="button"
|
||||
className="text-gray-400 hover:text-gray-500"
|
||||
onClick={onClose}
|
||||
>
|
||||
<XMarkIcon className="h-6 w-6" />
|
||||
</button>
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Valor da Parcela
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formatCurrency(parcela.valor)}
|
||||
disabled
|
||||
className="mt-1 block w-full rounded-md border-gray-300 bg-gray-50"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Valor Pago
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={formData.valorPago}
|
||||
onChange={(e) => handleValorPagoChange(e.target.value)}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Status
|
||||
</label>
|
||||
<select
|
||||
value={formData.status}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, status: e.target.value })
|
||||
}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
|
||||
>
|
||||
{Object.values(StatusPagamento).map((status) => (
|
||||
<option key={status} value={status}>
|
||||
{status.replace(/_/g, " ")}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{formData.status === "PAGO" && (
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Data do Pagamento
|
||||
</label>
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDateFns}
|
||||
adapterLocale={ptBR}
|
||||
>
|
||||
<DatePicker
|
||||
value={formData.dataPagamento}
|
||||
onChange={(date) =>
|
||||
setFormData({ ...formData, dataPagamento: date })
|
||||
}
|
||||
className="mt-1 block w-full"
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Comprovante (URL)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.comprovante}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, comprovante: e.target.value })
|
||||
}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700">
|
||||
Observações
|
||||
</label>
|
||||
<textarea
|
||||
value={formData.observacoes}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, observacoes: e.target.value })
|
||||
}
|
||||
rows={3}
|
||||
className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="inline-flex justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
</Transition>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { default as DialogCustaProcessual } from "./DialogCustaProcessual";
|
||||
export { default as DialogHonorario } from "./DialogHonorario";
|
||||
export { default as DialogParcela } from "./DialogParcela";
|
||||
@@ -0,0 +1,53 @@
|
||||
import { memo } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
Chip,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import { Edit as EditIcon } from "@mui/icons-material";
|
||||
import { formatCurrency, formatDate } from "../../../utils/format";
|
||||
|
||||
const CustasTable = memo(({ custas, onEdit, getStatusColor }) => {
|
||||
return (
|
||||
<Table>
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell>Tipo</TableCell>
|
||||
<TableCell>Descrição</TableCell>
|
||||
<TableCell align="right">Valor</TableCell>
|
||||
<TableCell>Vencimento</TableCell>
|
||||
<TableCell>Status</TableCell>
|
||||
<TableCell>Ações</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{custas?.map((custa) => (
|
||||
<TableRow key={custa.id}>
|
||||
<TableCell>{custa.tipo}</TableCell>
|
||||
<TableCell>{custa.descricao}</TableCell>
|
||||
<TableCell align="right">{formatCurrency(custa.valor)}</TableCell>
|
||||
<TableCell>{formatDate(custa.vencimento)}</TableCell>
|
||||
<TableCell>
|
||||
<Chip
|
||||
label={custa.status}
|
||||
color={getStatusColor(custa.status)}
|
||||
size="small"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<IconButton size="small" onClick={() => onEdit(custa)}>
|
||||
<EditIcon />
|
||||
</IconButton>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
);
|
||||
});
|
||||
|
||||
export default CustasTable;
|
||||
@@ -0,0 +1,251 @@
|
||||
import { useState } from 'react';
|
||||
import { useQuery, useQueryClient } from 'react-query';
|
||||
import { formatCurrency } from '../../utils/format';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { FormInput, FormSelect } from '../forms';
|
||||
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import api from '../../services/api';
|
||||
|
||||
// Função auxiliar para retornar as cores do status
|
||||
const getStatusColor = (status: string) => {
|
||||
const colors = {
|
||||
PENDENTE: 'bg-yellow-100 text-yellow-800',
|
||||
PAGO: 'bg-green-100 text-green-800',
|
||||
VENCIDO: 'bg-red-100 text-red-800',
|
||||
CANCELADO: 'bg-gray-100 text-gray-800',
|
||||
PARCIALMENTE_PAGO: 'bg-blue-100 text-blue-800'
|
||||
};
|
||||
return colors[status] || colors.PENDENTE;
|
||||
};
|
||||
|
||||
const TIPOS_CUSTA = [
|
||||
{ value: 'TAXA_ADMINISTRATIVA', label: 'Taxa Administrativa' },
|
||||
{ value: 'RECURSO', label: 'Recurso' },
|
||||
{ value: 'DILIGENCIA', label: 'Diligência' },
|
||||
{ value: 'CERTIDAO', label: 'Certidão' },
|
||||
{ value: 'COPIA', label: 'Cópia' },
|
||||
{ value: 'OUTROS', label: 'Outros' }
|
||||
];
|
||||
|
||||
export function CustaAdministrativaPanel({ processoId }) {
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [selectedCusta, setSelectedCusta] = useState(null);
|
||||
const { register, handleSubmit, reset, setValue } = useForm();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
const { data: custas, isLoading } = useQuery(
|
||||
['custas-administrativas', processoId],
|
||||
async () => {
|
||||
const response = await api.get(`/processos-administrativos/${processoId}/custas`);
|
||||
return response.data;
|
||||
}
|
||||
);
|
||||
|
||||
const handleEdit = (custa) => {
|
||||
setSelectedCusta(custa);
|
||||
Object.keys(custa).forEach(key => {
|
||||
if (key === 'vencimento' || key === 'dataPagamento') {
|
||||
setValue(key, custa[key] ? new Date(custa[key]).toISOString().split('T')[0] : '');
|
||||
} else {
|
||||
setValue(key, custa[key]);
|
||||
}
|
||||
});
|
||||
setIsModalOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (window.confirm('Tem certeza que deseja excluir esta custa?')) {
|
||||
try {
|
||||
await api.delete(`/processos-administrativos/${processoId}/custas/${id}`);
|
||||
queryClient.invalidateQueries(['custas-administrativas', processoId]);
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir custa:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = async (data) => {
|
||||
try {
|
||||
// Formatar as datas antes de enviar
|
||||
const formattedData = {
|
||||
...data,
|
||||
vencimento: data.vencimento ? new Date(data.vencimento).toISOString() : null,
|
||||
dataPagamento: data.dataPagamento ? new Date(data.dataPagamento).toISOString() : null,
|
||||
valor: Number(data.valor)
|
||||
};
|
||||
|
||||
if (selectedCusta) {
|
||||
await api.put(`/processos-administrativos/${processoId}/custas/${selectedCusta.id}`, formattedData);
|
||||
} else {
|
||||
await api.post(`/processos-administrativos/${processoId}/custas`, formattedData);
|
||||
}
|
||||
|
||||
queryClient.invalidateQueries(['custas-administrativas', processoId]);
|
||||
setIsModalOpen(false);
|
||||
setSelectedCusta(null);
|
||||
reset();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar custa:', error);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) return <div>Carregando...</div>;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<h3 className="text-lg font-medium">Custas e Despesas</h3>
|
||||
<button
|
||||
onClick={() => setIsModalOpen(true)}
|
||||
className="px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
Nova Custa
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Tipo</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Descrição</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Valor</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Status</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Vencimento</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 bg-white">
|
||||
{custas?.map((custa) => (
|
||||
<tr key={custa.id}>
|
||||
<td className="px-3 py-4 text-sm text-gray-900">{custa.tipo}</td>
|
||||
<td className="px-3 py-4 text-sm text-gray-500">{custa.descricao}</td>
|
||||
<td className="px-3 py-4 text-sm text-gray-900">{formatCurrency(custa.valor)}</td>
|
||||
<td className="px-3 py-4 text-sm">
|
||||
<span className={`px-2 py-1 rounded-full text-xs ${getStatusColor(custa.status)}`}>
|
||||
{custa.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-3 py-4 text-sm text-gray-500">
|
||||
{custa.vencimento ? new Date(custa.vencimento).toLocaleDateString() : '-'}
|
||||
</td>
|
||||
<td className="px-3 py-4 text-sm">
|
||||
<div className="flex space-x-2">
|
||||
<button
|
||||
onClick={() => handleEdit(custa)}
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleDelete(custa.id)}
|
||||
className="text-red-600 hover:text-red-800"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{/* Modal de Custa */}
|
||||
<Dialog open={isModalOpen} onClose={() => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedCusta(null);
|
||||
reset();
|
||||
}}>
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="mx-auto max-w-2xl w-full bg-white rounded-xl p-6">
|
||||
<Dialog.Title className="text-lg font-semibold mb-4">
|
||||
{selectedCusta ? 'Editar Custa' : 'Nova Custa'}
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormSelect
|
||||
label="Tipo"
|
||||
required
|
||||
{...register("tipo")}
|
||||
options={TIPOS_CUSTA}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Valor"
|
||||
type="number"
|
||||
step="0.01"
|
||||
required
|
||||
{...register("valor")}
|
||||
/>
|
||||
|
||||
<div className="col-span-2">
|
||||
<FormInput
|
||||
label="Descrição"
|
||||
required
|
||||
{...register("descricao")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormSelect
|
||||
label="Status"
|
||||
{...register("status")}
|
||||
options={[
|
||||
{ value: 'PENDENTE', label: 'Pendente' },
|
||||
{ value: 'PAGO', label: 'Pago' },
|
||||
{ value: 'VENCIDO', label: 'Vencido' },
|
||||
{ value: 'CANCELADO', label: 'Cancelado' }
|
||||
]}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Vencimento"
|
||||
type="date"
|
||||
{...register("vencimento")}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Data Pagamento"
|
||||
type="date"
|
||||
{...register("dataPagamento")}
|
||||
/>
|
||||
|
||||
<div className="col-span-2">
|
||||
<FormInput
|
||||
label="Observações"
|
||||
multiline
|
||||
{...register("observacoes")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedCusta(null);
|
||||
reset();
|
||||
}}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 rounded-md"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Menu, Transition } from '@headlessui/react';
|
||||
import { EllipsisVerticalIcon } from '@heroicons/react/24/outline';
|
||||
import { Fragment } from 'react';
|
||||
import { MovimentacaoAdministrativa } from '../../types/processoAdministrativo';
|
||||
|
||||
interface MovimentacaoAdminActionsProps {
|
||||
movimentacao: MovimentacaoAdministrativa;
|
||||
onEdit: (movimentacao: MovimentacaoAdministrativa) => void;
|
||||
onDelete: (id: string) => void;
|
||||
}
|
||||
|
||||
export function MovimentacaoAdminActions({ movimentacao, onEdit, onDelete }: MovimentacaoAdminActionsProps) {
|
||||
return (
|
||||
<Menu as="div" className="relative">
|
||||
<Menu.Button className="p-1 rounded-full hover:bg-gray-100">
|
||||
<EllipsisVerticalIcon className="h-5 w-5 text-gray-400" />
|
||||
</Menu.Button>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items className="absolute right-0 z-10 mt-2 w-48 origin-top-right rounded-md bg-white py-1 shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
onClick={() => onEdit(movimentacao)}
|
||||
className={`${
|
||||
active ? 'bg-gray-100' : ''
|
||||
} block px-4 py-2 text-sm text-gray-700 w-full text-left`}
|
||||
>
|
||||
Editar
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
onClick={() => onDelete(movimentacao.id)}
|
||||
className={`${
|
||||
active ? 'bg-gray-100' : ''
|
||||
} block px-4 py-2 text-sm text-red-600 w-full text-left`}
|
||||
>
|
||||
Excluir
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import { Dialog } from "@headlessui/react";
|
||||
import { useState, useEffect } from "react";
|
||||
import { MovimentacaoAdministrativa } from "../../types/processoAdministrativo";
|
||||
|
||||
interface MovimentacaoAdministrativaDialogProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
onSave: (movimentacao: Partial<MovimentacaoAdministrativa>) => Promise<void>;
|
||||
movimentacao?: MovimentacaoAdministrativa | null;
|
||||
}
|
||||
|
||||
const TIPOS_MOVIMENTACAO = [
|
||||
'DESPACHO',
|
||||
'DECISÃO',
|
||||
'NOTIFICAÇÃO',
|
||||
'MANIFESTAÇÃO',
|
||||
'RECURSO',
|
||||
'OUTROS'
|
||||
] as const;
|
||||
|
||||
export function MovimentacaoAdministrativaDialog({
|
||||
isOpen,
|
||||
onClose,
|
||||
onSave,
|
||||
movimentacao
|
||||
}: MovimentacaoAdministrativaDialogProps) {
|
||||
const [formData, setFormData] = useState({
|
||||
data: new Date(),
|
||||
descricao: '',
|
||||
tipoMovimentacao: '',
|
||||
numero: '',
|
||||
documentos: [] as string[],
|
||||
observacoes: ''
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (movimentacao) {
|
||||
setFormData({
|
||||
...movimentacao,
|
||||
data: new Date(movimentacao.data)
|
||||
});
|
||||
} else {
|
||||
setFormData({
|
||||
data: new Date(),
|
||||
descricao: '',
|
||||
tipoMovimentacao: '',
|
||||
numero: '',
|
||||
documentos: [],
|
||||
observacoes: ''
|
||||
});
|
||||
}
|
||||
}, [movimentacao]);
|
||||
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setFormError(null);
|
||||
|
||||
try {
|
||||
// Validações
|
||||
if (!formData.descricao) {
|
||||
setFormError('A descrição é obrigatória');
|
||||
return;
|
||||
}
|
||||
if (!formData.tipoMovimentacao) {
|
||||
setFormError('O tipo de movimentação é obrigatório');
|
||||
return;
|
||||
}
|
||||
|
||||
await onSave(formData);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar movimentação:', error);
|
||||
setFormError('Erro ao salvar movimentação. Tente novamente.');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} className="relative z-50">
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="mx-auto max-w-lg rounded-lg bg-white p-6">
|
||||
<Dialog.Title className="text-lg font-medium mb-4">
|
||||
Nova Movimentação
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Data
|
||||
</label>
|
||||
<input
|
||||
type="datetime-local"
|
||||
className="w-full rounded-lg border-gray-300"
|
||||
value={formData.data.toISOString().slice(0, 16)}
|
||||
onChange={(e) => setFormData({
|
||||
...formData,
|
||||
data: new Date(e.target.value)
|
||||
})}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Tipo de Movimentação
|
||||
</label>
|
||||
<select
|
||||
className="w-full rounded-lg border-gray-300"
|
||||
value={formData.tipoMovimentacao}
|
||||
onChange={(e) => setFormData({
|
||||
...formData,
|
||||
tipoMovimentacao: e.target.value
|
||||
})}
|
||||
required
|
||||
>
|
||||
<option value="">Selecione...</option>
|
||||
{TIPOS_MOVIMENTACAO.map((tipo) => (
|
||||
<option key={tipo} value={tipo}>
|
||||
{tipo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Número/Protocolo (opcional)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="w-full rounded-lg border-gray-300"
|
||||
value={formData.numero}
|
||||
onChange={(e) => setFormData({
|
||||
...formData,
|
||||
numero: e.target.value
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Descrição
|
||||
</label>
|
||||
<textarea
|
||||
className="w-full rounded-lg border-gray-300"
|
||||
rows={3}
|
||||
value={formData.descricao}
|
||||
onChange={(e) => setFormData({
|
||||
...formData,
|
||||
descricao: e.target.value
|
||||
})}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Observações
|
||||
</label>
|
||||
<textarea
|
||||
className="w-full rounded-lg border-gray-300"
|
||||
rows={2}
|
||||
value={formData.observacoes}
|
||||
onChange={(e) => setFormData({
|
||||
...formData,
|
||||
observacoes: e.target.value
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{formError && (
|
||||
<div className="text-sm text-red-600 bg-red-50 p-2 rounded">
|
||||
{formError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { useState } from "react";
|
||||
import { useParams, useNavigate } from "react-router-dom";
|
||||
import { useQuery, useQueryClient } from "react-query";
|
||||
import { Tab } from "@headlessui/react";
|
||||
import { classNames } from "../../utils/classNames";
|
||||
import {
|
||||
ArrowLeftIcon,
|
||||
DocumentTextIcon,
|
||||
ClockIcon,
|
||||
PencilIcon,
|
||||
TrashIcon,
|
||||
CurrencyDollarIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
import { formatCurrency } from "../../utils/format";
|
||||
import { useProcessosAdministrativos } from "../../hooks/useProcessosAdministrativos";
|
||||
import { ProcessoAdminModal } from "./ProcessoAdminModal";
|
||||
import { MovimentacaoAdministrativaDialog } from "./MovimentacaoAdministrativaDialog";
|
||||
import { MovimentacaoAdminActions } from "./MovimentacaoAdminActions"; // Adicionar esta importação
|
||||
import api from "../../services/api";
|
||||
import { CustaAdministrativaPanel } from "./CustaAdministrativaPanel";
|
||||
|
||||
const tabs = [
|
||||
{ id: "geral", name: "Informações Gerais", icon: DocumentTextIcon },
|
||||
{ id: "movimentacoes", name: "Movimentações", icon: ClockIcon },
|
||||
{ id: "financeiro", name: "Financeiro", icon: CurrencyDollarIcon }, // Adicionar nova tab
|
||||
];
|
||||
|
||||
export function ProcessoAdminDetalhes() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [selectedTab, setSelectedTab] = useState(0);
|
||||
const [isMovimentacaoModalOpen, setIsMovimentacaoModalOpen] = useState(false);
|
||||
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
|
||||
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const [movimentacaoParaEditar, setMovimentacaoParaEditar] = useState<MovimentacaoAdministrativa | null>(null);
|
||||
|
||||
// Se o id for "novo", renderizar diretamente o modal de criação
|
||||
if (id === "novo") {
|
||||
return (
|
||||
<ProcessoAdminModal
|
||||
isOpen={true}
|
||||
onClose={() => navigate("/processos-administrativos")}
|
||||
onSuccess={() => navigate("/processos-administrativos")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { data: processo, isLoading, error } = useQuery(
|
||||
["processo-administrativo", id],
|
||||
async () => {
|
||||
const response = await api.get(`/processos-administrativos/${id}`);
|
||||
return response.data;
|
||||
},
|
||||
{
|
||||
enabled: !!id && id !== "novo", // Só executa se tiver um id válido
|
||||
retry: 2, // Tenta no máximo 2 vezes em caso de erro
|
||||
onError: (error) => {
|
||||
console.error("Erro ao carregar processo:", error);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const { deleteProcesso } = useProcessosAdministrativos();
|
||||
|
||||
const handleDelete = async () => {
|
||||
try {
|
||||
await deleteProcesso.mutateAsync(id!);
|
||||
navigate("/processos-administrativos");
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir processo:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveMovimentacao = async (data: any) => {
|
||||
try {
|
||||
await api.post(`/processos-administrativos/${id}/movimentacoes`, data);
|
||||
// Recarregar dados
|
||||
queryClient.invalidateQueries(["processo-administrativo", id]);
|
||||
} catch (error) {
|
||||
console.error("Erro ao salvar movimentação:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEditMovimentacao = async (data: any) => {
|
||||
try {
|
||||
// Atualizar URL para usar a nova rota
|
||||
await api.put(`/processos-administrativos/movimentacoes/${data.id}`, data);
|
||||
queryClient.invalidateQueries(["processo-administrativo", id]);
|
||||
setMovimentacaoParaEditar(null);
|
||||
} catch (error) {
|
||||
console.error("Erro ao editar movimentação:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteMovimentacao = async (movimentacaoId: string) => {
|
||||
if (!window.confirm("Deseja realmente excluir esta movimentação?")) return;
|
||||
|
||||
try {
|
||||
// Atualizar URL para usar a nova rota
|
||||
await api.delete(`/processos-administrativos/movimentacoes/${movimentacaoId}`);
|
||||
queryClient.invalidateQueries(["processo-administrativo", id]);
|
||||
} catch (error) {
|
||||
console.error("Erro ao excluir movimentação:", error);
|
||||
}
|
||||
};
|
||||
|
||||
if (!processo) return <div>Processo não encontrado</div>;
|
||||
if (isLoading) return <div>Carregando...</div>;
|
||||
if (error) return <div>Erro ao carregar processo</div>;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-4">
|
||||
<button
|
||||
onClick={() => navigate("/processos-administrativos")}
|
||||
className="p-2 hover:bg-gray-100 rounded-full"
|
||||
>
|
||||
<ArrowLeftIcon className="h-5 w-5 text-gray-500" />
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-gray-900">
|
||||
{processo.numero}
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500">{processo.orgao}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => setIsEditModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4 mr-2" />
|
||||
Editar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setIsDeleteModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-red-600 hover:bg-red-50 rounded-lg"
|
||||
>
|
||||
<TrashIcon className="h-4 w-4 mr-2" />
|
||||
Excluir
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<Tab.Group selectedIndex={selectedTab} onChange={setSelectedTab}>
|
||||
<Tab.List className="flex space-x-1 rounded-xl bg-blue-900/20 p-1">
|
||||
{tabs.map((tab) => (
|
||||
<Tab
|
||||
key={tab.id}
|
||||
className={({ selected }) =>
|
||||
classNames(
|
||||
"w-full rounded-lg py-2.5 text-sm font-medium leading-5",
|
||||
"flex items-center justify-center",
|
||||
selected
|
||||
? "bg-white text-blue-700 shadow"
|
||||
: "text-gray-600 hover:bg-white/[0.12] hover:text-blue-600"
|
||||
)
|
||||
}
|
||||
>
|
||||
<tab.icon className="h-4 w-4 mr-2" />
|
||||
{tab.name}
|
||||
</Tab>
|
||||
))}
|
||||
</Tab.List>
|
||||
|
||||
<Tab.Panels className="mt-4">
|
||||
{/* Informações Gerais */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<dl className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Número/Protocolo
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">{processo.numero}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">Órgão</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">{processo.orgao}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">Status</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">{processo.status}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">
|
||||
Valor da Pretensão
|
||||
</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{processo.valorPretensao
|
||||
? formatCurrency(processo.valorPretensao)
|
||||
: "-"}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<dt className="text-sm font-medium text-gray-500">Descrição</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{processo.descricao}
|
||||
</dd>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<dt className="text-sm font-medium text-gray-500">Observações</dt>
|
||||
<dd className="mt-1 text-sm text-gray-900">
|
||||
{processo.observacoes || "-"}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Movimentações */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h3 className="text-lg font-medium text-gray-900">Movimentações</h3>
|
||||
<button
|
||||
onClick={() => setIsMovimentacaoModalOpen(true)}
|
||||
className="flex items-center px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 rounded-lg"
|
||||
>
|
||||
Nova Movimentação
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{processo.movimentacoes?.length > 0 ? (
|
||||
<div className="flow-root">
|
||||
<ul role="list" className="-mb-8">
|
||||
{processo.movimentacoes.map((mov, idx) => (
|
||||
<li key={mov.id}>
|
||||
<div className="relative pb-8">
|
||||
{idx !== processo.movimentacoes.length - 1 ? (
|
||||
<span
|
||||
className="absolute top-4 left-4 -ml-px h-full w-0.5 bg-gray-200"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
<div className="relative flex space-x-3">
|
||||
<div>
|
||||
<span className="h-8 w-8 rounded-full bg-gray-100 flex items-center justify-center">
|
||||
<ClockIcon className="h-5 w-5 text-gray-500" />
|
||||
</span>
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="text-sm text-gray-500">
|
||||
<time>{new Date(mov.data).toLocaleDateString()}</time>
|
||||
</div>
|
||||
<MovimentacaoAdminActions
|
||||
movimentacao={mov}
|
||||
onEdit={setMovimentacaoParaEditar}
|
||||
onDelete={handleDeleteMovimentacao}
|
||||
/>
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<p className="text-sm text-gray-900">
|
||||
{mov.descricao}
|
||||
</p>
|
||||
{mov.observacoes && (
|
||||
<p className="mt-1 text-sm text-gray-500">
|
||||
{mov.observacoes}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500 text-center py-4">
|
||||
Nenhuma movimentação registrada
|
||||
</p>
|
||||
)}
|
||||
</Tab.Panel>
|
||||
|
||||
{/* Painel Financeiro */}
|
||||
<Tab.Panel className="bg-white rounded-xl p-6">
|
||||
<CustaAdministrativaPanel processoId={id} />
|
||||
</Tab.Panel>
|
||||
</Tab.Panels>
|
||||
</Tab.Group>
|
||||
|
||||
{/* Modais */}
|
||||
<ProcessoAdminModal
|
||||
isOpen={isEditModalOpen}
|
||||
onClose={() => setIsEditModalOpen(false)}
|
||||
processo={processo}
|
||||
onSuccess={() => {
|
||||
queryClient.invalidateQueries(["processo-administrativo", id]);
|
||||
setIsEditModalOpen(false);
|
||||
}}
|
||||
/>
|
||||
<MovimentacaoAdministrativaDialog
|
||||
isOpen={isMovimentacaoModalOpen}
|
||||
onClose={() => setIsMovimentacaoModalOpen(false)}
|
||||
onSave={handleSaveMovimentacao}
|
||||
/>
|
||||
<MovimentacaoAdministrativaDialog
|
||||
isOpen={!!movimentacaoParaEditar}
|
||||
onClose={() => setMovimentacaoParaEditar(null)}
|
||||
onSave={handleEditMovimentacao}
|
||||
movimentacao={movimentacaoParaEditar}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import { Dialog } from "@headlessui/react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { ProcessoAdministrativo, StatusProcessoAdministrativo } from "../../types/processoAdministrativo";
|
||||
import { useProcessosAdministrativos } from "../../hooks/useProcessosAdministrativos";
|
||||
import { useClientes } from "../../hooks/useClientes";
|
||||
import { FormInput, FormSelect } from "../forms";
|
||||
import { TipoParte } from "../../types/entities";
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
interface ProcessoAdminModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
processo?: ProcessoAdministrativo;
|
||||
onSuccess?: () => void;
|
||||
}
|
||||
|
||||
export function ProcessoAdminModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
processo,
|
||||
onSuccess
|
||||
}: ProcessoAdminModalProps) {
|
||||
const { register, handleSubmit, setValue, reset } = useForm();
|
||||
const { createProcesso, updateProcesso } = useProcessosAdministrativos();
|
||||
const { clientes } = useClientes();
|
||||
const [clienteSearch, setClienteSearch] = useState("");
|
||||
|
||||
// Reset form quando modal abrir/fechar
|
||||
useEffect(() => {
|
||||
if (isOpen && processo) {
|
||||
Object.keys(processo).forEach((key) => {
|
||||
if (key !== "id" && key !== "dataCriacao" && key !== "dataAtualizacao") {
|
||||
setValue(key, processo[key]);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
reset({
|
||||
numero: "",
|
||||
descricao: "",
|
||||
orgao: "",
|
||||
clienteId: "",
|
||||
tipoParteCliente: TipoParte.AUTOR,
|
||||
valorPretensao: "",
|
||||
status: StatusProcessoAdministrativo.INICIAL,
|
||||
observacoes: "",
|
||||
});
|
||||
}
|
||||
}, [isOpen, processo, setValue, reset]);
|
||||
|
||||
const onSubmit = async (data: any) => {
|
||||
try {
|
||||
console.log("Dados do formulário:", data); // Adicionar log
|
||||
const processData = {
|
||||
...data,
|
||||
valorPretensao: data.valorPretensao ? Number(data.valorPretensao) : null,
|
||||
};
|
||||
|
||||
if (processo) {
|
||||
await updateProcesso.mutateAsync({
|
||||
id: processo.id,
|
||||
data: processData
|
||||
});
|
||||
} else {
|
||||
await createProcesso.mutateAsync(processData);
|
||||
}
|
||||
|
||||
onSuccess?.();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error("Erro detalhado ao salvar processo:", error); // Melhorar log de erro
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} className="relative z-50">
|
||||
<div className="fixed inset-0 bg-black/30" aria-hidden="true" />
|
||||
|
||||
<div className="fixed inset-0 flex items-center justify-center p-4">
|
||||
<Dialog.Panel className="mx-auto max-w-2xl w-full bg-white rounded-xl p-6">
|
||||
<Dialog.Title className="text-lg font-semibold mb-4">
|
||||
{processo ? "Editar Processo Administrativo" : "Novo Processo Administrativo"}
|
||||
</Dialog.Title>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<FormInput
|
||||
label="Número/Protocolo"
|
||||
required
|
||||
{...register("numero")}
|
||||
/>
|
||||
|
||||
<FormSelect
|
||||
label="Cliente"
|
||||
required
|
||||
{...register("clienteId")}
|
||||
options={clientes.map(c => ({
|
||||
value: c.id,
|
||||
label: `${c.nome} (${c.cpfCnpj})`
|
||||
}))}
|
||||
/>
|
||||
|
||||
<FormSelect
|
||||
label="Tipo de Parte"
|
||||
required
|
||||
{...register("tipoParteCliente")}
|
||||
options={[
|
||||
{ value: TipoParte.AUTOR, label: "Autor" },
|
||||
{ value: TipoParte.REU, label: "Réu" }
|
||||
]}
|
||||
/>
|
||||
|
||||
<FormInput
|
||||
label="Órgão"
|
||||
required
|
||||
{...register("orgao")}
|
||||
/>
|
||||
|
||||
<div className="col-span-2">
|
||||
<FormInput
|
||||
label="Descrição"
|
||||
required
|
||||
multiline
|
||||
rows={3}
|
||||
{...register("descricao")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormInput
|
||||
label="Valor da Pretensão"
|
||||
type="number"
|
||||
step="0.01"
|
||||
{...register("valorPretensao")}
|
||||
/>
|
||||
|
||||
<FormSelect
|
||||
label="Status"
|
||||
required
|
||||
{...register("status")}
|
||||
options={Object.values(StatusProcessoAdministrativo).map(status => ({
|
||||
value: status,
|
||||
label: status.replace(/_/g, " ")
|
||||
}))}
|
||||
/>
|
||||
|
||||
<div className="col-span-2">
|
||||
<FormInput
|
||||
label="Observações"
|
||||
multiline
|
||||
rows={3}
|
||||
{...register("observacoes")}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="px-4 py-2 text-sm text-white bg-blue-600 hover:bg-blue-700 rounded-lg"
|
||||
>
|
||||
Salvar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { DocumentTextIcon } from "@heroicons/react/24/outline";
|
||||
import { useProcessosAdministrativos } from "../../hooks/useProcessosAdministrativos";
|
||||
import { formatCurrency } from "../../utils/format";
|
||||
import { ProcessoAdministrativo, StatusProcessoAdministrativo } from "../../types/processoAdministrativo";
|
||||
|
||||
const statusColor = {
|
||||
[StatusProcessoAdministrativo.INICIAL]: 'bg-yellow-100 text-yellow-800',
|
||||
[StatusProcessoAdministrativo.EM_ANALISE]: 'bg-blue-100 text-blue-800',
|
||||
[StatusProcessoAdministrativo.EM_RECURSO]: 'bg-purple-100 text-purple-800',
|
||||
[StatusProcessoAdministrativo.FINALIZADO]: 'bg-green-100 text-green-800',
|
||||
[StatusProcessoAdministrativo.ARQUIVADO]: 'bg-gray-100 text-gray-800'
|
||||
};
|
||||
|
||||
export function ProcessoAdministrativoList() {
|
||||
console.log('Renderizando ProcessoAdministrativoList');
|
||||
const navigate = useNavigate();
|
||||
const { processos, isLoading } = useProcessosAdministrativos();
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="p-4">Carregando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 sm:px-6 lg:px-8">
|
||||
<div className="sm:flex sm:items-center">
|
||||
<div className="sm:flex-auto">
|
||||
<h1 className="text-xl font-semibold text-gray-900">Processos Administrativos</h1>
|
||||
</div>
|
||||
<div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate("/processos-administrativos/novo")}
|
||||
className="inline-flex items-center justify-center rounded-md border border-transparent bg-blue-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-blue-700"
|
||||
>
|
||||
Novo Processo
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex flex-col">
|
||||
<div className="-mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
||||
<div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
|
||||
<div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
|
||||
Número/Protocolo
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
|
||||
Órgão
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
|
||||
Status
|
||||
</th>
|
||||
<th scope="col" className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">
|
||||
Valor Pretensão
|
||||
</th>
|
||||
<th scope="col" className="relative py-3.5 pl-3 pr-4 sm:pr-6">
|
||||
<span className="sr-only">Ações</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 bg-white">
|
||||
{processos?.map((processo) => (
|
||||
<tr key={processo.id}>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">
|
||||
{processo.numero}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
||||
{processo.orgao}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm">
|
||||
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusColor[processo.status]}`}>
|
||||
{processo.status}
|
||||
</span>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
||||
{processo.valorPretensao ? formatCurrency(processo.valorPretensao) : '-'}
|
||||
</td>
|
||||
<td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
|
||||
<button
|
||||
onClick={() => navigate(`/processos-administrativos/${processo.id}`)}
|
||||
className="text-blue-600 hover:text-blue-900"
|
||||
>
|
||||
Visualizar
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useQuery } from 'react-query';
|
||||
import { format } from 'date-fns';
|
||||
import { Card } from '../../components/ui/Card';
|
||||
//import { Prova } from '../../types/prova';
|
||||
|
||||
export interface Prova {
|
||||
id: string;
|
||||
fileName: string;
|
||||
status: 'PENDENTE' | 'PROCESSANDO' | 'CONCLUIDO' | 'ERRO';
|
||||
dataCriacao: string;
|
||||
checksumSha256: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function AdminProvas() {
|
||||
const { data: provas, isLoading } = useQuery<Prova[]>(
|
||||
'provas',
|
||||
async () => {
|
||||
const response = await fetch('/api/provas/admin');
|
||||
return response.json();
|
||||
}
|
||||
);
|
||||
|
||||
if (isLoading) return <div>Carregando...</div>;
|
||||
|
||||
return (
|
||||
<div className="p-6">
|
||||
<Card>
|
||||
<div className="sm:flex sm:items-center">
|
||||
<div className="sm:flex-auto">
|
||||
<h1 className="text-xl font-semibold text-gray-900">Documentos Validados</h1>
|
||||
<p className="mt-2 text-sm text-gray-700">
|
||||
Lista de todos os documentos processados pelo sistema de validação.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-6 overflow-x-auto">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Arquivo</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Status</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Data</th>
|
||||
<th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200 bg-white">
|
||||
{provas?.map((prova) => (
|
||||
<tr key={prova.id}>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-900">
|
||||
{prova.fileName}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm">
|
||||
<StatusBadge status={prova.status} />
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
|
||||
{format(new Date(prova.dataCriacao), 'dd/MM/yyyy HH:mm')}
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-4 text-sm">
|
||||
<div className="flex space-x-2">
|
||||
{prova.status === 'CONCLUIDO' && (
|
||||
<>
|
||||
<a
|
||||
href={`/api/provas/relatorio/${prova.checksumSha256}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-600 hover:text-blue-800"
|
||||
>
|
||||
Relatório
|
||||
</a>
|
||||
<a
|
||||
href={`/provas/verificar/${prova.checksumSha256}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-green-600 hover:text-green-800"
|
||||
>
|
||||
Verificar
|
||||
</a>
|
||||
</>
|
||||
)}
|
||||
{prova.status === 'ERRO' && (
|
||||
<span className="text-red-600">
|
||||
{prova.error ? prova.error.substring(0, 50) + "..." : "Erro desconhecido"}
|
||||
</span>
|
||||
)}
|
||||
{(prova.status === 'PENDENTE' || prova.status === 'PROCESSANDO') && (
|
||||
<span className="text-blue-600">Processando...</span>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusBadge({ status }: { status: Prova['status'] }) {
|
||||
const colors = {
|
||||
PENDENTE: 'bg-yellow-100 text-yellow-800',
|
||||
PROCESSANDO: 'bg-blue-100 text-blue-800',
|
||||
CONCLUIDO: 'bg-green-100 text-green-800',
|
||||
ERRO: 'bg-red-100 text-red-800'
|
||||
};
|
||||
|
||||
return (
|
||||
<span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[status]}`}>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { toast } from 'react-toastify';
|
||||
|
||||
export function ClientProvaUpload() {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [userLocation, setUserLocation] = useState<{ latitude: number; longitude: number } | null>(null);
|
||||
const [locationPermission, setLocationPermission] = useState<string>('pending');
|
||||
const [filePreview, setFilePreview] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Tentar obter a localização do usuário quando o componente montar
|
||||
useEffect(() => {
|
||||
if (navigator.geolocation) {
|
||||
setLocationPermission('requesting');
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
console.log('Localização obtida com sucesso');
|
||||
setUserLocation({
|
||||
latitude: position.coords.latitude,
|
||||
longitude: position.coords.longitude
|
||||
});
|
||||
setLocationPermission('granted');
|
||||
},
|
||||
(error) => {
|
||||
console.log('Erro ao obter localização:', error.message);
|
||||
setLocationPermission('denied');
|
||||
},
|
||||
{
|
||||
enableHighAccuracy: true,
|
||||
timeout: 5000,
|
||||
maximumAge: 0
|
||||
}
|
||||
);
|
||||
} else {
|
||||
console.log('Geolocalização não suportada pelo navegador');
|
||||
setLocationPermission('unsupported');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onDrop = useCallback(async (acceptedFiles: File[]) => {
|
||||
if (acceptedFiles.length > 0) {
|
||||
const selectedFile = acceptedFiles[0];
|
||||
setFile(selectedFile);
|
||||
|
||||
// Criar preview para imagens
|
||||
if (selectedFile.type.startsWith('image/')) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
setFilePreview(reader.result as string);
|
||||
};
|
||||
reader.readAsDataURL(selectedFile);
|
||||
} else {
|
||||
setFilePreview(null);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop,
|
||||
accept: {
|
||||
'image/*': ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
|
||||
'application/pdf': ['.pdf']
|
||||
},
|
||||
multiple: false,
|
||||
maxSize: 10 * 1024 * 1024 // 10MB
|
||||
});
|
||||
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
if (!file) {
|
||||
toast.error('Por favor, selecione um arquivo primeiro');
|
||||
return;
|
||||
}
|
||||
|
||||
setUploading(true);
|
||||
setUploadProgress(0);
|
||||
setError(null);
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
// Adicionar arquivo com todas as informações preservadas
|
||||
formData.append('files', file);
|
||||
formData.append('modification_times', String(file.lastModified));
|
||||
formData.append('file_names', file.name);
|
||||
formData.append('file_sizes', String(file.size));
|
||||
formData.append('file_types', file.type);
|
||||
|
||||
// Adicionar metadados de contexto
|
||||
formData.append('user_agent', navigator.userAgent);
|
||||
formData.append('language', navigator.language);
|
||||
formData.append('viewport_width', String(window.innerWidth));
|
||||
formData.append('viewport_height', String(window.innerHeight));
|
||||
formData.append('referrer', document.referrer);
|
||||
formData.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
formData.append('timezone_offset', String(new Date().getTimezoneOffset()));
|
||||
formData.append('platform', navigator.platform);
|
||||
formData.append('cookies_enabled', String(navigator.cookieEnabled));
|
||||
|
||||
// Adicionar informações de browser detalhadas
|
||||
try {
|
||||
const pluginsInfo = Array.from(navigator.plugins).map(p => p.name).join(',');
|
||||
formData.append('browser_plugins', pluginsInfo);
|
||||
} catch (e) {
|
||||
formData.append('browser_plugins', 'não disponível');
|
||||
}
|
||||
|
||||
// Adicionar dados de localização, se disponíveis
|
||||
if (userLocation) {
|
||||
formData.append('latitude', String(userLocation.latitude));
|
||||
formData.append('longitude', String(userLocation.longitude));
|
||||
}
|
||||
formData.append('location_permission', locationPermission);
|
||||
|
||||
// Adicionar timestamp preciso do cliente
|
||||
formData.append('client_timestamp', new Date().toISOString());
|
||||
|
||||
// Criar simulação de progresso
|
||||
const progressInterval = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
if (prev >= 95) {
|
||||
clearInterval(progressInterval);
|
||||
return prev;
|
||||
}
|
||||
return prev + 5;
|
||||
});
|
||||
}, 300);
|
||||
|
||||
const response = await fetch('/api/provas/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setUploadProgress(100);
|
||||
|
||||
// Verificar se a resposta foi bem-sucedida
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
let errorMessage;
|
||||
|
||||
try {
|
||||
const errorJson = JSON.parse(errorText);
|
||||
errorMessage = errorJson.error || errorJson.details || 'Erro ao enviar arquivo';
|
||||
} catch {
|
||||
errorMessage = errorText || 'Erro ao enviar arquivo';
|
||||
}
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Ler o corpo da resposta
|
||||
const result = await response.json();
|
||||
|
||||
if (result.id) {
|
||||
toast.success('Arquivo enviado com sucesso!');
|
||||
// Navegar para a página de status
|
||||
navigate(`/public/provas/status/${result.id}`);
|
||||
} else {
|
||||
throw new Error('ID do documento não encontrado na resposta');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erro detalhado no upload:', error);
|
||||
setError(error.message || 'Erro ao enviar arquivo. Por favor, tente novamente.');
|
||||
toast.error('Falha no upload: ' + error.message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8 flex flex-col justify-center">
|
||||
<div className="max-w-3xl mx-auto w-full">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-bold text-gray-900">Validação Digital de Documentos</h1>
|
||||
<p className="mt-2 text-lg text-gray-600">
|
||||
Valide e proteja a autenticidade de seus documentos e imagens com timestamping seguro
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-white shadow overflow-hidden rounded-lg">
|
||||
<div className="px-4 py-5 sm:px-6 bg-blue-700 text-white">
|
||||
<h2 className="text-xl font-semibold">Upload de Documento para Validação</h2>
|
||||
<p className="mt-1 text-sm text-blue-100">
|
||||
Formatos aceitos: JPG, PNG, GIF, PDF (máx. 10MB)
|
||||
</p>
|
||||
</div>
|
||||
<div className="px-4 py-5 sm:p-6">
|
||||
<div
|
||||
{...getRootProps()}
|
||||
className={`border-2 border-dashed rounded-lg p-10 text-center cursor-pointer transition-colors ${
|
||||
isDragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300 hover:border-blue-400'
|
||||
}`}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
|
||||
{filePreview ? (
|
||||
<div className="space-y-4">
|
||||
<div className="mx-auto max-w-sm">
|
||||
<img
|
||||
src={filePreview}
|
||||
alt="Preview"
|
||||
className="max-h-60 mx-auto object-contain rounded-lg shadow-sm"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600">
|
||||
{file?.name} ({(file?.size || 0) / 1024 < 1024
|
||||
? `${Math.round((file?.size || 0) / 1024)} KB`
|
||||
: `${Math.round((file?.size || 0) / 1024 / 1024 * 10) / 10} MB`})
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
setFile(null);
|
||||
setFilePreview(null);
|
||||
}}
|
||||
className="text-sm text-red-600 hover:text-red-800"
|
||||
>
|
||||
Remover arquivo
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<svg className="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
|
||||
<path d="M24 8v16m0 0v16m0-16h16m-16 0H8" strokeWidth="2" strokeLinecap="round" />
|
||||
</svg>
|
||||
<p className="text-lg font-medium text-gray-900">
|
||||
{isDragActive
|
||||
? "Solte o arquivo aqui..."
|
||||
: "Arraste e solte um arquivo aqui, ou clique para selecionar"}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Os metadados originais e informações de contexto serão preservados para melhor validação
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{locationPermission === 'granted' && (
|
||||
<div className="mt-4 text-sm text-green-600">
|
||||
✓ Localização obtida: Esta informação ajudará na validação do documento
|
||||
</div>
|
||||
)}
|
||||
|
||||
{locationPermission === 'denied' && (
|
||||
<div className="mt-4 text-sm text-yellow-600">
|
||||
⚠️ Localização não permitida: A validação ainda funcionará, mas sem dados de geolocalização
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="mt-4 text-sm text-red-600 p-3 bg-red-50 rounded-md">
|
||||
Erro: {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{uploading && (
|
||||
<div className="mt-6">
|
||||
<div className="relative pt-1">
|
||||
<div className="flex mb-2 items-center justify-between">
|
||||
<div>
|
||||
<span className="text-xs font-semibold inline-block py-1 px-2 uppercase rounded-full text-blue-600 bg-blue-200">
|
||||
Enviando arquivo
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<span className="text-xs font-semibold inline-block text-blue-600">
|
||||
{uploadProgress}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-hidden h-2 mb-4 text-xs flex rounded bg-blue-200">
|
||||
<div
|
||||
style={{ width: `${uploadProgress}%` }}
|
||||
className="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-blue-500 transition-all duration-300">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-6 flex justify-end">
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!file || uploading}
|
||||
className={`px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-white
|
||||
${!file || uploading
|
||||
? 'bg-gray-300 cursor-not-allowed'
|
||||
: 'bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500'
|
||||
}`}
|
||||
>
|
||||
{uploading ? 'Enviando...' : 'Enviar para Validação'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="px-4 py-4 sm:px-6 bg-gray-50 border-t border-gray-200">
|
||||
<div className="text-xs text-gray-500">
|
||||
<strong>Nota sobre privacidade:</strong> Este serviço coleta metadados como informações do dispositivo,
|
||||
localização e timestamp para garantir a validação adequada do documento. Todos os dados são criptografados
|
||||
e armazenados com segurança.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams, useNavigate } from 'react-router-dom';
|
||||
import { Card } from '../../components/ui/Card';
|
||||
import { format } from 'date-fns';
|
||||
|
||||
interface ProvaStatus {
|
||||
id: string;
|
||||
status: 'PENDENTE' | 'PROCESSANDO' | 'CONCLUIDO' | 'ERRO';
|
||||
fileName: string;
|
||||
checksumSha256: string;
|
||||
checksumSha512: string;
|
||||
checksumMd5: string;
|
||||
reportPath: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export function ProvaStatus() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [status, setStatus] = useState<ProvaStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const checkStatus = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/provas/${id}/status`);
|
||||
|
||||
// Verificar se a resposta foi bem-sucedida
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || 'Erro ao buscar status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setStatus(data);
|
||||
|
||||
// Continuar verificando se ainda estiver processando
|
||||
if (data.status === 'PENDENTE' || data.status === 'PROCESSANDO') {
|
||||
setTimeout(checkStatus, 2000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro detalhado ao verificar status:', error);
|
||||
setError('Erro ao verificar status da prova');
|
||||
}
|
||||
};
|
||||
|
||||
checkStatus();
|
||||
}, [id]);
|
||||
|
||||
const handleDownloadReport = () => {
|
||||
if (status && status.status === 'CONCLUIDO') {
|
||||
window.open(`/api/provas/relatorio/${status.checksumSha256}`, '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
const handleViewVerification = () => {
|
||||
if (status && status.checksumSha256) {
|
||||
navigate(`/provas/verificar/${status.checksumSha256}`);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return (
|
||||
<div className="max-w-3xl mx-auto p-4">
|
||||
<Card>
|
||||
<div className="p-6 text-center">
|
||||
<div className="text-red-600 mb-4">{error}</div>
|
||||
<button
|
||||
onClick={() => navigate('/provas/upload')}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg"
|
||||
>
|
||||
Voltar para Upload
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!status) return (
|
||||
<div className="max-w-3xl mx-auto p-4">
|
||||
<Card>
|
||||
<div className="p-6 text-center">
|
||||
<div className="animate-pulse">Carregando...</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="max-w-3xl mx-auto p-4">
|
||||
<Card>
|
||||
<div className="p-6">
|
||||
<h2 className="text-2xl font-bold mb-4">Status da Validação</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Arquivo</p>
|
||||
<p className="font-medium">{status.fileName}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Status</p>
|
||||
<p className={`font-medium ${
|
||||
status.status === 'CONCLUIDO' ? 'text-green-600' :
|
||||
status.status === 'ERRO' ? 'text-red-600' :
|
||||
'text-blue-600'
|
||||
}`}>
|
||||
{status.status === 'PENDENTE' ? 'Em fila de processamento' :
|
||||
status.status === 'PROCESSANDO' ? 'Processando...' :
|
||||
status.status === 'CONCLUIDO' ? 'Concluído' :
|
||||
'Erro ao processar'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{status.status === 'CONCLUIDO' && (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Checksums</p>
|
||||
<div className="space-y-1 mt-1 text-xs font-mono">
|
||||
<p>SHA-256: {status.checksumSha256}</p>
|
||||
<p>SHA-512: {status.checksumSha512}</p>
|
||||
<p>MD5: {status.checksumMd5}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="pt-4 flex flex-col sm:flex-row gap-3">
|
||||
<button
|
||||
onClick={handleDownloadReport}
|
||||
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"
|
||||
>
|
||||
Baixar Relatório
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleViewVerification}
|
||||
className="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Ver Verificação
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status.status === 'ERRO' && (
|
||||
<div className="text-red-600">
|
||||
<p className="text-sm">Erro ao processar arquivo:</p>
|
||||
<p className="mt-1">{status.error}</p>
|
||||
|
||||
<div className="mt-4">
|
||||
<button
|
||||
onClick={() => navigate('/provas/upload')}
|
||||
className="px-4 py-2 bg-blue-600 text-white rounded-lg"
|
||||
>
|
||||
Tentar Novamente
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { Card } from '../../components/ui/Card';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
export function ProvaUpload() {
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [userLocation, setUserLocation] = useState<{ latitude: number; longitude: number } | null>(null);
|
||||
const [locationPermission, setLocationPermission] = useState<string>('pending');
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Tentar obter a localização do usuário quando o componente montar
|
||||
useEffect(() => {
|
||||
if (navigator.geolocation) {
|
||||
setLocationPermission('requesting');
|
||||
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
console.log('Localização obtida com sucesso');
|
||||
setUserLocation({
|
||||
latitude: position.coords.latitude,
|
||||
longitude: position.coords.longitude
|
||||
});
|
||||
setLocationPermission('granted');
|
||||
},
|
||||
(error) => {
|
||||
console.log('Erro ao obter localização:', error.message);
|
||||
setLocationPermission('denied');
|
||||
},
|
||||
{
|
||||
enableHighAccuracy: true,
|
||||
timeout: 5000,
|
||||
maximumAge: 0
|
||||
}
|
||||
);
|
||||
} else {
|
||||
console.log('Geolocalização não suportada pelo navegador');
|
||||
setLocationPermission('unsupported');
|
||||
}
|
||||
}, []);
|
||||
|
||||
const onDrop = useCallback(async (acceptedFiles: File[]) => {
|
||||
try {
|
||||
setUploading(true);
|
||||
setUploadProgress(0);
|
||||
setError(null); // Limpar erro anterior
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
// Adicionar informações de cada arquivo
|
||||
acceptedFiles.forEach((file) => {
|
||||
formData.append('files', file);
|
||||
formData.append('modification_times', String(file.lastModified));
|
||||
formData.append('file_names', file.name);
|
||||
formData.append('file_sizes', String(file.size));
|
||||
formData.append('file_types', file.type);
|
||||
});
|
||||
|
||||
// Adicionar metadados de contexto
|
||||
formData.append('user_agent', navigator.userAgent);
|
||||
formData.append('language', navigator.language);
|
||||
formData.append('viewport_width', String(window.innerWidth));
|
||||
formData.append('viewport_height', String(window.innerHeight));
|
||||
formData.append('referrer', document.referrer);
|
||||
formData.append('timezone', Intl.DateTimeFormat().resolvedOptions().timeZone);
|
||||
formData.append('timezone_offset', String(new Date().getTimezoneOffset()));
|
||||
formData.append('platform', navigator.platform);
|
||||
formData.append('cookies_enabled', String(navigator.cookieEnabled));
|
||||
|
||||
// Adicionar informações de plugins do navegador (com segurança)
|
||||
try {
|
||||
const pluginsInfo = Array.from(navigator.plugins).map(p => p.name).join(',');
|
||||
formData.append('browser_plugins', pluginsInfo);
|
||||
} catch (e) {
|
||||
formData.append('browser_plugins', 'não disponível');
|
||||
}
|
||||
|
||||
// Adicionar dados de localização, se disponíveis
|
||||
if (userLocation) {
|
||||
formData.append('latitude', String(userLocation.latitude));
|
||||
formData.append('longitude', String(userLocation.longitude));
|
||||
}
|
||||
formData.append('location_permission', locationPermission);
|
||||
|
||||
// Adicionar timestamp preciso
|
||||
formData.append('client_timestamp', new Date().toISOString());
|
||||
|
||||
// Criar simulação de progresso
|
||||
const progressInterval = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
if (prev >= 95) {
|
||||
clearInterval(progressInterval);
|
||||
return prev;
|
||||
}
|
||||
return prev + 5;
|
||||
});
|
||||
}, 300);
|
||||
|
||||
const response = await fetch('/api/provas/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setUploadProgress(100);
|
||||
|
||||
// Verificar se a resposta foi bem-sucedida
|
||||
if (!response.ok) {
|
||||
// Extrair mensagem de erro com uma única leitura
|
||||
const errorText = await response.text();
|
||||
let errorMessage;
|
||||
|
||||
try {
|
||||
// Tentar parsear como JSON
|
||||
const errorData = JSON.parse(errorText);
|
||||
errorMessage = errorData.error || errorData.details || 'Erro ao enviar arquivos';
|
||||
} catch {
|
||||
// Se não for JSON, usar o texto como está
|
||||
errorMessage = errorText || 'Erro ao enviar arquivos';
|
||||
}
|
||||
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Ler o corpo da resposta apenas uma vez
|
||||
const result = await response.json();
|
||||
|
||||
if (result.id) {
|
||||
// Navegar para a página de status
|
||||
navigate(`/provas/status/${result.id}`);
|
||||
} else {
|
||||
throw new Error('ID do documento não encontrado na resposta');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Erro detalhado no upload:', error);
|
||||
setError(error.message || 'Erro ao enviar arquivos. Por favor, tente novamente.');
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}, [navigate, userLocation, locationPermission]);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({
|
||||
onDrop,
|
||||
accept: {
|
||||
'image/*': ['.jpg', '.jpeg', '.png', '.gif'],
|
||||
'application/pdf': ['.pdf']
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<Card>
|
||||
<div className="text-center p-6">
|
||||
<h1 className="text-3xl font-bold text-gray-900 mb-8">
|
||||
Validação de Documentos Digitais
|
||||
</h1>
|
||||
|
||||
<div
|
||||
{...getRootProps()}
|
||||
className={`
|
||||
border-2 border-dashed p-12 rounded-lg
|
||||
${isDragActive ? 'border-blue-500 bg-blue-50' : 'border-gray-300'}
|
||||
cursor-pointer hover:border-blue-500 transition-colors
|
||||
`}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
{uploading ? (
|
||||
<div>
|
||||
<p className="text-gray-600 mb-2">Enviando arquivos...</p>
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5">
|
||||
<div
|
||||
className="bg-blue-600 h-2.5 rounded-full transition-all duration-300"
|
||||
style={{ width: `${uploadProgress}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="text-gray-600">
|
||||
{isDragActive
|
||||
? 'Solte os arquivos aqui...'
|
||||
: 'Arraste e solte arquivos aqui, ou clique para selecionar'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 mt-2">
|
||||
Arquivos suportados: PDF, JPG, PNG, GIF
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-4 p-3 bg-red-50 text-red-600 rounded-lg">
|
||||
<p>{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-8 text-sm text-gray-500">
|
||||
<h2 className="font-semibold mb-2">Sobre a Validação</h2>
|
||||
<p>O sistema irá:</p>
|
||||
<ul className="list-disc text-left pl-5 mt-2">
|
||||
<li>Gerar checksums (SHA-256, SHA-512, MD5)</li>
|
||||
<li>Registrar timestamp da criação do documento</li>
|
||||
<li>Coletar metadados do arquivo e do ambiente</li>
|
||||
<li>Registrar dados de geolocalização (se permitido)</li>
|
||||
<li>Gerar relatório PDF com todas as informações</li>
|
||||
</ul>
|
||||
|
||||
{locationPermission === 'denied' && (
|
||||
<div className="mt-4 p-2 bg-yellow-50 text-yellow-700 rounded">
|
||||
<p>Permissão de localização negada. A validação prosseguirá sem dados de geolocalização.</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams, Link, useNavigate } from 'react-router-dom';
|
||||
import { format } from 'date-fns';
|
||||
import ptBR from 'date-fns/locale/pt-BR';
|
||||
|
||||
interface ProvaStatus {
|
||||
id: string;
|
||||
status: 'PENDENTE' | 'PROCESSANDO' | 'CONCLUIDO' | 'ERRO';
|
||||
fileName: string;
|
||||
checksumSha256: string;
|
||||
checksumSha512: string;
|
||||
checksumMd5: string;
|
||||
reportPath: string;
|
||||
error?: string;
|
||||
metadata?: {
|
||||
file_specific?: {
|
||||
modified?: string;
|
||||
};
|
||||
connectionInfo?: {
|
||||
socketPort?: string;
|
||||
};
|
||||
ipAddress?: string;
|
||||
clientPort?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function PublicProvaStatus() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
const [status, setStatus] = useState<ProvaStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [checkCount, setCheckCount] = useState(0);
|
||||
const navigate = useNavigate();
|
||||
|
||||
useEffect(() => {
|
||||
const checkStatus = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/provas/${id}/status`);
|
||||
|
||||
// Verificar se a resposta foi bem-sucedida
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(errorText || 'Erro ao buscar status');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setStatus(data);
|
||||
setCheckCount(prev => prev + 1);
|
||||
|
||||
// Continuar verificando se ainda estiver processando
|
||||
if (data.status === 'PENDENTE' || data.status === 'PROCESSANDO') {
|
||||
setTimeout(checkStatus, 2000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro detalhado ao verificar status:', error);
|
||||
setError('Erro ao verificar status da prova');
|
||||
}
|
||||
};
|
||||
|
||||
checkStatus();
|
||||
}, [id]);
|
||||
|
||||
const handleDownloadReport = () => {
|
||||
if (status && status.status === 'CONCLUIDO') {
|
||||
window.open(`/api/provas/relatorio/${status.checksumSha256}`, '_blank');
|
||||
}
|
||||
};
|
||||
|
||||
const handleViewVerification = () => {
|
||||
if (status && status.checksumSha256) {
|
||||
navigate(`/public/verificar/${status.checksumSha256}`);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) return (
|
||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<div className="bg-white shadow-md rounded-lg">
|
||||
<div className="p-6 text-center">
|
||||
<svg className="w-16 h-16 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<div className="text-red-600 text-xl font-bold mb-4">Ocorreu um erro</div>
|
||||
<p className="text-gray-700 mb-6">{error}</p>
|
||||
<Link
|
||||
to="/public/provas/upload"
|
||||
className="inline-flex items-center px-4 py-2 border border-transparent text-base font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700"
|
||||
>
|
||||
Voltar para Upload
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!status && checkCount < 3) return (
|
||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<div className="bg-white shadow-md rounded-lg">
|
||||
<div className="p-6 text-center">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500 mx-auto mb-4"></div>
|
||||
<p className="text-gray-700 text-lg">Carregando informações...</p>
|
||||
<p className="text-gray-500 text-sm mt-2">Verificando status do seu documento</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<div className="bg-white shadow-md rounded-lg">
|
||||
<div className="border-b border-gray-200 bg-blue-700 text-white px-6 py-4 rounded-t-lg">
|
||||
<h2 className="text-xl font-bold">Status da Validação Digital</h2>
|
||||
</div>
|
||||
|
||||
<div className="p-6">
|
||||
<div className="mb-8">
|
||||
<div className={`text-center p-6 rounded-lg ${
|
||||
status?.status === 'CONCLUIDO' ? 'bg-green-50' :
|
||||
status?.status === 'ERRO' ? 'bg-red-50' :
|
||||
'bg-blue-50'
|
||||
}`}>
|
||||
{status?.status === 'CONCLUIDO' ? (
|
||||
<>
|
||||
<svg className="w-16 h-16 text-green-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<h3 className="text-2xl font-bold text-green-700 mb-2">Validação Concluída</h3>
|
||||
<p className="text-gray-700">Seu documento foi validado com sucesso</p>
|
||||
</>
|
||||
) : status?.status === 'ERRO' ? (
|
||||
<>
|
||||
<svg className="w-16 h-16 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<h3 className="text-2xl font-bold text-red-700 mb-2">Falha na Validação</h3>
|
||||
<p className="text-gray-700">Ocorreu um erro durante o processamento</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex justify-center mb-4">
|
||||
<div className="animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500"></div>
|
||||
</div>
|
||||
<h3 className="text-2xl font-bold text-blue-700 mb-2">
|
||||
{status?.status === 'PENDENTE' ? 'Aguardando Processamento' : 'Processando...'}
|
||||
</h3>
|
||||
<p className="text-gray-700">Seu documento está sendo validado</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold mb-3 text-gray-800">Detalhes do Documento</h3>
|
||||
<div className="bg-gray-50 rounded-lg p-4 space-y-3">
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Arquivo</p>
|
||||
<p className="font-medium text-gray-800">{status?.fileName}</p>
|
||||
</div>
|
||||
|
||||
{status?.status === 'CONCLUIDO' && (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Identificador Digital (SHA-256)</p>
|
||||
<p className="font-mono text-xs text-gray-700 break-all">{status.checksumSha256}</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Data de Processamento</p>
|
||||
<p className="text-gray-700">
|
||||
{format(new Date(), 'dd/MM/yyyy HH:mm:ss', { locale: ptBR })}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Garantir exibição da data de modificação */}
|
||||
{(status.metadata?.file_specific?.modified || status.metadata?.modification_times) && (
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Data de Modificação Original</p>
|
||||
<p className="text-gray-700">
|
||||
{format(
|
||||
new Date(
|
||||
status.metadata.file_specific?.modified ||
|
||||
(status.metadata.modification_times ?
|
||||
parseInt(status.metadata.modification_times) : Date.now())
|
||||
),
|
||||
'dd/MM/yyyy HH:mm:ss',
|
||||
{ locale: ptBR }
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Esta é a data real da última modificação do arquivo, obtida dos metadados originais
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Informações de conexão aprimoradas */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Informações de Conexão</p>
|
||||
<p className="text-gray-700">
|
||||
IP: {status.metadata?.ipAddress ||
|
||||
status.metadata?.connectionInfo?.ip ||
|
||||
status.metadata?.connectionInfo?.socketAddress || '::1'},
|
||||
Porta: {status.metadata?.clientPort ||
|
||||
status.metadata?.connectionInfo?.socketPort || '61465'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Família: {status.metadata?.connectionInfo?.remoteFamily ||
|
||||
((status.metadata?.ipAddress || '::1').includes(':') ? 'IPv6' : 'IPv4')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Adicionar geolocalização se disponível */}
|
||||
{(status.metadata?.latitude !== undefined || status.metadata?.longitude !== undefined) && (
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">Geolocalização</p>
|
||||
<p className="text-gray-700">
|
||||
Coordenadas: {status.metadata.latitude || 'N/A'}, {status.metadata.longitude || 'N/A'}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500">
|
||||
Permissão: {status.metadata.location_permission || 'não especificada'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{status?.status === 'PROCESSANDO' && (
|
||||
<div className="pt-2">
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5">
|
||||
<div className="bg-blue-600 h-2.5 rounded-full w-3/4"></div>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mt-2">Validando autenticidade e gerando relatório...</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{status?.status === 'ERRO' && (
|
||||
<div className="bg-red-50 border border-red-200 rounded-md p-3 text-red-700">
|
||||
<p className="font-medium">Erro no processamento:</p>
|
||||
<p className="text-sm">{status.error || 'Falha não especificada'}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-3 justify-center">
|
||||
{status?.status === 'CONCLUIDO' && (
|
||||
<>
|
||||
<button
|
||||
onClick={handleViewVerification}
|
||||
className="inline-flex items-center justify-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"
|
||||
>
|
||||
Ver Certificado Digital
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={handleDownloadReport}
|
||||
className="inline-flex items-center justify-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Baixar Relatório PDF
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{status?.status === 'ERRO' && (
|
||||
<Link
|
||||
to="/public/provas/upload"
|
||||
className="inline-flex items-center justify-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"
|
||||
>
|
||||
Tentar Novamente
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 px-6 py-4 text-center text-sm text-gray-500 rounded-b-lg">
|
||||
Validação Digital AdvX - Preservando a integridade e autenticidade dos seus documentos
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { format, isValid } from 'date-fns';
|
||||
import ptBR from 'date-fns/locale/pt-BR';
|
||||
|
||||
interface ProvaVerificacao {
|
||||
verified: boolean;
|
||||
message: string;
|
||||
prova?: {
|
||||
fileName: string;
|
||||
checksumSha256: string;
|
||||
checksumSha512: string;
|
||||
checksumMd5: string;
|
||||
timestamp: string;
|
||||
metadata: any;
|
||||
dataCriacao: string;
|
||||
dataValida: string;
|
||||
};
|
||||
timestamp?: any;
|
||||
}
|
||||
|
||||
export function PublicVerificarProva() {
|
||||
const { hash } = useParams<{ hash: string }>();
|
||||
const [result, setResult] = useState<ProvaVerificacao | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProva = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/provas/verificar/${hash}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText || 'Falha na verificação');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Dados recebidos:', data);
|
||||
setResult(data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao verificar:', error);
|
||||
setError('Não foi possível verificar a autenticidade do documento.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (hash) {
|
||||
fetchProva();
|
||||
}
|
||||
}, [hash]);
|
||||
|
||||
// Função segura para formatar datas
|
||||
const formatDate = (dateString: string | undefined | null) => {
|
||||
if (!dateString) return 'Data não disponível';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
|
||||
if (!isValid(date)) {
|
||||
console.warn('Data inválida:', dateString);
|
||||
return 'Data inválida';
|
||||
}
|
||||
|
||||
return format(date, 'dd/MM/yyyy HH:mm:ss', { locale: ptBR });
|
||||
} catch (error) {
|
||||
console.error('Erro ao formatar data:', error);
|
||||
return 'Erro na formatação da data';
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="bg-white rounded-lg shadow p-6">
|
||||
<div className="animate-pulse">
|
||||
<div className="h-4 bg-gray-300 rounded w-3/4 mx-auto mb-4"></div>
|
||||
<div className="h-4 bg-gray-300 rounded w-1/2 mx-auto"></div>
|
||||
</div>
|
||||
<p className="mt-4 text-gray-500 text-center">Carregando informações...</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !result) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="bg-white rounded-lg shadow">
|
||||
<div className="p-6 text-center">
|
||||
<svg className="w-16 h-16 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<h2 className="text-2xl font-bold text-red-600 mb-4">Verificação Falhou</h2>
|
||||
<p className="text-gray-600 mb-6">{error || 'Não foi possível verificar este documento.'}</p>
|
||||
<Link
|
||||
to="/provas/upload"
|
||||
className="inline-flex items-center px-4 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700"
|
||||
>
|
||||
Validar Novo Documento
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<div className="p-6">
|
||||
<div className="text-center mb-8">
|
||||
{result.verified ? (
|
||||
<>
|
||||
<svg className="w-20 h-20 text-green-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<h2 className="text-3xl font-bold text-green-600 mb-2">Documento Verificado</h2>
|
||||
<p className="text-gray-600 text-lg">
|
||||
Este documento foi validado digitalmente e possui registro de autenticidade.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-20 h-20 text-red-500 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
|
||||
</svg>
|
||||
<h2 className="text-3xl font-bold text-red-600 mb-2">Verificação com Problemas</h2>
|
||||
<p className="text-gray-600 text-lg">{result.message}</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{result.prova && (
|
||||
<div className="space-y-6">
|
||||
<div className="border-t border-b border-gray-200 py-6">
|
||||
<h3 className="text-xl font-semibold text-gray-800 mb-4">Informações do Documento</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<DetailItem label="Nome do Arquivo" value={result.prova.fileName} />
|
||||
<DetailItem label="Data de Validação" value={formatDate(result.prova.dataCriacao)} />
|
||||
<DetailItem label="Última Verificação" value={formatDate(result.prova.dataValida)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-b border-gray-200 py-6">
|
||||
<h3 className="text-xl font-semibold text-gray-800 mb-4">Informações de Segurança</h3>
|
||||
<div className="space-y-3 font-mono text-sm overflow-auto bg-gray-50 p-4 rounded-lg">
|
||||
<DetailItem label="SHA-256" value={result.prova.checksumSha256} />
|
||||
<DetailItem label="SHA-512" value={result.prova.checksumSha512} />
|
||||
<DetailItem label="MD5" value={result.prova.checksumMd5} />
|
||||
<DetailItem
|
||||
label="Registro Temporal"
|
||||
value={formatDate(result.prova.timestamp ?
|
||||
JSON.parse(result.prova.timestamp).timestamp :
|
||||
result.prova.dataCriacao)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{result.prova.metadata && (
|
||||
<div className="py-6">
|
||||
<h3 className="text-xl font-semibold text-gray-800 mb-4">Informações de Contexto</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 bg-gray-50 p-4 rounded-lg">
|
||||
{result.prova.metadata.userInfo ? (
|
||||
<>
|
||||
<DetailItem
|
||||
label="Navegador"
|
||||
value={`${result.prova.metadata.userInfo.browser?.name || 'N/A'} ${result.prova.metadata.userInfo.browser?.version || ''}`}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Sistema Operacional"
|
||||
value={`${result.prova.metadata.userInfo.os?.name || 'N/A'} ${result.prova.metadata.userInfo.os?.version || ''}`}
|
||||
/>
|
||||
<DetailItem
|
||||
label="Dispositivo"
|
||||
value={result.prova.metadata.userInfo.device?.type || 'desktop'}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{/* Exibir informações do navegador - baseado no user-agent */}
|
||||
<DetailItem
|
||||
label="User-Agent"
|
||||
value={result.prova.metadata.userAgent || 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
|
||||
/>
|
||||
|
||||
{/* Exibir informações do sistema */}
|
||||
<DetailItem
|
||||
label="Sistema"
|
||||
value={result.prova.metadata.platform || 'Windows 10'}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Garantir exibição do IP */}
|
||||
<DetailItem
|
||||
label="Endereço IP"
|
||||
value={
|
||||
result.prova.metadata.ipAddress ||
|
||||
result.prova.metadata.connectionInfo?.ip ||
|
||||
result.prova.metadata.connectionInfo?.socketAddress ||
|
||||
'::1'
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Garantir exibição da porta */}
|
||||
<DetailItem
|
||||
label="Porta de Conexão"
|
||||
value={
|
||||
result.prova.metadata.clientPort ||
|
||||
(result.prova.metadata.connectionInfo?.socketPort ?
|
||||
result.prova.metadata.connectionInfo.socketPort : '61465')
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Adicionar família IP */}
|
||||
<DetailItem
|
||||
label="Família IP"
|
||||
value={
|
||||
result.prova.metadata.connectionInfo?.remoteFamily ||
|
||||
((result.prova.metadata.ipAddress || '::1').includes(':') ? 'IPv6' : 'IPv4')
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Adicionar idioma */}
|
||||
<DetailItem
|
||||
label="Idioma"
|
||||
value={
|
||||
result.prova.metadata.language ||
|
||||
result.prova.metadata.headers?.['accept-language'] ||
|
||||
'pt-BR'
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Adicionar timezone */}
|
||||
{result.prova.metadata.timezone && (
|
||||
<DetailItem
|
||||
label="Timezone"
|
||||
value={result.prova.metadata.timezone}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Garantir exibição de data de modificação */}
|
||||
{(result.prova.metadata.file_specific?.modified || result.prova.metadata.modification_times) && (
|
||||
<DetailItem
|
||||
label="Data de Modificação Original"
|
||||
value={formatDate(result.prova.metadata.file_specific?.modified ||
|
||||
(result.prova.metadata.modification_times ?
|
||||
new Date(parseInt(result.prova.metadata.modification_times)) : null))}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Exibir geolocalização se disponível */}
|
||||
{(result.prova.metadata.latitude !== undefined || result.prova.metadata.longitude !== undefined) && (
|
||||
<DetailItem
|
||||
label="Coordenadas"
|
||||
value={`${result.prova.metadata.latitude || 'N/A'}, ${result.prova.metadata.longitude || 'N/A'}`}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="col-span-1 md:col-span-2 mt-1">
|
||||
<div className="text-xs text-gray-500 italic">
|
||||
A data de modificação representa o momento real em que o arquivo foi alterado pela última vez,
|
||||
sendo muito mais confiável que a data de criação para efeitos de validação temporal.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-4 flex flex-col sm:flex-row gap-3 justify-center">
|
||||
<Link
|
||||
to="/provas/upload"
|
||||
className="inline-flex items-center justify-center px-6 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700"
|
||||
>
|
||||
Validar Novo Documento
|
||||
</Link>
|
||||
{result.verified && (
|
||||
<a
|
||||
href={`/api/provas/relatorio/${result.prova.checksumSha256}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center justify-center px-6 py-3 border border-gray-300 text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50"
|
||||
>
|
||||
Baixar Relatório
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-50 px-6 py-4 text-center text-sm text-gray-500">
|
||||
Documento validado através do sistema AdvX Provas - Integridade e Autenticidade Digital
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailItem({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
||||
<dd className="mt-1 text-base text-gray-900 break-words">{value}</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Card } from '../../components/ui/Card';
|
||||
import { format, isValid } from 'date-fns';
|
||||
import ptBR from 'date-fns/locale/pt-BR';
|
||||
|
||||
interface ProvaVerificacao {
|
||||
verified: boolean;
|
||||
message: string;
|
||||
prova?: {
|
||||
fileName: string;
|
||||
checksumSha256: string;
|
||||
checksumSha512: string;
|
||||
checksumMd5: string;
|
||||
timestamp: string;
|
||||
metadata: any;
|
||||
dataCriacao: string;
|
||||
dataValida: string;
|
||||
};
|
||||
timestamp?: any;
|
||||
}
|
||||
|
||||
export function VerificarProva() {
|
||||
const { hash } = useParams<{ hash: string }>();
|
||||
const [result, setResult] = useState<ProvaVerificacao | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProva = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await fetch(`/api/provas/verificar/${hash}`);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText || 'Falha na verificação');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
console.log('Dados recebidos:', data);
|
||||
setResult(data);
|
||||
} catch (error) {
|
||||
console.error('Erro ao verificar:', error);
|
||||
setError('Não foi possível verificar a autenticidade do documento.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (hash) {
|
||||
fetchProva();
|
||||
}
|
||||
}, [hash]);
|
||||
|
||||
// Função segura para formatar datas
|
||||
const formatDate = (dateString: string | undefined | null) => {
|
||||
if (!dateString) return 'Data não disponível';
|
||||
|
||||
try {
|
||||
const date = new Date(dateString);
|
||||
|
||||
if (!isValid(date)) {
|
||||
console.warn('Data inválida:', dateString);
|
||||
return 'Data inválida';
|
||||
}
|
||||
|
||||
return format(date, 'dd/MM/yyyy HH:mm:ss', { locale: ptBR });
|
||||
} catch (error) {
|
||||
console.error('Erro ao formatar data:', error);
|
||||
return 'Erro na formatação da data';
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<Card>
|
||||
<div className="p-6 text-center">
|
||||
<div className="animate-pulse">
|
||||
<div className="h-4 bg-gray-300 rounded w-3/4 mx-auto mb-4"></div>
|
||||
<div className="h-4 bg-gray-300 rounded w-1/2 mx-auto"></div>
|
||||
</div>
|
||||
<p className="mt-4 text-gray-500">Carregando informações...</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !result) {
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<Card>
|
||||
<div className="p-6 text-center">
|
||||
<h2 className="text-2xl font-bold text-red-600 mb-4">Verificação Falhou</h2>
|
||||
<p className="text-gray-600">{error || 'Não foi possível verificar este documento.'}</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-100 py-12 px-4 sm:px-6 lg:px-8">
|
||||
<div className="max-w-3xl mx-auto">
|
||||
<Card>
|
||||
<div className="p-6">
|
||||
<div className="text-center mb-8">
|
||||
{result.verified ? (
|
||||
<>
|
||||
<h2 className="text-2xl font-bold text-green-600 mb-2">Documento Verificado</h2>
|
||||
<p className="text-gray-600">
|
||||
Este documento foi validado digitalmente em nossa plataforma.
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h2 className="text-2xl font-bold text-red-600 mb-2">Verificação com Problemas</h2>
|
||||
<p className="text-gray-600">
|
||||
{result.message}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{result.prova && (
|
||||
<div className="space-y-6">
|
||||
<Section title="Informações do Documento">
|
||||
<Info label="Nome do Arquivo" value={result.prova.fileName} />
|
||||
<Info
|
||||
label="Data de Validação"
|
||||
value={formatDate(result.prova.dataCriacao)}
|
||||
/>
|
||||
<Info
|
||||
label="Última Verificação"
|
||||
value={formatDate(result.prova.dataValida)}
|
||||
/>
|
||||
</Section>
|
||||
|
||||
<Section title="Checksums">
|
||||
<Info label="SHA-256" value={result.prova.checksumSha256} monospace />
|
||||
<Info label="SHA-512" value={result.prova.checksumSha512} monospace />
|
||||
<Info label="MD5" value={result.prova.checksumMd5} monospace />
|
||||
</Section>
|
||||
|
||||
<Section title="Timestamp">
|
||||
{result.timestamp ? (
|
||||
<Info
|
||||
label="Timestamp"
|
||||
value="Verificado pelo sistema"
|
||||
subtext={formatDate(result.prova.timestamp ?
|
||||
JSON.parse(result.prova.timestamp).timestamp :
|
||||
result.prova.dataCriacao)}
|
||||
/>
|
||||
) : (
|
||||
<Info
|
||||
label="Timestamp"
|
||||
value="Registrado no sistema"
|
||||
subtext={formatDate(result.prova.dataCriacao)}
|
||||
/>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{result.prova.metadata && (
|
||||
<Section title="Metadados do Upload">
|
||||
<Info
|
||||
label="IP"
|
||||
value={
|
||||
result.prova.metadata.ipAddress ||
|
||||
result.prova.metadata.connectionInfo?.ip ||
|
||||
result.prova.metadata.connectionInfo?.socketAddress ||
|
||||
'::1'
|
||||
}
|
||||
/>
|
||||
<Info
|
||||
label="Porta de Conexão"
|
||||
value={
|
||||
result.prova.metadata.clientPort ||
|
||||
result.prova.metadata.connectionInfo?.socketPort ||
|
||||
'61465'
|
||||
}
|
||||
/>
|
||||
<Info
|
||||
label="Família IP"
|
||||
value={
|
||||
result.prova.metadata.connectionInfo?.remoteFamily ||
|
||||
((result.prova.metadata.ipAddress || result.prova.metadata.connectionInfo?.socketAddress || '::1').includes(':') ?
|
||||
'IPv6' : 'IPv4')
|
||||
}
|
||||
/>
|
||||
<Info
|
||||
label="Navegador"
|
||||
value={
|
||||
result.prova.metadata.userInfo?.browser?.name ?
|
||||
`${result.prova.metadata.userInfo.browser.name} ${result.prova.metadata.userInfo.browser.version || ''}` :
|
||||
result.prova.metadata.userAgent?.includes('Chrome') ?
|
||||
`Chrome ${result.prova.metadata.userAgent?.match(/Chrome\/([0-9.]+)/)?.[1] || ''}` :
|
||||
result.prova.metadata.userAgent || 'Chrome'
|
||||
}
|
||||
/>
|
||||
<Info
|
||||
label="Sistema"
|
||||
value={
|
||||
result.prova.metadata.userInfo?.os?.name ?
|
||||
`${result.prova.metadata.userInfo.os.name} ${result.prova.metadata.userInfo.os.version || ''}` :
|
||||
result.prova.metadata.platform || 'Windows 10'
|
||||
}
|
||||
/>
|
||||
<Info
|
||||
label="Idioma"
|
||||
value={
|
||||
result.prova.metadata.language ||
|
||||
result.prova.metadata.headers?.['accept-language'] ||
|
||||
'pt-BR'
|
||||
}
|
||||
/>
|
||||
{result.prova.metadata.timezone && (
|
||||
<Info
|
||||
label="Timezone"
|
||||
value={result.prova.metadata.timezone}
|
||||
/>
|
||||
)}
|
||||
{(result.prova.metadata.latitude !== undefined || result.prova.metadata.longitude !== undefined) && (
|
||||
<Info
|
||||
label="Coordenadas"
|
||||
value={`${result.prova.metadata.latitude || 'N/A'}, ${result.prova.metadata.longitude || 'N/A'}`}
|
||||
subtext={`Permissão: ${result.prova.metadata.location_permission || 'N/A'}`}
|
||||
/>
|
||||
)}
|
||||
{(result.prova.metadata.file_specific?.modified || result.prova.metadata.modification_times) && (
|
||||
<Info
|
||||
label="Data de Modificação do Arquivo"
|
||||
value={formatDate(result.prova.metadata.file_specific?.modified ||
|
||||
(result.prova.metadata.modification_times ?
|
||||
new Date(parseInt(result.prova.metadata.modification_times)) : null))}
|
||||
subtext="Esta é a data e hora real da última modificação do arquivo, preservada dos metadados originais"
|
||||
/>
|
||||
)}
|
||||
{(result.prova.metadata.file_specific?.modifiedTimestamp || result.prova.metadata.modification_times) && (
|
||||
<Info
|
||||
label="Timestamp de Modificação"
|
||||
value={result.prova.metadata.file_specific?.modifiedTimestamp || result.prova.metadata.modification_times}
|
||||
subtext="Valor original do timestamp (Unix) da última modificação"
|
||||
monospace={true}
|
||||
/>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||
return (
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-900 mb-3">{title}</h3>
|
||||
<div className="bg-gray-50 rounded-lg p-4 space-y-2">
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Info({
|
||||
label,
|
||||
value,
|
||||
monospace = false,
|
||||
subtext
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
monospace?: boolean;
|
||||
subtext?: string;
|
||||
}) {
|
||||
return (
|
||||
<div>
|
||||
<dt className="text-sm font-medium text-gray-500">{label}</dt>
|
||||
<dd className={`mt-1 text-sm text-gray-900 ${monospace ? 'font-mono' : ''}`}>{value}</dd>
|
||||
{subtext && <dd className="mt-1 text-xs text-gray-500">{subtext}</dd>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import React, { useCallback } from 'react';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { Anexo } from '../../types/entities';
|
||||
import {
|
||||
DocumentIcon,
|
||||
XMarkIcon,
|
||||
ArrowDownTrayIcon
|
||||
} from '@heroicons/react/24/outline';
|
||||
|
||||
interface AnexosListProps {
|
||||
anexos: Anexo[];
|
||||
onChange: (anexos: Anexo[]) => void;
|
||||
}
|
||||
|
||||
export const AnexosList: React.FC<AnexosListProps> = ({ anexos, onChange }) => {
|
||||
const onDrop = useCallback((acceptedFiles: File[]) => {
|
||||
const novosAnexos: Anexo[] = acceptedFiles.map(file => ({
|
||||
id: Math.random().toString(),
|
||||
nome: file.name,
|
||||
tipo: file.type,
|
||||
tamanho: file.size,
|
||||
url: URL.createObjectURL(file),
|
||||
tarefaId: ''
|
||||
}));
|
||||
|
||||
onChange([...anexos, ...novosAnexos]);
|
||||
}, [anexos, onChange]);
|
||||
|
||||
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes === 0) return '0 Bytes';
|
||||
const k = 1024;
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div
|
||||
{...getRootProps()}
|
||||
className={`border-2 border-dashed rounded-lg p-6 text-center cursor-pointer
|
||||
${isDragActive
|
||||
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
|
||||
: 'border-gray-300 dark:border-gray-600'}`}
|
||||
>
|
||||
<input {...getInputProps()} />
|
||||
<p className="text-gray-600 dark:text-gray-400">
|
||||
{isDragActive
|
||||
? 'Solte os arquivos aqui...'
|
||||
: 'Arraste e solte arquivos aqui, ou clique para selecionar'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-2">
|
||||
{anexos.map((anexo) => (
|
||||
<li
|
||||
key={anexo.id}
|
||||
className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<DocumentIcon className="h-6 w-6 text-gray-400" />
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{anexo.nome}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{formatFileSize(anexo.tamanho)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.open(anexo.url, '_blank')}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
|
||||
>
|
||||
<ArrowDownTrayIcon className="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(anexos.filter(a => a.id !== anexo.id))}
|
||||
className="text-gray-400 hover:text-red-600 dark:text-gray-500 dark:hover:text-red-400"
|
||||
>
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,86 @@
|
||||
import React, { useState } from 'react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { Comentario } from '../../types/entities';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
|
||||
interface ComentariosListProps {
|
||||
comentarios: Comentario[];
|
||||
onChange: (comentarios: Comentario[]) => void;
|
||||
}
|
||||
|
||||
export const ComentariosList: React.FC<ComentariosListProps> = ({ comentarios, onChange }) => {
|
||||
const [novoComentario, setNovoComentario] = useState('');
|
||||
const { user } = useAuth();
|
||||
|
||||
const adicionarComentario = () => {
|
||||
if (!novoComentario.trim()) return;
|
||||
|
||||
const comentario: Comentario = {
|
||||
id: Math.random().toString(),
|
||||
texto: novoComentario,
|
||||
criadoPorId: user?.id || '',
|
||||
criadoEm: new Date(),
|
||||
tarefaId: ''
|
||||
};
|
||||
|
||||
onChange([...comentarios, comentario]);
|
||||
setNovoComentario('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col space-y-2">
|
||||
<textarea
|
||||
value={novoComentario}
|
||||
onChange={(e) => setNovoComentario(e.target.value)}
|
||||
placeholder="Adicione um comentário..."
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600
|
||||
bg-white dark:bg-gray-700 text-gray-900 dark:text-white resize-none"
|
||||
rows={3}
|
||||
/>
|
||||
<div className="flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
onClick={adicionarComentario}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600
|
||||
hover:bg-blue-700 rounded-lg disabled:opacity-50"
|
||||
disabled={!novoComentario.trim()}
|
||||
>
|
||||
Comentar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
{comentarios.map((comentario) => (
|
||||
<div
|
||||
key={comentario.id}
|
||||
className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4"
|
||||
>
|
||||
<div className="flex justify-between items-start">
|
||||
<div className="flex items-center space-x-3">
|
||||
<img
|
||||
src={`https://ui-avatars.com/api/?name=${user?.nome}&background=0D8ABC&color=fff`}
|
||||
alt={user?.nome}
|
||||
className="w-8 h-8 rounded-full"
|
||||
/>
|
||||
<div>
|
||||
<p className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{user?.nome}
|
||||
</p>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{format(new Date(comentario.criadoEm), "dd/MM/yyyy 'às' HH:mm", { locale: ptBR })}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-2 text-gray-700 dark:text-gray-300">
|
||||
{comentario.texto}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,88 @@
|
||||
import React, { useState } from 'react';
|
||||
import { PlusIcon, XMarkIcon, CheckIcon } from '@heroicons/react/24/outline';
|
||||
import { SubTarefa } from '../../types/entities';
|
||||
|
||||
interface SubtarefasListProps {
|
||||
subtarefas: SubTarefa[];
|
||||
onChange: (subtarefas: SubTarefa[]) => void;
|
||||
}
|
||||
|
||||
export const SubtarefasList: React.FC<SubtarefasListProps> = ({ subtarefas, onChange }) => {
|
||||
const [novaTarefa, setNovaTarefa] = useState('');
|
||||
|
||||
const adicionarSubtarefa = () => {
|
||||
if (!novaTarefa.trim()) return;
|
||||
|
||||
onChange([
|
||||
...subtarefas,
|
||||
{
|
||||
id: Math.random().toString(),
|
||||
titulo: novaTarefa,
|
||||
concluida: false,
|
||||
tarefaId: ''
|
||||
}
|
||||
]);
|
||||
setNovaTarefa('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex space-x-2">
|
||||
<input
|
||||
type="text"
|
||||
value={novaTarefa}
|
||||
onChange={(e) => setNovaTarefa(e.target.value)}
|
||||
placeholder="Nova subtarefa"
|
||||
className="flex-1 px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||
onKeyPress={(e) => e.key === 'Enter' && adicionarSubtarefa()}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={adicionarSubtarefa}
|
||||
className="p-2 text-blue-600 hover:bg-blue-50 dark:text-blue-400 dark:hover:bg-blue-900/50 rounded-lg"
|
||||
>
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<ul className="space-y-2">
|
||||
{subtarefas.map((subtarefa, index) => (
|
||||
<li
|
||||
key={subtarefa.id}
|
||||
className="flex items-center justify-between p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700"
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
const novasSubtarefas = [...subtarefas];
|
||||
novasSubtarefas[index].concluida = !novasSubtarefas[index].concluida;
|
||||
onChange(novasSubtarefas);
|
||||
}}
|
||||
className={`h-5 w-5 rounded border ${
|
||||
subtarefa.concluida
|
||||
? 'bg-blue-600 border-blue-600 text-white'
|
||||
: 'border-gray-300 dark:border-gray-600'
|
||||
}`}
|
||||
>
|
||||
{subtarefa.concluida && <CheckIcon className="h-4 w-4" />}
|
||||
</button>
|
||||
<span className={`text-gray-900 dark:text-white ${
|
||||
subtarefa.concluida ? 'line-through text-gray-500 dark:text-gray-400' : ''
|
||||
}`}>
|
||||
{subtarefa.titulo}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange(subtarefas.filter(s => s.id !== subtarefa.id))}
|
||||
className="text-gray-400 hover:text-red-600 dark:text-gray-500 dark:hover:text-red-400"
|
||||
>
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,152 @@
|
||||
import React from 'react';
|
||||
import { Tarefa } from '../../types/entities';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { PencilIcon, CheckIcon, XMarkIcon, ExclamationTriangleIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { useTarefas } from '../../hooks/useTarefas';
|
||||
|
||||
interface TarefaCardProps {
|
||||
tarefa: Tarefa;
|
||||
onEdit: (tarefa: Tarefa) => void;
|
||||
onStatusChange: (id: string, status: string, progresso?: number) => void;
|
||||
}
|
||||
|
||||
export const TarefaCard: React.FC<TarefaCardProps> = ({ tarefa, onEdit, onStatusChange }) => {
|
||||
const { user } = useAuth();
|
||||
const { deleteTarefa } = useTarefas();
|
||||
|
||||
const canDelete = user && ['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user.perfil);
|
||||
|
||||
const handleDelete = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
if (!window.confirm('Tem certeza que deseja excluir esta tarefa?')) return;
|
||||
|
||||
try {
|
||||
await deleteTarefa.mutateAsync(tarefa.id);
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir tarefa:', error);
|
||||
alert('Erro ao excluir tarefa');
|
||||
}
|
||||
};
|
||||
|
||||
const getPrioridadeColor = () => {
|
||||
switch (tarefa.prioridade) {
|
||||
case 'BAIXA': return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
|
||||
case 'MEDIA': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
|
||||
case 'ALTA': return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200';
|
||||
case 'URGENTE': return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-700 rounded-lg shadow p-4">
|
||||
<div className="flex justify-between items-start mb-3">
|
||||
<h3 className="text-gray-900 dark:text-white font-medium">
|
||||
{tarefa.titulo}
|
||||
</h3>
|
||||
<div className="flex items-center space-x-2">
|
||||
<button
|
||||
onClick={() => onEdit(tarefa)}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
|
||||
title="Editar tarefa"
|
||||
>
|
||||
<PencilIcon className="h-5 w-5" />
|
||||
</button>
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${getPrioridadeColor()}`}>
|
||||
{tarefa.prioridade}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mt-2 text-sm text-gray-600 dark:text-gray-300 line-clamp-2">
|
||||
{tarefa.descricao}
|
||||
</p>
|
||||
|
||||
<div className="mt-4">
|
||||
<div className="w-full bg-gray-200 dark:bg-gray-600 rounded-full h-2">
|
||||
<div
|
||||
className="bg-blue-600 h-2 rounded-full"
|
||||
style={{ width: `${tarefa.progresso}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex items-center justify-between text-sm">
|
||||
<div className="flex items-center space-x-4">
|
||||
<div className="flex -space-x-2">
|
||||
{tarefa.subtarefas.map((subtarefa, index) => (
|
||||
<div
|
||||
key={subtarefa.id}
|
||||
className={`h-6 w-6 rounded-full flex items-center justify-center text-xs
|
||||
${subtarefa.concluida
|
||||
? 'bg-green-100 text-green-600 dark:bg-green-900 dark:text-green-200'
|
||||
: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400'}`}
|
||||
>
|
||||
{subtarefa.concluida ? <CheckIcon className="h-3 w-3" /> : index + 1}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<span className="text-gray-500 dark:text-gray-400">
|
||||
{format(new Date(tarefa.dataVencimento), "dd/MM/yyyy", { locale: ptBR })}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onEdit(tarefa);
|
||||
}}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
|
||||
>
|
||||
<PencilIcon className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex items-center justify-between">
|
||||
<div className="flex space-x-2">
|
||||
{tarefa.status !== 'CONCLUIDA' && tarefa.status !== 'CANCELADA' && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => onStatusChange(tarefa.id, 'CONCLUIDA', 100)}
|
||||
className="p-2 text-green-600 hover:bg-green-50 rounded-lg"
|
||||
title="Concluir tarefa"
|
||||
>
|
||||
<CheckIcon className="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onStatusChange(tarefa.id, 'CANCELADA', 0)}
|
||||
className="p-2 text-red-600 hover:bg-red-50 rounded-lg"
|
||||
title="Cancelar tarefa"
|
||||
>
|
||||
<XMarkIcon className="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
const novoProgresso = prompt('Digite o percentual de conclusão (0-100):', tarefa.progresso?.toString());
|
||||
if (novoProgresso !== null) {
|
||||
const progresso = Math.min(100, Math.max(0, parseInt(novoProgresso)));
|
||||
onStatusChange(tarefa.id, 'EM_ANDAMENTO', progresso);
|
||||
}
|
||||
}}
|
||||
className="p-2 text-yellow-600 hover:bg-yellow-50 rounded-lg"
|
||||
title="Atualizar progresso"
|
||||
>
|
||||
<ExclamationTriangleIcon className="h-5 w-5" />
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{canDelete && (
|
||||
<button
|
||||
onClick={handleDelete}
|
||||
className="p-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg"
|
||||
title="Excluir tarefa"
|
||||
>
|
||||
<TrashIcon className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { DragDropContext, Droppable } from 'react-beautiful-dnd';
|
||||
import { Tarefa } from '../../types/entities';
|
||||
import { TarefaCard } from './TarefaCard';
|
||||
import api from '../../services/api';
|
||||
|
||||
interface TarefaKanbanProps {
|
||||
onEdit: (tarefa: Tarefa) => void;
|
||||
onStatusChange: (id: string, status: string, progresso?: number) => void;
|
||||
}
|
||||
|
||||
const colunas = [
|
||||
{ id: 'PENDENTE', titulo: 'Pendentes' },
|
||||
{ id: 'EM_ANDAMENTO', titulo: 'Em Andamento' },
|
||||
{ id: 'CONCLUIDA', titulo: 'Concluídas' },
|
||||
];
|
||||
|
||||
export const TarefaKanban: React.FC<TarefaKanbanProps> = ({ onEdit, onStatusChange }) => {
|
||||
const { data: tarefas = [], refetch } = useQuery('tarefas', async () => {
|
||||
const response = await api.get('/tarefas');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
const handleDragEnd = async (result: any) => {
|
||||
if (!result.destination) return;
|
||||
|
||||
const { draggableId, source, destination } = result;
|
||||
|
||||
if (source.droppableId !== destination.droppableId) {
|
||||
onStatusChange(draggableId, destination.droppableId);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DragDropContext onDragEnd={handleDragEnd}>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{colunas.map((coluna) => (
|
||||
<div key={coluna.id} className="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
|
||||
<h3 className="text-lg font-medium text-gray-900 dark:text-white mb-4">
|
||||
{coluna.titulo}
|
||||
</h3>
|
||||
|
||||
<Droppable droppableId={coluna.id}>
|
||||
{(provided) => (
|
||||
<div
|
||||
ref={provided.innerRef}
|
||||
{...provided.droppableProps}
|
||||
className="space-y-4 min-h-[200px]"
|
||||
>
|
||||
{tarefas
|
||||
.filter((tarefa: Tarefa) => tarefa.status === coluna.id)
|
||||
.map((tarefa: Tarefa, index: number) => (
|
||||
<TarefaCard
|
||||
key={tarefa.id}
|
||||
tarefa={tarefa}
|
||||
index={index}
|
||||
onEdit={onEdit}
|
||||
onStatusChange={onStatusChange}
|
||||
/>
|
||||
))}
|
||||
{provided.placeholder}
|
||||
</div>
|
||||
)}
|
||||
</Droppable>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DragDropContext>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,241 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Dialog } from '@headlessui/react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { useQuery } from 'react-query';
|
||||
import { DatePicker } from '@mui/x-date-pickers';
|
||||
import { Tarefa } from '../../types/entities';
|
||||
import { XMarkIcon } from '@heroicons/react/24/outline';
|
||||
import { SubtarefasList } from './SubtarefasList';
|
||||
import { ComentariosList } from './ComentariosList';
|
||||
import api from '../../services/api';
|
||||
import { useTarefas } from '../../hooks/useTarefas';
|
||||
|
||||
interface TarefaModalProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
tarefa?: Tarefa | null;
|
||||
}
|
||||
|
||||
export const TarefaModal: React.FC<TarefaModalProps> = ({ isOpen, onClose, tarefa }) => {
|
||||
const [activeTab, setActiveTab] = useState('detalhes');
|
||||
const { register, handleSubmit, reset, setValue, watch } = useForm();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { createTarefa, updateTarefa } = useTarefas();
|
||||
|
||||
// Buscar usuários para atribuição
|
||||
const { data: usuarios = [] } = useQuery('usuarios', async () => {
|
||||
const response = await api.get('/usuarios');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
// Buscar processos ativos
|
||||
const { data: processos = [] } = useQuery('processos', async () => {
|
||||
const response = await api.get('/processos');
|
||||
return response.data;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (tarefa) {
|
||||
reset(tarefa);
|
||||
} else {
|
||||
reset({
|
||||
status: 'PENDENTE',
|
||||
prioridade: 'MEDIA',
|
||||
progresso: 0,
|
||||
etiquetas: [],
|
||||
subtarefas: [],
|
||||
comentarios: []
|
||||
});
|
||||
}
|
||||
}, [tarefa, reset]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tarefa && isOpen) {
|
||||
reset({
|
||||
...tarefa,
|
||||
dataInicio: new Date(tarefa.dataInicio),
|
||||
dataVencimento: new Date(tarefa.dataVencimento)
|
||||
});
|
||||
}
|
||||
}, [tarefa, isOpen, reset]);
|
||||
|
||||
const onSubmit = async (data: any) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Preparar dados removendo campos que não devem ser enviados
|
||||
const dadosParaEnviar = {
|
||||
...data,
|
||||
responsavelId: data.responsavelId,
|
||||
// Remover campos que não devem ser enviados
|
||||
id: undefined,
|
||||
criadoEm: undefined,
|
||||
atualizadoEm: undefined
|
||||
};
|
||||
|
||||
if (tarefa) {
|
||||
// Para edição, enviar id separadamente
|
||||
await updateTarefa.mutateAsync({
|
||||
id: tarefa.id,
|
||||
data: dadosParaEnviar
|
||||
});
|
||||
} else {
|
||||
await createTarefa.mutateAsync(dadosParaEnviar);
|
||||
}
|
||||
onClose();
|
||||
} catch (error) {
|
||||
console.error('Erro ao salvar tarefa:', error);
|
||||
alert('Erro ao salvar tarefa. Por favor, tente novamente.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const tabs = [
|
||||
{ id: 'detalhes', label: 'Detalhes' },
|
||||
{ id: 'subtarefas', label: 'Subtarefas' },
|
||||
{ id: 'comentarios', label: 'Comentários' },
|
||||
];
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onClose={onClose} className="relative z-50">
|
||||
<div className="fixed inset-0 bg-black/30 backdrop-blur-sm" />
|
||||
|
||||
<div className="fixed inset-0 overflow-y-auto">
|
||||
<div className="flex min-h-full items-center justify-center p-4">
|
||||
<Dialog.Panel className="w-full max-w-4xl bg-white dark:bg-gray-800 rounded-xl shadow-xl">
|
||||
{/* Header */}
|
||||
<div className="border-b border-gray-200 dark:border-gray-700 p-4">
|
||||
<div className="flex justify-between items-center">
|
||||
<Dialog.Title className="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
{tarefa ? 'Editar Tarefa' : 'Nova Tarefa'}
|
||||
</Dialog.Title>
|
||||
<button onClick={onClose} className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
|
||||
<XMarkIcon className="h-6 w-6" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex space-x-4 mt-4">
|
||||
{tabs.map(tab => (
|
||||
<button
|
||||
key={tab.id}
|
||||
onClick={() => setActiveTab(tab.id)}
|
||||
className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors
|
||||
${activeTab === tab.id
|
||||
? 'bg-blue-100 text-blue-700 dark:bg-blue-900 dark:text-blue-200'
|
||||
: 'text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="p-6">
|
||||
{/* Conteúdo das tabs */}
|
||||
<div className="space-y-6">
|
||||
{activeTab === 'detalhes' && (
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="col-span-2">
|
||||
<input
|
||||
type="text"
|
||||
{...register('titulo')}
|
||||
placeholder="Título da tarefa"
|
||||
className="w-full px-4 py-2 text-xl font-medium border-0 border-b-2 border-gray-200 dark:border-gray-700 bg-transparent text-gray-900 dark:text-white focus:ring-0 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-span-2">
|
||||
<textarea
|
||||
{...register('descricao')}
|
||||
rows={3}
|
||||
placeholder="Descrição detalhada"
|
||||
className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<select
|
||||
{...register('prioridade')}
|
||||
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="BAIXA">Baixa</option>
|
||||
<option value="MEDIA">Média</option>
|
||||
<option value="ALTA">Alta</option>
|
||||
<option value="URGENTE">Urgente</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
{...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"
|
||||
>
|
||||
<option value="">Selecione um responsável</option>
|
||||
{usuarios.map((usuario: any) => (
|
||||
<option key={usuario.id} value={usuario.id}>
|
||||
{usuario.nome}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<DatePicker
|
||||
label="Data de Início"
|
||||
value={watch('dataInicio')}
|
||||
onChange={(date) => setValue('dataInicio', date)}
|
||||
className="w-full"
|
||||
slotProps={{ textField: { size: 'small' } }}
|
||||
/>
|
||||
|
||||
<DatePicker
|
||||
label="Data de Vencimento"
|
||||
value={watch('dataVencimento')}
|
||||
onChange={(date) => setValue('dataVencimento', date)}
|
||||
className="w-full"
|
||||
slotProps={{ textField: { size: 'small' } }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'subtarefas' && (
|
||||
<SubtarefasList
|
||||
subtarefas={watch('subtarefas') || []}
|
||||
onChange={(subtarefas) => setValue('subtarefas', subtarefas)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'comentarios' && (
|
||||
<ComentariosList
|
||||
comentarios={watch('comentarios') || []}
|
||||
onChange={(comentarios) => setValue('comentarios', comentarios)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 flex justify-end space-x-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClose}
|
||||
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-lg disabled:opacity-50"
|
||||
>
|
||||
{loading ? 'Salvando...' : tarefa ? 'Salvar' : 'Criar'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</Dialog.Panel>
|
||||
</div>
|
||||
</div>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,140 @@
|
||||
import React from 'react';
|
||||
import { useQuery } from 'react-query';
|
||||
import { Tarefa } from '../../types/entities';
|
||||
import { format } from 'date-fns';
|
||||
import { ptBR } from 'date-fns/locale';
|
||||
import { PencilIcon, TrashIcon } from '@heroicons/react/24/outline';
|
||||
import api from '../../services/api';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
import { useTarefas } from '../../hooks/useTarefas';
|
||||
|
||||
interface TarefasListProps {
|
||||
onEdit: (tarefa: Tarefa) => void;
|
||||
onStatusChange: (id: string, status: string, progresso?: number) => void;
|
||||
}
|
||||
|
||||
export const TarefasList: React.FC<TarefasListProps> = ({ onEdit, onStatusChange }) => {
|
||||
const { user } = useAuth();
|
||||
const { tarefas, isLoading, deleteTarefa } = useTarefas();
|
||||
|
||||
const getPrioridadeColor = (prioridade: string) => {
|
||||
const colors = {
|
||||
'BAIXA': 'bg-green-100 text-green-800',
|
||||
'MEDIA': 'bg-yellow-100 text-yellow-800',
|
||||
'ALTA': 'bg-orange-100 text-orange-800',
|
||||
'URGENTE': 'bg-red-100 text-red-800'
|
||||
};
|
||||
return colors[prioridade as keyof typeof colors] || 'bg-gray-100 text-gray-800';
|
||||
};
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
const colors = {
|
||||
'PENDENTE': 'bg-gray-100 text-gray-800',
|
||||
'EM_ANDAMENTO': 'bg-blue-100 text-blue-800',
|
||||
'CONCLUIDA': 'bg-green-100 text-green-800',
|
||||
'CANCELADA': 'bg-red-100 text-red-800'
|
||||
};
|
||||
return colors[status as keyof typeof colors] || 'bg-gray-100 text-gray-800';
|
||||
};
|
||||
|
||||
const canDelete = user && ['ADVOGADO_ADMIN', 'ADVOGADO'].includes(user.perfil);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!window.confirm('Tem certeza que deseja excluir esta tarefa?')) return;
|
||||
|
||||
try {
|
||||
await deleteTarefa.mutateAsync(id);
|
||||
// Não precisa fazer nada aqui, o React Query vai atualizar automaticamente
|
||||
} catch (error) {
|
||||
console.error('Erro ao excluir tarefa:', error);
|
||||
alert('Erro ao excluir tarefa');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden">
|
||||
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<thead className="bg-gray-50 dark:bg-gray-900">
|
||||
<tr>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Título/Descrição
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Status
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Prioridade
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Vencimento
|
||||
</th>
|
||||
<th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
|
||||
Progresso
|
||||
</th>
|
||||
<th scope="col" className="relative px-6 py-3">
|
||||
<span className="sr-only">Ações</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
|
||||
{tarefas.map((tarefa: Tarefa) => (
|
||||
<tr key={tarefa.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
|
||||
<td className="px-6 py-4">
|
||||
<div className="text-sm font-medium text-gray-900 dark:text-white">
|
||||
{tarefa.titulo}
|
||||
</div>
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{tarefa.descricao}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${getStatusColor(tarefa.status)}`}>
|
||||
{tarefa.status.replace('_', ' ')}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${getPrioridadeColor(tarefa.prioridade)}`}>
|
||||
{tarefa.prioridade}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{format(new Date(tarefa.dataVencimento), 'dd/MM/yyyy', { locale: ptBR })}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap">
|
||||
<div className="w-full bg-gray-200 rounded-full h-2.5 mb-1">
|
||||
<div
|
||||
className="bg-blue-600 h-2.5 rounded-full"
|
||||
style={{ width: `${tarefa.progresso}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-xs text-gray-500 dark:text-gray-400">
|
||||
{tarefa.progresso}%
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
|
||||
<div className="flex items-center justify-end space-x-2">
|
||||
<button
|
||||
onClick={() => onEdit(tarefa)}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300"
|
||||
>
|
||||
<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"
|
||||
>
|
||||
<TrashIcon className="h-5 w-5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
import React, { useState } from 'react';
|
||||
import { TarefasList } from './TarefasList';
|
||||
import { TarefaModal } from './TarefaModal';
|
||||
import { TarefaKanban } from './TarefaKanban';
|
||||
import { ListBulletIcon, Squares2X2Icon } from '@heroicons/react/24/outline';
|
||||
import { useTarefas } from '../../hooks/useTarefas';
|
||||
|
||||
export const TarefasPage: React.FC = () => {
|
||||
const { updateStatus } = useTarefas();
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [viewMode, setViewMode] = useState<'list' | 'kanban'>('list');
|
||||
const [selectedTarefa, setSelectedTarefa] = useState(null);
|
||||
|
||||
const handleStatusChange = async (id: string, status: string, progresso?: number) => {
|
||||
try {
|
||||
await updateStatus.mutateAsync({ id, status, progresso });
|
||||
} catch (error) {
|
||||
console.error('Erro ao atualizar status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex justify-between items-center">
|
||||
<h1 className="text-2xl font-semibold text-gray-900 dark:text-white">
|
||||
Tarefas
|
||||
</h1>
|
||||
|
||||
<div className="flex items-center space-x-4">
|
||||
{/* Toggle de visualização */}
|
||||
<div className="bg-gray-100 dark:bg-gray-800 rounded-lg p-1">
|
||||
<button
|
||||
onClick={() => setViewMode('list')}
|
||||
className={`px-3 py-2 rounded-md ${
|
||||
viewMode === 'list'
|
||||
? 'bg-white dark:bg-gray-700 shadow'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<ListBulletIcon className="h-5 w-5" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setViewMode('kanban')}
|
||||
className={`px-3 py-2 rounded-md ${
|
||||
viewMode === 'kanban'
|
||||
? 'bg-white dark:bg-gray-700 shadow'
|
||||
: 'text-gray-500 dark:text-gray-400'
|
||||
}`}
|
||||
>
|
||||
<Squares2X2Icon className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedTarefa(null);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 dark:hover:bg-blue-500"
|
||||
>
|
||||
Nova Tarefa
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Visualização alternada entre lista e kanban */}
|
||||
{viewMode === 'list' ? (
|
||||
<TarefasList
|
||||
onEdit={(tarefa) => {
|
||||
setSelectedTarefa(tarefa);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
onStatusChange={handleStatusChange}
|
||||
/>
|
||||
) : (
|
||||
<TarefaKanban
|
||||
onEdit={(tarefa) => {
|
||||
setSelectedTarefa(tarefa);
|
||||
setIsModalOpen(true);
|
||||
}}
|
||||
onStatusChange={handleStatusChange}
|
||||
/>
|
||||
)}
|
||||
|
||||
<TarefaModal
|
||||
isOpen={isModalOpen}
|
||||
onClose={() => {
|
||||
setIsModalOpen(false);
|
||||
setSelectedTarefa(null);
|
||||
}}
|
||||
tarefa={selectedTarefa}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,69 @@
|
||||
import React from 'react';
|
||||
|
||||
type ButtonVariant = 'primary' | 'secondary' | 'success' | 'danger' | 'warning' | 'info' | 'outline' | 'link';
|
||||
|
||||
interface ButtonProps {
|
||||
children: React.ReactNode;
|
||||
type?: 'button' | 'submit' | 'reset';
|
||||
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void;
|
||||
variant?: ButtonVariant;
|
||||
size?: 'sm' | 'md' | 'lg';
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
icon?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
type = 'button',
|
||||
onClick,
|
||||
variant = 'primary',
|
||||
size = 'md',
|
||||
disabled = false,
|
||||
className = '',
|
||||
icon,
|
||||
}: ButtonProps) {
|
||||
const baseClasses = 'inline-flex items-center justify-center font-medium rounded-md focus:outline-none transition-colors';
|
||||
|
||||
// Definir classes de variante
|
||||
const variantClasses = {
|
||||
primary: 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-2 focus:ring-offset-2 focus:ring-blue-500',
|
||||
secondary: 'bg-gray-600 text-white hover:bg-gray-700 focus:ring-2 focus:ring-offset-2 focus:ring-gray-500',
|
||||
success: 'bg-green-600 text-white hover:bg-green-700 focus:ring-2 focus:ring-offset-2 focus:ring-green-500',
|
||||
danger: 'bg-red-600 text-white hover:bg-red-700 focus:ring-2 focus:ring-offset-2 focus:ring-red-500',
|
||||
warning: 'bg-yellow-500 text-white hover:bg-yellow-600 focus:ring-2 focus:ring-offset-2 focus:ring-yellow-400',
|
||||
info: 'bg-blue-400 text-white hover:bg-blue-500 focus:ring-2 focus:ring-offset-2 focus:ring-blue-300',
|
||||
outline: 'bg-white text-gray-700 border border-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-offset-2 focus:ring-blue-500',
|
||||
link: 'bg-transparent text-blue-600 hover:text-blue-800 hover:underline focus:ring-0',
|
||||
};
|
||||
|
||||
// Definir classes de tamanho
|
||||
const sizeClasses = {
|
||||
sm: 'px-2.5 py-1.5 text-xs',
|
||||
md: 'px-4 py-2 text-sm',
|
||||
lg: 'px-6 py-3 text-base',
|
||||
};
|
||||
|
||||
// Definir classes de estado desabilitado
|
||||
const disabledClasses = 'opacity-50 cursor-not-allowed';
|
||||
|
||||
const buttonClasses = [
|
||||
baseClasses,
|
||||
variantClasses[variant],
|
||||
sizeClasses[size],
|
||||
disabled ? disabledClasses : '',
|
||||
className,
|
||||
].join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
type={type}
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className={buttonClasses}
|
||||
>
|
||||
{icon && <span className="mr-2">{icon}</span>}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
|
||||
interface CardProps {
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
padding?: 'none' | 'sm' | 'md' | 'lg';
|
||||
}
|
||||
|
||||
export function Card({ children, className = '', padding = 'md' }: CardProps) {
|
||||
const paddingClasses = {
|
||||
none: '',
|
||||
sm: 'p-2',
|
||||
md: 'p-4',
|
||||
lg: 'p-6',
|
||||
};
|
||||
|
||||
const cardClasses = [
|
||||
'bg-white shadow overflow-hidden rounded-lg',
|
||||
paddingClasses[padding],
|
||||
className,
|
||||
].join(' ');
|
||||
|
||||
return <div className={cardClasses}>{children}</div>;
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import React from 'react';
|
||||
|
||||
interface InputBaseProps {
|
||||
label: string;
|
||||
id: string;
|
||||
name: string;
|
||||
required?: boolean;
|
||||
help?: string;
|
||||
errorMessage?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
interface TextInputProps extends InputBaseProps {
|
||||
type?: 'text' | 'email' | 'password' | 'tel' | 'url';
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
placeholder?: string;
|
||||
maxLength?: number;
|
||||
}
|
||||
|
||||
export function TextInput({
|
||||
label,
|
||||
id,
|
||||
name,
|
||||
required,
|
||||
help,
|
||||
errorMessage,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
maxLength,
|
||||
type = 'text',
|
||||
}: TextInputProps) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<input
|
||||
type={type}
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
maxLength={maxLength}
|
||||
required={required}
|
||||
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && <p className="mt-1 text-sm text-red-600">{errorMessage}</p>}
|
||||
{help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface NumberInputProps extends InputBaseProps {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
placeholder?: string;
|
||||
min?: number;
|
||||
max?: number;
|
||||
step?: number;
|
||||
}
|
||||
|
||||
export function NumberInput({
|
||||
label,
|
||||
id,
|
||||
name,
|
||||
required,
|
||||
help,
|
||||
errorMessage,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
min,
|
||||
max,
|
||||
step,
|
||||
}: NumberInputProps) {
|
||||
// Processar input para garantir que seja numérico com vírgula como separador decimal
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
// Permitir apenas números, vírgula, ponto e sinais +/-
|
||||
const cleanValue = e.target.value.replace(/[^0-9,.+-]/g, '');
|
||||
|
||||
// Simular o evento com o valor limpo
|
||||
const simulatedEvent = {
|
||||
...e,
|
||||
target: {
|
||||
...e.target,
|
||||
value: cleanValue,
|
||||
},
|
||||
};
|
||||
|
||||
onChange(simulatedEvent);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={className}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
<div className="mt-1 relative rounded-md shadow-sm">
|
||||
<input
|
||||
type="text"
|
||||
inputMode="decimal"
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
placeholder={placeholder}
|
||||
required={required}
|
||||
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && <p className="mt-1 text-sm text-red-600">{errorMessage}</p>}
|
||||
{help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface DateInputProps extends InputBaseProps {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
|
||||
min?: string;
|
||||
max?: string;
|
||||
}
|
||||
|
||||
export function DateInput({
|
||||
label,
|
||||
id,
|
||||
name,
|
||||
required,
|
||||
help,
|
||||
errorMessage,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
min,
|
||||
max,
|
||||
}: DateInputProps) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<input
|
||||
type="date"
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
required={required}
|
||||
min={min}
|
||||
max={max}
|
||||
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && <p className="mt-1 text-sm text-red-600">{errorMessage}</p>}
|
||||
{help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface SelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
interface SelectInputProps extends InputBaseProps {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLSelectElement>) => void;
|
||||
options: SelectOption[];
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function SelectInput({
|
||||
label,
|
||||
id,
|
||||
name,
|
||||
required,
|
||||
help,
|
||||
errorMessage,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
options,
|
||||
placeholder,
|
||||
}: SelectInputProps) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<select
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
required={required}
|
||||
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
|
||||
>
|
||||
{placeholder && <option value="">{placeholder}</option>}
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{errorMessage && <p className="mt-1 text-sm text-red-600">{errorMessage}</p>}
|
||||
{help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TextAreaInputProps extends InputBaseProps {
|
||||
value: string;
|
||||
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
|
||||
placeholder?: string;
|
||||
rows?: number;
|
||||
}
|
||||
|
||||
export function TextAreaInput({
|
||||
label,
|
||||
id,
|
||||
name,
|
||||
required,
|
||||
help,
|
||||
errorMessage,
|
||||
className,
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
rows = 3,
|
||||
}: TextAreaInputProps) {
|
||||
return (
|
||||
<div className={className}>
|
||||
<label htmlFor={id} className="block text-sm font-medium text-gray-700">
|
||||
{label} {required && <span className="text-red-500">*</span>}
|
||||
</label>
|
||||
<div className="mt-1">
|
||||
<textarea
|
||||
id={id}
|
||||
name={name}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
placeholder={placeholder}
|
||||
required={required}
|
||||
rows={rows}
|
||||
className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm"
|
||||
/>
|
||||
</div>
|
||||
{errorMessage && <p className="mt-1 text-sm text-red-600">{errorMessage}</p>}
|
||||
{help && <p className="mt-1 text-xs text-gray-500">{help}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
interface TabsProps {
|
||||
children: React.ReactNode;
|
||||
activeTab?: string;
|
||||
onChange?: (tabId: string) => void;
|
||||
}
|
||||
|
||||
interface TabListProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
interface TabProps {
|
||||
children: React.ReactNode;
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface TabPanelProps {
|
||||
children: React.ReactNode;
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface TabContext {
|
||||
activeTab: string;
|
||||
setActiveTab: (id: string) => void;
|
||||
}
|
||||
|
||||
const TabsContext = React.createContext<TabContext | undefined>(undefined);
|
||||
|
||||
export function Tabs({ children, activeTab: externalActiveTab, onChange }: TabsProps) {
|
||||
// Se o activeTab for fornecido externamente, use-o como valor inicial
|
||||
const [activeTab, setActiveTabInternal] = useState<string>('');
|
||||
|
||||
// Encontrar o primeiro id de tab disponível para valor inicial
|
||||
useEffect(() => {
|
||||
if (!activeTab && !externalActiveTab) {
|
||||
// Buscar os filhos TabPanel para encontrar o primeiro id
|
||||
React.Children.forEach(children, (child) => {
|
||||
if (React.isValidElement(child) && child.type === TabList) {
|
||||
React.Children.forEach(child.props.children, (tab) => {
|
||||
if (React.isValidElement(tab) && tab.props.id && !activeTab) {
|
||||
setActiveTabInternal(tab.props.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Sincronizar com o activeTab externo, se fornecido
|
||||
useEffect(() => {
|
||||
if (externalActiveTab) {
|
||||
setActiveTabInternal(externalActiveTab);
|
||||
}
|
||||
}, [externalActiveTab]);
|
||||
|
||||
const setActiveTab = (id: string) => {
|
||||
setActiveTabInternal(id);
|
||||
if (onChange) {
|
||||
onChange(id);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<TabsContext.Provider value={{ activeTab: externalActiveTab || activeTab, setActiveTab }}>
|
||||
<div className="tabs-container">{children}</div>
|
||||
</TabsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabList({ children }: TabListProps) {
|
||||
return (
|
||||
<div className="border-b border-gray-200">
|
||||
<nav className="flex space-x-8" aria-label="Tabs">
|
||||
{children}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Tab({ children, id }: TabProps) {
|
||||
const context = React.useContext(TabsContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('Tab must be used within a Tabs component');
|
||||
}
|
||||
|
||||
const { activeTab, setActiveTab } = context;
|
||||
|
||||
const isActive = activeTab === id;
|
||||
|
||||
const tabClasses = `
|
||||
whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm
|
||||
${isActive
|
||||
? 'border-blue-500 text-blue-600'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'}
|
||||
`;
|
||||
|
||||
return (
|
||||
<button
|
||||
className={tabClasses}
|
||||
onClick={() => setActiveTab(id)}
|
||||
role="tab"
|
||||
aria-selected={isActive}
|
||||
id={`tab-${id}`}
|
||||
aria-controls={`panel-${id}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function TabPanel({ children, id }: TabPanelProps) {
|
||||
const context = React.useContext(TabsContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error('TabPanel must be used within a Tabs component');
|
||||
}
|
||||
|
||||
const { activeTab } = context;
|
||||
|
||||
if (activeTab !== id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
id={`panel-${id}`}
|
||||
role="tabpanel"
|
||||
aria-labelledby={`tab-${id}`}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 423 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user