553 lines
17 KiB
Markdown
553 lines
17 KiB
Markdown
# CLAUDE.md
|
|
|
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
|
|
## Project Overview
|
|
|
|
**Xpeditis** is a B2B SaaS maritime freight booking and management platform (maritime equivalent of WebCargo). The platform allows freight forwarders to search and compare real-time shipping rates, book containers online, and manage shipments from a centralized dashboard.
|
|
|
|
**Current Status**: Phase 4 - Production-ready with security hardening, monitoring, and comprehensive testing infrastructure.
|
|
|
|
## Development Commands
|
|
|
|
### Local Development Setup
|
|
|
|
```bash
|
|
# Install all dependencies (monorepo)
|
|
npm install
|
|
cd apps/backend && npm install
|
|
cd ../frontend && npm install
|
|
|
|
# Start infrastructure (PostgreSQL + Redis)
|
|
docker-compose up -d # Development (uses docker-compose.yml)
|
|
# OR
|
|
docker-compose -f docker-compose.dev.yml up -d
|
|
|
|
# Run database migrations
|
|
cd apps/backend
|
|
npm run migration:run
|
|
|
|
# Start backend development server (with hot reload)
|
|
npm run backend:dev # From root, or:
|
|
cd apps/backend && npm run dev
|
|
|
|
# Start frontend development server
|
|
npm run frontend:dev # From root, or:
|
|
cd apps/frontend && npm run dev
|
|
```
|
|
|
|
**Access Points**:
|
|
- Frontend: http://localhost:3000
|
|
- Backend API: http://localhost:4000
|
|
- API Docs (Swagger): http://localhost:4000/api/docs
|
|
|
|
### Monorepo Scripts (from root)
|
|
|
|
```bash
|
|
# Development
|
|
npm run backend:dev # Start backend dev server
|
|
npm run frontend:dev # Start frontend dev server
|
|
|
|
# Testing
|
|
npm run backend:test # Run backend unit tests
|
|
npm run frontend:test # Run frontend tests
|
|
npm run backend:lint # Lint backend code
|
|
npm run frontend:lint # Lint frontend code
|
|
|
|
# Code Quality
|
|
npm run format # Format all code (Prettier)
|
|
npm run format:check # Check formatting
|
|
|
|
# Build
|
|
npm run backend:build # Build backend for production
|
|
npm run frontend:build # Build frontend for production
|
|
|
|
# Utilities
|
|
npm run install:all # Install deps for all workspaces
|
|
npm run clean # Clean all node_modules and build artifacts
|
|
```
|
|
|
|
### Testing Commands
|
|
|
|
#### Backend Tests
|
|
|
|
```bash
|
|
cd apps/backend
|
|
|
|
# Unit tests (domain layer - no external dependencies)
|
|
npm test # Run all unit tests
|
|
npm run test:watch # Run in watch mode
|
|
npm run test:cov # With coverage report
|
|
|
|
# Integration tests (infrastructure layer with real DB/Redis)
|
|
npm run test:integration # Run all integration tests
|
|
npm run test:integration:watch # Run in watch mode
|
|
npm run test:integration:cov # With coverage report
|
|
|
|
# E2E tests (full API workflow)
|
|
npm run test:e2e # Run end-to-end tests
|
|
|
|
# Run a single test file
|
|
npm test -- booking.service.spec.ts
|
|
npm run test:integration -- redis-cache.adapter.spec.ts
|
|
```
|
|
|
|
#### Load Testing (K6)
|
|
|
|
```bash
|
|
cd apps/backend
|
|
|
|
# Install k6 (macOS)
|
|
brew install k6
|
|
|
|
# Run rate search load test (100 virtual users)
|
|
k6 run load-tests/rate-search.test.js
|
|
|
|
# Run with custom parameters
|
|
k6 run --vus 50 --duration 60s load-tests/rate-search.test.js
|
|
```
|
|
|
|
#### E2E Testing (Playwright)
|
|
|
|
```bash
|
|
cd apps/frontend
|
|
|
|
# Install Playwright
|
|
npx playwright install
|
|
|
|
# Run E2E tests (booking workflow)
|
|
npx playwright test e2e/booking-workflow.spec.ts
|
|
|
|
# Run with UI mode
|
|
npx playwright test --ui
|
|
|
|
# Run specific browser
|
|
npx playwright test --project=chromium
|
|
```
|
|
|
|
#### API Testing (Postman/Newman)
|
|
|
|
```bash
|
|
# Install Newman globally
|
|
npm install -g newman
|
|
|
|
# Run Postman collection
|
|
newman run postman/Xpeditis_API.postman_collection.json
|
|
```
|
|
|
|
### Database Migrations
|
|
|
|
```bash
|
|
cd apps/backend
|
|
|
|
# Generate new migration (after changing ORM entities)
|
|
npm run migration:generate -- src/infrastructure/persistence/typeorm/migrations/MigrationName
|
|
|
|
# Run pending migrations
|
|
npm run migration:run
|
|
|
|
# Revert last migration
|
|
npm run migration:revert
|
|
```
|
|
|
|
### Build & Production
|
|
|
|
```bash
|
|
# Backend build
|
|
cd apps/backend
|
|
npm run build
|
|
npm run start:prod
|
|
|
|
# Frontend build
|
|
cd apps/frontend
|
|
npm run build
|
|
npm start
|
|
```
|
|
|
|
## Architecture
|
|
|
|
### Hexagonal Architecture (Ports & Adapters)
|
|
|
|
The backend follows strict hexagonal architecture with three isolated layers:
|
|
|
|
```
|
|
apps/backend/src/
|
|
├── domain/ # 🎯 Pure business logic (ZERO external dependencies)
|
|
│ ├── entities/ # Booking, RateQuote, User, Organization, Carrier
|
|
│ ├── value-objects/ # Email, Money, BookingNumber, PortCode
|
|
│ ├── services/ # Domain services (rate-search, booking, availability)
|
|
│ ├── ports/
|
|
│ │ ├── in/ # Use cases (search-rates, create-booking)
|
|
│ │ └── out/ # Repository interfaces, connector ports
|
|
│ └── exceptions/ # Business exceptions
|
|
│
|
|
├── application/ # 🔌 Controllers & DTOs (depends ONLY on domain)
|
|
│ ├── controllers/ # REST endpoints
|
|
│ ├── dto/ # Data transfer objects with validation
|
|
│ ├── guards/ # Auth guards, rate limiting, RBAC
|
|
│ ├── services/ # Brute-force protection, file validation
|
|
│ └── mappers/ # DTO ↔ Domain entity mapping
|
|
│
|
|
└── infrastructure/ # 🏗️ External integrations (depends ONLY on domain)
|
|
├── persistence/typeorm/ # PostgreSQL repositories
|
|
├── cache/ # Redis adapter
|
|
├── carriers/ # Maersk, MSC, CMA CGM connectors
|
|
├── email/ # MJML email service
|
|
├── storage/ # S3 storage adapter
|
|
├── websocket/ # Real-time carrier updates
|
|
└── security/ # Helmet.js, rate limiting, CORS
|
|
```
|
|
|
|
**Critical Rules**:
|
|
1. **Domain layer**: No imports of NestJS, TypeORM, Redis, or any framework
|
|
2. **Dependencies flow inward**: Infrastructure → Application → Domain
|
|
3. **TypeScript path aliases**: Use `@domain/*`, `@application/*`, `@infrastructure/*`
|
|
4. **Testing**: Domain tests must run without NestJS TestingModule
|
|
|
|
### Frontend Architecture (Next.js 14 App Router)
|
|
|
|
```
|
|
apps/frontend/src/
|
|
├── app/ # Next.js 14 App Router pages (routing)
|
|
├── components/ # React components
|
|
│ ├── ui/ # shadcn/ui components (Button, Dialog, etc.)
|
|
│ └── features/ # Feature-specific components
|
|
├── hooks/ # Custom React hooks
|
|
├── lib/ # Utilities and API client
|
|
├── types/ # TypeScript type definitions
|
|
└── utils/ # Helper functions
|
|
```
|
|
|
|
**Frontend Patterns**:
|
|
- Server Components by default, Client Components when needed (`"use client"`)
|
|
- React Hook Form + Zod for form validation
|
|
- TanStack Query for server state management
|
|
- Zustand for client state management
|
|
- shadcn/ui for accessible UI components
|
|
|
|
### Tech Stack
|
|
|
|
**Backend**:
|
|
- NestJS 10+ (framework)
|
|
- TypeScript 5+ (strict mode)
|
|
- PostgreSQL 15+ (database)
|
|
- TypeORM 0.3+ (ORM)
|
|
- Redis 7+ (cache, 15min TTL for rates)
|
|
- Passport + JWT (authentication)
|
|
- Helmet.js (security headers)
|
|
- Pino (structured logging)
|
|
- Sentry (error tracking + APM)
|
|
|
|
**Frontend**:
|
|
- Next.js 14+ App Router
|
|
- TypeScript 5+
|
|
- TanStack Table (data grids)
|
|
- React Hook Form + Zod (forms)
|
|
- Socket.IO (real-time updates)
|
|
- Tailwind CSS + shadcn/ui
|
|
|
|
**Infrastructure**:
|
|
- Docker + Docker Compose
|
|
- GitHub Actions (CI/CD)
|
|
- AWS RDS (PostgreSQL)
|
|
- AWS ElastiCache (Redis)
|
|
- AWS S3 (document storage)
|
|
|
|
## Testing Strategy
|
|
|
|
### Test Coverage Targets
|
|
- **Domain layer**: 90%+ (currently ~100% for value objects and entities)
|
|
- **Application layer**: 80%+
|
|
- **Infrastructure layer**: 70%+ (currently ~82% for Phase 3 services)
|
|
|
|
### Test File Locations
|
|
|
|
```
|
|
apps/backend/
|
|
├── src/
|
|
│ └── domain/
|
|
│ ├── entities/
|
|
│ │ └── rate-quote.entity.spec.ts # Unit test example
|
|
│ └── value-objects/
|
|
│ ├── email.vo.spec.ts
|
|
│ └── money.vo.spec.ts
|
|
├── test/
|
|
│ ├── integration/ # Infrastructure tests
|
|
│ │ ├── booking.repository.spec.ts
|
|
│ │ ├── redis-cache.adapter.spec.ts
|
|
│ │ └── maersk.connector.spec.ts
|
|
│ ├── app.e2e-spec.ts # E2E API tests
|
|
│ ├── jest-integration.json # Integration test config
|
|
│ └── setup-integration.ts # Test setup
|
|
└── load-tests/
|
|
└── rate-search.test.js # K6 load tests
|
|
|
|
apps/frontend/
|
|
└── e2e/
|
|
└── booking-workflow.spec.ts # Playwright E2E tests
|
|
```
|
|
|
|
### Running Tests in CI
|
|
|
|
Tests run automatically on GitHub Actions for all PRs:
|
|
- Linting & formatting check
|
|
- Backend unit tests
|
|
- Backend integration tests (with PostgreSQL + Redis services)
|
|
- Backend E2E tests
|
|
- Frontend tests
|
|
- Security scans
|
|
|
|
See [.github/workflows/ci.yml](.github/workflows/ci.yml) for full pipeline.
|
|
|
|
## Security Features (Phase 4)
|
|
|
|
**OWASP Top 10 Compliance**:
|
|
- ✅ Helmet.js security headers (CSP, HSTS, X-Frame-Options)
|
|
- ✅ Rate limiting (global: 100/min, auth: 5/min, search: 30/min)
|
|
- ✅ Brute-force protection (exponential backoff after 3 failed attempts)
|
|
- ✅ File upload validation (MIME, magic number, size limits)
|
|
- ✅ Password policy (12+ chars, complexity requirements)
|
|
- ✅ CORS with strict origin validation
|
|
- ✅ SQL injection prevention (TypeORM parameterized queries)
|
|
- ✅ XSS protection (CSP headers + input sanitization)
|
|
|
|
**Monitoring & Observability**:
|
|
- Sentry error tracking + APM (10% trace sampling)
|
|
- Performance monitoring interceptor (slow request alerts)
|
|
- Structured JSON logging with Pino
|
|
- WebSocket real-time carrier status updates
|
|
|
|
## Database Schema
|
|
|
|
**Key Tables**:
|
|
- `organizations` - Freight forwarders and carriers
|
|
- `users` - User accounts with RBAC roles
|
|
- `carriers` - Shipping line integrations (Maersk, MSC, CMA CGM, etc.)
|
|
- `ports` - 10k+ global ports (UN LOCODE)
|
|
- `rate_quotes` - Cached shipping rates (15min TTL)
|
|
- `bookings` - Container bookings (status workflow)
|
|
- `containers` - Container details (type, VGM, seal numbers)
|
|
- `shipments` - Real-time shipment tracking
|
|
- `audit_logs` - Compliance audit trail
|
|
|
|
**Migrations**: Located in `apps/backend/src/infrastructure/persistence/typeorm/migrations/`
|
|
|
|
See [apps/backend/DATABASE-SCHEMA.md](apps/backend/DATABASE-SCHEMA.md) for complete schema documentation.
|
|
|
|
## Environment Variables
|
|
|
|
### Required Variables
|
|
|
|
**Backend** (`apps/backend/.env`):
|
|
```bash
|
|
NODE_ENV=development
|
|
PORT=4000
|
|
DATABASE_HOST=localhost
|
|
DATABASE_PORT=5432
|
|
DATABASE_USER=xpeditis
|
|
DATABASE_PASSWORD=xpeditis_dev_password
|
|
DATABASE_NAME=xpeditis_dev
|
|
REDIS_HOST=localhost
|
|
REDIS_PORT=6379
|
|
REDIS_PASSWORD=xpeditis_redis_password
|
|
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
|
|
```
|
|
|
|
**Frontend** (`apps/frontend/.env.local`):
|
|
```bash
|
|
NEXT_PUBLIC_API_URL=http://localhost:4000
|
|
NEXT_PUBLIC_WS_URL=ws://localhost:4000
|
|
```
|
|
|
|
See `apps/backend/.env.example` and `apps/frontend/.env.example` for all available variables.
|
|
|
|
## API Documentation
|
|
|
|
**OpenAPI/Swagger**: http://localhost:4000/api/docs (when backend running)
|
|
|
|
**Key Endpoints**:
|
|
- `POST /api/v1/auth/login` - JWT authentication
|
|
- `POST /api/v1/auth/register` - User registration
|
|
- `POST /api/v1/rates/search` - Search shipping rates (cached 15min)
|
|
- `POST /api/v1/bookings` - Create booking
|
|
- `GET /api/v1/bookings` - List bookings (paginated)
|
|
- `GET /api/v1/bookings/:id` - Get booking details
|
|
- `GET /api/v1/carriers/:id/status` - Real-time carrier status
|
|
- `WS /carrier-status` - WebSocket for real-time updates
|
|
|
|
## Business Rules
|
|
|
|
**Critical Constraints**:
|
|
- Rate quotes expire after 15 minutes (Redis TTL)
|
|
- Carrier API timeout: 5 seconds per carrier
|
|
- Booking workflow: Maximum 4 steps
|
|
- Session timeout: 2 hours inactivity
|
|
- Rate search: <2s response time (90% with cache)
|
|
- Booking number format: `WCM-YYYY-XXXXXX` (6 alphanumeric chars)
|
|
- Cache hit target: >90% for common routes
|
|
- Multi-currency support: USD, EUR
|
|
|
|
**RBAC Roles**:
|
|
- `admin` - Full system access
|
|
- `manager` - Manage organization bookings + users
|
|
- `user` - Create and view own bookings
|
|
- `viewer` - Read-only access
|
|
|
|
## Common Development Tasks
|
|
|
|
### Adding a New Domain Entity
|
|
|
|
1. Create entity in `src/domain/entities/entity-name.entity.ts`
|
|
2. Create value objects if needed in `src/domain/value-objects/`
|
|
3. Write unit tests: `entity-name.entity.spec.ts`
|
|
4. Add repository port in `src/domain/ports/out/entity-name.repository.ts`
|
|
5. Create ORM entity in `src/infrastructure/persistence/typeorm/entities/`
|
|
6. Implement repository in `src/infrastructure/persistence/typeorm/repositories/`
|
|
7. Create mapper in `src/infrastructure/persistence/typeorm/mappers/`
|
|
8. Generate migration: `npm run migration:generate`
|
|
|
|
### Adding a New API Endpoint
|
|
|
|
1. Create DTO in `src/application/dto/feature-name.dto.ts`
|
|
2. Add endpoint to controller in `src/application/controllers/`
|
|
3. Add Swagger decorators (`@ApiOperation`, `@ApiResponse`)
|
|
4. Create domain service in `src/domain/services/` if needed
|
|
5. Write unit tests for domain logic
|
|
6. Write integration tests for infrastructure
|
|
7. Update Postman collection in `postman/`
|
|
|
|
### Adding a New Carrier Integration
|
|
|
|
1. Create connector in `src/infrastructure/carriers/carrier-name/`
|
|
2. Implement `CarrierConnectorPort` interface
|
|
3. Add request/response mappers
|
|
4. Implement circuit breaker (5s timeout)
|
|
5. Add retry logic with exponential backoff
|
|
6. Write integration tests
|
|
7. Update carrier seed data
|
|
8. Add API credentials to `.env.example`
|
|
|
|
## Documentation
|
|
|
|
**Architecture & Planning**:
|
|
- [ARCHITECTURE.md](ARCHITECTURE.md) - System architecture (5,800 words)
|
|
- [DEPLOYMENT.md](DEPLOYMENT.md) - Deployment guide (4,500 words)
|
|
- [PRD.md](PRD.md) - Product requirements
|
|
- [TODO.md](TODO.md) - 30-week development roadmap
|
|
|
|
**Implementation Summaries**:
|
|
- [PHASE4_SUMMARY.md](PHASE4_SUMMARY.md) - Security, monitoring, testing
|
|
- [PHASE3_COMPLETE.md](PHASE3_COMPLETE.md) - Booking workflow, exports
|
|
- [PHASE2_COMPLETE.md](PHASE2_COMPLETE.md) - Authentication, RBAC
|
|
- [PHASE-1-WEEK5-COMPLETE.md](PHASE-1-WEEK5-COMPLETE.md) - Rate search, cache
|
|
|
|
**Testing**:
|
|
- [TEST_EXECUTION_GUIDE.md](TEST_EXECUTION_GUIDE.md) - How to run all tests
|
|
- [TEST_COVERAGE_REPORT.md](TEST_COVERAGE_REPORT.md) - Coverage metrics
|
|
- [GUIDE_TESTS_POSTMAN.md](GUIDE_TESTS_POSTMAN.md) - Postman API tests
|
|
|
|
## Deployment
|
|
|
|
### Docker Build
|
|
|
|
```bash
|
|
# Build backend image
|
|
docker build -t xpeditis-backend:latest -f apps/backend/Dockerfile .
|
|
|
|
# Build frontend image
|
|
docker build -t xpeditis-frontend:latest -f apps/frontend/Dockerfile .
|
|
|
|
# Run with Docker Compose
|
|
docker-compose -f docker/portainer-stack-production.yml up -d
|
|
```
|
|
|
|
### Production Deployment (AWS)
|
|
|
|
See [DEPLOYMENT.md](DEPLOYMENT.md) for complete instructions:
|
|
- AWS RDS (PostgreSQL)
|
|
- AWS ElastiCache (Redis)
|
|
- AWS S3 (documents)
|
|
- AWS ECS/Fargate (containers)
|
|
- AWS ALB (load balancer)
|
|
- AWS CloudWatch (logs + metrics)
|
|
- Sentry (error tracking)
|
|
|
|
**CI/CD**: Automated via GitHub Actions
|
|
- Build and push Docker images
|
|
- Deploy to staging/production via Portainer
|
|
- Run smoke tests post-deployment
|
|
|
|
See [docker/PORTAINER_DEPLOYMENT_GUIDE.md](docker/PORTAINER_DEPLOYMENT_GUIDE.md) for Portainer setup.
|
|
|
|
## Performance Targets
|
|
|
|
- Rate search: <2s for 90% of requests (with cache)
|
|
- Rate search: <5s for 90% of requests (cache miss)
|
|
- Dashboard load: <1s for up to 5k bookings
|
|
- Email confirmation: Send within 3s of booking
|
|
- Cache hit ratio: >90% for top 100 trade lanes
|
|
- Carrier API timeout: 5s (with circuit breaker)
|
|
|
|
## Naming Conventions
|
|
|
|
**TypeScript**:
|
|
- Entities: `Booking`, `RateQuote` (PascalCase)
|
|
- Value Objects: `Email`, `Money`, `BookingNumber`
|
|
- Services: `BookingService`, `RateSearchService`
|
|
- Repositories: `BookingRepository` (interface in domain)
|
|
- Repository Implementations: `TypeOrmBookingRepository`
|
|
- DTOs: `CreateBookingDto`, `RateSearchRequestDto`
|
|
- Ports: `SearchRatesPort`, `CarrierConnectorPort`
|
|
|
|
**Files**:
|
|
- Entities: `booking.entity.ts`
|
|
- Value Objects: `email.vo.ts`
|
|
- Services: `booking.service.ts`
|
|
- Tests: `booking.service.spec.ts`
|
|
- ORM Entities: `booking.orm-entity.ts`
|
|
- Migrations: `1730000000001-CreateBookings.ts`
|
|
|
|
## Common Pitfalls to Avoid
|
|
|
|
❌ **DO NOT**:
|
|
- Import NestJS/TypeORM in domain layer
|
|
- Put business logic in controllers or repositories
|
|
- Use `any` type (strict mode enabled)
|
|
- Skip writing tests (coverage targets enforced)
|
|
- Use `DATABASE_SYNC=true` in production
|
|
- Commit `.env` files
|
|
- Expose sensitive data in API responses
|
|
- Skip rate limiting on public endpoints
|
|
- Use circular imports (leverage barrel exports)
|
|
|
|
✅ **DO**:
|
|
- Follow hexagonal architecture strictly
|
|
- Write tests for all new features (domain 90%+)
|
|
- Use TypeScript path aliases (`@domain/*`)
|
|
- Validate all DTOs with `class-validator`
|
|
- Implement circuit breakers for external APIs
|
|
- Cache frequently accessed data (Redis)
|
|
- Use structured logging (Pino)
|
|
- Document APIs with Swagger decorators
|
|
- Run migrations before deployment
|
|
|
|
## Support & Contribution
|
|
|
|
**Code Review Checklist**:
|
|
1. Hexagonal architecture principles followed
|
|
2. Domain layer has zero external dependencies
|
|
3. Unit tests written (90%+ coverage for domain)
|
|
4. Integration tests for infrastructure adapters
|
|
5. DTOs validated with class-validator
|
|
6. Swagger documentation updated
|
|
7. No secrets committed
|
|
8. TypeScript strict mode passes
|
|
9. Prettier formatting applied
|
|
10. ESLint passes with no warnings
|
|
|
|
**Getting Help**:
|
|
- Check existing documentation (ARCHITECTURE.md, DEPLOYMENT.md)
|
|
- Review Swagger API docs (http://localhost:4000/api/docs)
|
|
- Check GitHub Actions for CI failures
|
|
- Review Sentry for production errors
|