first commit
This commit is contained in:
commit
c9fb67e751
423 files changed
+53287
No files matched your search
@@ -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>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user