first commit
This commit is contained in:
commit
c9fb67e751
423 files changed
+53287
No files matched your search
@@ -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