docs: Comprehensive BACKEND.md update with all services, endpoints, and integrations
This commit is contained in:
parent
867a155423
commit
6c5b7586c9
1 changed files with 174 additions and 54 deletions
|
|
@ -10,29 +10,61 @@ API REST desenvolvida em Go seguindo princípios de **Clean Architecture** e **D
|
|||
## 🏗️ Arquitetura
|
||||
|
||||
```
|
||||
internal/
|
||||
├── api/ # Clean Architecture Layer
|
||||
│ ├── handlers/ # HTTP Handlers (Controllers)
|
||||
│ └── middleware/ # Auth, CORS, Rate Limiting
|
||||
backend/
|
||||
├── cmd/
|
||||
│ ├── api/ # Entrypoint principal
|
||||
│ └── manual_migrate/ # Migration runner
|
||||
│
|
||||
├── core/ # Domain Layer (DDD)
|
||||
│ ├── domain/entity/ # Entidades puras (sem deps externas)
|
||||
│ ├── ports/ # Interfaces (Repository, Service)
|
||||
│ └── usecases/ # Casos de uso (Business Logic)
|
||||
├── internal/
|
||||
│ ├── api/ # Clean Architecture Layer
|
||||
│ │ ├── handlers/ # HTTP Handlers (Admin, Auth, Settings, Storage)
|
||||
│ │ └── middleware/ # Auth, CORS, Rate Limiting, Sanitize
|
||||
│ │
|
||||
│ ├── core/ # Domain Layer (DDD)
|
||||
│ │ ├── domain/entity/ # Entidades (User, Company, Email)
|
||||
│ │ ├── ports/ # Interfaces (Repositories)
|
||||
│ │ └── usecases/ # Casos de uso (Auth, Register)
|
||||
│ │
|
||||
│ ├── infrastructure/ # Infrastructure Layer
|
||||
│ │ ├── auth/ # JWT Service implementation
|
||||
│ │ └── persistence/ # Repository implementations (Postgres)
|
||||
│ │
|
||||
│ ├── dto/ # Data Transfer Objects
|
||||
│ ├── handlers/ # Legacy controllers (Job, Application)
|
||||
│ ├── middleware/ # Security middlewares
|
||||
│ ├── models/ # GORM models
|
||||
│ ├── router/ # Route configuration
|
||||
│ ├── services/ # Business logic services
|
||||
│ └── utils/ # Helpers (JWT, Sanitizer)
|
||||
│
|
||||
├── infrastructure/ # Infrastructure Layer
|
||||
│ ├── auth/ # JWT Service implementation
|
||||
│ └── persistence/ # Repository implementations
|
||||
│
|
||||
├── handlers/ # Legacy controllers
|
||||
├── middleware/ # Security middlewares
|
||||
├── models/ # GORM models
|
||||
├── services/ # Business logic (legacy)
|
||||
└── utils/ # Helpers (JWT, Sanitizer)
|
||||
├── migrations/ # SQL Migrations (30+)
|
||||
├── tests/ # E2E and Integration tests
|
||||
└── docs/ # Swagger documentation
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Services
|
||||
|
||||
| Service | Arquivo | Descrição |
|
||||
|---------|---------|-----------|
|
||||
| **AdminService** | `admin_service.go` | CRUD de empresas, usuários, candidatos, tags, email templates |
|
||||
| **JobService** | `job_service.go` | CRUD de vagas com filtros avançados |
|
||||
| **ApplicationService** | `application_service.go` | Gestão de candidaturas |
|
||||
| **TicketService** | `ticket_service.go` | Sistema de tickets de suporte |
|
||||
| **ChatService** | `chat_service.go` | Mensagens e conversas (Appwrite) |
|
||||
| **NotificationService** | `notification_service.go` | Notificações push |
|
||||
| **EmailService** | `email_service.go` | Produtor de emails via LavinMQ |
|
||||
| **FCMService** | `fcm_service.go` | Firebase Cloud Messaging |
|
||||
| **StorageService** | `storage_service.go` | Pre-signed URLs (S3/R2) |
|
||||
| **CredentialsService** | `credentials_service.go` | Gestão de credenciais criptografadas |
|
||||
| **CloudflareService** | `cloudflare_service.go` | Cache purge via API |
|
||||
| **SettingsService** | `settings_service.go` | System settings |
|
||||
| **AppwriteService** | `appwrite_service.go` | Integração Appwrite Realtime |
|
||||
| **AuditService** | `audit_service.go` | Logs de auditoria |
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Segurança
|
||||
|
||||
### Middlewares Implementados
|
||||
|
|
@ -43,10 +75,14 @@ internal/
|
|||
| **CORS** | `middleware/cors.go` | Whitelist de origens via `CORS_ORIGINS` |
|
||||
| **Rate Limiting** | `middleware/rate_limit.go` | 100 req/min por IP |
|
||||
| **Security Headers** | `middleware/security_headers.go` | OWASP headers (XSS, CSP, etc.) |
|
||||
| **Sanitize** | `middleware/sanitize.go` | XSS sanitization em JSON bodies |
|
||||
|
||||
### Validação de JWT
|
||||
### Autenticação
|
||||
|
||||
O servidor valida no boot que `JWT_SECRET` tenha pelo menos 32 caracteres. Em produção (`ENV=production`), o servidor **não inicia** com secrets fracos.
|
||||
- **JWT** com expiração configurável
|
||||
- **Password Pepper** via `PASSWORD_PEPPER` env var
|
||||
- **HttpOnly Cookies** para refresh tokens
|
||||
- **RSA Encryption** para credenciais sensíveis
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -56,53 +92,111 @@ O servidor valida no boot que `JWT_SECRET` tenha pelo menos 32 caracteres. Em pr
|
|||
|
||||
| Método | Endpoint | Descrição |
|
||||
|--------|----------|-----------|
|
||||
| `GET` | `/` | Root check |
|
||||
| `GET` | `/health` | Health check |
|
||||
| `GET` | `/swagger/*` | Documentação Swagger |
|
||||
| `POST` | `/api/v1/auth/login` | Autenticação |
|
||||
| `POST` | `/api/v1/companies` | Registro de empresa |
|
||||
| `GET` | `/jobs` | Listar vagas (Busca, Filtros, Paginação) |
|
||||
|
||||
### 🔍 Busca e Filtros (`GET /jobs`)
|
||||
|
||||
O endpoint `/jobs` suporta filtros avançados via query params:
|
||||
- `q`: Busca textual (Título, Descrição, Empresa)
|
||||
- `location`: Filtro por localização (Partial Match)
|
||||
- `type`: Tipo de contrato (full-time, part-time, etc.)
|
||||
- `workMode`: Modelo de trabalho (remote, hybrid, onsite)
|
||||
- `page` & `limit`: Paginação server-side
|
||||
| `GET` | `/docs/*` | Swagger UI |
|
||||
| `POST` | `/api/v1/auth/login` | Login |
|
||||
| `POST` | `/api/v1/auth/register/candidate` | Registro de candidato |
|
||||
| `POST` | `/api/v1/auth/register/company` | Registro de empresa |
|
||||
| `GET` | `/api/v1/jobs` | Listar vagas (filtros, paginação) |
|
||||
| `GET` | `/api/v1/jobs/{id}` | Detalhes da vaga |
|
||||
| `GET` | `/api/v1/companies/{id}` | Detalhes da empresa |
|
||||
|
||||
### Protegidos (JWT Required)
|
||||
|
||||
| Método | Endpoint | Roles | Descrição |
|
||||
|--------|----------|-------|-----------|
|
||||
| `GET` | `/api/v1/users` | `superadmin`, `admin` | Listar usuários |
|
||||
| `POST` | `/api/v1/users` | `superadmin`, `admin` | Criar usuário |
|
||||
| `GET` | `/api/v1/users/me` | `any` | Perfil do usuário |
|
||||
| `PATCH` | `/api/v1/users/me/profile` | `any` | Atualizar perfil |
|
||||
| `GET` | `/api/v1/users` | `admin`, `superadmin` | Listar usuários |
|
||||
| `POST` | `/api/v1/users` | `admin`, `superadmin` | Criar usuário |
|
||||
| `DELETE` | `/api/v1/users/{id}` | `superadmin` | Deletar usuário |
|
||||
| `POST` | `/jobs` | `admin`, `recruiter` | Criar vaga |
|
||||
| `GET` | `/api/v1/users/me` | `any` (authed) | Perfil do usuário |
|
||||
| `DELETE` | `/api/v1/applications/{id}` | `admin`, `recruiter` | Deletar candidatura |
|
||||
|
||||
### Vagas (Autenticado)
|
||||
|
||||
| Método | Endpoint | Roles | Descrição |
|
||||
|--------|----------|-------|-----------|
|
||||
| `POST` | `/api/v1/jobs` | `admin`, `recruiter` | Criar vaga |
|
||||
| `PUT` | `/api/v1/jobs/{id}` | `admin`, `recruiter` | Atualizar vaga |
|
||||
| `DELETE` | `/api/v1/jobs/{id}` | `admin` | Deletar vaga |
|
||||
|
||||
### Admin
|
||||
|
||||
| Método | Endpoint | Descrição |
|
||||
|--------|----------|-----------|
|
||||
| `GET` | `/api/v1/admin/companies` | Listar empresas |
|
||||
| `PATCH` | `/api/v1/admin/companies/{id}/status` | Aprovar/Suspender empresa |
|
||||
| `GET` | `/api/v1/admin/email-templates` | Listar templates de email |
|
||||
| `POST` | `/api/v1/admin/email-templates` | Criar template |
|
||||
| `PUT` | `/api/v1/admin/email-templates/{slug}` | Atualizar template |
|
||||
| `DELETE` | `/api/v1/admin/email-templates/{slug}` | Deletar template |
|
||||
| `GET` | `/api/v1/admin/email-settings` | Obter configurações SMTP |
|
||||
| `PUT` | `/api/v1/admin/email-settings` | Atualizar configurações SMTP |
|
||||
|
||||
### Outros
|
||||
|
||||
| Método | Endpoint | Descrição |
|
||||
|--------|----------|-----------|
|
||||
| `GET` | `/api/v1/storage/upload-url` | Pre-signed URL para upload |
|
||||
| `GET` | `/api/v1/notifications` | Listar notificações |
|
||||
| `POST` | `/api/v1/tokens` | Salvar FCM token |
|
||||
| `GET` | `/api/v1/support/tickets` | Listar tickets |
|
||||
| `POST` | `/api/v1/support/tickets` | Criar ticket |
|
||||
| `GET` | `/api/v1/conversations` | Listar conversas |
|
||||
| `POST` | `/api/v1/conversations/{id}/messages` | Enviar mensagem |
|
||||
|
||||
---
|
||||
|
||||
### Exemplo: atualizar candidatura para "Contratado"
|
||||
## 🗄️ Migrations
|
||||
|
||||
Use este fluxo para marcar uma candidatura como aprovada (status `hired`).
|
||||
O projeto usa um sistema de migrations manuais via `cmd/manual_migrate`.
|
||||
|
||||
1. **Endpoint**: `PUT /applications/{id}/status`
|
||||
- Substitua `{id}` pelo identificador numérico da candidatura. Exemplo: `/applications/1234/status`.
|
||||
2. **Payload (`application/json`)**:
|
||||
### Principais Migrations
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "hired",
|
||||
"notes": "Candidato APROVADO após a entrevista final. Salário de R$ 5.500,00 acordado. Início em 01/02/2026."
|
||||
}
|
||||
| # | Arquivo | Descrição |
|
||||
|---|---------|-----------|
|
||||
| 000 | `000_init_uuid_v7.sql` | Função UUID v7 |
|
||||
| 001 | `001_create_users_table.sql` | Tabela de usuários |
|
||||
| 002 | `002_create_companies_table.sql` | Tabela de empresas |
|
||||
| 005 | `005_create_jobs_table.sql` | Tabela de vagas |
|
||||
| 006 | `006_create_applications_table.sql` | Tabela de candidaturas |
|
||||
| 016 | `016_create_notifications_table.sql` | Notificações |
|
||||
| 017 | `017_create_tickets_table.sql` | Tickets de suporte |
|
||||
| 021 | `021_location_hierarchy.sql` | Países, regiões, cidades |
|
||||
| 024 | `024_create_external_services_credentials.sql` | Credenciais criptografadas |
|
||||
| 025 | `025_create_chat_tables.sql` | Conversas e mensagens |
|
||||
| 026 | `026_create_system_settings.sql` | Configurações do sistema |
|
||||
| 027 | `027_create_email_system.sql` | Templates e configurações de email |
|
||||
| 028 | `028_add_avatar_url_to_users.sql` | Avatar de usuário |
|
||||
|
||||
### Executar Migrations
|
||||
|
||||
```bash
|
||||
go run ./cmd/manual_migrate
|
||||
```
|
||||
|
||||
- O campo `status` é obrigatório e deve ser `"hired"` para confirmar a contratação.
|
||||
- O campo `notes` é opcional e pode registrar observações do recrutador.
|
||||
---
|
||||
|
||||
3. **Próximo passo recomendado**: Após o `200 OK`, crie a conta de usuário interno do contratado com `POST /api/v1/users`.
|
||||
## 🔧 Environment Variables
|
||||
|
||||
```bash
|
||||
# Database
|
||||
DATABASE_URL=postgres://user:pass@host:5432/dbname
|
||||
|
||||
# Auth
|
||||
JWT_SECRET=your-secret-key-min-32-chars
|
||||
PASSWORD_PEPPER=your-pepper-key
|
||||
|
||||
# CORS
|
||||
CORS_ORIGINS=https://frontend.com,https://admin.com
|
||||
|
||||
# External Services
|
||||
RSA_PRIVATE_KEY_BASE64=base64-encoded-private-key
|
||||
|
||||
# Optional
|
||||
PORT=8080
|
||||
ENV=production
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
|
|
@ -111,10 +205,13 @@ Use este fluxo para marcar uma candidatura como aprovada (status `hired`).
|
|||
### Executar
|
||||
|
||||
```bash
|
||||
# Copie o .env
|
||||
# Copiar .env
|
||||
cp .env.example .env
|
||||
|
||||
# Execute
|
||||
# Executar migrations
|
||||
go run ./cmd/manual_migrate
|
||||
|
||||
# Iniciar servidor
|
||||
go run ./cmd/api
|
||||
```
|
||||
|
||||
|
|
@ -124,8 +221,17 @@ go run ./cmd/api
|
|||
# Todos os testes
|
||||
go test ./...
|
||||
|
||||
# Com verbose
|
||||
go test -v ./internal/middleware/... ./internal/utils/...
|
||||
# Com cobertura
|
||||
go test -cover ./...
|
||||
|
||||
# Verbose
|
||||
go test -v ./internal/services/...
|
||||
```
|
||||
|
||||
### Build
|
||||
|
||||
```bash
|
||||
go build -o api ./cmd/api
|
||||
```
|
||||
|
||||
### Regenerar Swagger
|
||||
|
|
@ -155,7 +261,21 @@ docker run -p 8080:8080 --env-file .env gohorse-backend
|
|||
| Arquivo | Descrição |
|
||||
|---------|-----------|
|
||||
| `cmd/api/main.go` | Entrypoint da aplicação |
|
||||
| `cmd/manual_migrate/main.go` | Migration runner |
|
||||
| `internal/router/router.go` | Configuração de todas as rotas |
|
||||
| `internal/database/database.go` | Conexão GORM com PostgreSQL |
|
||||
| `migrations/*.sql` | Migrations do banco de dados |
|
||||
| `docs/swagger.json` | Documentação OpenAPI gerada |
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Integrações
|
||||
|
||||
| Serviço | Uso |
|
||||
|---------|-----|
|
||||
| **LavinMQ** | Fila de emails assíncronos |
|
||||
| **Appwrite** | Chat realtime |
|
||||
| **Firebase** | Push notifications (FCM) |
|
||||
| **Cloudflare** | CDN com cache purge |
|
||||
| **S3/R2** | Storage com pre-signed URLs |
|
||||
| **Stripe** | Pagamentos (via Backoffice) |
|
||||
|
|
|
|||
Loading…
Reference in a new issue