docs: Comprehensive BACKOFFICE.md update with all modules and integrations

This commit is contained in:
Tiago Yamamoto 2025-12-26 12:40:04 -03:00
parent 6c5b7586c9
commit b0378985a4

View file

@ -1,55 +1,296 @@
# Backoffice API - NestJS
GoHorse Jobs SaaS Administration and Subscription Management API.
[![NestJS](https://img.shields.io/badge/NestJS-11+-E0234E?style=flat-square&logo=nestjs)](https://nestjs.com/)
[![TypeScript](https://img.shields.io/badge/TypeScript-5+-3178C6?style=flat-square&logo=typescript)](https://typescriptlang.org/)
[![Fastify](https://img.shields.io/badge/Fastify-4+-000000?style=flat-square&logo=fastify)](https://fastify.io/)
## Features
GoHorse Jobs SaaS Administration, Subscription Management, and Email Worker API.
- 💳 **Stripe Integration** - Payment processing and subscriptions
- 📊 **Dashboard Stats** - Platform analytics
- 👥 **User Management** - Admin controls for users
- 🏢 **Company Management** - Tenant administration
- 📋 **Subscription Plans** - Monthly/yearly plans
- 🔐 **JWT Authentication** - Bearer token and Cookie support
---
## Authentication
## 🏗️ Arquitetura
The backoffice supports **two authentication methods**:
```
backoffice/
├── src/
│ ├── admin/ # Dashboard e estatísticas
│ │ ├── admin.controller.ts
│ │ ├── admin.service.ts
│ │ └── admin.module.ts
│ │
│ ├── auth/ # Autenticação JWT
│ │ ├── jwt-auth.guard.ts
│ │ ├── jwt-strategy.ts
│ │ └── auth.module.ts
│ │
│ ├── email/ # Email Worker (LavinMQ Consumer)
│ │ ├── email.service.ts
│ │ ├── email.module.ts
│ │ └── entities/
│ │ ├── email-setting.entity.ts
│ │ └── email-template.entity.ts
│ │
│ ├── external-services/ # Gestão de credenciais
│ │ ├── external-services.controller.ts
│ │ ├── external-services.service.ts
│ │ └── external-services.module.ts
│ │
│ ├── fcm-tokens/ # Firebase Cloud Messaging
│ │ ├── fcm-tokens.controller.ts
│ │ ├── fcm-tokens.service.ts
│ │ └── fcm-tokens.module.ts
│ │
│ ├── plans/ # Planos de assinatura
│ │ ├── plans.controller.ts
│ │ ├── plans.service.ts
│ │ └── plans.module.ts
│ │
│ ├── stripe/ # Integração Stripe
│ │ ├── stripe.controller.ts
│ │ ├── stripe.service.ts
│ │ └── stripe.module.ts
│ │
│ ├── app.module.ts # Módulo raiz
│ └── main.ts # Bootstrap
```
---
## 🔧 Módulos
| Módulo | Descrição |
|--------|-----------|
| **AdminModule** | Dashboard stats, revenue analytics, subscription metrics |
| **AuthModule** | JWT validation (Bearer + Cookie), guards |
| **EmailModule** | LavinMQ consumer, Nodemailer sender, template rendering (Handlebars) |
| **ExternalServicesModule** | RSA encryption, credentials storage |
| **FcmTokensModule** | Firebase Admin SDK, push notifications |
| **PlansModule** | Subscription plans CRUD |
| **StripeModule** | Checkout sessions, webhooks, billing portal |
---
## 📧 Email Worker
O módulo `EmailModule` atua como **consumer** do LavinMQ:
### Fluxo
```
1. Go Backend → Publica job em `mail_queue`
2. NestJS → Consome job da fila
3. NestJS → Busca template do banco (email_templates)
4. NestJS → Renderiza com Handlebars
5. NestJS → Envia via SMTP (Nodemailer)
```
### Entidades (TypeORM)
```typescript
// email_settings
{
id: UUID,
provider: string,
smtp_host: string,
smtp_port: number,
smtp_user: string,
smtp_pass: string,
smtp_secure: boolean,
sender_name: string,
sender_email: string,
amqp_url: string,
is_active: boolean
}
// email_templates
{
id: UUID,
slug: string,
subject: string,
body_html: string,
variables: string[]
}
```
---
## 💳 Stripe Integration
### Endpoints
| Método | Endpoint | Descrição |
|--------|----------|-----------|
| `POST` | `/stripe/checkout` | Criar Checkout Session |
| `POST` | `/stripe/portal` | Criar Billing Portal |
| `POST` | `/stripe/webhook` | Webhook handler |
### Webhooks Suportados
- `checkout.session.completed` - Pagamento concluído
- `customer.subscription.created` - Nova assinatura
- `customer.subscription.updated` - Assinatura atualizada
- `customer.subscription.deleted` - Assinatura cancelada
- `invoice.payment_failed` - Pagamento falhou
---
## 📊 Admin Dashboard
### Endpoints
| Método | Endpoint | Descrição |
|--------|----------|-----------|
| `GET` | `/admin/stats` | Dashboard stats |
| `GET` | `/admin/revenue` | Revenue by month |
| `GET` | `/admin/subscriptions-by-plan` | Subscriptions breakdown |
### Stats Response
```json
{
"totalCompanies": 150,
"activeSubscriptions": 120,
"monthlyRevenue": 25000,
"newCompaniesThisMonth": 15
}
```
---
## 🔒 Autenticação
O backoffice suporta **dois métodos**:
1. **Bearer Token** - `Authorization: Bearer <token>`
2. **JWT Cookie** - `jwt=<token>` (fallback)
This is implemented in `src/auth/jwt-auth.guard.ts`.
Implementado em `src/auth/jwt-auth.guard.ts`.
## Tech Stack
---
- NestJS 10+
- TypeScript
- Stripe SDK
- Swagger (OpenAPI)
- JWT (jsonwebtoken)
## 🔐 External Services Credentials
## Getting Started
Gerenciamento seguro de credenciais com criptografia RSA:
```bash
npm install
npm run start:dev
```typescript
// Fluxo de criptografia
1. Frontend envia credencial
2. Backoffice criptografa com RSA public key
3. Armazena criptografada no banco (external_services_credentials)
4. Go Backend descriptografa com private key quando necessário
```
## Environment Variables
### Services Suportados
```env
- Stripe
- Firebase (FCM)
- Cloudflare
- SMTP (Email)
- S3/R2 (Storage)
---
## 🔧 Environment Variables
```bash
# Server
PORT=3001
# Database (compartilhado com Go)
DATABASE_URL=postgres://user:pass@host:5432/dbname
# Stripe
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
# Firebase
FIREBASE_ADMIN_SDK_PATH=/path/to/service-account.json
# OU
FIREBASE_SERVICE_ACCOUNT={"type":"service_account",...}
# JWT (mesmo do Go backend)
JWT_SECRET=your-secret-key
```
## API Documentation
---
Visit: `http://localhost:3001/api/docs`
## 🚀 Desenvolvimento
## Docker
### Requisitos
- Node.js 20+
- pnpm 9+
### Executar
```bash
docker build -t gohorse-backoffice .
docker run -p 3001:3001 gohorse-backoffice
# Instalar dependências
pnpm install
# Desenvolvimento
pnpm start:dev
# Produção
pnpm build
pnpm start:prod
```
### Testes
```bash
# Unit tests
pnpm test
# E2E tests
pnpm test:e2e
# Coverage
pnpm test:cov
```
---
## 📡 API Documentation
Swagger UI disponível em:
**Development:** `http://localhost:3001/api/docs`
---
## 🐳 Docker
```bash
# Build
docker build -t gohorse-backoffice .
# Run
docker run -p 3001:3001 --env-file .env gohorse-backoffice
```
---
## 📦 Tech Stack
| Tecnologia | Versão | Uso |
|------------|--------|-----|
| NestJS | 11+ | Framework |
| Fastify | 4+ | HTTP Server |
| TypeORM | 0.3+ | ORM (Email entities) |
| Stripe | 20+ | Pagamentos |
| Firebase Admin | 13+ | Push Notifications |
| amqplib | 0.10+ | LavinMQ Consumer |
| Nodemailer | 6+ | SMTP Client |
| Handlebars | 4+ | Template Engine |
| Pino | 9+ | Logging |
---
## 🔗 Integrações
| Serviço | Módulo | Uso |
|---------|--------|-----|
| **Stripe** | StripeModule | Pagamentos, assinaturas |
| **LavinMQ** | EmailModule | Fila de emails |
| **Firebase** | FcmTokensModule | Push notifications |
| **PostgreSQL** | TypeORM | Email settings/templates |