gohorsejobs/docs/root/CLAUDE.md

315 lines
12 KiB
Markdown

# CLAUDE.md - GoHorse Jobs
## Project Overview
GoHorse Jobs is a B2B SaaS recruitment platform connecting companies with candidates. It is structured as a monorepo with multiple services sharing a single PostgreSQL database.
**Business model**: Freemium (Free / Pro R$199/month / Enterprise custom pricing).
## Repository Structure
```
gohorsejobs/
├── backend/ # Go 1.24 REST API (Clean Architecture + DDD)
├── frontend/ # Next.js 15 web application (App Router)
├── backoffice/ # NestJS 11 admin/worker API (Fastify adapter)
├── seeder-api/ # Node.js Express database seeder
├── job-scraper-multisite/# Job scraping service
├── ass-email/ # Email assistant service
├── k8s/ # Kubernetes manifests (dev, hml, prd)
├── docs/ # Central documentation (API, DB, DevOps, Roadmap)
├── .forgejo/ # Forgejo CI/CD workflows
├── .drone.yml # Drone CI/CD pipelines (dev/hml/prd)
└── start.sh # Interactive dev startup script
```
## Tech Stack
| Service | Language | Framework | Key Libraries |
|---------|----------|-----------|---------------|
| Backend | Go 1.24 | stdlib net/http | JWT v5, lib/pq, GORM, Stripe, AWS SDK v2, RabbitMQ, Firebase Admin, Swaggo |
| Frontend | TypeScript 5 | Next.js 15 (App Router) | React 19, Tailwind CSS 4, shadcn/ui (Radix), Zustand, React Hook Form + Zod, Framer Motion, Appwrite, Firebase |
| Backoffice | TypeScript 5 | NestJS 11 (Fastify) | TypeORM, Passport + JWT, Stripe, AMQP, Nodemailer, Pino, Firebase Admin |
| Seeder | JavaScript (ESM) | Express 5 | pg, bcrypt |
**Database**: PostgreSQL 16+ with UUID v7 primary keys. 42 SQL migration files in `backend/migrations/`.
## Quick Start
```bash
./start.sh # Interactive menu
```
| Option | Action |
|--------|--------|
| 1 | Start Frontend + Backend |
| 2 | Reset DB + Seed + Start |
| 3 | Start all services (Frontend + Backend + Backoffice) |
| 4 | Run migrations only |
| 5 | Seed database (append) |
| 6 | Full DB reset + migrate + seed |
| 7 | Run backend E2E tests |
| 8 | Seed reset LITE (skip 153k cities) |
| 9 | Run all tests (Backend + Frontend) |
### Service Ports
| Service | Port |
|---------|------|
| Backend | 8521 |
| Frontend | 8963 |
| Backoffice | 3001 |
| Swagger (Backend) | 8521/swagger/index.html |
| Swagger (Backoffice) | 3001/api/docs |
## Build & Test Commands
### Backend (Go)
```bash
# Run
cd backend && go run cmd/api/main.go
# Test
go test -v ./... -count=1 # All unit tests
go test -tags=e2e -v ./tests/e2e/... # E2E tests
# Swagger generation (requires swag CLI)
swag init -g cmd/api/main.go --parseDependency --parseInternal
# Dependencies
go mod tidy
```
### Frontend (Next.js)
```bash
cd frontend
npm install # Install deps
npm run dev # Dev server (default port 3000, use -p 8963 for project convention)
npm run build # Production build
npm run lint # ESLint (next lint)
npm run test # Jest unit tests
```
### Backoffice (NestJS)
```bash
cd backoffice
pnpm install # Uses pnpm (packageManager: pnpm@9.15.4)
npm run start:dev # Dev server with watch
npm run build # Production build (nest build)
npm run lint # ESLint with auto-fix
npm run format # Prettier
npm run test # Jest unit tests
npm run test:cov # Coverage
npm run test:e2e # E2E tests
```
### Seeder
```bash
cd seeder-api
npm install
npm run migrate # Run migrations
npm run seed # Seed data
npm run seed:reset # Drop all tables
npm run seed:lite # Seed without 153k cities
```
## Architecture & Conventions
### Backend (Go) - Clean Architecture + DDD
```
backend/internal/
├── api/ # (legacy) HTTP handlers
├── handlers/ # HTTP request handlers (current)
├── middleware/ # Auth, CORS, rate limiting, security headers, XSS sanitizer
├── core/
│ ├── domain/entity/ # Business entities (User, Company, Job, etc.)
│ ├── ports/ # Repository interfaces
│ └── usecases/ # Business logic (LoginUseCase, RegisterUseCase, etc.)
├── infrastructure/
│ ├── auth/ # JWT service
│ ├── persistence/ # PostgreSQL repository implementations
│ └── storage/ # S3/R2 storage adapter
├── services/ # Business services (Email, FCM, Storage, Admin)
├── dto/ # Data Transfer Objects
├── router/ # Route definitions
├── models/ # GORM models (legacy, being migrated)
├── database/ # DB connection & migration runner
└── utils/ # Utilities (JWT, sanitizer)
```
**Patterns**:
- Constructor injection: `func NewService(db *sql.DB) *Service`
- All DB operations accept `ctx context.Context`
- Error handling: `(T, error)` return tuples
- Repository interfaces in `core/ports/`, implementations in `infrastructure/persistence/`
- Test files: `*_test.go`
### Frontend (Next.js) - App Router
```
frontend/src/
├── app/ # File-based routing (20+ routes)
│ ├── dashboard/ # Protected routes (12+ sub-pages)
│ ├── jobs/ # Job listing & details
│ ├── auth/ # Login, register flows
│ └── ...
├── components/ # Reusable components (44+)
│ └── ui/ # shadcn/ui primitives (24+)
├── hooks/ # Custom React hooks (useAuth, useFetch, etc.)
├── contexts/ # React contexts (auth, theme)
├── lib/ # Utilities (API calls, validation helpers)
└── i18n/ # Internationalization (PT, EN, ES, JA)
```
**Patterns**:
- Server Components by default; use `'use client'` directive for interactivity
- Tailwind CSS utility classes for styling
- Path alias: `@/*` maps to `./src/*`
- Form validation: React Hook Form + Zod schemas
- Global state: Zustand stores
- Real-time features: Appwrite SDK
- Test files: `*.test.tsx`
### Backoffice (NestJS) - Modular
```
backoffice/src/
├── admin/ # Dashboard & statistics
├── auth/ # JWT authentication (Passport)
├── email/ # Email worker (AMQP/LavinMQ consumer)
├── external-services/ # Credential management
├── fcm-tokens/ # Firebase push tokens
├── plans/ # Subscription plans
├── stripe/ # Stripe payment integration
├── tickets/ # Support tickets
├── activity-logs/ # Activity tracking
└── credentials/ # External credentials management
```
**Patterns**:
- NestJS module pattern: `*.module.ts`, `*.controller.ts`, `*.service.ts`, `*.entity.ts`
- Guards for auth: `@UseGuards(JwtAuthGuard)`
- DTOs: `create-*.dto.ts`, `update-*.dto.ts` with class-validator decorators
- Prettier config: single quotes, trailing commas
## Authentication & Authorization
- **JWT**: HS256 with HttpOnly cookies (web) + Bearer tokens (API/mobile)
- **4 roles**: `superadmin` > `admin` > `recruiter` > `candidate`
- **Middleware stack**: Auth (JWT+RBAC) -> CORS -> Rate Limiting (100 req/min) -> Security Headers -> XSS Sanitizer
- **JWT secret must match** between Backend and Backoffice services
## Database
- PostgreSQL 16+ with UUID v7 for primary keys (SERIAL for reference tables)
- Migrations: `backend/migrations/` (42 SQL files, numbered `000_` through `999_`)
- Core tables: `users`, `companies`, `user_companies`, `jobs`, `applications`, `favorite_jobs`, `notifications`, `tickets`, `activity_logs`, `job_payments`
- Relationships: Users belong to companies via `user_companies`; jobs belong to companies; applications link users to jobs
## API Routes
All backend routes under `/api/v1`:
- **Auth**: `/auth/login`, `/auth/register/candidate`, `/auth/register/company`, `/auth/forgot-password`, `/auth/reset-password`
- **Jobs**: CRUD at `/jobs`, moderation at `/jobs/moderation`
- **Companies**: CRUD at `/companies`, status management
- **Users**: `/users/me` (profile), admin CRUD at `/users`
- **Applications**: `/applications` with status updates
- **Storage**: `/storage/upload-url` (presigned S3/R2 URLs)
- **Admin**: `/admin/companies`, `/admin/email-templates`, `/admin/email-settings`
- **Notifications**: `/notifications`, `/tokens` (FCM)
- **Chat**: `/conversations`, `/conversations/{id}/messages`
## External Services
| Service | Purpose |
|---------|---------|
| Stripe | Payment processing & subscriptions |
| Firebase (FCM) | Push notifications |
| Appwrite | Real-time chat/messaging |
| LavinMQ (AMQP) | Message queue for background jobs |
| Cloudflare R2 / S3 | File/image storage |
| Resend | Transactional email |
| cPanel API | Email account management |
## Deployment
- **Environments**: `dev` (branch: dev), `hml` (branch: hml), `prd` (branch: main)
- **CI/CD**: Forgejo workflows (`.forgejo/workflows/deploy.yaml`) + Drone (`.drone.yml`)
- **Container runtime**: Podman (dev), Kubernetes (production)
- **Registry**: Forgejo (`forgejo-gru.rede5.com.br/rede5/`) and Harbor (`in.gohorsejobs.com`)
- **Docker images**: `gohorsejobs-backend`, `gohorsejobs-frontend`, `gohorsejobs-backoffice`, `gohorsejobs-seeder`
## Documentation
Detailed docs are in the `docs/` directory:
- `docs/API.md` - Complete API reference
- `docs/API_SECURITY.md` - Authentication & RBAC details
- `docs/DATABASE.md` - Schema & ERD
- `docs/DEVOPS.md` - Infrastructure & deployment
- `docs/ROADMAP.md` - Product roadmap
- `docs/TASKS.md` - Task tracking
## Key Things to Know
- The backend uses Clean Architecture with DDD; always respect the layer boundaries (handlers -> usecases -> ports/repositories)
- Frontend uses Next.js App Router conventions; new pages go in `src/app/`, shared components in `src/components/`
- The backoffice is a separate NestJS service that shares the same PostgreSQL database as the backend
- Migrations are plain SQL files executed by the seeder-api; they are not managed by an ORM migration tool
- The project supports 4 languages (PT, EN, ES, JA) via i18n message files in `frontend/src/i18n/`
- Environment variables must be configured in `.env` files for each service (backend, frontend, backoffice, seeder-api); these files are gitignored
- The `start.sh` script is the recommended way to run the development environment
## Git Workflow
### Remotes
| Remote | URL | Funcao |
|--------|-----|--------|
| **origin** | git@github.com:rede5/gohorsejobs.git | GitHub - desenvolvimento principal |
| **pipe** | https://pipe.gohorsejobs.com/bohessefm/gohorsejobs.git | Forgejo - mirror/CI |
| **dokku** | dokku@localhost:gohorsejobs | Deploy Dokku (gohorsejobs) |
| **dokku-frontend** | dokku@localhost:gohorse-frontend | Deploy Dokku (frontend) |
### Fluxo de Desenvolvimento
O desenvolvimento acontece no **GitHub (origin)**. O Forgejo (pipe) eh um mirror que recebe o codigo via push manual.
```
GitHub (origin) ---> VPS vim ---> Forgejo (pipe)
[dev] git pull git push pipe dev
```
**Passo a passo para sincronizar:**
```bash
# 1. Na VPS, puxar as alteracoes do GitHub
cd /root/gohorsejobs
git pull origin dev
# 2. Enviar para o Forgejo
git push pipe dev
# 3. (Opcional) Enviar para outras branches
git pull origin main && git push pipe main
git pull origin hml && git push pipe hml
```
### Branches
| Branch | Ambiente | Descricao |
|--------|----------|-----------|
| **dev** | Desenvolvimento | Branch principal de trabalho |
| **hml** | Homologacao | Testes pre-producao |
| **main** | Producao | Versao estavel |
### Regras
1. **Todo desenvolvimento acontece no GitHub** (origin) - PRs, code review, CI
2. **Forgejo (pipe) eh mirror** - recebe push manual apos pull do GitHub
3. **Nunca commitar direto no Forgejo** - sempre via GitHub primeiro
4. **Deploy via Dokku** - push para remotes dokku/dokku-frontend para deploy na VPS