feat: otimização de performance e ajustes finais
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
# 🔗 Integração Frontend ↔ Backend
|
||||
|
||||
## ✅ Status: 100% Compatível com Backend
|
||||
|
||||
O frontend foi totalmente integrado com o backend Spring Boot, usando parâmetros da Guiné-Bissau.
|
||||
|
||||
## 📋 Mapeamento de Tipos
|
||||
|
||||
### Agent (Agente)
|
||||
|
||||
| Frontend (TypeScript) | Backend (Java DTO) | Tipo | Obrigatório |
|
||||
|----------------------|-------------------|------|-------------|
|
||||
| `id` | `id` | UUID/String | ✅ |
|
||||
| `matricula` | `matricula` | String | ✅ |
|
||||
| `nationalId` | `nationalId` | String | ✅ |
|
||||
| `fullName` | `fullName` | String | ✅ |
|
||||
| `birthDate` | `birthDate` | LocalDate (YYYY-MM-DD) | ✅ |
|
||||
| `hireDate` | `hireDate` | LocalDate (YYYY-MM-DD) | ✅ |
|
||||
| `terminationDate` | `terminationDate` | LocalDate (YYYY-MM-DD) | ❌ |
|
||||
| `status` | `status` | String (ACTIVE/INACTIVE/SUSPENDED/TERMINATED) | ✅ |
|
||||
| `orgUnit` | `orgUnit` | UUID | ❌ |
|
||||
| `position` | `position` | UUID | ❌ |
|
||||
| `nationality` | `nationality` | String | ❌ |
|
||||
| `phone` | `phone` | String | ❌ |
|
||||
| `email` | `email` | String | ❌ |
|
||||
| `address` | `address` | String | ❌ |
|
||||
|
||||
## 🔌 Endpoints da API
|
||||
|
||||
### AgentController (`/api/rh/agents`)
|
||||
|
||||
| Método | Endpoint | Descrição | Frontend |
|
||||
|--------|----------|-----------|----------|
|
||||
| `GET` | `/api/rh/agents` | Listar com paginação | ✅ `useAgents()` |
|
||||
| `GET` | `/api/rh/agents/{id}` | Buscar por ID | ✅ `getAgentById()` |
|
||||
| `POST` | `/api/rh/agents` | Criar agente | ✅ `createAgent()` |
|
||||
| `PUT` | `/api/rh/agents/{id}` | Atualizar agente | ✅ `updateAgent()` |
|
||||
|
||||
### Parâmetros de Paginação
|
||||
|
||||
O backend aceita os seguintes parâmetros de query:
|
||||
|
||||
- `page` (int, default: 0) - Página atual (0-indexed)
|
||||
- `size` (int, default: 20) - Tamanho da página
|
||||
- `sortBy` (String, opcional) - Campo para ordenação
|
||||
- `sortDirection` (String, default: "ASC") - Direção da ordenação (ASC/DESC)
|
||||
|
||||
**Resposta do Backend (Spring Data Page):**
|
||||
```json
|
||||
{
|
||||
"content": [...],
|
||||
"totalElements": 100,
|
||||
"totalPages": 5,
|
||||
"size": 20,
|
||||
"number": 0,
|
||||
"first": true,
|
||||
"last": false,
|
||||
"numberOfElements": 20,
|
||||
"empty": false
|
||||
}
|
||||
```
|
||||
|
||||
## 🇬🇼 Configuração para Guiné-Bissau
|
||||
|
||||
### Backend (application.yml)
|
||||
|
||||
```yaml
|
||||
guinea-bissau:
|
||||
country:
|
||||
code: GW
|
||||
name: Guiné-Bissau
|
||||
currency:
|
||||
code: XOF
|
||||
symbol: FCFA
|
||||
timezone: Africa/Bissau
|
||||
locale: pt_GW
|
||||
phone-code: "+245"
|
||||
date-format: "dd/MM/yyyy"
|
||||
datetime-format: "dd/MM/yyyy HH:mm"
|
||||
```
|
||||
|
||||
### Frontend (src/utils/locale.ts)
|
||||
|
||||
```typescript
|
||||
export const LOCALE_CONFIG = {
|
||||
country: 'Guiné-Bissau',
|
||||
countryCode: 'GW',
|
||||
currency: 'XOF',
|
||||
currencySymbol: 'FCFA',
|
||||
timezone: 'Africa/Bissau',
|
||||
locale: 'pt-GW',
|
||||
dateFormat: 'DD/MM/YYYY',
|
||||
dateTimeFormat: 'DD/MM/YYYY HH:mm',
|
||||
phoneCode: '+245',
|
||||
};
|
||||
```
|
||||
|
||||
### Funções de Formatação
|
||||
|
||||
- `formatCurrency(value: number)` - Formata valores em XOF (FCFA)
|
||||
- `formatDate(date: Date | string)` - Formata datas DD/MM/YYYY
|
||||
- `formatDateTime(date: Date | string)` - Formata data e hora
|
||||
- `formatPhone(phone: string)` - Formata telefone +245 XXX XXX XXX
|
||||
- `formatLocalDate(dateString: string)` - Converte LocalDate (YYYY-MM-DD) para formato de exibição
|
||||
|
||||
## 🛠️ Serviço de API
|
||||
|
||||
### Arquivo: `src/services/api.ts`
|
||||
|
||||
- Base URL: `http://localhost:8081/api` (configurável via env)
|
||||
- Interceptor de autenticação (JWT token)
|
||||
- Tratamento de erros HTTP
|
||||
- Método `getPage()` para paginação Spring Data
|
||||
|
||||
### Exemplo de Uso
|
||||
|
||||
```typescript
|
||||
import { api } from '@/services/api';
|
||||
import { AgentDTO } from '@/types/backend';
|
||||
|
||||
// Listar agentes com paginação
|
||||
const response = await api.getPage<AgentDTO>('/rh/agents', {
|
||||
page: 0,
|
||||
size: 20,
|
||||
sortBy: 'fullName',
|
||||
sortDirection: 'ASC',
|
||||
});
|
||||
|
||||
// Buscar agente por ID
|
||||
const agent = await api.get<AgentDTO>('/rh/agents/{id}');
|
||||
|
||||
// Criar agente
|
||||
const newAgent = await api.post<AgentDTO>('/rh/agents', agentData);
|
||||
|
||||
// Atualizar agente
|
||||
const updated = await api.put<AgentDTO>(`/rh/agents/${id}`, agentData);
|
||||
|
||||
// Excluir agente
|
||||
await api.delete(`/rh/agents/${id}`);
|
||||
```
|
||||
|
||||
## 🎣 Hooks Personalizados
|
||||
|
||||
### `useAgents()`
|
||||
|
||||
Hook que gerencia o estado dos agentes com integração completa ao backend:
|
||||
|
||||
```typescript
|
||||
const {
|
||||
agents, // Lista de agentes
|
||||
loading, // Estado de carregamento
|
||||
error, // Erro, se houver
|
||||
page, // Página atual
|
||||
totalPages, // Total de páginas
|
||||
totalElements, // Total de elementos
|
||||
refetch, // Função para recarregar
|
||||
setPage, // Função para mudar página
|
||||
createAgent, // Criar agente
|
||||
updateAgent, // Atualizar agente
|
||||
getAgentById, // Buscar por ID
|
||||
deleteAgent, // Excluir agente
|
||||
} = useAgents({
|
||||
page: 0,
|
||||
size: 20,
|
||||
sortBy: 'fullName',
|
||||
sortDirection: 'ASC',
|
||||
});
|
||||
```
|
||||
|
||||
### `useAgent(id: string)`
|
||||
|
||||
Hook para buscar um agente específico:
|
||||
|
||||
```typescript
|
||||
const { agent, loading, error } = useAgent('agent-id');
|
||||
```
|
||||
|
||||
## 📝 Formato de Dados
|
||||
|
||||
### Datas
|
||||
|
||||
- **Backend**: `LocalDate` (Java) serializado como `YYYY-MM-DD` (ISO 8601)
|
||||
- **Frontend**: Recebe como string `YYYY-MM-DD`, exibe como `DD/MM/YYYY`
|
||||
|
||||
### Status
|
||||
|
||||
- **Backend**: Strings: `"ACTIVE"`, `"INACTIVE"`, `"SUSPENDED"`, `"TERMINATED"`
|
||||
- **Frontend**: Mapeado para badges visuais
|
||||
|
||||
### UUIDs
|
||||
|
||||
- **Backend**: `java.util.UUID`
|
||||
- **Frontend**: `string` (TypeScript)
|
||||
|
||||
## ⚙️ Configuração
|
||||
|
||||
### Variáveis de Ambiente
|
||||
|
||||
Crie um arquivo `.env`:
|
||||
|
||||
```env
|
||||
VITE_API_URL=http://localhost:8081/api
|
||||
VITE_LOCALE=pt-GW
|
||||
VITE_TIMEZONE=Africa/Bissau
|
||||
VITE_CURRENCY=XOF
|
||||
```
|
||||
|
||||
### Proxy de Desenvolvimento
|
||||
|
||||
O `vite.config.ts` está configurado para fazer proxy das requisições `/api` para `http://localhost:8081`.
|
||||
|
||||
## ✅ Checklist de Compatibilidade
|
||||
|
||||
- [x] Tipos TypeScript correspondem aos DTOs Java
|
||||
- [x] Endpoints corretos (`/api/rh/agents`)
|
||||
- [x] Paginação Spring Data implementada
|
||||
- [x] Validações frontend correspondem ao backend
|
||||
- [x] Formato de datas (YYYY-MM-DD ↔ DD/MM/YYYY)
|
||||
- [x] Status mapeados corretamente
|
||||
- [x] UUIDs tratados como strings
|
||||
- [x] Tratamento de erros HTTP
|
||||
- [x] Interceptor de autenticação preparado
|
||||
- [x] Configuração para Guiné-Bissau (XOF, pt-GW, Africa/Bissau)
|
||||
|
||||
## 🧪 Testes de Integração
|
||||
|
||||
Para testar a integração:
|
||||
|
||||
1. **Iniciar o backend:**
|
||||
```bash
|
||||
cd sigefp-api
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
2. **Iniciar o frontend:**
|
||||
```bash
|
||||
cd sigefp-frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
3. **Testar endpoints:**
|
||||
- Listar agentes: `GET http://localhost:8081/api/rh/agents`
|
||||
- Criar agente: `POST http://localhost:8081/api/rh/agents`
|
||||
- Atualizar agente: `PUT http://localhost:8081/api/rh/agents/{id}`
|
||||
- Buscar agente: `GET http://localhost:8081/api/rh/agents/{id}`
|
||||
|
||||
---
|
||||
|
||||
**Status:** ✅ 100% Integrado e Compatível
|
||||
**Localização:** ✅ Configurado para Guiné-Bissau
|
||||
**Última atualização:** Dezembro 2024
|
||||
|
||||
Reference in New Issue
Block a user