docs: dịch 22 file Markdown còn lại sang tiếng Việt có dấu (TEC-2881)
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 18s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m15s
Deploy / Build API Image (push) Failing after 28s
Deploy / Build Web Image (push) Failing after 16s
Deploy / Build AI Services Image (push) Failing after 17s
E2E Tests / Playwright E2E (push) Failing after 31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 3s
Security Scanning / Trivy Scan — API Image (push) Failing after 1m46s
Security Scanning / Trivy Scan — Web Image (push) Failing after 1m7s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 53s
Security Scanning / Trivy Filesystem Scan (push) Failing after 35s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Security Scanning / Security Gate (push) Failing after 0s
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped

Hoàn tất đợt cuối của nhiệm vụ chuyển toàn bộ tài liệu sang tiếng Việt.
Đã dịch 22 file `.md` còn sót (~9.7k dòng) — gồm RUNBOOK, audits,
docs/architecture, docs/load-testing, libs READMEs và các quick references.
Giữ nguyên code blocks, đường dẫn, identifier kỹ thuật, URL và biến môi trường.

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-19 03:26:14 +07:00
parent 11f2bf26e6
commit d8b409a9ab
22 changed files with 3697 additions and 3703 deletions

View File

@@ -1,332 +1,332 @@
# GoodGo Platform — Production Readiness Checklist
# GoodGo Platform — Checklist Sẵn Sàng Production
> **Last updated:** 2026-04-12
> **Status:** NOT READY — 5 critical blockers remain
> **Target launch:** TBD (pending blocker resolution)
> **Sign-off required from:** SRE Engineer, DevOps Engineer, CTO
> **Cập nhật lần cuối:** 2026-04-12
> **Trạng thái:** CHƯA SẴN SÀNG — còn 5 blocker quan trọng
> **Mục tiêu launch:** TBD (chờ giải quyết blocker)
> **Cần sign-off từ:** SRE Engineer, DevOps Engineer, CTO
---
## Summary
## Tóm Tắt
| Category | Pass | Fail | Blocked | Total |
| Hạng mục | Pass | Fail | Blocked | Tổng |
|----------|------|------|---------|-------|
| Infrastructure | 1 | 3 | 0 | 4 |
| Application Quality | 2 | 1 | 0 | 3 |
| Operations | 3 | 0 | 0 | 3 |
| Security | 0 | 1 | 0 | 1 |
| Performance | 0 | 0 | 1 | 1 |
| **Total** | **6** | **5** | **1** | **12** |
| Hạ tầng | 1 | 3 | 0 | 4 |
| Chất lượng ứng dụng | 2 | 1 | 0 | 3 |
| Vận hành | 3 | 0 | 0 | 3 |
| Bảo mật | 0 | 1 | 0 | 1 |
| Hiệu năng | 0 | 0 | 1 | 1 |
| **Tổng** | **6** | **5** | **1** | **12** |
---
## Checklist
### 1. Load Testing Results (K6 Baseline)
### 1. Kết Quả Load Test (K6 Baseline)
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PARTIAL PASS |
| **Trạng thái** | PARTIAL PASS |
| **Owner** | SRE Engineer |
| **Evidence** | [`load-tests/results/BASELINE-REPORT.md`](../load-tests/results/BASELINE-REPORT.md) |
| **Date tested** | 2026-04-09 |
| **Bằng chứng** | [`load-tests/results/BASELINE-REPORT.md`](../load-tests/results/BASELINE-REPORT.md) |
| **Ngày test** | 2026-04-09 |
**Findings:**
- K6 v1.7.1 baseline run completed against local dev environment
- 4 test suites executed: Auth, Listings, Search, Payments
- Latency SLAs met at framework level (p50 < 3ms, p95 < 6ms, p99 < 19ms)
- Error rate SLA **FAILED** — auth/listings/payments return HTTP 500 due to dev-environment dependency issues (Prisma/DB not fully configured)
- Search tests skipped (Typesense unavailable in dev)
**Phát hiện:**
- Đã hoàn thành chạy baseline K6 v1.7.1 với môi trường dev local
- 4 bộ test được chạy: Auth, Listings, Search, Payments
- SLA latency đạt yêu cầu ở mức framework (p50 < 3ms, p95 < 6ms, p99 < 19ms)
- SLA error rate **THẤT BẠI** — auth/listings/payments trả về HTTP 500 do vấn đề dependency môi trường dev (Prisma/DB chưa được cấu hình đầy đủ)
- Bỏ qua test search (Typesense không khả dụng trong dev)
**Blocker:** Load tests must be re-run against a staging environment with fully operational backend dependencies (PostgreSQL, Redis, Typesense, VNPay sandbox). Framework-level latency is validated; business logic performance is not.
**Blocker:** Load test phải được chạy lại với môi trường staging có đầy đủ các dependency backend hoạt động (PostgreSQL, Redis, Typesense, sandbox VNPay). Latency ở mức framework đã được validate; hiệu năng business logic thì chưa.
**Required action:**
- [ ] Provision staging environment with all dependencies
- [ ] Re-run K6 suites against staging
- [ ] Validate error rate < 1% across all critical paths
- [ ] Document production-equivalent load test results
**Hành động cần thiết:**
- [ ] Provision môi trường staging với tất cả dependency
- [ ] Chạy lại bộ test K6 với staging
- [ ] Validate error rate < 1% trên tất cả critical path
- [ ] Tài liệu hóa kết quả load test tương đương production
---
### 2. Security Penetration Test Sign-off
### 2. Sign-off Penetration Test Bảo Mật
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | FAIL |
| **Trạng thái** | FAIL |
| **Owner** | CTO / DevOps Engineer |
| **Evidence** | None — no formal pen-test report exists |
| **Bằng chứng** | Không có — chưa có báo cáo pen-test chính thức |
**Findings:**
- Automated security scanning exists (`.github/workflows/security.yml`, `.github/workflows/codeql.yml`)
- No formal third-party or manual penetration test has been conducted
- No security sign-off document exists
**Phát hiện:**
- Có scanning bảo mật tự động (`.github/workflows/security.yml`, `.github/workflows/codeql.yml`)
- Chưa có penetration test chính thức từ bên thứ ba hoặc thủ công
- Chưa có tài liệu sign-off bảo mật
**Blocker:** Production launch requires a formal security assessment covering OWASP Top 10, authentication flows (JWT, OAuth, CSRF), payment endpoint security, and API authorization boundaries.
**Blocker:** Launch production yêu cầu đánh giá bảo mật chính thức bao quát OWASP Top 10, các luồng xác thực (JWT, OAuth, CSRF), bảo mật endpoint thanh toán, và ranh giới authorization API.
**Required action:**
- [ ] Schedule penetration test (internal or third-party)
- [ ] Scope: auth flows, payment callbacks (VNPay/MoMo/ZaloPay), admin endpoints, file upload, geospatial API
- [ ] Remediate critical/high findings
- [ ] Obtain signed pen-test report and remediation confirmation
**Hành động cần thiết:**
- [ ] Lên lịch penetration test (nội bộ hoặc bên thứ ba)
- [ ] Phạm vi: luồng auth, callback thanh toán (VNPay/MoMo/ZaloPay), endpoint admin, file upload, API geospatial
- [ ] Khắc phục các phát hiện critical/high
- [ ] Lấy báo cáo pen-test có chữ ký và xác nhận khắc phục
---
### 3. Monitoring Alert Thresholds Configured
### 3. Cấu Hình Ngưỡng Alert Monitoring
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PASS |
| **Trạng thái** | PASS |
| **Owner** | SRE Engineer |
| **Evidence** | [`monitoring/prometheus/alert-rules.yml`](../monitoring/prometheus/alert-rules.yml) |
| **Bằng chứng** | [`monitoring/prometheus/alert-rules.yml`](../monitoring/prometheus/alert-rules.yml) |
**Findings:**
- 15+ Prometheus alert rules configured across multiple groups:
- `goodgo_api_latency`p99 latency warnings (>1s), critical SLO breach (>3s), per-endpoint latency
- `goodgo_api_errors`5xx error rate alerts
- `goodgo_database` — connection pool exhaustion, query latency
- `goodgo_infrastructure` — disk, memory, CPU, container health
- Alert severity levels: `warning` and `critical`
- Runbook URLs linked in alert annotations
- Grafana dashboards referenced for investigation
- AlertManager integration configured
**Phát hiện:**
- 15+ alert rule Prometheus đã cấu hình trên nhiều nhóm:
- `goodgo_api_latency`cảnh báo latency p99 (>1s), critical SLO breach (>3s), latency theo từng endpoint
- `goodgo_api_errors`alert tỷ lệ lỗi 5xx
- `goodgo_database` cạn kiệt connection pool, latency truy vấn
- `goodgo_infrastructure` — disk, memory, CPU, sức khỏe container
- Mức độ severity alert: `warning` `critical`
- URL runbook được link trong annotation alert
- Dashboard Grafana được tham chiếu cho việc điều tra
- AlertManager đã được tích hợp
**Status: READY** — Alert thresholds are well-defined and follow best practices.
**Trạng thái: SẴN SÀNG** — Ngưỡng alert được định nghĩa rõ ràng và theo best practice.
---
### 4. Backup/Restore Verification Completed
### 4. Hoàn Tất Verify Backup/Restore
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PASS |
| **Trạng thái** | PASS |
| **Owner** | SRE Engineer / DevOps Engineer |
| **Evidence** | [`docs/backup-restore.md`](backup-restore.md), [`.github/workflows/backup-verify.yml`](../.github/workflows/backup-verify.yml) |
| **Bằng chứng** | [`docs/backup-restore.md`](backup-restore.md), [`.github/workflows/backup-verify.yml`](../.github/workflows/backup-verify.yml) |
**Findings:**
- Daily automated PostgreSQL backups (02:00 UTC) via `pg_dump` custom format
- 7-day retention policy (configurable via `BACKUP_RETENTION_DAYS`)
- Automated weekly backup verification via GitHub Actions workflow
- RTO target: ≤ 30 minutes | RPO target: ≤ 24 hours
- Manual backup/restore procedures documented
- Restore tested and documented with step-by-step runbook
**Phát hiện:**
- Backup PostgreSQL hằng ngày tự động (02:00 UTC) qua `pg_dump` định dạng custom
- Chính sách giữ 7 ngày (có thể cấu hình qua `BACKUP_RETENTION_DAYS`)
- Tự động verify backup hằng tuần qua GitHub Actions workflow
- Mục tiêu RTO: ≤ 30 phút | Mục tiêu RPO: ≤ 24 giờ
- Quy trình backup/restore thủ công đã được tài liệu hóa
- Restore đã được test và tài liệu hóa với runbook từng bước
**Status: READY** — Backup procedures are automated, verified, and documented.
**Trạng thái: SẴN SÀNG** — Quy trình backup được tự động hóa, đã verify và tài liệu hóa.
**Recommendation:** Consider WAL archiving for continuous point-in-time recovery to reduce RPO below 24 hours.
**Khuyến nghị:** Cân nhắc WAL archiving cho point-in-time recovery liên tục để giảm RPO xuống dưới 24 giờ.
---
### 5. Incident Response Runbook Reviewed
### 5. Đã Review Runbook Phản Ứng Sự Cố
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PASS |
| **Trạng thái** | PASS |
| **Owner** | SRE Engineer |
| **Evidence** | [`docs/RUNBOOK.md`](RUNBOOK.md) |
| **Bằng chứng** | [`docs/RUNBOOK.md`](RUNBOOK.md) |
**Findings:**
- Comprehensive 41KB runbook covering:
- Service inventory and health checks
- 10 common incident scenarios (DB pool exhaustion, Redis failure, Typesense unavailable, high latency, payment callback failures, disk alerts, MinIO failure, AI service outage, log pipeline failure, 5xx spikes)
- 6 recovery procedures (DB restore, Redis flush, rolling restart, rollback, Typesense reindex, full host recovery)
- Escalation matrix
- Monitoring dashboard links
- Useful PromQL queries
- Environment quick reference
- Last updated: 2026-04-11
**Phát hiện:**
- Runbook 41KB toàn diện bao quát:
- Danh mục dịch vụ và health check
- 10 kịch bản sự cố thường gặp (cạn DB pool, Redis fail, Typesense không khả dụng, latency cao, lỗi callback thanh toán, alert disk, MinIO fail, AI service mất, lỗi pipeline log, đột biến 5xx)
- 6 quy trình recovery (restore DB, flush Redis, rolling restart, rollback, reindex Typesense, recovery toàn host)
- Ma trận escalation
- Link đến dashboard monitoring
- Các truy vấn PromQL hữu ích
- Tham khảo nhanh môi trường
- Cập nhật lần cuối: 2026-04-11
**Status: READY** — Runbook is thorough and up to date.
**Trạng thái: SẴN SÀNG** — Runbook đầy đủ và cập nhật.
---
### 6. Database Schema Frozen (Migration Lockdown)
### 6. Đóng Băng Schema Database (Migration Lockdown)
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PASS (conditional) |
| **Trạng thái** | PASS (có điều kiện) |
| **Owner** | DevOps Engineer / CTO |
| **Evidence** | `prisma/migrations/` (16 migrations), `prisma/migrations/migration_lock.toml` |
| **Bằng chứng** | `prisma/migrations/` (16 migration), `prisma/migrations/migration_lock.toml` |
**Findings:**
- 16 sequential Prisma migrations exist
- Latest migration: `20260411200000_add_mfa_totp_support` (2026-04-11)
- Migration lock file present (`migration_lock.toml`)
- 22 database models defined (User, Property, Listing, Payment, Subscription, etc.)
- PostGIS extension configured for geospatial queries
**Phát hiện:**
- 16 migration Prisma tuần tự đã có
- Migration mới nhất: `20260411200000_add_mfa_totp_support` (2026-04-11)
- Có file migration lock (`migration_lock.toml`)
- 22 model database đã được định nghĩa (User, Property, Listing, Payment, Subscription, v.v.)
- PostGIS extension đã cấu hình cho truy vấn geospatial
**Condition:** Schema must be formally frozen before launch. Recent migrations (4 on 2026-04-10/11) indicate active schema changes. A freeze date must be declared and no new migrations accepted after that date without CTO sign-off.
**Điều kiện:** Schema phải được đóng băng chính thức trước khi launch. Các migration gần đây (4 cái vào 2026-04-10/11) cho thấy schema đang được thay đổi tích cực. Phải khai báo ngày freeze và không chấp nhận migration mới sau ngày đó nếu không có sign-off của CTO.
**Required action:**
- [ ] Declare schema freeze date (recommended: 48 hours before launch)
- [ ] Communicate freeze to all developers
- [ ] CTO approval required for any post-freeze schema changes
**Hành động cần thiết:**
- [ ] Khai báo ngày freeze schema (khuyến nghị: 48 giờ trước launch)
- [ ] Thông báo freeze đến tất cả developer
- [ ] Cần phê duyệt CTO cho mọi thay đổi schema sau freeze
---
### 7. CI/CD Pipeline Green (Lint, Typecheck, Test, Build)
### 7. CI/CD Pipeline Xanh (Lint, Typecheck, Test, Build)
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | PASS |
| **Trạng thái** | PASS |
| **Owner** | DevOps Engineer |
| **Evidence** | `.github/workflows/` (7 workflows) |
| **Bằng chứng** | `.github/workflows/` (7 workflow) |
**Findings:**
- **ci.yml** — Full pipeline: lint → typecheck → test → build
- **deploy.yml** — Deployment automation
- **e2e.yml** — Playwright E2E test suite
- **security.yml** — Automated security scanning
- **codeql.yml** — GitHub CodeQL analysis
- **load-test.yml** — K6 load test automation
- **backup-verify.yml** — Weekly backup verification
**Phát hiện:**
- **ci.yml** — Pipeline đầy đủ: lint → typecheck → test → build
- **deploy.yml** — Tự động hóa deployment
- **e2e.yml** — Bộ test E2E Playwright
- **security.yml** — Scan bảo mật tự động
- **codeql.yml** — Phân tích GitHub CodeQL
- **load-test.yml** — Tự động hóa load test K6
- **backup-verify.yml** — Verify backup hằng tuần
**Status: READY**CI/CD pipeline is comprehensive and covers the full quality gate (lint, typecheck, unit tests, build, E2E, security, load testing).
**Trạng thái: SẴN SÀNG**Pipeline CI/CD toàn diện và bao quát đầy đủ quality gate (lint, typecheck, unit test, build, E2E, security, load test).
---
### 8. E2E Test Results
### 8. Kết Quả Test E2E
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | FAIL |
| **Owner** | DevOps Engineer / Backend Engineers |
| **Evidence** | `e2e/` (31 test spec files across `api/`, `web/`, `load/`) |
| **Trạng thái** | FAIL |
| **Owner** | DevOps Engineer / Backend Engineer |
| **Bằng chứng** | `e2e/` (31 file test spec trên `api/`, `web/`, `load/`) |
**Findings:**
- 31 E2E test spec files covering API and Web surfaces
- Test infrastructure: Playwright with global setup/teardown
- Organized by domain: `api/` (backend API tests), `web/` (frontend browser tests), `load/` (load scenario tests)
- **2 tests currently failing** (per last Playwright run)
- No saved `test-results/.last-run.json` available for detailed failure analysis
**Phát hiện:**
- 31 file test spec E2E bao quát surface API Web
- Hạ tầng test: Playwright với global setup/teardown
- Tổ chức theo domain: `api/` (test API backend), `web/` (test browser frontend), `load/` (test kịch bản tải)
- **2 test hiện đang fail** (theo lần chạy Playwright cuối)
- Không có file `test-results/.last-run.json` được lưu lại để phân tích chi tiết lỗi
**Blocker:** All E2E tests must pass before production launch.
**Blocker:** Tất cả test E2E phải pass trước khi launch production.
**Required action:**
- [ ] Run full E2E suite: `pnpm test:e2e`
- [ ] Fix 2 failing tests
- [ ] Achieve 100% pass rate on the full suite
- [ ] Archive passing test results as evidence
**Hành động cần thiết:**
- [ ] Chạy bộ test E2E đầy đủ: `pnpm test:e2e`
- [ ] Sửa 2 test đang fail
- [ ] Đạt 100% pass rate trên bộ test đầy đủ
- [ ] Lưu trữ kết quả test pass làm bằng chứng
---
### 9. Performance Benchmarks Documented
### 9. Tài Liệu Hóa Benchmark Hiệu Năng
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | BLOCKED |
| **Trạng thái** | BLOCKED |
| **Owner** | SRE Engineer |
| **Evidence** | [`load-tests/results/BASELINE-REPORT.md`](../load-tests/results/BASELINE-REPORT.md) (partial) |
| **Bằng chứng** | [`load-tests/results/BASELINE-REPORT.md`](../load-tests/results/BASELINE-REPORT.md) (một phần) |
**Findings:**
- Framework-level latency benchmarks documented (p50/p95/p99)
- Business logic benchmarks not available (auth returns 500, search unavailable)
- No production-equivalent performance profile exists
- Blocked on staging environment availability
**Phát hiện:**
- Benchmark latency mức framework đã được tài liệu hóa (p50/p95/p99)
- Benchmark business logic không khả dụng (auth trả 500, search không khả dụng)
- Chưa có profile hiệu năng tương đương production
- Bị chặn vì chưa có môi trường staging
**Blocker:** Cannot establish meaningful performance benchmarks without a staging environment running all dependencies.
**Blocker:** Không thể thiết lập benchmark hiệu năng có ý nghĩa nếu không có môi trường staging chạy đầy đủ dependency.
**Required action:**
- [ ] Provision staging environment
- [ ] Run K6 suites with real database, Redis, Typesense
- [ ] Document per-endpoint latency baselines (auth, listings CRUD, search, payments)
- [ ] Establish throughput capacity (max concurrent users per instance)
- [ ] Document resource utilization under load (CPU, memory, connections)
**Hành động cần thiết:**
- [ ] Provision môi trường staging
- [ ] Chạy bộ test K6 với database, Redis, Typesense thật
- [ ] Tài liệu hóa baseline latency theo từng endpoint (auth, CRUD listing, search, payment)
- [ ] Thiết lập sức chứa throughput (số user đồng thời tối đa mỗi instance)
- [ ] Tài liệu hóa mức sử dụng tài nguyên dưới tải (CPU, memory, connection)
---
### 10. SSL/TLS Certificates Ready
### 10. Sẵn Sàng Chứng Chỉ SSL/TLS
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | FAIL |
| **Trạng thái** | FAIL |
| **Owner** | DevOps Engineer |
| **Evidence** | `docs/deployment.md` (line ~146, unchecked item) |
| **Bằng chứng** | `docs/deployment.md` (dòng ~146, mục chưa tích) |
**Findings:**
- No reverse proxy (nginx/Caddy/Traefik) configured in `docker-compose.prod.yml`
- No SSL/TLS certificate provisioning (Let's Encrypt, manual, or cloud-managed)
- Deployment doc lists SSL/TLS as an unchecked to-do item
- API and web services currently exposed on plain HTTP
**Phát hiện:**
- Chưa có reverse proxy (nginx/Caddy/Traefik) cấu hình trong `docker-compose.prod.yml`
- Chưa có cấp chứng chỉ SSL/TLS (Let's Encrypt, thủ công, hay cloud-managed)
- Tài liệu deployment liệt kê SSL/TLS như một mục to-do chưa tích
- API web service hiện đang exposed trên HTTP thường
**Blocker:** All production traffic must be encrypted via HTTPS.
**Blocker:** Tất cả lưu lượng production phải được mã hóa qua HTTPS.
**Required action:**
- [ ] Add reverse proxy service (nginx or Traefik) to `docker-compose.prod.yml`
- [ ] Configure Let's Encrypt auto-renewal (certbot or Traefik ACME)
- [ ] Enforce HTTPS redirect (HTTP → HTTPS)
- [ ] Configure HSTS headers
- [ ] Verify certificate chain validity
**Hành động cần thiết:**
- [ ] Thêm dịch vụ reverse proxy (nginx hoặc Traefik) o `docker-compose.prod.yml`
- [ ] Cấu hình tự động gia hạn Let's Encrypt (certbot hoặc Traefik ACME)
- [ ] Bắt buộc redirect HTTPS (HTTP → HTTPS)
- [ ] Cấu hình HSTS header
- [ ] Verify tính hợp lệ của chuỗi chứng chỉ
---
### 11. DNS Configuration Verified
### 11. Verify Cấu Hình DNS
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | FAIL |
| **Trạng thái** | FAIL |
| **Owner** | DevOps Engineer / CTO |
| **Evidence** | None — no DNS configuration documented |
| **Bằng chứng** | Không có — chưa có cấu hình DNS được tài liệu hóa |
**Findings:**
- No domain names registered or documented (e.g., goodgo.vn, api.goodgo.vn)
- No DNS zone files or configuration in `infra/`
- No documentation for DNS provider setup
- Deployment doc does not reference DNS configuration
**Phát hiện:**
- Chưa có domain nào được đăng ký hoặc tài liệu hóa (vd: goodgo.vn, api.goodgo.vn)
- Không có DNS zone file hay cấu hình trong `infra/`
- Không có tài liệu cho cấu hình DNS provider
- Tài liệu deployment không tham chiếu cấu hình DNS
**Blocker:** Production requires domain names with proper DNS records.
**Blocker:** Production yêu cầu domain với DNS record phù hợp.
**Required action:**
- [ ] Register production domain(s) (e.g., goodgo.vn)
- [ ] Configure DNS A/CNAME records for web (goodgo.vn) and API (api.goodgo.vn)
- [ ] Set up DNS monitoring/health checks
- [ ] Document DNS provider and record configuration in `docs/`
- [ ] Configure appropriate TTL values
**Hành động cần thiết:**
- [ ] Đăng ký domain production (vd: goodgo.vn)
- [ ] Cấu hình DNS A/CNAME record cho web (goodgo.vn) API (api.goodgo.vn)
- [ ] Cài đặt monitoring/health check cho DNS
- [ ] Tài liệu hóa nhà cung cấp DNS và cấu hình record trong `docs/`
- [ ] Cấu hình giá trị TTL phù hợp
---
### 12. CDN Setup for Static Assets
### 12. Cài Đặt CDN Cho Static Asset
| Field | Value |
| Trường | Giá trị |
|-------|-------|
| **Status** | FAIL |
| **Trạng thái** | FAIL |
| **Owner** | DevOps Engineer |
| **Evidence** | `docs/deployment.md` (line ~167, unchecked item) |
| **Bằng chứng** | `docs/deployment.md` (dòng ~167, mục chưa tích) |
**Findings:**
- No CDN (Cloudflare, CloudFront, or similar) configured
- Next.js static assets served directly from origin
- No edge caching for images, JS bundles, or CSS
- Deployment doc lists CDN as an unchecked to-do item
**Phát hiện:**
- Chưa cấu hình CDN (Cloudflare, CloudFront hay tương tự)
- Static asset của Next.js phục vụ trực tiếp từ origin
- Không có edge caching cho ảnh, JS bundle hay CSS
- Tài liệu deployment liệt kê CDN như một mục to-do chưa tích
**Blocker:** CDN improves Vietnamese user experience (latency, availability) and protects origin from DDoS.
**Blocker:** CDN cải thiện trải nghiệm người dùng Việt Nam (latency, tính sẵn sàng) và bảo vệ origin khỏi DDoS.
**Required action:**
- [ ] Select CDN provider (Cloudflare recommended for ease; CloudFront if on AWS)
- [ ] Configure CDN for Next.js static assets (`_next/static/`)
- [ ] Set cache headers for immutable assets
- [ ] Configure CDN for image optimization (property photos)
- [ ] Set up DDoS protection rules
**Hành động cần thiết:**
- [ ] Chọn nhà cung cấp CDN (khuyến nghị Cloudflare để dễ; CloudFront nếu trên AWS)
- [ ] Cấu hình CDN cho static asset Next.js (`_next/static/`)
- [ ] Đặt cache header cho asset bất biến
- [ ] Cấu hình CDN cho tối ưu hình ảnh (ảnh bất động sản)
- [ ] Cài đặt rule bảo vệ DDoS
---
## Critical Blockers Summary
## Tóm Tắt Blocker Quan Trọng
| # | Blocker | Owner | Priority | Dependency |
| # | Blocker | Owner | Ưu tiên | Phụ thuộc |
|---|---------|-------|----------|------------|
| B1 | Security penetration test not conducted | CTO / DevOps | **P0 — Critical** | External scheduling |
| B2 | 2 E2E tests failing | DevOps / Backend | **P0 — Critical** | Code fix required |
| B3 | SSL/TLS not configured | DevOps | **P0 — Critical** | Requires reverse proxy setup |
| B4 | DNS not configured | DevOps / CTO | **P0 — Critical** | Requires domain registration |
| B5 | Performance benchmarks blocked on staging | SRE | **P1 — High** | Requires staging environment |
| B6 | CDN not set up | DevOps | **P1 — High** | Requires CDN provider decision |
| B1 | Chưa có penetration test bảo mật | CTO / DevOps | **P0 — Critical** | Sắp lịch bên ngoài |
| B2 | 2 test E2E đang fail | DevOps / Backend | **P0 — Critical** | Cần fix code |
| B3 | Chưa cấu hình SSL/TLS | DevOps | **P0 — Critical** | Cần setup reverse proxy |
| B4 | Chưa cấu hình DNS | DevOps / CTO | **P0 — Critical** | Cần đăng ký domain |
| B5 | Benchmark hiệu năng bị chặn vì staging | SRE | **P1 — High** | Cần môi trường staging |
| B6 | Chưa setup CDN | DevOps | **P1 — High** | Cần quyết định nhà cung cấp CDN |
---
## Sign-off
Production launch requires sign-off from all listed roles after all checklist items pass.
Launch production yêu cầu sign-off từ tất cả vai trò được liệt kê sau khi tất cả mục checklist pass.
| Role | Name | Status | Date | Signature |
| Vai trò | Tên | Trạng thái | Ngày | Chữ ký |
|------|------|--------|------|-----------|
| SRE Engineer | — | Pending | — | — |
| DevOps Engineer | — | Pending | — | — |
@@ -334,8 +334,8 @@ Production launch requires sign-off from all listed roles after all checklist it
---
## Revision History
## Lịch Sử Sửa Đổi
| Date | Author | Changes |
| Ngày | Tác giả | Thay đổi |
|------|--------|---------|
| 2026-04-12 | SRE Engineer | Initial checklist created, 12 items assessed |
| 2026-04-12 | SRE Engineer | Tạo checklist ban đầu, đánh giá 12 mục |

View File

@@ -1,8 +1,8 @@
# GoodGo Platform - Authentication Quick Reference
# GoodGo Platform - Tham chiếu nhanh Authentication
## 🔑 Key Points at a Glance
## 🔑 Các điểm chính trong nháy mắt
### Password Hashing
### Hash mật khẩu
```
Algorithm: bcrypt
Salt Rounds: 12 (env: BCRYPT_ROUNDS)
@@ -10,7 +10,7 @@ Min Length: 8 characters
Example: bcrypt.hash('password', 12)
```
### Phone Numbers (Vietnamese)
### Số điện thoại (Việt Nam)
```
Valid Formats: 0900000001, 84900000001, +84900000001
Normalized: +84900000001
@@ -25,7 +25,7 @@ Normalization: lowercase + trim
Storage: admin@goodgo.vn
```
### PII Encryption
### Mã hoá PII
```
Algorithm: AES-256-GCM
Key: 32 bytes (64 hex chars)
@@ -35,7 +35,7 @@ Searchable: email → emailHash (HMAC-SHA256)
Env Var: FIELD_ENCRYPTION_KEY
```
### User Login
### Đăng nhập User
```
Username: phone (normalized)
Password: plain text
@@ -44,7 +44,7 @@ Required: isActive = true, passwordHash ≠ null
Response: tokens (or MFA challenge)
```
### User Roles
### Vai trò người dùng
```
BUYER - Search, inquire, offer (default)
SELLER - Create listings
@@ -63,33 +63,33 @@ Hashing: HMAC-SHA256 (not bcrypt)
---
## 📋 Creating a Login-Capable Admin User
## 📋 Tạo người dùng Admin có thể đăng nhập
### 5-Step Process
### Quy trình 5 bước
**1. Normalize phone**
**1. Chuẩn hoá số điện thoại**
```typescript
phone = '0900000001' '+84900000001'
```
**2. Derive HMAC key**
**2. Tạo HMAC key**
```typescript
hmacKey = crypto.hkdfSync('sha256', Buffer.from(encryptionKey, 'hex'),
Buffer.alloc(0), Buffer.from('goodgo-field-hash', 'utf8'), 32)
```
**3. Compute hashes**
**3. Tính các hash**
```typescript
phoneHash = crypto.createHmac('sha256', hmacKey).update('+84900000001').digest('hex')
emailHash = crypto.createHmac('sha256', hmacKey).update('admin@goodgo.vn').digest('hex')
```
**4. Hash password**
**4. Hash mật khẩu**
```typescript
passwordHash = await bcrypt.hash('AdminPassword123', 12)
```
**5. Create user**
**5. Tạo user**
```typescript
await prisma.user.create({
data: {
@@ -111,7 +111,7 @@ await prisma.user.create({
---
## 🧪 Test Login
## 🧪 Test đăng nhập
```bash
curl -X POST http://localhost:3000/auth/login \
@@ -122,7 +122,7 @@ curl -X POST http://localhost:3000/auth/login \
}'
```
**Success Response:**
**Response thành công:**
```json
{
"requiresMfa": false,
@@ -136,42 +136,42 @@ curl -X POST http://localhost:3000/auth/login \
---
## ⚠️ Common Issues
## ⚠️ Vấn đề thường gặp
| Issue | Fix |
| Vấn đề | Cách sửa |
|-------|-----|
| User can't login | Check: `passwordHash` ≠ null, `isActive` = true |
| "Invalid phone" | Phone must match regex (mobile only) |
| Hash mismatch | Verify `FIELD_ENCRYPTION_KEY` is consistent |
| MFA issue | Verify `MFA_BACKUP_CODE_SECRET` env var |
| PII not encrypted | Verify key is exactly 32 bytes (64 hex chars) |
| User không đăng nhập được | Kiểm tra: `passwordHash` ≠ null, `isActive` = true |
| "Invalid phone" | Phone phải khớp regex (chỉ mobile) |
| Hash không khớp | Xác minh `FIELD_ENCRYPTION_KEY` nhất quán |
| Vấn đề MFA | Xác minh biến môi trường `MFA_BACKUP_CODE_SECRET` |
| PII không được mã hoá | Xác minh key đúng 32 bytes (64 ký tự hex) |
---
## 📁 Key Files
## 📁 Các file chính
| File | Purpose |
| File | Mục đích |
|------|---------|
| `hashed-password.vo.ts` | bcrypt hashing |
| `vietnam-phone.validator.ts` | Phone validation |
| `field-encryption.ts` | AES-256-GCM encryption |
| `local.strategy.ts` | Login endpoint |
| `mfa.service.ts` | TOTP / backup codes |
| `user.entity.ts` | User domain model |
| `prisma-user.repository.ts` | User persistence |
| `seed.ts` | Seed script |
| `hashed-password.vo.ts` | Hash bcrypt |
| `vietnam-phone.validator.ts` | Validation số điện thoại |
| `field-encryption.ts` | Mã hoá AES-256-GCM |
| `local.strategy.ts` | Endpoint đăng nhập |
| `mfa.service.ts` | TOTP / backup code |
| `user.entity.ts` | Domain model User |
| `prisma-user.repository.ts` | Persistence User |
| `seed.ts` | Script seed |
---
## 🔐 Checklist for Seed User
## 🔐 Checklist cho Seed User
- [ ] Password ≥ 8 chars
- [ ] Phone matches regex
- [ ] Phone normalized: +84...
- [ ] Phone hashed: HMAC-SHA256
- [ ] Email lowercased
- [ ] Email hashed: HMAC-SHA256
- [ ] Password hashed: bcrypt (12 rounds)
- [ ] Mật khẩu ≥ 8 ký tự
- [ ] Phone khớp regex
- [ ] Phone đã chuẩn hoá: +84...
- [ ] Phone đã hash: HMAC-SHA256
- [ ] Email đã chuyển lowercase
- [ ] Email đã hash: HMAC-SHA256
- [ ] Password đã hash: bcrypt (12 rounds)
- [ ] `isActive: true`
- [ ] `passwordHash` ≠ null
- [ ] `totpEnabled: false`
@@ -179,14 +179,14 @@ curl -X POST http://localhost:3000/auth/login \
---
## 📚 Full Documentation Files
## 📚 Các file tài liệu đầy đủ
1. **AUTHENTICATION_GUIDE.md** - Complete technical reference
2. **AUTH_IMPLEMENTATION_CHECKLIST.md** - Implementation checklist & troubleshooting
3. **SEED_GENERATION_SCRIPT.ts** - Ready-to-use seed script
4. **QUICK_REFERENCE.md** - This file
1. **AUTHENTICATION_GUIDE.md** - Tham chiếu kỹ thuật đầy đủ
2. **AUTH_IMPLEMENTATION_CHECKLIST.md** - Checklist triển khai & troubleshoot
3. **SEED_GENERATION_SCRIPT.ts** - Script seed sẵn sàng dùng
4. **QUICK_REFERENCE.md** - File này
---
**Last Updated:** April 12, 2026
**Status:** Production-Ready
**Cập nhật cuối:** 12 tháng 4, 2026
**Trạng thái:** ✅ Sẵn sàng Production

View File

@@ -1,26 +1,26 @@
# GoodGo Platform — Quick Start Reference
# GoodGo Platform — Tham Khảo Nhanh
**Status:** MVP Complete (Phase 7 Wave 14) ✅
**Generated:** April 12, 2026
**Trạng thái:** MVP Hoàn Tất (Phase 7 Wave 14) ✅
**Ngày tạo:** 12 tháng 4, 2026
---
## 📊 PROJECT MATURITY AT A GLANCE
## 📊 MỨC ĐỘ HOÀN THIỆN DỰ ÁN
| Category | Rating | Details |
| Hạng mục | Đánh giá | Chi tiết |
|----------|--------|---------|
| **Feature Completeness** | 🟢 95% | All MVP features done; 3 edge cases remaining |
| **Code Quality** | 🟢 High | 242 tests, ESLint pass, DDD architecture |
| **Security** | 🟢 Hardened | JWT/MFA, encryption, rate limiting, CSRF protection |
| **Documentation** | 🟢 Comprehensive | 80+ audit files, runbooks, API reference |
| **Performance** | 🟢 Optimized | Caching, indexing, K6 load tests baseline |
| **Ops Readiness** | 🟢 Ready | Docker/Kubernetes, monitoring, backup strategy |
| **Hoàn thiện tính năng** | 🟢 95% | Tất cả tính năng MVP xong; còn 3 edge case |
| **Chất lượng code** | 🟢 Cao | 242 test, ESLint pass, kiến trúc DDD |
| **Bảo mật** | 🟢 Hardened | JWT/MFA, mã hóa, rate limiting, bảo vệ CSRF |
| **Tài liệu** | 🟢 Toàn diện | 80+ file audit, runbook, tham khảo API |
| **Hiệu năng** | 🟢 Đã tối ưu | Cache, indexing, K6 load test baseline |
| **Sẵn sàng vận hành** | 🟢 Sẵn sàng | Docker/Kubernetes, monitoring, chiến lược backup |
**Overall:****Production Ready**Ready to launch with 3 minor fixes
**Tổng thể:****Sẵn sàng Production**Sẵn sàng launch với 3 fix nhỏ
---
## 🏗️ ARCHITECTURE AT A GLANCE
## 🏗️ KIẾN TRÚC TỔNG QUAN
```
Frontend Backend Database
@@ -44,312 +44,312 @@ ioredis Full-text + geo Pre-signed URLs
---
## 📦 KEY STATISTICS
## 📦 THỐNG KÊ CHÍNH
```
Code: ~50,000 LOC
Backend: 845 TypeScript files (18 modules)
Frontend: 245 TypeScript/TSX files
Database: 31 models, 30+ indexes, 7+ migrations
Tests: 242 files (unit + E2E + load)
API: 100+ endpoints (Swagger documented)
Deployment: Docker + Kubernetes ready
Backend: 845 file TypeScript (18 module)
Frontend: 245 file TypeScript/TSX
Database: 31 model, 30+ index, 7+ migration
Tests: 242 file (unit + E2E + load)
API: 100+ endpoint (đã tài liệu Swagger)
Deployment: Sẵn sàng Docker + Kubernetes
```
---
## 🚀 QUICK START COMMANDS
## 🚀 LỆNH KHỞI ĐỘNG NHANH
### Local Development
### Phát Triển Local
```bash
# Install & start everything
# Cài đặt và khởi động tất cả
docker-compose up -d
# API development
# Phát triển API
cd apps/api
pnpm dev # Watch mode on :3001
pnpm dev # Chế độ watch ở :3001
# Frontend development
# Phát triển frontend
cd apps/web
pnpm dev # Dev server on :3000
pnpm dev # Dev server :3000
# Both together (from root)
pnpm dev # All apps via Turbo
# Cả hai cùng lúc (từ root)
pnpm dev # Tất cả app qua Turbo
```
### Testing
```bash
pnpm test # All unit tests
pnpm test:e2e # All E2E tests (Playwright)
pnpm test:e2e:web # Just web E2E
pnpm test:e2e:api # Just API E2E
pnpm test:e2e:report # View Playwright report
pnpm test # Tất cả unit test
pnpm test:e2e # Tất cả E2E test (Playwright)
pnpm test:e2e:web # Chỉ E2E web
pnpm test:e2e:api # Chỉ E2E API
pnpm test:e2e:report # Xem report Playwright
```
### Database
```bash
pnpm db:generate # Regenerate Prisma client
pnpm db:migrate:dev # Create & apply migration
pnpm db:push # Push schema (dev only)
pnpm db:seed # Seed test data
pnpm db:studio # Prisma Studio UI (localhost:5555)
pnpm db:generate # Sinh lại Prisma client
pnpm db:migrate:dev # Tạo và áp dụng migration
pnpm db:push # Push schema (chỉ dev)
pnpm db:seed # Seed dữ liệu test
pnpm db:studio # UI Prisma Studio (localhost:5555)
```
### Quality
### Chất Lượng
```bash
pnpm lint # ESLint check
pnpm format:check # Prettier check
pnpm format # Auto-format all files
pnpm typecheck # TypeScript check
pnpm dep-cruise # Architecture validation
pnpm lint # Kiểm tra ESLint
pnpm format:check # Kiểm tra Prettier
pnpm format # Tự format tất cả file
pnpm typecheck # Kiểm tra TypeScript
pnpm dep-cruise # Validate kiến trúc
```
### Build & Deployment
```bash
pnpm build # Build API + frontend
pnpm start # Start production server
pnpm start # Chạy production server
# Production Docker
# Docker production
docker-compose -f docker-compose.prod.yml up -d
```
---
## 📁 KEY FILES TO KNOW
## 📁 FILE QUAN TRỌNG CẦN BIẾT
### Planning & Status
- **PROJECT_TRACKER.md** — All 7 phases, 40+ issues, current status
- **IMPLEMENTATION_PLAN.md** — Feature roadmap with priority
- **CODEBASE_OVERVIEW.md** — Comprehensive guide (this was just created!)
### Lập Kế Hoạch & Trạng Thái
- **PROJECT_TRACKER.md** — Cả 7 phase, 40+ issue, trạng thái hiện tại
- **IMPLEMENTATION_PLAN.md** — Roadmap tính năng theo ưu tiên
- **CODEBASE_OVERVIEW.md** — Hướng dẫn toàn diện (vừa được tạo!)
### Architecture & Design
- **docs/architecture.md** — DDD layers, module boundaries, CQRS
- **docs/api-endpoints.md** — All endpoints with examples
- **docs/api-error-codes.md** — Error taxonomy & handling
### Kiến Trúc & Thiết Kế
- **docs/architecture.md** — Tầng DDD, ranh giới module, CQRS
- **docs/api-endpoints.md** — Tất cả endpoint kèm ví dụ
- **docs/api-error-codes.md** — Phân loại lỗi và xử lý
### Technical
- **prisma/schema.prisma** — Full database model (31 entities)
- **apps/api/src/modules/** — 18 feature modules (auth, listings, payments, etc.)
- **apps/web/app/** — Next.js routes & page groups
- **apps/web/components/** — UI components (16 directories)
### Kỹ Thuật
- **prisma/schema.prisma** — Model database đầy đủ (31 entity)
- **apps/api/src/modules/** — 18 module tính năng (auth, listings, payments, v.v.)
- **apps/web/app/** — Route và group page Next.js
- **apps/web/components/** — UI component (16 thư mục)
### Operations
- **docs/deployment.md** — Docker, Kubernetes, CI/CD steps
- **docs/RUNBOOK.md** — Operational procedures, troubleshooting
- **docker-compose.yml** — Local dev stack
- **docker-compose.prod.yml** — Production stack
### Vận Hành
- **docs/deployment.md** — Bước Docker, Kubernetes, CI/CD
- **docs/RUNBOOK.md** — Quy trình vận hành, troubleshooting
- **docker-compose.yml** — Stack dev local
- **docker-compose.prod.yml** — Stack production
---
## 🔧 API MODULES OVERVIEW
## 🔧 TỔNG QUAN MODULE API
### Authentication (1)
```
auth/
├── JWT + OAuth (Google, Zalo)
├── MFA/TOTP + backup codes
├── Passport strategies
└── Session management
├── MFA/TOTP + backup code
├── Passport strategy
└── Quản lý session
```
### Business Logic (5)
```
listings/ Properties + media upload + moderation
search/ Typesense + PostGIS geo-search
inquiries/ Buyer-to-seller messages
leads/ Agent CRM & lead scoring
reviews/ User ratings & reviews
listings/ Bất động sản + upload media + moderation
search/ Typesense + tìm kiếm địa lý PostGIS
inquiries/ Tin nhắn buyer-to-seller
leads/ CRM agent và lead scoring
reviews/ Đánh giá và review của user
```
### Monetization (2)
```
payments/ VNPay, MoMo, ZaloPay + webhooks
subscriptions/ 4 tiers (FREE, AGENT_PRO, INVESTOR, ENTERPRISE)
payments/ VNPay, MoMo, ZaloPay + webhook
subscriptions/ 4 tier (FREE, AGENT_PRO, INVESTOR, ENTERPRISE)
```
### Operations (5)
```
agents/ Agent profiles & verification
admin/ Moderation, KYC, audit logs
agents/ Hồ sơ agent và xác minh
admin/ Moderation, KYC, audit log
notifications/ Email, SMS, Push, Zalo OA
analytics/ Market reports, AI valuations
metrics/ Prometheus + HTTP metrics
analytics/ Báo cáo thị trường, định giá AI
metrics/ Prometheus + metric HTTP
```
### Infrastructure (4)
```
health/ Kubernetes liveness/readiness
shared/ DI, encryption, logger, events
health/ Liveness/readiness Kubernetes
shared/ DI, mã hóa, logger, event
mcp/ Model Context Protocol server
```
---
## 💾 DATABASE MODELS (31 TOTAL)
## 💾 MODEL DATABASE (TỔNG 31)
### Core (13)
```
User Main profile + KYC + MFA
Agent Extended agent profile
Property Address + geolocation
PropertyMedia Images/videos
Listing Sale/rent listing instance
SavedSearch User search preferences
User Hồ sơ chính + KYC + MFA
Agent Hồ sơ agent mở rộng
Property Địa chỉ + vị trí địa lý
PropertyMedia Hình ảnh/video
Listing Instance tin đăng bán/cho thuê
SavedSearch Tùy chọn tìm kiếm của user
```
### Commerce (9)
```
Transaction Inquiry → completed flow
Inquiry Buyer question on listing
Payment All payment methods + history
Plan Subscription tier definition
Subscription User's active plan
Order Auction settlement
Escrow Payment holding & release
Lead Agent CRM lead
Review User ratings
Transaction Luồng từ inquiry đến hoàn tất
Inquiry Câu hỏi buyer trên tin đăng
Payment Tất cả phương thức thanh toán + lịch sử
Plan Định nghĩa tier subscription
Subscription Plan đang active của user
Order Settlement đấu giá
Escrow Giữ và giải phóng thanh toán
Lead Lead CRM agent
Review Đánh giá user
```
### Operations (9)
```
RefreshToken JWT refresh chain
OAuthAccount OAuth provider links
MfaChallenge TOTP verification tracking
NotificationLog Sent notifications
NotificationPref User opt-in/out
AdminAuditLog Admin action audit trail
MarketIndex District/city statistics
Valuation AI price estimates
UsageRecord Subscription usage tracking
RefreshToken Chuỗi refresh JWT
OAuthAccount Liên kết OAuth provider
MfaChallenge Theo dõi xác minh TOTP
NotificationLog Thông báo đã gửi
NotificationPref Opt-in/out của user
AdminAuditLog Audit trail hành động admin
MarketIndex Thống kê quận/thành phố
Valuation Ước tính giá AI
UsageRecord Theo dõi sử dụng subscription
```
---
## 🧪 TESTING BREAKDOWN
## 🧪 PHÂN TÍCH TESTING
### Unit Tests (Vitest)
- Payment gateways (VNPay, MoMo, ZaloPay) — ~30 specs
- Value objects (Money, PlatformFee) — ~10 specs
- Stores & utilities (Auth, Currency) — ~20 specs
### Unit Test (Vitest)
- Payment gateway (VNPay, MoMo, ZaloPay) — ~30 spec
- Value object (Money, PlatformFee) — ~10 spec
- Store utility (Auth, Currency) — ~20 spec
### E2E Tests (Playwright)
- **Web (15 tests):** auth, listings, search, admin, responsive
- **API (16 tests):** all major endpoints
- **Load (K6):** baseline benchmarks, 1000 VU stress tests
### E2E Test (Playwright)
- **Web (15 test):** auth, listings, search, admin, responsive
- **API (16 test):** tất cả endpoint chính
- **Load (K6):** baseline benchmark, stress test 1000 VU
**Total: 242 test files**
**Tổng cộng: 242 file test**
---
## 🔐 SECURITY FEATURES
## 🔐 TÍNH NĂNG BẢO MẬT
✅ JWT authentication with refresh tokens
✅ JWT authentication với refresh token
✅ OAuth2 (Google, Zalo)
✅ TOTP/MFA with backup codes
Field-level encryption (PII)
CSRF protection middleware
✅ Rate limiting (global + per-user)
✅ HMAC-SHA256 for payment verification
✅ Helmet security headers
✅ CORS configured
Input validation & sanitization
✅ TOTP/MFA với backup code
Mã hóa cấp field (PII)
Middleware bảo vệ CSRF
✅ Rate limiting (toàn cục + theo user)
✅ HMAC-SHA256 cho verify thanh toán
✅ Header bảo mật Helmet
✅ CORS đã cấu hình
Validate và sanitize input
---
## 📊 MONITORING & OBSERVABILITY
```
Metrics Prometheus + Grafana (dashboards)
Logs Pino (structured) + Loki (aggregated)
Tracing Sentry (error tracking)
Alerts AlertManager (configured)
APM Core Web Vitals tracking
Health Checks /health (liveness), /ready (readiness)
Metric Prometheus + Grafana (dashboard)
Log Pino (structured) + Loki (tổng hợp)
Tracing Sentry (theo dõi lỗi)
Alert AlertManager (đã cấu hình)
APM Theo dõi Core Web Vitals
Health Check /health (liveness), /ready (readiness)
```
---
## 🚢 DEPLOYMENT OPTIONS
## 🚢 LỰA CHỌN DEPLOYMENT
### Option 1: Docker Compose (Development)
### Lựa chọn 1: Docker Compose (Development)
```bash
docker-compose up -d
# Runs: API (3001), Web (3000), DB, Redis, Typesense, etc.
# Chạy: API (3001), Web (3000), DB, Redis, Typesense, v.v.
```
### Option 2: Docker Compose Production
### Lựa chọn 2: Docker Compose Production
```bash
docker-compose -f docker-compose.prod.yml up -d
# Runs: Full stack with monitoring, logging, connection pooling
# Chạy: Stack đầy đủ với monitoring, logging, connection pooling
```
### Option 3: Kubernetes
- ConfigMaps for env variables
- Secrets for credentials
- PersistentVolumes for database
- HPA for auto-scaling
- Ingress for traffic routing
### Lựa chọn 3: Kubernetes
- ConfigMap cho biến env
- Secret cho credential
- PersistentVolume cho database
- HPA cho auto-scaling
- Ingress cho định tuyến traffic
**See:** `docs/deployment.md` for detailed steps
**Xem:** `docs/deployment.md` để biết các bước chi tiết
---
## ⚠️ KNOWN ISSUES (Phase 7 Wave 14)
## ⚠️ ISSUE ĐÃ BIẾT (Phase 7 Wave 14)
| ID | Title | Priority | Status |
| ID | Tiêu đề | Ưu tiên | Trạng thái |
|----|-------|----------|--------|
| TEC-1650 | Listing detail 404 error handling | High | todo |
| TEC-1652 | Full E2E test suite validation | High | todo |
| TEC-1657 | Comprehensive audit logging | High | todo |
| TEC-1650 | Xử lý lỗi 404 chi tiết tin đăng | High | todo |
| TEC-1652 | Validate bộ test E2E đầy đủ | High | todo |
| TEC-1657 | Audit logging toàn diện | High | todo |
**Impact:** Minimal (edge cases only)
**Fix ETA:** <2 hours each
**Ảnh hưởng:** Tối thiểu (chỉ edge case)
**ETA fix:** <2 giờ mỗi cái
---
## 📚 DOCUMENTATION STRUCTURE
## 📚 CẤU TRÚC TÀI LIỆU
```
/
├── PROJECT_TRACKER.md ← START HERE for status
├── IMPLEMENTATION_PLAN.md ← Feature roadmap
├── CODEBASE_OVERVIEW.md ← Comprehensive guide
├── ARCHITECTURE_SUMMARY.txt ← Visual overview
└── QUICK_START_REFERENCE.md ← This file
├── PROJECT_TRACKER.md ← BẮT ĐẦU TỪ ĐÂY cho trạng thái
├── IMPLEMENTATION_PLAN.md ← Roadmap tính năng
├── CODEBASE_OVERVIEW.md ← Hướng dẫn toàn diện
├── ARCHITECTURE_SUMMARY.txt ← Tổng quan trực quan
└── QUICK_START_REFERENCE.md ← File này
/docs/
├── architecture.md ← Technical deep dive
├── api-endpoints.md ← All endpoints (Swagger)
├── api-error-codes.md ← Error taxonomy
├── deployment.md ← Deploy instructions
├── dev-environment.md ← Local setup
├── RUNBOOK.md ← Operations guide
├── PRODUCTION_READINESS.md ← Compliance checklist
└── /audits/ ← 80+ implementation audits
├── architecture.md ← Sâu về kỹ thuật
├── api-endpoints.md ← Tất cả endpoint (Swagger)
├── api-error-codes.md ← Phân loại lỗi
├── deployment.md ← Hướng dẫn deploy
├── dev-environment.md ← Setup local
├── RUNBOOK.md ← Hướng dẫn vận hành
├── PRODUCTION_READINESS.md ← Checklist tuân thủ
└── /audits/ ← 80+ audit triển khai
```
---
## 🎯 NEXT STEPS
## 🎯 BƯỚC TIẾP THEO
1. **Understand:** Read `PROJECT_TRACKER.md` (5 min)
2. **Setup:** Run `docker-compose up` (2 min)
3. **Explore:** Visit `http://localhost:3000` (web) & `http://localhost:3001` (API)
4. **Test:** Run `pnpm test:e2e` to validate (5 min)
5. **Deploy:** Use `docker-compose.prod.yml` or Kubernetes manifests
1. **Hiểu:** Đọc `PROJECT_TRACKER.md` (5 phút)
2. **Setup:** Chạy `docker-compose up` (2 phút)
3. **Khám phá:** Truy cập `http://localhost:3000` (web) & `http://localhost:3001` (API)
4. **Test:** Chạy `pnpm test:e2e` để validate (5 phút)
5. **Deploy:** Dùng `docker-compose.prod.yml` hoặc manifest Kubernetes
---
## 🆘 TROUBLESHOOTING
### Port already in use
### Port đang được dùng
```bash
# Find process using port 3000/3001
# Tìm process đang dùng port 3000/3001
lsof -i :3000
kill -9 <PID>
```
### Database connection failed
### Kết nối database thất bại
```bash
# Reset database
pnpm db:reset
@@ -357,69 +357,69 @@ pnpm db:reset
pnpm db:seed
```
### Tests failing
### Test thất bại
```bash
# Clear cache
# Xóa cache
rm -rf .turbo
# Reinstall
# Cài lại
pnpm install
# Run again
# Chạy lại
pnpm test
```
### Docker issues
### Vấn đề Docker
```bash
# Complete reset
# Reset hoàn toàn
docker-compose down -v
docker-compose up --build
```
---
## 🎓 LEARNING PATHS
## 🎓 LỘ TRÌNH HỌC
### Backend Development
1. Read: `docs/architecture.md`
2. Explore: `apps/api/src/modules/auth` (simplest module)
3. Understand: DDD layers (presentation → application → domain → infrastructure)
4. Practice: Add a new endpoint following the pattern
### Phát Triển Backend
1. Đọc: `docs/architecture.md`
2. Khám phá: `apps/api/src/modules/auth` (module đơn giản nhất)
3. Hiểu: Tầng DDD (presentation → application → domain → infrastructure)
4. Thực hành: Thêm endpoint mới theo pattern
### Frontend Development
1. Review: `apps/web/app` (route structure)
2. Study: `components/listings` (complex component)
3. Learn: React Query patterns in `lib/*-api.ts`
4. Practice: Create a new feature page
### Phát Triển Frontend
1. Xem lại: `apps/web/app` (cấu trúc route)
2. Nghiên cứu: `components/listings` (component phức tạp)
3. Học: Pattern React Query trong `lib/*-api.ts`
4. Thực hành: Tạo trang tính năng mới
### DevOps
1. Review: `docker-compose.yml` (architecture)
2. Study: `.github/workflows` (CI/CD)
3. Learn: `docs/deployment.md` (production)
4. Practice: Deploy to staging environment
1. Xem lại: `docker-compose.yml` (kiến trúc)
2. Nghiên cứu: `.github/workflows` (CI/CD)
3. Học: `docs/deployment.md` (production)
4. Thực hành: Deploy lên môi trường staging
---
## 💡 PRO TIPS
## 💡 MẸO HAY
- Use `pnpm dev` (from root) to develop all apps simultaneously
- ESLint is configured to catch module boundary violations
- Prisma Studio (`pnpm db:studio`) is great for exploring data
- Playwright reports are interactive and very helpful
- PROJECT_TRACKER.md is the source of truth for status
- Dùng `pnpm dev` (từ root) để phát triển tất cả app cùng lúc
- ESLint được cấu hình để bắt vi phạm ranh giới module
- Prisma Studio (`pnpm db:studio`) rất tuyệt để khám phá dữ liệu
- Report Playwright có tính tương tác và rất hữu ích
- PROJECT_TRACKER.md là nguồn sự thật cho trạng thái
---
## 📞 QUICK REFERENCE
## 📞 THAM KHẢO NHANH
| Need | Command | Where |
| Nhu cầu | Lệnh | Vị trí |
|------|---------|-------|
| Check status | `cat PROJECT_TRACKER.md` | Root |
| Run tests | `pnpm test:e2e` | Root |
| View API docs | `http://localhost:3001/api` | After startup |
| See database | `pnpm db:studio` | Root |
| Check logs | Grafana/Loki | Docker |
| Monitor errors | Sentry dashboard | Configured |
| Kiểm tra trạng thái | `cat PROJECT_TRACKER.md` | Root |
| Chạy test | `pnpm test:e2e` | Root |
| Xem tài liệu API | `http://localhost:3001/api` | Sau khi khởi động |
| Xem database | `pnpm db:studio` | Root |
| Kiểm tra log | Grafana/Loki | Docker |
| Theo dõi lỗi | Sentry dashboard | Đã cấu hình |
---
**Last Updated:** April 12, 2026
**Project Status:** MVP Complete ✅ — Production Ready 🚀
**Cập nhật lần cuối:** 12 tháng 4, 2026
**Trạng thái dự án:** MVP Hoàn Tất ✅ — Sẵn sàng Production 🚀

View File

@@ -1,347 +1,346 @@
# 📚 NEW DOCUMENTATION — Complete Codebase Analysis
# 📚 TÀI LIỆU MỚI — Phân Tích Toàn Diện Codebase
**Generated:** April 12, 2026
**Purpose:** Comprehensive overview of the GoodGo Platform codebase
**Status:** ✅ Ready for team onboarding
**Ngày tạo:** 12 tháng 4, 2026
**Mục đích:** Tổng quan toàn diện về codebase GoodGo Platform
**Trạng thái:** ✅ Sẵn sàng để onboard team
---
## 🎯 WHY THIS DOCUMENTATION EXISTS
## 🎯 VÌ SAO CÓ TÀI LIỆU NÀY
The GoodGo Platform is a sophisticated, enterprise-grade real estate marketplace with:
- 18 backend modules (NestJS)
- Modern frontend (Next.js 15)
- 31 database models (PostgreSQL 16)
- 242 test files
- Complete monitoring & DevOps setup
GoodGo Platform là một sàn giao dịch bất động sản cấp doanh nghiệp, tinh vi với:
- 18 module backend (NestJS)
- Frontend hiện đại (Next.js 15)
- 31 model database (PostgreSQL 16)
- 242 file test
- Hệ thống monitoring & DevOps đầy đủ
**This documentation makes it easy to understand how far along the project is and what to work on next.**
**Tài liệu này giúp dễ dàng hiểu được tiến độ dự án và những việc cần làm tiếp theo.**
---
## 📖 DOCUMENTATION FILES CREATED
## 📖 CÁC FILE TÀI LIỆU ĐÃ TẠO
### 1. **EXPLORATION_COMPLETE.md** ← **START HERE**
**Best for:** Getting the executive summary
**Length:** 2-3 min read
**Contains:**
- Project maturity at a glance (95% complete)
- What was explored (8 areas)
- Key findings with evidence
- Code statistics
- Immediate next steps
- New files overview
### 1. **EXPLORATION_COMPLETE.md** ← **BẮT ĐẦU TỪ ĐÂY**
**Tốt nhất cho:** Nhận tóm tắt cấp điều hành
**Độ dài:** Đọc trong 2-3 phút
**Nội dung:**
- Mức độ hoàn thiện dự án (95% hoàn thành)
- Những gì đã được khám phá (8 lĩnh vực)
- Các phát hiện chính kèm bằng chứng
- Thống kê code
- Các bước tiếp theo cần làm ngay
- Tổng quan các file mới
**👉 Read this first to get oriented.**
**👉 Đọc file này trước để định hướng.**
---
### 2. **QUICK_START_REFERENCE.md**
**Best for:** Developers who need quick answers
**Length:** 5-10 min read
**Contains:**
- Project maturity table
- Architecture diagram
- All common commands (dev, test, deploy)
- Key files to know
- Database models overview
- Troubleshooting guide
- Learning paths by role
**Tốt nhất cho:** Developer cần câu trả lời nhanh
**Độ dài:** Đọc trong 5-10 phút
**Nội dung:**
- Bảng đánh giá mức độ hoàn thiện dự án
- Sơ đồ kiến trúc
- Tất cả lệnh thông dụng (dev, test, deploy)
- Các file quan trọng cần biết
- Tổng quan các model database
- Hướng dẫn troubleshooting
- Lộ trình học theo vai trò
**👉 Bookmark this for daily reference.**
**👉 Bookmark file này để tham khảo hằng ngày.**
---
### 3. **CODEBASE_OVERVIEW.md**
**Best for:** Deep technical understanding
**Length:** 15-20 min read
**Contains:**
- 12 comprehensive sections
- Top-level directory structure
- All 18 API modules documented
- Frontend structure & components
- Complete Prisma schema explanation
- Dependencies breakdown
- Test coverage details
- Implementation status by phase
- Key statistics & metrics
**Tốt nhất cho:** Hiểu sâu về kỹ thuật
**Độ dài:** Đọc trong 15-20 phút
**Nội dung:**
- 12 phần toàn diện
- Cấu trúc thư mục cấp cao
- Tài liệu cho cả 18 module API
- Cấu trúc và component frontend
- Giải thích đầy đủ schema Prisma
- Phân tích dependency
- Chi tiết test coverage
- Trạng thái triển khai theo từng phase
- Thống kê và metric chính
**👉 Read this to fully understand the system.**
**👉 Đọc file này để hiểu hệ thống một cách trọn vẹn.**
---
### 4. **ARCHITECTURE_SUMMARY.txt**
**Best for:** Visual learners, presentations
**Length:** 10-15 min read
**Contains:**
- ASCII art architecture diagrams
- Technology stack visualization
- API layer organization
- Database model breakdown
- Frontend layer structure
- Testing & QA breakdown
- Observability stack
- Implementation progress by phase
- Key metrics
**Tốt nhất cho:** Người học bằng hình ảnh, làm thuyết trình
**Độ dài:** Đọc trong 10-15 phút
**Nội dung:**
- Sơ đồ kiến trúc bằng ASCII art
- Trực quan hóa tech stack
- Tổ chức tầng API
- Phân tích model database
- Cấu trúc tầng frontend
- Phân tích testing & QA
- Stack observability
- Tiến độ triển khai theo phase
- Các metric chính
**👉 Use for presentations or quick visual reference.**
**👉 Dùng cho thuyết trình hoặc tham khảo nhanh bằng hình ảnh.**
---
## 🗺️ NAVIGATION GUIDE
## 🗺️ HƯỚNG DẪN ĐIỀU HƯỚNG
### "I need a quick overview"
**EXPLORATION_COMPLETE.md** (2 min)
### "Tôi cần tổng quan nhanh"
**EXPLORATION_COMPLETE.md** (2 phút)
### "I'm starting development"
**QUICK_START_REFERENCE.md** (first 3 sections)
### "Tôi đang bắt đầu phát triển"
**QUICK_START_REFERENCE.md** (3 phần đầu tiên)
### "I need to understand the architecture"
**CODEBASE_OVERVIEW.md** (Section 1-3)
### "Tôi cần hiểu kiến trúc"
**CODEBASE_OVERVIEW.md** (Phần 1-3)
### "I need to understand the API"
**CODEBASE_OVERVIEW.md** (Section 2 + docs/api-endpoints.md)
### "Tôi cần hiểu API"
**CODEBASE_OVERVIEW.md** (Phần 2 + docs/api-endpoints.md)
### "I need to understand the database"
**CODEBASE_OVERVIEW.md** (Section 4)
### "Tôi cần hiểu database"
**CODEBASE_OVERVIEW.md** (Phần 4)
### "I need deployment steps"
**QUICK_START_REFERENCE.md** (deployment section) or docs/deployment.md
### "Tôi cần các bước deploy"
**QUICK_START_REFERENCE.md** (phần deployment) hoặc docs/deployment.md
### "I need to run tests"
**QUICK_START_REFERENCE.md** (testing section)
### "Tôi cần chạy test"
**QUICK_START_REFERENCE.md** (phần testing)
### "I need to troubleshoot an issue"
**QUICK_START_REFERENCE.md** (troubleshooting section)
### "Tôi cần troubleshoot một vấn đề"
**QUICK_START_REFERENCE.md** (phần troubleshooting)
### "I'm giving a technical presentation"
**ARCHITECTURE_SUMMARY.txt** (visual reference)
### "Tôi đang làm bài thuyết trình kỹ thuật"
**ARCHITECTURE_SUMMARY.txt** (tham khảo trực quan)
---
## 📊 PROJECT STATUS SNAPSHOT
## 📊 TÌNH TRẠNG DỰ ÁN
| Metric | Value | Status |
| Chỉ số | Giá trị | Trạng thái |
|--------|-------|--------|
| **Feature Completeness** | 95% | ✅ Nearly done |
| **Code Quality** | High | ✅ 242 tests, DDD architecture |
| **Backend Files** | 845 | ✅ Well organized |
| **Frontend Files** | 245 | ✅ Modern React setup |
| **Database Models** | 31 | ✅ Fully normalized |
| **API Endpoints** | 100+ | ✅ Documented |
| **Test Files** | 242 | ✅ Comprehensive |
| **Security** | Hardened | ✅ JWT, MFA, encryption |
| **DevOps** | Production-Ready | ✅ Docker, Kubernetes |
| **Documentation** | Excellent | ✅ 80+ audit files |
| **Mức hoàn thiện tính năng** | 95% | ✅ Gần xong |
| **Chất lượng code** | Cao | ✅ 242 test, kiến trúc DDD |
| **File backend** | 845 | ✅ Tổ chức tốt |
| **File frontend** | 245 | ✅ Setup React hiện đại |
| **Model database** | 31 | ✅ Chuẩn hóa đầy đủ |
| **API endpoint** | 100+ | ✅ Đã tài liệu hóa |
| **File test** | 242 | ✅ Toàn diện |
| **Bảo mật** | Đã hardened | ✅ JWT, MFA, mã hóa |
| **DevOps** | Sẵn sàng production | ✅ Docker, Kubernetes |
| **Tài liệu** | Xuất sắc | ✅ 80+ file audit |
**Overall Status:****Production Ready**Only 3 edge cases remain
**Trạng thái tổng thể:****Sẵn sàng Production**Chỉ còn 3 edge case
---
## 🚀 IMMEDIATE ACTIONS
## 🚀 HÀNH ĐỘNG NGAY
### For Team Leads
1. Read **EXPLORATION_COMPLETE.md** (understand status)
2. Share **QUICK_START_REFERENCE.md** with team
3. Review **docs/deployment.md** for go-live checklist
### Dành cho Team Lead
1. Đọc **EXPLORATION_COMPLETE.md** (hiểu tình trạng)
2. Chia sẻ **QUICK_START_REFERENCE.md** với team
3. Xem lại **docs/deployment.md** để chuẩn bị go-live
### For Backend Developers
1. Read **QUICK_START_REFERENCE.md** (architecture section)
2. Study **apps/api/src/modules/auth** (simplest module)
3. Review **docs/architecture.md** (design patterns)
### Dành cho Backend Developer
1. Đọc **QUICK_START_REFERENCE.md** (phần kiến trúc)
2. Nghiên cứu **apps/api/src/modules/auth** (module đơn giản nhất)
3. Xem lại **docs/architecture.md** (design pattern)
### For Frontend Developers
1. Read **QUICK_START_REFERENCE.md** (architecture section)
2. Review **apps/web/app** (route structure)
3. Study **components/listings** (complex component)
### Dành cho Frontend Developer
1. Đọc **QUICK_START_REFERENCE.md** (phần kiến trúc)
2. Xem lại **apps/web/app** (cấu trúc route)
3. Nghiên cứu **components/listings** (component phức tạp)
### For DevOps/Platform Engineers
1. Read **QUICK_START_REFERENCE.md** (deployment section)
2. Study **docker-compose.yml** and **docker-compose.prod.yml**
3. Review **docs/deployment.md** and **docs/RUNBOOK.md**
### Dành cho DevOps/Platform Engineer
1. Đọc **QUICK_START_REFERENCE.md** (phần deployment)
2. Nghiên cứu **docker-compose.yml** **docker-compose.prod.yml**
3. Xem lại **docs/deployment.md** **docs/RUNBOOK.md**
---
## 📋 WHAT EACH FILE COVERS
## 📋 NỘI DUNG CỦA TỪNG FILE
### EXPLORATION_COMPLETE.md
```
What was explored (8 areas)
✓ Project maturity breakdown
Key findings with metrics
Remaining work (3 items)
New documentation overview
Next steps for team
Key insights & recommendations
Những gì đã được khám phá (8 lĩnh vực)
✓ Phân tích mức độ hoàn thiện
Phát hiện chính kèm metric
Công việc còn lại (3 mục)
Tổng quan tài liệu mới
Các bước tiếp theo cho team
Insight và khuyến nghị chính
```
### QUICK_START_REFERENCE.md
```
Project maturity snapshot
Architecture at a glance
Quick commands (dev, test, deploy)
Key files to know
✓ API modules overview (18 modules)
Database models (31 total)
Testing breakdown
Security features
Deployment options (3)
Tổng quan mức hoàn thiện dự án
Kiến trúc tổng quan
Lệnh nhanh (dev, test, deploy)
File quan trọng cần biết
Tổng quan API module (18 module)
Model database (tổng 31)
Phân tích testing
Tính năng bảo mật
Lựa chọn deploy (3 cách)
✓ Troubleshooting
✓ Learning paths by role
✓ Lộ trình học theo vai trò
```
### CODEBASE_OVERVIEW.md
```
Top-level directory structure
All 18 API modules detailed
Frontend structure (routes + components)
Database schema (31 models)
Documentation & tracking
Dependencies breakdown
Test coverage details (242 files)
Implementation status (all 7 phases)
Project maturity indicators
Statistics & metrics
✓ Tech stack summary
Next steps
Cấu trúc thư mục cấp cao
Chi tiết cho cả 18 module API
Cấu trúc frontend (route + component)
Schema database (31 model)
Tài liệu và theo dõi
Phân tích dependency
Chi tiết test coverage (242 file)
Trạng thái triển khai (cả 7 phase)
Chỉ số mức hoàn thiện dự án
Thống kê và metric
✓ Tóm tắt tech stack
Bước tiếp theo
```
### ARCHITECTURE_SUMMARY.txt
```
✓ Tech stack visual
API layer diagram
Database entity diagram
Frontend layer diagram
Testing breakdown
Observability stack
Implementation progress
Key metrics
Project maturity assessment
✓ Trực quan tech stack
Sơ đồ tầng API
Sơ đồ entity database
Sơ đồ tầng frontend
Phân tích testing
Stack observability
Tiến độ triển khai
Các metric chính
Đánh giá mức hoàn thiện dự án
```
---
## 🎓 LEARNING SEQUENCES
## 🎓 LỘ TRÌNH HỌC
### Backend Developer Onboarding (2-3 hours)
1. **EXPLORATION_COMPLETE.md** (5 min) — Understand status
2. **QUICK_START_REFERENCE.md** architecture section (10 min) — Visual overview
3. `pnpm dev` (5 min) — Get environment running
4. **docs/architecture.md** (30 min) — Learn DDD/CQRS patterns
5. `apps/api/src/modules/auth` (30 min) — Study simplest module
6. **CODEBASE_OVERVIEW.md** section 2 (20 min) — Understand all modules
7. Add a simple feature (60 min) — Hands-on learning
### Onboarding Backend Developer (2-3 giờ)
1. **EXPLORATION_COMPLETE.md** (5 phút) — Hiểu tình trạng
2. **QUICK_START_REFERENCE.md** phần kiến trúc (10 phút) — Tổng quan trực quan
3. `pnpm dev` (5 phút) — Khởi động môi trường
4. **docs/architecture.md** (30 phút) — Học pattern DDD/CQRS
5. `apps/api/src/modules/auth` (30 phút) — Nghiên cứu module đơn giản nhất
6. **CODEBASE_OVERVIEW.md** phần 2 (20 phút) — Hiểu tất cả module
7. Thêm một tính năng đơn giản (60 phút) — Học thực hành
### Frontend Developer Onboarding (2-3 hours)
1. **EXPLORATION_COMPLETE.md** (5 min) — Understand status
2. **QUICK_START_REFERENCE.md** architecture section (10 min) — Visual overview
3. `pnpm dev` (5 min) — Get environment running
4. `apps/web/app` (20 min) — Learn route structure
5. **CODEBASE_OVERVIEW.md** section 3 (20 min) — Understand components
6. `components/listings` (30 min) — Study complex component
7. Create a simple page (60 min) — Hands-on learning
### Onboarding Frontend Developer (2-3 giờ)
1. **EXPLORATION_COMPLETE.md** (5 phút) — Hiểu tình trạng
2. **QUICK_START_REFERENCE.md** phần kiến trúc (10 phút) — Tổng quan trực quan
3. `pnpm dev` (5 phút) — Khởi động môi trường
4. `apps/web/app` (20 phút) — Học cấu trúc route
5. **CODEBASE_OVERVIEW.md** phần 3 (20 phút) — Hiểu các component
6. `components/listings` (30 phút) — Nghiên cứu component phức tạp
7. Tạo một trang đơn giản (60 phút) — Học thực hành
### DevOps/Platform Engineer Onboarding (2-3 hours)
1. **EXPLORATION_COMPLETE.md** (5 min) — Understand status
2. **QUICK_START_REFERENCE.md** deployment section (15 min) — Overview
3. `docker-compose up` (5 min) — Get environment running
4. **docs/deployment.md** (30 min) — Learn deployment steps
5. **docs/RUNBOOK.md** (30 min) — Learn operations
6. Study Kubernetes manifests (20 min) — Production setup
7. Test deployment to staging (60 min) — Hands-on learning
### Onboarding DevOps/Platform Engineer (2-3 giờ)
1. **EXPLORATION_COMPLETE.md** (5 phút) — Hiểu tình trạng
2. **QUICK_START_REFERENCE.md** phần deployment (15 phút) — Tổng quan
3. `docker-compose up` (5 phút) — Khởi động môi trường
4. **docs/deployment.md** (30 phút) — Học các bước deploy
5. **docs/RUNBOOK.md** (30 phút) — Học vận hành
6. Nghiên cứu manifest Kubernetes (20 phút) — Setup production
7. Test deploy lên staging (60 phút) — Học thực hành
---
## ✅ VERIFICATION CHECKLIST
## ✅ CHECKLIST KIỂM TRA
Use this to verify you have everything you need:
Dùng để xác nhận bạn đã có đầy đủ những gì cần thiết:
- [ ] Read EXPLORATION_COMPLETE.md
- [ ] Found QUICK_START_REFERENCE.md in root
- [ ] Found CODEBASE_OVERVIEW.md in root
- [ ] Found ARCHITECTURE_SUMMARY.txt in root
- [ ] Can run `docker-compose up`
- [ ] Can run `pnpm test:e2e`
- [ ] Can access `http://localhost:3000` (frontend)
- [ ] Can access `http://localhost:3001` (API)
- [ ] Understand PROJECT_TRACKER.md status
- [ ] Know the 3 remaining Phase 7 issues
- [ ] Đã đọc EXPLORATION_COMPLETE.md
- [ ] Đã tìm thấy QUICK_START_REFERENCE.md ở thư mục gốc
- [ ] Đã tìm thấy CODEBASE_OVERVIEW.md ở thư mục gốc
- [ ] Đã tìm thấy ARCHITECTURE_SUMMARY.txt ở thư mục gốc
- [ ] Có thể chạy `docker-compose up`
- [ ] Có thể chạy `pnpm test:e2e`
- [ ] Truy cập được `http://localhost:3000` (frontend)
- [ ] Truy cập được `http://localhost:3001` (API)
- [ ] Hiểu trạng thái trong PROJECT_TRACKER.md
- [ ] Biết 3 issue còn lại của Phase 7
---
## 🔗 RELATED DOCUMENTATION
## 🔗 TÀI LIỆU LIÊN QUAN
These pre-existing files contain additional valuable information:
Các file đã có sẵn dưới đây chứa thêm thông tin giá trị:
**Planning & Status:**
- `PROJECT_TRACKER.md`All phases, issues, and current status
- `IMPLEMENTATION_PLAN.md`Feature roadmap
**Lập kế hoạch & Trạng thái:**
- `PROJECT_TRACKER.md`Tất cả phase, issue và trạng thái hiện tại
- `IMPLEMENTATION_PLAN.md`Roadmap tính năng
**Technical:**
- `docs/architecture.md` — DDD/CQRS patterns
- `docs/api-endpoints.md`All endpoints (Swagger)
- `docs/api-error-codes.md`Error taxonomy
- `prisma/schema.prisma`Database schema
**Kỹ thuật:**
- `docs/architecture.md`Pattern DDD/CQRS
- `docs/api-endpoints.md`Tất cả endpoint (Swagger)
- `docs/api-error-codes.md`Phân loại lỗi
- `prisma/schema.prisma`Schema database
**Operations:**
- `docs/deployment.md`Deployment procedures
- `docs/RUNBOOK.md`Troubleshooting guide
- `docker-compose.yml`Local development
- `docker-compose.prod.yml`Production stack
**Vận hành:**
- `docs/deployment.md`Quy trình deploy
- `docs/RUNBOOK.md`Hướng dẫn troubleshoot
- `docker-compose.yml`Phát triển local
- `docker-compose.prod.yml`Stack production
**Audits:**
- `docs/audits/` — 80+ implementation audits
**Audit:**
- `docs/audits/` — 80+ audit triển khai
---
## 💡 PRO TIPS
## 💡 MẸO HAY
1. **Bookmark QUICK_START_REFERENCE.md** for daily reference
2. **Keep PROJECT_TRACKER.md** handy for status updates
3. **Use Prisma Studio** (`pnpm db:studio`) to explore the database
4. **Review docs/RUNBOOK.md** before going on-call
5. **Check docs/architecture.md** before proposing changes
6. **Run tests frequently** (`pnpm test:e2e`) to catch issues early
1. **Bookmark QUICK_START_REFERENCE.md** để tham khảo hằng ngày
2. **Giữ PROJECT_TRACKER.md** sẵn sàng cho cập nhật trạng thái
3. **Dùng Prisma Studio** (`pnpm db:studio`) để khám phá database
4. **Xem lại docs/RUNBOOK.md** trước khi trực on-call
5. **Kiểm tra docs/architecture.md** trước khi đề xuất thay đổi
6. **Chạy test thường xuyên** (`pnpm test:e2e`) để phát hiện sớm vấn đề
---
## 📞 QUESTIONS?
## 📞 CÂU HỎI?
| Question | Answer Location |
| Câu hỏi | Vị trí trả lời |
|----------|-----------------|
| "What's the current status?" | EXPLORATION_COMPLETE.md |
| "How do I start development?" | QUICK_START_REFERENCE.md |
| "How does the system work?" | CODEBASE_OVERVIEW.md |
| "What's the tech stack?" | ARCHITECTURE_SUMMARY.txt |
| "How do I deploy?" | docs/deployment.md |
| "How do I troubleshoot?" | docs/RUNBOOK.md |
| "What's the database model?" | prisma/schema.prisma |
| "What are the remaining tasks?" | PROJECT_TRACKER.md |
| "Tình trạng hiện tại thế nào?" | EXPLORATION_COMPLETE.md |
| "Làm sao để bắt đầu phát triển?" | QUICK_START_REFERENCE.md |
| "Hệ thống hoạt động ra sao?" | CODEBASE_OVERVIEW.md |
| "Tech stack là gì?" | ARCHITECTURE_SUMMARY.txt |
| "Làm sao để deploy?" | docs/deployment.md |
| "Làm sao để troubleshoot?" | docs/RUNBOOK.md |
| "Model database là gì?" | prisma/schema.prisma |
| "Còn task nào chưa làm?" | PROJECT_TRACKER.md |
---
## 📈 NEXT REVIEW DATE
## 📈 NGÀY REVIEW TIẾP THEO
**Recommended Review:** May 1, 2026
**Update Trigger:** When Phase 7 completes or major features ship
**Đề xuất review:** 1 tháng 5, 2026
**Trigger cập nhật:** Khi Phase 7 hoàn tất hoặc có tính năng lớn được ship
---
## 📝 DOCUMENT MANIFEST
## 📝 DANH MỤC TÀI LIỆU
| File | Size | Purpose | Audience |
| File | Kích thước | Mục đích | Đối tượng |
|------|------|---------|----------|
| EXPLORATION_COMPLETE.md | 9 KB | Executive summary | Everyone |
| QUICK_START_REFERENCE.md | 12 KB | Developer guide | Developers |
| CODEBASE_OVERVIEW.md | 15 KB | Technical reference | Tech leads |
| ARCHITECTURE_SUMMARY.txt | 24 KB | Visual overview | Presenters |
| EXPLORATION_COMPLETE.md | 9 KB | Tóm tắt điều hành | Mọi người |
| QUICK_START_REFERENCE.md | 12 KB | Hướng dẫn developer | Developer |
| CODEBASE_OVERVIEW.md | 15 KB | Tham khảo kỹ thuật | Tech lead |
| ARCHITECTURE_SUMMARY.txt | 24 KB | Tổng quan trực quan | Người thuyết trình |
**Total:** 60 KB of new documentation
**Generated:** April 12, 2026
**Time to Read:** 30-45 minutes (all four)
**Value:** Foundation for team onboarding
**Tổng cộng:** 60 KB tài liệu mới
**Ngày tạo:** 12 tháng 4, 2026
**Thời gian đọc:** 30-45 phút (cả bốn file)
**Giá trị:** Nền tảng cho onboarding team
---
**Start with EXPLORATION_COMPLETE.md — you'll understand the project in 2 minutes! 🚀**
**Bắt đầu với EXPLORATION_COMPLETE.md — bạn sẽ hiểu dự án trong 2 phút! 🚀**

File diff suppressed because it is too large Load Diff

View File

@@ -1,252 +1,252 @@
# API Endpoints Reference
# Tham Khảo API Endpoint
All routes are prefixed with `/api/v1/` except health checks. Authentication uses Bearer JWT tokens.
Tất cả route được prefix với `/api/v1/` ngoại trừ health check. Authentication dùng Bearer JWT token.
> **Interactive docs**: Swagger UI is available at `http://localhost:3001/api/v1/docs` when running the API locally.
> **Tài liệu tương tác**: Swagger UI có sẵn tại `http://localhost:3001/api/v1/docs` khi chạy API local.
## Auth (`/auth`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/auth/register` | Public | Register a new user |
| POST | `/auth/login` | Public | Login with phone and password |
| POST | `/auth/refresh` | Cookie | Refresh access token using httpOnly refresh cookie |
| POST | `/auth/logout` | JWT | Logout and clear auth cookies |
| POST | `/auth/exchange-token` | Public | Exchange OAuth token pair for httpOnly cookies |
| GET | `/auth/profile` | JWT | Get current user profile |
| GET | `/auth/profile/agent` | JWT | Get agent profile for current user |
| PATCH | `/auth/kyc` | Admin | Verify user KYC status |
| POST | `/auth/register` | Public | Đăng ký user mới |
| POST | `/auth/login` | Public | Đăng nhập bằng số điện thoại và mật khẩu |
| POST | `/auth/refresh` | Cookie | Làm mới access token bằng cookie refresh httpOnly |
| POST | `/auth/logout` | JWT | Đăng xuất và xóa cookie auth |
| POST | `/auth/exchange-token` | Public | Trao đổi cặp token OAuth lấy cookie httpOnly |
| GET | `/auth/profile` | JWT | Lấy hồ sơ user hiện tại |
| GET | `/auth/profile/agent` | JWT | Lấy hồ sơ agent của user hiện tại |
| PATCH | `/auth/kyc` | Admin | Verify trạng thái KYC của user |
### OAuth
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/auth/google` | Public | Initiate Google OAuth2 login |
| GET | `/auth/google/callback` | Public | Google OAuth2 callback |
| GET | `/auth/zalo` | Public | Initiate Zalo OAuth2 login |
| GET | `/auth/zalo/callback` | Public | Zalo OAuth2 callback |
| GET | `/auth/google` | Public | Khởi tạo đăng nhập Google OAuth2 |
| GET | `/auth/google/callback` | Public | Callback Google OAuth2 |
| GET | `/auth/zalo` | Public | Khởi tạo đăng nhập Zalo OAuth2 |
| GET | `/auth/zalo/callback` | Public | Callback Zalo OAuth2 |
### User Data (GDPR)
### Dữ Liệu User (GDPR)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| DELETE | `/users/me` | JWT | Request account deletion (30-day grace period) |
| POST | `/users/me/cancel-deletion` | JWT | Cancel pending account deletion |
| GET | `/users/me/export` | JWT | Export user data (GDPR Article 20) |
| DELETE | `/users/:id/force` | Admin | Force-delete user immediately |
| DELETE | `/users/me` | JWT | Yêu cầu xóa tài khoản (thời hạn 30 ngày) |
| POST | `/users/me/cancel-deletion` | JWT | Hủy yêu cầu xóa tài khoản đang chờ |
| GET | `/users/me/export` | JWT | Export dữ liệu user (GDPR Điều 20) |
| DELETE | `/users/:id/force` | Admin | Force-delete user ngay lập tức |
---
## Listings (`/listings`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/listings` | JWT + Quota | Create a new property listing |
| GET | `/listings` | Public | Search and filter property listings |
| GET | `/listings/pending` | Admin | Get listings pending moderation |
| GET | `/listings/:id` | Public | Get listing details by ID |
| PATCH | `/listings/:id/status` | JWT | Update listing status |
| POST | `/listings` | JWT + Quota | Tạo tin đăng bất động sản mới |
| GET | `/listings` | Public | Tìm kiếm và lọc tin đăng |
| GET | `/listings/pending` | Admin | Lấy tin đăng đang chờ duyệt |
| GET | `/listings/:id` | Public | Lấy chi tiết tin đăng theo ID |
| PATCH | `/listings/:id/status` | JWT | Cập nhật trạng thái tin đăng |
| POST | `/listings/:id/media` | JWT | Upload media (multipart file upload) |
| PATCH | `/listings/:id/moderate` | Admin | Moderate a listing |
| PATCH | `/listings/:id/moderate` | Admin | Duyệt một tin đăng |
---
## Search (`/search`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/search` | Public | Full-text and faceted property search |
| GET | `/search/geo` | Public | Geographic radius search |
| POST | `/search/reindex` | Admin | Reindex all properties in Typesense |
| GET | `/search` | Public | Tìm kiếm bất động sản full-text faceted |
| GET | `/search/geo` | Public | Tìm kiếm theo bán kính địa lý |
| POST | `/search/reindex` | Admin | Reindex tất cả bất động sản trong Typesense |
### Saved Searches (`/saved-searches`)
### Saved Search (`/saved-searches`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/saved-searches` | JWT | Save search filters |
| GET | `/saved-searches` | JWT | List saved searches |
| GET | `/saved-searches/:id` | JWT | Get saved search details |
| PATCH | `/saved-searches/:id` | JWT | Update saved search |
| DELETE | `/saved-searches/:id` | JWT | Delete saved search |
| POST | `/saved-searches` | JWT | Lưu bộ lọc tìm kiếm |
| GET | `/saved-searches` | JWT | Lit kê các tìm kiếm đã lưu |
| GET | `/saved-searches/:id` | JWT | Lấy chi tiết tìm kiếm đã lưu |
| PATCH | `/saved-searches/:id` | JWT | Cập nhật tìm kiếm đã lưu |
| DELETE | `/saved-searches/:id` | JWT | Xóa tìm kiếm đã lưu |
---
## Payments (`/payments`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/payments` | JWT | Create a new payment |
| GET | `/payments` | JWT | List transactions for authenticated user |
| GET | `/payments/:id` | JWT | Get payment status by ID |
| POST | `/payments/:id/refund` | Admin | Refund a payment |
| POST | `/payments/callback/:provider` | Public | Payment provider webhook (VNPay, MoMo, ZaloPay) |
| POST | `/payments` | JWT | Tạo thanh toán mới |
| GET | `/payments` | JWT | Lit kê giao dịch của user đã xác thực |
| GET | `/payments/:id` | JWT | Lấy trạng thái thanh toán theo ID |
| POST | `/payments/:id/refund` | Admin | Hoàn tiền một thanh toán |
| POST | `/payments/callback/:provider` | Public | Webhook nhà cung cấp thanh toán (VNPay, MoMo, ZaloPay) |
---
## Subscriptions (`/subscriptions`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/subscriptions/plans` | Public | List all subscription plans |
| GET | `/subscriptions/plans/:tier` | Public | Get subscription plan by tier |
| POST | `/subscriptions` | JWT | Create a new subscription |
| PUT | `/subscriptions/upgrade` | JWT | Upgrade existing subscription |
| DELETE | `/subscriptions` | JWT | Cancel active subscription |
| POST | `/subscriptions/usage` | JWT | Record metered usage |
| GET | `/subscriptions/quota/:metric` | JWT | Check remaining quota for a metric |
| GET | `/subscriptions/billing` | JWT | Get billing history |
| GET | `/subscriptions/plans` | Public | Lit kê tất cả plan subscription |
| GET | `/subscriptions/plans/:tier` | Public | Lấy plan subscription theo tier |
| POST | `/subscriptions` | JWT | Tạo subscription mới |
| PUT | `/subscriptions/upgrade` | JWT | Nâng cấp subscription hiện tại |
| DELETE | `/subscriptions` | JWT | Hủy subscription đang hoạt động |
| POST | `/subscriptions/usage` | JWT | Ghi nhận lượng sử dụng metered |
| GET | `/subscriptions/quota/:metric` | JWT | Kiểm tra quota còn lại theo metric |
| GET | `/subscriptions/billing` | JWT | Lấy lịch sử thanh toán |
---
## Admin (`/admin`)
### User Management
### Quản Lý User
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/admin/users` | Admin | List users with optional filters |
| GET | `/admin/users/:id` | Admin | Get user details by ID |
| PATCH | `/admin/users/status` | Admin | Update user active status |
| POST | `/admin/users/ban` | Admin | Ban or unban a user |
| POST | `/admin/subscriptions/adjust` | Admin | Adjust user subscription plan |
| GET | `/admin/dashboard` | Admin | Get admin dashboard statistics |
| GET | `/admin/revenue` | Admin | Get revenue statistics by date range |
| GET | `/admin/audit-logs` | Admin | Get admin audit logs |
| GET | `/admin/users` | Admin | Liệt kê user với bộ lọc tùy chọn |
| GET | `/admin/users/:id` | Admin | Lấy chi tiết user theo ID |
| PATCH | `/admin/users/status` | Admin | Cập nhật trạng thái active của user |
| POST | `/admin/users/ban` | Admin | Ban hoặc unban user |
| POST | `/admin/subscriptions/adjust` | Admin | Điều chỉnh plan subscription của user |
| GET | `/admin/dashboard` | Admin | Lấy thống kê dashboard admin |
| GET | `/admin/revenue` | Admin | Lấy thống kê doanh thu theo khoảng ngày |
| GET | `/admin/audit-logs` | Admin | Lấy audit log admin |
### Moderation
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/admin/moderation` | Admin | Get listing moderation queue |
| POST | `/admin/moderation/approve` | Admin | Approve a listing |
| POST | `/admin/moderation/reject` | Admin | Reject a listing |
| POST | `/admin/moderation/bulk` | Admin | Bulk approve or reject listings |
| GET | `/admin/kyc` | Admin | Get KYC verification queue |
| POST | `/admin/kyc/approve` | Admin | Approve KYC verification |
| POST | `/admin/kyc/reject` | Admin | Reject KYC verification |
| GET | `/admin/moderation` | Admin | Lấy hàng đợi duyệt tin đăng |
| POST | `/admin/moderation/approve` | Admin | Duyệt một tin đăng |
| POST | `/admin/moderation/reject` | Admin | Từ chối một tin đăng |
| POST | `/admin/moderation/bulk` | Admin | Duyệt hoặc từ chối tin đăng hàng loạt |
| GET | `/admin/kyc` | Admin | Lấy hàng đợi xác minh KYC |
| POST | `/admin/kyc/approve` | Admin | Duyệt xác minh KYC |
| POST | `/admin/kyc/reject` | Admin | Từ chối xác minh KYC |
---
## Notifications (`/notifications`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/notifications/history` | JWT | Get notification history |
| GET | `/notifications/preferences` | JWT | Get notification preferences |
| PUT | `/notifications/preferences` | JWT | Update notification preferences |
| GET | `/notifications/unread` | JWT | Get unread notifications |
| PATCH | `/notifications/:id/read` | JWT | Mark notification as read |
| PATCH | `/notifications/read-all` | JWT | Mark all notifications as read |
| GET | `/notifications/templates` | JWT | Get available notification templates |
| GET | `/notifications/history` | JWT | Lấy lịch sử thông báo |
| GET | `/notifications/preferences` | JWT | Lấy tùy chọn thông báo |
| PUT | `/notifications/preferences` | JWT | Cập nhật tùy chọn thông báo |
| GET | `/notifications/unread` | JWT | Lấy thông báo chưa đọc |
| PATCH | `/notifications/:id/read` | JWT | Đánh dấu thông báo đã đọc |
| PATCH | `/notifications/read-all` | JWT | Đánh dấu tất cả thông báo đã đọc |
| GET | `/notifications/templates` | JWT | Lấy các template thông báo có sẵn |
---
## Analytics (`/analytics`)
All analytics endpoints require JWT and are quota-guarded.
Tất cả endpoint analytics yêu cầu JWT và được giới hạn theo quota.
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/analytics/market-report` | JWT + Quota | Get market report for a city |
| GET | `/analytics/price-trend` | JWT + Quota | Get price trend for a district |
| GET | `/analytics/heatmap` | JWT + Quota | Get price heatmap for a city |
| GET | `/analytics/district-stats` | JWT + Quota | Get statistics by district |
| GET | `/analytics/valuation` | JWT + Quota | Get automated property valuation (AVM) |
| GET | `/analytics/market-report` | JWT + Quota | Lấy báo cáo thị trường cho một thành phố |
| GET | `/analytics/price-trend` | JWT + Quota | Lấy xu hướng giá cho một quận |
| GET | `/analytics/heatmap` | JWT + Quota | Lấy heatmap giá cho một thành phố |
| GET | `/analytics/district-stats` | JWT + Quota | Lấy thống kê theo quận |
| GET | `/analytics/valuation` | JWT + Quota | Lấy định giá bất động sản tự động (AVM) |
---
## Agents (`/agents`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/agents/me/dashboard` | Agent | Get agent dashboard stats |
| POST | `/agents/:agentId/recalculate-score` | Admin | Recalculate agent quality score |
| GET | `/agents/me/dashboard` | Agent | Lấy thống kê dashboard agent |
| POST | `/agents/:agentId/recalculate-score` | Admin | Tính lại điểm chất lượng agent |
---
## Inquiries (`/inquiries`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/inquiries` | JWT | Create inquiry for a listing |
| GET | `/inquiries/listing/:listingId` | JWT | List inquiries by listing |
| GET | `/inquiries/agent/me` | Agent | List inquiries for current agent |
| PATCH | `/inquiries/:id/read` | Agent | Mark inquiry as read |
| POST | `/inquiries` | JWT | Tạo inquiry cho một tin đăng |
| GET | `/inquiries/listing/:listingId` | JWT | Liệt kê inquiry theo tin đăng |
| GET | `/inquiries/agent/me` | Agent | Liệt kê inquiry cho agent hiện tại |
| PATCH | `/inquiries/:id/read` | Agent | Đánh dấu inquiry đã đọc |
---
## Leads (`/leads`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/leads` | Agent | Create lead |
| GET | `/leads` | Agent | List leads for agent |
| GET | `/leads/stats` | Agent | Get lead statistics |
| PATCH | `/leads/:id/status` | Agent | Update lead status |
| DELETE | `/leads/:id` | Agent | Delete lead |
| POST | `/leads` | Agent | Tạo lead |
| GET | `/leads` | Agent | Liệt kê lead cho agent |
| GET | `/leads/stats` | Agent | Lấy thống kê lead |
| PATCH | `/leads/:id/status` | Agent | Cập nhật trạng thái lead |
| DELETE | `/leads/:id` | Agent | Xóa lead |
---
## Reviews (`/reviews`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/reviews` | JWT | Create a review |
| GET | `/reviews` | Public | List reviews by target |
| GET | `/reviews/stats` | Public | Get aggregate rating stats for a target |
| GET | `/reviews/me` | JWT | Get reviews by authenticated user |
| DELETE | `/reviews/:id` | JWT | Delete own review |
| POST | `/reviews` | JWT | Tạo một review |
| GET | `/reviews` | Public | Liệt kê review theo target |
| GET | `/reviews/stats` | Public | Lấy thống kê đánh giá tổng hợp cho một target |
| GET | `/reviews/me` | JWT | Lấy review của user đã xác thực |
| DELETE | `/reviews/:id` | JWT | Xóa review của chính mình |
---
## Health (`/health`)
Health endpoints are **not** prefixed with `/api/v1/`.
Endpoint health **không** prefix với `/api/v1/`.
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/health` | Public | Liveness probe |
| GET | `/health/ready` | Public | Readiness probe (DB + Redis) |
| GET | `/health/db` | Public | Database connectivity check |
| GET | `/health/redis` | Public | Redis connectivity check |
| GET | `/health/db` | Public | Kiểm tra kết nối database |
| GET | `/health/redis` | Public | Kiểm tra kết nối Redis |
---
## MCP (`/mcp`)
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| GET | `/mcp/servers` | JWT | List available MCP servers |
| GET | `/mcp/:serverName/sse` | JWT | Open SSE connection to MCP server |
| POST | `/mcp/:serverName/messages` | JWT | Send message to MCP server session |
| GET | `/mcp/servers` | JWT | Lit kê các MCP server có sẵn |
| GET | `/mcp/:serverName/sse` | JWT | Mở kết nối SSE đến MCP server |
| POST | `/mcp/:serverName/messages` | JWT | Gửi message tới session MCP server |
---
## Metrics
| Method | Path | Auth | Description |
| Method | Path | Auth | Mô tả |
|--------|------|------|-------------|
| POST | `/web-vitals` | Public | Ingest Core Web Vitals metrics |
| POST | `/web-vitals` | Public | Ingest metric Core Web Vitals |
---
## Authentication Summary
## Tóm Tắt Authentication
| Auth Type | Description |
| Loại Auth | Mô tả |
|-----------|-------------|
| **Public** | No authentication required |
| **JWT** | Requires `Authorization: Bearer <token>` header |
| **Admin** | JWT + `ADMIN` role required |
| **Agent** | JWT + `AGENT` role required |
| **Quota** | JWT + subscription quota enforcement |
| **Cookie** | Uses httpOnly refresh token cookie |
| **Public** | Không yêu cầu authentication |
| **JWT** | Yêu cầu header `Authorization: Bearer <token>` |
| **Admin** | JWT + role `ADMIN` |
| **Agent** | JWT + role `AGENT` |
| **Quota** | JWT + giới hạn quota subscription |
| **Cookie** | Dùng cookie refresh token httpOnly |
## Rate Limiting
The following endpoints have stricter rate limits:
Các endpoint sau có rate limit nghiêm ngặt hơn:
- Auth endpoints (register, login, refresh): `10 req/60s`
- OAuth callbacks: `10 req/60s`
- Payment callbacks: `60 req/60s`
- MCP endpoints: `30 req/60s`
- Default: `60 req/60s`
- Endpoint Auth (register, login, refresh): `10 req/60s`
- OAuth callback: `10 req/60s`
- Payment callback: `60 req/60s`
- Endpoint MCP: `30 req/60s`
- Mặc định: `60 req/60s`

View File

@@ -1,11 +1,11 @@
# GoodGo Platform — Comprehensive Codebase Overview
# Nền tảng GoodGo — Tổng quan toàn diện về Codebase
**Generated:** April 12, 2026
**Project Status:** MVP Complete — Phase 7 Wave 14 ✅ Build Green
**Được tạo:** Ngày 12 tháng 4 năm 2026
**Trạng thái dự án:** MVP hoàn thành — Phase 7 Wave 14 ✅ Build Green
---
## 1. TOP-LEVEL DIRECTORY STRUCTURE
## 1. CẤU TRÚC THƯ MỤC CẤP CAO NHẤT
```
goodgo-platform-ai/
@@ -39,69 +39,69 @@ goodgo-platform-ai/
---
## 2. API MODULES (`apps/api/src/modules/`) — 18 MODULES
## 2. CÁC MODULE API (`apps/api/src/modules/`) — 18 MODULE
### Core Authentication & Authorization
- **auth/** — JWT, OAuth (Google/Zalo), MFA, TOTP backup codes
- Subdirs: application, domain, infrastructure, presentation, __tests__
- Key: JWT guards, passport strategies, role-based access
### Xác thực & Phân quyền cốt lõi
- **auth/** — JWT, OAuth (Google/Zalo), MFA, mã dự phòng TOTP
- Thư mục con: application, domain, infrastructure, presentation, __tests__
- Chính: JWT guards, passport strategies, phân quyền dựa trên vai trò
### Listings & Properties
- **listings/** — CRUD, status management, media, AI price estimates
- Moderation scoring, featured listings, expiration logic
- Media upload with pre-signed URLs (AWS S3)
### Listings & Bất động sản
- **listings/** — CRUD, quản lý trạng thái, media, AI ước tính giá
- Chấm điểm kiểm duyệt, listing nổi bật, logic hết hạn
- Upload media với pre-signed URL (AWS S3)
### Search & Discovery
- **search/** — Typesense integration (full-text), geospatial (PostGIS)
- Resilient repository with fallback to PostgreSQL
- Filters: location, price, property type, bedrooms
### Search & Khám phá
- **search/** — Tích hợp Typesense (full-text), geospatial (PostGIS)
- Repository có khả năng phục hồi với fallback về PostgreSQL
- Bộ lọc: vị trí, giá, loại bất động sản, số phòng ngủ
### Transactions & Inquiries
- **inquiries/** — Buyer-to-seller messages for specific listings
- **leads/** — Agent CRM (lead scoring, status tracking, notes)
### Giao dịch & Inquiry
- **inquiries/** — Tin nhắn người mua-người bán cho listing cụ thể
- **leads/** — CRM dành cho agent (chấm điểm lead, theo dõi trạng thái, ghi chú)
### Monetization
- **payments/** — VNPay, MoMo, ZaloPay, Bank Transfer
- Idempotency keys, webhook callbacks, refund handling
- 4 payment types: subscription, listing fee, deposit, featured
### Kiếm tin
- **payments/** — VNPay, MoMo, ZaloPay, Chuyển khoản ngân hàng
- Khóa idempotency, webhook callback, xử lý hoàn tiền
- 4 loại thanh toán: subscription, phí listing, đặt cọc, nổi bật
- **subscriptions/** — Plans (FREE, AGENT_PRO, INVESTOR, ENTERPRISE)
- Usage tracking, quota management, billing cycles
- **subscriptions/** — Các gói (FREE, AGENT_PRO, INVESTOR, ENTERPRISE)
- Theo dõi sử dụng, quản lý hạn ngạch, chu kỳ thanh toán
### Operations
- **agents/** — Agent profiles, quality scores, service areas, verification
- **admin/** — User bans, KYC approval, listing moderation, audit logs
### Vận hành
- **agents/** — Hồ sơ agent, điểm chất lượng, khu vực phục vụ, xác minh
- **admin/** — Cấm người dùng, duyệt KYC, kiểm duyệt listing, audit log
- **notifications/** — Email, SMS, Push (FCM), Zalo OA
- Preferences per user/channel, template system
- Tùy chọn theo người dùng/kênh, hệ thống template
### Analytics & Intelligence
- **analytics/** — Market reports, price index by district/city/type
- Valuation engine integration (AI/ML service)
### Analytics & Trí tuệ
- **analytics/** — Báo cáo thị trường, chỉ số giá theo quận/thành phố/loại
- Tích hợp engine định giá (dịch vụ AI/ML)
### Infrastructure & System
- **health/** — Liveness/readiness probes, Kubernetes hooks
- **metrics/** — Prometheus metrics, HTTP latency, error rates
- **mcp/** — Model Context Protocol server for AI tools
- **shared/** — Domain primitives, encryption, logging, error handling
### Hạ tầng & Hệ thống
- **health/** — Probe liveness/readiness, hook Kubernetes
- **metrics/** — Metrics Prometheus, độ trễ HTTP, tỷ lệ lỗi
- **mcp/** — Model Context Protocol server cho công cụ AI
- **shared/** — Domain primitives, mã hóa, logging, xử lý lỗi
**Code Metrics:**
- ~845 TypeScript files
- Layered DDD architecture: presentation → application → domain → infrastructure
- Uses NestJS modules, CQRS pattern for complex operations
**Số liệu code:**
- ~845 file TypeScript
- Kiến trúc DDD phân lớp: presentation → application → domain → infrastructure
- Sử dụng module NestJS, pattern CQRS cho các thao tác phức tạp
---
## 3. FRONTEND STRUCTURE (`apps/web/`)
## 3. CẤU TRÚC FRONTEND (`apps/web/`)
### Root Layout
- **app/layout.tsx** — Root wrapper
- **app/[locale]/** — i18n routing (Vietnamese + English)
- **app/[locale]/** — Định tuyến i18n (Tiếng Việt + Tiếng Anh)
### Page Groups (Route Groups with Shared Layouts)
- **(public)/** — Landing, listings, search (no auth required)
- **(auth)/** — Login, register, OAuth callbacks
- **(dashboard)/** — Seller/agent dashboard
- **(admin)/** — Admin moderation, KYC review, user management
### Nhóm trang (Route Groups với Layout dùng chung)
- **(public)/** — Landing, listings, search (không yêu cầu xác thực)
- **(auth)/** — Login, register, OAuth callback
- **(dashboard)/** — Dashboard người bán/agent
- **(admin)/** — Kiểm duyệt admin, duyệt KYC, quản lý người dùng
### Components (`components/`)
```
@@ -132,81 +132,81 @@ goodgo-platform-ai/
```
### i18n (`i18n/`)
- Vietnamese & English message files
- next-intl integration
- File messages tiếng Việt & tiếng Anh
- Tích hợp next-intl
**Frontend Metrics:**
- ~245 TypeScript/TSX files
- Built on: Next.js 15, React 18, Tailwind CSS, Shadcn/ui
**Số liệu Frontend:**
- ~245 file TypeScript/TSX
- Xây dựng trên: Next.js 15, React 18, Tailwind CSS, Shadcn/ui
- State: Zustand + React Query
- Forms: React Hook Form + Zod validation
- Forms: React Hook Form + validation Zod
---
## 4. PRISMA SCHEMA — DATA MODEL
## 4. PRISMA SCHEMA — MÔ HÌNH DỮ LIỆU
**Database:** PostgreSQL 16 + PostGIS extension
**Database:** PostgreSQL 16 + extension PostGIS
### Total Models: 31
### Tổng số Model: 31
#### Authentication (5)
| Model | Purpose |
#### Xác thực (5)
| Model | Mục đích |
|-------|---------|
| User | Main user profile + KYC status, MFA fields |
| RefreshToken | JWT refresh token chain management |
| OAuthAccount | Google/Zalo OAuth linkage |
| Agent | Seller/Agent extended profile |
| MfaChallenge | TOTP/backup code verification tracking |
| User | Hồ sơ người dùng chính + trạng thái KYC, các trường MFA |
| RefreshToken | Quản lý chuỗi JWT refresh token |
| OAuthAccount | Liên kết OAuth Google/Zalo |
| Agent | Hồ sơ mở rộng cho người bán/Agent |
| MfaChallenge | Theo dõi xác minh TOTP/mã dự phòng |
#### Listings & Properties (4)
| Model | Purpose |
#### Listings & Bất động sản (4)
| Model | Mục đích |
|-------|---------|
| Property | Physical property details + geolocation |
| PropertyMedia | Images/videos per property |
| Listing | Listing instance (sale/rent) + status |
| SavedSearch | User's saved search preferences |
| Property | Chi tiết bất động sản vật lý + định vị địa lý |
| PropertyMedia | Hình ảnh/video cho mỗi bất động sản |
| Listing | Phiên bản listing (bán/cho thuê) + trạng thái |
| SavedSearch | Tùy chọn tìm kiếm đã lưu của người dùng |
#### Transactions (4)
| Model | Purpose |
#### Giao dịch (4)
| Model | Mục đích |
|-------|---------|
| Transaction | Buyer-seller transaction flow (inquiry → completed) |
| Inquiry | Buyer questions on specific listings |
| Lead | Agent CRM lead records |
| Review | User reviews of agents/transactions |
| Transaction | Luồng giao dịch người mua-người bán (inquiry → hoàn thành) |
| Inquiry | Câu hỏi người mua về listing cụ thể |
| Lead | Bản ghi lead CRM của agent |
| Review | Đánh giá người dùng về agent/giao dịch |
#### Payments (2)
| Model | Purpose |
#### Thanh toán (2)
| Model | Mục đích |
|-------|---------|
| Payment | Payment records (all providers) |
| Plan | Subscription tier definitions |
| Payment | Bản ghi thanh toán (tất cả nhà cung cấp) |
| Plan | Định nghĩa cấp subscription |
#### Orders & Escrow (3)
| Model | Purpose |
#### Đơn hàng & Escrow (3)
| Model | Mục đích |
|-------|---------|
| Order | Auction settlement order |
| Escrow | Escrow holding for transactions |
| Subscription | User's active subscription |
| Order | Lệnh thanh toán đấu giá |
| Escrow | Giữ ký quỹ cho giao dịch |
| Subscription | Subscription đang hoạt động của người dùng |
#### Analytics (2)
| Model | Purpose |
| Model | Mục đích |
|-------|---------|
| Valuation | AI-generated property valuations |
| MarketIndex | Market statistics per district/city |
| Valuation | Định giá bất động sản do AI tạo |
| MarketIndex | Thống kê thị trường theo quận/thành phố |
#### Operations (6)
| Model | Purpose |
#### Vận hành (6)
| Model | Mục đích |
|-------|---------|
| NotificationLog | Sent notification records |
| NotificationPreference | User notification opt-in/out |
| AdminAuditLog | Admin action audit trail |
| UsageRecord | Subscription usage tracking |
| NotificationLog | Bản ghi thông báo đã gửi |
| NotificationPreference | Tùy chọn nhận thông báo của người dùng |
| AdminAuditLog | Audit trail hành động admin |
| UsageRecord | Theo dõi sử dụng subscription |
**Index Strategy:**
- Single-column indexes on foreign keys, status fields, dates
- Compound indexes for common query patterns (e.g., `[role, isActive, createdAt DESC]`)
- GIST index on PostGIS location geometry
**Chiến lược Index:**
- Index một cột trên foreign key, các trường trạng thái, ngày tháng
- Index ghép cho các pattern truy vấn phổ biến (ví dụ: `[role, isActive, createdAt DESC]`)
- Index GIST trên hình học vị trí PostGIS
**Key Enums:**
**Các Enum chính:**
- UserRole: BUYER, SELLER, AGENT, ADMIN
- PropertyType: APARTMENT, VILLA, TOWNHOUSE, LAND, OFFICE, SHOPHOUSE
- TransactionType: SALE, RENT
@@ -215,32 +215,32 @@ goodgo-platform-ai/
---
## 5. DOCUMENTATION & TRACKING
## 5. TÀI LIỆU & THEO DÕI
### Root-Level Planning Docs
- **PROJECT_TRACKER.md** — 7 phases, 40+ issues, current status (Phase 7 Wave 14)
- **IMPLEMENTATION_PLAN.md** — Feature roadmap with priority/status
- **COMPREHENSIVE_AUDIT_2026-04-12.md** — Full system audit with implementation notes
### Tài liệu lập kế hoạch ở cấp Root
- **PROJECT_TRACKER.md** — 7 phase, 40+ issue, trạng thái hiện tại (Phase 7 Wave 14)
- **IMPLEMENTATION_PLAN.md** — Lộ trình tính năng với ưu tiên/trạng thái
- **COMPREHENSIVE_AUDIT_2026-04-12.md** — Audit toàn hệ thống với ghi chú triển khai
### Technical Docs (`docs/`)
- **architecture.md** — DDD layering, CQRS, module boundaries
- **api-endpoints.md** — Swagger-generated endpoint reference
- **api-error-codes.md** — Structured error code taxonomy
- **deployment.md** — Docker, K8s, CI/CD pipeline steps
- **RUNBOOK.md** — Operational procedures, troubleshooting
- **PRODUCTION_READINESS.md** — Security, compliance, performance checklist
### Tài liệu kỹ thuật (`docs/`)
- **architecture.md** — Phân lớp DDD, CQRS, ranh giới module
- **api-endpoints.md** — Tham chiếu endpoint do Swagger tạo
- **api-error-codes.md** — Phân loại mã lỗi có cấu trúc
- **deployment.md** — Docker, K8s, các bước CI/CD
- **RUNBOOK.md** — Quy trình vận hành, xử lý sự cố
- **PRODUCTION_READINESS.md** — Checklist bảo mật, tuân thủ, hiệu năng
### Audit Directory (`docs/audits/`)
- 80+ audit files documenting feature implementations
- Pricing audit, checkout flow, KYC, payment gateway testing
### Thư mục Audit (`docs/audits/`)
- 80+ file audit tài liệu hóa các triển khai tính năng
- Audit pricing, luồng checkout, KYC, test cổng thanh toán
---
## 6. DEPENDENCIES & TOOLING
## 6. PHỤ THUỘC & CÔNG CỤ
### Monorepo Setup
- **pnpm** v10.27.0 (workspace) — faster, strict peer deps
- **Turbo** v2.9.4 — task orchestration & caching
### Thiết lập Monorepo
- **pnpm** v10.27.0 (workspace) — nhanh hơn, peer deps nghiêm ngặt
- **Turbo** v2.9.4 — điều phối tác vụ & cache
- **Node** ≥22.0.0
### Backend (NestJS)
@@ -269,7 +269,7 @@ Maps: mapbox-gl ^3.21
Monitoring: @sentry/nextjs
```
### Testing & Quality
### Testing & Chất lượng
```
Test: vitest ^4.1.3, @playwright/test ^1.59
Lint: eslint ^9.39, prettier ^3.8, typescript-eslint
@@ -278,20 +278,20 @@ Dependencies: dependency-cruiser (architecture validation)
---
## 7. TEST COVERAGE & QUALITY
## 7. ĐỘ BAO PHỦ TEST & CHẤT LƯỢNG
### Test Files: 242 total
### Tổng số file Test: 242
#### API Tests
- **Unit tests:** Payment gateways (VNPay, MoMo, ZaloPay), Money value objects, Platform fee logic
- **Integration tests:** Auth flows, health checks, notifications
- Located in `__tests__` subdirs within each module
- **Unit tests:** Cổng thanh toán (VNPay, MoMo, ZaloPay), Money value objects, logic phí nền tảng
- **Integration tests:** Luồng auth, health check, notifications
- Nằm trong các thư mục con `__tests__` trong từng module
#### Frontend Tests
- **Unit tests:** Auth store, comparison store, currency formatting, validations
- **E2E tests (Playwright):** 15+ web tests, 16+ API tests
- **Unit tests:** Auth store, comparison store, định dạng tiền tệ, validation
- **E2E tests (Playwright):** 15+ web test, 16+ API test
#### E2E Test Coverage
#### Độ bao phủ E2E Test
**Web Tests (15):**
- auth-login, auth-register, auth-oauth-callback
- homepage, navigation, responsive
@@ -310,57 +310,57 @@ Dependencies: dependency-cruiser (architecture validation)
- mcp, admin
**Load Tests (K6):**
- Baseline benchmarks for search, listings, auth endpoints
- Concurrency testing up to 1000 virtual users
- Benchmark cơ sở cho các endpoint search, listings, auth
- Test đồng thời lên đến 1000 virtual users
---
## 8. IMPLEMENTATION STATUS
## 8. TRẠNG THÁI TRIỂN KHAI
### ✅ COMPLETE (Phase 7 MVP)
1. **Foundation** — Monorepo, Docker, Prisma schema, CI/CD
2. **Auth** — JWT, OAuth, MFA/TOTP, session management
3. **Listings**Full CRUD, media upload, status workflow
4. **Search** — Typesense + PostGIS geo-search
5. **Payments** — 3 VN payment gateways, webhook handling
6. **Subscriptions** — 4 tiers, quota tracking
### ✅ HOÀN THÀNH (Phase 7 MVP)
1. **Foundation** — Monorepo, Docker, schema Prisma, CI/CD
2. **Auth** — JWT, OAuth, MFA/TOTP, quản lý phiên
3. **Listings**CRUD đầy đủ, upload media, workflow trạng thái
4. **Search** — Typesense + tìm kiếm địa lý PostGIS
5. **Payments** — 3 cổng thanh toán VN, xử lý webhook
6. **Subscriptions** — 4 cấp, theo dõi quota
7. **Notifications** — Email, SMS, Push, Zalo OA
8. **Admin Panel**Moderation, user management, audit logs
9. **Agents** — Portal, inquiries, lead CRM, quality metrics
10. **Analytics**Market reports, AI valuation service
11. **Security** — Rate limiting, CSRF, field encryption, PII masking
12. **Monitoring** — Prometheus, Grafana, Sentry, log aggregation
13. **Testing** — Unit tests, E2E tests (Playwright), load tests (K6)
8. **Admin Panel**Kiểm duyệt, quản lý người dùng, audit log
9. **Agents** — Portal, inquiries, lead CRM, chỉ số chất lượng
10. **Analytics**Báo cáo thị trường, dịch vụ định giá AI
11. **Security** — Rate limiting, CSRF, mã hóa trường, che PII
12. **Monitoring** — Prometheus, Grafana, Sentry, tổng hợp log
13. **Testing** — Unit test, E2E test (Playwright), load test (K6)
### 🔄 IN PROGRESS / REMAINING
- Per Wave 14:
- TEC-1650: Listing detail non-existent ID error handling
- TEC-1652: Full E2E test suite validation
- TEC-1657: Comprehensive audit logging
### 🔄 ĐANG TIẾN HÀNH / CÒN LẠI
- Theo Wave 14:
- TEC-1650: Xử lý lỗi ID không tồn tại trên trang chi tiết listing
- TEC-1652: Xác thực bộ test E2E đầy đủ
- TEC-1657: Audit logging toàn diện
### Database Migrations
- 7+ migrations applied
### Migration Database
- 7+ migration đã được áp dụng
- Connection pooling (PgBouncer)
- PostGIS extension enabled
- Đã bật extension PostGIS
---
## 9. PROJECT MATURITY INDICATORS
## 9. CHỈ SỐ TRƯỞNG THÀNH DỰ ÁN
| Dimension | Status | Evidence |
| Khía cạnh | Trạng thái | Bằng chứng |
|-----------|--------|----------|
| **Architecture** | Production-Ready | DDD, CQRS, layered modules, clear boundaries |
| **Code Quality** | High | 242 tests, ESLint enforcement, module cruiser |
| **Security** | Hardened | JWT, MFA, encryption, rate limiting, CSRF, PII masking |
| **Documentation** | Comprehensive | 80+ audit files, runbooks, error codes, architecture |
| **Performance** | Optimized | Redis caching, Typesense search, query optimization, load tests |
| **Monitoring** | Complete | Prometheus, Grafana, Sentry, structured logging |
| **DevOps** | Mature | Docker, Kubernetes config, CI/CD pipelines, smoke tests |
| **Scaling** | Prepared | Connection pooling, caching layer, resilient services |
| **Kiến trúc** | Sẵn sàng Production | DDD, CQRS, các module phân lớp, ranh giới rõ ràng |
| **Chất lượng code** | Cao | 242 test, ESLint thực thi, module cruiser |
| **Bảo mật** | Đã được củng cố | JWT, MFA, mã hóa, rate limiting, CSRF, che PII |
| **Tài liệu** | Toàn diện | 80+ file audit, runbook, mã lỗi, kiến trúc |
| **Hiệu năng** | Đã tối ưu | Cache Redis, tìm kiếm Typesense, tối ưu truy vấn, load test |
| **Monitoring** | Hoàn chỉnh | Prometheus, Grafana, Sentry, structured logging |
| **DevOps** | Trưởng thành | Docker, cấu hình Kubernetes, pipeline CI/CD, smoke test |
| **Khả năng mở rộng** | Đã chuẩn bị | Connection pooling, lớp cache, dịch vụ có khả năng phục hồi |
---
## 10. KEY STATISTICS
## 10. THỐNG KÊ CHÍNH
```
Backend Files: ~845 TypeScript files
@@ -378,9 +378,9 @@ Lines of Code: ~50,000+ (excluding node_modules)
---
## 11. TECH STACK SUMMARY
## 11. TÓM TẮT TECH STACK
| Layer | Technology |
| Lớp | Công nghệ |
|-------|-----------|
| **Frontend** | Next.js 15, React 18, Tailwind CSS, Shadcn/ui |
| **Backend** | NestJS 11, TypeScript 6 |
@@ -397,16 +397,15 @@ Lines of Code: ~50,000+ (excluding node_modules)
| **Package Manager** | pnpm 10.27 |
| **Orchestration** | Turbo |
| **Containerization** | Docker + Docker Compose |
| **i18n** | next-intl (Vietnamese + English) |
| **i18n** | next-intl (Tiếng Việt + Tiếng Anh) |
---
## 12. NEXT STEPS FOR DEVELOPERS
1. **Local Setup:** `docker-compose up` → database + API + frontend
2. **Run Tests:** `pnpm test` (unit), `pnpm test:e2e` (E2E)
3. **Check Status:** Review PROJECT_TRACKER.md for ongoing issues
4. **Architecture:** Read docs/architecture.md for module boundaries
5. **API:** Browse docs/api-endpoints.md (Swagger-generated)
6. **Deploy:** Follow docs/deployment.md for production setup
## 12. CÁC BƯỚC TIẾP THEO CHO LẬP TRÌNH VIÊN
1. **Thiết lập cục bộ:** `docker-compose up` → database + API + frontend
2. **Chạy Test:** `pnpm test` (unit), `pnpm test:e2e` (E2E)
3. **Kiểm tra trạng thái:** Xem PROJECT_TRACKER.md để biết các issue đang diễn ra
4. **Kiến trúc:** Đọc docs/architecture.md để biết ranh giới module
5. **API:** Duyệt docs/api-endpoints.md (do Swagger tạo)
6. **Deploy:** Theo dõi docs/deployment.md để thiết lập production

View File

@@ -1,16 +1,16 @@
# GoodGo Frontend: File-by-File i18n & A11y Implementation Guide
# GoodGo Frontend: Hướng dẫn triển khai i18n & A11y theo từng file
## 📋 Complete File Mapping
## 📋 Ánh xạ file đầy đủ
### PHASE 1: INFRASTRUCTURE SETUP
### GIAI ĐOẠN 1: THIẾT LẬP HẠ TẦNG
#### 1. `middleware.ts` (CRITICAL)
**Current:** Auth routing only
**Changes:**
- Add locale detection from URL pathname
- Add cookie-based locale storage
- Redirect `/en/*` and `/vi/*` paths appropriately
- Add Accept-Language header fallback
#### 1. `middleware.ts` (QUAN TRỌNG)
**Hiện tại:** Chỉ định tuyến xác thực
**Thay đổi:**
- Thêm phát hiện locale từ pathname URL
- Thêm lưu trữ locale dựa trên cookie
- Chuyển hướng các đường dẫn `/en/*` `/vi/*` một cách phù hợp
- Thêm dự phòng dựa trên header Accept-Language
**Pseudo-code:**
```typescript
@@ -32,15 +32,15 @@ export function middleware(request: NextRequest) {
}
```
#### 2. `app/layout.tsx` (CRITICAL)
**Current:** Thai providers, hardcoded Vietnamese metadata
**Changes:**
- Change `lang="vi"` to dynamic locale
- Update metadata to be i18n-aware
- Wrap with `NextIntlClientProvider` from next-intl
- Keep existing providers (ThemeProvider, QueryProvider, AuthProvider)
#### 2. `app/layout.tsx` (QUAN TRỌNG)
**Hiện tại:** Các provider chính, metadata tiếng Việt được hardcode
**Thay đổi:**
- Thay đổi `lang="vi"` thành locale động
- Cập nhật metadata để hỗ trợ i18n
- Bao bọc bằng `NextIntlClientProvider` từ next-intl
- Giữ nguyên các provider hiện có (ThemeProvider, QueryProvider, AuthProvider)
**Key changes:**
**Các thay đổi chính:**
```typescript
import { getLocale, getTranslations } from 'next-intl/server';
@@ -59,8 +59,8 @@ export async function generateMetadata(): Promise<Metadata> {
}
```
#### 3. `i18n/config.ts` (NEW)
**Create new file** with i18n configuration:
#### 3. `i18n/config.ts` (MỚI)
**Tạo file mới** với cấu hình i18n:
```typescript
export const locales = ['en', 'vi'] as const;
export const defaultLocale = 'vi';
@@ -68,8 +68,8 @@ export const defaultLocale = 'vi';
export const timeZone = 'Asia/Ho_Chi_Minh';
```
#### 4. `public/locales/en.json` (NEW - LARGE FILE)
**Structure:**
#### 4. `public/locales/en.json` (MỚI - FILE LỚN)
**Cấu trúc:**
```json
{
"common": {
@@ -179,16 +179,16 @@ export const timeZone = 'Asia/Ho_Chi_Minh';
}
```
#### 5. `public/locales/vi.json` (NEW - LARGE FILE)
Same structure as en.json but with Vietnamese translations.
#### 5. `public/locales/vi.json` (MỚI - FILE LỚN)
Cấu trúc giống en.json nhưng với bản dịch tiếng Việt.
---
### PHASE 2: CORE COMPONENT UPDATES
### GIAI ĐOẠN 2: CẬP NHẬT COMPONENT CỐT LÕI
#### Files Requiring Translation Hook Integration
#### Các file cần tích hợp Translation Hook
##### Layout Files
##### Các file Layout
1. **`app/(public)/layout.tsx`**
```typescript
@@ -220,20 +220,20 @@ const toggleLabel = theme === 'light'
```
3. **`app/(auth)/layout.tsx`**
Update any error messages or labels to use translations.
Cập nhật mọi thông báo lỗi hoặc nhãn để sử dụng bản dịch.
##### Page Files
##### Các file Page
1. **`app/(public)/page.tsx` (LARGE FILE)**
**Areas to update:**
- Hero section (title, subtitle)
- Search form (placeholder)
- Property type badges
- Price ranges
- City options
- Section headings
- Stats labels
- CTA buttons
1. **`app/(public)/page.tsx` (FILE LỚN)**
**Các phần cần cập nhật:**
- Phần hero (tiêu đề, phụ đề)
- Form tìm kiếm (placeholder)
- Các badge loại bất động sản
- Các khoảng giá
- Tùy chọn thành phố
- Tiêu đề các phần
- Nhãn thống kê
- Các nút CTA
```typescript
export default function LandingPage() {
@@ -268,32 +268,32 @@ const OAUTH_ERROR_MESSAGES = {
```
3. **`app/(auth)/register/page.tsx`**
Same pattern as login page.
Tương tự như trang login.
4. **`app/(dashboard)/dashboard/page.tsx`** and all other dashboard pages
Update section titles, empty states, button labels.
4. **`app/(dashboard)/dashboard/page.tsx`** và tất cả các trang dashboard khác
Cập nhật tiêu đề các phần, trạng thái rỗng, nhãn các nút.
##### Search & Listing Pages
##### Các trang Search & Listing
1. **`app/(public)/search/page.tsx`**
Update search results headings, empty states, filter labels.
Cập nhật tiêu đề kết quả tìm kiếm, trạng thái rỗng, nhãn bộ lọc.
2. **`app/(public)/listings/[id]/page.tsx`**
Update property detail labels.
Cập nhật nhãn chi tiết bất động sản.
3. **`app/(dashboard)/listings/page.tsx`**
Update table headers, status labels, action labels.
Cập nhật tiêu đề bảng, nhãn trạng thái, nhãn hành động.
4. **`app/(dashboard)/listings/new/page.tsx`**
Uses listing-form-steps component (see below).
Sử dụng component listing-form-steps (xem bên dưới).
---
#### Component Files
#### Các file Component
##### Critical Components (Do First)
##### Các component quan trọng (Làm trước)
1. **`components/search/filter-bar.tsx` (HIGH PRIORITY)**
1. **`components/search/filter-bar.tsx` (ƯU TIÊN CAO)**
```typescript
// Current: Hardcoded arrays
const CITIES = ['Hồ Chí Minh', 'Hà Nội', 'Đà Nẵng', ...];
@@ -310,14 +310,14 @@ const PRICE_RANGES = [
];
```
2. **`components/listings/listing-form-steps.tsx` (HIGH PRIORITY - LARGE FILE)**
This multi-step form has many labels to translate:
- Step 1: Transaction type, property type, title, description
- Step 2: Address fields, location
- Step 3: Area, rooms, bathrooms, direction, year built, etc.
- Step 4: Pricing
2. **`components/listings/listing-form-steps.tsx` (ƯU TIÊN CAO - FILE LỚN)**
Form đa bước này có nhiều nhãn cần dịch:
- Bước 1: Loại giao dịch, loại bất động sản, tiêu đề, mô tả
- Bước 2: Các trường địa chỉ, vị trí
- Bước 3: Diện tích, phòng, phòng tắm, hướng, năm xây dựng, v.v.
- Bước 4: Giá
All field labels should use `t('form.field_name')` pattern.
Tất cả nhãn các trường nên sử dụng pattern `t('form.field_name')`.
3. **`components/auth/oauth-buttons.tsx`**
```typescript
@@ -330,7 +330,7 @@ All field labels should use `t('form.field_name')` pattern.
</Button>
```
##### Medium Priority Components
##### Các component ưu tiên trung bình
1. **`components/search/property-card.tsx`**
```typescript
@@ -361,21 +361,21 @@ const LISTING_STATUSES = {
```
3. **`components/valuation/valuation-form.tsx`**
Update form labels and buttons.
Cập nhật nhãn form và các nút.
4. **`components/listings/image-upload.tsx`**
Update button text and error messages.
Cập nhật văn bản nút và thông báo lỗi.
5. **All `components/ui/*.tsx` files with text**
- Button: any default text
- Dialog: Close button aria-label
- Input: placeholder attrs if hardcoded
- Label: any default text
- Others: similar
5. **Tất cả các file `components/ui/*.tsx` có văn bản**
- Button: bất kỳ văn bản mặc định nào
- Dialog: aria-label nút Đóng
- Input: thuộc tính placeholder nếu được hardcode
- Label: bất kỳ văn bản mặc định nào
- Khác: tương tự
---
### PHASE 3: VALIDATION & ERROR MESSAGES
### GIAI ĐOẠN 3: VALIDATION & THÔNG BÁO LỖI
#### 1. `lib/validations/auth.ts`
```typescript
@@ -394,21 +394,21 @@ const schema = z.object({
});
```
#### 2. `lib/validations/listings.ts` (LARGE FILE)
Update all Zod validation error messages:
#### 2. `lib/validations/listings.ts` (FILE LỚN)
Cập nhật tất cả thông báo lỗi validation Zod:
- "Vui lòng chọn loại giao dịch" → `t('validation.transaction_required')`
- "Tiêu đề tối thiểu 5 ký tự" → `t('validation.title_min_length')`
- All other validation messages
- Tất cả các thông báo validation khác
#### 3. `lib/validations/valuation.ts`
Similar pattern to listings.
Mẫu tương tự như listings.
---
### PHASE 4: UTILITY UPDATES
### GIAI ĐOẠN 4: CẬP NHẬT TIỆN ÍCH
#### 1. `lib/utils.ts`
No changes (already minimal).
Không thay đổi (đã tối giản).
#### 2. `lib/auth-store.ts`
```typescript
@@ -417,17 +417,17 @@ No changes (already minimal).
```
#### 3. `lib/api-client.ts`
Check if error messages from API need i18n wrapping.
Kiểm tra xem các thông báo lỗi từ API có cần bao bọc i18n hay không.
#### 4. All `lib/*-api.ts` files
Update error message handling if needed.
#### 4. Tất cả các file `lib/*-api.ts`
Cập nhật xử lý thông báo lỗi nếu cần.
---
### PHASE 5: ACCESSIBILITY UPDATES
### GIAI ĐOẠN 5: CẬP NHẬT KHẢ NĂNG TIẾP CẬN
#### 1. `components/ui/dialog.tsx` (CRITICAL A11y)
**Add focus management:**
#### 1. `components/ui/dialog.tsx` (A11y QUAN TRỌNG)
**Thêm quản lý focus:**
```typescript
// Add focus trap
// Save initial focus element
@@ -466,7 +466,7 @@ function Dialog() {
```
#### 2. `components/ui/input.tsx`
Add aria-describedby for error messages:
Thêm aria-describedby cho thông báo lỗi:
```typescript
export function Input({ error, ...props }) {
const errorId = `${props.id}-error`;
@@ -484,8 +484,8 @@ export function Input({ error, ...props }) {
```
#### 3. `components/ui/button.tsx`
Ensure all buttons have visible focus indicator (already in CSS likely).
Add aria-busy for loading state if used:
Đảm bảo tất cả các nút có chỉ báo focus rõ ràng (có thể đã có trong CSS).
Thêm aria-busy cho trạng thái loading nếu được sử dụng:
```typescript
export function Button({ disabled, isLoading, ...props }) {
return (
@@ -500,15 +500,15 @@ export function Button({ disabled, isLoading, ...props }) {
}
```
#### 4. Form Components
Update all forms to use aria-describedby for error messages:
- `app/(auth)/login/page.tsx`Already has role="alert" ✓ but could use aria-describedby
- `app/(auth)/register/page.tsx`Same
- `components/listings/listing-form-steps.tsx`Add aria-describedby
- `components/search/filter-bar.tsx`Ensure accessible labels
#### 4. Các component Form
Cập nhật tất cả các form để sử dụng aria-describedby cho thông báo lỗi:
- `app/(auth)/login/page.tsx`Đã có role="alert" ✓ nhưng có thể dùng aria-describedby
- `app/(auth)/register/page.tsx`Tương tự
- `components/listings/listing-form-steps.tsx`Thêm aria-describedby
- `components/search/filter-bar.tsx`Đảm bảo nhãn dễ tiếp cận
#### 5. All Icon-Only Buttons
Find all buttons with only icons and add aria-label:
#### 5. Tất cả các nút chỉ có biểu tượng
Tìm tất cả các nút chỉ có biểu tượng và thêm aria-label:
```typescript
// Search in components for: <Button> with only SVG children
// Add aria-label={t('...')}
@@ -524,7 +524,7 @@ Find all buttons with only icons and add aria-label:
```
#### 6. Loading Spinners
Add aria-busy and aria-label:
Thêm aria-busy aria-label:
```typescript
// In app/(public)/page.tsx and similar:
<div aria-busy={loadingFeatured} aria-label={t('common.loading')}>
@@ -533,7 +533,7 @@ Add aria-busy and aria-label:
```
#### 7. `components/listings/image-gallery.tsx`
Add keyboard navigation (arrow keys):
Thêm điều hướng bằng bàn phím (phím mũi tên):
```typescript
// Add keyboard event handler for arrow keys
// Left/Right arrows to navigate images
@@ -541,7 +541,7 @@ Add keyboard navigation (arrow keys):
---
### PHASE 6: TEST SETUP UPDATES
### GIAI ĐOẠN 6: CẬP NHẬT THIẾT LẬP TEST
#### 1. `vitest.setup.ts`
```typescript
@@ -564,35 +564,35 @@ vi.mock('next-intl', () => ({
```
#### 2. `vitest.config.ts`
May need to add path aliases or test environment setup.
Có thể cần thêm path alias hoặc thiết lập môi trường test.
#### 3. Update all test files in `__tests__/` folders
- Add locale prop to component renders
- Test both English and Vietnamese if applicable
- Mock i18n translations
#### 3. Cập nhật tất cả các file test trong thư mục `__tests__/`
- Thêm prop locale khi render component
- Test cả tiếng Anh và tiếng Việt nếu có thể
- Mock các bản dịch i18n
---
## 📊 Summary: Files by Update Complexity
## 📊 Tóm tắt: Các file theo độ phức tạp cập nhật
### Trivial (5 min each)
### Đơn giản (5 phút mỗi file)
- `app/robots.ts`
- `app/sitemap.ts`
- `components/ui/badge.tsx`
- `components/ui/card.tsx`
- `components/ui/tabs.tsx`
### Simple (15-30 min each)
- `app/(admin)/*.tsx` files (3 files)
### Đơn giản (15-30 phút mỗi file)
- Các file `app/(admin)/*.tsx` (3 file)
- `app/(dashboard)/analytics/page.tsx`
- `app/(dashboard)/profile/page.tsx`
- `app/(dashboard)/subscription/page.tsx`
- `app/(dashboard)/payments/page.tsx`
- `components/ui/*.tsx` (8 files)
- `components/ui/*.tsx` (8 file)
- `components/auth/oauth-buttons.tsx`
- `components/listings/listing-status-badge.tsx`
### Medium (30-60 min each)
### Trung bình (30-60 phút mỗi file)
- `app/(public)/layout.tsx`
- `app/(auth)/login/page.tsx`
- `app/(auth)/register/page.tsx`
@@ -602,47 +602,47 @@ May need to add path aliases or test environment setup.
- `components/search/property-card.tsx`
- `components/search/filter-bar.tsx`
- `components/listings/image-upload.tsx`
- `components/valuation/*.tsx` (3 files)
- `components/valuation/*.tsx` (3 file)
### Complex (1-2 hours each)
- `app/(public)/page.tsx` (landing page - many sections)
- `components/listings/listing-form-steps.tsx` (multi-step form)
- `components/map/listing-map.tsx` (if has labels)
- `components/charts/*.tsx` (3 files - chart labels)
### Phức tạp (1-2 giờ mỗi file)
- `app/(public)/page.tsx` (trang landing - nhiều phần)
- `components/listings/listing-form-steps.tsx` (form đa bước)
- `components/map/listing-map.tsx` (nếu có nhãn)
- `components/charts/*.tsx` (3 file - nhãn biểu đồ)
### Critical Infrastructure
- `middleware.ts` (30-45 min)
- `app/layout.tsx` (30 min)
- `lib/validations/*.ts` (3 files - 45 min)
### Hạ tầng quan trọng
- `middleware.ts` (30-45 phút)
- `app/layout.tsx` (30 phút)
- `lib/validations/*.ts` (3 file - 45 phút)
---
## ✅ Validation Checklist
## ✅ Checklist xác minh
Before considering i18n + A11y complete:
Trước khi xem xét i18n + A11y hoàn tất:
### i18n Verification
- [ ] Both `/en/*` and `/vi/*` routes work
- [ ] All text from messages files, not hardcoded
- [ ] Metadata changes with locale
- [ ] Cookies/headers work for locale selection
- [ ] Validation messages use i18n
- [ ] All enums use translations
- [ ] Tests mock i18n correctly
### Xác minh i18n
- [ ] Cả route `/en/*` `/vi/*` đều hoạt động
- [ ] Tất cả văn bản từ file messages, không hardcode
- [ ] Metadata thay đổi theo locale
- [ ] Cookie/header hoạt động cho việc chọn locale
- [ ] Thông báo validation sử dụng i18n
- [ ] Tất cả các enum sử dụng bản dịch
- [ ] Test mock i18n đúng cách
### A11y Verification
- [ ] Focus trap works in dialogs
- [ ] Focus indicator visible on all inputs
- [ ] Form errors linked with aria-describedby
- [ ] Icon buttons all have aria-labels
- [ ] Color contrast >= 4.5:1 for text (AA standard)
- [ ] Keyboard navigation works everywhere
- [ ] Screen reader testing (NVDA/JAWS)
- [ ] Loading spinners have aria-busy
- [ ] All tables have proper headers
### Xác minh A11y
- [ ] Focus trap hoạt động trong dialog
- [ ] Chỉ báo focus hiển thị trên tất cả input
- [ ] Lỗi form được liên kết với aria-describedby
- [ ] Tất cả nút biểu tượng có aria-label
- [ ] Tỷ lệ tương phản màu >= 4.5:1 cho văn bản (chuẩn AA)
- [ ] Điều hướng bàn phím hoạt động ở mọi nơi
- [ ] Test với screen reader (NVDA/JAWS)
- [ ] Loading spinner aria-busy
- [ ] Tất cả các bảng có header phù hợp
---
**Generated:** April 9, 2026
**Confidence:** High
**Total Estimated Files to Update:** 50-60 files
**Được tạo:** Ngày 9 tháng 4 năm 2026
**Độ tin cậy:** Cao
**Tổng số file ước tính cần cập nhật:** 50-60 file

View File

@@ -1,22 +1,22 @@
# GoodGo Platform AI — Implementation Plan
# Nền tảng GoodGo AI — Kế hoạch triển khai
**Last Updated:** 2026-04-12
**Cập nhật lần cuối:** 2026-04-12
---
## Milestones
## Các Milestone
### Milestone 1: Walking Skeleton (Phase 0)
**Goal:** Any engineer can clone, install, and start developing.
**Mục tiêu:** Bất kỳ kỹ sư nào cũng có thể clone, cài đặt và bắt đầu phát triển.
**Execution Order:**
**Thứ tự thực hiện:**
1. **[TEC-1415] Monorepo Scaffolding** + **[TEC-1416] Docker Compose** (parallel — no deps)
2. **[TEC-1420] ESLint/Prettier** (after F1)
3. **[TEC-1417] Prisma Schema** (after F1 + F2)
4. **[TEC-1418] Shared Module** (after F1)
5. **[TEC-1419] CI/CD Pipeline** (after F1)
1. **[TEC-1415] Monorepo Scaffolding** + **[TEC-1416] Docker Compose** (song song — không có dependency)
2. **[TEC-1420] ESLint/Prettier** (sau F1)
3. **[TEC-1417] Prisma Schema** (sau F1 + F2)
4. **[TEC-1418] Shared Module** (sau F1)
5. **[TEC-1419] CI/CD Pipeline** (sau F1)
```
F1 (Monorepo) ──┬── F6 (Lint/Prettier)
@@ -28,17 +28,17 @@ F2 (Docker) ─────┘
### Milestone 2: Core Product (Phase 1)
**Goal:** Users can register, post listings, and search properties.
**Mục tiêu:** Người dùng có thể đăng ký, đăng tin và tìm kiếm bất động sản.
**Execution Order:**
**Thứ tự thực hiện:**
1. **[TEC-1421] Auth Backend** (after F3, F4)
2. **[TEC-1425] Security Hardening** + **[TEC-1426] Error Handling** (parallel, after F1/F4)
3. **[TEC-1422] Auth Frontend** (after C1)
4. **[TEC-1423] Listings Backend** (after C1)
5. **[TEC-1424] Search Backend** (after C3)
6. **[TEC-1427] Listings Frontend** (after C3)
7. **[TEC-1428] Search + Landing Frontend** (after C5)
1. **[TEC-1421] Auth Backend** (sau F3, F4)
2. **[TEC-1425] Security Hardening** + **[TEC-1426] Error Handling** (song song, sau F1/F4)
3. **[TEC-1422] Auth Frontend** (sau C1)
4. **[TEC-1423] Listings Backend** (sau C1)
5. **[TEC-1424] Search Backend** (sau C3)
6. **[TEC-1427] Listings Frontend** (sau C3)
7. **[TEC-1428] Search + Landing Frontend** (sau C5)
```
F3 + F4 ──→ C1 (Auth BE) ──┬── C2 (Auth FE)
@@ -50,7 +50,7 @@ F3 + F4 ──→ C1 (Auth BE) ──┬── C2 (Auth FE)
### Milestone 3: Monetization (Phase 2)
**Goal:** Revenue-generating MVP with payments, subscriptions, and admin tools.
**Mục tiêu:** MVP tạo doanh thu với thanh toán, subscription và công cụ admin.
```
C1 ──→ M1 (Payments) ──→ M2 (Subscriptions)
@@ -61,7 +61,7 @@ Phase 1 ──→ X4 (E2E Tests)
### Milestone 4: AI-Powered (Phase 3)
**Goal:** Differentiated product with AI features.
**Mục tiêu:** Sản phẩm khác biệt với các tính năng AI.
```
F2 ──→ A1 (AI/ML Container) ──→ A2 (Analytics)
@@ -70,12 +70,12 @@ C5 + A2 ──→ A3 (MCP Servers)
---
## Dependency Map
## Bản đồ phụ thuộc
| Task | Depends On |
| Task | Phụ thuộc vào |
| ------------- | ---------- |
| TEC-1415 (F1) | None |
| TEC-1416 (F2) | None |
| TEC-1415 (F1) | Không |
| TEC-1416 (F2) | Không |
| TEC-1417 (F3) | F1, F2 |
| TEC-1418 (F4) | F1 |
| TEC-1419 (F5) | F1 |
@@ -96,15 +96,15 @@ C5 + A2 ──→ A3 (MCP Servers)
### Milestone 5: Production Hardening (Phase 4)
**Goal:** Fix all critical security issues. Establish production deployment capability.
**Mục tiêu:** Sửa tất cả các vấn đề bảo mật quan trọng. Thiết lập khả năng triển khai production.
**Execution Order:**
**Thứ tự thực hiện:**
1. **[TEC-1449] JWT Secret Fix** + **[TEC-1451] HMAC Timing Fix** + **[TEC-1452] MinIO Fix** + **[TEC-1453] CSRF** (parallel — no deps between them)
2. **[TEC-1455] DB Index** (independent — can run parallel with above)
3. **[TEC-1450] Deployment Pipeline** (after security fixes verified)
4. **[TEC-1457] Backups + Logs** (after deployment infra exists)
5. **[TEC-1456] Test Coverage** (parallel — independent of infra)
1. **[TEC-1449] JWT Secret Fix** + **[TEC-1451] HMAC Timing Fix** + **[TEC-1452] MinIO Fix** + **[TEC-1453] CSRF** (song song — không có dependency giữa chúng)
2. **[TEC-1455] DB Index** (độc lập — có thể chạy song song với các task trên)
3. **[TEC-1450] Deployment Pipeline** (sau khi đã xác minh các bản sửa lỗi bảo mật)
4. **[TEC-1457] Backups + Logs** (sau khi hạ tầng deployment đã có)
5. **[TEC-1456] Test Coverage** (song song — độc lập với hạ tầng)
```
TEC-1449 (JWT) ──────┐
@@ -117,7 +117,7 @@ TEC-1456 (Tests) ─────────────────────
### Milestone 6: Quality & Polish (Phase 5)
**Goal:** Production-quality UX, documentation, and performance.
**Mục tiêu:** UX, tài liệu và hiệu năng đạt chất lượng production.
```
Phase 4 done ──→ TEC-1458 (Redis Caching)
@@ -128,47 +128,47 @@ Phase 4 done ──→ TEC-1458 (Redis Caching)
---
## Dependency Map (Phase 4-5)
## Bản đồ phụ thuộc (Phase 4-5)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1449 | None |
| TEC-1450 | TEC-1449 (security first) |
| TEC-1451 | None |
| TEC-1452 | None |
| TEC-1453 | None |
| TEC-1455 | None |
| TEC-1456 | None |
| TEC-1449 | Không |
| TEC-1450 | TEC-1449 (bảo mật trước) |
| TEC-1451 | Không |
| TEC-1452 | Không |
| TEC-1453 | Không |
| TEC-1455 | Không |
| TEC-1456 | Không |
| TEC-1457 | TEC-1450 |
| TEC-1458 | Phase 4 |
| TEC-1459 | None |
| TEC-1460 | None |
| TEC-1461 | None |
| TEC-1459 | Không |
| TEC-1460 | Không |
| TEC-1461 | Không |
### Milestone 7: MVP Feature Completion & Audit (Phase 6)
### Milestone 7: Hoàn thành tính năng MVP & Audit (Phase 6)
**Goal:** Complete remaining MVP features (Agent Portal, AI, Payments), clean up tech debt from audit.
**Mục tiêu:** Hoàn thành các tính năng MVP còn lại (Agent Portal, AI, Payments), dọn dẹp tech debt từ audit.
**Sprint 1 — Stabilize (Week 1):**
1. **[TEC-1592] Commit untracked files** (P0, no deps)
2. **[TEC-1593] Fix Architect agent** (P0, no deps)
3. **[TEC-1594] i18n consolidation** (P1, no deps)
**Sprint 1 — Ổn định (Tuần 1):**
1. **[TEC-1592] Commit các file chưa được track** (P0, không có dependency)
2. **[TEC-1593] Sửa Architect agent** (P0, không có dependency)
3. **[TEC-1594] Hợp nhất i18n** (P1, không có dependency)
**Sprint 2 — Agent Portal + Payments (Weeks 2-3):**
4. **[TEC-1595] Agent Portal** (P1, after TEC-1592)
5. **[TEC-1597] Payment flow** (P1, after TEC-1592)
6. **[TEC-1598] Smoke tests** (P1, independent)
**Sprint 2 — Agent Portal + Payments (Tuần 2-3):**
4. **[TEC-1595] Agent Portal** (P1, sau TEC-1592)
5. **[TEC-1597] Luồng thanh toán** (P1, sau TEC-1592)
6. **[TEC-1598] Smoke test** (P1, độc lập)
**Sprint 3 — AI & Quality (Weeks 4-5):**
7. **[TEC-1596] AI/ML integration** (P1, after TEC-1592)
8. **[TEC-1599] Test coverage** (P2, independent)
9. **[TEC-1600] OpenAPI docs** (P2, independent)
**Sprint 3 — AI & Chất lượng (Tuần 4-5):**
7. **[TEC-1596] Tích hợp AI/ML** (P1, sau TEC-1592)
8. **[TEC-1599] Độ bao phủ test** (P2, độc lập)
9. **[TEC-1600] Tài liệu OpenAPI** (P2, độc lập)
**Sprint 4 — Hardening (Weeks 5-6):**
10. **[TEC-1601] K6 baselines** (P2, independent)
11. **[TEC-1602] Security audit** (P2, after Phase 4 security fixes)
12. **[TEC-1603] DB index optimization** (P2, independent)
13. **[TEC-1604] Sentry integration** (P2, independent)
**Sprint 4 — Củng cố (Tuần 5-6):**
10. **[TEC-1601] Baseline K6** (P2, độc lập)
11. **[TEC-1602] Audit bảo mật** (P2, sau các bản sửa bảo mật Phase 4)
12. **[TEC-1603] Tối ưu DB index** (P2, độc lập)
13. **[TEC-1604] Tích hợp Sentry** (P2, độc lập)
```
TEC-1592 (Commit) ──┬── TEC-1595 (Agent Portal)
@@ -182,51 +182,51 @@ TEC-1599..1604 (P2 quality) ── (all independent, parallel)
---
## Dependency Map (Phase 6)
## Bản đồ phụ thuộc (Phase 6)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1592 | None |
| TEC-1593 | None |
| TEC-1594 | None |
| TEC-1592 | Không |
| TEC-1593 | Không |
| TEC-1594 | Không |
| TEC-1595 | TEC-1592 |
| TEC-1596 | TEC-1592 |
| TEC-1597 | TEC-1592 |
| TEC-1598 | None |
| TEC-1599 | None |
| TEC-1600 | None |
| TEC-1601 | None |
| TEC-1602 | Phase 4 security |
| TEC-1603 | None |
| TEC-1604 | None |
| TEC-1598 | Không |
| TEC-1599 | Không |
| TEC-1600 | Không |
| TEC-1601 | Không |
| TEC-1602 | Bảo mật Phase 4 |
| TEC-1603 | Không |
| TEC-1604 | Không |
### Milestone 8: Post-MVP Improvements (Phase 7)
### Milestone 8: Cải tiến sau MVP (Phase 7)
**Goal:** Fix remaining bugs, harden for production, improve UX and DX.
**Mục tiêu:** Sửa các bug còn lại, củng cố cho production, cải thiện UX DX.
**Wave 1 — Critical Bug Fixes (1-2 days):**
1. **[TEC-1647] Fix Reviews routing** (P0, no deps)
2. **[TEC-1648] Fix Health endpoints** (P0, no deps)
3. **[TEC-1649] Fix Login error handling** (P0, needs DB)
4. **[TEC-1650] Fix Listing 404** (P1, needs DB)
**Wave 1 — Sửa lỗi quan trọng (1-2 ngày):**
1. **[TEC-1647] Sửa định tuyến Reviews** (P0, không có dependency)
2. **[TEC-1648] Sửa các Health endpoint** (P0, không có dependency)
3. **[TEC-1649] Sửa xử lý lỗi Login** (P0, cần DB)
4. **[TEC-1650] Sửa Listing 404** (P1, cần DB)
**Wave 2 — Production Readiness (3-5 days):**
5. **[TEC-1651] E2E CI environment** (P1, no deps)
6. **[TEC-1652] Run E2E tests** (P1, after Wave 1 fixes)
7. **[TEC-1653] Security headers audit** (P1, no deps)
8. **[TEC-1658] PgBouncer pooling** (P1, no deps)
**Wave 2 — Sẵn sàng Production (3-5 ngày):**
5. **[TEC-1651] Môi trường E2E CI** (P1, không có dependency)
6. **[TEC-1652] Chạy E2E test** (P1, sau các fix Wave 1)
7. **[TEC-1653] Audit security header** (P1, không có dependency)
8. **[TEC-1658] PgBouncer pooling** (P1, không có dependency)
**Wave 3 — User-Facing Quality (1-2 weeks):**
9. **[TEC-1654] Mobile responsive** (P1, no deps)
10. **[TEC-1655] SEO optimization** (P1, no deps)
11. **[TEC-1656] Per-user rate limiting** (P1, no deps)
12. **[TEC-1657] Admin audit logging** (P1, no deps)
**Wave 3 — Chất lượng hướng tới người dùng (1-2 tuần):**
9. **[TEC-1654] Mobile responsive** (P1, không có dependency)
10. **[TEC-1655] Tối ưu SEO** (P1, không có dependency)
11. **[TEC-1656] Rate limiting theo người dùng** (P1, không có dependency)
12. **[TEC-1657] Audit logging cho admin** (P1, không có dependency)
**Wave 4 — Engineering Excellence (2-3 weeks):**
13. **[TEC-1659] Graceful degradation** (P2, no deps)
14. **[TEC-1660] Error codes documentation** (P2, no deps)
15. **[TEC-1661] RUM + Web Vitals** (P2, no deps)
16. **[TEC-1662] Update QA Tracker** (P2, after Wave 2)
**Wave 4 — Xuất sắc về Engineering (2-3 tuần):**
13. **[TEC-1659] Graceful degradation** (P2, không có dependency)
14. **[TEC-1660] Tài liệu mã lỗi** (P2, không có dependency)
15. **[TEC-1661] RUM + Web Vitals** (P2, không có dependency)
16. **[TEC-1662] Cập nhật QA Tracker** (P2, sau Wave 2)
```
TEC-1647 (Reviews) ──┐
@@ -242,39 +242,39 @@ TEC-1659..1661 (Wave 4) ── (all independent, parallel)
---
## Dependency Map (Phase 7)
## Bản đồ phụ thuộc (Phase 7)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1647 | None |
| TEC-1648 | None |
| TEC-1649 | None |
| TEC-1650 | None |
| TEC-1651 | None |
| TEC-1647 | Không |
| TEC-1648 | Không |
| TEC-1649 | Không |
| TEC-1650 | Không |
| TEC-1651 | Không |
| TEC-1652 | TEC-1647, TEC-1648 |
| TEC-1653 | None |
| TEC-1654 | None |
| TEC-1655 | None |
| TEC-1656 | None |
| TEC-1657 | None |
| TEC-1658 | None |
| TEC-1659 | None |
| TEC-1660 | None |
| TEC-1661 | None |
| TEC-1653 | Không |
| TEC-1654 | Không |
| TEC-1655 | Không |
| TEC-1656 | Không |
| TEC-1657 | Không |
| TEC-1658 | Không |
| TEC-1659 | Không |
| TEC-1660 | Không |
| TEC-1661 | Không |
| TEC-1662 | TEC-1652 |
### Milestone 9: CEO Audit Wave 5 — Security & Features (Phase 7 continued)
### Milestone 9: Audit của CEO Wave 5 — Bảo mật & Tính năng (Phase 7 tiếp)
**Goal:** Address security vulnerabilities, improve test coverage, implement missing Sprint 3 feature.
**Mục tiêu:** Xử lý các lỗ hổng bảo mật, cải thiện độ bao phủ test, triển khai tính năng còn thiếu của Sprint 3.
**Wave 5a — Security (DAY 1-2, parallel):**
1. **[TEC-1684] Fix npm vulnerabilities** (P0, Security Engineer)
2. **[TEC-1685] Fix lint error** (P1, QA Engineer)
**Wave 5a — Bảo mật (NGÀY 1-2, song song):**
1. **[TEC-1684] Sửa lỗ hổng npm** (P0, Security Engineer)
2. **[TEC-1685] Sửa lỗi lint** (P1, QA Engineer)
**Wave 5b — Quality & Features (WEEK 1-2):**
3. **[TEC-1686] Test coverage push** (P1, QA Engineer, after 5a)
**Wave 5b — Chất lượng & Tính năng (TUẦN 1-2):**
3. **[TEC-1686] Đẩy mạnh độ bao phủ test** (P1, QA Engineer, sau 5a)
4. **[TEC-1688] Saved Searches + Alerts** (P1, Architect)
5. **[TEC-1687] Dependabot setup** (P2, DevOps Engineer)
5. **[TEC-1687] Thiết lập Dependabot** (P2, DevOps Engineer)
```
TEC-1684 (NPM Vuln) ─────── (independent, P0)
@@ -285,43 +285,43 @@ TEC-1687 (Dependabot) ────── (independent, P2)
---
## Dependency Map (Wave 5)
## Bản đồ phụ thuộc (Wave 5)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1684 | None |
| TEC-1685 | None |
| TEC-1684 | Không |
| TEC-1685 | Không |
| TEC-1686 | TEC-1685 |
| TEC-1687 | None |
| TEC-1688 | None |
| TEC-1687 | Không |
| TEC-1688 | Không |
---
## Rollout Notes
## Ghi chú triển khai
- **Phase 0-6 complete** — 51/51 tasks done, MVP feature-complete
- **Phase 7 is current priority** — bug fixes and production hardening
- **Wave 13 is current sprint** — 6 tasks (TEC-1918 through TEC-1923)
- **Total project status** (from Paperclip, 2026-04-12): 219 done / 3 in progress / 9 todo / 3 cancelled out of 234 issues
- **Critical path:** TEC-1918 (TS errors) → TEC-1919 (E2E unblock) → production readiness checklist (TEC-1922)
- **Priorities:** CI green (TEC-1918), E2E (TEC-1919), backlog grooming (TEC-1920), /pricing page (TEC-1921)
- **Production path:** Wave 13 fixes → production readiness checklist → go-live decision
- **Phase 0-6 đã hoàn thành** — 51/51 task xong, MVP hoàn chỉnh tính năng
- **Phase 7 là ưu tiên hiện tại** — sửa bug và củng cố production
- **Wave 13 là sprint hiện tại** — 6 task (TEC-1918 đến TEC-1923)
- **Tổng trạng thái dự án** (từ Paperclip, 2026-04-12): 219 done / 3 in progress / 9 todo / 3 cancelled trên tổng số 234 issue
- **Đường găng:** TEC-1918 (TS errors) → TEC-1919 (E2E unblock) → checklist sẵn sàng production (TEC-1922)
- **Ưu tiên:** CI green (TEC-1918), E2E (TEC-1919), grooming backlog (TEC-1920), trang /pricing (TEC-1921)
- **Lộ trình production:** Các fix Wave 13 → checklist sẵn sàng production → quyết định go-live
### Milestone 13: CEO Audit Wave 13 (Phase 7 continued)
### Milestone 13: Audit của CEO Wave 13 (Phase 7 tiếp)
**Goal:** Fix remaining TS errors, unblock E2E, groom backlog, complete pricing page, production readiness checklist.
**Mục tiêu:** Sửa các lỗi TS còn lại, gỡ chặn E2E, grooming backlog, hoàn thành trang pricing, checklist sẵn sàng production.
**Wave 13A — CI Fix (Day 1):**
1. **[TEC-1918] Fix 7 TS compile errors in web test files** (P0, Senior Backend Engineer)
**Wave 13A — Sửa CI (Ngày 1):**
1. **[TEC-1918] Sửa 7 lỗi biên dịch TS trong các file test web** (P0, Senior Backend Engineer)
**Wave 13B — Features & Quality (Days 2-3):**
2. **[TEC-1919] Unblock E2E test environment** (P1, DevOps Engineer)
3. **[TEC-1920] Backlog grooming — deduplicate and close resolved** (P1, QA Engineer)
4. **[TEC-1921] Complete /pricing page** (P1, Senior Frontend Engineer)
**Wave 13B — Tính năng & Chất lượng (Ngày 2-3):**
2. **[TEC-1919] Gỡ chặn môi trường E2E test** (P1, DevOps Engineer)
3. **[TEC-1920] Grooming backlog — loại bỏ trùng lặp và đóng các task đã giải quyết** (P1, QA Engineer)
4. **[TEC-1921] Hoàn thành trang /pricing** (P1, Senior Frontend Engineer)
**Wave 13C — Documentation & Readiness (Days 3-5):**
5. **[TEC-1922] Production readiness checklist** (P2, SRE Engineer)
6. **[TEC-1923] Update PROJECT_TRACKER.md** (P2, Technical Writer)
**Wave 13C — Tài liệu & Sẵn sàng (Ngày 3-5):**
5. **[TEC-1922] Checklist sẵn sàng production** (P2, SRE Engineer)
6. **[TEC-1923] Cập nhật PROJECT_TRACKER.md** (P2, Technical Writer)
```
TEC-1918 (TS Errors) ──→ TEC-1919 (E2E Unblock)
@@ -333,31 +333,31 @@ TEC-1923 (Tracker) ────── (independent)
---
## Dependency Map (Wave 13)
## Bản đồ phụ thuộc (Wave 13)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1918 | None |
| TEC-1918 | Không |
| TEC-1919 | TEC-1918 |
| TEC-1920 | None |
| TEC-1921 | None |
| TEC-1920 | Không |
| TEC-1921 | Không |
| TEC-1922 | TEC-1918, TEC-1919|
| TEC-1923 | None |
| TEC-1923 | Không |
### Milestone 12: CEO Audit CI Pipeline Fix (Phase 7 Wave 12)
### Milestone 12: Audit của CEO — Sửa CI Pipeline (Phase 7 Wave 12)
**Goal:** Restore CI pipeline to green. Fix all TypeScript, ESLint, and test failures. Commit outstanding work.
**Mục tiêu:** Khôi phục CI pipeline về trạng thái xanh. Sửa tất cả các lỗi TypeScript, ESLint và test. Commit công việc còn tồn đọng.
**Wave 12A — Fix CI (Day 1, parallel):**
1. **[TEC-1898] Fix Prisma 7 migration** (P0, Senior Backend Engineer)
2. **[TEC-1899] Fix 31 failing unit tests** (P0, QA Engineer)
3. **[TEC-1900] Fix ESLint errors + commit files** (P0, Senior Backend Engineer, after TEC-1898)
**Wave 12A — Sửa CI (Ngày 1, song song):**
1. **[TEC-1898] Sửa migration Prisma 7** (P0, Senior Backend Engineer)
2. **[TEC-1899] Sửa 31 unit test thất bại** (P0, QA Engineer)
3. **[TEC-1900] Sửa lỗi ESLint + commit file** (P0, Senior Backend Engineer, sau TEC-1898)
**Wave 12B — Bug Fixes (Days 2-3):**
4. **[TEC-1649] Login 500→401 fix** (P1, in progress)
5. **[TEC-1657] Admin audit logging** (P1, todo)
6. **[TEC-1878] E2E environment** (P1, DevOps Engineer)
7. **[TEC-1847] React component tests** (P1, QA Engineer)
**Wave 12B — Sửa lỗi (Ngày 2-3):**
4. **[TEC-1649] Fix Login 500→401** (P1, đang tiến hành)
5. **[TEC-1657] Audit logging cho admin** (P1, todo)
6. **[TEC-1878] Môi trường E2E** (P1, DevOps Engineer)
7. **[TEC-1847] Test component React** (P1, QA Engineer)
```
TEC-1898 (Prisma Fix) ──┬── TEC-1900 (ESLint + Commit)
@@ -370,14 +370,14 @@ TEC-1847 (RTL Tests) ──── (independent)
---
## Dependency Map (Wave 12)
## Bản đồ phụ thuộc (Wave 12)
| Task | Depends On |
| Task | Phụ thuộc vào |
| --------------- | ----------------- |
| TEC-1898 | None |
| TEC-1899 | None |
| TEC-1898 | Không |
| TEC-1899 | Không |
| TEC-1900 | TEC-1898 |
| TEC-1649 | None |
| TEC-1657 | None |
| TEC-1878 | None |
| TEC-1847 | None |
| TEC-1649 | Không |
| TEC-1657 | Không |
| TEC-1878 | Không |
| TEC-1847 | Không |

View File

@@ -1,19 +1,19 @@
# GoodGo Frontend: i18n + A11y Implementation Quick Reference
# GoodGo Frontend: Tham chiếu nhanh triển khai i18n + A11y
## 🎯 Key Findings at a Glance
## 🎯 Những phát hiện chính trong nháy mắt
### Current State
-**Next.js 15** with App Router (well-structured)
-**React 18** + TypeScript (type-safe)
-**Tailwind CSS** with dark mode support (HSL-based theme)
-**Good component library** (~35 components)
-**Some A11y basics** in place (semantic HTML, ARIA labels, skip link)
-**NO i18n setup** (everything hardcoded Vietnamese)
-**A11y gaps** (focus management, some ARIA missing, color contrast TBD)
### Trạng thái hiện tại
-**Next.js 15** với App Router (cấu trúc tốt)
-**React 18** + TypeScript (an toàn kiểu)
-**Tailwind CSS** với hỗ trợ dark mode (theme dựa trên HSL)
-**Thư viện component tốt** (~35 component)
-**Một số kiến thức cơ bản về A11y** đã có (HTML ngữ nghĩa, ARIA labels, skip link)
-**CHƯA thiết lập i18n** (tất cả tiếng Việt được hardcode)
-**Thiếu sót A11y** (quản lý focus, một số ARIA còn thiếu, tương phản màu chưa xác định)
### Strategic Entry Points for Implementation
### Điểm vào chiến lược cho việc triển khai
#### 1. **i18n Entry Points** (Priority 1)
#### 1. **Điểm vào i18n** (Ưu tiên 1)
```
Files to modify for i18n:
├── app/layout.tsx → Add i18n provider
@@ -29,7 +29,7 @@ Files to modify for i18n:
Total files to update: ~25-30 files with hardcoded strings
```
#### 2. **A11y Critical Fixes** (Priority 1.5)
#### 2. **Sửa lỗi A11y quan trọng** (Ưu tiên 1.5)
```
Components needing A11y updates:
├── components/ui/dialog.tsx → Focus trapping + focus restoration
@@ -46,7 +46,7 @@ Tasks:
- Link form errors to inputs with aria-describedby
```
#### 3. **Message File Structure for i18n**
#### 3. **Cấu trúc file Message cho i18n**
```
public/locales/
├── en.json
@@ -64,142 +64,142 @@ public/locales/
---
## 📋 Implementation Checklist
## 📋 Checklist triển khai
### Phase 1: Setup (2-3 hours)
- [ ] Install `next-intl` package
- [ ] Create message files (en.json, vi.json)
- [ ] Update next.config.js for i18n routing
- [ ] Create i18n config (config.ts)
- [ ] Update middleware.ts for locale detection
- [ ] Wrap root layout with i18n provider
### Giai đoạn 1: Thiết lập (2-3 giờ)
- [ ] Cài đặt gói `next-intl`
- [ ] Tạo các file message (en.json, vi.json)
- [ ] Cập nhật next.config.js cho routing i18n
- [ ] Tạo cấu hình i18n (config.ts)
- [ ] Cập nhật middleware.ts để phát hiện locale
- [ ] Bao bọc root layout bằng provider i18n
### Phase 2: Core Refactoring (6-8 hours)
- [ ] Update root layout & metadata
- [ ] Refactor all validations (Zod) to use messages
- [ ] Extract component strings to useTranslations()
- [ ] Update all enums (TRANSACTION_TYPES, PROPERTY_TYPES, etc.) to use i18n
- [ ] Update page layouts (public, auth, dashboard)
- [ ] Update all page content
### Giai đoạn 2: Tái cấu trúc cốt lõi (6-8 giờ)
- [ ] Cập nhật root layout & metadata
- [ ] Tái cấu trúc tất cả validation (Zod) để sử dụng messages
- [ ] Trích xuất chuỗi component sang useTranslations()
- [ ] Cập nhật tất cả các enum (TRANSACTION_TYPES, PROPERTY_TYPES, v.v.) để sử dụng i18n
- [ ] Cập nhật các page layout (public, auth, dashboard)
- [ ] Cập nhật toàn bộ nội dung trang
### Phase 3: Component Updates (4-6 hours)
- [ ] Update all UI components
- [ ] Update form components
- [ ] Update navigation components
- [ ] Update search/filter components
- [ ] Update listing form
### Giai đoạn 3: Cập nhật component (4-6 giờ)
- [ ] Cập nhật tất cả các component UI
- [ ] Cập nhật các component form
- [ ] Cập nhật các component navigation
- [ ] Cập nhật các component search/filter
- [ ] Cập nhật form đăng tin (listing form)
### Phase 4: A11y Fixes (4-6 hours)
- [ ] Fix focus management in dialogs
- [ ] Add focus trapping
- [ ] Update form error linking (aria-describedby)
- [ ] Add aria-busy to loading states
- [ ] Add aria-labels to icon buttons
- [ ] Verify color contrast
- [ ] Update test setup for i18n
### Giai đoạn 4: Sửa lỗi A11y (4-6 giờ)
- [ ] Sửa quản lý focus trong dialog
- [ ] Thêm focus trapping
- [ ] Cập nhật liên kết lỗi form (aria-describedby)
- [ ] Thêm aria-busy cho trạng thái loading
- [ ] Thêm aria-label cho các nút biểu tượng
- [ ] Xác minh tương phản màu
- [ ] Cập nhật thiết lập test cho i18n
### Phase 5: Testing & QA (3-4 hours)
- [ ] Test both locales on all pages
- [ ] Run axe DevTools accessibility audit
- [ ] Test keyboard navigation
- [ ] Test screen reader compatibility
- [ ] Update unit tests for i18n
### Giai đoạn 5: Test & QA (3-4 giờ)
- [ ] Test cả hai locale trên tất cả các trang
- [ ] Chạy kiểm tra khả năng tiếp cận bằng axe DevTools
- [ ] Test điều hướng bằng bàn phím
- [ ] Test tương thích screen reader
- [ ] Cập nhật unit test cho i18n
---
## 🗣️ Text Content Inventory
## 🗣️ Kiểm kê nội dung văn bản
### Navigation & Layout (~15 items)
| Location | Text | Status |
### Navigation & Layout (~15 mục)
| Vị trí | Văn bản | Trạng thái |
|----------|------|--------|
| Public header | Trang chủ, Tìm kiếm, Đăng nhập, Đăng ký | ❌ Hardcoded |
| Dashboard nav | 8 nav items | ❌ Hardcoded |
| Footer | 4 sections | ❌ Hardcoded |
| Dashboard nav | 8 mục nav | ❌ Hardcoded |
| Footer | 4 phần | ❌ Hardcoded |
### Forms & Validation (~40+ items)
| Location | Type | Count | Status |
### Forms & Validation (~40+ mục)
| Vị trí | Loại | Số lượng | Trạng thái |
|----------|------|-------|--------|
| Login form | Labels + errors | 8 | ❌ Hardcoded |
| Register form | Labels + errors | 10 | ❌ Hardcoded |
| Listing form | Multi-step labels | 25+ | ❌ Hardcoded |
| Search filters | Option labels | 30+ | ❌ Hardcoded |
| Zod validation | Error messages | 20+ | ❌ Hardcoded |
| Login form | Nhãn + lỗi | 8 | ❌ Hardcoded |
| Register form | Nhãn + lỗi | 10 | ❌ Hardcoded |
| Listing form | Nhãn đa bước | 25+ | ❌ Hardcoded |
| Search filters | Nhãn tùy chọn | 30+ | ❌ Hardcoded |
| Zod validation | Thông báo lỗi | 20+ | ❌ Hardcoded |
### Enums & Constants (~50+ items)
| File | Items | Status |
### Enum & Hằng số (~50+ mục)
| File | Mục | Trạng thái |
|------|-------|--------|
| TRANSACTION_TYPES | 2 labels | ❌ Hardcoded |
| PROPERTY_TYPES | 6 labels | ❌ Hardcoded |
| LISTING_STATUSES | 8 labels | ❌ Hardcoded |
| DIRECTIONS | 8 labels | ❌ Hardcoded |
| CITIES | 13 names | ❌ Hardcoded |
| PRICE_RANGES | 6 ranges | ❌ Hardcoded |
| TRANSACTION_TYPES | 2 nhãn | ❌ Hardcoded |
| PROPERTY_TYPES | 6 nhãn | ❌ Hardcoded |
| LISTING_STATUSES | 8 nhãn | ❌ Hardcoded |
| DIRECTIONS | 8 nhãn | ❌ Hardcoded |
| CITIES | 13 tên | ❌ Hardcoded |
| PRICE_RANGES | 6 khoảng | ❌ Hardcoded |
### Page Content (~30 items)
| Page | Sections | Status |
### Nội dung trang (~30 mục)
| Trang | Phần | Trạng thái |
|------|----------|--------|
| Landing page | Hero, search, stats, CTA | ❌ Hardcoded |
| Search results | No results, loading, headers | ❌ Hardcoded |
| Dashboard | Section titles, empty states | ❌ Hardcoded |
| Trang landing | Hero, search, stats, CTA | ❌ Hardcoded |
| Kết quả tìm kiếm | Không có kết quả, loading, header | ❌ Hardcoded |
| Dashboard | Tiêu đề phần, trạng thái rỗng | ❌ Hardcoded |
---
## 🔑 Critical Files for i18n
## 🔑 Các file quan trọng cho i18n
### Must-Update Files (Blockers)
1. **middleware.ts**Locale routing
2. **app/layout.tsx**i18n provider setup
3. **lib/validations/*.ts**Message integration
4. **lib/*.ts**Any API error message handling
### Các file phải cập nhật (Blocker)
1. **middleware.ts**Định tuyến locale
2. **app/layout.tsx**Thiết lập provider i18n
3. **lib/validations/*.ts**Tích hợp messages
4. **lib/*.ts**Bất kỳ xử lý thông báo lỗi API nào
### High-Priority Files
### Các file ưu tiên cao
1. **app/(public)/layout.tsx** — Navigation
2. **app/(auth)/login/page.tsx**Auth forms
2. **app/(auth)/login/page.tsx**Form xác thực
3. **components/listings/listing-form-steps.tsx** — Forms
4. **components/search/filter-bar.tsx**Filters
4. **components/search/filter-bar.tsx**Bộ lọc
### Medium-Priority Files
1. All page components
2. All UI components with text
3. Error boundary components
### Các file ưu tiên trung bình
1. Tất cả các component trang
2. Tất cả các component UI có văn bản
3. Các component error boundary
---
## ♿ A11y Implementation Priority
## ♿ Ưu tiên triển khai A11y
### WCAG 2.1 AA Critical Fixes
1. **Focus Management** (Level A)
- Add focus trap in `dialog.tsx`
- Restore focus on dialog close
- Visible focus indicator on all buttons
### Sửa lỗi quan trọng WCAG 2.1 AA
1. **Quản lý focus** (Cấp A)
- Thêm focus trap trong `dialog.tsx`
- Khôi phục focus khi đóng dialog
- Chỉ báo focus rõ ràng trên tất cả các nút
2. **Color Contrast** (Level AA)
- Run axe DevTools audit
- Fix any < 4.5:1 ratio text
- Fix < 3:1 ratio graphics
2. **Tương phản màu** (Cấp AA)
- Chạy kiểm tra axe DevTools
- Sửa văn bản có tỷ lệ < 4.5:1
- Sửa đồ họa có tỷ lệ < 3:1
3. **Form Accessibility** (Level A)
- Link all error messages with aria-describedby
- Proper labeling with htmlFor
- Fieldset grouping for complex forms
3. **Khả năng tiếp cận form** (Cấp A)
- Liên kết tất cả thông báo lỗi với aria-describedby
- Gắn nhãn đúng cách với htmlFor
- Nhóm fieldset cho các form phức tạp
4. **Loading States** (Level A)
- Add aria-busy to spinners
- Add aria-label with context
4. **Trạng thái Loading** (Cấp A)
- Thêm aria-busy cho spinner
- Thêm aria-label kèm ngữ cảnh
5. **Icon Buttons** (Level A)
- All icon-only buttons need aria-label
- Theme toggle button already has label
5. **Nút biểu tượng** (Cấp A)
- Tất cả các nút chỉ có biểu tượng cần aria-label
- Nút bật/tắt theme đã có nhãn
### Nice-to-Have A11y Enhancements
- Skip link already present
- Semantic HTML already used
- Role="alert" on errors
- aria-invalid on form fields
### Các cải tiến A11y nên có
- Skip link đã có sẵn
- HTML ngữ nghĩa đã được sử dụng
- Role="alert" trên lỗi
- aria-invalid trên các trường form
---
## 📦 Dependencies to Add
## 📦 Các phụ thuộc cần thêm
```bash
npm install next-intl
@@ -208,11 +208,11 @@ npm install next-intl
# Testing with mocked i18n available
```
**Total installation footprint:** ~500KB minified
**Tổng kích thước cài đặt:** ~500KB đã minify
---
## 🧪 Testing Strategy
## 🧪 Chiến lược test
### Unit Tests
```typescript
@@ -241,43 +241,43 @@ describe('LoginForm', () => {
---
## 📊 Estimated Timeline
## 📊 Lộ trình ước tính
| Phase | Duration | Effort |
| Giai đoạn | Thời gian | Công sức |
|-------|----------|--------|
| Setup | 2-3h | Low |
| Core Refactoring | 6-8h | Medium |
| Components | 4-6h | Medium |
| A11y Fixes | 4-6h | Low-Medium |
| Testing | 3-4h | Medium |
| **Total** | **19-27h** | **~3-4 days** |
| Thiết lập | 2-3h | Thấp |
| Tái cấu trúc cốt lõi | 6-8h | Trung bình |
| Components | 4-6h | Trung bình |
| Sửa lỗi A11y | 4-6h | Thấp-Trung bình |
| Testing | 3-4h | Trung bình |
| **Tổng** | **19-27h** | **~3-4 ngày** |
---
## 🚀 Implementation Order (Recommended)
## 🚀 Thứ tự triển khai (Khuyến nghị)
1. **Setup i18n infrastructure** (creates foundation)
2. **Update middleware + root layout** (enables routing)
3. **Extract & centralize all text** (main work)
4. **Fix A11y issues** (parallelize with #3)
5. **Test thoroughly** (final verification)
1. **Thiết lập hạ tầng i18n** (tạo nền tảng)
2. **Cập nhật middleware + root layout** (kích hoạt routing)
3. **Trích xuất & tập trung tất cả văn bản** (công việc chính)
4. **Sửa các vấn đề A11y** (song song với #3)
5. **Test kỹ lưỡng** (xác minh cuối cùng)
---
## 💡 Quick Win Opportunities
## 💡 Cơ hội thắng nhanh
These can be done immediately:
1. Create message file structure (30 min)
2. Add focus trap to dialog (30 min)
3. Add aria-busy to spinners (20 min)
4. Color contrast audit (1 hour)
5. Icon button aria-labels (30 min)
Những việc có thể làm ngay:
1. Tạo cấu trúc file message (30 phút)
2. Thêm focus trap cho dialog (30 phút)
3. Thêm aria-busy cho spinner (20 phút)
4. Kiểm tra tương phản màu (1 giờ)
5. Aria-label cho nút biểu tượng (30 phút)
---
## 📝 Notes for Implementation
## 📝 Ghi chú khi triển khai
### Locale Detection (middleware)
### Phát hiện locale (middleware)
```typescript
// Check in order: URL > cookie > header > default
function getLocale(request) {
@@ -288,19 +288,19 @@ function getLocale(request) {
}
```
### Message Fallback Strategy
### Chiến lược dự phòng Message
```typescript
// If translation missing, use English as fallback
// Otherwise fallback to Vietnamese (primary)
```
### Performance Considerations
- Keep message files < 100KB each
- Lazy load per-page messages if needed
- Static generation for SEO-critical pages
### Cân nhắc về hiệu năng
- Giữ các file message < 100KB mỗi file
- Lazy load message theo trang nếu cần
- Static generation cho các trang quan trọng về SEO
---
**Last Updated:** April 9, 2026
**Version:** 1.0 - Pre-Implementation
**Confidence:** High
**Cập nhật lần cuối:** Ngày 9 tháng 4 năm 2026
**Phiên bản:** 1.0 - Trước triển khai
**Độ tin cậy:** Cao

View File

@@ -1,80 +1,80 @@
# GoodGo Platform AI — Audit Reports Index
**Generated**: 2026-04-11 | **Status**: Wave 10 (Active Development)
# GoodGo Platform AI — Mục lục báo cáo Audit
**Tạo ngày**: 2026-04-11 | **Trạng thái**: Wave 10 (Đang phát triển)
---
## Quick Links
## Liên kết nhanh
### 📋 Main Audit Reports
1. **[COMPREHENSIVE_AUDIT_2026-04-11.md](COMPREHENSIVE_AUDIT_2026-04-11.md)** (768 lines)
- Complete codebase analysis with all 10 required sections
- Detailed module inventory, architecture breakdown, metrics
- Strengths, weaknesses, and actionable recommendations
### 📋 Báo cáo Audit chính
1. **[COMPREHENSIVE_AUDIT_2026-04-11.md](COMPREHENSIVE_AUDIT_2026-04-11.md)** (768 dòng)
- Phân tích toàn bộ mã nguồn với cả 10 phần yêu cầu
- Kiểm kê module chi tiết, phân tích kiến trúc, số liệu
- Điểm mạnh, điểm yếu và các khuyến nghị hành động
2. **[AUDIT_SUMMARY_2026-04-11.txt](AUDIT_SUMMARY_2026-04-11.txt)** (Quick Reference)
- Executive summary with key metrics and scores
- Visual breakdown of codebase structure
- Priority recommendations at a glance
2. **[AUDIT_SUMMARY_2026-04-11.txt](AUDIT_SUMMARY_2026-04-11.txt)** (Tham chiếu nhanh)
- Tóm tắt điều hành với các số liệu và điểm số chính
- Sơ đồ trực quan cấu trúc mã nguồn
- Khuyến nghị ưu tiên trong nháy mắt
---
## Audit Scope (All 10 Requirements Covered)
## Phạm vi Audit (Bao phủ cả 10 yêu cầu)
### ✅ 1. Top-Level Structure
### ✅ 1. Cấu trúc cấp cao nhất
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 1
- **Coverage**: All root directories, 10 config files, monorepo setup
- **Status**: Complete
- **Phạm vi**: Tất cả thư mục gốc, 10 file config, thiết lập monorepo
- **Trạng thái**: Hoàn tất
### ✅ 2. Apps/API Module Analysis
### ✅ 2. Phân tích Module Apps/API
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 2
- **Coverage**: 16 API modules, layer analysis, 788 TypeScript files, 229 tests
- **Findings**: 13 full-stack modules, 3 incomplete (health, metrics, mcp)
- **Phạm vi**: 16 module API, phân tích theo lớp, 788 file TypeScript, 229 test
- **Phát hiện**: 13 module full-stack, 3 module chưa hoàn chỉnh (health, metrics, mcp)
### ✅ 3. Apps/Web Frontend
### ✅ 3. Frontend Apps/Web
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 3
- **Coverage**: 28 routes across 4 layout groups, 66 components, 16,568 LOC
- **Findings**: Full Next.js 15 implementation, limited unit tests (6 only)
- **Phạm vi**: 28 route trên 4 nhóm layout, 66 component, 16.568 LOC
- **Phát hiện**: Triển khai đầy đủ Next.js 15, ít unit test (chỉ 6)
### ✅ 4. Prisma Database Layer
### ✅ 4. Tầng Database Prisma
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 4
- **Coverage**: 21 models, 18 enums, 12 migrations, 78 indexes
- **Findings**: Production-ready schema with GDPR compliance, audit logging
- **Phạm vi**: 21 model, 18 enum, 12 migration, 78 index
- **Phát hiện**: Schema sẵn sàng production với tuân th GDPR, audit logging
### ✅ 5. Shared Libraries (libs/)
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 5
- **Coverage**: AI services (21 Python files), MCP servers (12 TypeScript files)
- **Findings**: AI services minimal, MCP servers are stubs needing implementation
- **Phạm vi**: AI services (21 file Python), MCP servers (12 file TypeScript)
- **Phát hiện**: AI services còn tối thiểu, MCP servers mới chỉ là stub cần triển khai
### ✅ 6. E2E Testing
### ✅ 6. Testing E2E
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 6
- **Coverage**: 31 Playwright specs (16 API, 15 Web), test organization
- **Findings**: Good E2E coverage, global setup/teardown configured
- **Phạm vi**: 31 Playwright spec (16 API, 15 Web), tổ chức test
- **Phát hiện**: Độ phủ E2E tốt, đã cấu hình global setup/teardown
### ✅ 7. Configuration Files
### ✅ 7. File cấu hình
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 7
- **Coverage**: 10 root config files, 178-line .env.example, Docker stacks
- **Findings**: Comprehensive configuration documentation
- **Phạm vi**: 10 file config gốc, .env.example 178 dòng, Docker stack
- **Phát hiện**: Tài liệu cấu hình đầy đủ
### ✅ 8. Test Coverage Analysis
### ✅ 8. Phân tích độ phủ Test
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 8
- **Coverage**: 745 total test files breakdown by layer and module
- **Findings**: 229 API tests, 6 web tests, 31 E2E specs
- **Phạm vi**: Phân tích 745 file test theo lớp và theo module
- **Phát hiện**: 229 API test, 6 web test, 31 E2E spec
### ✅ 9. Documentation
### ✅ 9. Tài liệu
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 9
- **Coverage**: 89 core docs + 81 audit reports in docs/audits/
- **Findings**: Comprehensive documentation trail
- **Phạm vi**: 89 doc cốt lõi + 81 báo cáo audit trong docs/audits/
- **Phát hiện**: Lưu trữ tài liệu toàn diện
### ✅ 10. CI/CD Pipeline
- **File**: COMPREHENSIVE_AUDIT_2026-04-11.md, Section 10
- **Coverage**: 7 GitHub Actions workflows, 13-service Docker stack
- **Findings**: Production-ready DevOps, Kubernetes-ready
- **Phạm vi**: 7 workflow GitHub Actions, Docker stack 13 service
- **Phát hiện**: DevOps sẵn sàng production, sẵn sàng Kubernetes
---
## Key Findings Summary
## Tóm tắt phát hiện chính
### 📊 Codebase Metrics
### 📊 Số liệu mã nguồn
```
Total Lines of Code: 76,402 LOC
├─ API Backend: 23,926 LOC (31%)
@@ -89,123 +89,123 @@ Documentation: 89 files + 81 audits
Git Commits: 203
```
### 🏗️ Architecture Summary
- **16 NestJS API modules** (13 full-stack with ADIP layers)
- **28 Next.js routes** (public, auth, dashboard, admin)
- **21 Prisma models** (comprehensive domain model)
- **12 database migrations** (schema evolution tracked)
- **7 GitHub Actions workflows** (CI/CD complete)
### 🏗️ Tóm tắt kiến trúc
- **16 module API NestJS** (13 full-stack với lớp ADIP)
- **28 route Next.js** (public, auth, dashboard, admin)
- **21 model Prisma** (mô hình domain đầy đủ)
- **12 migration database** (theo dõi tiến hoá schema)
- **7 workflow GitHub Actions** (CI/CD hoàn chỉnh)
### 📈 Quality Scores
| Aspect | Score | Status |
### 📈 Điểm chất lượng
| Khía cạnh | Điểm | Trạng thái |
|--------|-------|--------|
| Architecture | 9/10 | ✅ Excellent |
| Code Quality | 8/10 | ✅ Good |
| Test Coverage | 7/10 | ⚠️ Needs web tests |
| Documentation | 8/10 | ✅ Comprehensive |
| CI/CD | 9/10 | ✅ Excellent |
| Database | 9/10 | ✅ Excellent |
| Error Handling | 8/10 | ⚠️ Some gaps |
| Performance | 8/10 | ✅ Good |
| Security | 7/10 | ⚠️ Add MFA |
| DevOps | 9/10 | ✅ Excellent |
| **OVERALL** | **8.2/10** | **✅ Production-Ready** |
| Kiến trúc | 9/10 | ✅ Xuất sắc |
| Chất lượng mã | 8/10 | ✅ Tốt |
| Độ phủ test | 7/10 | ⚠️ Cần thêm web test |
| Tài liệu | 8/10 | ✅ Đầy đủ |
| CI/CD | 9/10 | ✅ Xuất sắc |
| Database | 9/10 | ✅ Xuất sắc |
| Xử lý lỗi | 8/10 | ⚠️ Còn vài thiếu sót |
| Performance | 8/10 | ✅ Tốt |
| Bảo mật | 7/10 | ⚠️ Thêm MFA |
| DevOps | 9/10 | ✅ Xuất sắc |
| **TỔNG THỂ** | **8.2/10** | ** Sẵn sàng Production** |
### 🎯 Key Strengths
1.Mature DDD + CQRS architecture
2. ✅ 76K LOC of real implementation
3. ✅ 745+ test files (229 API, 31 E2E)
4.Modern tech stack (NestJS 11, Next.js 15, PostgreSQL 16)
5.Strong DevOps (Docker, K8s, GitHub Actions)
6.Excellent documentation (89 docs + 81 audits)
7. ✅ Type-safe TypeScript (strict mode)
8. ✅ 21 models with 78 indexes (optimized)
### 🎯 Điểm mạnh chính
1.Kiến trúc DDD + CQRS trưởng thành
2. ✅ 76K LOC triển khai thực sự
3. ✅ 745+ file test (229 API, 31 E2E)
4.Tech stack hiện đại (NestJS 11, Next.js 15, PostgreSQL 16)
5.DevOps vững chắc (Docker, K8s, GitHub Actions)
6.Tài liệu xuất sắc (89 doc + 81 audit)
7. ✅ TypeScript type-safe (strict mode)
8. ✅ 21 model với 78 index (đã tối ưu)
### ⚠️ Areas for Improvement
1. ⚠️ Incomplete modules (3): health, metrics, mcp
2. ⚠️ Web unit tests: only 6 (needs 50% coverage)
3. ⚠️ MCP servers: stubs only (~50 lines each)
4. ⚠️ Error handling: some CQRS handlers incomplete
5. ⚠️ Security: add field encryption, MFA, rate limiting
### ⚠️ Các điểm cần cải thiện
1. ⚠️ Module chưa hoàn chỉnh (3): health, metrics, mcp
2. ⚠️ Web unit test: chỉ 6 (cần đạt 50% coverage)
3. ⚠️ MCP servers: chỉ là stub (~50 dòng mỗi file)
4. ⚠️ Xử lý lỗi: một số CQRS handler chưa hoàn chỉnh
5. ⚠️ Bảo mật: thêm mã hoá field, MFA, rate limiting
---
## Recommendations Priority Matrix
## Ma trận ưu tiên khuyến nghị
### 🔴 High Priority (DO NOW) — 30-40 hours
1. **Complete incomplete modules** (health, metrics, mcp)
- Implement full ADIP layers for health/metrics
- Real MCP server implementations
- Effort: 5-10 hours
### 🔴 Ưu tiên cao (LÀM NGAY) — 30-40 giờ
1. **Hoàn thiện các module chưa xong** (health, metrics, mcp)
- Triển khai đầy đủ các lớp ADIP cho health/metrics
- Triển khai MCP server thực sự
- Công sức: 5-10 giờ
2. **Expand web unit tests to 50% coverage**
- Focus on critical components (auth, listings, search)
- Effort: 10-15 hours
2. **Mở rộng web unit test lên 50% coverage**
- Tập trung vào các component quan trọng (auth, listings, search)
- Công sức: 10-15 giờ
3. **Audit & complete error handling**
- Review remaining CQRS handlers
- Ensure consistent error responses
- Effort: 5 hours
3. **Audit & hoàn thiện xử lý lỗi**
- Rà soát các CQRS handler còn lại
- Đảm bảo response lỗi nhất quán
- Công sức: 5 giờ
### 🟡 Medium Priority (DO SOON) — 40-60 hours
1. **Add field-level encryption** (PII, payments)
2. **Implement API rate limiting** (per-endpoint quotas)
3. **Add OpenTelemetry tracing** (distributed tracing)
4. **Expand monitoring dashboards** (Grafana)
5. **Performance optimization** (query analysis)
### 🟡 Ưu tiên trung bình (LÀM SỚM) — 40-60 giờ
1. **Thêm field-level encryption** (PII, payments)
2. **Triển khai rate limiting API** (quota theo endpoint)
3. **Thêm OpenTelemetry tracing** (distributed tracing)
4. **Mở rộng dashboard monitoring** (Grafana)
5. **Tối ưu hoá performance** (phân tích query)
### 🟢 Low Priority (DO LATER) — Future phases
1. GraphQL API (optional)
### 🟢 Ưu tiên thấp (LÀM SAU) — Các giai đoạn sau
1. GraphQL API (tuỳ chọn)
2. Mobile app (React Native/Flutter)
3. Advanced ML features
4. Multi-tenant support
3. Tính năng ML nâng cao
4. Hỗ trợ multi-tenant
---
## Development Status
## Trạng thái phát triển
### Current Milestone: Wave 10 (Beta Phase)
- **MVP Phase**: ✅ COMPLETE (Core modules, DDD architecture)
- **Beta Phase**: 🔄 IN PROGRESS (Testing, refinement, monitoring)
- **Production Phase**: ⏳ READY (Pending validation)
- **Scale Phase**: 📋 PLANNED
### Cột mốc hiện tại: Wave 10 (Giai đoạn Beta)
- **Giai đoạn MVP**: ✅ HOÀN TẤT (Các module cốt lõi, kiến trúc DDD)
- **Giai đoạn Beta**: 🔄 ĐANG TIẾN HÀNH (Test, tinh chỉnh, monitoring)
- **Giai đoạn Production**: ⏳ SẴN SÀNG (Chờ kiểm định)
- **Giai đoạn Scale**: 📋 ĐÃ LÊN KẾ HOẠCH
### Recent Progress (Last 10 commits)
-Added comprehensive alerting rules (Alertmanager)
-K6 load testing coverage expanded
-Error handling added to 51 CQRS handlers
-Login endpoint fixed (prevented 500 errors)
-Email alert templates for saved searches
-Unit tests added for MCP, Inquiries, Leads modules
### Tiến độ gần đây (10 commit gần nhất)
-Thêm alerting rule đầy đủ (Alertmanager)
-Mở rộng độ phủ load test K6
-Thêm xử lý lỗi cho 51 CQRS handler
-Sửa endpoint login (tránh lỗi 500)
-Mẫu email alert cho saved searches
-Thêm unit test cho module MCP, Inquiries, Leads
### Development Velocity
- 203 total commits on master
- ~2 commits/day average
- Consistent feature delivery & bug fixes
### Vận tốc phát triển
- 203 commit tổng trên master
- Trung bình ~2 commit/ngày
- Delivery tính năng & sửa lỗi đều đặn
---
## Deployment Status
## Trạng thái triển khai
### Ready for:
**MVP Launch**All core features implemented
**Staging Deployment**Full CI/CD pipeline configured
**Production**Pending final validation & load testing
### Sẵn sàng cho:
**MVP Launch**Đã triển khai tất cả tính năng cốt lõi
**Staging Deployment**Pipeline CI/CD đã cấu hình đầy đủ
**Production**Chờ validation cuối cùng & load test
### Infrastructure Status
✅ Local development (docker-compose.yml, 13 services)
### Trạng thái hạ tầng
✅ Local development (docker-compose.yml, 13 service)
✅ CI environment (docker-compose.ci.yml)
✅ Production stack (docker-compose.prod.yml)
✅ Kubernetes manifests (infra/)
✅ Kubernetes manifest (infra/)
✅ Monitoring (Prometheus + Grafana)
✅ Backup/restore (pg-backup + verification)
✅ Load testing (K6 suite)
✅ Load testing (bộ K6)
---
## Technology Stack Summary
## Tóm tắt Technology Stack
| Layer | Technology | Version |
| Tầng | Công nghệ | Phiên bản |
|-------|-----------|---------|
| Backend | NestJS | 11 |
| Frontend | Next.js | 15 |
@@ -224,68 +224,68 @@ Git Commits: 203
---
## How to Use These Reports
## Cách sử dụng các báo cáo này
### For Project Managers
- Read: **AUDIT_SUMMARY_2026-04-11.txt** (quick overview)
- Then: **COMPREHENSIVE_AUDIT_2026-04-11.md** sections 1, 8-10
### Dành cho Project Managers
- Đọc: **AUDIT_SUMMARY_2026-04-11.txt** (tổng quan nhanh)
- Sau đó: **COMPREHENSIVE_AUDIT_2026-04-11.md** các phần 1, 8-10
### For Developers
- Read: **COMPREHENSIVE_AUDIT_2026-04-11.md** entire document
- Reference: **AUDIT_SUMMARY_2026-04-11.txt** for quick stats
### Dành cho Developers
- Đọc: toàn bộ **COMPREHENSIVE_AUDIT_2026-04-11.md**
- Tham khảo: **AUDIT_SUMMARY_2026-04-11.txt** để xem số liệu nhanh
### For Architects
- Focus: Sections 1-5, 7 of comprehensive audit
- Review: Module completeness, architecture patterns
### Dành cho Architects
- Tập trung: Các phần 1-5, 7 của audit toàn diện
- Rà soát: Mức độ hoàn thiện module, pattern kiến trúc
### For QA/Testers
- Focus: Sections 6, 8 of comprehensive audit
- Review: Test coverage, E2E test organization
### Dành cho QA/Testers
- Tập trung: Các phần 6, 8 của audit toàn diện
- Rà soát: Độ phủ test, tổ chức E2E test
### For DevOps/Infrastructure
- Focus: Sections 7, 10 of comprehensive audit
- Review: CI/CD workflows, Docker stack, monitoring
### Dành cho DevOps/Infrastructure
- Tập trung: Các phần 7, 10 của audit toàn diện
- Rà soát: Workflow CI/CD, Docker stack, monitoring
---
## Additional Resources
## Tài nguyên bổ sung
### In Repository
- `docs/architecture.md`Detailed system design
- `docs/api-endpoints.md`REST API reference
- `docs/api-error-codes.md`Error handling guide
- `docs/deployment.md`Production deployment guide
- `IMPLEMENTATION_PLAN.md`Remaining work
- `PROJECT_TRACKER.md`Development roadmap
- `docs/audits/` — 81 specialized audit reports
### Trong Repository
- `docs/architecture.md`Thiết kế hệ thống chi tiết
- `docs/api-endpoints.md`Tham chiếu REST API
- `docs/api-error-codes.md`Hướng dẫn xử lý lỗi
- `docs/deployment.md`Hướng dẫn deploy production
- `IMPLEMENTATION_PLAN.md`Công việc còn lại
- `PROJECT_TRACKER.md`Lộ trình phát triển
- `docs/audits/` — 81 báo cáo audit chuyên biệt
### Key Files
- `README.md`Project overview & quick start
- `CONTRIBUTING.md`Development conventions
- `CHANGELOG.md`Version history
### File quan trọng
- `README.md`Tổng quan dự án & quick start
- `CONTRIBUTING.md`Quy ước phát triển
- `CHANGELOG.md`Lịch sử phiên bản
---
## Audit Verification Checklist
## Checklist xác minh Audit
- [x] Top-level structure reviewed (all root directories)
- [x] apps/api module analysis complete (16 modules, 788 files)
- [x] apps/web frontend mapped (28 routes, 66 components)
- [x] prisma schema analyzed (21 models, 12 migrations)
- [x] libs/ libraries reviewed (AI + MCP servers)
- [x] E2E testing evaluated (31 Playwright specs)
- [x] Configuration files documented (10 root configs)
- [x] Test coverage analyzed (745 total files)
- [x] Documentation surveyed (89 docs + 81 audits)
- [x] CI/CD pipeline reviewed (7 workflows, 13 services)
- [x] Đã rà soát cấu trúc cấp cao nhất (tất cả thư mục gốc)
- [x] Hoàn tất phân tích module apps/api (16 module, 788 file)
- [x] Đã map frontend apps/web (28 route, 66 component)
- [x] Đã phân tích schema prisma (21 model, 12 migration)
- [x] Đã rà soát libs/ (AI + MCP servers)
- [x] Đã đánh giá E2E testing (31 Playwright spec)
- [x] Đã tài liệu hoá file cấu hình (10 config gốc)
- [x] Đã phân tích độ phủ test (tổng 745 file)
- [x] Đã khảo sát tài liệu (89 doc + 81 audit)
- [x] Đã rà soát CI/CD pipeline (7 workflow, 13 service)
---
**Audit Conducted**: 2026-04-11
**Status**: ✅ COMPLETE
**Quality Score**: 8.2/10 (Production-Ready)
**Next Review**: Recommend after Wave 10 completion
**Audit tiến hành**: 2026-04-11
**Trạng thái**: ✅ HOÀN TẤT
**Điểm chất lượng**: 8.2/10 (Sẵn sàng Production)
**Lần rà soát tiếp theo**: Khuyến nghị sau khi hoàn tất Wave 10
---
*For questions or clarifications, refer to the comprehensive audit document or contact the development team.*
*Nếu có thắc mắc hoặc cần làm rõ, vui lòng tham khảo tài liệu audit toàn diện hoặc liên hệ nhóm phát triển.*

View File

@@ -1,119 +1,119 @@
# GoodGo Platform AI — QUICK REFERENCE AUDIT (1-Pager)
# GoodGo Platform AI — TÀI LIỆU AUDIT THAM CHIẾU NHANH (1 trang)
**Date:** April 12, 2026 | **Status:** 🟢 **PRODUCTION-READY** | **Confidence:** 95%
**Ngày:** 12 tháng 4, 2026 | **Trạng thái:** 🟢 **SẴN SÀNG PRODUCTION** | **Mức độ tin cậy:** 95%
---
## TL;DR — THE ESSENTIALS
## TÓM TẮT — NHỮNG ĐIỂM CỐT LÕI
| Aspect | Rating | Summary |
| Khía cạnh | Đánh giá | Tóm tắt |
|--------|--------|---------|
| **Overall Score** | 8.3/10 | Production-quality code with minor gaps |
| **Architecture** | 9/10 | Excellent DDD + CQRS implementation |
| **Testing** | 8/10 | 307+ test files, 28% coverage |
| **Security** | 8.5/10 | JWT/MFA, no exposed secrets, audit logs |
| **DevOps** | 9/10 | 8 automated GitHub Actions workflows |
| **Documentation** | 7/10 | Comprehensive but some gaps |
| **Điểm tổng thể** | 8.3/10 | Mã nguồn chất lượng production với một vài lỗ hổng nhỏ |
| **Kiến trúc** | 9/10 | Triển khai DDD + CQRS xuất sắc |
| **Testing** | 8/10 | 307+ file test, độ phủ 28% |
| **Bảo mật** | 8.5/10 | JWT/MFA, không lộ secret, audit log |
| **DevOps** | 9/10 | 8 workflow GitHub Actions tự động |
| **Tài liệu** | 7/10 | Đầy đủ nhưng còn vài thiếu sót |
---
## CODEBASE SNAPSHOT
## TỔNG QUAN MÃ NGUỒN
**Size:** 815 (API TS) + 241 (Web TS) + 21 (Python AI) files
**Modules:** 16 API modules (13 fully DDD-compliant)
**Database:** 22 models + 18 enums + 60+ indexes
**Routes:** 31+ frontend routes
**Components:** 87 organized React components
**Tests:** 307+ test files
**Kích thước:** 815 (API TS) + 241 (Web TS) + 21 (Python AI) file
**Modules:** 16 module API (13 tuân thủ DDD đầy đủ)
**Database:** 22 model + 18 enum + 60+ index
**Routes:** 31+ route frontend
**Components:** 87 component React được tổ chức gọn gàng
**Tests:** 307+ file test
**Commits:** 207
**Docs:** 60+ files
**Docs:** 60+ file
---
## WHAT'S GREAT
## ĐIỂM MẠNH
1. **DDD Architecture** — 13/16 modules fully layered (domain → app → infra → presentation)
2. **Type Safety** — Strict TypeScript throughout, no `any` escapes
3. **Testing**Unit, integration, and E2E tests across the stack
4. **Security** — TOTP MFA, OAuth2, no hardcoded secrets, audit trail
5. **DevOps**CI/CD pipeline fully automated (lint → test → build → deploy)
6. **Database**Well-indexed, cascade rules defined, PostGIS support
7. **Scalability** — Turbo builds, Redis caching, horizontal scaling ready
8. **Git Hygiene** — Linting hooks, conventional commits, 207 commits
1. **Kiến trúc DDD** — 13/16 module phân lớp đầy đủ (domain → app → infra → presentation)
2. **An toàn kiểu** — TypeScript strict mode toàn bộ, không có `any` lọt qua
3. **Testing**Có unit, integration, E2E test trên toàn stack
4. **Bảo mật** — TOTP MFA, OAuth2, không hardcode secret, audit trail
5. **DevOps**Pipeline CI/CD tự động hoàn toàn (lint → test → build → deploy)
6. **Database**Đánh index tốt, định nghĩa cascade rule, hỗ trợ PostGIS
7. **Khả năng mở rộng** — Turbo build, Redis cache, sẵn sàng scale ngang
8. **Git Hygiene** — Linting hooks, conventional commit, 207 commit
---
## WHAT NEEDS WORK ⚠️
## NHỮNG ĐIỂM CẦN CẢI THIỆN ⚠️
1. **Load Testing Thresholds** — K6 tests exist but SLAs not fully documented
2. **Payment Error Cases**Mock providers need more edge-case failure tests
3. **Agents Module**Infrastructure layer light (2 files vs. 12+ in other modules)
4. **Disaster Recovery**Playbooks missing, though backup verification works
5. **Search Edge Cases**Complex filters need fuzz testing coverage
1. **Ngưỡng load test** K6 test nhưng SLA chưa được tài liệu hoá đầy đủ
2. **Trường hợp lỗi thanh toán**Provider mock cần thêm test edge case
3. **Module Agents**Lớp infrastructure mỏng (2 file so với 12+ ở các module khác)
4. **Disaster Recovery**Thiếu playbook, dù xác minh backup vẫn hoạt động
5. **Search Edge Cases**Bộ lọc phức tạp cần thêm fuzz test
---
## KEY MODULES (16 TOTAL)
## CÁC MODULE CHÍNH (TỔNG 16)
**Most Complex (Testing-heavy):**
- `auth` (124 files) — JWT, TOTP MFA, OAuth, CSRF, rate limiting
- `listings` (81 files) — Core marketplace CRUD + featured listings
- `payments` (49 files) — VNPay, MoMo, ZaloPay integration
**Phức tạp nhất (nặng test):**
- `auth` (124 file) — JWT, TOTP MFA, OAuth, CSRF, rate limiting
- `listings` (81 file) — CRUD marketplace cốt lõi + featured listings
- `payments` (49 file) — Tích hợp VNPay, MoMo, ZaloPay
**Solid Implementation:**
**Triển khai vững chắc:**
- `search`, `admin`, `analytics`, `subscriptions`, `notifications`, `inquiries`, `leads`, `reviews`
**Infrastructure-only (by design):**
- `health` (4 files) — k8s health checks
- `metrics` (8 files) — Prometheus metrics
- `mcp` (12 files) — Model Context Protocol server
**Chỉ có infrastructure (theo thiết kế):**
- `health` (4 file) — Health check k8s
- `metrics` (8 file) — Prometheus metrics
- `mcp` (12 file) — Model Context Protocol server
---
## DATABASE (22 MODELS)
## DATABASE (22 MODEL)
| Group | Models | Highlights |
| Nhóm | Models | Điểm nổi bật |
|-------|--------|-----------|
| **Auth** | User, Agent, MfaChallenge, RefreshToken, OAuthAccount | TOTP, OAuth, token rotation |
| **Marketplace** | Property, Listing, PropertyMedia, SavedSearch, Valuation | Geo-indexed, AI valuation |
| **Commerce** | Transaction, Inquiry, Lead, Payment, Subscription | 6+ status enums, audit trail |
| **Admin** | Plan, UsageRecord, NotificationLog, AdminAuditLog, Review, MarketIndex | GDPR-ready, quota tracking |
| **Auth** | User, Agent, MfaChallenge, RefreshToken, OAuthAccount | TOTP, OAuth, xoay vòng token |
| **Marketplace** | Property, Listing, PropertyMedia, SavedSearch, Valuation | Index địa lý, định giá AI |
| **Commerce** | Transaction, Inquiry, Lead, Payment, Subscription | 6+ enum trạng thái, audit trail |
| **Admin** | Plan, UsageRecord, NotificationLog, AdminAuditLog, Review, MarketIndex | Sẵn sàng GDPR, theo dõi quota |
**Indexes:** 60+ (including compound indexes for common queries)
**PostGIS:** Enabled for geospatial searches
**Cascade Rules:** Properly defined (Cascade, SetNull, Restrict)
**Indexes:** 60+ (gồm cả compound index cho các truy vấn phổ biến)
**PostGIS:** Đã bật cho tìm kiếm theo vị trí địa lý
**Cascade Rules:** Định nghĩa đúng (Cascade, SetNull, Restrict)
---
## FRONTEND (31+ ROUTES, 87 COMPONENTS)
## FRONTEND (31+ ROUTE, 87 COMPONENT)
**Public:**
- Homepage, search, listing detail, agent profiles, pricing, comparison
- Trang ch, tìm kiếm, chi tiết tin đăng, hồ sơ môi giới, bảng giá, so sánh
**Dashboard (Auth):**
- Manage listings, inquiries, leads, analytics, KYC, subscription, valuation
- Quản lý tin đăng, inquiry, lead, analytics, KYC, subscription, định giá
**Admin:**
- Moderation queue, KYC verification, user management
- Hàng đợi kiểm duyệt, xác minh KYC, quản lý người dùng
**Components:**
- 22 UI kit (Shadcn/Radix) + 12 listing + 6 search + 8 valuation + 8 comparison + more
- 22 UI kit (Shadcn/Radix) + 12 listing + 6 search + 8 valuation + 8 comparison + nhiều hơn
---
## TESTING COVERAGE
## ĐỘ PHỦ TEST
| Type | Count | Status |
| Loại | Số lượng | Trạng thái |
|------|-------|--------|
| **API Unit Tests** | 233 files | ✅ Active |
| **Frontend Unit Tests** | 66 files | ✅ Active |
| **E2E Tests (Playwright)** | 40+ cases | ✅ Active |
| **Coverage Ratio** | 28% (API/Web) | ✅ Good |
| **Test DB** | PostgreSQL 16 + PostGIS | ✅ CI-integrated |
| **API Unit Tests** | 233 file | ✅ Đang dùng |
| **Frontend Unit Tests** | 66 file | ✅ Đang dùng |
| **E2E Tests (Playwright)** | 40+ case | ✅ Đang dùng |
| **Tỉ lệ coverage** | 28% (API/Web) | ✅ Tốt |
| **Test DB** | PostgreSQL 16 + PostGIS | ✅ Tích hợp CI |
---
## CI/CD PIPELINE (8 WORKFLOWS)
## CI/CD PIPELINE (8 WORKFLOW)
```
Push → Lint (2m) → Typecheck (2m) → Test (4m) → Build (3m) → E2E (8m)
@@ -121,71 +121,71 @@ Push → Lint (2m) → Typecheck (2m) → Test (4m) → Build (3m) → E2E (8m)
```
**Workflows:**
1. `ci.yml` — Lint → Typecheck → Test → Build (~30 min)
2. `deploy.yml` — Build images → DB migrationsRollback strategy
3. `e2e.yml` — Playwright tests (API + Web)
1. `ci.yml` — Lint → Typecheck → Test → Build (~30 phút)
2. `deploy.yml` — Build image → DB migration → Chiến lược rollback
3. `e2e.yml` — Playwright test (API + Web)
4. `security.yml` — CodeQL + dependency audit
5. `load-test.yml` Weekly K6 performance tests
6. `backup-verify.yml`Daily backup integrity checks
7. `codeql.yml`Code scanning
8. `Dependabot`Dependency updates
5. `load-test.yml` — K6 performance test hàng tuần
6. `backup-verify.yml`Kiểm tra tính toàn vẹn backup hàng ngày
7. `codeql.yml`Quét mã nguồn
8. `Dependabot`Cập nhật dependency
---
## SECURITY SCORECARD
## BẢNG ĐIỂM BẢO MẬT
| Category | Grade | Notes |
| Hạng mục | Điểm | Ghi chú |
|----------|-------|-------|
| **Secrets** | A+ | No exposed keys, .env properly gitignored |
| **Secrets** | A+ | Không lộ key, .env đã gitignore đúng |
| **Auth** | A+ | JWT, TOTP MFA, OAuth2, CSRF, rate limiting |
| **Encryption** | B+ | Bcrypt passwords, PII hashing, no DB encryption at rest |
| **Audit Trail** | A+ | AdminAuditLog, NotificationLog, IP/user-agent tracking |
| **Dependencies** | B+ | pnpm overrides for CVEs, lock file locked |
| **Infrastructure** | B+ | Multi-stage Docker, k8s-ready, TLS-ready |
| **OVERALL** | **A-** | 8.5/10 — Production-grade |
| **Mã hoá** | B+ | Mật khẩu Bcrypt, hash PII, chưa mã hoá DB at rest |
| **Audit Trail** | A+ | AdminAuditLog, NotificationLog, theo dõi IP/user-agent |
| **Dependencies** | B+ | pnpm overrides cho CVE, lock file đã khoá |
| **Infrastructure** | B+ | Docker multi-stage, sẵn sàng k8s, sẵn sàng TLS |
| **TỔNG THỂ** | **A-** | 8.5/10 — Cấp độ production |
**No Critical Issues Found**
**Không phát hiện vấn đề nghiêm trọng**
---
## DEPLOYMENT READINESS
## MỨC ĐỘ SẴN SÀNG TRIỂN KHAI
| Item | Status | Details |
| Mục | Trạng thái | Chi tiết |
|------|--------|---------|
| Docker | ✅ Ready | Multi-stage builds, production-optimized |
| Database | ✅ Ready | 15 migrations, seed script, backup verification |
| Secrets | ✅ Ready | GitHub Actions secrets, no hardcoded values |
| Monitoring | ✅ Ready | Prometheus, Grafana, Loki, Sentry |
| Health Checks | ✅ Ready | /health endpoint, k8s probes |
| Rollback | ✅ Ready | Blue-green strategy, automated |
| Documentation | ✅ Ready | Deployment guides, runbooks |
| **SCORE** | **9.5/10** | **READY FOR PRODUCTION** |
| Docker | ✅ Sẵn sàng | Build multi-stage, tối ưu cho production |
| Database | ✅ Sẵn sàng | 15 migration, seed script, xác minh backup |
| Secrets | ✅ Sẵn sàng | GitHub Actions secrets, không hardcode giá trị |
| Monitoring | ✅ Sẵn sàng | Prometheus, Grafana, Loki, Sentry |
| Health Checks | ✅ Sẵn sàng | Endpoint /health, k8s probe |
| Rollback | ✅ Sẵn sàng | Chiến lược blue-green, tự động |
| Tài liệu | ✅ Sẵn sàng | Hướng dẫn deploy, runbook |
| **ĐIỂM** | **9.5/10** | **SẴN SÀNG CHO PRODUCTION** |
---
## PRE-LAUNCH CHECKLIST
## CHECKLIST TRƯỚC KHI LAUNCH
**Critical (Must Do):**
- [ ] Set production environment variables
- [ ] Configure PostgreSQL backup
- [ ] Enable HTTPS/TLS
- [ ] Set up monitoring (Prometheus/Grafana)
- [ ] Configure error tracking (Sentry)
**Quan trọng (Bắt buộc):**
- [ ] Đặt biến môi trường production
- [ ] Cấu hình backup PostgreSQL
- [ ] Bật HTTPS/TLS
- [ ] Thiết lập monitoring (Prometheus/Grafana)
- [ ] Cấu hình theo dõi lỗi (Sentry)
**Important (Should Do):**
- [ ] Load test with production data
- [ ] Security audit (optional but recommended)
- [ ] UAT with stakeholders
- [ ] Document runbooks
**Quan trọng (Nên làm):**
- [ ] Load test với dữ liệu production
- [ ] Audit bảo mật (tuỳ chọn nhưng khuyến nghị)
- [ ] UAT với stakeholder
- [ ] Tài liệu hoá runbook
**Nice-to-Have:**
- [ ] Set up CDN for media assets
- [ ] Database read replicas
- [ ] Multi-region failover
**Nên có:**
- [ ] Thiết lập CDN cho media
- [ ] Database read replica
- [ ] Failover đa vùng
---
## TECH STACK HIGHLIGHTS
## ĐIỂM NHẤN TECH STACK
**Backend:** NestJS 11 + Prisma 7 + PostgreSQL 16 + PostGIS 3.4
**Frontend:** Next.js 15 + React 18 + Tailwind CSS + Zustand
@@ -197,24 +197,24 @@ Push → Lint (2m) → Typecheck (2m) → Test (4m) → Build (3m) → E2E (8m)
---
## WHAT TO FIX THIS WEEK (P0)
## CẦN FIX TRONG TUẦN NÀY (P0)
1. Document load testing SLAs and thresholds
2. Add payment provider failure mock tests
3. Create database maintenance playbook
1. Tài liệu hoá SLA và ngưỡng load testing
2. Thêm test mock lỗi cho payment provider
3. Tạo playbook bảo trì database
---
## FINAL VERDICT
## KẾT LUẬN CUỐI CÙNG
**APPROVED FOR PRODUCTION**
**PHÊ DUYỆT CHO PRODUCTION**
This is enterprise-quality code with proper architecture, comprehensive testing, and production-grade security. Minor gaps are non-blocking and can be addressed post-launch.
Đây là mã nguồn chất lượng doanh nghiệp với kiến trúc đúng chuẩn, test toàn diện và bảo mật cấp production. Các lỗ hổng nhỏ không cản trở việc launch và có thể giải quyết sau.
**Confidence Level:** 95%
**Risk Level:** LOW
**Mức độ tin cậy:** 95%
**Mức độ rủi ro:** THẤP
**Go/No-Go:** 🟢 **GO**
---
**Report:** April 12, 2026 | **Auditor:** Claude Code | **Time:** Comprehensive (Very Thorough)
**Báo cáo:** 12 tháng 4, 2026 | **Auditor:** Claude Code | **Thời lượng:** Toàn diện (Rất kỹ lưỡng)

View File

@@ -1,52 +1,52 @@
# GoodGo Platform AI - Audit Reports & Analysis
**Complete Code Audit - April 11, 2026**
# GoodGo Platform AI - Báo cáo Audit & Phân tích
**Audit mã nguồn toàn diện - 11 tháng 4, 2026**
This directory contains three comprehensive audit documents analyzing the GoodGo Platform AI codebase:
Thư mục này chứa ba tài liệu audit toàn diện phân tích mã nguồn GoodGo Platform AI:
---
## 📋 AUDIT DOCUMENTS
## 📋 CÁC TÀI LIỆU AUDIT
### 1. **AUDIT_EXECUTIVE_SUMMARY.md** ⭐ START HERE
**Target Audience:** CEO, CTO, Product Managers, Investors
**Length:** ~8 pages (quick read)
**Time to Read:** 15-20 minutes
### 1. **AUDIT_EXECUTIVE_SUMMARY.md** ⭐ BẮT ĐẦU TẠI ĐÂY
**Đối tượng:** CEO, CTO, Product Manager, Nhà đầu tư
**Độ dài:** ~8 trang (đọc nhanh)
**Thời gian đọc:** 15-20 phút
**Contains:**
- Project snapshot (metrics, grades)
- Architecture quality assessment (A-grade)
- Security posture (A-)
- Code quality (A)
- Testing coverage (B+)
- Deployment readiness (B with conditions)
- Risk matrix & Go/No-Go decision
- Prioritized recommendations
**Nội dung:**
- Tóm tắt dự án (số liệu, xếp hạng)
- Đánh giá chất lượng kiến trúc (xếp hạng A)
- Tư thế bảo mật (A-)
- Chất lượng mã (A)
- Độ phủ test (B+)
- Mức độ sẵn sàng deploy (B kèm điều kiện)
- Ma trận rủi ro & quyết định Go/No-Go
- Khuyến nghị theo ưu tiên
**Key Takeaway:**
> **Production-Ready with standard pre-launch validation. Focus on operational readiness (monitoring, runbooks) rather than code quality.**
**Điểm mấu chốt:**
> **Sẵn sàng Production với validation tiền-launch chuẩn. Tập trung vào sẵn sàng vận hành (monitoring, runbook) hơn là chất lượng mã.**
---
### 2. **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** 📊 DETAILED REFERENCE
**Target Audience:** Tech leads, Senior developers, Architects
**Length:** ~50 pages (comprehensive)
**Time to Read:** 1-2 hours (full), 30 min (key sections)
### 2. **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** 📊 THAM CHIẾU CHI TIẾT
**Đối tượng:** Tech lead, Senior developer, Architect
**Độ dài:** ~50 trang (toàn diện)
**Thời gian đọc:** 1-2 giờ (đầy đủ), 30 phút (các phần chính)
**Contains:**
- Complete project structure breakdown
- 16 backend modules detailed analysis
- Frontend architecture & routes
- Database schema (21 models, 13 migrations)
- Docker & infrastructure setup
- CI/CD pipelines explanation
- Code quality standards
- Testing framework details
- Dependencies catalog
- Security implementation details
- Performance & scalability
- Compliance & governance
**Nội dung:**
- Phân tích cấu trúc dự án đầy đủ
- Phân tích chi tiết 16 backend module
- Kiến trúc & route frontend
- Schema database (21 model, 13 migration)
- Thiết lập Docker & hạ tầng
- Giải thích các pipeline CI/CD
- Tiêu chuẩn chất lượng mã
- Chi tiết framework testing
- Danh mục dependencies
- Chi tiết triển khai bảo mật
- Performance & khả năng mở rộng
- Tuân thủ & quản trị
**Structure:**
**Cấu trúc:**
```
1. Project Structure (2 pages)
2. Backend Deep Dive (8 pages)
@@ -66,122 +66,122 @@ This directory contains three comprehensive audit documents analyzing the GoodGo
---
### 3. **AUDIT_TECHNICAL_REFERENCE.md** 🔧 DEVELOPER GUIDE
**Target Audience:** Developers implementing features, DevOps engineers
**Length:** ~30 pages (practical)
**Time to Read:** 30-45 minutes (sections as needed)
### 3. **AUDIT_TECHNICAL_REFERENCE.md** 🔧 HƯỚNG DẪN DEVELOPER
**Đối tượng:** Developer triển khai tính năng, kỹ sư DevOps
**Độ dài:** ~30 trang (thực tiễn)
**Thời gian đọc:** 30-45 phút (các phần khi cần)
**Contains:**
- Backend module hierarchy & dependencies
- Domain model relationships
- Authentication flow (detailed)
- Database schema with indexing strategy
- Security layers (network → data level)
- CQRS pattern implementation
- Caching strategy (multi-level)
- Error handling & observability
- Background jobs & events
- Frontend state management
- Deployment architecture
- CI/CD pipeline stages
- Performance tuning checklist
- Troubleshooting guide
- Security pre-deployment checklist
**Nội dung:**
- Phân cấp module backend & dependency
- Quan hệ giữa các domain model
- Luồng xác thực (chi tiết)
- Schema database với chiến lược index
- Các lớp bảo mật (network → data level)
- Triển khai pattern CQRS
- Chiến lược cache (đa cấp)
- Xử lý lỗi & observability
- Background job & event
- Quản lý state frontend
- Kiến trúc deploy
- Các giai đoạn pipeline CI/CD
- Checklist tinh chỉnh hiệu năng
- Hướng dẫn troubleshoot
- Checklist bảo mật trước deploy
**Usage:** Keep this as reference while developing or debugging
**Cách dùng:** Giữ làm tài liệu tham chiếu khi phát triển hoặc debug
---
## 📊 KEY METRICS AT A GLANCE
## 📊 SỐ LIỆU CHÍNH TRONG NHÁY MẮT
| Metric | Value | Grade |
| Chỉ số | Giá trị | Xếp hạng |
|--------|-------|-------|
| Codebase Size | 70,569 LOC | — |
| TypeScript Files | 992 | A |
| Backend Modules | 16 (all properly layered) | A |
| Frontend Routes | 33 pages + 8 layouts | A |
| Database Models | 21 | B+ |
| Test Files | 289 | B+ |
| Architecture Pattern | Hexagonal DDD | A |
| Code Quality | Strict TS, 0 TODOs, ESLint | A |
| Security | Enterprise-grade | A- |
| Testing | Unit + E2E coverage | B+ |
| DevOps Readiness | Full CI/CD pipeline | B |
| Kích thước mã nguồn | 70.569 LOC | — |
| File TypeScript | 992 | A |
| Module Backend | 16 (đều phân lớp đúng) | A |
| Route Frontend | 33 trang + 8 layout | A |
| Model Database | 21 | B+ |
| File Test | 289 | B+ |
| Pattern kiến trúc | Hexagonal DDD | A |
| Chất lượng mã | TS strict, 0 TODO, ESLint | A |
| Bảo mật | Cấp doanh nghiệp | A- |
| Testing | Phủ Unit + E2E | B+ |
| Sẵn sàng DevOps | Pipeline CI/CD đầy đủ | B |
---
## 🎯 QUICK FINDINGS
## 🎯 PHÁT HIỆN NHANH
### ✅ WHAT'S WORKING WELL
1. **Architecture** - Hexagonal pattern properly applied across all 16 modules
2. **Security** - Multiple layers (Helmet, CSRF, encryption, audit logs)
3. **Code Quality** - Strict TypeScript, ESLint enforced, zero technical debt markers
4. **Testing** - 289 test files covering happy paths
5. **DevOps** - Full CI/CD automation with security scanning
6. **Type Safety** - ~100% TypeScript strict mode compliance
### ✅ NHỮNG ĐIỀU HOẠT ĐỘNG TỐT
1. **Kiến trúc** - Pattern Hexagonal được áp dụng đúng cho cả 16 module
2. **Bảo mật** - Nhiều lớp (Helmet, CSRF, mã hoá, audit log)
3. **Chất lượng mã** - TypeScript strict, ESLint được enforce, không có dấu nợ kỹ thuật
4. **Testing** - 289 file test phủ happy path
5. **DevOps** - Tự động hoá CI/CD đầy đủ với security scan
6. **An toàn kiểu** - ~100% tuân thủ TypeScript strict mode
### ⚠️ AREAS TO WATCH
1. **Database** - 13 migrations in 4 days (schema still stabilizing)
2. **Testing** - 70K LOC with ~0.4% test file ratio (adequate but improvable)
3. **Documentation** - README minimal, operational docs missing
4. **Monitoring** - Stack deployed but alert rules need configuration
5. **Admin Security** - No 2FA implemented
### ⚠️ KHU VỰC CẦN CHÚ Ý
1. **Database** - 13 migration trong 4 ngày (schema còn đang ổn định)
2. **Testing** - 70K LOC với tỉ lệ ~0.4% file test (đủ nhưng có thể cải thiện)
3. **Tài liệu** - README tối thiểu, thiếu tài liệu vận hành
4. **Monitoring** - Đã deploy stack nhưng cần cấu hình alert rule
5. **Bảo mật Admin** - Chưa có 2FA
### 🚀 READY FOR PRODUCTION?
**Status:** **YES, with conditions**
- ✅ Code quality excellent
-Security controls in place
- ⚠️ Need: Load testing, schema lockdown, pentest
- ⚠️ Need: Runbooks, alert thresholds, incident procedures
### 🚀 SẴN SÀNG CHO PRODUCTION?
**Trạng thái:** **CÓ, kèm điều kiện**
- ✅ Chất lượng mã xuất sắc
-Đã có các kiểm soát bảo mật
- ⚠️ Cần: Load test, khoá schema, pentest
- ⚠️ Cần: Runbook, ngưỡng alert, quy trình ứng phó sự cố
---
## 📑 HOW TO USE THESE DOCUMENTS
## 📑 CÁCH SỬ DỤNG CÁC TÀI LIỆU NÀY
### For Non-Technical Leadership
1. Read: **AUDIT_EXECUTIVE_SUMMARY.md** (section "GO/NO-GO DECISION")
2. Focus: Architecture grade, security posture, deployment readiness
3. Time: 10 minutes
### Dành cho Lãnh đạo phi kỹ thuật
1. Đọc: **AUDIT_EXECUTIVE_SUMMARY.md** (phần "GO/NO-GO DECISION")
2. Tập trung: Xếp hạng kiến trúc, tư thế bảo mật, mức độ sẵn sàng deploy
3. Thời gian: 10 phút
### For Technical Decision Makers (CTO, Tech Leads)
1. Read: **AUDIT_EXECUTIVE_SUMMARY.md** (entire)
2. Reference: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (sections 2-5)
3. Time: 1 hour
### Dành cho Người ra quyết định kỹ thuật (CTO, Tech Lead)
1. Đọc: toàn bộ **AUDIT_EXECUTIVE_SUMMARY.md**
2. Tham khảo: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (phần 2-5)
3. Thời gian: 1 giờ
### For Implementing Developers
1. Bookmark: **AUDIT_TECHNICAL_REFERENCE.md**
2. Read: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (section 2-3)
3. Use as: Daily reference for patterns & architecture
### Dành cho Developer triển khai
1. Đánh dấu: **AUDIT_TECHNICAL_REFERENCE.md**
2. Đọc: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (phần 2-3)
3. Sử dụng làm: Tham chiếu hàng ngày cho pattern & kiến trúc
### For DevOps/SRE
1. Focus: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (section 5)
2. Reference: **AUDIT_TECHNICAL_REFERENCE.md** (deployment architecture, troubleshooting)
3. Checklist: Security pre-deployment checklist in Technical Reference
### Dành cho DevOps/SRE
1. Tập trung: **COMPREHENSIVE_AUDIT_REPORT_2026-04-11.md** (phần 5)
2. Tham khảo: **AUDIT_TECHNICAL_REFERENCE.md** (kiến trúc deploy, troubleshoot)
3. Checklist: Checklist bảo mật trước deploy trong Technical Reference
---
## 🔐 SECURITY HIGHLIGHTS
## 🔐 ĐIỂM NHẤN BẢO MẬT
**Implemented Controls:**
- ✓ Helmet security headers (CSP, HSTS, X-Frame-Options)
- ✓ CSRF protection (double-submit cookie pattern)
- ✓ Rate limiting (global 60 req/min, auth 10 req/min)
-Input sanitization (XSS prevention)
-PII encryption (field-level AES-256-GCM)
-Hash fields (email/phone searchable yet hashed)
- ✓ Audit logging (AdminAuditLog model)
-JWT token rotation (refresh token families)
-bcrypt password hashing (6 rounds)
- ✓ GDPR soft deletes (User.deletedAt)
**Các kiểm soát đã triển khai:**
- ✓ Helmet security header (CSP, HSTS, X-Frame-Options)
- ✓ CSRF protection (pattern double-submit cookie)
- ✓ Rate limiting (global 60 req/phút, auth 10 req/phút)
-Sanitize đầu vào (chống XSS)
-Mã hoá PII (field-level AES-256-GCM)
-Trường hash (email/phone vẫn search được nhưng đã hash)
- ✓ Audit logging (model AdminAuditLog)
-Xoay vòng JWT token (refresh token family)
-Hash mật khẩu bcrypt (6 rounds)
- ✓ GDPR soft delete (User.deletedAt)
**Missing (Nice-to-Have):**
- 2FA for admin accounts
- Penetration test report
- Incident response runbooks
**Còn thiếu (Nên có):**
- 2FA cho tài khoản admin
- Báo cáo penetration test
- Runbook ứng phó sự cố
---
## 📈 ARCHITECTURE RATING BREAKDOWN
## 📈 PHÂN TÍCH XẾP HẠNG KIẾN TRÚC
```
Code Architecture ████████████████████ A
@@ -195,73 +195,72 @@ Operational Readiness ████████░░░░░░░░░░░
---
## 🎬 NEXT STEPS
## 🎬 CÁC BƯỚC TIẾP THEO
### Immediate (This Week)
- [ ] Review Executive Summary with leadership
- [ ] Lock database schema (freeze migrations)
- [ ] Schedule security penetration test
- [ ] Configure monitoring alert thresholds
### Ngay lập tức (Tuần này)
- [ ] Rà soát Executive Summary với lãnh đạo
- [ ] Khoá schema database (đóng băng migration)
- [ ] Lên lịch penetration test bảo mật
- [ ] Cấu hình ngưỡng alert monitoring
### Short-Term (Week 2-3)
- [ ] Run comprehensive load testing (1M+ req/day simulation)
- [ ] Create incident response runbooks
- [ ] Implement admin 2FA
- [ ] Expand E2E test coverage
### Ngắn hạn (Tuần 2-3)
- [ ] Chạy load testing toàn diện (mô phỏng 1M+ req/ngày)
- [ ] Tạo runbook ứng phó sự cố
- [ ] Triển khai 2FA cho admin
- [ ] Mở rộng độ phủ E2E test
### Medium-Term (Month 2)
- [ ] Add mutation testing to CI/CD
- [ ] Implement GDPR data export feature
- [ ] Document scaling architecture
- [ ] Performance optimization pass
### Trung hạn (Tháng 2)
- [ ] Thêm mutation testing o CI/CD
- [ ] Triển khai tính năng GDPR data export
- [ ] Tài liệu hoá kiến trúc scale
- [ ] Đợt tối ưu hoá performance
---
## 📞 QUESTIONS?
## 📞 CÂU HỎI?
**About the audit process:**
- See "CODEBASE_ANALYSIS.md" for discovery notes
- See "CHANGELOG.md" for recent git commits
- See "CLAUDE.md" for AI integration guidelines
**Về quy trình audit:**
- Xem "CODEBASE_ANALYSIS.md" để xem ghi chú khám phá
- Xem "CHANGELOG.md" để xem các commit gần đây
- Xem "CLAUDE.md" để xem hướng dẫn tích hợp AI
**About specific modules:**
- Backend: Check apps/api/src/modules/[module-name]/
- Frontend: Check apps/web/app/[locale]/
**Về module cụ thể:**
- Backend: Xem apps/api/src/modules/[module-name]/
- Frontend: Xem apps/web/app/[locale]/
**About deployment:**
- Docker: See docker-compose.yml files
- CI/CD: See .github/workflows/ files
- Kubernetes: See deployment architecture in Technical Reference
**Về deployment:**
- Docker: Xem các file docker-compose.yml
- CI/CD: Xem các file .github/workflows/
- Kubernetes: Xem kiến trúc deploy trong Technical Reference
---
## 📄 DOCUMENT VERSIONS
## 📄 PHIÊN BẢN TÀI LIỆU
| Document | Version | Last Updated | Pages |
| Tài liệu | Phiên bản | Cập nhật cuối | Trang |
|----------|---------|--------------|-------|
| Executive Summary | 1.0 | Apr 11, 2026 | 8 |
| Comprehensive Report | 1.0 | Apr 11, 2026 | 50 |
| Technical Reference | 1.0 | Apr 11, 2026 | 30 |
| Executive Summary | 1.0 | 11/4/2026 | 8 |
| Comprehensive Report | 1.0 | 11/4/2026 | 50 |
| Technical Reference | 1.0 | 11/4/2026 | 30 |
---
## ✨ CONCLUSION
## ✨ KẾT LUẬN
The GoodGo Platform AI demonstrates **mature software engineering practices**:
- Clean, maintainable architecture
- Enterprise-grade security controls
- Comprehensive automated testing
- Modern technology stack
- Production-ready DevOps pipeline
GoodGo Platform AI thể hiện **các thực hành kỹ thuật phần mềm trưởng thành**:
- Kiến trúc sạch, dễ bảo trì
- Kiểm soát bảo mật cấp doanh nghiệp
- Test tự động toàn diện
- Tech stack hiện đại
- Pipeline DevOps sẵn sàng production
**Recommendation:** **APPROVED FOR PRODUCTION** with standard pre-launch security & performance validation.
**Khuyến nghị:** **PHÊ DUYỆT CHO PRODUCTION** với validation bảo mật & hiệu năng tiền-launch tiêu chuẩn.
The team is well-equipped to maintain, scale, and extend this platform.
Đội ngũ đã sẵn sàng để bảo trì, mở rộng và phát triển nền tảng này.
---
**Audit Conducted By:** Claude Code
**Audit Date:** April 11, 2026
**Codebase Location:** `/Users/velikho/Desktop/WORKING/goodgo-platform-ai/`
**Confidence Level:** High (full codebase reviewed)
**Audit thực hiện bởi:** Claude Code
**Ngày Audit:** 11 tháng 4, 2026
**Vị trí mã nguồn:** `/Users/velikho/Desktop/WORKING/goodgo-platform-ai/`
**Mức độ tin cậy:** Cao (đã rà soát toàn bộ mã nguồn)

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
# GoodGo Platform Web - Audit Summary
# GoodGo Platform Web - Tóm tắt Audit
## 📊 Overall Grade: A+ (Production-Ready)
## 📊 Xếp hạng tổng thể: A+ (Sẵn sàng Production)
```
┌─────────────────────────────────────────┐
@@ -18,45 +18,45 @@
---
## ✅ QUICK AUDIT RESULTS
## ✅ KẾT QUẢ AUDIT NHANH
| Category | Result | Score |
| Hạng mục | Kết quả | Điểm |
|----------|--------|-------|
| **Pages Implemented** | 24/24 ✅ | 100% |
| **Components** | 45+ fully typed | 100% |
| **Technical Debt** | 0 items | 100% |
| **Test Coverage** | 25 test suites | 75% |
| **Type Safety** | Full TypeScript | 100% |
| **Security Headers** | 8 headers set | 90% |
| **Accessibility** | WCAG compliant | 80% |
| **Mobile Responsive** | All breakpoints | 100% |
| **Trang đã triển khai** | 24/24 ✅ | 100% |
| **Components** | 45+ đánh kiểu đầy đủ | 100% |
| **Nợ kỹ thuật** | 0 mục | 100% |
| **Độ phủ test** | 25 test suite | 75% |
| **An toàn kiểu** | TypeScript đầy đủ | 100% |
| **Header bảo mật** | 8 header được set | 90% |
| **Khả năng truy cập** | Tuân thủ WCAG | 80% |
| **Mobile Responsive** | Tất cả breakpoint | 100% |
---
## 🎯 KEY FINDINGS
## 🎯 PHÁT HIỆN CHÍNH
### ✨ Strengths
-**Zero TODO/FIXME comments** - Codebase is production-clean
-**24 fully implemented pages** - All blueprint features complete
-**Multi-language support** - Vietnamese & English
-**OAuth integration** - Google & Zalo authentication
-**Modern tech stack** - Next.js 15, React 18, TypeScript 6
-**API abstraction** - 10 specialized API clients
-**State management** - 2 Zustand stores with persistence
-**Comprehensive testing** - 25 test suites
-**Error tracking** - Sentry integration
-**Security hardened** - CSP, CSRF, secure headers
### ✨ Điểm mạnh
-**Không còn TODO/FIXME** - Mã nguồn sạch sẽ ở mức production
-**24 trang triển khai đầy đủ** - Hoàn tất tính năng theo blueprint
-**Hỗ trợ đa ngôn ngữ** - Tiếng Việt & tiếng Anh
-**Tích hợp OAuth** - Đăng nhập Google & Zalo
-**Tech stack hiện đại** - Next.js 15, React 18, TypeScript 6
-**Trừu tượng API** - 10 API client chuyên biệt
-**Quản lý state** - 2 store Zustand persistence
-**Test toàn diện** - 25 test suite
-**Theo dõi lỗi** - Tích hợp Sentry
-**Bảo mật chắc chắn** - CSP, CSRF, secure header
### ⚠️ Minor Improvements
1. **Image Optimization** - Use responsive images with sizes attribute
2. **CSP Strictness** - Enable strict CSP in production
3. **Date Handling** - Consider adding date-fns for consistency
4. **API Retry Logic** - Add retry configuration for network errors
5. **Logging Strategy** - Add structured logging for debugging
### ⚠️ Cải thiện nhỏ
1. **Tối ưu hình ảnh** - Dùng responsive image với thuộc tính sizes
2. **Tăng độ chặt CSP** - Bật CSP nghiêm ngặt cho production
3. **Xử lý ngày tháng** - Cân nhắc thêm date-fns để nhất quán
4. **API Retry Logic** - Thêm cấu hình retry cho lỗi mạng
5. **Chiến lược logging** - Thêm structured logging cho debug
---
## 📁 PROJECT STRUCTURE
## 📁 CẤU TRÚC DỰ ÁN
```
156 TypeScript/TSX Files
@@ -76,9 +76,9 @@ TOTAL: ~12,000 lines of well-organized code
---
## 🏗️ ARCHITECTURE
## 🏗️ KIẾN TRÚC
### Route Structure
### Cấu trúc Route
```
Public Routes (5)
├── / (Landing)
@@ -115,7 +115,7 @@ Admin (4)
└── /admin/moderation
```
### State Management Architecture
### Kiến trúc quản lý State
```
Zustand Stores (2)
├── Auth Store
@@ -138,113 +138,113 @@ Context Providers (3)
---
## 🔐 SECURITY OVERVIEW
## 🔐 TỔNG QUAN BẢO MẬT
**Headers Set:** 8 security headers
**Header được set:** 8 header bảo mật
- ✅ X-Content-Type-Options: nosniff
- ✅ X-Frame-Options: DENY
- ✅ X-XSS-Protection: 1; mode=block
- ✅ Referrer-Policy: strict-origin-when-cross-origin
- ✅ Strict-Transport-Security: 1 year + preload
- ✅ Permissions-Policy: Camera/Mic disabled, Geo/Payment self-only
- ✅ Content-Security-Policy: Multi-directive policy
-API calls use credentials: 'include' + CSRF tokens
- ✅ Strict-Transport-Security: 1 năm + preload
- ✅ Permissions-Policy: Tắt Camera/Mic, Geo/Payment chỉ cho self
- ✅ Content-Security-Policy: Policy đa directive
-Các call API dùng credentials: 'include' + CSRF token
**Authentication:**
- ✅ Cookie-based sessions (goodgo_authenticated)
- ✅ OAuth with Google & Zalo
-Automatic token refresh on 401
-Middleware route protection
**Xác thực:**
- ✅ Cookie-based session (goodgo_authenticated)
- ✅ OAuth với Google & Zalo
-Tự động refresh token khi gặp 401
-Bảo vệ route bằng middleware
**Issues:** None critical. Minor CSP relaxation for development (can be tightened in production).
**Vấn đề:** Không có vấn đề nghiêm trọng. Có thả lỏng CSP nhỏ cho dev (có thể siết chặt ở production).
---
## 🎨 UI/UX QUALITY
## 🎨 CHẤT LƯỢNG UI/UX
### Accessibility (WCAG)
-Semantic HTML structure
- ✅ ARIA labels on interactive elements
-Focus management & keyboard navigation
-Skip to main content link
- ✅ Proper heading hierarchy
-Color contrast compliance
### Khả năng truy cập (WCAG)
-Cấu trúc HTML semantic
- ✅ ARIA label trên các phần tử tương tác
-Quản lý focus & điều hướng bàn phím
-Link skip to main content
- ✅ Phân cấp heading đúng
-Tuân thủ tương phản màu
### Responsive Design
- ✅ Mobile-first approach
-All Tailwind breakpoints used (sm, md, lg, xl, 2xl)
-Tested on 320px - 2560px widths
- ✅ Grid & Flexbox layouts
- ✅ Aspect ratios for media
-Dùng đầy đủ breakpoint Tailwind (sm, md, lg, xl, 2xl)
-Đã test trên 320px - 2560px
- Layout Grid & Flexbox
- ✅ Aspect ratio cho media
### Dark Mode
-System preference detection
-Manual toggle
- ✅ LocalStorage persistence
-Smooth transitions
-Phát hiện system preference
-Toggle thủ công
- ✅ Lưu trong LocalStorage
-Chuyển đổi mượt mà
---
## 📊 PERFORMANCE METRICS
## 📊 CHỈ SỐ HIỆU NĂNG
### Optimizations in Place
- ✅ Dynamic imports for heavy components
-Image optimization configuration
- ✅ Code splitting strategy
- ✅ Web Vitals tracking (CLS, LCP, FID)
-Sentry performance monitoring
- ✅ React Query caching
### Tối ưu đã có
- ✅ Dynamic import cho component nặng
-Cấu hình tối ưu hình ảnh
- ✅ Chiến lược code splitting
- Theo dõi Web Vitals (CLS, LCP, FID)
-Theo dõi performance Sentry
- Cache React Query
### Identified Improvements
1. Use responsive images with `sizes` attribute
2. Implement retry logic in React Query
3. Add structured logging for debugging
4. Consider date-fns for date formatting
### Cải thiện được xác định
1. Dùng responsive image với thuộc tính `sizes`
2. Triển khai retry logic trong React Query
3. Thêm structured logging cho debug
4. Cân nhắc date-fns cho định dạng ngày tháng
---
## 🧪 TESTING COVERAGE
## 🧪 ĐỘ PHỦ TEST
**25 Test Suites Across:**
- 9 UI component tests (Button, Card, Input, etc.)
- 7 Library tests (Stores, Validations, Utils)
- 9 Page tests (Landing, Search, Dashboard, Admin)
**25 Test Suite trên:**
- 9 test UI component (Button, Card, Input, v.v.)
- 7 test thư viện (Stores, Validations, Utils)
- 9 test trang (Landing, Search, Dashboard, Admin)
**Testing Stack:**
**Bộ công cụ Test:**
- Vitest 4.1.3
- Testing Library (React)
- MSW (Mock Service Worker)
- jsdom (Virtual DOM)
**Coverage Areas:**
-Component rendering
-User interactions
-Store state management
-Form validation
-API mocking
**Khu vực được phủ:**
-Render component
-Tương tác người dùng
-Quản lý state store
-Validation form
-Mock API
---
## 🚀 DEPLOYMENT READINESS
## 🚀 SẴN SÀNG TRIỂN KHAI
### Pre-Deployment Checklist
- [ ] `npm run typecheck` - verify no TS errors
- [ ] `npm run lint` - check code style
- [ ] `npm test` - verify all tests pass
- [ ] `npm run build` - verify production build
- [ ] Set environment variables
- [ ] Configure Sentry
- [ ] Verify API endpoints
- [ ] Test OAuth providers
### Checklist trước deploy
- [ ] `npm run typecheck` - kiểm tra không có lỗi TS
- [ ] `npm run lint` - kiểm tra code style
- [ ] `npm test` - đảm bảo tất cả test pass
- [ ] `npm run build` - kiểm tra build production
- [ ] Đặt biến môi trường
- [ ] Cấu hình Sentry
- [ ] Xác minh các endpoint API
- [ ] Test các provider OAuth
### Build Configuration
### Cấu hình Build
- ✅ Next.js standalone output
-Sentry integration enabled
-next-intl configured
- ✅ Dockerfile provided
-Security headers configured
-Đã bật tích hợp Sentry
-Đã cấu hình next-intl
- Đã cung cấp Dockerfile
-Đã cấu hình security header
### Environment Variables
### Biến môi trường
```bash
NEXT_PUBLIC_API_URL=
NEXT_PUBLIC_SITE_URL=
@@ -259,43 +259,43 @@ NEXT_PUBLIC_ZALO_APP_ID=
## 📦 DEPENDENCIES
### Production (17 packages)
- Next.js 15.5.14 ✅ Latest
- React 18.3.0 ✅ Latest
- TypeScript 6.0.2 ✅ Latest
- Zustand 5.0.12 ✅ Latest
- React Query 5.96.2 ✅ Latest
- Tailwind CSS 3.4.0 ✅ Latest
- Zod 4.3.6 ✅ Latest
- Mapbox GL 3.21.0 ✅ Latest
- Recharts 3.8.1 ✅ Latest
- Sentry 10.47.0 ✅ Latest
- next-intl 4.9.0 ✅ Latest
- React Hook Form 7.72.1 ✅ Latest
### Production (17 package)
- Next.js 15.5.14 ✅ Mới nhất
- React 18.3.0 ✅ Mới nhất
- TypeScript 6.0.2 ✅ Mới nhất
- Zustand 5.0.12 ✅ Mới nhất
- React Query 5.96.2 ✅ Mới nhất
- Tailwind CSS 3.4.0 ✅ Mới nhất
- Zod 4.3.6 ✅ Mới nhất
- Mapbox GL 3.21.0 ✅ Mới nhất
- Recharts 3.8.1 ✅ Mới nhất
- Sentry 10.47.0 ✅ Mới nhất
- next-intl 4.9.0 ✅ Mới nhất
- React Hook Form 7.72.1 ✅ Mới nhất
### No Security Vulnerabilities
-All packages scanned and approved
-Regular update maintenance
- ✅ Sentry for runtime monitoring
### Không có lỗ hổng bảo mật
-Tất cả package đã được quét và phê duyệt
-Bảo trì cập nhật định kỳ
- ✅ Sentry để theo dõi runtime
---
## 🌍 INTERNATIONALIZATION
## 🌍 ĐA NGÔN NGỮ
**Locales Supported:**
- 🇻🇳 Vietnamese (vi) - Default
- 🇬🇧 English (en)
**Locale được hỗ trợ:**
- 🇻🇳 Tiếng Việt (vi) - Mặc định
- 🇬🇧 Tiếng Anh (en)
**Implementation:**
**Triển khai:**
- next-intl v4.9.0
- Route-based locale handling
- 10,154 bytes Vietnamese translations
- 8,698 bytes English translations
- Complete coverage of UI labels, errors, validation messages
- Xử lý locale theo route
- 10.154 byte bản dịch tiếng Việt
- 8.698 byte bản dịch tiếng Anh
- Phủ đầy đủ nhãn UI, lỗi, thông báo validation
---
## 📈 CODE METRICS SUMMARY
## 📈 TÓM TẮT CHỈ SỐ MÃ NGUỒN
```
Code Organization ████████████ Excellent
@@ -310,55 +310,55 @@ Accessibility ██████████░░ Good
---
## 🎓 RECOMMENDATIONS
## 🎓 KHUYẾN NGHỊ
### Immediate (Before Production)
1.Verify OAuth provider credentials are configured
2.Set up Sentry account for error tracking
3. ✅ Configure API_URL environment variable
4.Enable strict CSP headers for production
5. ✅ Test authentication flow end-to-end
### Ngay lập tức (Trước Production)
1.Xác minh credential OAuth provider đã được cấu hình
2.Thiết lập tài khoản Sentry để theo dõi lỗi
3. ✅ Cấu hình biến môi trường API_URL
4.Bật CSP header nghiêm ngặt cho production
5. ✅ Test luồng xác thực end-to-end
### Short Term (After Launch)
1. Monitor Core Web Vitals using Sentry
2. Gather user feedback on UI/UX
3. Review error logs weekly
4. Optimize images with responsive sizes
5. Consider implementing notifications
### Ngắn hạn (Sau khi launch)
1. Theo dõi Core Web Vitals qua Sentry
2. Thu thập phản hồi người dùng về UI/UX
3. Rà soát log lỗi hàng tuần
4. Tối ưu hình ảnh với responsive size
5. Cân nhắc triển khai notification
### Long Term (Future Enhancements)
1. Add structured logging (Pino/Winston)
2. Implement messaging system UI
3. Create notifications center
4. Build mobile app (React Native)
5. Add more admin tools
### Dài hạn (Cải tiến tương lai)
1. Thêm structured logging (Pino/Winston)
2. Triển khai UI hệ thống tin nhắn
3. Tạo trung tâm thông báo
4. Xây mobile app (React Native)
5. Thêm công cụ admin
---
## ✨ FINAL VERDICT
## ✨ KẾT LUẬN CUỐI CÙNG
### Status: ✅ PRODUCTION-READY
### Trạng thái: ✅ SẴN SÀNG PRODUCTION
**The GoodGo Platform Web frontend is:**
- 🎯 **Feature-Complete** - All 24 pages implemented
- 🏗️ **Well-Architected** - Clean separation of concerns
- 🔐 **Secure** - Industry-standard security practices
-**Accessible** - WCAG 2.1 AA compliant
-**Performant** - Optimized with modern techniques
- 🌍 **Global** - Multi-language support
- 🧪 **Tested** - 25 test suites
- 📊 **Monitored** - Sentry integration ready
- 🚀 **Deployable** - Docker & build configs included
**Frontend GoodGo Platform Web :**
- 🎯 **Đầy đủ tính năng** - Đã triển khai cả 24 trang
- 🏗️ **Kiến trúc tốt** - Phân tách trách nhiệm rõ ràng
- 🔐 **Bảo mật** - Chuẩn bảo mật ngành
-**Truy cập được** - Tuân thủ WCAG 2.1 AA
-**Hiệu năng cao** - Tối ưu bằng kỹ thuật hiện đại
- 🌍 **Toàn cầu** - Hỗ trợ đa ngôn ngữ
- 🧪 **Đã test** - 25 test suite
- 📊 **Được giám sát** - Sẵn sàng tích hợp Sentry
- 🚀 **Deploy được** - Có sẵn cấu hình Docker & build
### Confidence Level: **VERY HIGH**
### Mức độ tin cậy: **RẤT CAO**
All code is production-ready with zero critical issues. Minor recommendations are optional quality improvements.
Toàn bộ mã nguồn đã sẵn sàng production với 0 vấn đề nghiêm trọng. Các khuyến nghị nhỏ chỉ là cải thiện chất lượng tuỳ chọn.
**Estimated Time to First Deploy:** 1-2 hours (after environment setup)
**Thời gian dự kiến tới lần deploy đầu:** 1-2 giờ (sau khi setup môi trường)
---
**Audit Completed:** April 11, 2026
**Total Audit Time:** Comprehensive 2+ hour analysis
**Files Reviewed:** 156 TypeScript/TSX files
**Issues Found:** 0 Critical, 5 Minor (optional)
**Audit hoàn tất:** 11 tháng 4, 2026
**Tổng thời gian Audit:** Phân tích toàn diện 2+ giờ
**Số file rà soát:** 156 file TypeScript/TSX
**Vấn đề phát hiện:** 0 nghiêm trọng, 5 nhỏ (tuỳ chọn)

View File

@@ -1,96 +1,96 @@
# Deployment Guide
# Hướng Dẫn Deployment
## Overview
## Tổng Quan
GoodGo Platform AI consists of four deployable services:
GoodGo Platform AI gồm bốn dịch vụ có thể deploy:
| Service | Technology | Default Port |
| Dịch vụ | Công nghệ | Port mặc định |
|---------|-----------|-------------|
| **API** | NestJS (Node.js) | 3001 |
| **Web** | Next.js | 3000 |
| **AI Services** | FastAPI (Python) | 8000 |
| **Infrastructure** | Docker Compose | Various |
| **Infrastructure** | Docker Compose | Khác nhau |
## Prerequisites
## Yêu Cầu Trước
- Docker Engine 24+ & Docker Compose v2
- Node.js 22 LTS
- pnpm 10.27+
- Python 3.12 (for AI services, if running outside Docker)
- Python 3.12 (cho AI services, nếu chạy ngoài Docker)
## Environment Configuration
## Cấu Hình Môi Trường
Copy `.env.example` to `.env` and configure all required values:
Sao chép `.env.example` thành `.env` và cấu hình tất cả giá trị bắt buộc:
```bash
cp .env.example .env
```
### Required Variables
### Biến Bắt Buộc
| Variable | Description | Example |
| Biến | Mô tả | Ví dụ |
|----------|-------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | `postgresql://user:pass@host:5432/goodgo` |
| `JWT_SECRET` | JWT signing key (min 32 chars) | Generate with `openssl rand -hex 32` |
| `JWT_REFRESH_SECRET` | Refresh token signing key | Generate with `openssl rand -hex 32` |
| `REDIS_URL` | Redis connection string | `redis://localhost:6379` |
| `TYPESENSE_API_KEY` | Typesense admin API key | Generate a secure random key |
| `DATABASE_URL` | Chuỗi kết nối PostgreSQL | `postgresql://user:pass@host:5432/goodgo` |
| `JWT_SECRET` | Khóa ký JWT (tối thiểu 32 ký tự) | Tạo bằng `openssl rand -hex 32` |
| `JWT_REFRESH_SECRET` | Khóa ký refresh token | Tạo bằng `openssl rand -hex 32` |
| `REDIS_URL` | Chuỗi kết nối Redis | `redis://localhost:6379` |
| `TYPESENSE_API_KEY` | API key admin Typesense | Tạo một khóa ngẫu nhiên an toàn |
### Optional Variables
### Biến Tùy Chọn
| Variable | Description | Default |
| Biến | Mô tả | Mặc định |
|----------|-------------|---------|
| `API_PORT` | API server port | `3000` |
| `WEB_PORT` | Web app port | `3001` |
| `NODE_ENV` | Environment mode | `development` |
| `CORS_ORIGINS` | Allowed CORS origins | — |
| `CLAUDE_API_KEY` | Claude API key (for content moderation) | — |
| `NEXT_PUBLIC_MAPBOX_TOKEN` | Mapbox token (for maps) | — |
| `VNPAY_*`, `MOMO_*`, `ZALOPAY_*` | Payment gateway credentials | — |
| `API_PORT` | Port API server | `3000` |
| `WEB_PORT` | Port web app | `3001` |
| `NODE_ENV` | Chế độ môi trường | `development` |
| `CORS_ORIGINS` | Các origin CORS được phép | — |
| `CLAUDE_API_KEY` | Claude API key (cho content moderation) | — |
| `NEXT_PUBLIC_MAPBOX_TOKEN` | Token Mapbox (cho bản đồ) | — |
| `VNPAY_*`, `MOMO_*`, `ZALOPAY_*` | Thông tin payment gateway | — |
## Infrastructure Setup (Docker Compose)
## Cài Đặt Hạ Tầng (Docker Compose)
Start all infrastructure services:
Khởi động tất cả dịch vụ hạ tầng:
```bash
docker compose up -d
```
This starts:
Lệnh này khởi động:
- **PostgreSQL 16 + PostGIS 3.4** (port 5432)
- **Redis 7** (port 6379)
- **Typesense 27** (port 8108)
- **MinIO** (API: 9000, Console: 9001)
- **AI Services** (port 8000)
- **pg-backup** — automated daily PostgreSQL backups at 02:00 UTC with verification at 04:00 UTC
- **Loki** (port 3100) — log aggregation
- **Promtail** — log collection agent (ships container logs to Loki)
- **pg-backup** — backup PostgreSQL hằng ngày tự động lúc 02:00 UTC, có verify lúc 04:00 UTC
- **Loki** (port 3100) — tổng hợp log
- **Promtail** — agent thu thập log (chuyển log container đến Loki)
- **Prometheus** (port 9090)
- **Grafana** (port 3002) — dashboards for metrics and logs
- **Grafana** (port 3002) — dashboard cho metric log
Verify all services are healthy:
Kiểm tra tất cả dịch vụ đang khỏe mạnh:
```bash
docker compose ps
```
All services include health checks. Wait until all show `healthy` status.
Tất cả dịch vụ đều có health check. Đợi đến khi tất cả hiển thị trạng thái `healthy`.
## Database Setup
## Cài Đặt Database
```bash
# Generate Prisma client
# Sinh Prisma client
pnpm db:generate
# Apply migrations
# Áp dụng migration
pnpm db:migrate:deploy
# Seed initial data (optional)
# Seed dữ liệu khởi tạo (tùy chọn)
pnpm db:seed
```
## Building for Production
## Build cho Production
### API (NestJS)
@@ -101,7 +101,7 @@ pnpm build
Output: `apps/api/dist/`
Run in production:
Chạy trong production:
```bash
NODE_ENV=production PORT=3001 node apps/api/dist/main.js
@@ -116,7 +116,7 @@ pnpm build
Output: `apps/web/.next/`
Run in production:
Chạy trong production:
```bash
NODE_ENV=production pnpm --filter web start
@@ -124,7 +124,7 @@ NODE_ENV=production pnpm --filter web start
### AI Services (FastAPI)
The AI service runs in Docker via `docker compose`. To build separately:
AI service chạy trong Docker qua `docker compose`. Để build riêng:
```bash
cd libs/ai-services
@@ -132,64 +132,64 @@ docker build -t goodgo-ai-services .
docker run -p 8000:8000 --env-file ../../.env goodgo-ai-services
```
## Production Checklist
## Checklist Production
### Security
### Bảo Mật
- [ ] Set strong, unique `JWT_SECRET` and `JWT_REFRESH_SECRET` (min 32 characters)
- [ ] Set `NODE_ENV=production`
- [ ] Configure `CORS_ORIGINS` to only allow your domain(s)
- [ ] Change default database passwords
- [ ] Change default MinIO credentials (`MINIO_USER`, `MINIO_PASSWORD`)
- [ ] Change default Grafana credentials (`GRAFANA_ADMIN_USER`, `GRAFANA_ADMIN_PASSWORD`)
- [ ] Use a strong, unique `TYPESENSE_API_KEY`
- [ ] Enable SSL/TLS termination (reverse proxy)
- [ ] Set `MINIO_USE_SSL=true` if MinIO is exposed publicly
- [ ] Đặt `JWT_SECRET` `JWT_REFRESH_SECRET` mạnh, độc nhất (tối thiểu 32 ký tự)
- [ ] Đặt `NODE_ENV=production`
- [ ] Cấu hình `CORS_ORIGINS` chỉ cho phép domain của bạn
- [ ] Đổi mật khẩu database mặc định
- [ ] Đổi credential MinIO mặc định (`MINIO_USER`, `MINIO_PASSWORD`)
- [ ] Đổi credential Grafana mặc định (`GRAFANA_ADMIN_USER`, `GRAFANA_ADMIN_PASSWORD`)
- [ ] Dùng `TYPESENSE_API_KEY` mạnh, độc nhất
- [ ] Bật SSL/TLS termination (reverse proxy)
- [ ] Đặt `MINIO_USE_SSL=true` nếu MinIO được public
### Database
- [ ] Run `pnpm db:migrate:deploy` (not `db:migrate:dev`)
- [ ] Enable PostgreSQL connection pooling (PgBouncer recommended)
- [ ] Configure automated backups
- [ ] Set appropriate `max_connections` in PostgreSQL config
- [ ] Chạy `pnpm db:migrate:deploy` (không dùng `db:migrate:dev`)
- [ ] Bật connection pooling cho PostgreSQL (khuyến nghị PgBouncer)
- [ ] Cấu hình backup tự động
- [ ] Đặt `max_connections` phù hợp trong cấu hình PostgreSQL
### Monitoring
- [ ] Verify Prometheus is scraping `/metrics` endpoint
- [ ] Import Grafana dashboards from `monitoring/grafana/dashboards/`
- [ ] Set up alerting rules for error rates and latency
- [ ] Xác nhận Prometheus đang scrape endpoint `/metrics`
- [ ] Import dashboard Grafana từ `monitoring/grafana/dashboards/`
- [ ] Cài đặt rule alerting cho error rate latency
### Performance
- [ ] Configure Redis `maxmemory` and eviction policy
- [ ] Set appropriate Typesense `--memory-limit`
- [ ] Enable gzip/brotli compression in reverse proxy
- [ ] Configure CDN for static assets (Next.js `/_next/static/`)
- [ ] Cấu hình Redis `maxmemory` và chính sách eviction
- [ ] Đặt `--memory-limit` phù hợp cho Typesense
- [ ] Bật nén gzip/brotli reverse proxy
- [ ] Cấu hình CDN cho static asset (Next.js `/_next/static/`)
## Health Checks
## Health Check
| Service | Endpoint | Expected Response |
| Dịch vụ | Endpoint | Phản hồi mong đợi |
|---------|----------|-------------------|
| API | `GET /health` | `{"status": "ok"}` |
| API (Swagger) | `GET /api/v1/docs` | Swagger UI page |
| API (Metrics) | `GET /api/v1/metrics` | Prometheus metrics |
| API (Swagger) | `GET /api/v1/docs` | Trang Swagger UI |
| API (Metrics) | `GET /api/v1/metrics` | Metric Prometheus |
| AI Services | `GET /health` | `{"status": "ok"}` |
| Typesense | `GET /health` | `{"ok": true}` |
| Loki | `GET /ready` | 200 OK |
| Redis | `redis-cli ping` | `PONG` |
| PostgreSQL | `pg_isready -h host -p 5432` | Exit code 0 |
## Scaling Considerations
## Cân Nhắc Về Scaling
### Horizontal Scaling
- **API**: Stateless — scale with multiple instances behind a load balancer
- **Web**: Stateless — scale with multiple instances or deploy to Vercel/Cloudflare
- **AI Services**: CPU-bound — scale based on valuation request volume
- **Redis**: Use Redis Cluster for high availability
- **PostgreSQL**: Read replicas for query-heavy workloads
- **API**: Stateless — scale với nhiều instance phía sau load balancer
- **Web**: Stateless — scale với nhiều instance hoặc deploy lên Vercel/Cloudflare
- **AI Services**: CPU-bound — scale theo lượng yêu cầu định giá
- **Redis**: Dùng Redis Cluster cho tính sẵn sàng cao
- **PostgreSQL**: Read replica cho workload nhiều truy vấn
### Recommended Architecture (Production)
### Kiến Trúc Khuyến Nghị (Production)
```
┌─────────────┐
@@ -216,143 +216,143 @@ docker run -p 8000:8000 --env-file ../../.env goodgo-ai-services
## CI/CD Pipeline
### Branch Strategy
### Chiến Lược Branch
| Branch | Deploy Target | Trigger | Notes |
| Branch | Đích deploy | Trigger | Ghi chú |
|--------|--------------|---------|-------|
| `develop` | Staging | Auto (push) | Every merge to `develop` auto-deploys to staging |
| `master` | Staging | Auto (push) | Master push also deploys to staging for verification |
| Manual | Staging/Production | `workflow_dispatch` | Manual trigger via GitHub Actions UI |
| `develop` | Staging | Tự động (push) | Mọi merge o `develop` đều tự deploy lên staging |
| `master` | Staging | Tự động (push) | Push master cũng deploy lên staging để verify |
| Manual | Staging/Production | `workflow_dispatch` | Trigger thủ công qua GitHub Actions UI |
### Staging Auto-Deploy Flow
### Quy Trình Auto-Deploy Staging
```
Push to develop → Build images → Tag rollback → Deploy to staging → Smoke tests → Cleanup / Rollback
```
1. **Build**: Docker images for API, Web, and AI Services are built and pushed to GHCR with `staging-latest` tag
2. **Tag rollback**: Current running images are tagged as `:rollback` before new images are pulled
3. **Deploy**: New images are pulled and services are updated via rolling restart (zero-downtime)
4. **Verify**: Health check polls `$STAGING_URL/health` for up to 100 seconds
5. **Smoke test**: `scripts/smoke-test.sh` runs against the staging URL, checking health probes, core API endpoints, search, and auth
6. **Cleanup**: On success, `:rollback` tags are removed and `docker image prune` cleans up old layers
7. **Notify**: Slack notification on success or failure
8. **Rollback**: If smoke tests fail, automatic rollback restores the `:rollback` tagged images
1. **Build**: Docker image cho API, Web, AI Services được build và push lên GHCR với tag `staging-latest`
2. **Tag rollback**: Image hiện đang chạy được tag là `:rollback` trước khi pull image mới
3. **Deploy**: Image mới được pull và dịch vụ được cập nhật qua rolling restart (zero-downtime)
4. **Verify**: Health check poll `$STAGING_URL/health` trong tối đa 100 giây
5. **Smoke test**: `scripts/smoke-test.sh` chạy với staging URL, kiểm tra health probe, các endpoint API cốt lõi, search auth
6. **Cleanup**: Khi thành công, các tag `:rollback` được xóa và `docker image prune` dọn dẹp các layer
7. **Notify**: Thông báo Slack khi thành công hoặc thất bại
8. **Rollback**: Nếu smoke test thất bại, rollback tự động khôi phục image có tag `:rollback`
### Notifications
### Thông Báo
Deploy status notifications are sent to Slack via `SLACK_WEBHOOK_URL` secret:
Trạng thái deploy được gửi đến Slack qua secret `SLACK_WEBHOOK_URL`:
| Event | Channel | Content |
| Sự kiện | Kênh | Nội dung |
|-------|---------|---------|
| Staging smoke tests pass | Slack | ✅ Commit SHA, branch, link to run |
| Staging smoke tests fail | Slack | 🚨 Commit SHA, branch, link to run |
| Staging rollback triggered | Slack | ⚠️ Commit SHA, reason, link to run |
| Production deploy success | Slack | ✅ Commit SHA, branch |
| Production rollback triggered | Slack | ⚠️ Commit SHA, reason, link to run |
| Smoke test staging pass | Slack | ✅ Commit SHA, branch, link đến run |
| Smoke test staging fail | Slack | 🚨 Commit SHA, branch, link đến run |
| Trigger rollback staging | Slack | ⚠️ Commit SHA, lý do, link đến run |
| Deploy production thành công | Slack | ✅ Commit SHA, branch |
| Trigger rollback production | Slack | ⚠️ Commit SHA, lý do, link đến run |
### Required Secrets
### Secret Bắt Buộc
| Secret | Environment | Description |
| Secret | Môi trường | Mô tả |
|--------|-------------|-------------|
| `STAGING_HOST` | staging | Staging server hostname/IP |
| `STAGING_USER` | staging | SSH user for staging deploys |
| `STAGING_SSH_KEY` | staging | SSH private key for staging |
| `STAGING_URL` | staging | Staging base URL (e.g., `https://staging.goodgo.vn`) |
| `PRODUCTION_HOST` | production | Production server hostname/IP |
| `PRODUCTION_USER` | production | SSH user for production deploys |
| `PRODUCTION_SSH_KEY` | production | SSH private key for production |
| `PRODUCTION_URL` | production | Production base URL |
| `SLACK_WEBHOOK_URL` | both | Slack incoming webhook URL |
| `STAGING_HOST` | staging | Hostname/IP server staging |
| `STAGING_USER` | staging | User SSH cho deploy staging |
| `STAGING_SSH_KEY` | staging | Khóa SSH private cho staging |
| `STAGING_URL` | staging | URL gốc staging (vd: `https://staging.goodgo.vn`) |
| `PRODUCTION_HOST` | production | Hostname/IP server production |
| `PRODUCTION_USER` | production | User SSH cho deploy production |
| `PRODUCTION_SSH_KEY` | production | Khóa SSH private cho production |
| `PRODUCTION_URL` | production | URL gốc production |
| `SLACK_WEBHOOK_URL` | cả hai | URL incoming webhook Slack |
## Rollback
### Rollback Safety Mechanism
### Cơ Chế An Toàn Khi Rollback
The deploy pipeline uses **explicit `:rollback` image tags** to guarantee safe rollbacks. Here's how it works:
Pipeline deploy sử dụng **tag image `:rollback` rõ ràng** để bảo đảm rollback an toàn. Cách hoạt động như sau:
1. **Before pulling new images**: The current running images are tagged as `goodgo-api:rollback`, `goodgo-web:rollback`, and `goodgo-ai-services:rollback`
2. **After pulling new images**: Services are updated with the new images via rolling restart
3. **After smoke tests pass**: The `:rollback` tags are removed and `docker image prune` cleans up old layers
4. **If smoke tests fail**: The `:rollback` tagged images are used to restore the previous version
1. **Trước khi pull image mới**: Image hiện đang chạy được tag là `goodgo-api:rollback`, `goodgo-web:rollback`, `goodgo-ai-services:rollback`
2. **Sau khi pull image mới**: Dịch vụ được cập nhật với image mới qua rolling restart
3. **Sau khi smoke test pass**: Tag `:rollback` được xóa và `docker image prune` dọn dẹp layer
4. **Nếu smoke test fail**: Image có tag `:rollback` được dùng để khôi phục phiên bản trước
This ensures that `docker image prune` never deletes the images needed for rollback, because:
- Image pruning only happens **after** smoke tests pass
- The `:rollback` tags keep the previous images pinned even if pruning were to run accidentally
Điều này bảo đảm `docker image prune` không bao giờ xóa image cần cho rollback, :
- Image pruning chỉ xảy ra **sau** khi smoke test pass
- Tag `:rollback` giữ image trước được pin lại ngay cả khi pruning vô tình chạy
### Automatic Rollback (Staging)
### Rollback Tự Động (Staging)
The staging pipeline includes automatic rollback when smoke tests fail:
Pipeline staging có rollback tự động khi smoke test thất bại:
1. **Pre-deploy**: Current container images are tagged with `:rollback` suffix before new images are pulled
2. **Smoke test failure**: If `scripts/smoke-test.sh` exits non-zero, the `rollback-staging` job triggers
3. **Rollback execution**: Containers are stopped and restarted using the `:rollback` tagged images
4. **Verification**: Health check confirms the rollback succeeded
5. **Notification**: Slack notification reports the rollback with links to the failed run
1. **Trước deploy**: Image container hiện tại được tag với hậu tố `:rollback` trước khi pull image mới
2. **Smoke test thất bại**: Nếu `scripts/smoke-test.sh` thoát non-zero, job `rollback-staging` được trigger
3. **Thực hiện rollback**: Container được dừng và khởi động lại bằng image có tag `:rollback`
4. **Verify**: Health check xác nhận rollback đã thành công
5. **Notification**: Slack báo cáo rollback kèm link đến run thất bại
### Automatic Rollback (Production)
### Rollback Tự Động (Production)
Same mechanism as staging — smoke test failure triggers `rollback-production` using the `:rollback` tagged images.
Cơ chế giống staging — smoke test thất bại sẽ trigger `rollback-production` dùng image có tag `:rollback`.
### Manual Rollback
### Rollback Thủ Công
To manually rollback a staging or production deployment:
Để rollback thủ công một deployment staging hoặc production:
#### Option 1: Re-deploy a known-good commit
#### Lựa chọn 1: Re-deploy một commit đã biết là tốt
```bash
# Trigger a deploy of a specific commit via GitHub Actions
# Trigger deploy của một commit cụ thể qua GitHub Actions
gh workflow run deploy.yml \
--ref <known-good-commit-or-branch> \
-f environment=staging
```
#### Option 2: SSH rollback using :rollback tags (fastest)
#### Lựa chọn 2: SSH rollback dùng tag :rollback (nhanh nhất)
```bash
# SSH into the staging/production server
# SSH vào server staging/production
ssh deploy@<host>
cd ~/goodgo
# Stop current services
# Dừng dịch vụ hiện tại
docker compose -f docker-compose.prod.yml stop api web ai-services
# Verify :rollback images exist
# Xác nhận image :rollback tồn tại
docker image inspect goodgo-api:rollback > /dev/null 2>&1 && echo "API rollback available"
docker image inspect goodgo-web:rollback > /dev/null 2>&1 && echo "Web rollback available"
docker image inspect goodgo-ai-services:rollback > /dev/null 2>&1 && echo "AI rollback available"
# Restart services (compose picks up cached/rollback images)
# Khởi động lại dịch vụ (compose lấy image cache/rollback)
docker compose -f docker-compose.prod.yml up -d --wait api web ai-services
# Verify health
curl -sf http://localhost:3001/health && echo "Rollback successful"
```
> **Note:** The `:rollback` tags are only available until the next successful deploy cleans them up. If you need to roll back to an older version, use Option 3 below.
> **Lưu ý:** Tag `:rollback` chỉ có sẵn cho đến khi lần deploy thành công kế tiếp dọn chúng đi. Nếu cần rollback về phiên bản cũ hơn, dùng Lựa chọn 3 dưới đây.
#### Option 3: Pin to a specific image tag
#### Lựa chọn 3: Pin về một image tag cụ thể
```bash
ssh deploy@<host>
cd ~/goodgo
# Set IMAGE_TAG to a known-good SHA
# Đặt IMAGE_TAG về một SHA đã biết là tốt
export IMAGE_TAG=<known-good-commit-sha>
export REGISTRY_URL=ghcr.io/<owner>
# Pull and restart with the pinned tag
# Pull và khởi động lại với tag đã pin
docker compose -f docker-compose.prod.yml pull api web ai-services
docker compose -f docker-compose.prod.yml up -d --no-deps --wait api web ai-services
```
#### Option 4: Use deploy-production.sh (built-in rollback)
#### Lựa chọn 4: Dùng deploy-production.sh (rollback tích hợp sẵn)
The manual deploy script (`scripts/deploy-production.sh`) has integrated rollback support:
- Automatically tags `:rollback` images before pulling
- Runs health checks and smoke tests
- Auto-rollbacks using `:rollback` tags if either fails
- Only prunes images after smoke tests pass
Script deploy thủ công (`scripts/deploy-production.sh`) có hỗ trợ rollback tích hợp:
- Tự động tag image `:rollback` trước khi pull
- Chạy health check smoke test
- Tự rollback dùng tag `:rollback` nếu một trong hai thất bại
- Chỉ prune image sau khi smoke test pass
```bash
ssh ubuntu@185.225.232.65
@@ -360,21 +360,21 @@ cd ~/goodgo
./scripts/deploy-production.sh [image-tag]
```
### Database Rollback
### Rollback Database
Prisma does not support automatic down migrations. If a migration must be reverted:
Prisma không hỗ trợ down migration tự động. Nếu một migration cần được hoàn tác:
1. Identify the migration in `prisma/migrations/`
2. Write a manual SQL rollback script
3. Apply via `psql` or a migration tool
4. Update `_prisma_migrations` table
1. Xác định migration trong `prisma/migrations/`
2. Viết script rollback SQL thủ công
3. Áp dụng qua `psql` hoặc công cụ migration
4. Cập nhật bảng `_prisma_migrations`
Always test migrations against a staging database before production deployment.
Luôn test migration với database staging trước khi deploy production.
### Post-Rollback Checklist
### Checklist Sau Rollback
- [ ] Verify health endpoints respond: `GET /health`, `GET /ready`
- [ ] Run smoke tests manually: `./scripts/smoke-test.sh <url>`
- [ ] Check application logs: `docker compose -f docker-compose.prod.yml logs --tail=100 api web`
- [ ] Confirm Grafana dashboards show normal metrics
- [ ] Notify the team via Slack about the rollback and root cause
- [ ] Xác nhận health endpoint phản hồi: `GET /health`, `GET /ready`
- [ ] Chạy smoke test thủ công: `./scripts/smoke-test.sh <url>`
- [ ] Kiểm tra log ứng dụng: `docker compose -f docker-compose.prod.yml logs --tail=100 api web`
- [ ] Xác nhận dashboard Grafana hiển thị metric bình thường
- [ ] Thông báo cho team qua Slack về rollback và nguyên nhân gốc

View File

@@ -1,114 +1,114 @@
# GoodGo Platform - Authentication Implementation Checklist
# GoodGo Platform - Checklist Triển Khai Authentication
**Date:** April 12, 2026
**Status:** ✅ Complete Analysis
**Ngày:** 12 tháng 4, 2026
**Trạng thái:** ✅ Phân Tích Hoàn Tất
---
## 📋 Authentication System Components
## 📋 Các Thành Phần Của Hệ Thống Authentication
### ✅ 1. Password Hashing
- **Algorithm:** bcrypt
- **Salt Rounds:** 12 (configurable via `BCRYPT_ROUNDS` env var)
- **Min Password:** 8 characters
- **Location:** `apps/api/src/modules/auth/domain/value-objects/hashed-password.vo.ts`
- **Method Used:** `HashedPassword.fromPlain(password)` → async bcrypt.hash()
- **Comparison:** `passwordHash.compare(plainPassword)` → bcrypt.compare()
### ✅ 1. Hashing Mật Khẩu
- **Thuật toán:** bcrypt
- **Salt Rounds:** 12 (có thể cấu hình qua biến env `BCRYPT_ROUNDS`)
- **Mật khẩu tối thiểu:** 8 ký tự
- **Vị trí:** `apps/api/src/modules/auth/domain/value-objects/hashed-password.vo.ts`
- **Method dùng:** `HashedPassword.fromPlain(password)` → async bcrypt.hash()
- **So sánh:** `passwordHash.compare(plainPassword)` → bcrypt.compare()
### ✅ 2. Phone Validation & Normalization
### ✅ 2. Validate & Chuẩn Hóa Số Điện Thoại
- **File:** `apps/api/src/modules/shared/utils/vietnam-phone.validator.ts`
- **Regex:** `/^(?:\+84|84|0)(3[2-9]|5[2689]|7[06-9]|8[1-9]|9[0-9])\d{7}$/`
- **Accepted Formats:**
- **Định dạng được chấp nhận:**
- `0900000001` (local)
- `84900000001` (country code, no +)
- `+84900000001` (international)
- **Normalized Format:** Always `+84XXX...` (country code prefix)
- **Carriers:** Mobile only (no landlines)
- `84900000001` (mã quốc gia, không +)
- `+84900000001` (quốc tế)
- **Định dạng chuẩn hóa:** Luôn là `+84XXX...` (prefix mã quốc gia)
- **Nhà mạng:** Chỉ di động (không có cố định)
- 32-39: Viettel/VinaPhone/MobiFone
- 52, 56, 58, 59: Viettel
- 70, 76-79: Newer carriers
- 70, 76-79: Nhà mạng mới
- 81-89: VinaPhone
- 90-99: MobiFone
### ✅ 3. Email Validation & Normalization
### ✅ 3. Validate & Chuẩn Hóa Email
- **File:** `apps/api/src/modules/auth/domain/value-objects/email.vo.ts`
- **Regex:** `/^[^\s@]+@[^\s@]+\.[^\s@]+$/` (basic validation)
- **Normalization:** lowercase + trimmed
- **Example:** `ADMIN@GOODGO.VN`stored as `admin@goodgo.vn`
- **Regex:** `/^[^\s@]+@[^\s@]+\.[^\s@]+$/` (validate cơ bản)
- **Chuẩn hóa:** lowercase + trim
- **Ví dụ:** `ADMIN@GOODGO.VN`lưu thành `admin@goodgo.vn`
### ✅ 4. PII Encryption & Hashing
### ✅ 4. Mã Hóa & Hashing PII
- **File:** `apps/api/src/modules/shared/infrastructure/field-encryption.ts`
- **Encryption Algorithm:** AES-256-GCM
- **Key Size:** 32 bytes (64 hex characters)
- **IV:** 12 bytes (random)
- **Auth Tag:** 16 bytes
- **Storage Format:** `enc:v{version}:{iv}:{authTag}:{ciphertext}` (hex)
- **Encrypted Fields:**
- `email`stored encrypted + hash in `emailHash`
- `phone`stored encrypted + hash in `phoneHash`
- `kycData`stored encrypted (no separate hash)
- **Hash Function:** HMAC-SHA256 (derived from encryption key via HKDF-SHA256)
- **Hash Normalization:** lowercase + trimmed
- **Env Vars:**
- `FIELD_ENCRYPTION_KEY` (required) - hex string, 64 chars
- `FIELD_ENCRYPTION_KEY_VERSION` (optional, default: 1)
- **Thuật toán mã hóa:** AES-256-GCM
- **Kích thước key:** 32 byte (64 ký tự hex)
- **IV:** 12 byte (ngẫu nhiên)
- **Auth Tag:** 16 byte
- **Định dạng lưu trữ:** `enc:v{version}:{iv}:{authTag}:{ciphertext}` (hex)
- **Field được mã hóa:**
- `email`lưu mã hóa + hash trong `emailHash`
- `phone`lưu mã hóa + hash trong `phoneHash`
- `kycData`lưu mã hóa (không có hash riêng)
- **Hàm hash:** HMAC-SHA256 (dẫn xuất từ encryption key qua HKDF-SHA256)
- **Chuẩn hóa hash:** lowercase + trim
- **Biến env:**
- `FIELD_ENCRYPTION_KEY` (bắt buộc) - chuỗi hex, 64 ký tự
- `FIELD_ENCRYPTION_KEY_VERSION` (tùy chọn, mặc định: 1)
- Fallback: `KYC_ENCRYPTION_KEY` / `KYC_ENCRYPTION_KEY_VERSION`
### ✅ 5. Login Flow
### ✅ 5. Luồng Đăng Nhập
- **File:** `apps/api/src/modules/auth/infrastructure/strategies/local.strategy.ts`
- **Username Field:** `phone` (Vietnamese format)
- **Password Field:** `password` (plaintext)
- **User Lookup:** By `phoneHash` (unique index)
- **Steps:**
1. Normalize phone
2. Find user by phoneHash
3. Check `isActive` = true
4. Compare password (bcrypt)
5. Check `totpEnabled`
6. Issue JWT tokens or MFA challenge
- **MFA Response (if enabled):** `challengeId` + 5-minute TTL
- **No MFA Response:** `accessToken` + `refreshToken` + expiry
- **Trường username:** `phone` (định dạng Việt Nam)
- **Trường password:** `password` (plaintext)
- **Lookup user:** Theo `phoneHash` (unique index)
- **Các bước:**
1. Chuẩn hóa số điện thoại
2. Tìm user theo phoneHash
3. Kiểm tra `isActive` = true
4. So sánh password (bcrypt)
5. Kiểm tra `totpEnabled`
6. Cấp JWT token hoặc MFA challenge
- **Phản hồi MFA (nếu bật):** `challengeId` + TTL 5 phút
- **Phản hồi không có MFA:** `accessToken` + `refreshToken` + thời hạn
### ✅ 6. User Roles
### ✅ 6. Vai Trò User
- **Enum:** `UserRole` (Prisma)
- **Values:**
- `BUYER` (default) - Can search, inquire, make offers
- `SELLER` - Can create listings
- `AGENT` - Professional agent with verified profile
- `ADMIN` - Full platform access
- **Default Role:** `BUYER`
- **Admin Role:** Created explicitly with `role: 'ADMIN'`
- **Giá trị:**
- `BUYER` (mặc định) - Có thể tìm kiếm, hỏi, đặt giá
- `SELLER` - Có thể tạo tin đăng
- `AGENT` - Agent chuyên nghiệp với hồ sơ đã verify
- `ADMIN` - Truy cập đầy đủ platform
- **Vai trò mặc định:** `BUYER`
- **Vai trò Admin:** Tạo rõ ràng với `role: 'ADMIN'`
### ✅ 7. MFA (Multi-Factor Authentication)
- **TOTP:**
- Generator: otplib (RFC 6238)
- Period: 30 seconds
- Digits: 6
- Clock Skew: ±30 seconds
- **Backup Codes:**
- Count: 10
- Length: 8 characters each
- Charset: A-Z (no O, I), 2-9 (no 0, 1)
- Hashing: HMAC-SHA256 (not bcrypt)
- Secret Key: `MFA_BACKUP_CODE_SECRET` or fallback to `JWT_SECRET`
- **TOTP Secret Storage:** Encrypted with AES-256-GCM
- Period: 30 giây
- Digit: 6
- Clock Skew: ±30 giây
- **Backup Code:**
- Số lượng: 10
- Độ dài: 8 ký tự mỗi mã
- Charset: A-Z (không có O, I), 2-9 (không có 0, 1)
- Hashing: HMAC-SHA256 (không phải bcrypt)
- Secret Key: `MFA_BACKUP_CODE_SECRET` hoặc fallback về `JWT_SECRET`
- **Lưu trữ TOTP Secret:** Mã hóa với AES-256-GCM
### ✅ 8. User Model Fields (Required for Login)
### ✅ 8. Field User Model (Bắt Buộc Cho Đăng Nhập)
```typescript
User {
id: string // CUID
phone: string // Normalized: +84XXX...
phone: string // Chuẩn hóa: +84XXX...
phoneHash: string // HMAC-SHA256 (unique index)
email?: string // Lowercase, trimmed (encrypted)
email?: string // Lowercase, trim (mã hóa)
emailHash?: string // HMAC-SHA256 (unique index)
passwordHash?: string // bcrypt hash (nullable for OAuth)
passwordHash?: string // hash bcrypt (nullable cho OAuth)
fullName: string
role: UserRole // BUYER | SELLER | AGENT | ADMIN
isActive: boolean // true = can login
isActive: boolean // true = có thể đăng nhập
kycStatus: KYCStatus // NONE | PENDING | VERIFIED | REJECTED
totpEnabled: boolean // MFA enabled
totpSecret?: string // Encrypted
totpBackupCodes: string[] // HMAC-SHA256 hashed codes
totpEnabled: boolean // MFA đã bật
totpSecret?: string // Mã hóa
totpBackupCodes: string[] // Mã đã hash HMAC-SHA256
createdAt: DateTime
updatedAt: DateTime
}
@@ -116,32 +116,32 @@ User {
---
## 🔐 Creating Login-Capable Seed Users
## 🔐 Tạo Seed User Có Khả Năng Đăng Nhập
### Requirements Checklist
- [ ] Password ≥ 8 characters
- [ ] Phone matches Vietnamese regex
- [ ] Phone normalized to `+84...` format
- [ ] Email matches basic regex `^[^\s@]+@[^\s@]+\.[^\s@]+$`
### Checklist Yêu Cầu
- [ ] Mật khẩu ≥ 8 ký tự
- [ ] Số điện thoại khớp regex Việt Nam
- [ ] Số điện thoại chuẩn hóa thành định dạng `+84...`
- [ ] Email khớp regex cơ bản `^[^\s@]+@[^\s@]+\.[^\s@]+$`
- [ ] Email lowercased
- [ ] Password hashed with bcrypt (≥12 rounds)
- [ ] `phoneHash` computed (HMAC-SHA256)
- [ ] `emailHash` computed (HMAC-SHA256)
- [ ] Mật khẩu hash với bcrypt (≥12 rounds)
- [ ] `phoneHash` được tính (HMAC-SHA256)
- [ ] `emailHash` được tính (HMAC-SHA256)
- [ ] `isActive: true`
- [ ] `totpEnabled: false` (for seed users)
- [ ] `totpEnabled: false` (cho seed user)
- [ ] `totpBackupCodes: []`
### Implementation Steps
### Các Bước Triển Khai
**Step 1: Normalize Phone**
**Bước 1: Chuẩn Hóa Số Điện Thoại**
```typescript
const phone = '0900000001';
const normalized = `+84${phone.slice(1)}`; // '+84900000001'
```
**Step 2: Derive HMAC Key**
**Bước 2: Dẫn Xuất HMAC Key**
```typescript
const encryptionKey = process.env['FIELD_ENCRYPTION_KEY']; // hex string
const encryptionKey = process.env['FIELD_ENCRYPTION_KEY']; // chuỗi hex
const hmacKey = crypto.hkdfSync(
'sha256',
Buffer.from(encryptionKey, 'hex'),
@@ -151,7 +151,7 @@ const hmacKey = crypto.hkdfSync(
);
```
**Step 3: Compute Hashes**
**Bước 3: Tính Hash**
```typescript
const phoneHash = crypto
.createHmac('sha256', hmacKey)
@@ -164,12 +164,12 @@ const emailHash = crypto
.digest('hex');
```
**Step 4: Hash Password**
**Bước 4: Hash Mật Khẩu**
```typescript
const passwordHash = await bcrypt.hash('AdminPassword123', 12);
```
**Step 5: Create User**
**Bước 5: Tạo User**
```typescript
await prisma.user.create({
data: {
@@ -191,15 +191,15 @@ await prisma.user.create({
---
## 🧪 Testing Login
## 🧪 Test Đăng Nhập
### Prerequisites
- User exists in database
- `passwordHash` is set (not null)
### Yêu Cầu Trước
- User tồn tại trong database
- `passwordHash` được set (không null)
- `isActive: true`
- No MFA enabled (or have MFA code ready)
- Không bật MFA (hoặc có sẵn mã MFA)
### Test Request
### Request Test
```bash
curl -X POST http://localhost:3000/auth/login \
-H "Content-Type: application/json" \
@@ -209,7 +209,7 @@ curl -X POST http://localhost:3000/auth/login \
}'
```
### Expected Response (Success)
### Phản Hồi Mong Đợi (Thành Công)
```json
{
"requiresMfa": false,
@@ -221,127 +221,127 @@ curl -X POST http://localhost:3000/auth/login \
}
```
### Error Cases
- **Invalid phone format:** "Số điện thoại không hợp lệ"
- **User not found:** "Số điện thoại hoặc mật khẩu không đúng"
- **User inactive:** "Tài khoản đã bị vô hiệu hóa"
- **Wrong password:** "Số điện thoại hoặc mật khẩu không đúng"
- **MFA required:** `{ "requiresMfa": true, "challengeId": "..." }`
### Các Trường Hợp Lỗi
- **Định dạng số điện thoại không hợp lệ:** "Số điện thoại không hợp lệ"
- **Không tìm thấy user:** "Số điện thoại hoặc mật khẩu không đúng"
- **User không active:** "Tài khoản đã bị vô hiệu hóa"
- **Sai mật khẩu:** "Số điện thoại hoặc mật khẩu không đúng"
- **Yêu cầu MFA:** `{ "requiresMfa": true, "challengeId": "..." }`
---
## 📁 Key Files Reference
## 📁 Tham Khảo Các File Chính
| File | Purpose | Key Functions |
| File | Mục đích | Hàm chính |
|------|---------|---------------|
| `hashed-password.vo.ts` | Password hashing | `fromPlain()`, `compare()` |
| `phone.vo.ts` | Phone validation | `create()` |
| `email.vo.ts` | Email validation | `create()` |
| `vietnam-phone.validator.ts` | Phone regex/normalize | `isValidVietnamPhone()`, `normalizeVietnamPhone()` |
| `field-encryption.ts` | PII encryption/hashing | `encryptField()`, `decryptField()`, `computeHash()` |
| `local.strategy.ts` | Login flow | `validate()` |
| `mfa.service.ts` | TOTP/backup codes | `generateSetup()`, `verifyTotp()`, `generateBackupCodes()` |
| `user.entity.ts` | User domain model | `createNew()` |
| `prisma-user.repository.ts` | User persistence | `findByPhone()`, `save()` |
| `encrypt-pii-fields.ts` | Backfill encryption | Batch encryption migration |
| `schema.prisma` | Database schema | User model, enums |
| `seed.ts` | Seed data | Current seeds (no passwords) |
| `hashed-password.vo.ts` | Hash mật khẩu | `fromPlain()`, `compare()` |
| `phone.vo.ts` | Validate số điện thoại | `create()` |
| `email.vo.ts` | Validate email | `create()` |
| `vietnam-phone.validator.ts` | Regex/chuẩn hóa số điện thoại | `isValidVietnamPhone()`, `normalizeVietnamPhone()` |
| `field-encryption.ts` | Mã hóa/hash PII | `encryptField()`, `decryptField()`, `computeHash()` |
| `local.strategy.ts` | Luồng đăng nhập | `validate()` |
| `mfa.service.ts` | TOTP/backup code | `generateSetup()`, `verifyTotp()`, `generateBackupCodes()` |
| `user.entity.ts` | Domain model User | `createNew()` |
| `prisma-user.repository.ts` | Persist user | `findByPhone()`, `save()` |
| `encrypt-pii-fields.ts` | Backfill mã hóa | Migration mã hóa hàng loạt |
| `schema.prisma` | Schema database | Model User, enum |
| `seed.ts` | Dữ liệu seed | Seed hiện tại (không có mật khẩu) |
---
## 🚀 Deployment Checklist
## 🚀 Checklist Deployment
### Environment Variables Required
- [ ] `BCRYPT_ROUNDS` (optional, default: 12)
- [ ] `FIELD_ENCRYPTION_KEY` (required for PII, hex string 64 chars)
- [ ] `FIELD_ENCRYPTION_KEY_VERSION` (optional, default: 1)
- [ ] `MFA_BACKUP_CODE_SECRET` (optional, fallback to JWT_SECRET)
- [ ] `JWT_SECRET` (required for tokens)
### Biến Môi Trường Bắt Buộc
- [ ] `BCRYPT_ROUNDS` (tùy chọn, mặc định: 12)
- [ ] `FIELD_ENCRYPTION_KEY` (bắt buộc cho PII, chuỗi hex 64 ký tự)
- [ ] `FIELD_ENCRYPTION_KEY_VERSION` (tùy chọn, mặc định: 1)
- [ ] `MFA_BACKUP_CODE_SECRET` (tùy chọn, fallback về JWT_SECRET)
- [ ] `JWT_SECRET` (bắt buộc cho token)
### Database Setup
- [ ] Run migrations (including `add_mfa_totp_support`)
- [ ] Seed users with passwords (use provided script)
- [ ] Test login functionality
- [ ] Verify PII encryption working
### Cài Đặt Database
- [ ] Chạy migration (bao gồm `add_mfa_totp_support`)
- [ ] Seed user với mật khẩu (dùng script đã cung cấp)
- [ ] Test chức năng đăng nhập
- [ ] Verify mã hóa PII hoạt động
### Testing
- [ ] Test login with various phone formats (0900..., 84900..., +84900...)
- [ ] Test invalid phone numbers (rejected)
- [ ] Test password validation (min 8 chars)
- [ ] Test email validation
- [ ] Test MFA setup and verification
- [ ] Test backup code generation/usage
- [ ] Verify hashes computed correctly
- [ ] Test đăng nhập với nhiều định dạng số điện thoại (0900..., 84900..., +84900...)
- [ ] Test số điện thoại không hợp lệ (bị từ chối)
- [ ] Test validate mật khẩu (tối thiểu 8 ký tự)
- [ ] Test validate email
- [ ] Test setup verify MFA
- [ ] Test sinh/dùng backup code
- [ ] Verify hash được tính đúng
---
## 📝 Current Seed Data Status
## 📝 Trạng Thái Dữ Liệu Seed Hiện Tại
### Existing Seed (prisma/seed.ts)
**Status:** ❌ **NOT login-capable** (no passwords)
### Seed Hiện Có (prisma/seed.ts)
**Trạng thái:** ❌ **KHÔNG có khả năng đăng nhập** (không có mật khẩu)
```typescript
// Current seed - users created without passwords
// Seed hiện tại - user được tạo không có mật khẩu
const admin = await prisma.user.upsert({
where: { id: 'seed-user-admin' },
create: {
id: 'seed-user-admin',
phone: '0900000001', // NOT normalized/hashed
phone: '0900000001', // CHƯA chuẩn hóa/hash
email: 'admin@goodgo.vn',
fullName: 'Admin GoodGo',
role: UserRole.ADMIN,
// passwordHash: null ← Cannot login!
// passwordHash: null ← Không thể đăng nhập!
},
});
```
### Recommended Enhancement
Use `SEED_GENERATION_SCRIPT.ts` to create users with full auth capability.
### Cải Tiến Khuyến Nghị
Dùng `SEED_GENERATION_SCRIPT.ts` để tạo user với khả năng auth đầy đủ.
---
## 🔍 Troubleshooting
### User Can't Login
1. Verify `passwordHash` is NOT null: `SELECT id, passwordHash FROM "User" WHERE id = 'user-id';`
2. Check `isActive = true`
3. Verify phone is normalized to `+84...` format
4. Test phone normalization function directly
### User Không Đăng Nhập Được
1. Verify `passwordHash` KHÔNG null: `SELECT id, passwordHash FROM "User" WHERE id = 'user-id';`
2. Kiểm tra `isActive = true`
3. Verify số điện thoại chuẩn hóa thành định dạng `+84...`
4. Test trực tiếp hàm chuẩn hóa số điện thoại
### Phone Hash Mismatch
1. Verify `FIELD_ENCRYPTION_KEY` is same across deployments
2. Check hash computation: `HMAC-SHA256(lowercased_phone, hmacKey)`
3. HKDF derivation must use exact string: `"goodgo-field-hash"`
### Phone Hash Không Khớp
1. Verify `FIELD_ENCRYPTION_KEY` giống nhau giữa các deployment
2. Kiểm tra cách tính hash: `HMAC-SHA256(lowercased_phone, hmacKey)`
3. Dẫn xuất HKDF phải dùng đúng chuỗi: `"goodgo-field-hash"`
### MFA Not Working
1. Verify `MFA_BACKUP_CODE_SECRET` is set
2. Check TOTP secret is encrypted properly
3. Test clock skew (±30s tolerance)
### MFA Không Hoạt Động
1. Verify `MFA_BACKUP_CODE_SECRET` đã được set
2. Kiểm tra TOTP secret được mã hóa đúng cách
3. Test clock skew (dung sai ±30s)
### Encryption/Decryption Issues
1. Verify key is exactly 32 bytes (64 hex chars)
2. Check IV length (12 bytes)
3. Verify auth tag (16 bytes)
4. Ensure `enc:` prefix detection working
### Vấn Đề Mã Hóa/Giải Mã
1. Verify key đúng 32 byte (64 ký tự hex)
2. Kiểm tra độ dài IV (12 byte)
3. Verify auth tag (16 byte)
4. Đảm bảo phát hiện prefix `enc:` hoạt động
---
## 📚 Additional Resources
## 📚 Tài Nguyên Bổ Sung
### External Documentation
### Tài Liệu Bên Ngoài
- **bcrypt:** https://github.com/kelektiv/node.bcrypt.js
- **otplib:** https://github.com/yeojz/otplib
- **Prisma:** https://www.prisma.io/docs
- **NestJS:** https://docs.nestjs.com
### Related Files
- Registration flow: `register-user.handler.ts`
- Token generation: `token.service.ts`
### File Liên Quan
- Luồng đăng ký: `register-user.handler.ts`
- Sinh token: `token.service.ts`
- JWT strategy: `jwt.strategy.ts`
- Refresh token: `refresh-token.handler.ts`
---
**Last Updated:** April 12, 2026
**Cập nhật lần cuối:** 12 tháng 4, 2026
**Platform:** GoodGo Real Estate Platform
**Status:** Production-Ready
**Trạng thái:** ✅ Sẵn sàng Production

View File

@@ -1,17 +1,17 @@
# GoodGo Platform API — K6 Load Testing Guide
# GoodGo Platform API — Hướng Dẫn K6 Load Testing
## 🎯 Quick Summary
## 🎯 Tóm Tắt Nhanh
**Base URL**: `http://localhost:3001/api/v1`
**Node Version**: >= 22.0.0
**Phiên bản Node**: >= 22.0.0
**Testing Framework**: Playwright (E2E), Vitest (Unit)
**No existing K6 or load testing setup found**
**Chưa có thiết lập K6 hoặc load testing nào tồn tại**
---
## 📋 Project Structure
## 📋 Cấu Trúc Dự Án
### Root Directory
### Thư Mục Gốc
```
goodgo-platform/
├── apps/api # NestJS backend (port 3001)
@@ -25,7 +25,7 @@ goodgo-platform/
└── playwright.config.ts # Playwright configuration
```
### Key Scripts (package.json)
### Các Script Chính (package.json)
```bash
pnpm dev # Start all apps (API :3001, Web :3000)
pnpm test # Unit tests via Vitest (API only)
@@ -39,11 +39,11 @@ pnpm typecheck # TypeScript checking
---
## 🏗️ API Module Structure
## 🏗️ Cấu Trúc Module API
### API Base Architecture: `apps/api/src/modules/`
### Kiến Trúc Cơ Sở API: `apps/api/src/modules/`
Each module follows DDD layers: `domain/``application/``infrastructure/``presentation/`
Mỗi module tuân theo các tầng DDD: `domain/``application/``infrastructure/``presentation/`
```
modules/
@@ -64,22 +64,22 @@ modules/
---
## 🔐 AUTH MODULE
## 🔐 MODULE AUTH
### Controllers & Endpoints
#### File: `apps/api/src/modules/auth/presentation/controllers/auth.controller.ts`
| Method | Endpoint | Rate Limit | Auth | Description |
| Method | Endpoint | Rate Limit | Auth | Mô tả |
|--------|----------|-----------|------|-------------|
| POST | `/auth/register` | 5/hour | No | Register new user |
| POST | `/auth/login` | 5/hour | LocalAuth | Login with phone + password |
| POST | `/auth/refresh` | 5/hour | No | Refresh access token |
| POST | `/auth/logout` | No limit | No | Clear auth cookies |
| POST | `/auth/exchange-token` | No limit | No | Exchange OAuth tokens for cookies |
| GET | `/auth/profile` | No limit | JWT | Get current user profile |
| GET | `/auth/profile/agent` | No limit | JWT | Get agent profile for user |
| PATCH | `/auth/kyc` | No limit | JWT+Admin | Verify user KYC (admin only) |
| POST | `/auth/register` | 5/giờ | Không | Đăng ký người dùng mới |
| POST | `/auth/login` | 5/giờ | LocalAuth | Đăng nhập bằng số điện thoại + mật khẩu |
| POST | `/auth/refresh` | 5/giờ | Không | Làm mới access token |
| POST | `/auth/logout` | Không giới hạn | Không | Xóa cookie xác thực |
| POST | `/auth/exchange-token` | Không giới hạn | Không | Đổi OAuth token lấy cookie |
| GET | `/auth/profile` | Không giới hạn | JWT | Lấy hồ sơ người dùng hiện tại |
| GET | `/auth/profile/agent` | Không giới hạn | JWT | Lấy hồ sơ agent của người dùng |
| PATCH | `/auth/kyc` | Không giới hạn | JWT+Admin | Xác minh KYC người dùng (chỉ admin) |
### DTOs
@@ -117,50 +117,50 @@ modules/
}
```
### Cookies & Authentication
### Cookies & Xác Thực
**Access Token**:
- Cookie: `access_token`
- Max Age: 15 minutes (900s)
- Max Age: 15 phút (900s)
- HttpOnly: true
- Secure: true (production only)
- Secure: true (chỉ production)
- SameSite: strict
- Path: /
**Refresh Token**:
- Cookie: `refresh_token`
- Max Age: 30 days
- Max Age: 30 ngày
- HttpOnly: true
- Secure: true (production only)
- Secure: true (chỉ production)
- SameSite: strict
- Path: `/auth`
**Session Indicator**:
**Chỉ Báo Phiên**:
- Cookie: `goodgo_authenticated` = "1"
- HttpOnly: false (visible to frontend)
- HttpOnly: false (frontend nhìn thấy được)
### OAuth Support
### Hỗ Trợ OAuth
- Google OAuth 2.0
- Zalo OAuth (Vietnamese platform)
- Zalo OAuth (nền tảng Việt Nam)
- Environment: `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, `ZALO_APP_ID`, `ZALO_APP_SECRET`
---
## 🏠 LISTINGS MODULE
## 🏠 MODULE LISTINGS
### Controllers & Endpoints
#### File: `apps/api/src/modules/listings/presentation/controllers/listings.controller.ts`
| Method | Endpoint | Auth | Quota | Description |
| Method | Endpoint | Auth | Quota | Mô tả |
|--------|----------|------|-------|-------------|
| POST | `/listings` | JWT | Yes | Create new listing |
| GET | `/listings` | No | No | Search/filter listings (public) |
| GET | `/listings/:id` | No | No | Get listing detail |
| GET | `/listings/pending` | JWT+Admin | No | Get listings pending moderation |
| PATCH | `/listings/:id/status` | JWT | No | Update listing status |
| POST | `/listings/:id/media` | JWT | No | Upload photo/video |
| PATCH | `/listings/:id/moderate` | JWT+Admin | No | Moderate a listing (admin) |
| POST | `/listings` | JWT | Có | Tạo listing mới |
| GET | `/listings` | Không | Không | Tìm kiếm/lọc listing (công khai) |
| GET | `/listings/:id` | Không | Không | Lấy chi tiết listing |
| GET | `/listings/pending` | JWT+Admin | Không | Lấy listing đang chờ kiểm duyệt |
| PATCH | `/listings/:id/status` | JWT | Không | Cập nhật trạng thái listing |
| POST | `/listings/:id/media` | JWT | Không | Tải lên ảnh/video |
| PATCH | `/listings/:id/moderate` | JWT+Admin | Không | Kiểm duyệt listing (admin) |
### DTOs
@@ -233,10 +233,10 @@ modules/
}
```
### Response Structures
### Cấu Trúc Phản Hồi
#### ListingDetailData
Contains full listing information including:
Chứa thông tin đầy đủ về listing bao gồm:
- id, title, description
- propertyType, transactionType
- address, latitude, longitude, ward, district, city
@@ -244,7 +244,7 @@ Contains full listing information including:
- areaM2, usableAreaM2, bedrooms, bathrooms, floors
- amenities, nearbyPOIs
- legalStatus, yearBuilt, direction
- mediaUrls (photos/videos)
- mediaUrls (ảnh/video)
- agentInfo
- createdAt, updatedAt
@@ -261,19 +261,19 @@ Contains full listing information including:
---
## 💳 PAYMENTS MODULE
## 💳 MODULE PAYMENTS
### Controllers & Endpoints
#### File: `apps/api/src/modules/payments/presentation/controllers/payments.controller.ts`
| Method | Endpoint | Auth | Rate Limit | Description |
| Method | Endpoint | Auth | Rate Limit | Mô tả |
|--------|----------|------|-----------|-------------|
| POST | `/payments` | JWT | No | Create payment |
| GET | `/payments` | JWT | No | List user transactions |
| GET | `/payments/:id` | JWT | No | Get payment status |
| POST | `/payments/callback/:provider` | No | 20/min | Handle payment callback (webhook) |
| POST | `/payments/:id/refund` | JWT+Admin | No | Refund payment (admin) |
| POST | `/payments` | JWT | Không | Tạo thanh toán |
| GET | `/payments` | JWT | Không | Lit kê giao dịch của người dùng |
| GET | `/payments/:id` | JWT | Không | Lấy trạng thái thanh toán |
| POST | `/payments/callback/:provider` | Không | 20/phút | Xử lý callback thanh toán (webhook) |
| POST | `/payments/:id/refund` | JWT+Admin | Không | Hoàn tiền (admin) |
### DTOs
@@ -306,47 +306,47 @@ Contains full listing information including:
}
```
### Payment Providers
### Nhà Cung Cấp Thanh Toán
- **VNPay** (Primary for Vietnam)
- **VNPay** (Chính cho Việt Nam)
- Environment: `VNPAY_TMN_CODE`, `VNPAY_HASH_SECRET`
- Sandbox: `https://sandbox.vnpayment.vn/paymentv2/vpcpay.html`
- API: `https://sandbox.vnpayment.vn/merchant_webapi/api/transaction`
- **MoMo** (Mobile wallet)
- **MoMo** (Ví di động)
- Environment: `MOMO_PARTNER_CODE`, `MOMO_ACCESS_KEY`, `MOMO_SECRET_KEY`
- Endpoint: `https://test-payment.momo.vn/v2/gateway/api`
- **ZaloPay** (Zalo integrated)
- **ZaloPay** (Tích hợp Zalo)
- Environment: `ZALOPAY_APP_ID`, `ZALOPAY_KEY1`, `ZALOPAY_KEY2`
- Endpoint: `https://sb-openapi.zalopay.vn/v2`
### Callback Processing
### Xử Lý Callback
**Webhook URL Pattern**: `/payments/callback/{provider}`
**Mẫu URL Webhook**: `/payments/callback/{provider}`
Supports both:
Hỗ trợ cả:
- Query parameters (VNPay)
- Request body (MoMo, ZaloPay)
- Merged data handling internally
- Xử lý dữ liệu hợp nhất nội bộ
---
## 🔍 SEARCH MODULE
## 🔍 MODULE SEARCH
### Controllers & Endpoints
#### File: `apps/api/src/modules/search/presentation/controllers/search.controller.ts`
| Method | Endpoint | Auth | Description |
| Method | Endpoint | Auth | Mô tả |
|--------|----------|------|-------------|
| GET | `/search` | No | Full-text search (public) |
| GET | `/search/geo` | No | Geographic radius search (public) |
| POST | `/search/reindex` | JWT+Admin | Reindex all properties (admin) |
| GET | `/search` | Không | Tìm kiếm full-text (công khai) |
| GET | `/search/geo` | Không | Tìm kiếm theo bán kính địa lý (công khai) |
| POST | `/search/reindex` | JWT+Admin | Lập chỉ mục lại tất cả bất động sản (admin) |
### DTOs
#### SearchPropertiesDto (Full-text search)
#### SearchPropertiesDto (Tìm kiếm full-text)
```typescript
{
q?: string, // Free-text query, e.g., 'chung cu quan 7'
@@ -365,7 +365,7 @@ Supports both:
}
```
#### GeoSearchDto (Geographic search)
#### GeoSearchDto (Tìm kiếm địa lý)
```typescript
{
lat: number, // Latitude, -90 to 90
@@ -383,11 +383,11 @@ Supports both:
### Search Engine
**Typesense** integration for fast full-text & faceted search
Tích hợp **Typesense** cho tìm kiếm full-text & faceted nhanh
- Environment: `TYPESENSE_HOST`, `TYPESENSE_PORT`, `TYPESENSE_API_KEY`
- Default: `http://localhost:8108`
- Mặc định: `http://localhost:8108`
### Response Structure
### Cấu Trúc Phản Hồi
#### SearchResult
```typescript
@@ -409,7 +409,7 @@ Supports both:
## 🗄️ Database & Environment
### PostgreSQL with PostGIS
### PostgreSQL với PostGIS
```
DB_HOST=localhost
@@ -426,7 +426,7 @@ DATABASE_URL=postgresql://goodgo:password@localhost:5432/goodgo?schema=public
REDIS_URL=redis://localhost:6379
```
### Key Environment Variables
### Các Biến Môi Trường Chính
```bash
# JWT Secrets (REQUIRED)
@@ -472,9 +472,9 @@ LOG_LEVEL=info
---
## 🧪 Existing Test Setup
## 🧪 Thiết Lập Test Hiện Có
### Playwright Configuration
### Cấu Hình Playwright
**File**: `playwright.config.ts`
@@ -490,7 +490,7 @@ Projects:
baseURL: http://localhost:3000
```
### Playwright Scripts
### Các Script Playwright
```bash
pnpm test:e2e # Run all E2E tests
@@ -499,14 +499,14 @@ pnpm test:e2e:web # Web tests only
pnpm test:e2e:report # Show HTML report
```
### Test Database
### Database Test
- CI uses `goodgo_test` database
- Local uses `.env.test` for test database URL
- Migrations & seed run in `global-setup.ts`
- Cleanup in `global-teardown.ts`
- CI sử dụng database `goodgo_test`
- Local sử dụng `.env.test` cho URL database test
- Migration & seed chạy trong `global-setup.ts`
- Dọn dẹp trong `global-teardown.ts`
### Example E2E Test
### Ví Dụ E2E Test
**File**: `e2e/api/auth-register.spec.ts`
@@ -536,51 +536,51 @@ pnpm test:integration # Integration tests
---
## 🔄 CI/CD Setup
## 🔄 Thiết Lập CI/CD
### GitHub Actions Workflows
### Workflow GitHub Actions
#### `ci.yml` - Lint → Typecheck → Test → Build
- Runs on: `push main` and `pull_request`
- Chạy khi: `push main` `pull_request`
- Services: PostgreSQL 16 + PostGIS
- Steps: lint → typecheck → test → build
- Các bước: lint → typecheck → test → build
#### `e2e.yml` - Playwright E2E Tests
- Runs on: `push main` and `pull_request`
- Chạy khi: `push main` `pull_request`
- Services:
- PostgreSQL 16 + PostGIS
- Redis 7
- Typesense 27.1
- MinIO (S3-compatible storage)
- MinIO (lưu trữ tương thích S3)
- Artifacts: HTML report + traces
#### `security.yml` - Code Security
- Dependency scanning
- SAST analysis
#### `security.yml` - Bảo Mật Mã Nguồn
- Quét dependency
- Phân tích SAST
#### `deploy.yml` - Production Deployment
- Docker builds
- Registry push
- Deployment orchestration
#### `deploy.yml` - Triển Khai Production
- Build Docker
- Push registry
- Điều phối triển khai
---
## 📊 Architecture Patterns
## 📊 Mẫu Kiến Trúc
### NestJS CQRS Pattern
### Mẫu CQRS NestJS
Each module uses:
- **Commands** (Write operations)
Mỗi module sử dụng:
- **Commands** (Thao tác ghi)
- `CommandBus.execute(command)`
- Located in `application/commands/`
- Handlers in `application/commands/{command}/`
- Đặt trong `application/commands/`
- Handlers trong `application/commands/{command}/`
- **Queries** (Read operations)
- **Queries** (Thao tác đọc)
- `QueryBus.execute(query)`
- Located in `application/queries/`
- Handlers in `application/queries/{query}/`
- Đặt trong `application/queries/`
- Handlers trong `application/queries/{query}/`
Example:
Ví dụ:
```typescript
// In controller
const result = await this.commandBus.execute(
@@ -594,17 +594,17 @@ const profile = await this.queryBus.execute(
### Guards & Interceptors
- `JwtAuthGuard` - Validates JWT token
- `LocalAuthGuard` - Email/password validation
- `RolesGuard` - Role-based access control
- `QuotaGuard` - Subscription quota enforcement
- `FileValidationPipe` - File upload validation
- `JwtAuthGuard` - Xác thực JWT token
- `LocalAuthGuard` - Xác thực email/mật khẩu
- `RolesGuard` - Kiểm soát truy cập dựa trên vai trò
- `QuotaGuard` - Thi hành hạn ngạch subscription
- `FileValidationPipe` - Xác thực file upload
---
## 🚀 Starting the API
## 🚀 Khởi Động API
### Local Development
### Phát Triển Cục Bộ
```bash
# Install dependencies
@@ -627,7 +627,7 @@ pnpm dev
# Swagger UI: http://localhost:3001/api/v1/docs
```
### With Docker
### Với Docker
```bash
docker-compose up
@@ -636,37 +636,37 @@ docker-compose up
---
## 🎯 K6 Load Testing Recommendations
## 🎯 Khuyến Nghị K6 Load Testing
### Key Endpoints to Test
### Các Endpoint Chính Cần Test
1. **Authentication** (High priority)
1. **Authentication** (Ưu tiên cao)
- Register: `POST /auth/register`
- Login: `POST /auth/login`
- Refresh: `POST /auth/refresh`
- Profile: `GET /auth/profile` (authenticated)
- Profile: `GET /auth/profile` (đã xác thực)
2. **Listings** (High priority)
- Create: `POST /listings` (quota-gated)
- Search: `GET /listings` (public, high volume)
- Detail: `GET /listings/:id` (public, high volume)
2. **Listings** (Ưu tiên cao)
- Create: `POST /listings` (giới hạn quota)
- Search: `GET /listings` (công khai, lưu lượng cao)
- Detail: `GET /listings/:id` (công khai, lưu lượng cao)
3. **Search** (High priority)
- Full-text: `GET /search?q=...` (public, high volume)
- Geo: `GET /search/geo?lat=...&lng=...` (public, high volume)
3. **Search** (Ưu tiên cao)
- Full-text: `GET /search?q=...` (công khai, lưu lượng cao)
- Geo: `GET /search/geo?lat=...&lng=...` (công khai, lưu lượng cao)
4. **Payments** (Medium priority)
- Create: `POST /payments` (authenticated)
- List: `GET /payments` (authenticated)
- Webhook: `POST /payments/callback/:provider` (unthrottled)
4. **Payments** (Ưu tiên trung bình)
- Create: `POST /payments` (đã xác thực)
- List: `GET /payments` (đã xác thực)
- Webhook: `POST /payments/callback/:provider` (không giới hạn throttle)
5. **Admin Endpoints** (Medium priority, restricted)
- Moderate listings: `PATCH /listings/:id/moderate`
- List pending: `GET /listings/pending`
- Verify KYC: `PATCH /auth/kyc`
5. **Endpoint Admin** (Ưu tiên trung bình, hạn chế)
- Kiểm duyệt listing: `PATCH /listings/:id/moderate`
- Liệt kê pending: `GET /listings/pending`
- Xác minh KYC: `PATCH /auth/kyc`
- Reindex: `POST /search/reindex`
### K6 Script Structure
### Cấu Trúc Script K6
```javascript
import http from 'k6/http';
@@ -692,16 +692,16 @@ export default function() {
}
```
### Data Generation Tips
### Mẹo Tạo Dữ Liệu
- Use test fixture users from Playwright tests
- Leverage Prisma seed data (districts, property types)
- Generate realistic search queries
- Test with various geo coordinates (Ho Chi Minh City: ~10.77°N, 106.70°E)
- Sử dụng test fixture user từ Playwright tests
- Tận dụng dữ liệu Prisma seed (quận, loại bất động sản)
- Tạo các truy vấn tìm kiếm thực tế
- Test với các tọa độ địa lý khác nhau (TP.HCM: ~10.77°N, 106.70°E)
---
## 📁 File Locations Quick Reference
## 📁 Tham Khảo Nhanh Vị Trí File
```
apps/api/
@@ -768,38 +768,37 @@ playwright.config.ts # Playwright config
---
## 🔗 Useful Links & References
## 🔗 Liên Kết & Tham Khảo Hữu Ích
- **API Swagger Docs**: `http://localhost:3001/api/v1/docs`
- **Project Root Docs**: `CLAUDE.md`
- **Existing Analysis**: `CODEBASE_ANALYSIS.md`, `EXPLORATION_REPORT.md`
- **Frontend Docs**: `docs/audits/FRONTEND_EXPLORATION.md`
- **Tài Liệu Gốc Dự Án**: `CLAUDE.md`
- **Phân Tích Hiện Có**: `CODEBASE_ANALYSIS.md`, `EXPLORATION_REPORT.md`
- **Tài Liệu Frontend**: `docs/audits/FRONTEND_EXPLORATION.md`
---
## ✅ Summary for K6 Implementation
## ✅ Tóm Tắt Triển Khai K6
**No existing K6 setup** — you have a clean slate!
**Chưa có thiết lập K6 nào** — bạn có một khởi đầu hoàn toàn mới!
**Key endpoints** identified across:
**Các endpoint chính** được xác định trên các module:
- Auth (register, login, refresh, profile)
- Listings (create, search, detail, moderate)
- Search (full-text, geo)
- Payments (create, callback, list, refund)
- Admin (moderate, KYC, reindex)
**Rate limits** to consider:
- Auth: 5/hour per endpoint
- Payments callback: 20/min
- Others: No limit (except quota guards on create operations)
**Rate limit** cần xem xét:
- Auth: 5/giờ mỗi endpoint
- Payments callback: 20/phút
- Khác: Không giới hạn (trừ quota guard cho thao tác create)
**Infrastructure ready**:
- Turbo monorepo for dependency management
- PostgreSQL + PostGIS for spatial data
- Typesense for search indexing
- Redis for caching
- MinIO for media storage
- Prometheus metrics endpoint
**Tests can be integrated** into CI/CD pipeline via `.github/workflows/` (suggested: new `load-test.yml`)
**Hạ tầng sẵn sàng**:
- Turbo monorepo cho quản lý dependency
- PostgreSQL + PostGIS cho dữ liệu không gian
- Typesense cho lập chỉ mục tìm kiếm
- Redis cho caching
- MinIO cho lưu trữ media
- Endpoint Prometheus metrics
**Tests có thể được tích hợp** vào CI/CD pipeline qua `.github/workflows/` (đề xuất: `load-test.yml` mới)

View File

@@ -1,10 +1,10 @@
# K6 Load Testing — Quick Start Guide
# K6 Load Testing — Hướng Dẫn Bắt Đầu Nhanh
Get started with K6 load tests for GoodGo Platform API in minutes.
Bắt đầu với K6 load tests cho GoodGo Platform API trong vài phút.
---
## 1Installation
## 1Cài Đặt
### macOS
```bash
@@ -21,16 +21,16 @@ apt-get install k6
docker pull grafana/k6:latest
```
### Verify Installation
### Xác Minh Cài Đặt
```bash
k6 version
```
---
## 2Setup Test Environment
## 2Thiết Lập Môi Trường Test
### Start API & Database
### Khởi Động API & Database
```bash
# Terminal 1: Start all services
pnpm dev
@@ -39,7 +39,7 @@ pnpm dev
pnpm db:seed
```
### Verify API is Running
### Xác Minh API Đang Chạy
```bash
curl http://localhost:3001/api/v1/docs
# Should return Swagger UI
@@ -47,11 +47,11 @@ curl http://localhost:3001/api/v1/docs
---
## 3Create Your First K6 Test
## 3Tạo Test K6 Đầu Tiên
### Simple Search Load Test
### Search Load Test Đơn Giản
Create file: `load-tests/search.k6.js`
Tạo file: `load-tests/search.k6.js`
```javascript
import http from 'k6/http';
@@ -101,19 +101,19 @@ export default function() {
---
## 4Run Your First Test
## 4Chạy Test Đầu Tiên
### Local Development
### Phát Triển Cục Bộ
```bash
k6 run load-tests/search.k6.js
```
### With Custom Base URL
### Với Base URL Tùy Chỉnh
```bash
BASE_URL=http://localhost:3001/api/v1 k6 run load-tests/search.k6.js
```
### With Docker
### Với Docker
```bash
docker run -i grafana/k6 run - < load-tests/search.k6.js
```
@@ -145,9 +145,9 @@ docker run -i grafana/k6 run - < load-tests/search.k6.js
---
## 5⃣ Authentication Test
## 5 Test Authentication
Create file: `load-tests/auth.k6.js`
Tạo file: `load-tests/auth.k6.js`
```javascript
import http from 'k6/http';
@@ -212,16 +212,16 @@ export default function() {
}
```
### Run Auth Test
### Chạy Auth Test
```bash
k6 run load-tests/auth.k6.js
```
---
## 6Listing Creation Test (Authenticated)
## 6Test Tạo Listing (Đã Xác Thực)
Create file: `load-tests/listings.k6.js`
Tạo file: `load-tests/listings.k6.js`
```javascript
import http from 'k6/http';
@@ -319,16 +319,16 @@ export default function() {
}
```
### Run Listing Test
### Chạy Listing Test
```bash
k6 run load-tests/listings.k6.js
```
---
## 7⃣ Payment Test
## 7 Test Payment
Create file: `load-tests/payments.k6.js`
Tạo file: `load-tests/payments.k6.js`
```javascript
import http from 'k6/http';
@@ -404,16 +404,16 @@ export default function() {
}
```
### Run Payment Test
### Chạy Payment Test
```bash
k6 run load-tests/payments.k6.js
```
---
## 8Run All Tests with Results
## 8Chạy Tất Cả Tests Với Kết Quả
Create file: `load-tests/all-scenarios.k6.js`
Tạo file: `load-tests/all-scenarios.k6.js`
```javascript
import http from 'k6/http';
@@ -472,7 +472,7 @@ export default function() {
}
```
### Run with Summary
### Chạy Với Tóm Tắt
```bash
k6 run load-tests/all-scenarios.k6.js \
--vus=50 \
@@ -482,21 +482,21 @@ k6 run load-tests/all-scenarios.k6.js \
---
## 9Generate Reports
## 9Tạo Báo Cáo
### JSON Report
### Báo Cáo JSON
```bash
k6 run load-tests/search.k6.js --summary-export=report.json
```
### Upload to Grafana Cloud
### Tải Lên Grafana Cloud
```bash
k6 run load-tests/search.k6.js \
--out cloud
# Requires: k6 login or K6_CLOUD_TOKEN env var
```
### Generate HTML Report (with extension)
### Tạo Báo Cáo HTML (với extension)
```bash
k6 run load-tests/search.k6.js \
--out csv=results.csv
@@ -504,9 +504,9 @@ k6 run load-tests/search.k6.js \
---
## 🔟 CI Integration
## 🔟 Tích Hợp CI
Create: `.github/workflows/load-test.yml`
Tạo: `.github/workflows/load-test.yml`
```yaml
name: Load Tests
@@ -576,7 +576,7 @@ jobs:
---
## 📊 Common K6 Checks
## 📊 Các Check K6 Phổ Biến
```javascript
// HTTP Status
@@ -605,55 +605,55 @@ check(res, {
---
## 🛠️ Debugging
## 🛠️ Debug
### Verbose Output
### Output Chi Tiết
```bash
k6 run -v load-tests/search.k6.js
```
### Show Request/Response
### Hiển Thị Request/Response
```bash
k6 run --http-debug=full load-tests/search.k6.js
```
### Limit to Single VU
### Giới Hạn Một VU
```bash
k6 run --vus=1 --iterations=1 load-tests/search.k6.js
```
---
## 📚 Next Steps
## 📚 Bước Tiếp Theo
1. **Read Full Guide**: `K6_LOAD_TESTING_GUIDE.md`
2. **Check Endpoints**: `K6_ENDPOINTS_SUMMARY.md`
3. **Explore K6 Docs**: https://k6.io/docs
4. **Community Scripts**: https://github.com/grafana/k6-templates
1. **Đọc Hướng Dẫn Đầy Đủ**: `K6_LOAD_TESTING_GUIDE.md`
2. **Kiểm Tra Endpoint**: `K6_ENDPOINTS_SUMMARY.md`
3. **Khám Phá Tài Liệu K6**: https://k6.io/docs
4. **Script Cộng Đồng**: https://github.com/grafana/k6-templates
---
## ✅ Troubleshooting
## ✅ Xử Lý Sự Cố
### "connection refused"
- Ensure API is running: `pnpm dev`
- Check port: 3001
- Verify BASE_URL: `http://localhost:3001/api/v1`
- Đảm bảo API đang chạy: `pnpm dev`
- Kiểm tra port: 3001
- Xác minh BASE_URL: `http://localhost:3001/api/v1`
### "rate limit exceeded"
- Auth endpoints: 5/hour limit
- Spread requests or use different test data
- Check test database has seed data
- Endpoint auth: giới hạn 5/giờ
- Phân tán request hoặc dùng dữ liệu test khác
- Kiểm tra database test có dữ liệu seed
### "insufficient credits" (payments)
- Payments require authenticated user
- Create user session first in test
- Use test provider credentials
- Payment yêu cầu người dùng đã xác thực
- Tạo phiên người dùng trước trong test
- Sử dụng thông tin xác thực provider test
### "timeout"
- Increase K6 timeout in options
- Check API logs for errors
- Reduce number of VUs initially
- Tăng K6 timeout trong options
- Kiểm tra log API để tìm lỗi
- Giảm số lượng VU ban đầu
---

View File

@@ -1,75 +1,75 @@
# K6 Load Testing Documentation for GoodGo Platform
# Tài Liệu K6 Load Testing cho GoodGo Platform
Complete guide to understanding and implementing K6 load tests for the GoodGo Platform API.
Hướng dẫn đầy đủ để hiểu và triển khai K6 load tests cho GoodGo Platform API.
---
## 📚 Documentation Files
## 📚 Các File Tài Liệu
This directory contains three comprehensive guides for K6 load testing:
Thư mục này chứa ba hướng dẫn toàn diện về K6 load testing:
### 1. **K6_LOAD_TESTING_GUIDE.md** (Primary Reference)
Comprehensive exploration of the GoodGo Platform API structure for load testing.
### 1. **K6_LOAD_TESTING_GUIDE.md** (Tham Khảo Chính)
Khám phá toàn diện cấu trúc GoodGo Platform API cho load testing.
**Contents:**
- API module structure (auth, listings, payments, search)
- Detailed endpoint documentation with HTTP methods, rate limits, and auth requirements
- Complete DTO specifications with request/response body shapes
- Database and environment configuration reference
- Existing test setup (Playwright, Vitest, CI/CD)
- Architecture patterns (CQRS, DDD)
- File location quick reference
- K6 implementation recommendations
**Nội dung:**
- Cấu trúc module API (auth, listings, payments, search)
- Tài liệu endpoint chi tiết với HTTP method, rate limit và yêu cầu auth
- Đặc tả DTO đầy đủ với hình dạng request/response body
- Tham khảo cấu hình database environment
- Thiết lập test hiện có (Playwright, Vitest, CI/CD)
- Mẫu kiến trúc (CQRS, DDD)
- Tham khảo nhanh vị trí file
- Khuyến nghị triển khai K6
**When to use:** Deep dives into specific endpoints, understanding authentication flows, checking environment variables
**Khi nào sử dụng:** Khi cần đào sâu vào các endpoint cụ thể, hiểu luồng xác thực, kiểm tra biến môi trường
### 2. **K6_ENDPOINTS_SUMMARY.md** (Quick Reference)
Condensed endpoint reference with data shapes for immediate lookup.
### 2. **K6_ENDPOINTS_SUMMARY.md** (Tham Khảo Nhanh)
Tham khảo endpoint cô đọng với hình dạng dữ liệu để tra cứu ngay lập tức.
**Contents:**
- All endpoints in table format (method, path, auth, rate limit)
- Authentication module (register, login, refresh, profile)
- Listings module (CRUD, moderation, media upload)
- Payments module (create, list, callbacks, refund)
- Search module (full-text, geo)
- Request/response body examples (JSON)
- K6 test scenarios (search, auth, listings, payments, webhooks)
- Rate limits summary
- Authentication flow examples (cookies vs tokens)
**Nội dung:**
- Tất cả endpoint dưới dạng bảng (method, path, auth, rate limit)
- Module Authentication (register, login, refresh, profile)
- Module Listings (CRUD, kiểm duyệt, upload media)
- Module Payments (create, list, callback, refund)
- Module Search (full-text, geo)
- Ví dụ request/response body (JSON)
- Các kịch bản test K6 (search, auth, listings, payments, webhook)
- Tóm tắt rate limit
- Ví dụ luồng xác thực (cookies vs tokens)
**When to use:** Quick lookup of endpoint details, copy-paste example payloads, understanding rate limits
**Khi nào sử dụng:** Tra cứu nhanh chi tiết endpoint, sao chép payload mẫu, hiểu rate limit
### 3. **K6_QUICK_START.md** (Executable Examples)
Step-by-step guide with ready-to-run K6 scripts and setup instructions.
### 3. **K6_QUICK_START.md** (Ví Dụ Chạy Được)
Hướng dẫn từng bước với script K6 sẵn sàng chạy và hướng dẫn thiết lập.
**Contents:**
- Installation instructions (macOS, Linux, Docker)
- Environment setup (starting API, seeding database)
- Five runnable K6 scripts:
- Search load test (public, high volume)
- Auth load test (rate-limited registration)
- Listing creation (authenticated, quota-gated)
- Payment processing (authenticated)
- All scenarios combined
- CI integration with GitHub Actions
- Report generation options (JSON, Grafana Cloud, CSV)
- Common K6 checks and patterns
- Debugging and troubleshooting
**Nội dung:**
- Hướng dẫn cài đặt (macOS, Linux, Docker)
- Thiết lập môi trường (khởi động API, seed database)
- Năm script K6 chạy được:
- Search load test (công khai, lưu lượng cao)
- Auth load test (đăng ký bị giới hạn rate)
- Tạo listing (đã xác thực, giới hạn quota)
- Xử lý payment (đã xác thực)
- Tất cả kịch bản kết hợp
- Tích hợp CI với GitHub Actions
- Tùy chọn tạo báo cáo (JSON, Grafana Cloud, CSV)
- Các check K6 và mẫu phổ biến
- Debug và xử lý sự cố
**When to use:** Getting started quickly, running tests immediately, setting up CI/CD
**Khi nào sử dụng:** Bắt đầu nhanh, chạy test ngay, thiết lập CI/CD
---
## 🚀 Quick Start (3 Minutes)
## 🚀 Bắt Đầu Nhanh (3 Phút)
### 1. Install K6
### 1. Cài Đặt K6
```bash
brew install k6 # macOS
# or
apt-get install k6 # Linux
```
### 2. Start API & Database
### 2. Khởi Động API & Database
```bash
pnpm install
pnpm db:generate
@@ -78,39 +78,39 @@ pnpm db:seed
pnpm dev
```
### 3. Run a Load Test
### 3. Chạy Load Test
```bash
# Copy this from K6_QUICK_START.md Step 3
k6 run load-tests/search.k6.js
```
### 4. View Results
K6 prints a summary to console. For more detailed reports, see K6_QUICK_START.md section on report generation.
### 4. Xem Kết Quả
K6 in tóm tắt ra console. Để xem báo cáo chi tiết hơn, xem mục tạo báo cáo trong K6_QUICK_START.md.
---
## 📊 Test Scenarios Implemented
## 📊 Các Kịch Bản Test Đã Triển Khai
| Scenario | File | Focus | VUs | Duration | Key Endpoints |
| Kịch Bản | File | Trọng Tâm | VUs | Thời Lượng | Endpoint Chính |
|----------|------|-------|-----|----------|--------------|
| Search Load | `load-tests/search.k6.js` | Public search performance | 50 | 4m | `GET /search`, `GET /search/geo` |
| Authentication | `load-tests/auth.k6.js` | Auth throughput & rate limits | 10 | 2m | `POST /auth/register`, `POST /auth/login` |
| Listing Creation | `load-tests/listings.k6.js` | Authenticated listing CRUD | 5 | 2m | `POST /listings`, `GET /listings/:id` |
| Payments | `load-tests/payments.k6.js` | Payment initiation & status | 10 | 2m | `POST /payments`, `GET /payments/:id` |
| Combined | `load-tests/all-scenarios.k6.js` | Realistic mixed load | 50 | 5m | Multiple endpoints |
| Search Load | `load-tests/search.k6.js` | Hiệu suất tìm kiếm công khai | 50 | 4m | `GET /search`, `GET /search/geo` |
| Authentication | `load-tests/auth.k6.js` | Throughput auth & rate limit | 10 | 2m | `POST /auth/register`, `POST /auth/login` |
| Tạo Listing | `load-tests/listings.k6.js` | CRUD listing đã xác thực | 5 | 2m | `POST /listings`, `GET /listings/:id` |
| Payments | `load-tests/payments.k6.js` | Khởi tạo & trạng thái thanh toán | 10 | 2m | `POST /payments`, `GET /payments/:id` |
| Combined | `load-tests/all-scenarios.k6.js` | Tải hỗn hợp thực tế | 50 | 5m | Nhiều endpoint |
---
## 🔐 Authentication Methods
## 🔐 Phương Thức Xác Thực
### Option 1: Cookie-Based (Recommended for Browser-Like Tests)
### Tùy Chọn 1: Dựa Trên Cookie (Khuyến nghị cho test giống trình duyệt)
```javascript
const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password });
// Cookies automatically managed by K6
const profileRes = http.get(`${BASE_URL}/auth/profile`);
```
### Option 2: Bearer Token (Recommended for API-Only Tests)
### Tùy Chọn 2: Bearer Token (Khuyến nghị cho test chỉ API)
```javascript
const loginRes = http.post(`${BASE_URL}/auth/login`, { phone, password });
const { accessToken } = loginRes.json();
@@ -118,40 +118,40 @@ const headers = { Authorization: `Bearer ${accessToken}` };
const profileRes = http.get(`${BASE_URL}/auth/profile`, { headers });
```
See K6_ENDPOINTS_SUMMARY.md for full examples.
Xem K6_ENDPOINTS_SUMMARY.md để xem ví dụ đầy đủ.
---
## 🎯 Key Endpoints by Priority
## 🎯 Endpoint Chính Theo Mức Ưu Tiên
### High Priority (Core Functionality)
| Endpoint | Priority | Why |
### Ưu Tiên Cao (Chức Năng Cốt Lõi)
| Endpoint | Ưu Tiên | Tại sao |
|----------|----------|-----|
| `GET /search` | ⭐⭐⭐ | Public, high-volume query |
| `GET /search/geo` | ⭐⭐⭐ | Geospatial, frequently used |
| `GET /listings` | ⭐⭐⭐ | Public search/filter |
| `GET /listings/:id` | ⭐⭐⭐ | Detail page load |
| `POST /auth/login` | ⭐⭐ | User session creation |
| `POST /auth/register` | ⭐⭐ | Rate-limited, important |
| `GET /search` | ⭐⭐⭐ | Công khai, truy vấn lưu lượng cao |
| `GET /search/geo` | ⭐⭐⭐ | Địa không gian, dùng thường xuyên |
| `GET /listings` | ⭐⭐⭐ | Tìm/lọc công khai |
| `GET /listings/:id` | ⭐⭐⭐ | Tải trang chi tiết |
| `POST /auth/login` | ⭐⭐ | Tạo phiên người dùng |
| `POST /auth/register` | ⭐⭐ | Bị giới hạn rate, quan trọng |
### Medium Priority (Feature-Specific)
| Endpoint | Priority | Why |
### Ưu Tiên Trung Bình (Tính Năng Cụ Thể)
| Endpoint | Ưu Tiên | Tại sao |
|----------|----------|-----|
| `POST /listings` | ⭐⭐ | Quota-gated, authenticated |
| `POST /payments` | ⭐⭐ | External integrations |
| `GET /payments` | ⭐⭐ | User transaction history |
| `POST /payments/callback/:provider` | ⭐⭐ | Webhook handler, critical |
| `POST /listings` | ⭐⭐ | Bị giới hạn quota, đã xác thực |
| `POST /payments` | ⭐⭐ | Tích hợp bên ngoài |
| `GET /payments` | ⭐⭐ | Lịch sử giao dịch người dùng |
| `POST /payments/callback/:provider` | ⭐⭐ | Webhook handler, then chốt |
### Low Priority (Admin/Specialized)
| Endpoint | Priority | Why |
### Ưu Tiên Thấp (Admin/Chuyên Biệt)
| Endpoint | Ưu Tiên | Tại sao |
|----------|----------|-----|
| `PATCH /listings/:id/moderate` | ⭐ | Admin-only |
| `GET /listings/pending` | ⭐ | Admin-only |
| `POST /search/reindex` | ⭐ | Admin-only, scheduled |
| `PATCH /listings/:id/moderate` | ⭐ | Chỉ admin |
| `GET /listings/pending` | ⭐ | Chỉ admin |
| `POST /search/reindex` | ⭐ | Chỉ admin, có lịch |
---
## 📍 API Structure at a Glance
## 📍 Tổng Quan Cấu Trúc API
```
API Base: http://localhost:3001/api/v1
@@ -168,9 +168,9 @@ Modules:
---
## 🗄️ Database Configuration
## 🗄️ Cấu Hình Database
### Local Development
### Phát Triển Cục Bộ
```bash
DATABASE_URL=postgresql://goodgo:password@localhost:5432/goodgo
REDIS_URL=redis://localhost:6379
@@ -178,7 +178,7 @@ TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
```
### Test Environment (CI)
### Môi Trường Test (CI)
```bash
DATABASE_URL=postgresql://goodgo:goodgo_test_secret@localhost:5432/goodgo_test
REDIS_URL=redis://localhost:6379
@@ -186,23 +186,23 @@ TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
```
See K6_LOAD_TESTING_GUIDE.md for full environment variables.
Xem K6_LOAD_TESTING_GUIDE.md để biết đầy đủ biến môi trường.
---
## ⚡ Rate Limits
## ⚡ Rate Limit
Respect these limits in your load tests:
Tôn trọng các giới hạn này trong load test của bạn:
| Endpoint | Limit | Window | Action on Exceeded |
| Endpoint | Limit | Cửa Sổ | Hành Động Khi Vượt |
|----------|-------|--------|-------------------|
| `/auth/register` | 5 | per hour | Returns 429 |
| `/auth/login` | 5 | per hour | Returns 429 |
| `/auth/refresh` | 5 | per hour | Returns 429 |
| `/payments/callback/*` | 20 | per minute | Returns 429 |
| All others | None | N/A | Quota gates apply for writes |
| `/auth/register` | 5 | mỗi giờ | Trả về 429 |
| `/auth/login` | 5 | mỗi giờ | Trả về 429 |
| `/auth/refresh` | 5 | mỗi giờ | Trả về 429 |
| `/payments/callback/*` | 20 | mỗi phút | Trả về 429 |
| Tất cả khác | Không có | N/A | Quota gate áp dụng cho thao tác ghi |
**K6 Handling:**
**Xử Lý K6:**
```javascript
check(res, {
'status not rate limited': (r) => r.status !== 429,
@@ -212,7 +212,7 @@ check(res, {
---
## 🏗️ Recommended Test Structure
## 🏗️ Cấu Trúc Test Đề Xuất
```
load-tests/
@@ -228,24 +228,24 @@ load-tests/
└── config.js # Base URL, env, thresholds
```
Example helper structure provided in K6_QUICK_START.md.
Cấu trúc helper mẫu được cung cấp trong K6_QUICK_START.md.
---
## 🧪 Integration with Existing Tests
## 🧪 Tích Hợp Với Các Test Hiện Có
### Complement, Don't Replace
### Bổ Sung, Không Thay Thế
K6 is for **load testing** (performance under concurrent load).
Existing tests serve different purposes:
K6 dành cho **load testing** (hiệu suất dưới tải đồng thời).
Các test hiện có phục vụ các mục đích khác:
| Test Type | Tool | Purpose | When |
| Loại Test | Công Cụ | Mục Đích | Khi Nào |
|-----------|------|---------|------|
| Unit Tests | Vitest | Verify function logic | During development |
| E2E Tests | Playwright | Verify user flows work | Before deployment |
| Load Tests | K6 | Verify performance at scale | Scheduled, on-demand |
| Unit Tests | Vitest | Xác minh logic hàm | Trong quá trình phát triển |
| E2E Tests | Playwright | Xác minh luồng người dùng hoạt động | Trước khi triển khai |
| Load Tests | K6 | Xác minh hiệu suất ở quy mô lớn | Theo lịch, theo yêu cầu |
### Running All Tests
### Chạy Tất Cả Test
```bash
# Unit tests (API only)
@@ -263,11 +263,11 @@ pnpm test && pnpm test:e2e && k6 run load-tests/all-scenarios.k6.js
---
## 📈 CI/CD Integration
## 📈 Tích Hợp CI/CD
### GitHub Actions Workflow
### Workflow GitHub Actions
Create `.github/workflows/load-test.yml` (template in K6_QUICK_START.md section 🔟):
Tạo `.github/workflows/load-test.yml` (mẫu trong K6_QUICK_START.md mục 🔟):
```bash
# Runs on schedule (daily at 2 AM)
@@ -275,7 +275,7 @@ Create `.github/workflows/load-test.yml` (template in K6_QUICK_START.md section
# Reports results as artifacts
```
### Manual Reporting
### Báo Cáo Thủ Công
```bash
# Export JSON
@@ -290,74 +290,74 @@ K6_CLOUD_TOKEN=xxx k6 run load-tests/search.k6.js --out cloud
---
## 🔗 Cross-Reference Guide
## 🔗 Hướng Dẫn Tham Chiếu Chéo
### Looking for...?
### Đang tìm kiếm...?
| Need | Find in |
| Cần | Tìm trong |
|------|----------|
| All endpoint URLs & methods | K6_ENDPOINTS_SUMMARY.md |
| Request/response JSON shapes | K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes) |
| DTOs & validation rules | K6_LOAD_TESTING_GUIDE.md (Controllers & DTOs) |
| Rate limit specifics | K6_ENDPOINTS_SUMMARY.md (📌 Important Rate Limits) |
| Authentication flows | K6_ENDPOINTS_SUMMARY.md (🔗 Authentication Flow for K6) |
| Database variables | K6_LOAD_TESTING_GUIDE.md (🗄️ Database & Environment) |
| Ready-to-run scripts | K6_QUICK_START.md (Steps 3-8⃣) |
| CI/CD setup | K6_QUICK_START.md (Step 🔟) |
| Troubleshooting | K6_QUICK_START.md (✅ Troubleshooting) |
| Architecture details | K6_LOAD_TESTING_GUIDE.md (📊 Architecture Patterns) |
| File locations | K6_LOAD_TESTING_GUIDE.md (📁 File Locations Quick Reference) |
| Tất cả URL & method endpoint | K6_ENDPOINTS_SUMMARY.md |
| Hình dạng JSON request/response | K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes) |
| DTO & quy tắc validation | K6_LOAD_TESTING_GUIDE.md (Controllers & DTOs) |
| Chi tiết rate limit | K6_ENDPOINTS_SUMMARY.md (📌 Important Rate Limits) |
| Luồng xác thực | K6_ENDPOINTS_SUMMARY.md (🔗 Authentication Flow for K6) |
| Biến database | K6_LOAD_TESTING_GUIDE.md (🗄️ Database & Environment) |
| Script sẵn sàng chạy | K6_QUICK_START.md (Steps 3-8⃣) |
| Thiết lập CI/CD | K6_QUICK_START.md (Step 🔟) |
| Xử lý sự cố | K6_QUICK_START.md (✅ Troubleshooting) |
| Chi tiết kiến trúc | K6_LOAD_TESTING_GUIDE.md (📊 Architecture Patterns) |
| Vị trí file | K6_LOAD_TESTING_GUIDE.md (📁 File Locations Quick Reference) |
---
## 🛠️ Common Tasks
## 🛠️ Công Việc Phổ Biến
### Task: Load Test Search Endpoint
1. Read: K6_ENDPOINTS_SUMMARY.md (🔍 Search section)
2. Use: K6_QUICK_START.md (Step 3⃣ - Search Load Test)
3. Run: `k6 run load-tests/search.k6.js`
### Công Việc: Load Test Endpoint Search
1. Đọc: K6_ENDPOINTS_SUMMARY.md (mục 🔍 Search)
2. Sử dụng: K6_QUICK_START.md (Bước 3⃣ - Search Load Test)
3. Chạy: `k6 run load-tests/search.k6.js`
### Task: Understand Payment Flow
1. Read: K6_LOAD_TESTING_GUIDE.md (💳 PAYMENTS MODULE)
2. Check: K6_ENDPOINTS_SUMMARY.md (💳 Payments section)
3. Use: K6_QUICK_START.md (Step 7⃣ - Payment Test)
### Công Việc: Hiểu Luồng Payment
1. Đọc: K6_LOAD_TESTING_GUIDE.md (💳 PAYMENTS MODULE)
2. Kiểm tra: K6_ENDPOINTS_SUMMARY.md (mục 💳 Payments)
3. Sử dụng: K6_QUICK_START.md (Bước 7⃣ - Payment Test)
### Task: Add New Endpoint to Load Tests
1. Find endpoint in: K6_LOAD_TESTING_GUIDE.md or K6_ENDPOINTS_SUMMARY.md
2. Get data shape from: K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes)
3. Check auth from: K6_LOAD_TESTING_GUIDE.md (each module section)
4. Implement using examples in: K6_QUICK_START.md
### Công Việc: Thêm Endpoint Mới Vào Load Tests
1. Tìm endpoint trong: K6_LOAD_TESTING_GUIDE.md hoặc K6_ENDPOINTS_SUMMARY.md
2. Lấy hình dạng dữ liệu từ: K6_ENDPOINTS_SUMMARY.md (📊 Key Data Shapes)
3. Kiểm tra auth từ: K6_LOAD_TESTING_GUIDE.md (mỗi mục module)
4. Triển khai sử dụng ví dụ trong: K6_QUICK_START.md
---
## ✅ Verification Checklist
## ✅ Danh Sách Kiểm Tra Xác Minh
Before running load tests, verify:
Trước khi chạy load test, hãy xác minh:
- [ ] API running: `pnpm dev` (port 3001)
- [ ] Database seeded: `pnpm db:seed`
- [ ] K6 installed: `k6 version`
- [ ] Can reach API: `curl http://localhost:3001/api/v1/docs`
- [ ] ENV variables set: `JWT_SECRET`, `CORS_ORIGINS`, etc.
- [ ] Load test file exists: `load-tests/*.k6.js`
- [ ] Test data available: Check seed in `prisma/seed.ts`
- [ ] API đang chạy: `pnpm dev` (port 3001)
- [ ] Database đã seed: `pnpm db:seed`
- [ ] K6 đã cài đặt: `k6 version`
- [ ] Có thể truy cập API: `curl http://localhost:3001/api/v1/docs`
- [ ] Biến ENV đã set: `JWT_SECRET`, `CORS_ORIGINS`, v.v.
- [ ] File load test tồn tại: `load-tests/*.k6.js`
- [ ] Có sẵn dữ liệu test: Kiểm tra seed trong `prisma/seed.ts`
---
## 📞 Support & References
## 📞 Hỗ Trợ & Tham Khảo
### Internal Documentation
- **Full Architecture**: K6_LOAD_TESTING_GUIDE.md
- **Endpoint Reference**: K6_ENDPOINTS_SUMMARY.md
- **Getting Started**: K6_QUICK_START.md
### Tài Liệu Nội Bộ
- **Kiến Trúc Đầy Đủ**: K6_LOAD_TESTING_GUIDE.md
- **Tham Khảo Endpoint**: K6_ENDPOINTS_SUMMARY.md
- **Bắt Đầu**: K6_QUICK_START.md
### External Resources
- **K6 Official Docs**: https://k6.io/docs
- **K6 API Reference**: https://k6.io/docs/javascript-api
- **K6 Community**: https://community.k6.io
- **K6 Examples**: https://github.com/grafana/k6-templates
### Tài Nguyên Bên Ngoài
- **Tài Liệu Chính Thức K6**: https://k6.io/docs
- **Tham Khảo K6 API**: https://k6.io/docs/javascript-api
- **Cộng Đồng K6**: https://community.k6.io
- **Ví Dụ K6**: https://github.com/grafana/k6-templates
### Project Files
### File Dự Án
- **API Controllers**: `apps/api/src/modules/*/presentation/controllers/`
- **DTOs**: `apps/api/src/modules/*/presentation/dto/`
- **E2E Tests**: `e2e/api/`
@@ -365,40 +365,39 @@ Before running load tests, verify:
---
## 🎓 Learning Path
## 🎓 Lộ Trình Học
### Beginner (30 minutes)
1. Read K6_QUICK_START.md (Steps 1-4)
2. Install K6
3. Run: `k6 run load-tests/search.k6.js`
### Người Mới Bắt Đầu (30 phút)
1. Đọc K6_QUICK_START.md (Bước 1-4)
2. Cài đặt K6
3. Chạy: `k6 run load-tests/search.k6.js`
### Intermediate (1-2 hours)
1. Read K6_ENDPOINTS_SUMMARY.md
2. Understand auth flows
3. Run auth test: `k6 run load-tests/auth.k6.js`
4. Run listing test: `k6 run load-tests/listings.k6.js`
### Trung Cấp (1-2 giờ)
1. Đọc K6_ENDPOINTS_SUMMARY.md
2. Hiểu luồng auth
3. Chạy test auth: `k6 run load-tests/auth.k6.js`
4. Chạy test listing: `k6 run load-tests/listings.k6.js`
### Advanced (2-4 hours)
1. Read K6_LOAD_TESTING_GUIDE.md completely
2. Review controller implementations in source
3. Create custom load test script
4. Set up CI/CD with GitHub Actions (K6_QUICK_START.md Step 🔟)
5. Generate and analyze reports
### Nâng Cao (2-4 giờ)
1. Đọc K6_LOAD_TESTING_GUIDE.md đầy đủ
2. Xem xét triển khai controller trong source
3. Tạo script load test tùy chỉnh
4. Thiết lập CI/CD với GitHub Actions (K6_QUICK_START.md Bước 🔟)
5. Tạo và phân tích báo cáo
---
## 📝 Notes
## 📝 Ghi Chú
- **No existing K6 setup** — These docs provide complete guidance
- **Three complementary docs** — Explore different docs for different needs
- **Executable examples** — K6_QUICK_START.md scripts work as-is
- **Rate limits matter** — Consider them in test design
- **Quota gates** — Some operations (listings, payments) are gated by subscription
- **Test data** — Use seed data or generate unique test users per VU
- **Production ready** — Guides follow K6 best practices
- **Chưa có thiết lập K6 nào** — Tài liệu này cung cấp hướng dẫn đầy đủ
- **Ba tài liệu bổ sung cho nhau** — Khám phá các tài liệu khác nhau cho các nhu cầu khác nhau
- **Ví dụ chạy được** — Script K6_QUICK_START.md hoạt động ngay
- **Rate limit quan trọng** — Hãy xem xét chúng trong thiết kế test
- **Quota gate** — Một số thao tác (listings, payments) bị giới hạn theo subscription
- **Dữ liệu test** — Sử dụng dữ liệu seed hoặc tạo người dùng test duy nhất cho mỗi VU
- **Sẵn sàng cho production** — Hướng dẫn tuân theo các thực hành tốt nhất của K6
---
Generated: 2026-04-09
Last Updated: K6_QUICK_START.md latest
Đã tạo: 2026-04-09
Cập nhật lần cuối: K6_QUICK_START.md mới nhất

View File

@@ -1,22 +1,22 @@
# @goodgo/ai-services
Python FastAPI AI/ML microservice for the GoodGo Platform.
Microservice AI/ML viết bằng Python FastAPI cho GoodGo Platform.
## Services
## Các dịch vụ
| Service | Router | Description |
| Dịch vụ | Router | Mô tả |
|---------|--------|-------------|
| **AVM** | `/avm` | Automated Valuation Model — XGBoost-based property price predictions |
| **Moderation** | `/moderation` | Content moderation for listings (text + image analysis) |
| **NLP** | `/nlp` | Vietnamese NLP — feature extraction, search query understanding |
| **AVM** | `/avm` | Mô hình định giá tự động — dự đoán giá bất động sản dựa trên XGBoost |
| **Moderation** | `/moderation` | Kiểm duyệt nội dung tin đăng (phân tích văn bản + hình ảnh) |
| **NLP** | `/nlp` | NLP tiếng Việt — trích xuất đặc trưng, hiểu truy vấn tìm kiếm |
## Tech Stack
- **Python** 3.12+
- **FastAPI** 0.115 + Uvicorn
- **XGBoost** 2.1 (property valuation model)
- **Underthesea** 6.8 (Vietnamese NLP tokenizer)
- **Pydantic** 2.9 (request/response schemas)
- **XGBoost** 2.1 (mô hình định giá bất động sản)
- **Underthesea** 6.8 (tokenizer NLP tiếng Việt)
- **Pydantic** 2.9 (schema request/response)
## Quick Start
@@ -30,7 +30,7 @@ pip install -e ".[dev]"
uvicorn app.main:app --reload --port 8000
```
## Project Structure
## Cấu trúc dự án
```
libs/ai-services/
@@ -55,7 +55,7 @@ libs/ai-services/
└── pyproject.toml # Dependencies and config
```
## Testing
## Test
```bash
cd libs/ai-services

View File

@@ -1,23 +1,23 @@
# @goodgo/mcp-servers
MCP (Model Context Protocol) tool server library for the GoodGo Platform. Provides structured tools that AI assistants can use to query property data, run analytics, and perform valuations.
Thư viện tool server MCP (Model Context Protocol) cho GoodGo Platform. Cung cấp các công cụ có cấu trúc để trợ lý AI có thể truy vấn dữ liệu bất động sản, chạy phân tích và thực hiện định giá.
## Tool Servers
| Server | Path | Description |
| Server | Đường dẫn | Mô tả |
|--------|------|-------------|
| **Property Search** | `property-search/` | Geo search, full-text search, filter by type/price/area |
| **Market Analytics** | `market-analytics/` | Price trends, heatmaps, district comparisons |
| **Valuation** | `valuation/` | AVM property valuation requests |
| **Property Search** | `property-search/` | Tìm kiếm theo vị trí địa lý, full-text search, lọc theo loại/giá/diện tích |
| **Market Analytics** | `market-analytics/` | Xu hướng giá, heatmap, so sánh giữa các quận |
| **Valuation** | `valuation/` | Yêu cầu định giá bất động sản qua AVM |
## Tech Stack
- **TypeScript** 6+
- **@modelcontextprotocol/sdk** 1.12 (MCP protocol implementation)
- **Zod** 3.24 (schema validation)
- **NestJS** integration module (optional peer dependency)
- **@modelcontextprotocol/sdk** 1.12 (triển khai giao thức MCP)
- **Zod** 3.24 (kiểm tra schema)
- **NestJS** module tích hợp (peer dependency tuỳ chọn)
## Project Structure
## Cấu trúc dự án
```
libs/mcp-servers/
@@ -33,21 +33,21 @@ libs/mcp-servers/
└── tsconfig.json
```
## Usage
## Cách dùng
```typescript
import { PropertySearchServer, MarketAnalyticsServer } from '@goodgo/mcp-servers';
```
The MCP endpoints are exposed via the API's `apps/api/src/modules/mcp/` module.
Các endpoint MCP được expose qua module `apps/api/src/modules/mcp/` của API.
## Building
## Build
```bash
pnpm --filter @goodgo/mcp-servers build
```
## Testing
## Test
```bash
pnpm --filter @goodgo/mcp-servers test