chore: Remove obsolete plans and skills documentation

- Deleted several outdated plan files related to cursor skills and microservices architecture, including plans for cursor skills, i18n adjustments, enterprise microservices, and event-driven architecture.
- Removed associated skill documentation files that are no longer relevant to the current project structure and standards.
- This cleanup helps streamline the documentation and maintain focus on active development areas.
This commit is contained in:
Ho Ngoc Hai
2026-01-14 10:11:08 +07:00
parent 7d6686c1a7
commit 4d69684fa4
50 changed files with 0 additions and 9798 deletions

View File

@@ -1,450 +0,0 @@
---
name: Create Cursor Skills
overview: Create 5 comprehensive Cursor Skills (400-500 lines each, English only) covering testing, API design, database, observability, and Kubernetes deployment patterns based on existing codebase patterns.
todos:
- id: create-testing-skill
content: Create testing-patterns skill with Jest config, mocking strategies, and test examples
status: completed
- id: create-api-skill
content: Create api-design skill with RESTful patterns, DTO validation, and OpenAPI docs
status: completed
- id: create-database-skill
content: Create database-prisma skill with repository pattern, migrations, and query optimization
status: completed
- id: create-observability-skill
content: Create observability-monitoring skill with metrics, logging, tracing, and health checks
status: completed
- id: create-kubernetes-skill
content: Create deployment-kubernetes skill with K8s manifests, HPA, and deployment strategies
status: completed
---
# Create Comprehensive Cursor Skills
## Overview
Create 5 detailed Cursor Skills (400-500 lines each, English only) to codify best practices and patterns from the GoodGo microservices platform. Each skill will be based on actual code patterns found in the codebase.
## Skills to Create
### 1. testing-patterns
**Location**: `.cursor/skills/testing-patterns/SKILL.md`
**Content Structure**:
- Jest configuration patterns (from [`services/_template/jest.config.ts`](services/_template/jest.config.ts))
- Test setup utilities (from [`services/_template/src/__tests__/setupTests.ts`](services/_template/src/__tests__/setupTests.ts))
- Unit testing patterns (from feature.service.test.ts, feature.repository.test.ts)
- Integration testing patterns (from health.controller.test.ts)
- E2E testing patterns (from feature.e2e.ts, health.e2e.ts)
- Mocking strategies:
- Prisma mocking
- Redis mocking
- Auth SDK mocking
- Logger mocking
- Test utilities (createMockReq, createMockRes, createMockNext)
- Coverage requirements (>70%)
- Common testing mistakes
- Debugging test failures
**Key Patterns to Document**:
```typescript
// Mock setup pattern
jest.mock('@goodgo/logger');
jest.mock('../feature.repository');
// Test structure pattern
describe('FeatureService', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should create feature successfully', async () => {
// Arrange
const mockData = {...};
(repository.create as jest.Mock).mockResolvedValue(mockData);
// Act
const result = await service.create(input);
// Assert
expect(repository.create).toHaveBeenCalledWith(input);
expect(result).toEqual(mockData);
});
});
```
### 2. api-design
**Location**: `.cursor/skills/api-design/SKILL.md`
**Content Structure**:
- RESTful conventions (resource naming, HTTP methods)
- Response format standards (from existing API responses)
- Error response structure (from [`services/_template/src/errors/`](services/_template/src/errors/))
- DTO validation with Zod (from [`services/_template/src/modules/feature/feature.dto.ts`](services/_template/src/modules/feature/feature.dto.ts))
- Controller patterns (from feature.controller.ts)
- Route organization (from feature.module.ts)
- OpenAPI/Swagger documentation (from [`services/_template/src/docs/swagger.ts`](services/_template/src/docs/swagger.ts))
- Pagination patterns
- Filtering and sorting
- API versioning (/api/v1/)
- Authentication headers
- Correlation ID propagation
**Key Patterns to Document**:
```typescript
// DTO with Zod
export const createFeatureDtoSchema = z.object({
name: z.string().min(1).max(100),
title: z.string().max(200).optional(),
});
// Controller pattern
export class FeatureController {
async create(req: Request, res: Response, next: NextFunction) {
const dto = createFeatureDtoSchema.parse(req.body);
const result = await this.service.create(dto);
res.status(201).json({ success: true, data: result });
}
}
// Route with middleware
router.post('/',
authenticate(),
authorize('admin'),
validateDto(createFeatureDtoSchema),
asyncHandler(controller.create)
);
```
### 3. database-prisma
**Location**: `.cursor/skills/database-prisma/SKILL.md`
**Content Structure**:
- Prisma schema conventions (from [`services/_template/prisma/schema.prisma`](services/_template/prisma/schema.prisma))
- Migration workflow (dev vs production)
- Seeding strategies (from [`services/_template/prisma/seed.ts`](services/_template/prisma/seed.ts))
- Repository pattern (from [`services/_template/src/modules/common/repository.ts`](services/_template/src/modules/common/repository.ts))
- BaseRepository implementation
- Feature-specific repositories (from feature.repository.ts)
- Connection pooling with Neon
- Transaction handling
- Query optimization
- Error handling (DatabaseError)
- Soft delete pattern
- Prisma Client generation
**Key Patterns to Document**:
```typescript
// BaseRepository pattern
export class BaseRepository<T, CreateInput, UpdateInput> {
constructor(
protected prisma: PrismaClient,
protected modelName: string,
protected delegate: any
) {}
async findById(id: string): Promise<T | null> {
try {
return await this.delegate.findUnique({ where: { id } });
} catch (error: any) {
throw new DatabaseError(`Failed to find ${this.modelName}`, { id });
}
}
}
// Feature-specific repository
export class FeatureRepository extends BaseRepository<Feature, CreateFeatureInput, UpdateFeatureInput> {
async findByName(name: string): Promise<Feature | null> {
return this.findByUnique({ name });
}
}
```
### 4. observability-monitoring
**Location**: `.cursor/skills/observability-monitoring/SKILL.md`
**Content Structure**:
- Prometheus metrics patterns (from [`services/_template/src/middlewares/metrics.middleware.ts`](services/_template/src/middlewares/metrics.middleware.ts))
- Metric types (Counter, Gauge, Histogram, Summary)
- Custom metrics creation
- Correlation ID middleware (from correlation.middleware.ts)
- Structured logging patterns (from logger.middleware.ts)
- Jaeger tracing integration
- Health check patterns (liveness vs readiness)
- Prometheus configuration (from [`infra/observability/prometheus/prometheus.yml`](infra/observability/prometheus/prometheus.yml))
- Grafana dashboard setup
- Loki log aggregation
- Alert rules
- Debugging with observability tools
**Key Patterns to Document**:
```typescript
// Metrics middleware pattern
const httpRequestDurationSeconds = new client.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'route', 'status_code', 'correlation_id'],
buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10],
});
// Correlation ID pattern
export const correlationMiddleware = () => {
return (req: Request, res: Response, next: NextFunction) => {
const correlationId = req.headers['x-correlation-id'] || generateCorrelationId();
req.correlationId = correlationId;
res.setHeader('X-Correlation-ID', correlationId);
next();
};
};
// Health check pattern
export class HealthController {
async liveness(req: Request, res: Response) {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
}
async readiness(req: Request, res: Response) {
const dbHealthy = await checkDatabaseConnection();
const redisHealthy = await checkRedisConnection();
res.json({ status: dbHealthy && redisHealthy ? 'ok' : 'degraded' });
}
}
```
### 5. deployment-kubernetes
**Location**: `.cursor/skills/deployment-kubernetes/SKILL.md`
**Content Structure**:
- Kubernetes manifest structure (from [`deployments/production/kubernetes/`](deployments/production/kubernetes/))
- Deployment configuration
- Service types (ClusterIP, LoadBalancer)
- ConfigMap and Secrets management (from configmap.yaml, secrets.yaml.example)
- Ingress configuration (from ingress.yaml)
- HorizontalPodAutoscaler setup
- Resource limits and requests
- Health probes (liveness, readiness, startup)
- Rolling update strategy
- Environment variable management
- Multi-environment setup (staging vs production)
- Namespace organization
- Service discovery in K8s
- Troubleshooting K8s deployments
**Key Patterns to Document**:
```yaml
# Deployment with HPA
apiVersion: apps/v1
kind: Deployment
metadata:
name: auth-service
namespace: production
spec:
replicas: 3
template:
spec:
containers:
- name: auth-service
image: goodgo/auth-service:latest
resources:
requests:
memory: "512Mi"
cpu: "500m"
limits:
memory: "1Gi"
cpu: "1000m"
livenessProbe:
httpGet:
path: /health/live
port: 5001
readinessProbe:
httpGet:
path: /health/ready
port: 5001
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: auth-service-hpa
spec:
scaleTargetRef:
kind: Deployment
name: auth-service
minReplicas: 3
maxReplicas: 10
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
```
## Implementation Plan
### Skill Structure Template
Each skill will follow this structure:
```markdown
---
name: skill-name
description: Brief description of when to use this skill
---
# Skill Title
## When to Use This Skill
Clear description of scenarios where this skill applies.
## Core Concepts
Key concepts and terminology.
## Patterns and Best Practices
### Pattern 1: Name
**Purpose**: What this pattern solves
**When to Use**: Specific scenarios
**Implementation**: Code example
**Common Mistakes**: What to avoid
### Pattern 2: Name
[Same structure...]
## Code Examples
### Example 1: Scenario
Full working example with explanation.
### Example 2: Scenario
[More examples...]
## Common Mistakes
List of anti-patterns and how to fix them.
## Troubleshooting
Common issues and solutions.
## Checklist
- [ ] Item 1
- [ ] Item 2
## Resources
Links to related docs and code.
```
## Content Sources
Each skill will extract patterns from:
1. **testing-patterns**:
- `services/_template/jest.config.ts`
- `services/_template/src/__tests__/setupTests.ts`
- `services/_template/src/modules/feature/__tests__/*.test.ts`
- `services/_template/src/__tests__/*.e2e.ts`
2. **api-design**:
- `services/_template/src/modules/feature/feature.dto.ts`
- `services/_template/src/modules/feature/feature.controller.ts`
- `services/_template/src/modules/feature/feature.module.ts`
- `services/_template/src/docs/swagger.ts`
- `services/_template/src/errors/`
3. **database-prisma**:
- `services/_template/prisma/schema.prisma`
- `services/_template/prisma/seed.ts`
- `services/_template/src/modules/common/repository.ts`
- `services/_template/src/modules/feature/feature.repository.ts`
- `services/_template/src/config/database.config.ts`
4. **observability-monitoring**:
- `services/_template/src/middlewares/metrics.middleware.ts`
- `services/_template/src/middlewares/correlation.middleware.ts`
- `services/_template/src/middlewares/logger.middleware.ts`
- `services/_template/src/modules/health/health.controller.ts`
- `infra/observability/prometheus/prometheus.yml`
5. **deployment-kubernetes**:
- `deployments/production/kubernetes/auth-service.yaml`
- `deployments/production/kubernetes/configmap.yaml`
- `deployments/production/kubernetes/secrets.yaml.example`
- `deployments/production/kubernetes/ingress.yaml`
- `deployments/staging/kubernetes/` (for comparison)
## Skill Features
Each skill will include:
- Clear "When to Use" section
- Real code examples from the codebase
- Common mistakes and anti-patterns
- Troubleshooting guide
- Checklist for implementation
- Links to related documentation
- Cross-references to other skills
## Quality Standards
- Length: 400-500 lines per skill
- Language: English only (technical content)
- Code examples: Working, tested patterns from codebase
- Format: Markdown with code blocks
- Structure: Consistent across all skills
- Practical: Focus on actionable patterns, not theory
## Expected Outcomes
After creating these skills, developers will have:
1. Clear testing patterns for unit, integration, and E2E tests
2. Standardized API design with validation and documentation
3. Database best practices with Prisma and repository pattern
4. Observability setup for metrics, logging, and tracing
5. Kubernetes deployment patterns for production
These skills will complement existing skills:
- `project-rules`: General architecture and standards
- `documentation`: How to write docs
- `comment-code`: Bilingual code comments
## Implementation Order
1. `testing-patterns` - Most frequently used
2. `api-design` - Every new feature needs this
3. `database-prisma` - Database work is common
4. `observability-monitoring` - Important for debugging
5. `deployment-kubernetes` - Less frequent but critical
Each skill will be self-contained and can be used independently.

File diff suppressed because it is too large Load Diff

View File

@@ -1,405 +0,0 @@
---
name: Event-Driven Architecture Skill
overview: Tạo skill documentation chi tiết cho Event-Driven Architecture với Apache Kafka, bao gồm patterns cho event publishing/consuming, schema versioning, tích hợp Traefik để expose events qua HTTP (SSE/WebSocket), error handling, observability, và testing patterns phù hợp với GoodGo platform standards.
todos:
- id: create-skill-file
content: Tạo file .cursor/skills/event-driven-architecture/SKILL.md với structure cơ bản (header, When to Use, Core Concepts)
status: completed
- id: kafka-setup-section
content: Viết section Kafka Setup & Configuration (infrastructure, client config, connection management)
status: completed
- id: publishing-patterns
content: Viết Event Publishing Patterns section (Publisher class, outbox pattern, best practices)
status: completed
- id: consuming-patterns
content: Viết Event Consuming Patterns section (Consumer class, DLQ, processing strategies)
status: completed
- id: schema-versioning
content: Viết Schema Versioning section (Schema Registry, Avro, evolution strategies)
status: completed
- id: traefik-integration
content: Viết Traefik Integration section (SSE endpoints, WebSocket, routing config)
status: completed
- id: error-resilience
content: Viết Error Handling & Resilience section (error patterns, retries, DLQ, replay)
status: completed
- id: observability
content: Viết Observability section (logging events, metrics, tracing)
status: completed
- id: testing-patterns
content: Viết Testing Patterns section (unit, integration, E2E với test containers)
status: completed
- id: best-practices-examples
content: Viết Best Practices section và Complete Examples (end-to-end flows)
status: completed
- id: review-integration
content: Review và ensure consistency với existing skills, add references, final polish
status: completed
---
# Event-Driven Architecture Skill Implementation Plan
## Overview
Tạo comprehensive skill documentation cho Event-Driven Architecture patterns sử dụng Apache Kafka làm message broker. Skill này sẽ cover event publishing, consuming, schema versioning, integration với Traefik (SSE/WebSocket), error handling, observability, và testing patterns theo chuẩn GoodGo.
## Architecture Context
**Tech Stack:**
- **Message Broker**: Apache Kafka (high-throughput, streaming)
- **API Gateway**: Traefik (existing) - expose events qua HTTP/SSE/WebSocket
- **Schema Registry**: Confluent Schema Registry (Avro schemas)
- **Services**: Node.js/TypeScript microservices với Express
- **Libraries**: kafkajs (Node.js Kafka client), @goodgo/logger, @goodgo/tracing
**Traefik Integration:**
- Traefik vẫn giữ vai trò API Gateway cho synchronous HTTP/REST
- Thêm support expose event streams qua HTTP endpoints (Server-Sent Events / WebSocket)
- Services publish events vào Kafka, Traefik routes SSE/WebSocket requests tới event streaming endpoints
## Files to Create/Update
### Primary File
- `.cursor/skills/event-driven-architecture/SKILL.md` - Main skill documentation (new)
### Potential Updates (if needed)
- `.cursor/skills/project-rules/SKILL.md` - Update infrastructure section to include Kafka
- `docs/en/architecture/service-communication.md` - Add event-driven communication section
- `docs/vi/architecture/service-communication.md` - Add event-driven communication section
## Detailed Implementation Plan
### Phase 1: Skill File Structure
Tạo file `.cursor/skills/event-driven-architecture/SKILL.md` với structure:
1. **Header Metadata**
- name: event-driven-architecture
- description: Event-driven architecture patterns với Kafka
2. **When to Use This Skill** section
- Khi nào nên dùng event-driven patterns
- Use cases: async processing, decoupling services, event sourcing, CQRS
3. **Core Concepts**
- Event-driven vs request-response
- Kafka fundamentals (topics, partitions, consumer groups)
- Event schema versioning
- Traefik integration for event streaming
### Phase 2: Kafka Setup & Configuration
**Topics Covered:**
- Kafka infrastructure setup (docker-compose, Kubernetes)
- KafkaJS client configuration
- Connection management và pooling
- Environment variables (KAFKA_BROKERS, KAFKA_CLIENT_ID, etc.)
**Code Examples:**
```typescript
// Kafka client setup
// Producer configuration
// Consumer configuration
// Connection error handling
```
### Phase 3: Event Publishing Patterns
**Topics:**
- Event structure và naming conventions
- Publisher service pattern
- Transactional publishing (outbox pattern)
- Idempotency keys
- Event correlation IDs
- Publishing best practices
**Patterns:**
- Simple event publisher
- Transactional publisher với outbox pattern
- Batch publishing
- Error handling và retries
**Code Examples:**
```typescript
// EventPublisher class
// Publishing events from services
// Outbox pattern implementation
// Event metadata (correlationId, traceId, timestamp)
```
### Phase 4: Event Consuming Patterns
**Topics:**
- Consumer service patterns
- Consumer groups và partition assignment
- Processing strategies (at-least-once, exactly-once)
- Commit strategies
- Dead letter queue (DLQ) pattern
- Consumer error handling
**Patterns:**
- Simple consumer
- Batch consumer
- Transactional consumer
- DLQ handling
- Retry patterns với exponential backoff
**Code Examples:**
```typescript
// EventConsumer class
// Consumer group management
// Message processing với error handling
// DLQ implementation
```
### Phase 5: Schema Versioning & Registry
**Topics:**
- Schema Registry setup (Confluent)
- Avro schema definitions
- Schema evolution (backward/forward compatible)
- Schema versioning strategy
- Schema validation
**Code Examples:**
```typescript
// Schema definitions
// Schema registry integration
// Schema evolution examples
// Validation patterns
```
### Phase 6: Traefik Integration (SSE/WebSocket)
**Topics:**
- Exposing events qua HTTP endpoints
- Server-Sent Events (SSE) pattern
- WebSocket support (optional)
- Traefik routing configuration
- Authentication/authorization cho event streams
- Rate limiting cho event streams
**Patterns:**
- SSE endpoint implementation
- Event filtering và subscription
- Connection management
- Traefik labels configuration
**Code Examples:**
```typescript
// SSE endpoint implementation
// Event stream service
// Traefik routing config
// Client subscription patterns
```
### Phase 7: Error Handling & Resilience
**Topics:**
- Event publishing failures
- Consumer error handling
- Retry strategies
- Circuit breaker cho Kafka operations
- Dead letter queue management
- Event replay patterns
**Integration với existing skills:**
- Reuse resilience-patterns (circuit breaker, retry)
- Reuse error-handling-patterns (custom errors)
**Code Examples:**
```typescript
// Error handling trong publisher
// Error handling trong consumer
// DLQ processing
// Event replay service
```
### Phase 8: Observability
**Topics:**
- Logging events (structured logging)
- Metrics (events published/consumed, lag, throughput)
- Distributed tracing với OpenTelemetry
- Health checks cho Kafka connectivity
- Monitoring consumer lag
**Integration:**
- Use @goodgo/logger
- Use @goodgo/tracing
- Prometheus metrics
**Code Examples:**
```typescript
// Event logging
// Metrics collection
// Tracing events
// Health check endpoints
```
### Phase 9: Testing Patterns
**Topics:**
- Unit testing publishers/consumers
- Integration testing với Kafka
- Test containers cho local testing
- Mocking Kafka trong tests
- E2E event flow testing
**Code Examples:**
```typescript
// Unit test examples
// Integration test setup
// Test containers usage
// Mocking strategies
```
### Phase 10: Best Practices & Patterns
**Topics:**
- Event naming conventions (`domain.action.version`)
- Topic naming (`domain.entity.action`)
- Partition key selection
- Event ordering guarantees
- Event size limits
- Performance optimization
- Common anti-patterns to avoid
**Examples:**
- Complete event flow example
- Service integration examples
- Real-world use cases
### Phase 11: Documentation Examples
**Complete Examples:**
1. UserCreated event flow (Auth Service → Notification Service)
2. OrderPlaced event với multiple consumers
3. SSE endpoint với filtering
4. Outbox pattern implementation
5. Event replay scenario
**Integration Examples:**
- Service publishing events
- Service consuming events
- Traefik routing SSE endpoints
- Error recovery flows
## Skill File Structure (Detailed Outline)
```markdown
---
name: event-driven-architecture
description: Event-driven architecture patterns with Apache Kafka for GoodGo microservices. Use when implementing async communication, event publishing/consuming, event sourcing, CQRS, or integrating event streams with HTTP endpoints.
---
# Event-Driven Architecture Patterns
## When to Use This Skill
[Use cases và scenarios]
## Core Concepts
[Event-driven fundamentals, Kafka basics, Traefik integration]
## Kafka Setup & Configuration
[Infrastructure, client setup, configuration]
## Event Publishing Patterns
[Publisher patterns, outbox pattern, best practices]
## Event Consuming Patterns
[Consumer patterns, DLQ, processing strategies]
## Schema Versioning
[Schema Registry, Avro, evolution strategies]
## Traefik Integration (SSE/WebSocket)
[Exposing events via HTTP, SSE endpoints, routing]
## Error Handling & Resilience
[Error patterns, retries, DLQ, replay]
## Observability
[Logging, metrics, tracing events]
## Testing Patterns
[Unit, integration, E2E testing]
## Best Practices
[Naming conventions, patterns, anti-patterns]
## Complete Examples
[End-to-end examples]
## Resources
[Links to related skills, docs]
```
## Key Design Decisions
1. **Kafka over RabbitMQ**: User selected Kafka for high-throughput and streaming capabilities
2. **Traefik Integration**: Expose events via SSE/WebSocket through Traefik, keeping Traefik as API Gateway
3. **Schema Registry**: Use Confluent Schema Registry với Avro for schema versioning
4. **Outbox Pattern**: Include outbox pattern for transactional event publishing
5. **Consistency với existing skills**: Reuse patterns từ resilience-patterns, error-handling-patterns, observability-monitoring
## Dependencies & Integration Points
**Existing Skills to Reference:**
- `resilience-patterns` - Circuit breaker, retry patterns
- `error-handling-patterns` - Error classes và handling
- `observability-monitoring` - Logging, metrics, tracing
- `middleware-patterns` - SSE endpoint middleware
- `project-rules` - Coding standards, naming conventions
**Infrastructure:**
- Kafka cluster setup (docker-compose, K8s)
- Schema Registry setup
- Traefik configuration updates
## Acceptance Criteria
- [ ] Skill file created với comprehensive coverage
- [ ] All code examples are working và follow GoodGo patterns
- [ ] Bilingual comments (EN/VI) trong code examples
- [ ] Integration examples với Traefik SSE/WebSocket
- [ ] Error handling patterns documented
- [ ] Observability patterns documented
- [ ] Testing patterns documented
- [ ] References to related skills
- [ ] Complete end-to-end examples
- [ ] Consistent với existing skill format và style

View File

@@ -1,270 +0,0 @@
---
name: Fix Template Structure
overview: Restructure services/_template to align with microservices platform architecture by removing duplicate Docker/Traefik configs and refactoring ARCHITECTURE.md to focus on single service context with platform integration.
todos:
- id: delete-docker-compose
content: Delete docker-compose.yml and docker-compose.prod.yml from services/_template/
status: completed
- id: delete-traefik-config
content: Delete services/_template/traefik/ directory
status: completed
- id: refactor-architecture-md
content: "Refactor ARCHITECTURE.md with clear sections: Single Service Architecture, Platform Integration, Deployment Context"
status: completed
- id: update-readme-deployment
content: Update README.md to remove Docker Development option and add Platform Integration section
status: completed
- id: update-readme-traefik
content: Update README.md Traefik references to point to infra/traefik/ and explain Docker labels
status: completed
---
# Fix Template Structure for Microservices Platform
## Problem Summary
The `services/_template` currently contains configurations that conflict with the platform-level setup:
1. Docker Compose files that duplicate `deployments/local/docker-compose.yml` functionality
2. Traefik configuration that duplicates `infra/traefik/` global config
3. ARCHITECTURE.md that describes multi-service architecture instead of single service template
## Proposed Changes
### 1. Remove Docker Compose Files
**Files to delete:**
- [`services/_template/docker-compose.yml`](services/_template/docker-compose.yml) - Full environment setup (conflicts with deployments/local/)
- [`services/_template/docker-compose.prod.yml`](services/_template/docker-compose.prod.yml) - Production overrides (should be in deployments/)
**File to keep:**
- [`services/_template/docker-compose.test.yml`](services/_template/docker-compose.test.yml) - Isolated test environment (useful for CI/CD)
**Rationale:**
- Template services should be deployed via `deployments/local/docker-compose.yml`
- Individual services don't need their own compose files for orchestration
- Test compose file is legitimate for isolated testing
### 2. Remove Duplicate Traefik Configuration
**Directory to delete:**
- `services/_template/traefik/` - Contains duplicate traefik.yml and dynamic.yml
**Rationale:**
- Traefik is a platform-level API Gateway managed at `infra/traefik/`
- Service discovery happens via Docker labels in `deployments/local/docker-compose.yml`
- Services don't configure Traefik directly; they register via labels
**Example of correct pattern:**
```yaml
# In deployments/local/docker-compose.yml
services:
my-service:
labels:
- "traefik.enable=true"
- "traefik.http.routers.my-service.rule=PathPrefix(`/api/v1/my-service`)"
- "traefik.http.services.my-service.loadbalancer.server.port=5000"
```
### 3. Refactor ARCHITECTURE.md
**Current issues:**
- Shows multi-service architecture (Auth, User, Product, Order, Payment)
- Mixes single service internals with platform-level concerns
- Unclear context about what the template represents
**New structure:**
```markdown
# Service Template Architecture
## Part 1: Single Service Architecture (Internal)
- Component layers: Controller → Service → Repository
- Middleware chain: Correlation → Auth → Validation → Error → Logger → Metrics
- Data flow within one service
- Internal dependencies: Database, Redis, Jaeger client
## Part 2: Platform Integration (External)
- How this service fits in the microservices platform
- Integration with Traefik API Gateway (via Docker labels)
- Shared infrastructure: Redis, PostgreSQL, Observability stack
- Service discovery and registration
- Inter-service communication patterns
## Part 3: Deployment Context
- Reference to deployments/local/docker-compose.yml
- How to add this service to the platform
- Environment variables and configuration
```
**Diagrams to update:**
1. **Internal Service Architecture** - Focus on single service layers
```mermaid
graph TD
Request[HTTP Request] --> Traefik[Traefik Gateway]
Traefik -->|Routes to Service| Middleware[Middleware Chain]
subgraph SingleService[Single Service Boundary]
Middleware --> Correlation[Correlation ID]
Correlation --> Auth[Authentication]
Auth --> Validation[Validation]
Validation --> Router[Router]
Router --> Controller[Controller]
Controller --> Service[Service Layer]
Service --> Repository[Repository]
Repository --> Database[(PostgreSQL)]
Service --> Cache[(Redis)]
end
Service -.->|Metrics| Prometheus[Prometheus]
Service -.->|Traces| Jaeger[Jaeger]
```
2. **Platform Integration** - Show how service fits in ecosystem
```mermaid
graph TD
Client[Client] --> Traefik[Traefik API Gateway]
subgraph Platform[Microservices Platform]
Traefik --> AuthService[Auth Service]
Traefik --> YourService[Your Service from Template]
Traefik --> OtherService[Other Services]
YourService --> SharedDB[(Shared PostgreSQL)]
YourService --> SharedRedis[(Shared Redis)]
AuthService -.->|JWT Validation| YourService
end
subgraph Observability[Observability Stack]
Prometheus[Prometheus]
Grafana[Grafana]
Jaeger[Jaeger]
Loki[Loki]
end
YourService -.->|Metrics| Prometheus
YourService -.->|Traces| Jaeger
YourService -.->|Logs| Loki
```
### 4. Update README.md References
**Changes needed in [`services/_template/README.md`](services/_template/README.md):**
1. Remove "Option 2: Docker Development" section (lines 73-91)
- This references the deleted docker-compose.yml
- Replace with reference to platform deployment
2. Update "Getting Started" section:
- Point to `deployments/local/docker-compose.yml` for full platform
- Explain how to add this service to the platform
- Keep local development instructions (without docker-compose)
3. Remove "Docker Compose Files" section (lines 472-476)
- Only docker-compose.test.yml remains
4. Update "Traefik API Gateway" section (lines 494+)
- Remove references to local traefik/ directory
- Point to `infra/traefik/` for configuration
- Explain Docker labels for service registration
**New section to add:**
````markdown
## Adding This Service to the Platform
### 1. Add to deployments/local/docker-compose.yml
```yaml
services:
your-service:
build:
context: ../..
dockerfile: services/your-service/Dockerfile
container_name: your-service-local
environment:
- NODE_ENV=development
- PORT=5002
- DATABASE_URL=${DATABASE_URL}
- REDIS_HOST=redis
- JWT_SECRET=${JWT_SECRET}
depends_on:
redis:
condition: service_healthy
networks:
- microservices-network
labels:
- "traefik.enable=true"
- "traefik.http.routers.your-service.rule=PathPrefix(`/api/v1/your-service`)"
- "traefik.http.services.your-service.loadbalancer.server.port=5002"
````
### 2. Start the Platform
```bash
cd deployments/local
docker-compose up -d
```
### 3. Access Your Service
- API: http://localhost/api/v1/your-service
- Health: http://localhost/api/v1/your-service/health
- Docs: http://localhost/api/v1/your-service/api-docs
```
## Implementation Steps
1. Delete `services/_template/docker-compose.yml`
2. Delete `services/_template/docker-compose.prod.yml`
3. Delete `services/_template/traefik/` directory
4. Refactor `services/_template/ARCHITECTURE.md`:
- Add clear section headers for Single Service vs Platform Integration
- Update diagrams to show correct context
- Add deployment context section
5. Update `services/_template/README.md`:
- Remove Docker Development option
- Remove Docker Compose Files section
- Update Traefik references
- Add "Adding This Service to the Platform" section
6. Keep `services/_template/docker-compose.test.yml` for isolated testing
## Files Affected
- Delete: `services/_template/docker-compose.yml`
- Delete: `services/_template/docker-compose.prod.yml`
- Delete: `services/_template/traefik/traefik.yml`
- Delete: `services/_template/traefik/dynamic.yml`
- Modify: `services/_template/ARCHITECTURE.md`
- Modify: `services/_template/README.md`
- Keep: `services/_template/docker-compose.test.yml`
- Keep: `services/_template/Dockerfile`
## Expected Outcome
After these changes:
1. Template structure clearly represents a single microservice
2. No confusion about deployment - services are added to `deployments/local/docker-compose.yml`
3. Traefik configuration is centralized at `infra/traefik/`
4. ARCHITECTURE.md clearly separates internal service architecture from platform integration
5. Developers understand how to use the template in the microservices platform context

View File

@@ -1,905 +0,0 @@
---
name: IAM Service Audit Plan
overview: "Kế hoạch kiểm tra toàn diện cho IAM Service bao gồm: logic nghiệp vụ, quy trình build, bảo mật, và triển khai môi trường dev/staging/production. Plan được chia thành 6 phases: Pre-deployment Audit, Security Fixes, Local Environment, Staging Deployment, Production Deployment, và Post-deployment."
todos:
- id: audit-auth-1
content: "Review Authentication Module - Registration Flow: Check email validation, password hashing with bcrypt cost 12, user profile creation in services/iam-service/src/modules/auth/auth.service.ts"
status: completed
- id: audit-auth-2
content: "Review Authentication Module - Login Flow: Check password verification, JWT generation (access + refresh), session creation, MFA integration in services/iam-service/src/modules/auth/auth.service.ts"
status: completed
- id: audit-auth-3
content: "Review Authentication Module - Token Refresh: Check token family tracking, refresh token rotation, replay attack detection in services/iam-service/src/modules/token/jwt.service.ts"
status: completed
- id: audit-auth-4
content: "Review Authentication Module - Password Change: Check refresh token revocation, audit logging in services/iam-service/src/modules/auth/change-password.service.ts"
status: completed
- id: audit-rbac-1
content: "Review RBAC Module - Permission Resolution: Check hierarchy (Direct user → Role → Group → Policy) in services/iam-service/src/modules/rbac/rbac.service.ts"
status: completed
- id: audit-rbac-2
content: "Review RBAC Module - Role Assignment: Check expiration handling in services/iam-service/src/modules/rbac/rbac.service.ts"
status: completed
- id: audit-rbac-3
content: "Review RBAC Module - Policy Engine: Check JSON Logic implementation in services/iam-service/src/modules/rbac/policy.engine.ts"
status: completed
- id: audit-rbac-4
content: "Review RBAC Module - Permission Caching: Verify 5 min TTL and cache invalidation in services/iam-service/src/core/cache/cache.service.ts"
status: completed
- id: audit-identity-1
content: "Review Identity Module - User Management: Check CRUD operations, bulk import/export in services/iam-service/src/modules/identity/user/user.service.ts"
status: completed
- id: audit-identity-2
content: "Review Identity Module - Profile Management: Check custom fields, avatar upload/delete in services/iam-service/src/modules/identity/profile/profile.service.ts"
status: completed
- id: audit-identity-3
content: "Review Identity Module - Verification: Check email/phone/document verification flows in services/iam-service/src/modules/identity/verification/verification.service.ts"
status: completed
- id: audit-identity-4
content: "Review Identity Module - Organizations: Check multi-tenant support, hierarchical structure in services/iam-service/src/modules/identity/organization/organization.service.ts"
status: completed
- id: audit-identity-5
content: "Review Identity Module - Groups: Check member management, group-based permissions in services/iam-service/src/modules/identity/group/group.service.ts"
status: completed
- id: audit-access-1
content: "Review Access Module - Access Requests: Check workflow, approval chains, JIT access in services/iam-service/src/modules/access/request/request.service.ts"
status: completed
- id: audit-access-2
content: "Review Access Module - Access Reviews: Check certification campaigns, automated cleanup in services/iam-service/src/modules/access/review/review.service.ts"
status: completed
- id: audit-access-3
content: "Review Access Module - Access Analytics: Check usage tracking, risk identification in services/iam-service/src/modules/access/analytics/analytics.service.ts"
status: completed
- id: audit-mfa-1
content: "Review MFA Module - TOTP: Check TOTP implementation using speakeasy library in services/iam-service/src/modules/mfa/mfa.service.ts"
status: completed
- id: audit-mfa-2
content: "Review MFA Module - QR Code: Check QR code generation in services/iam-service/src/modules/mfa/mfa.service.ts"
status: completed
- id: audit-mfa-3
content: "Review MFA Module - WebAuthn: Check WebAuthn support in services/iam-service/src/modules/mfa/mfa.service.ts"
status: completed
- id: audit-mfa-4
content: "Review MFA Module - Multiple Devices: Check multiple devices per user support in services/iam-service/src/modules/mfa/mfa.service.ts"
status: completed
- id: audit-mfa-5
content: "Review MFA Module - Recovery Flow: Verify MFA recovery flow exists (NOTE: Currently missing, needs review)"
status: completed
- id: audit-social-1
content: "Review Social Authentication Module: Check Google/Facebook/GitHub OAuth flows, account linking, token refresh in services/iam-service/src/modules/social/social.service.ts"
status: completed
- id: audit-oidc-1
content: "Review OIDC Provider Module: Check discovery endpoint, authorization code flow, token exchange, JWKS endpoint in services/iam-service/src/modules/oidc/oidc-provider.service.ts"
status: completed
- id: audit-session-1
content: "Review Session Management Module: Check device fingerprinting, session expiration, revocation, activity tracking in services/iam-service/src/modules/session/session.service.ts"
status: completed
- id: audit-governance-1
content: "Review Governance Module: Check compliance reporting (GDPR, SOC2, ISO27001), policy management, risk scoring in services/iam-service/src/modules/governance/"
status: completed
- id: audit-cache-1
content: "Review Cache Service: Check multi-layer caching (L1: Memory, L2: Redis, L3: DB), cache warming, invalidation in services/iam-service/src/core/cache/cache.service.ts"
status: completed
- id: audit-events-1
content: "Review Event Sourcing: Check audit logging for all security events, 7-year retention in services/iam-service/src/core/events/"
status: completed
- id: audit-build-1
content: "Run TypeScript typecheck: cd services/iam-service && pnpm typecheck - Verify no TypeScript errors"
status: completed
- id: audit-build-2
content: "Run TypeScript build: cd services/iam-service && pnpm build - Verify build succeeds, check for unused variables/imports"
status: completed
- id: audit-build-3
content: "Verify Type Safety: Check type safety for Prisma models, verify path aliases (@/*) working correctly"
status: completed
- id: audit-lint-1
content: "Run ESLint: cd services/iam-service && pnpm lint - Verify coding standards compliance"
status: completed
- id: audit-lint-2
content: "Check Code Quality: Verify no console.log in production code, proper error handling, no security anti-patterns"
status: completed
- id: audit-prisma-1
content: "Generate Prisma Client: cd services/iam-service && pnpm prisma:generate - Verify generation succeeds"
status: completed
- id: audit-prisma-2
content: "Validate Prisma Schema: Verify schema syntax valid, all relations properly defined, indexes optimized, migration files consistent"
status: completed
- id: audit-test-1
content: "Run Unit Tests: cd services/iam-service && pnpm test:unit - Verify all unit tests pass"
status: completed
- id: audit-test-2
content: "Run E2E Tests: cd services/iam-service && pnpm test:e2e - Verify all E2E tests pass"
status: completed
- id: audit-test-3
content: "Generate Test Coverage: cd services/iam-service && pnpm test:coverage - Verify coverage >= 70% (branches, functions, lines, statements)"
status: completed
- id: audit-docker-1
content: "Build Docker Image: docker build -t iam-service:test -f services/iam-service/Dockerfile . - Verify multi-stage build succeeds"
status: completed
- id: audit-docker-2
content: "Verify Docker Image: Check image size <500MB, non-root user configured, health check functional"
status: completed
- id: security-mfa-1
content: "CRITICAL: Create Encryption Service - Create services/iam-service/src/core/security/encryption.service.ts with encrypt/decrypt functions using crypto module"
status: completed
- id: security-mfa-2
content: "CRITICAL: Update Schema for MFA Encryption - Update prisma/schema.prisma to support encrypted MFA secret fields (add encrypted field or use existing secret field with encryption layer)"
status: completed
- id: security-mfa-3
content: "CRITICAL: Update MFA Service - Update services/iam-service/src/modules/mfa/mfa.service.ts to encrypt MFA secrets before saving and decrypt when reading"
status: completed
- id: security-refresh-1
content: "CRITICAL: Hash Refresh Tokens - Update services/iam-service/src/modules/token/jwt.service.ts to hash refresh tokens (SHA-256) before storing in database"
status: completed
- id: security-refresh-2
content: "CRITICAL: Update Refresh Token Validation - Update refresh token validation logic in jwt.service.ts to compare hashes instead of plaintext tokens"
status: completed
- id: security-jwt-1
content: "CRITICAL: Block Default JWT Secrets - Update services/iam-service/src/config/jwt.config.ts to throw error if default secrets are used when NODE_ENV === 'production'"
status: completed
- id: security-input-1
content: "MEDIUM: Install DOMPurify: cd services/iam-service && pnpm add dompurify @types/dompurify"
status: completed
- id: security-input-2
content: "MEDIUM: Update Input Sanitization - Update services/iam-service/src/utils/helpers.ts sanitizeInput function to use DOMPurify instead of simple < > removal"
status: completed
- id: security-password-1
content: "MEDIUM: Add Password Complexity Schema - Update services/iam-service/src/modules/auth/auth.dto.ts RegisterDto to enforce: uppercase, lowercase, numbers, symbols (minimum 8 characters)"
status: completed
- id: security-password-2
content: "MEDIUM: Update Change Password Schema - Update services/iam-service/src/modules/auth/auth.dto.ts ChangePasswordDto to enforce same password complexity rules"
status: completed
- id: security-fingerprint-1
content: "MEDIUM: Install FingerprintJS: cd services/iam-service && pnpm add @fingerprintjs/fingerprintjs"
status: completed
- id: security-fingerprint-2
content: "MEDIUM: Update Device Fingerprinting - Update services/iam-service/src/modules/token/cookie.service.ts to use @fingerprintjs/fingerprintjs library instead of basic User-Agent + IP hash"
status: skipped
- id: security-lockout-1
content: "MEDIUM: Add Lockout Fields to Schema - Update prisma/schema.prisma User model to add failedLoginAttempts (Int, default 0) and lockedUntil (DateTime?) fields"
status: completed
- id: security-lockout-2
content: "MEDIUM: Create Account Lockout Service - Create services/iam-service/src/modules/auth/account-lockout.service.ts with lockout logic and exponential backoff"
status: completed
- id: security-lockout-3
content: "MEDIUM: Update Auth Service for Lockout - Update services/iam-service/src/modules/auth/auth.service.ts to track failed attempts and check lockout status before login"
status: completed
- id: security-lockout-4
content: "MEDIUM: Create Lockout Migration - Create Prisma migration for failedLoginAttempts and lockedUntil fields"
status: completed
- id: security-audit-1
content: "LOW: Run npm audit: cd services/iam-service && npm audit - Review vulnerabilities"
status: completed
- id: security-audit-2
content: "LOW: Fix npm vulnerabilities: cd services/iam-service && npm audit fix - Apply fixes for vulnerabilities"
status: completed
- id: security-cors-1
content: "LOW: Review CORS Configuration - Check services/iam-service/src/main.ts CORS settings, verify necessity of credentials enabled"
status: pending
- id: security-social-1
content: "LOW: Review Social Token Storage - Check services/iam-service/prisma/schema.prisma SocialAccount model, consider encryption for accessToken and refreshToken fields"
status: pending
- id: security-backup-1
content: "LOW: Design MFA Backup Codes - Design backup codes generation and storage strategy for MFA recovery scenarios"
status: pending
- id: local-env-1
content: "Copy Environment File: cp deployments/local/env.local.example deployments/local/.env.local"
status: completed
- id: local-env-2
content: "Update DATABASE_URL: Set DATABASE_URL in deployments/local/.env.local to Neon PostgreSQL connection string"
status: completed
- id: local-env-3
content: "Update REDIS_URL: Set REDIS_URL in deployments/local/.env.local to redis://localhost:6379"
status: completed
- id: local-env-4
content: "Generate JWT Secrets: Generate new JWT_SECRET, JWT_REFRESH_SECRET, JWT_ID_SECRET (NOT defaults) and update deployments/local/.env.local"
status: completed
- id: local-env-5
content: "Update Social Auth Credentials: Set Google/Facebook/GitHub OAuth credentials in deployments/local/.env.local"
status: skipped
- id: local-docker-1
content: "Start Docker Compose: cd deployments/local && docker-compose up -d"
status: completed
- id: local-docker-2
content: "Verify Docker Services: Check Traefik, IAM Service, Redis, PostgreSQL containers are running successfully"
status: completed
- id: local-migrate-1
content: "Run Prisma Migrate: cd services/iam-service && pnpm prisma:migrate - Verify migrations apply successfully"
status: completed
- id: local-migrate-2
content: "Run Prisma Seed: cd services/iam-service && pnpm prisma:seed - Verify seed data is created"
status: completed
- id: local-verify-1
content: "Test Traefik Dashboard: Open http://localhost:8080 and verify Traefik dashboard loads"
status: completed
- id: local-verify-2
content: "Test IAM Service: Open http://localhost:5001 and verify service is accessible"
status: completed
- id: local-verify-3
content: "Test API Gateway: Test http://localhost/api/v1/auth endpoint"
status: completed
- id: local-verify-4
content: "Test Redis: Verify Redis connection on localhost:6379"
status: completed
- id: local-health-1
content: "Test Liveness Endpoint: curl http://localhost:5001/health/live - Verify returns 200 OK"
status: completed
- id: local-health-2
content: "Test Readiness Endpoint: curl http://localhost:5001/health/ready - Verify returns 200 OK (includes DB check)"
status: completed
- id: local-health-3
content: "Test Metrics Endpoint: curl http://localhost:5001/metrics - Verify Prometheus metrics are returned"
status: completed
- id: local-test-1
content: "Test Registration Flow: Register new user via API, verify email validation, password hashing, profile creation"
status: completed
- id: local-test-2
content: "Test Login Flow: Login with registered user, verify JWT tokens, session creation"
status: completed
- id: local-test-3
content: "Test Logout Flow: Logout user, verify session revocation"
status: skipped
- id: local-test-4
content: "Test Authorization: Test RBAC/ABAC permissions with different user roles"
status: skipped
- id: local-test-5
content: "Test MFA: Test TOTP setup, QR code generation, WebAuthn if implemented"
status: skipped
- id: local-test-6
content: "Test Social Login: Test Google/Facebook/GitHub OAuth flows"
status: skipped
- id: local-test-7
content: "Review Logs and Metrics: Check application logs and Prometheus metrics for errors"
status: completed
- id: staging-k8s-1
content: "Create Staging Namespace: kubectl create namespace staging"
status: skipped
- id: staging-k8s-2
content: "Create Staging Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='...' --from-literal=jwt-refresh-secret='...' -n staging"
status: skipped
- id: staging-k8s-3
content: "Apply Staging ConfigMap: kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml"
status: skipped
- id: staging-k8s-4
content: "Deploy Staging Service: kubectl apply -f deployments/staging/kubernetes/iam-service.yaml"
status: skipped
- id: staging-k8s-5
content: "Apply Staging Ingress: kubectl apply -f deployments/staging/kubernetes/ingress.yaml"
status: skipped
- id: staging-migrate-1
content: "Run Staging Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy - Verify migrations apply successfully"
status: skipped
- id: staging-verify-1
content: "Check Staging Pods: kubectl get pods -n staging - Verify pods are running"
status: skipped
- id: staging-verify-2
content: "Check Staging Logs: kubectl logs -f deployment/iam-service -n staging - Review logs for errors"
status: skipped
- id: staging-verify-3
content: "Describe Staging Pod: kubectl describe pod <pod-name> -n staging - Verify pod status and events"
status: skipped
- id: staging-test-1
content: "Run Staging Smoke Tests: Execute basic API endpoint tests (health, auth endpoints)"
status: skipped
- id: staging-test-2
content: "Run Performance Tests: Execute performance tests on staging environment"
status: skipped
- id: staging-test-3
content: "Run Load Tests: Execute load tests on staging environment"
status: skipped
- id: staging-test-4
content: "Monitor Staging Logs: Monitor logs for errors during testing period"
status: skipped
- id: staging-test-5
content: "Verify Staging Health Endpoints: Test /health/live and /health/ready endpoints on staging"
status: skipped
- id: prod-check-1
content: "Pre-production: Verify security audit passed - Review all security fixes are implemented"
status: skipped
- id: prod-check-2
content: "Pre-production: Verify staging tests passed - Confirm all staging tests are successful"
status: skipped
- id: prod-check-3
content: "Pre-production: Backup Database - Create database backup before production deployment"
status: skipped
- id: prod-check-4
content: "Pre-production: Generate Production Secrets - Generate STRONG NON-DEFAULT JWT secrets for production"
status: skipped
- id: prod-check-5
content: "Pre-production: Verify Critical Security Fixes - Confirm all CRITICAL security fixes are implemented and tested"
status: skipped
- id: prod-k8s-1
content: "Create Production Namespace: kubectl create namespace production"
status: skipped
- id: prod-k8s-2
content: "Create Production Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='STRONG_SECRET' --from-literal=jwt-refresh-secret='STRONG_SECRET' --from-literal=jwt-id-secret='STRONG_SECRET' -n production"
status: skipped
- id: prod-k8s-3
content: "Apply Production ConfigMap: kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml"
status: skipped
- id: prod-k8s-4
content: "Deploy Production Service: kubectl apply -f deployments/production/kubernetes/iam-service.yaml"
status: skipped
- id: prod-k8s-5
content: "Deploy Production HPA: kubectl apply -f deployments/production/kubernetes/hpa.yaml"
status: skipped
- id: prod-k8s-6
content: "Apply Production Ingress: kubectl apply -f deployments/production/kubernetes/ingress.yaml"
status: skipped
- id: prod-migrate-1
content: "Run Production Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy (safe deployment mode) - Verify migrations apply successfully"
status: skipped
- id: prod-monitor-1
content: "Monitor Production Rollout: kubectl rollout status deployment/iam-service -n production - Verify deployment succeeds"
status: skipped
- id: prod-monitor-2
content: "Check Production HPA: kubectl get hpa -n production - Verify HPA is configured correctly"
status: skipped
- id: prod-security-1
content: "Production Security: Verify secrets NOT using defaults - Check all JWT secrets are strong and non-default"
status: skipped
- id: prod-security-2
content: "Production Security: Verify TLS/SSL certificates configured - Check certificates are valid and configured"
status: skipped
- id: prod-security-3
content: "Production Security: Verify network policies applied - Check Kubernetes network policies are in place"
status: skipped
- id: prod-security-4
content: "Production Security: Verify pod security policies enabled - Check pod security policies are configured"
status: skipped
- id: prod-security-5
content: "Production Security: Verify resource quotas set - Check resource quotas are configured for namespace"
status: skipped
- id: prod-security-6
content: "Production Security: Verify RBAC configured - Check Kubernetes RBAC is properly configured"
status: skipped
- id: prod-security-7
content: "Production Security: Verify monitoring alerts configured - Check Prometheus alerts are set up"
status: skipped
- id: prod-security-8
content: "Production Security: Verify backup strategy in place - Confirm database backup strategy is implemented"
status: skipped
- id: post-monitor-1
content: "Monitor Error Rates: Check error rates in monitoring dashboard, verify errors are within acceptable range"
status: skipped
- id: post-monitor-2
content: "Monitor Response Times: Check API response times, verify performance metrics are acceptable"
status: skipped
- id: post-monitor-3
content: "Check Security Events: Review audit logs for security events, verify no suspicious activities"
status: skipped
- id: post-monitor-4
content: "Review Audit Logs: Review comprehensive audit logs for any anomalies"
status: skipped
- id: post-monitor-5
content: "Verify Autoscaling: Monitor HPA scaling based on CPU/memory metrics, verify autoscaling works correctly"
status: skipped
- id: post-test-1
content: "Test Failover Scenarios: Test pod failures, verify service remains available"
status: skipped
- id: post-test-2
content: "Run Comprehensive Smoke Tests: Execute full smoke test suite on production"
status: skipped
- id: post-test-3
content: "Verify Health Endpoints: Test /health/live and /health/ready endpoints on production"
status: skipped
- id: post-test-4
content: "Test Authentication Flows: Test register, login, logout flows on production"
status: skipped
- id: post-test-5
content: "Test Authorization Flows: Test RBAC/ABAC authorization on production"
status: skipped
- id: post-doc-1
content: "Document Known Issues: Create document listing any known issues or limitations"
status: skipped
- id: post-doc-2
content: "Create Operations Runbook: Create runbook with operational procedures, troubleshooting guides"
status: skipped
- id: post-doc-3
content: "Update Deployment Procedures: Update deployment documentation with lessons learned"
status: skipped
- id: post-doc-4
content: "Document Rollback Procedures: Document step-by-step rollback procedures for production"
status: skipped
---
# IAM Service Audit Plan
## Tổng Quan (Overview)
Kế hoạch kiểm tra toàn diện cho IAM Service với 6 phases chính:
1. **Pre-deployment Audit**: Review logic nghiệp vụ, build, linting, testing
2. **Security Fixes (CRITICAL)**: Fix các lỗ hổng bảo mật nghiêm trọng
3. **Local Environment**: Setup và test môi trường local
4. **Staging Deployment**: Deploy và verify trên staging
5. **Production Deployment**: Deploy production với zero-downtime
6. **Post-deployment**: Monitor và validate sau deploy
---
## Phase 1: Pre-deployment Audit
### 1.1 Business Logic Review (10 Modules)
**Authentication Module** (`services/iam-service/src/modules/auth/`)
- Review registration flow: email validation, password hashing (bcrypt cost 12), user profile creation
- Review login flow: password verification, JWT generation (access + refresh), session creation, MFA integration
- Review token refresh: token family tracking, refresh token rotation, replay attack detection
- Review password change: refresh token revocation, audit logging
**Authorization/RBAC Module** (`services/iam-service/src/modules/rbac/`)
- Review permission resolution hierarchy: Direct user → Role → Group → Policy (ABAC)
- Review role assignment with expiration
- Review policy engine (JSON Logic)
- Validate permission caching (5 min TTL) và cache invalidation
**Identity Management** (`services/iam-service/src/modules/identity/`)
- User Management: CRUD operations, bulk import/export
- Profile Management: Custom fields, avatar upload/delete
- Verification: Email/phone/document verification flows
- Organizations: Multi-tenant support, hierarchical structure
- Groups: Member management, group-based permissions
**Access Management** (`services/iam-service/src/modules/access/`)
- Access Requests: Workflow, approval chains, JIT access
- Access Reviews: Certification campaigns, automated cleanup
- Access Analytics: Usage tracking, risk identification
**Multi-Factor Authentication** (`services/iam-service/src/modules/mfa/`)
- TOTP implementation (speakeasy library)
- QR code generation
- WebAuthn support
- Multiple devices per user
- MFA recovery flow (REVIEW REQUIRED - currently missing)
**Social Authentication** (`services/iam-service/src/modules/social/`)
- Google/Facebook/GitHub OAuth flows
- Account linking logic
- Token refresh for social providers
- Email verification bypass for verified social accounts
**OIDC Provider** (`services/iam-service/src/modules/oidc/`)
- Discovery endpoint
- Authorization code flow
- Token exchange
- JWKS endpoint
**Session Management** (`services/iam-service/src/modules/session/`)
- Device fingerprinting
- Session expiration
- Session revocation (single/all)
- Activity tracking
**Governance & Compliance** (`services/iam-service/src/modules/governance/`)
- Compliance reporting (GDPR, SOC2, ISO27001)
- Policy management và versioning
- Risk scoring (0-100)
- Audit reporting
**Cache và Event Sourcing** (`services/iam-service/src/core/cache/`, `services/iam-service/src/core/events/`)
- Multi-layer caching (L1: Memory, L2: Redis, L3: DB)
- Cache warming và invalidation
- Audit logging tất cả security events
- Event sourcing với 7-year retention
### 1.2 Build & Error Checking
**TypeScript Compilation**
```bash
cd services/iam-service
pnpm typecheck # Type checking
pnpm build # Full build
```
- Verify: No TypeScript errors, no unused variables/imports, type safety for Prisma models, path aliases (@/*) working
**Linting & Code Quality**
```bash
pnpm lint
```
- Verify: Coding standards compliance, no console.log in production code, proper error handling, no security anti-patterns
**Database Schema**
```bash
pnpm prisma:generate # Generate Prisma client
pnpm prisma:validate # Validate schema (if available)
```
- Verify: Schema syntax valid, all relations properly defined, indexes optimized, migration files consistent
**Testing**
```bash
pnpm test:unit # Unit tests
pnpm test:e2e # E2E tests
pnpm test:coverage # Coverage report
```
- Target: Coverage >= 70% (branches, functions, lines, statements), all critical paths tested
**Docker Build**
```bash
docker build -t iam-service:test -f services/iam-service/Dockerfile .
```
- Verify: Multi-stage build successful, image size <500MB, non-root user configured, health check functional
---
## Phase 2: Security Fixes (CRITICAL - Must Complete Before Production)
### 2.1 CRITICAL Vulnerabilities (HIGH PRIORITY)
**🔴 CRITICAL: MFA Secrets in Plaintext**
- **Location**: `services/iam-service/prisma/schema.prisma` (lines 23, 234)
- **Issue**: `MFADevice.secret``User.mfaSecret` stored unencrypted
- **Fix**: Implement field-level encryption using crypto module (encrypt before save, decrypt on read)
- **Files to modify**:
- `prisma/schema.prisma` - Add encrypted field support
- Create `services/iam-service/src/core/security/encryption.service.ts` for encryption/decryption
- Update `services/iam-service/src/modules/mfa/mfa.service.ts` to use encryption
**🔴 CRITICAL: Refresh Tokens in Plaintext**
- **Location**: `services/iam-service/prisma/schema.prisma` (line 177)
- **Issue**: `RefreshToken.token` stored as plaintext
- **Fix**: Store hashed tokens (SHA-256), compare hash during validation
- **Files to modify**:
- Update `services/iam-service/src/modules/token/jwt.service.ts` to hash refresh tokens before storing
- Update refresh token validation logic
**🔴 CRITICAL: Default JWT Secrets**
- **Location**: `services/iam-service/src/config/jwt.config.ts` (lines 7, 11, 15)
- **Issue**: Default secrets not blocked in production
- **Fix**: Add production check that throws error if defaults are used
- **Files to modify**:
- `services/iam-service/src/config/jwt.config.ts` - Add production validation
### 2.2 Medium Severity Issues
**🟡 Weak Input Sanitization**
- **Location**: `services/iam-service/src/utils/helpers.ts` (line 39)
- **Current**: Only removes `<` and `>`
- **Fix**: Use DOMPurify or proper HTML entity encoding
**🟡 No Password Complexity Rules**
- **Location**: `services/iam-service/src/modules/auth/auth.dto.ts` (line 9)
- **Current**: Only minimum 8 characters
- **Fix**: Enforce uppercase, lowercase, numbers, symbols
**🟡 Simple Device Fingerprinting**
- **Location**: `services/iam-service/src/modules/token/cookie.service.ts` (lines 117-126)
- **Current**: Basic User-Agent + IP hash
- **Fix**: Use @fingerprintjs/fingerprintjs library
**🟡 Missing Account Lockout**
- **Issue**: No protection after N failed login attempts
- **Fix**: Implement exponential backoff + account lockout
- **Files to create/modify**:
- Create `services/iam-service/src/modules/auth/account-lockout.service.ts`
- Update `services/iam-service/src/modules/auth/auth.service.ts` to track failed attempts
- Add `failedLoginAttempts``lockedUntil` fields to User model
### 2.3 Low Severity Issues
- No password history tracking
- CORS credentials enabled (review necessity)
- Social tokens in plaintext (consider encryption)
- No MFA backup codes
- Missing password breach checking (HaveIBeenPwned integration)
### 2.4 OWASP Top 10 Review
- A01: Broken Access Control - ✅ Well implemented via RBAC/ABAC
- A02: Cryptographic Failures - ❌ See vulnerabilities above
- A03: Injection - ✅ Protected by Prisma parameterized queries
- A04: Insecure Design - Review zero-trust implementation
- A05: Security Misconfiguration - Review Helmet.js settings
- A06: Vulnerable Components - Run `npm audit`
- A07: Auth Failures - ❌ Missing account lockout
- A08: Data Integrity Failures - Review JWT signature validation
- A09: Logging Failures - ✅ Comprehensive audit logging
- A10: SSRF - Review external API calls
---
## Phase 3: Local Environment Setup
### 3.1 Docker Compose Setup
**Environment Configuration**
- Copy `deployments/local/env.local.example` to `deployments/local/.env.local`
- Update environment variables:
- `DATABASE_URL` (Neon PostgreSQL)
- `REDIS_URL`
- `JWT_SECRET` (generate new, NOT default)
- `JWT_REFRESH_SECRET` (generate new)
- `JWT_ID_SECRET` (generate new)
- Social auth credentials
**Start Services**
```bash
cd deployments/local
docker-compose up -d
```
**Database Migrations**
```bash
cd services/iam-service
pnpm prisma:migrate
pnpm prisma:seed
```
**Verify Services**
- Traefik Dashboard: http://localhost:8080
- IAM Service: http://localhost:5001
- API Gateway: http://localhost/api/v1/auth
- Redis: localhost:6379
**Health Checks**
```bash
curl http://localhost:5001/health/live # Liveness
curl http://localhost:5001/health/ready # Readiness (includes DB)
curl http://localhost:5001/metrics # Prometheus metrics
```
### 3.2 Functional Testing
- Test authentication flows (register, login, logout)
- Test authorization (RBAC/ABAC)
- Test MFA (TOTP, WebAuthn)
- Test social login (Google, Facebook, GitHub)
- Review logs and metrics
---
## Phase 4: Staging Deployment
### 4.1 Kubernetes Setup
**Prerequisites**
- Kubernetes cluster configured
- kubectl installed và configured
- Docker images pushed to registry
**Create Namespace**
```bash
kubectl create namespace staging
```
**Create Secrets**
```bash
kubectl create secret generic iam-service-secrets \
--from-literal=database-url="postgresql://..." \
--from-literal=jwt-secret="..." \
--from-literal=jwt-refresh-secret="..." \
-n staging
```
**Apply ConfigMap**
```bash
kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml
```
**Deploy Service**
```bash
kubectl apply -f deployments/staging/kubernetes/iam-service.yaml
```
**Apply Ingress**
```bash
kubectl apply -f deployments/staging/kubernetes/ingress.yaml
```
**Run Migrations**
```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```
**Verify Deployment**
```bash
kubectl get pods -n staging
kubectl logs -f deployment/iam-service -n staging
kubectl describe pod <pod-name> -n staging
```
### 4.2 Configuration
- Replicas: 2
- Resources: Requests (256Mi memory, 250m CPU), Limits (512Mi memory, 500m CPU)
- Probes: Liveness (/health/live, 30s delay), Readiness (/health/ready, 10s delay)
### 4.3 Testing
- Smoke tests
- Performance testing
- Load testing
- Monitor logs for errors
---
## Phase 5: Production Deployment
### 5.1 Pre-deployment Checklist
- Security audit passed
- Staging tests passed
- Backup database
- Configure production secrets (NON-DEFAULT VALUES)
### 5.2 Kubernetes Setup
**Create Namespace**
```bash
kubectl create namespace production
```
**Create Secrets**
```bash
kubectl create secret generic iam-service-secrets \
--from-literal=database-url="postgresql://..." \
--from-literal=jwt-secret="STRONG_PRODUCTION_SECRET" \
--from-literal=jwt-refresh-secret="STRONG_PRODUCTION_REFRESH_SECRET" \
--from-literal=jwt-id-secret="STRONG_PRODUCTION_ID_SECRET" \
-n production
```
**Apply Production ConfigMap**
```bash
kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml
```
**Deploy with HPA**
```bash
kubectl apply -f deployments/production/kubernetes/iam-service.yaml
kubectl apply -f deployments/production/kubernetes/hpa.yaml
```
**Apply Production Ingress**
```bash
kubectl apply -f deployments/production/kubernetes/ingress.yaml
```
**Run Migrations (Safe Deployment)**
```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```
**Monitor Rollout**
```bash
kubectl rollout status deployment/iam-service -n production
kubectl get hpa -n production
```
### 5.3 Production Configuration
- Replicas: 3 (min) → 10 (max) via HPA
- Resources: Requests (512Mi memory, 500m CPU), Limits (1Gi memory, 1000m CPU)
- Autoscaling: CPU target 70%, Memory target 80%
- Environment: `NODE_ENV=production`, `LOG_LEVEL=warn`, `TRACING_ENABLED=true`
### 5.4 Security Checklist
- ✅ Secrets NOT using defaults
- ✅ TLS/SSL certificates configured
- ✅ Network policies applied
- ✅ Pod security policies enabled
- ✅ Resource quotas set
- ✅ RBAC configured
- ✅ Monitoring alerts configured
- ✅ Backup strategy in place
---
## Phase 6: Post-deployment
### 6.1 Monitoring
- Monitor error rates
- Monitor response times
- Check for security events
- Review audit logs
- Verify autoscaling works
### 6.2 Testing
- Test failover scenarios
- Run comprehensive smoke tests
- Verify health endpoints
### 6.3 Documentation
- Document known issues
- Create runbook for operations
- Update deployment procedures
---
## Critical Files to Review/Modify
### Security Fixes Required
- `services/iam-service/prisma/schema.prisma` - Add encryption for sensitive fields
- `services/iam-service/src/config/jwt.config.ts` - Block defaults in production
- `services/iam-service/src/modules/auth/auth.dto.ts` - Password complexity
- `services/iam-service/src/modules/auth/auth.service.ts` - Account lockout
- `services/iam-service/src/utils/helpers.ts` - Input sanitization
- `services/iam-service/src/modules/token/cookie.service.ts` - Device fingerprinting
### Deployment Configs
- `deployments/local/docker-compose.yml`
- `deployments/staging/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/hpa.yaml`
---
## Conclusion
### Strengths
- ✅ Clean architecture với separation of concerns
- ✅ Comprehensive business logic (10 modules)
- ✅ Multi-layered security (RBAC + ABAC + Zero-Trust)
- ✅ Excellent audit logging
- ✅ Production-ready deployment configs
- ✅ CI/CD automation
- ✅ Horizontal scaling support
### Critical Issues to Address
- ❌ Encrypt sensitive data at rest (MFA secrets, refresh tokens)
- ❌ Block default JWT secrets in production
- ❌ Implement account lockout
- ❌ Improve password policies
- ❌ Enhanced input sanitization
### Recommendations
- **Immediate**: Fix all HIGH severity security issues before production
- **Short-term**: Implement MEDIUM severity fixes within 2 weeks
- **Long-term**: Enhance with ML-based risk analysis, passwordless auth
- **Continuous**: Regular security audits, penetration testing, dependency updates

File diff suppressed because it is too large Load Diff

View File

@@ -1,176 +0,0 @@
---
name: implement-user-pages
overview: Implement responsive user-facing and admin pages wired to the users API, working on both desktop and mobile (native-like) layouts.
todos:
- id: create-users-api-helper
content: Create apps/web-client/src/lib/api/users.ts with typed methods for users API
status: completed
- id: create-users-store
content: Add apps/web-client/src/stores/users-store.ts and hooks to manage users state and actions
status: completed
- id: create-users-components
content: Add UsersTable, UserCard, UserForm components under src/features/shared/components/users/
status: completed
- id: implement-admin-pages
content: "Add admin pages: apps/web-client/src/app/admin/users/page.tsx and apps/web-client/src/app/admin/users/[id]/page.tsx"
status: completed
- id: implement-profile-settings
content: "Add profile and settings pages: /profile and /settings wired to users-store/auth-store"
status: completed
- id: implement-auth-pages
content: Ensure login/register pages under /auth use auth-store and redirect to /dashboard on success
status: completed
- id: integrate-layouts
content: Wire pages to desktop layout (sidebar) and MobileLayout for mobile breakpoints
status: completed
- id: add-guards
content: Implement client-side auth guard and role-check helper for admin routes
status: completed
- id: add-tests
content: Add smoke/integration tests for auth flow and users pages
status: completed
---
# Plan: Implement User Pages (Desktop + Mobile)
## Goal
Implement a cohesive set of pages that use the users API for both self-service (profile) and admin CRUD, and that render well on desktop (sidebar/content) and mobile (native-style MobileLayout).
## Scope
- Public & auth pages: landing, login, register, forgot-password
- Authenticated user pages: dashboard (chat), profile, settings
- Admin pages: users list, user detail, create/edit user, role management
- Mobile parity: same routes/components but rendered inside `MobileLayout`/`MobileBottomNav` for mobile sizes
- API integration: use existing http-client package and create users client helpers
## Files I'll update / create (high-signal)
- Pages
- `apps/web-client/src/app/page.tsx` (landing — already updated)
- `apps/web-client/src/app/auth/login/page.tsx` (login)
- `apps/web-client/src/app/auth/register/page.tsx` (register)
- `apps/web-client/src/app/dashboard/page.tsx` (user dashboard)
- `apps/web-client/src/app/profile/page.tsx` (profile self-service)
- `apps/web-client/src/app/settings/page.tsx` (settings)
- `apps/web-client/src/app/admin/users/page.tsx` (admin users list)
- `apps/web-client/src/app/admin/users/[id]/page.tsx` (admin user detail/edit)
- Components & layout
- `apps/web-client/src/features/shared/components/users/UserCard.tsx`
- `apps/web-client/src/features/shared/components/users/UserForm.tsx`
- `apps/web-client/src/features/shared/components/users/UsersTable.tsx`
- `apps/web-client/src/features/shared/components/layout/desktop-layout/desktop-layout.tsx` (ensure sidebar + content)
- reuse `MobileLayout`, `MobileBottomNav` for mobile
- State & API
- `apps/web-client/src/stores/users-store.ts` (zustand or existing store pattern used by `auth-store.ts`)
- `packages/http-client/src/index.ts` or new helper `apps/web-client/src/lib/api/users.ts` for typed users API calls
- Auth & guards
- `apps/web-client/src/features/shared/middleware/auth-guard.tsx` (client-side guard/wrapper)
- add role-check helper for admin routes
- Tests & docs
- `apps/web-client/src/features/shared/components/layout/mobile-layout/mobile-app-demo.tsx` (demo already added)
- Add basic integration tests under `apps/web-client/src/__tests__/` for users pages
## Implementation steps (high level)
1. API client helpers (users)
- Create `apps/web-client/src/lib/api/users.ts` with typed methods: `getUsers`, `getUser`, `createUser`, `updateUser`, `deleteUser`.
- Use existing http-client package where appropriate.
2. Users store & hooks
- Implement `users-store.ts` with methods that call the API helpers and manage loading/error state.
- Expose hooks: `useUsersStore` with `fetchUsers`, `fetchUser`, `createUser`, `updateUser`, `deleteUser`.
3. Desktop layouts & components
- Ensure `desktop-layout.tsx` (sidebar + content) exists and supports admin sections.
- Create `UsersTable`, `UserCard`, and `UserForm` components.
- Implement `apps/web-client/src/app/admin/users/page.tsx` to use `UsersTable` and `useUsersStore`.
- Implement `apps/web-client/src/app/admin/users/[id]/page.tsx `to show `UserCard` + `UserForm`.
4. Auth pages & routing
- Provide login/register pages that call `auth-store` actions; upon login redirect to `/dashboard`.
- Protect admin pages with a client-side guard that checks `auth-store.user.role`.
5. Profile & settings
- Implement `/profile` to fetch and update current user (self-service) via `users-store` or `auth-store` methods.
- Settings to manage preferences (theme, language) integrated with existing providers.
6. Mobile parity
- For all pages, ensure responsive variants use `MobileLayout` when viewport small.
- For admin pages, provide compact mobile UI or hide complex operations (offer an «Open on desktop» hint) while allowing read/update on mobile where feasible.
7. UX polish
- Loading and empty states
- Error handling following project error patterns
- Accessible controls (keyboard, focus)
8. Tests
- Add smoke/integration tests for user list, user detail, login flow.
## Minimal example: users API helper (proposed)
```javascript
// apps/web-client/src/lib/api/users.ts
import { http } from '@goodgo/http-client';
export async function getUsers(params = {}) {
return await http.get('/api/users', { params });
}
export async function getUser(id) {
return await http.get(`/api/users/${id}`);
}
export async function createUser(payload) {
return await http.post('/api/users', payload);
}
export async function updateUser(id, payload) {
return await http.put(`/api/users/${id}`, payload);
}
export async function deleteUser(id) {
return await http.delete(`/api/users/${id}`);
}
```
## Todos (implementation tasks)
- create-users-api-helper: Create `apps/web-client/src/lib/api/users.ts` with typed methods
- create-users-store: Implement `apps/web-client/src/stores/users-store.ts` and hooks
- create-users-components: Implement `UsersTable`, `UserCard`, `UserForm`
- implement-admin-pages: Add `apps/web-client/src/app/admin/users/page.tsx` and `[id]/page.tsx`
- implement-profile-settings: Add `/profile` and `/settings` pages
- implement-auth-pages: Ensure `login` and `register` pages integrate with `auth-store`
- integrate-layouts: Wire pages to `desktop-layout` and `MobileLayout` responsive behavior
- add-guards: Implement client-side `auth-guard` and role checks for admin
- add-tests: Add basic tests for login, users list, user detail
## Timeline (estimates)
- API helpers + store: 1-2 days
- Core components + admin pages: 2-3 days
- Auth/profile/settings: 1-2 days
- Mobile adjustments & polish: 1-2 days
- Tests + QA: 1-2 days
## Notes / assumptions
- Users API endpoints follow REST conventions (`/api/users`). If the real API URL differs, I'll adapt the helpers.
- Uses existing `auth-store` for JWT/session; token injection handled by `http-client`.
- Admin UI assumes role-based field `user.role` is present.
If you confirm this plan I will create the detailed implementation plan (file-by-file edits and the exact code snippets) and then proceed to implement. If you want any changes to scope (e.g., exclude admin CRUD for now, or prioritise mobile-first UX), tell me which items to adjust.

File diff suppressed because it is too large Load Diff

View File

@@ -1,125 +0,0 @@
---
name: service-template-improvements
overview: "Make the service template production-ready: add testing, env management, DB scaffolding, auth, validation, docs and CI."
todos: []
---
# Improve Service Template (services/_template)
## Goal
Make `services/_template` production-ready and developer-friendly by adding testing infra, environment templates/validation, database scaffolding, auth & RBAC, request validation, API docs, standardized error handling, repository pattern, and CI. Changes should preserve existing structure and follow GoodGo project rules.
## High-level steps
1. Testing & CI
- Add `jest.config.ts`, `setupTests.ts`, and example unit/integration tests for `FeatureService` and `HealthController`.
- Add `supertest` based E2E test for `/health` and `/api/v1/features`.
- Update `package.json` scripts to run tests and coverage.
- Files: `services/_template/package.json`, add `jest.config.ts` at repo root of template, tests under `services/_template/src/__tests__/`.
2. Environment & Local Dev
- Add `.env.example` and `.env.local.example` with all required vars (PORT, NODE_ENV, DATABASE_URL, REDIS_URL, JAEGER_ENDPOINT, TRACING_ENABLED, SERVICE_NAME, API_VERSION).
- Enhance `src/config/app.config.ts` to accept `.env.local` overrides and document each var in `README.md`.
- Files: `services/_template/.env.example`, `services/_template/.env.local.example`, `services/_template/src/config/app.config.ts`, `services/_template/README.md`.
3. Prisma & Database
- Add `prisma/schema.prisma` example with a `Feature` model, and `prisma/seed.ts` placeholder.
- Add migration/dev workflow to README and `package.json` scripts (`prisma:generate`, `prisma:migrate`, `prisma:seed`).
- Files: `services/_template/prisma/schema.prisma`, `services/_template/prisma/seed.ts`, `services/_template/package.json` (scripts already partly present — document usage).
4. Authentication & Authorization
- Add auth middleware `src/middlewares/auth.middleware.ts` using `@goodgo/auth-sdk` and JWT guards.
- Add role-based decorator/utility and example protected route in `Feature` module.
- Files: `services/_template/src/middlewares/auth.middleware.ts`, update `services/_template/src/routes/index.ts` and `services/_template/src/modules/feature/feature.module.ts`.
5. Request Validation & Sanitization
- Add `validateDto` middleware that uses Zod DTOs (e.g., `createFeatureDtoSchema`) and integrates in `feature.module` routes.
- Sanitize input (simple trimming) helper.
- Files: `services/_template/src/middlewares/validation.middleware.ts`, update `src/modules/feature/feature.module.ts` to parse body.
6. API Documentation (OpenAPI)
- Add OpenAPI spec generator (e.g., `openapi-typescript` or `swagger-jsdoc`) and `/docs` route serving Swagger UI.
- Files: `services/_template/src/docs/openapi.ts`, `services/_template/src/routes/docs.ts`, update `README.md`.
7. Error Handling & Standard Errors
- Introduce custom error classes (`src/errors/http-error.ts`, `src/errors/not-found.ts`, `src/errors/bad-request.ts`) and an `error-code` enum.
- Ensure `error.middleware.ts` maps known errors to proper status codes and structured `ApiResponse`.
- Files: `services/_template/src/errors/*.ts`, update `src/middlewares/error.middleware.ts`.
8. Repository Pattern & Transactions
- Add `src/modules/common/repository.ts` scaffolding and update `FeatureService` to use repository and Prisma transactions for multi-step operations.
- Files: `services/_template/src/modules/common/repository.ts`, update `services/_template/src/modules/feature/feature.service.ts`.
9. Observability Improvements
- Ensure metrics registry reset in tests to avoid global state contamination.
- Add correlation id middleware and attach trace ids to logs.
- Files: `services/_template/src/middlewares/correlation.middleware.ts`, update `src/middlewares/logger.middleware.ts` and `src/main.ts` to add header mappings.
10. Docker & Image Best Practices
- Add `.dockerignore` and ensure `NODE_ENV` build-time handling.
- Make Docker build cache-friendly and document image tagging conventions in README.
- Files: `services/_template/.dockerignore`, `services/_template/Dockerfile` (reviewed changes only documented).
11. Documentation & Examples
- Update `README.md` with examples: local dev, running tests, generating Prisma client, environment explanation, and how to create a new service from template.
- Add code comment examples showing bilingual comment pattern where new modules are introduced.
## Implementation details & snippets
- Example: Add DTO validation middleware and usage:
```typescript
// services/_template/src/middlewares/validation.middleware.ts
import { Request, Response, NextFunction } from 'express';
import { AnyZodObject } from 'zod';
export const validateDto = (schema: AnyZodObject) => (req: Request, res: Response, next: NextFunction) => {
try {
req.body = schema.parse(req.body);
return next();
} catch (err: any) {
return res.status(400).json({ success: false, error: { code: 'VALIDATION_ERROR', message: err.message } });
}
};
```
- Example: Custom HTTP error mapping in `error.middleware.ts` — convert `HttpError` to proper status and code.
- Tests: Add `src/__tests__/health.e2e.ts` using `supertest` to assert readiness/liveness and metrics endpoint.
## Todos (for tracking)
- setup-tests: Add Jest config, test utilities, and example tests.
- add-dotenv-examples: Add `.env.example` and `.env.local.example` and document envs in README.
- prisma-scaffold: Add `prisma/schema.prisma` and `prisma/seed.ts` with Feature model.
- auth-middleware: Implement auth middleware & RBAC utilities and protect example route.
- validation-middleware: Implement Zod validation middleware and apply to feature routes.
- openapi: Add OpenAPI generation and Swagger UI route.
- errors: Implement custom error classes and improve `error.middleware` mapping.
- repository-pattern: Add repository scaffolding and update FeatureService.
- observability: Add correlation id middleware and test-safe prom-client usage.
- docker-ci: Add .dockerignore and document Docker improvements in README.
- docs: Update README and ARCHITECTURE.md with new instructions.
Each todo will contain detailed substeps when started.
## Time estimates (rough)
- High priority set (tests, env, prisma, validation, auth): 24 days
- Medium (openapi, errors, repo pattern): 12 days
- Low (docker polish, extra docs): 0.51 day
## Next step
If you approve, I will generate a concrete implementation plan and break the top-priority todos into file-level patches. If you prefer a different priority (e.g., focus on Auth first), tell me which to prioritize.

File diff suppressed because it is too large Load Diff

View File

@@ -1,446 +0,0 @@
---
name: Điều chỉnh giao diện đa ngôn ngữ cho web-client
overview: Thiết lập hệ thống i18n hoàn chỉnh với next-intl, migrate tất cả hardcoded text sang translation files, và tích hợp với language preferences để hiển thị đúng ngôn ngữ người dùng chọn.
todos:
- id: install-deps
content: Cài đặt next-intl package - Update package.json và chạy pnpm install
status: completed
- id: create-i18n-config
content: Tạo src/i18n/config.ts - Định nghĩa locales ['en', 'vi'], default 'en'
status: completed
- id: create-i18n-request
content: Tạo src/i18n/request.ts - Request handler với locale detection logic
status: completed
- id: create-i18n-context
content: Tạo src/contexts/i18n-context.tsx - Context với setLocale, getLocale, localStorage sync
status: completed
- id: create-i18n-provider
content: Tạo src/providers/i18n-provider.tsx - Provider component với browser detection
status: completed
- id: create-translation-hook
content: Tạo src/hooks/use-translation.ts - Hook useTranslation() với type safety
status: completed
- id: update-root-layout
content: Update src/app/layout.tsx - Wrap với I18nProvider, dynamic lang attribute
status: completed
- id: extract-common-translations
content: Tạo translation keys cho common namespace - buttons, labels, placeholders (en.json + vi.json)
status: completed
- id: extract-auth-translations
content: Tạo translation keys cho auth namespace - login, register, forgot-password (en.json + vi.json)
status: completed
- id: extract-chat-translations
content: Tạo translation keys cho chat namespace - messages, sidebar, input (en.json + vi.json)
status: completed
- id: extract-settings-translations
content: Tạo translation keys cho settings namespace - preferences, profile, security, api-keys (en.json + vi.json)
status: completed
- id: extract-validation-translations
content: Tạo translation keys cho validation namespace - form errors, Zod messages (en.json + vi.json)
status: completed
- id: extract-error-translations
content: Tạo translation keys cho errors namespace - API errors, general errors (en.json + vi.json)
status: completed
- id: migrate-login-page
content: Migrate src/app/(auth)/login/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-register-page
content: Migrate src/app/(auth)/register/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-forgot-password-page
content: Migrate src/app/(auth)/forgot-password/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-login-validation
content: Update Zod schema trong login page - Sử dụng translated validation messages
status: completed
- id: migrate-register-validation
content: Update Zod schema trong register page - Sử dụng translated validation messages
status: completed
- id: migrate-forgot-password-validation
content: Update Zod schema trong forgot-password page - Sử dụng translated validation messages
status: completed
- id: migrate-home-page
content: Migrate src/app/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-chat-page
content: Migrate src/app/(dashboard)/chat/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-settings-layout
content: Migrate src/app/(dashboard)/settings/layout.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-preferences-page
content: Migrate src/app/(dashboard)/settings/preferences/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-profile-page
content: Migrate src/app/(dashboard)/settings/profile/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-security-page
content: Migrate src/app/(dashboard)/settings/security/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-api-keys-page
content: Migrate src/app/(dashboard)/settings/api-keys/page.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-chat-input
content: Migrate src/components/chat/chat-input.tsx - Replace hardcoded text với useTranslation()
status: completed
- id: migrate-conversation-sidebar
content: Migrate src/components/chat/conversation-sidebar.tsx - Replace hardcoded text, format dates với useTranslation()
status: completed
- id: migrate-message-bubble
content: Migrate src/components/chat/message-bubble.tsx - Replace hardcoded text với useTranslation() (nếu có)
status: completed
- id: migrate-chat-layout
content: Migrate src/components/chat/chat-layout.tsx - Replace hardcoded text với useTranslation() (nếu có)
status: completed
- id: migrate-message-actions-menu
content: Migrate src/components/chat/message-actions-menu.tsx - Replace hardcoded text với useTranslation() (nếu có)
status: completed
- id: migrate-typing-indicator
content: Migrate src/components/chat/typing-indicator.tsx - Replace hardcoded text với useTranslation() (nếu có)
status: completed
- id: check-ui-components
content: Review src/components/ui/*.tsx - Kiểm tra và migrate nếu có hardcoded text
status: completed
- id: migrate-chat-store
content: Review src/stores/chat-store.ts - Migrate error messages, status messages nếu có
status: completed
- id: migrate-auth-store
content: Review src/stores/auth-store.ts - Migrate error messages, status messages nếu có
status: completed
- id: integrate-preferences-language-switch
content: Update preferences page - Kết nối language selector với i18n context, trigger re-render
status: completed
- id: add-date-formatters
content: Implement date formatting - Sử dụng next-intl formatters cho relative time trong sidebar
status: completed
- id: add-number-formatters
content: Implement number formatting - Sử dụng next-intl formatters cho numbers (nếu cần)
status: completed
- id: test-language-switching
content: Test language switching - Verify UI updates khi đổi ngôn ngữ trong preferences
status: completed
- id: test-browser-detection
content: Test browser language detection - Verify auto-detect từ navigator.language
status: completed
- id: test-persistence
content: Test persistence - Verify language preference lưu trong localStorage và persist qua reload
status: completed
- id: test-all-pages-en
content: Test tất cả pages với English - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: test-all-pages-vi
content: Test tất cả pages với Vietnamese - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: verify-html-lang-attribute
content: Verify HTML lang attribute - Check <html lang> updates đúng khi đổi ngôn ngữ
status: completed
- id: test-validation-messages
content: Test validation messages - Verify form validation hiển thị đúng ngôn ngữ
status: completed
---
# Plan: Điều chỉnh giao diện đa ngôn ngữ cho web-client
## Tổng quan
Hiện tại web-client đang sử dụng format hardcode song ngữ "English / Tiếng Việt" cho tất cả text. Plan này sẽ:
- Setup next-intl cho Next.js App Router
- Tạo translation files cho en và vi
- Migrate tất cả hardcoded text sang translation system
- Tích hợp với language preferences từ localStorage
- Detect browser language cho user mới
- Update HTML lang attribute động
## Kiến trúc
```
apps/web-client/
├── src/
│ ├── i18n/
│ │ ├── config.ts # Cấu hình next-intl
│ │ ├── request.ts # Request handler cho SSR
│ │ └── messages/
│ │ ├── en.json # English translations
│ │ └── vi.json # Vietnamese translations
│ ├── contexts/
│ │ └── i18n-context.tsx # Client-side i18n context
│ ├── hooks/
│ │ └── use-translation.ts # Custom hook cho translations
│ └── providers/
│ └── i18n-provider.tsx # I18n provider component
```
## Các bước thực hiện
### 1. Cài đặt dependencies
- Thêm `next-intl` vào `package.json`
- Cài đặt package: `pnpm add next-intl`
### 2. Tạo cấu trúc i18n
**File: `src/i18n/config.ts`**
- Định nghĩa supported locales: `['en', 'vi']`
- Default locale: `'en'`
- Export locale configuration
**File: `src/i18n/request.ts`**
- Setup request handler cho next-intl
- Detect locale từ:
1. localStorage preferences (nếu có)
2. Browser language (nếu không có preference)
3. Default 'en'
**File: `src/i18n/messages/en.json`**
- Tất cả English translations được tổ chức theo namespace:
- `common`: buttons, labels, placeholders
- `auth`: login, register, forgot password
- `chat`: chat interface, messages
- `settings`: settings pages
- `errors`: error messages
- `validation`: form validation messages
**File: `src/i18n/messages/vi.json`**
- Tất cả Vietnamese translations với cùng structure
### 3. Tạo I18n Context và Provider
**File: `src/contexts/i18n-context.tsx`**
- Context để quản lý locale state
- Functions: `setLocale`, `getLocale`
- Sync với localStorage preferences
- Detect browser language cho user mới
**File: `src/providers/i18n-provider.tsx`**
- Provider component wrap app
- Initialize locale từ preferences hoặc browser
- Update HTML lang attribute khi locale thay đổi
### 4. Tạo custom hook
**File: `src/hooks/use-translation.ts`**
- Hook `useTranslation()` để access translations
- Type-safe với TypeScript
- Support namespaces: `t('common.save')`, `t('auth.login')`
### 5. Update Root Layout
**File: `src/app/layout.tsx`**
- Wrap app với `I18nProvider`
- Update `<html lang={locale}>` động
- Remove hardcoded `lang="en"`
### 6. Migrate Components
Migrate tất cả hardcoded text trong các files sau:
**Pages:**
- `src/app/page.tsx` - Home page
- `src/app/(auth)/login/page.tsx` - Login page
- `src/app/(auth)/register/page.tsx` - Register page
- `src/app/(auth)/forgot-password/page.tsx` - Forgot password
- `src/app/(dashboard)/chat/page.tsx` - Chat page
- `src/app/(dashboard)/settings/preferences/page.tsx` - Preferences
- `src/app/(dashboard)/settings/profile/page.tsx` - Profile
- `src/app/(dashboard)/settings/security/page.tsx` - Security
- `src/app/(dashboard)/settings/api-keys/page.tsx` - API Keys
- `src/app/(dashboard)/settings/layout.tsx` - Settings layout
**Components:**
- `src/components/chat/chat-input.tsx` - Chat input
- `src/components/chat/conversation-sidebar.tsx` - Sidebar
- `src/components/chat/message-bubble.tsx` - Message bubble
- `src/components/ui/input.tsx` - Input component (nếu có hardcoded text)
- `src/components/ui/select.tsx` - Select component (nếu có hardcoded text)
**Stores:**
- `src/stores/chat-store.ts` - Chat store messages (nếu có)
- `src/stores/auth-store.ts` - Auth store messages (nếu có)
### 7. Tích hợp với Preferences
**File: `src/app/(dashboard)/settings/preferences/page.tsx`**
- Khi user thay đổi language, update i18n context
- Sync với localStorage
- Trigger re-render để update toàn bộ UI
### 8. Update Validation Schemas
**Files có Zod schemas:**
- `src/app/(auth)/login/page.tsx` - Login validation
- `src/app/(auth)/register/page.tsx` - Register validation
- `src/app/(auth)/forgot-password/page.tsx` - Forgot password validation
- Tạo translation keys cho validation messages
- Update Zod schemas để sử dụng translated messages
### 9. Format Dates và Numbers
- Sử dụng next-intl formatters cho dates
- Format relative time trong conversation sidebar
- Format timestamps trong chat messages
### 10. Testing
- Test language switching
- Test browser language detection
- Test persistence qua page reloads
- Test tất cả pages với cả 2 ngôn ngữ
- Verify HTML lang attribute updates
## Translation Structure Example
```json
{
"common": {
"save": "Save",
"cancel": "Cancel",
"loading": "Loading...",
"error": "Error"
},
"auth": {
"login": {
"title": "Sign In",
"email": "Email",
"password": "Password",
"rememberMe": "Remember me",
"forgotPassword": "Forgot password?",
"signUp": "Sign up"
}
},
"chat": {
"newChat": "New Chat",
"searchPlaceholder": "Search conversations...",
"typeMessage": "Type your message...",
"send": "Send message"
},
"settings": {
"title": "Settings",
"preferences": {
"title": "Preferences",
"language": "Language",
"theme": "Theme"
}
}
}
```
## Lưu ý kỹ thuật
1. **SSR Compatibility**: next-intl hỗ trợ SSR, nhưng với client-side approach, chúng ta sẽ detect locale ở client-side
2. **Type Safety**: Sử dụng TypeScript để type-check translation keys
3. **Performance**: Lazy load translation files nếu cần
4. **Fallback**: Luôn có fallback về 'en' nếu translation key không tồn tại
5. **Browser Detection**: Sử dụng `navigator.language` hoặc `navigator.languages[0]` để detect
## Migration Strategy
1. Setup infrastructure trước (i18n config, provider, hook)
2. Migrate từng page/component một
3. Test sau mỗi migration
4. Update preferences page cuối cùng để hoàn thiện integration
## Phân chia Tasks cho Multiple Agents
### Agent Roles
1. **setup** - Setup infrastructure (phải làm trước, tuần tự)
- Cài đặt dependencies
- Tạo config, context, provider, hook
- Update root layout
2. **translations** - Tạo translation files (có thể làm song song)
- Extract và tạo translation keys cho các namespaces
- Có thể chia theo namespace: common, auth, chat, settings, validation, errors
3. **migration-auth** - Migrate auth pages (có thể làm song song sau khi có infrastructure)
- Login, register, forgot-password pages
- Validation schemas cho auth forms
4. **migration-dashboard** - Migrate dashboard pages (có thể làm song song)
- Home, chat, settings pages
- Có thể chia theo page: home, chat, preferences, profile, security, api-keys
5. **migration-components** - Migrate components (có thể làm song song)
- Chat components
- UI components (nếu có hardcoded text)
6. **migration-stores** - Migrate stores (có thể làm song song)
- Chat store, auth store messages
7. **integration** - Integration tasks (phải làm sau khi có migrations)
- Preferences language switching
- Date/number formatters
8. **testing** - Testing tasks (phải làm cuối)
- Test tất cả functionality
### Execution Order
**Phase 1 (Tuần tự):**
- `setup` agent làm tất cả infrastructure tasks theo thứ tự dependencies
**Phase 2 (Song song):**
- `translations` agent có thể làm tất cả translation extraction tasks cùng lúc
**Phase 3-6 (Song song, sau Phase 1+2):**
- `migration-auth`, `migration-dashboard`, `migration-components`, `migration-stores` có thể làm song song
- Mỗi agent làm các file độc lập của mình
**Phase 7 (Sau migrations):**
- `integration` agent làm integration tasks
**Phase 8 (Cuối cùng):**
- `testing` agent test toàn bộ system
### Dependencies Matrix
```
install-deps
└─> create-i18n-config
├─> create-i18n-request
├─> create-i18n-context
│ ├─> create-i18n-provider
│ │ └─> update-root-layout
│ └─> create-translation-hook
│ └─> [tất cả migration tasks]
└─> [tất cả translation extraction tasks]
└─> [tất cả migration tasks]
```
### Parallelization Opportunities
- **Translation extraction**: 6 tasks có thể làm song song (common, auth, chat, settings, validation, errors)
- **Auth pages migration**: 3 pages + 3 validation schemas có thể làm song song
- **Dashboard pages migration**: 7 pages có thể làm song song
- **Components migration**: 7+ components có thể làm song song
- **Stores migration**: 2 stores có thể làm song song
- **Testing**: Một số test cases có thể chạy song song (nhưng nên test tuần tự để dễ debug)

View File

@@ -1,660 +0,0 @@
---
name: Điều chỉnh giao diện đa ngôn ngữ và hoàn thiện features cho web-admin
overview: Thiết lập hệ thống i18n hoàn chỉnh với next-intl cho web-admin, migrate tất cả hardcoded text sang translation files, tạo/copy UI components từ web-client để đảm bảo consistency, và hoàn thiện các features còn thiếu từ plan cũ (Analytics page, Messages page, API/Advanced settings tabs).
todos:
- id: install-deps
content: Cài đặt next-intl package - Update apps/web-admin/package.json và chạy pnpm install
status: completed
- id: create-i18n-config
content: Tạo apps/web-admin/src/i18n/config.ts - Định nghĩa locales ['en', 'vi'], default 'en'
status: completed
- id: create-i18n-request
content: Tạo apps/web-admin/src/i18n/request.ts - Request handler với locale detection logic
status: completed
- id: create-i18n-context
content: Tạo apps/web-admin/src/contexts/i18n-context.tsx - Context với setLocale, getLocale, localStorage sync, browser detection
status: completed
- id: create-i18n-provider
content: Tạo apps/web-admin/src/providers/i18n-provider.tsx - Provider component với static message imports (giống web-client fix)
status: completed
- id: create-translation-hook
content: Tạo apps/web-admin/src/hooks/use-translation.ts - Hook useTranslation() với type safety
status: completed
- id: update-root-layout
content: Update apps/web-admin/src/app/layout.tsx - Wrap với I18nProvider, dynamic lang attribute
status: completed
- id: copy-ui-button
content: Copy apps/web-client/src/components/ui/button.tsx sang apps/web-admin/src/components/ui/button.tsx
status: completed
- id: copy-ui-input
content: Copy apps/web-client/src/components/ui/input.tsx sang apps/web-admin/src/components/ui/input.tsx
status: completed
- id: copy-ui-card
content: Copy apps/web-client/src/components/ui/card.tsx sang apps/web-admin/src/components/ui/card.tsx
status: completed
- id: copy-ui-dialog
content: Copy apps/web-client/src/components/ui/dialog.tsx sang apps/web-admin/src/components/ui/dialog.tsx
status: completed
- id: copy-ui-avatar
content: Copy apps/web-client/src/components/ui/avatar.tsx sang apps/web-admin/src/components/ui/avatar.tsx
status: completed
- id: copy-ui-switch
content: Copy apps/web-client/src/components/ui/switch.tsx sang apps/web-admin/src/components/ui/switch.tsx
status: completed
- id: copy-ui-select
content: Copy apps/web-client/src/components/ui/select.tsx sang apps/web-admin/src/components/ui/select.tsx (nếu cần)
status: completed
- id: copy-ui-dropdown
content: Copy apps/web-client/src/components/ui/dropdown-menu.tsx sang apps/web-admin/src/components/ui/dropdown-menu.tsx (nếu cần)
status: completed
- id: extract-common-translations
content: Tạo translation keys cho common namespace - buttons, labels, placeholders (en.json + vi.json)
status: completed
- id: extract-auth-translations
content: Tạo translation keys cho auth namespace - login (en.json + vi.json)
status: completed
- id: extract-admin-dashboard-translations
content: Tạo translation keys cho admin.dashboard namespace - metrics, charts, activity table (en.json + vi.json)
status: completed
- id: extract-admin-users-translations
content: Tạo translation keys cho admin.users namespace - search, filters, table headers, actions, user details modal (en.json + vi.json)
status: completed
- id: extract-admin-analytics-translations
content: Tạo translation keys cho admin.analytics namespace - tabs, charts, metrics, reports (en.json + vi.json)
status: completed
- id: extract-admin-messages-translations
content: Tạo translation keys cho admin.messages namespace - message list, filters, moderation tools (en.json + vi.json)
status: completed
- id: extract-admin-settings-translations
content: Tạo translation keys cho admin.settings namespace - tabs, form labels, descriptions, General/Email/Security/API/Advanced (en.json + vi.json)
status: completed
- id: extract-validation-translations
content: Tạo translation keys cho validation namespace - form errors, Zod messages (en.json + vi.json)
status: completed
- id: extract-error-translations
content: Tạo translation keys cho errors namespace - API errors, general errors (en.json + vi.json)
status: completed
- id: migrate-login-page-ui
content: Migrate apps/web-admin/src/app/login/page.tsx - Replace hardcoded UI text với useTranslation()
status: completed
- id: migrate-login-validation
content: Update Zod schema trong login page - Sử dụng translated validation messages
status: completed
- id: migrate-dashboard-layout
content: Migrate apps/web-admin/src/app/(dashboard)/layout.tsx - Replace navigation labels với useTranslation()
status: completed
- id: migrate-dashboard-page-metrics
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace metrics labels và values với useTranslation()
status: completed
- id: migrate-dashboard-page-charts
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace chart labels và descriptions với useTranslation()
status: completed
- id: migrate-dashboard-page-activity
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace activity table descriptions với useTranslation()
status: completed
- id: migrate-users-page-header
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace page header và description với useTranslation()
status: completed
- id: migrate-users-page-search-filters
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace search bar và filter labels với useTranslation()
status: completed
- id: migrate-users-page-table
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace table headers và actions với useTranslation()
status: completed
- id: migrate-settings-page
content: Migrate apps/web-admin/src/app/(dashboard)/settings/page.tsx - Replace tabs, headers, descriptions với useTranslation()
status: completed
- id: migrate-analytics-card
content: Migrate apps/web-admin/src/components/admin/analytics-card.tsx - Replace card labels, trend indicators với useTranslation()
status: completed
- id: migrate-data-table-headers
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace table headers và column labels với useTranslation()
status: completed
- id: migrate-data-table-pagination
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace pagination labels (Previous, Next, Page, etc.) với useTranslation()
status: completed
- id: migrate-data-table-actions
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace action buttons (Export, Select All, etc.) với useTranslation()
status: completed
- id: migrate-activity-table
content: Migrate apps/web-admin/src/components/admin/recent-activity-table.tsx - Replace activity descriptions, status labels với useTranslation()
status: completed
- id: migrate-user-details-modal-header
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace modal title, description với useTranslation()
status: completed
- id: migrate-user-details-modal-tabs
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace tab labels (Profile, Activity, Messages) với useTranslation()
status: completed
- id: migrate-user-details-modal-content
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace profile fields, activity descriptions, message history labels với useTranslation()
status: completed
- id: migrate-user-details-modal-actions
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace action buttons (Edit, Delete, Ban, etc.) với useTranslation()
status: completed
- id: migrate-user-growth-chart
content: Migrate apps/web-admin/src/components/admin/charts/user-growth-chart.tsx - Replace chart labels, tooltips với useTranslation()
status: completed
- id: migrate-revenue-chart
content: Migrate apps/web-admin/src/components/admin/charts/revenue-chart.tsx - Replace chart labels, tooltips với useTranslation()
status: completed
- id: migrate-general-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/general-settings.tsx - Replace form labels, descriptions, buttons với useTranslation()
status: completed
- id: migrate-general-settings-validation
content: Update Zod schema trong general-settings.tsx - Sử dụng translated validation messages
status: completed
- id: migrate-email-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/email-settings.tsx - Replace form labels, descriptions, buttons với useTranslation()
status: completed
- id: migrate-email-settings-validation
content: Update Zod schema trong email-settings.tsx - Sử dụng translated validation messages
status: completed
- id: migrate-security-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/security-settings.tsx - Replace form labels, descriptions, policy texts với useTranslation()
status: completed
- id: migrate-security-settings-validation
content: Update Zod schema trong security-settings.tsx - Sử dụng translated validation messages
status: completed
- id: create-analytics-page-layout
content: Tạo apps/web-admin/src/app/(dashboard)/analytics/page.tsx - Page layout với tabs structure (Overview, Users, Messages, Performance)
status: completed
- id: create-analytics-overview-metrics
content: Tạo Overview tab - Key metrics summary cards với useTranslation()
status: completed
- id: create-analytics-overview-charts
content: Tạo Overview tab - Trends visualization và comparison charts với useTranslation()
status: completed
- id: create-analytics-users-funnel
content: Tạo Users tab - User acquisition funnel chart với useTranslation()
status: completed
- id: create-analytics-users-retention
content: Tạo Users tab - Retention chart và cohort analysis với useTranslation()
status: completed
- id: create-analytics-messages-stats
content: Tạo Messages tab - Total messages, average per user metrics với useTranslation()
status: completed
- id: create-analytics-messages-activity
content: Tạo Messages tab - Peak activity times chart với useTranslation()
status: completed
- id: create-analytics-performance-metrics
content: Tạo Performance tab - API response times, error rates metrics với useTranslation()
status: completed
- id: create-analytics-performance-uptime
content: Tạo Performance tab - Uptime statistics và charts với useTranslation()
status: completed
- id: create-messages-page-layout
content: Tạo apps/web-admin/src/app/(dashboard)/messages/page.tsx - Page layout với header, search, filters
status: completed
- id: create-messages-page-list
content: Tạo Messages page - Message list component với pagination và useTranslation()
status: completed
- id: create-messages-page-details
content: Tạo Messages page - Message details view component với useTranslation()
status: completed
- id: create-messages-page-moderation
content: Tạo Messages page - Content moderation tools với useTranslation()
status: completed
- id: create-messages-page-stats
content: Tạo Messages page - Message statistics cards với useTranslation()
status: completed
- id: create-api-settings-ui
content: Tạo apps/web-admin/src/components/admin/settings/api-settings.tsx - Form UI với API keys management, webhooks config, rate limits với useTranslation()
status: completed
- id: create-api-settings-validation
content: Tạo Zod schema cho api-settings.tsx - Sử dụng translated validation messages
status: completed
- id: create-advanced-settings-ui
content: Tạo apps/web-admin/src/components/admin/settings/advanced-settings.tsx - Form UI với feature flags, logs, cache, database settings với useTranslation()
status: completed
- id: create-advanced-settings-validation
content: Tạo Zod schema cho advanced-settings.tsx - Sử dụng translated validation messages
status: completed
- id: update-settings-tabs
content: Update apps/web-admin/src/app/(dashboard)/settings/page.tsx - Thêm API và Advanced tabs
status: completed
- id: integrate-language-preferences
content: Tích hợp language selector trong settings (nếu chưa có) - Kết nối với i18n context, trigger re-render
status: completed
- id: add-date-formatters-tables
content: Implement date formatting trong tables - Sử dụng locale cho date formatting trong data-table, activity-table
status: completed
- id: add-date-formatters-charts
content: Implement date formatting trong charts - Sử dụng locale cho date formatting trong user-growth-chart, revenue-chart
status: completed
- id: add-date-formatters-modals
content: Implement date formatting trong modals - Sử dụng locale cho date formatting trong user-details-modal
status: completed
- id: add-number-formatters
content: Implement number formatting - Sử dụng locale cho number formatting (nếu cần)
status: completed
- id: test-language-switching
content: Test language switching - Verify UI updates khi đổi ngôn ngữ
status: completed
- id: test-browser-detection
content: Test browser language detection - Verify auto-detect từ navigator.language
status: completed
- id: test-persistence
content: Test persistence - Verify language preference lưu trong localStorage và persist qua reload
status: completed
- id: test-all-pages-en
content: Test tất cả pages với English - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: test-all-pages-vi
content: Test tất cả pages với Vietnamese - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: verify-html-lang-attribute
content: Verify HTML lang attribute - Check <html lang> updates đúng khi đổi ngôn ngữ
status: completed
- id: test-validation-messages
content: Test validation messages - Verify form validation hiển thị đúng ngôn ngữ
status: completed
---
# Plan: Điều chỉnh giao diện đa ngôn ngữ và hoàn thiện features cho web-admin
## Tổng quan
Plan này sẽ:
- Setup next-intl cho Next.js App Router trong web-admin
- Tạo translation files cho en và vi với đầy đủ admin-specific translations
- Migrate tất cả hardcoded text "English / Tiếng Việt" sang translation system
- Tạo/copy UI components từ web-client để đảm bảo design system consistency
- Hoàn thiện các features còn thiếu: Analytics page, Messages page, API/Advanced settings tabs
- Tích hợp với language preferences từ localStorage
- Detect browser language cho user mới
- Update HTML lang attribute động
## Kiến trúc
```
apps/web-admin/
├── src/
│ ├── i18n/
│ │ ├── config.ts # Cấu hình next-intl
│ │ ├── request.ts # Request handler cho SSR
│ │ └── messages/
│ │ ├── en.json # English translations
│ │ └── vi.json # Vietnamese translations
│ ├── contexts/
│ │ └── i18n-context.tsx # Client-side i18n context
│ ├── hooks/
│ │ └── use-translation.ts # Custom hook cho translations
│ ├── providers/
│ │ └── i18n-provider.tsx # I18n provider component
│ └── components/
│ └── ui/ # UI components (copy từ web-client nếu cần)
│ ├── button.tsx
│ ├── input.tsx
│ ├── card.tsx
│ ├── dialog.tsx
│ ├── avatar.tsx
│ ├── switch.tsx
│ ├── select.tsx
│ └── dropdown-menu.tsx
```
## Các bước thực hiện
### Phase 1: Setup i18n Infrastructure
#### 1.1 Cài đặt dependencies
- Thêm `next-intl` vào `apps/web-admin/package.json`
- Chạy `pnpm install`
#### 1.2 Tạo cấu trúc i18n
- **File: `src/i18n/config.ts`** - Định nghĩa locales ['en', 'vi'], default 'en'
- **File: `src/i18n/request.ts`** - Request handler với locale detection logic
- **File: `src/i18n/messages/en.json`** - English translations với namespaces:
- `common`: buttons, labels, placeholders
- `auth`: login
- `admin`: dashboard, users, analytics, messages, settings
- `validation`: form validation messages
- `errors`: error messages
- **File: `src/i18n/messages/vi.json`** - Vietnamese translations với cùng structure
#### 1.3 Tạo I18n Context và Provider
- **File: `src/contexts/i18n-context.tsx`** - Context với setLocale, getLocale, localStorage sync, browser detection
- **File: `src/providers/i18n-provider.tsx`** - Provider component với dynamic message loading
- **File: `src/hooks/use-translation.ts`** - Custom hook useTranslation() với type safety
#### 1.4 Update Root Layout
- **File: `src/app/layout.tsx`** - Wrap với I18nProvider, dynamic lang attribute
### Phase 2: Tạo/Copy UI Components
#### 2.1 Copy UI Components từ web-client
Các components cần copy từ `apps/web-client/src/components/ui/` sang `apps/web-admin/src/components/ui/`:
- `button.tsx` - Button component với variants và sizes
- `input.tsx` - Input component với validation states
- `card.tsx` - Card component với subcomponents
- `dialog.tsx` - Dialog/Modal component
- `avatar.tsx` - Avatar component với sizes
- `switch.tsx` - Switch component
- `select.tsx` - Select component (nếu cần)
- `dropdown-menu.tsx` - Dropdown menu component (nếu cần)
**Lưu ý**: Các components này đang được import trong web-admin nhưng chưa tồn tại, cần tạo/copy để tránh lỗi.
### Phase 3: Extract và Tạo Translation Files
#### 3.1 Extract translations từ các pages/components hiện có
- **Common namespace**: buttons, labels, placeholders, loading states
- **Auth namespace**: login page texts
- **Admin namespace**:
- Dashboard: metrics, charts, activity table
- Users: search, filters, table headers, actions, user details modal
- Analytics: tabs, charts, metrics (nếu có)
- Messages: message management (nếu có)
- Settings: tabs, form labels, descriptions, General/Email/Security/API/Advanced settings
- **Validation namespace**: form errors, Zod messages
- **Errors namespace**: API errors, general errors
### Phase 4: Migrate Pages và Components
#### 4.1 Auth Pages
- **File: `src/app/login/page.tsx`** - Migrate hardcoded text, update validation schema
#### 4.2 Dashboard Pages
- **File: `src/app/(dashboard)/layout.tsx`** - Migrate sidebar navigation labels
- **File: `src/app/(dashboard)/dashboard/page.tsx`** - Migrate metrics, charts labels, activity descriptions
- **File: `src/app/(dashboard)/users/page.tsx`** - Migrate search, filters, table headers, actions
- **File: `src/app/(dashboard)/settings/page.tsx`** - Migrate tabs, headers, descriptions
#### 4.3 Admin Components
- **File: `src/components/admin/analytics-card.tsx`** - Migrate card labels, trend indicators
- **File: `src/components/admin/data-table.tsx`** - Migrate table headers, pagination, actions
- **File: `src/components/admin/recent-activity-table.tsx`** - Migrate activity descriptions, status labels
- **File: `src/components/admin/user-details-modal.tsx`** - Migrate modal content, tabs, actions
- **File: `src/components/admin/charts/user-growth-chart.tsx`** - Migrate chart labels, tooltips
- **File: `src/components/admin/charts/revenue-chart.tsx`** - Migrate chart labels, tooltips
- **File: `src/components/admin/settings/general-settings.tsx`** - Migrate form labels, validation, success/error messages
- **File: `src/components/admin/settings/email-settings.tsx`** - Migrate form labels, validation, test email messages
- **File: `src/components/admin/settings/security-settings.tsx`** - Migrate form labels, validation, security policy descriptions
### Phase 5: Hoàn thiện Features Còn Thiếu
#### 5.1 Analytics Page
- **File: `src/app/(dashboard)/analytics/page.tsx`** - Tạo mới với tabs:
- Overview tab: Key metrics summary, trends visualization, comparison charts
- Users tab: User acquisition funnel, retention chart, cohort analysis
- Messages tab: Total messages, average per user, peak activity times
- Performance tab: API response times, error rates, uptime statistics
- **Components**: Tạo các chart components cần thiết (pie chart, donut chart, heatmap)
#### 5.2 Messages Page
- **File: `src/app/(dashboard)/messages/page.tsx`** - Tạo mới với:
- Message list với search và filters
- Message details view
- Content moderation tools
- Message statistics
#### 5.3 API Settings Tab
- **File: `src/components/admin/settings/api-settings.tsx`** - Tạo mới với:
- API keys management
- Webhooks configuration
- Rate limits settings
- Documentation link
- **Update**: `src/app/(dashboard)/settings/page.tsx` - Thêm API tab
#### 5.4 Advanced Settings Tab
- **File: `src/components/admin/settings/advanced-settings.tsx`** - Tạo mới với:
- Feature flags
- System logs
- Cache management
- Database settings
- Backup/restore options
- **Update**: `src/app/(dashboard)/settings/page.tsx` - Thêm Advanced tab
### Phase 6: Integration và Testing
#### 6.1 Tích hợp Language Preferences
- Update settings page để có language selector (nếu chưa có)
- Kết nối với i18n context
- Trigger re-render khi đổi ngôn ngữ
#### 6.2 Date và Number Formatting
- Sử dụng locale cho date formatting trong tables, charts
- Format numbers theo locale (nếu cần)
#### 6.3 Testing
- Test language switching
- Test browser language detection
- Test persistence qua page reloads
- Test tất cả pages với cả 2 ngôn ngữ
- Verify HTML lang attribute updates
- Test validation messages
## Translation Structure Example
```json
{
"common": {
"save": "Save",
"cancel": "Cancel",
"loading": "Loading...",
"search": "Search",
"filter": "Filter",
"export": "Export"
},
"admin": {
"dashboard": {
"title": "Dashboard",
"totalUsers": "Total Users",
"totalMessages": "Total Messages",
"activeUsers": "Active Users",
"revenue": "Revenue"
},
"users": {
"title": "User Management",
"searchPlaceholder": "Search users...",
"role": "Role",
"status": "Status",
"actions": "Actions"
},
"settings": {
"title": "System Settings",
"general": "General",
"email": "Email",
"security": "Security",
"api": "API",
"advanced": "Advanced"
}
}
}
```
## Dependencies và Execution Order
### Dependencies Matrix
```
install-deps
└─> create-i18n-config
├─> create-i18n-request
├─> create-i18n-context
│ ├─> create-i18n-provider
│ │ └─> update-root-layout
│ └─> create-translation-hook
│ └─> [tất cả migration tasks]
└─> [tất cả translation extraction tasks]
└─> [tất cả migration tasks]
copy-ui-components
└─> [tất cả migration tasks sử dụng UI components]
create-missing-features
└─> [migrate các features mới]
```
### Execution Phases
**Phase 1 (Tuần tự):**
- Setup i18n infrastructure (config, context, provider, hook)
- Update root layout
**Phase 2 (Song song):**
- Copy UI components từ web-client
- Extract và tạo translation files cho tất cả namespaces
**Phase 3 (Song song, sau Phase 1+2):**
- Migrate auth pages
- Migrate dashboard pages
- Migrate admin components
- Migrate settings components
**Phase 4 (Sau migrations):**
- Tạo Analytics page
- Tạo Messages page
- Tạo API settings tab
- Tạo Advanced settings tab
**Phase 5 (Cuối cùng):**
- Integration tasks (language preferences, date formatting)
- Testing toàn bộ system
## Parallelization Opportunities
- **Translation extraction**: 5 namespaces có thể làm song song (common, auth, admin, validation, errors)
- **UI components copy**: 8 components có thể copy song song
- **Page migrations**: 5 pages có thể migrate song song
- **Component migrations**: 8+ components có thể migrate song song
- **New features**: Analytics, Messages, API/Advanced settings có thể làm song song
## Lưu ý kỹ thuật
1. **UI Components**: Copy từ web-client để đảm bảo design system consistency
2. **Static Imports**: Sử dụng static imports cho messages trong provider (giống web-client fix)
3. **Type Safety**: Sử dụng TypeScript để type-check translation keys
4. **Fallback**: Luôn có fallback về 'en' nếu translation key không tồn tại
5. **Browser Detection**: Sử dụng `navigator.language` để detect
6. **Admin-specific Translations**: Tạo namespace `admin` riêng cho admin-specific texts
## Phân chia Tasks cho Multiple Agents
### Agent Roles
1. **setup** - Setup infrastructure (phải làm trước, tuần tự)
- Cài đặt dependencies
- Tạo config, context, provider, hook
- Update root layout
2. **ui-components** - Copy UI components (có thể làm song song)
- Copy 8 UI components từ web-client sang web-admin
- Có thể chia theo component: button, input, card, dialog, avatar, switch, select, dropdown-menu
3. **translations** - Tạo translation files (có thể làm song song)
- Extract và tạo translation keys cho các namespaces
- Có thể chia theo namespace: common, auth, admin.dashboard, admin.users, admin.analytics, admin.messages, admin.settings, validation, errors
4. **migration-auth** - Migrate auth pages (có thể làm song song sau khi có infrastructure)
- Login page UI và validation schema
5. **migration-dashboard** - Migrate dashboard pages (có thể làm song song)
- Dashboard layout, dashboard page (metrics, charts, activity), users page (header, search/filters, table), settings page
- Có thể chia theo page hoặc theo phần trong page
6. **migration-components** - Migrate admin components (có thể làm song song)
- Analytics card, data table (headers, pagination, actions), activity table, user details modal (header, tabs, content, actions), charts, settings forms
7. **new-features** - Tạo features mới (có thể làm song song sau migrations)
- Analytics page (layout, overview, users, messages, performance tabs)
- Messages page (layout, list, details, moderation, stats)
- API settings (UI, validation)
- Advanced settings (UI, validation)
8. **integration** - Integration tasks (phải làm sau khi có migrations)
- Language preferences integration
- Date/number formatters (tables, charts, modals)
9. **testing** - Testing tasks (phải làm cuối)
- Test tất cả functionality
### Execution Order
**Phase 1 (Tuần tự):**
- `setup` agent làm tất cả infrastructure tasks theo thứ tự dependencies
**Phase 2 (Song song):**
- `ui-components` agent copy 8 components song song
- `translations` agent có thể làm tất cả translation extraction tasks cùng lúc (5 admin sub-namespaces + common + auth + validation + errors)
**Phase 3-6 (Song song, sau Phase 1+2):**
- `migration-auth`, `migration-dashboard`, `migration-components` có thể làm song song
- Mỗi agent làm các file độc lập của mình
**Phase 7 (Sau migrations):**
- `new-features` agent làm các features mới (có thể chia nhỏ theo feature)
**Phase 8 (Sau new features):**
- `integration` agent làm integration tasks
**Phase 9 (Cuối cùng):**
- `testing` agent test toàn bộ system
### Dependencies Matrix
```
install-deps
└─> create-i18n-config
├─> create-i18n-request
├─> create-i18n-context
│ ├─> create-i18n-provider
│ │ └─> update-root-layout
│ └─> create-translation-hook
│ └─> [tất cả migration tasks]
└─> [tất cả translation extraction tasks]
└─> [tất cả migration tasks]
copy-ui-components (song song)
└─> [tất cả migration tasks sử dụng UI components]
create-missing-features
└─> [migrate các features mới]
```
### Parallelization Opportunities
- **UI components copy**: 8 components có thể copy song song
- **Translation extraction**: 9 namespaces có thể làm song song (common, auth, admin.dashboard, admin.users, admin.analytics, admin.messages, admin.settings, validation, errors)
- **Page migrations**: 4 pages có thể migrate song song (login, dashboard, users, settings)
- **Component migrations**: 9+ components có thể migrate song song
- **New features**: Analytics (9 subtasks), Messages (5 subtasks), API/Advanced settings (4 subtasks) có thể làm song song
- **Testing**: Một số test cases có thể chạy song song (nhưng nên test tuần tự để dễ debug)