From d8b409a9aba0e67be73d03d8e0cdc680cd89f1d8 Mon Sep 17 00:00:00 2001 From: Ho Ngoc Hai Date: Sun, 19 Apr 2026 03:26:14 +0700 Subject: [PATCH] =?UTF-8?q?docs:=20d=E1=BB=8Bch=2022=20file=20Markdown=20c?= =?UTF-8?q?=C3=B2n=20l=E1=BA=A1i=20sang=20ti=E1=BA=BFng=20Vi=E1=BB=87t=20c?= =?UTF-8?q?=C3=B3=20d=E1=BA=A5u=20(TEC-2881)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/PRODUCTION_READINESS.md | 418 +++---- docs/QUICK_REFERENCE.md | 96 +- docs/QUICK_START_REFERENCE.md | 428 +++---- docs/README_NEW_DOCUMENTATION.md | 469 ++++---- docs/RUNBOOK.md | 1014 ++++++++--------- docs/api-endpoints.md | 266 ++--- docs/architecture/CODEBASE_OVERVIEW.md | 347 +++--- docs/architecture/FILE_MAPPING_GUIDE.md | 274 ++--- docs/architecture/IMPLEMENTATION_PLAN.md | 344 +++--- .../IMPLEMENTATION_QUICK_REFERENCE.md | 292 ++--- docs/audits/AUDIT_INDEX.md | 346 +++--- .../AUDIT_QUICK_REFERENCE_2026-04-12.md | 252 ++-- docs/audits/AUDIT_README.md | 343 +++--- docs/audits/PRICING_CHECKOUT_AUDIT.md | 679 ++++++----- docs/audits/WEB_AUDIT_SUMMARY.md | 336 +++--- docs/deployment.md | 316 ++--- docs/guides/AUTH_IMPLEMENTATION_CHECKLIST.md | 344 +++--- docs/load-testing/K6_LOAD_TESTING_GUIDE.md | 307 +++-- docs/load-testing/K6_QUICK_START.md | 110 +- docs/load-testing/K6_README.md | 371 +++--- libs/ai-services/README.md | 22 +- libs/mcp-servers/README.md | 26 +- 22 files changed, 3697 insertions(+), 3703 deletions(-) diff --git a/docs/PRODUCTION_READINESS.md b/docs/PRODUCTION_READINESS.md index 3be957a..9229a84 100644 --- a/docs/PRODUCTION_READINESS.md +++ b/docs/PRODUCTION_READINESS.md @@ -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` và `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 và 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 và 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) và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) và 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 | diff --git a/docs/QUICK_REFERENCE.md b/docs/QUICK_REFERENCE.md index 87ce23b..500b0f1 100644 --- a/docs/QUICK_REFERENCE.md +++ b/docs/QUICK_REFERENCE.md @@ -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 diff --git a/docs/QUICK_START_REFERENCE.md b/docs/QUICK_START_REFERENCE.md index b5a37af..3e2e765 100644 --- a/docs/QUICK_START_REFERENCE.md +++ b/docs/QUICK_START_REFERENCE.md @@ -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 và 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 -✅ 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 +✅ JWT authentication với refresh token +✅ OAuth2 (Google, Zalo) +✅ 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 ``` -### 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 🚀 diff --git a/docs/README_NEW_DOCUMENTATION.md b/docs/README_NEW_DOCUMENTATION.md index 597a22f..9c99c4a 100644 --- a/docs/README_NEW_DOCUMENTATION.md +++ b/docs/README_NEW_DOCUMENTATION.md @@ -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** và **docker-compose.prod.yml** +3. Xem lại **docs/deployment.md** và **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! 🚀** diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index cc1261f..05e50b4 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -1,65 +1,65 @@ -# GoodGo Platform — Production Runbook +# GoodGo Platform — Runbook Vận hành Production -> **Audience:** On-call SRE, DevOps engineers, and platform operators. -> **Last updated:** 2026-04-11 +> **Đối tượng:** SRE on-call, kỹ sư DevOps và người vận hành nền tảng. +> **Cập nhật lần cuối:** 2026-04-11 --- -## Table of Contents +## Mục lục -1. [Service Inventory](#1-service-inventory) +1. [Danh sách dịch vụ](#1-service-inventory) 2. [Health Checks](#2-health-checks) -3. [Common Incidents](#3-common-incidents) - - [3.1 Database Connection Pool Exhaustion](#31-database-connection-pool-exhaustion) - - [3.2 Redis Connection Failure](#32-redis-connection-failure) - - [3.3 Typesense Unavailable](#33-typesense-unavailable) - - [3.4 High API Latency](#34-high-api-latency) - - [3.5 Payment Callback Failures](#35-payment-callback-failures) - - [3.6 Disk Space Alerts](#36-disk-space-alerts) - - [3.7 MinIO / Object Storage Failure](#37-minio--object-storage-failure) - - [3.8 AI Services Unavailable](#38-ai-services-unavailable) - - [3.9 Log Pipeline Failure (Loki/Promtail)](#39-log-pipeline-failure-lokipromtail) - - [3.10 5xx Error Rate Spike](#310-5xx-error-rate-spike) -4. [Recovery Procedures](#4-recovery-procedures) - - [4.1 Database Restore from Backup](#41-database-restore-from-backup) - - [4.2 Redis Cache Flush & Warm-up](#42-redis-cache-flush--warm-up) - - [4.3 Rolling Restart Procedures](#43-rolling-restart-procedures) - - [4.4 Rollback Deployment](#44-rollback-deployment) - - [4.5 Typesense Reindex from PostgreSQL](#45-typesense-reindex-from-postgresql) - - [4.6 Full Host Recovery](#46-full-host-recovery) -5. [Escalation Matrix](#5-escalation-matrix) -6. [Monitoring Dashboards](#6-monitoring-dashboards) -7. [Useful PromQL Queries](#7-useful-promql-queries) -8. [Environment Quick Reference](#8-environment-quick-reference) +3. [Các incident thường gặp](#3-common-incidents) + - [3.1 Cạn kiệt connection pool của database](#31-database-connection-pool-exhaustion) + - [3.2 Lỗi kết nối Redis](#32-redis-connection-failure) + - [3.3 Typesense không khả dụng](#33-typesense-unavailable) + - [3.4 Latency API cao](#34-high-api-latency) + - [3.5 Lỗi callback thanh toán](#35-payment-callback-failures) + - [3.6 Cảnh báo dung lượng đĩa](#36-disk-space-alerts) + - [3.7 Lỗi MinIO / Object Storage](#37-minio--object-storage-failure) + - [3.8 AI Services không khả dụng](#38-ai-services-unavailable) + - [3.9 Lỗi pipeline log (Loki/Promtail)](#39-log-pipeline-failure-lokipromtail) + - [3.10 Tăng đột biến tỷ lệ lỗi 5xx](#310-5xx-error-rate-spike) +4. [Quy trình khôi phục](#4-recovery-procedures) + - [4.1 Khôi phục database từ backup](#41-database-restore-from-backup) + - [4.2 Xóa cache Redis và warm-up](#42-redis-cache-flush--warm-up) + - [4.3 Quy trình rolling restart](#43-rolling-restart-procedures) + - [4.4 Rollback deployment](#44-rollback-deployment) + - [4.5 Reindex Typesense từ PostgreSQL](#45-typesense-reindex-from-postgresql) + - [4.6 Khôi phục toàn bộ host](#46-full-host-recovery) +5. [Ma trận leo thang](#5-escalation-matrix) +6. [Dashboard giám sát](#6-monitoring-dashboards) +7. [Truy vấn PromQL hữu ích](#7-useful-promql-queries) +8. [Tham chiếu nhanh môi trường](#8-environment-quick-reference) --- -## 1. Service Inventory +## 1. Danh sách dịch vụ -### Production Services (`docker-compose.prod.yml`) +### Dịch vụ Production (`docker-compose.prod.yml`) -| Service | Image | Port | Resource Limits | Health Check | +| Dịch vụ | Image | Port | Giới hạn tài nguyên | Health Check | |---------|-------|------|-----------------|--------------| | **api** (NestJS) | `ghcr.io/goodgo/goodgo-api` | 3001 | 1 CPU / 1 GB | `GET /health` (node fetch) | | **web** (Next.js) | `ghcr.io/goodgo/goodgo-web` | 3000 | 0.5 CPU / 512 MB | `GET /` (node fetch) | | **ai-services** (FastAPI) | `ghcr.io/goodgo/goodgo-ai-services` | 8000 | 1 CPU / 1 GB | `GET /health` (httpx) | -| **postgres** | `postgis/postgis:16-3.4` | 5432 (internal) | 2 CPU / 2 GB, shm=256m | `pg_isready` | -| **pgbouncer** | `edoburu/pgbouncer:1.23.1-p2` | 6432 (internal) | 0.5 CPU / 256 MB | `pg_isready -p 6432` | -| **redis** | `redis:7-alpine` | 6379 (internal) | 0.5 CPU / 768 MB | `redis-cli ping` | -| **typesense** | `typesense/typesense:27.1` | 8108 (internal) | 1 CPU / 1 GB | `curl /health` | -| **minio** | `minio/minio:latest` | 9000/9001 (internal) | 0.5 CPU / 1 GB | `mc ready local` | +| **postgres** | `postgis/postgis:16-3.4` | 5432 (nội bộ) | 2 CPU / 2 GB, shm=256m | `pg_isready` | +| **pgbouncer** | `edoburu/pgbouncer:1.23.1-p2` | 6432 (nội bộ) | 0.5 CPU / 256 MB | `pg_isready -p 6432` | +| **redis** | `redis:7-alpine` | 6379 (nội bộ) | 0.5 CPU / 768 MB | `redis-cli ping` | +| **typesense** | `typesense/typesense:27.1` | 8108 (nội bộ) | 1 CPU / 1 GB | `curl /health` | +| **minio** | `minio/minio:latest` | 9000/9001 (nội bộ) | 0.5 CPU / 1 GB | `mc ready local` | | **pg-backup** | `postgis/postgis:16-3.4` | — | 0.5 CPU / 512 MB | — (cron daemon) | -| **loki** | `grafana/loki:3.0.0` | 3100 (internal) | 0.5 CPU / 512 MB | `wget /ready` | +| **loki** | `grafana/loki:3.0.0` | 3100 (nội bộ) | 0.5 CPU / 512 MB | `wget /ready` | | **promtail** | `grafana/promtail:3.0.0` | — | 0.25 CPU / 256 MB | — | -| **prometheus** | `prom/prometheus:v2.51.0` | 9090 (internal) | 0.5 CPU / 1 GB | `wget /-/healthy` | -| **grafana** | `grafana/grafana:10.4.1` | 3002 (external) | 0.5 CPU / 512 MB | `wget /api/health` | -| **alertmanager** | `prom/alertmanager:v0.27.0` | 9093 (internal) | 0.25 CPU / 256 MB | `wget /-/healthy` | +| **prometheus** | `prom/prometheus:v2.51.0` | 9090 (nội bộ) | 0.5 CPU / 1 GB | `wget /-/healthy` | +| **grafana** | `grafana/grafana:10.4.1` | 3002 (bên ngoài) | 0.5 CPU / 512 MB | `wget /api/health` | +| **alertmanager** | `prom/alertmanager:v0.27.0` | 9093 (nội bộ) | 0.25 CPU / 256 MB | `wget /-/healthy` | -### Development-Only Services (`docker-compose.yml`) +### Dịch vụ chỉ dùng cho Development (`docker-compose.yml`) -Development uses the same data and monitoring services but runs API/Web on the host. The `pg-backup` service also runs in dev with default credentials. +Môi trường development sử dụng cùng các dịch vụ dữ liệu và giám sát nhưng chạy API/Web trực tiếp trên host. Dịch vụ `pg-backup` cũng chạy trong dev với credential mặc định. -### Service Dependency Chain +### Chuỗi phụ thuộc giữa các dịch vụ ``` web --> api --> pgbouncer --> postgres @@ -78,19 +78,19 @@ pg-backup --> postgres ## 2. Health Checks -### Application Health Endpoints +### Các endpoint health của ứng dụng -| Endpoint | Type | Checks | Expected Response | +| Endpoint | Loại | Kiểm tra | Phản hồi mong đợi | |----------|------|--------|-------------------| -| `GET /health` | Liveness | Process is running | `200 { status: "ok" }` | +| `GET /health` | Liveness | Tiến trình đang chạy | `200 { status: "ok" }` | | `GET /health/ready` | Readiness | PostgreSQL + Redis | `200 { status: "ok", info: { database: ..., redis: ... } }` | -| `GET /health/db` | Database only | PostgreSQL connectivity | `200 { status: "ok", info: { database: ... } }` | -| `GET /health/redis` | Redis only | Redis connectivity | `200 { status: "ok", info: { redis: ... } }` | +| `GET /health/db` | Chỉ database | Kết nối PostgreSQL | `200 { status: "ok", info: { database: ... } }` | +| `GET /health/redis` | Chỉ Redis | Kết nối Redis | `200 { status: "ok", info: { redis: ... } }` | -### Verify All Services Are Healthy +### Xác minh tất cả dịch vụ đang khỏe mạnh ```bash -# Quick check — all containers +# Kiểm tra nhanh — tất cả container docker compose -f docker-compose.prod.yml ps --format "table {{.Name}}\t{{.Status}}\t{{.Health}}" # API liveness @@ -99,7 +99,7 @@ curl -sf http://localhost:3001/health && echo "API OK" || echo "API FAIL" # API readiness (DB + Redis) curl -sf http://localhost:3001/health/ready | jq . -# Individual dependency checks +# Kiểm tra từng phụ thuộc curl -sf http://localhost:3001/health/db | jq . curl -sf http://localhost:3001/health/redis | jq . @@ -112,7 +112,7 @@ docker exec goodgo-minio mc ready local && echo "MinIO OK" # AI Services curl -sf http://localhost:8000/health && echo "AI OK" || echo "AI FAIL" -# PostgreSQL (direct) +# PostgreSQL (trực tiếp) docker exec goodgo-postgres pg_isready -U ${DB_USER} -d ${DB_NAME} # PgBouncer @@ -134,7 +134,7 @@ curl -sf http://localhost:3002/api/health | jq . curl -sf http://localhost:9093/-/healthy && echo "Alertmanager OK" ``` -### Container Resource Usage +### Tiêu thụ tài nguyên của container ```bash docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.NetIO}}" @@ -142,29 +142,29 @@ docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\ --- -## 3. Common Incidents +## 3. Các incident thường gặp -### 3.1 Database Connection Pool Exhaustion +### 3.1 Cạn kiệt connection pool của database -**Symptoms:** -- API returns 503 or hangs on requests -- `/health/ready` returns unhealthy for `database` -- PgBouncer logs: `no more connections allowed` or `query_wait_timeout` -- Prometheus: spike in `pg_stat_activity` active connections +**Triệu chứng:** +- API trả về 503 hoặc treo khi xử lý request +- `/health/ready` trả về unhealthy cho `database` +- Log PgBouncer: `no more connections allowed` hoặc `query_wait_timeout` +- Prometheus: tăng đột biến số kết nối active trong `pg_stat_activity` -**Diagnosis:** +**Chẩn đoán:** ```bash -# Check PgBouncer pool status +# Kiểm tra trạng thái pool của PgBouncer docker exec goodgo-pgbouncer psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;" docker exec goodgo-pgbouncer psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW CLIENTS;" docker exec goodgo-pgbouncer psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW STATS;" -# Check PostgreSQL active connections +# Kiểm tra số kết nối active của PostgreSQL docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT state, count(*) FROM pg_stat_activity WHERE datname = '${DB_NAME}' GROUP BY state;" -# Identify long-running queries +# Xác định các truy vấn chạy lâu docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT pid, now() - pg_stat_activity.query_start AS duration, query, state FROM pg_stat_activity @@ -173,10 +173,10 @@ docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ LIMIT 10;" ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. Kill long-running queries (> 5 minutes) +# 1. Hủy các truy vấn chạy lâu (> 5 phút) docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity @@ -185,177 +185,177 @@ docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ AND now() - query_start > interval '5 minutes' AND pid <> pg_backend_pid();" -# 2. If pool is fully exhausted, restart PgBouncer +# 2. Nếu pool đã cạn kiệt hoàn toàn, restart PgBouncer docker compose -f docker-compose.prod.yml restart pgbouncer -# 3. If issue persists, increase pool size temporarily -# Edit PGBOUNCER_POOL_SIZE in .env, then: +# 3. Nếu vấn đề vẫn còn, tạm thời tăng pool size +# Chỉnh sửa PGBOUNCER_POOL_SIZE trong .env, sau đó: docker compose -f docker-compose.prod.yml up -d --no-deps pgbouncer ``` -**PgBouncer Configuration Reference:** -- Pool mode: `transaction` (connections returned to pool after each transaction) -- Default pool size: 20 server connections per user/db pair -- Max client connections: 200 -- Reserve pool: 5 extra connections (after 3s wait) -- Query wait timeout: 120s (error if client waits this long) +**Tham chiếu cấu hình PgBouncer:** +- Pool mode: `transaction` (kết nối được trả về pool sau mỗi transaction) +- Pool size mặc định: 20 server connection cho mỗi cặp user/db +- Số client connection tối đa: 200 +- Reserve pool: 5 kết nối dự phòng (sau khi chờ 3s) +- Query wait timeout: 120s (báo lỗi nếu client chờ lâu hơn) -### 3.2 Redis Connection Failure +### 3.2 Lỗi kết nối Redis -**Symptoms:** -- `/health/redis` returns unhealthy -- Increased API response times (cache misses hitting DB) -- API logs show Redis connection errors +**Triệu chứng:** +- `/health/redis` trả về unhealthy +- Thời gian phản hồi API tăng (cache miss đánh vào DB) +- Log API hiển thị lỗi kết nối Redis -**Diagnosis:** +**Chẩn đoán:** ```bash -# Check Redis container +# Kiểm tra container Redis docker logs --tail=50 goodgo-redis -# Test connectivity +# Kiểm tra kết nối docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" ping docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" INFO server docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" INFO memory docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" INFO clients ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. Restart Redis (data persisted via AOF) +# 1. Restart Redis (dữ liệu được lưu qua AOF) docker compose -f docker-compose.prod.yml restart redis -# 2. If OOM — check memory usage +# 2. Nếu OOM — kiểm tra sử dụng bộ nhớ docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" INFO memory | grep used_memory_human -# Max memory is 512 MB (prod), eviction policy: allkeys-lru +# Bộ nhớ tối đa là 512 MB (prod), eviction policy: allkeys-lru -# 3. If AOF is corrupted +# 3. Nếu AOF bị hỏng docker compose -f docker-compose.prod.yml stop redis docker exec goodgo-redis redis-check-aof --fix /data/appendonly.aof docker compose -f docker-compose.prod.yml start redis ``` -**Graceful Degradation:** The API is designed to continue operating when Redis is unavailable. Cache misses fall through to PostgreSQL. Performance will degrade but functionality is preserved. Redis is non-critical for core operations. +**Graceful Degradation:** API được thiết kế để tiếp tục hoạt động khi Redis không khả dụng. Các cache miss sẽ đi thẳng xuống PostgreSQL. Hiệu năng sẽ giảm nhưng chức năng vẫn được bảo đảm. Redis không quan trọng đối với các hoạt động cốt lõi. -### 3.3 Typesense Unavailable +### 3.3 Typesense không khả dụng -**Symptoms:** -- Search functionality returns errors or falls back to basic DB search -- `curl http://localhost:8108/health` fails -- API logs show Typesense connection timeouts +**Triệu chứng:** +- Chức năng tìm kiếm trả về lỗi hoặc fallback về tìm kiếm DB cơ bản +- `curl http://localhost:8108/health` thất bại +- Log API hiển thị timeout kết nối Typesense -**Diagnosis:** +**Chẩn đoán:** ```bash -# Check container status +# Kiểm tra trạng thái container docker logs --tail=50 goodgo-typesense -# Check health +# Kiểm tra health curl -sf -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" http://localhost:8108/health -# Check collections +# Kiểm tra collection curl -sf -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" http://localhost:8108/collections | jq . -# Check disk space for Typesense data volume +# Kiểm tra dung lượng đĩa cho volume dữ liệu Typesense docker system df -v | grep typesense ``` -**Resolution:** +**Cách xử lý:** ```bash # 1. Restart Typesense docker compose -f docker-compose.prod.yml restart typesense -# 2. If data is corrupted — rebuild from PostgreSQL +# 2. Nếu dữ liệu bị hỏng — rebuild từ PostgreSQL docker compose -f docker-compose.prod.yml stop typesense docker volume rm goodgo-platform-ai_typesense_data docker compose -f docker-compose.prod.yml up -d typesense -# Wait for healthy, then reindex: +# Chờ tới khi healthy, sau đó reindex: docker compose -f docker-compose.prod.yml exec api npx ts-node scripts/typesense-reindex.ts -# Or: pnpm run typesense:reindex +# Hoặc: pnpm run typesense:reindex -# 3. If volume backup exists — restore +# 3. Nếu có backup volume — khôi phục docker compose -f docker-compose.prod.yml stop typesense docker run --rm -v goodgo-platform-ai_typesense_data:/data -v $(pwd)/backups:/backup \ alpine sh -c "rm -rf /data/* && tar xzf /backup/typesense_YYYYMMDD_HHMMSS.tar.gz -C /data" docker compose -f docker-compose.prod.yml start typesense ``` -**Fallback Behavior:** When Typesense is unavailable, property search falls back to PostgreSQL full-text search with PostGIS geo queries. Search quality degrades but core functionality works. +**Hành vi Fallback:** Khi Typesense không khả dụng, tìm kiếm bất động sản sẽ fallback về PostgreSQL full-text search kết hợp với truy vấn geo PostGIS. Chất lượng tìm kiếm giảm nhưng chức năng cốt lõi vẫn hoạt động. -### 3.4 High API Latency +### 3.4 Latency API cao -**Symptoms:** -- Prometheus alert `ApiLatencyP99High` fires (p99 > 1s for 5 min) -- Critical alert `ApiLatencyP99Critical` fires (p99 > 3s for 3 min — SLO breach) -- Users report slow page loads +**Triệu chứng:** +- Alert Prometheus `ApiLatencyP99High` kích hoạt (p99 > 1s trong 5 phút) +- Alert critical `ApiLatencyP99Critical` kích hoạt (p99 > 3s trong 3 phút — vi phạm SLO) +- Người dùng báo tải trang chậm -**Diagnosis:** +**Chẩn đoán:** ```bash -# 1. Check which endpoints are slow -# Grafana: GoodGo API Latency dashboard -# Or via PromQL: +# 1. Kiểm tra endpoint nào đang chậm +# Grafana: dashboard GoodGo API Latency +# Hoặc qua PromQL: curl -s "http://localhost:9090/api/v1/query" --data-urlencode \ 'query=topk(10, histogram_quantile(0.99, sum(rate(goodgo_api_request_duration_seconds_bucket[5m])) by (le, route, method)))' \ | jq '.data.result[] | {route: .metric.route, method: .metric.method, p99: .value[1]}' -# 2. Check database slow queries +# 2. Kiểm tra slow query của database docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT pid, now() - query_start AS duration, left(query, 100) AS query_preview FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '1 second' ORDER BY duration DESC;" -# 3. Check PgBouncer wait times +# 3. Kiểm tra thời gian chờ của PgBouncer docker exec goodgo-pgbouncer psql -h 127.0.0.1 -p 6432 -U pgbouncer_admin pgbouncer -c "SHOW POOLS;" -# 4. Check container resource usage +# 4. Kiểm tra sử dụng tài nguyên container docker stats --no-stream goodgo-api goodgo-postgres goodgo-redis goodgo-pgbouncer -# 5. Check Redis latency +# 5. Kiểm tra latency Redis docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" --latency-history -i 3 -# 6. Check application logs for errors +# 6. Kiểm tra log ứng dụng để tìm lỗi docker logs --tail=200 --since=5m goodgo-api 2>&1 | grep -i "error\|timeout\|slow" ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. If DB slow queries — terminate them +# 1. Nếu có slow query DB — terminate chúng docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'active' AND now() - query_start > interval '30 seconds';" -# 2. If connection pool exhaustion — see Section 3.1 +# 2. Nếu connection pool cạn kiệt — xem Mục 3.1 -# 3. If Redis is slow — restart +# 3. Nếu Redis chậm — restart docker compose -f docker-compose.prod.yml restart redis -# 4. If API container OOM — restart with more memory +# 4. Nếu container API bị OOM — restart với nhiều memory hơn docker compose -f docker-compose.prod.yml restart api -# 5. If specific endpoint is the bottleneck — check Loki logs: +# 5. Nếu một endpoint cụ thể là bottleneck — kiểm tra log Loki: # Grafana > Explore > Loki > {container_name="goodgo-api"} |= "slow" ``` -### 3.5 Payment Callback Failures +### 3.5 Lỗi callback thanh toán -**Symptoms:** -- Users report payments stuck in "pending" state -- VNPay/MoMo/ZaloPay IPN callbacks returning errors -- Payment reconciliation mismatches +**Triệu chứng:** +- Người dùng báo thanh toán bị kẹt ở trạng thái "pending" +- Callback IPN của VNPay/MoMo/ZaloPay trả về lỗi +- Không khớp đối soát thanh toán -**Diagnosis:** +**Chẩn đoán:** ```bash -# 1. Check payment callback logs +# 1. Kiểm tra log callback thanh toán docker logs goodgo-api 2>&1 | grep -i "payment\|callback\|vnpay\|momo\|zalopay" | tail -50 -# 2. Check for pending payments in DB +# 2. Kiểm tra các thanh toán pending trong DB docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "SELECT id, provider, status, \"amountVND\", \"createdAt\" FROM \"Payment\" @@ -364,102 +364,102 @@ docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ ORDER BY \"createdAt\" DESC LIMIT 20;" -# 3. Verify callback URL is reachable from external networks +# 3. Xác minh URL callback có thể truy cập được từ bên ngoài curl -sf https://your-domain.com/api/payments/vnpay/callback && echo "Callback URL reachable" -# 4. Check if API is receiving callbacks (via Loki) +# 4. Kiểm tra API có đang nhận callback không (qua Loki) # Grafana > Explore > Loki > {container_name="goodgo-api"} |= "callback" |= "payment" ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. If callbacks are timing out — check API health and restart if needed +# 1. Nếu callback bị timeout — kiểm tra health API và restart nếu cần docker compose -f docker-compose.prod.yml restart api -# 2. If VNPay signature verification fails — verify VNPAY_* env vars +# 2. Nếu xác thực chữ ký VNPay thất bại — kiểm tra các env var VNPAY_* docker compose -f docker-compose.prod.yml exec api printenv | grep VNPAY -# 3. For stuck payments — manual reconciliation -# Check VNPay/MoMo merchant portal for actual transaction status -# Update payment status in DB if confirmed paid: +# 3. Đối với thanh toán kẹt — đối soát thủ công +# Kiểm tra cổng merchant VNPay/MoMo để biết trạng thái giao dịch thực tế +# Cập nhật trạng thái thanh toán trong DB nếu xác nhận đã thanh toán: docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c \ "UPDATE \"Payment\" SET status = 'COMPLETED', \"updatedAt\" = now() WHERE id = '' AND status = 'PENDING';" -# 4. If callbacks are not reaching the server — check: -# - Firewall rules (port 3001 or reverse proxy port must be open) -# - SSL certificate validity -# - DNS resolution -# - Payment provider webhook configuration (correct callback URL) +# 4. Nếu callback không đến được server — kiểm tra: +# - Quy tắc firewall (cổng 3001 hoặc cổng reverse proxy phải mở) +# - Hiệu lực chứng chỉ SSL +# - Phân giải DNS +# - Cấu hình webhook của payment provider (URL callback đúng) ``` -**Important:** The payment callback handler uses idempotent processing with atomic state transitions. Replaying a callback is safe and will not duplicate payments. +**Quan trọng:** Trình xử lý callback thanh toán dùng xử lý idempotent với state transition nguyên tử. Việc replay một callback là an toàn và sẽ không tạo ra thanh toán trùng. -### 3.6 Disk Space Alerts +### 3.6 Cảnh báo dung lượng đĩa -**Symptoms:** -- Containers failing to start or crashing -- PostgreSQL refusing writes (`PANIC: could not write to file`) -- Docker daemon running out of space +**Triệu chứng:** +- Container thất bại khi khởi động hoặc bị crash +- PostgreSQL từ chối ghi (`PANIC: could not write to file`) +- Docker daemon hết dung lượng -**Diagnosis:** +**Chẩn đoán:** ```bash -# Host disk usage +# Dung lượng đĩa của host df -h -# Docker disk usage +# Dung lượng đĩa của Docker docker system df docker system df -v -# Check individual volume sizes +# Kiểm tra kích thước từng volume for vol in $(docker volume ls -q | grep goodgo); do echo -n "$vol: " docker run --rm -v "${vol}:/data" alpine du -sh /data 2>/dev/null done -# Check backup volume specifically +# Kiểm tra volume backup docker exec goodgo-pg-backup du -sh /backups/ docker exec goodgo-pg-backup ls -lht /backups/ ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. Clean up Docker artifacts -docker system prune -f # Remove stopped containers, unused networks, dangling images -docker image prune -a -f # Remove ALL unused images (careful in prod) +# 1. Dọn dẹp các tạo phẩm Docker +docker system prune -f # Xóa container đã dừng, network không dùng, image dangling +docker image prune -a -f # Xóa TẤT CẢ image không dùng (cẩn thận trên prod) -# 2. Clean old backups (if retention not working) +# 2. Xóa backup cũ (nếu retention không hoạt động) docker exec goodgo-pg-backup find /backups -name "goodgo_*.sql.gz" -mtime +7 -delete -# 3. Clean Prometheus data (if too large) -# Prometheus retention is 30d (prod) / 15d (dev) — configured via --storage.tsdb.retention.time -# To force compaction: -curl -sf -XPOST http://localhost:9090/-/quit # Graceful shutdown triggers compaction +# 3. Dọn dẹp dữ liệu Prometheus (nếu quá lớn) +# Retention của Prometheus là 30d (prod) / 15d (dev) — cấu hình qua --storage.tsdb.retention.time +# Để ép compaction: +curl -sf -XPOST http://localhost:9090/-/quit # Tắt graceful sẽ kích hoạt compaction docker compose -f docker-compose.prod.yml start prometheus -# 4. Clean Loki data (15-day retention) -# Loki handles its own cleanup via compactor. If urgent: +# 4. Dọn dẹp dữ liệu Loki (retention 15 ngày) +# Loki tự dọn dẹp qua compactor. Nếu khẩn cấp: docker compose -f docker-compose.prod.yml restart loki -# 5. Truncate Docker container logs +# 5. Truncate log container Docker sudo truncate -s 0 $(docker inspect --format='{{.LogPath}}' goodgo-api) -# Or for all containers: +# Hoặc cho tất cả container: sudo sh -c 'truncate -s 0 /var/lib/docker/containers/*/*-json.log' ``` -**Prevention:** All production containers use `json-file` logging with `max-size: 10m` and `max-file: 3-5`. Backup retention is 7 days (configurable via `BACKUP_RETENTION_DAYS`). +**Phòng ngừa:** Tất cả container production dùng logging `json-file` với `max-size: 10m` và `max-file: 3-5`. Retention backup là 7 ngày (cấu hình qua `BACKUP_RETENTION_DAYS`). -### 3.7 MinIO / Object Storage Failure +### 3.7 Lỗi MinIO / Object Storage -**Symptoms:** -- Image/file uploads fail -- Property photos not loading -- MinIO console inaccessible at port 9001 +**Triệu chứng:** +- Upload ảnh/file thất bại +- Ảnh bất động sản không tải được +- Console MinIO không truy cập được ở cổng 9001 -**Diagnosis:** +**Chẩn đoán:** ```bash docker logs --tail=50 goodgo-minio @@ -467,27 +467,27 @@ docker exec goodgo-minio mc ready local docker exec goodgo-minio mc admin info local ``` -**Resolution:** +**Cách xử lý:** ```bash # 1. Restart MinIO docker compose -f docker-compose.prod.yml restart minio -# 2. If data volume corrupted +# 2. Nếu volume dữ liệu bị hỏng docker compose -f docker-compose.prod.yml stop minio -docker volume rm goodgo-platform-ai_minio_data # WARNING: data loss +docker volume rm goodgo-platform-ai_minio_data # CẢNH BÁO: mất dữ liệu docker compose -f docker-compose.prod.yml up -d minio -# Recreate buckets via API or admin console +# Tạo lại bucket qua API hoặc admin console ``` -### 3.8 AI Services Unavailable +### 3.8 AI Services không khả dụng -**Symptoms:** -- AI-powered features (AVM, property descriptions) fail -- `GET /health` on port 8000 fails -- API logs show AI service connection timeouts +**Triệu chứng:** +- Tính năng dùng AI (AVM, mô tả bất động sản) thất bại +- `GET /health` trên cổng 8000 thất bại +- Log API hiển thị timeout kết nối AI service -**Diagnosis:** +**Chẩn đoán:** ```bash docker logs --tail=50 goodgo-ai-services @@ -495,28 +495,28 @@ curl -sf http://localhost:8000/health docker stats --no-stream goodgo-ai-services ``` -**Resolution:** +**Cách xử lý:** ```bash # 1. Restart AI services docker compose -f docker-compose.prod.yml restart ai-services -# 2. Check rate limits (default: 60/minute) +# 2. Kiểm tra rate limit (mặc định: 60/phút) docker compose -f docker-compose.prod.yml exec ai-services printenv | grep AI_RATE_LIMIT -# 3. If OOM — the service has 1 GB limit; may need to increase for large models +# 3. Nếu OOM — service có giới hạn 1 GB; có thể cần tăng cho các model lớn ``` -**Graceful Degradation:** AI features are optional. The API should handle AI service unavailability gracefully and return non-AI results. +**Graceful Degradation:** Tính năng AI là tùy chọn. API nên xử lý việc AI service không khả dụng một cách mượt mà và trả về kết quả không dùng AI. -### 3.9 Log Pipeline Failure (Loki/Promtail) +### 3.9 Lỗi pipeline log (Loki/Promtail) -**Symptoms:** -- Grafana log explorer returns empty results -- Promtail container unhealthy or crash-looping -- Loki returning 503 +**Triệu chứng:** +- Log explorer Grafana trả về kết quả trống +- Container Promtail unhealthy hoặc bị crash-loop +- Loki trả về 503 -**Diagnosis:** +**Chẩn đoán:** ```bash docker logs --tail=50 goodgo-loki @@ -524,143 +524,143 @@ docker logs --tail=50 goodgo-promtail curl -sf http://localhost:3100/ready && echo "Loki ready" || echo "Loki NOT ready" ``` -**Resolution:** +**Cách xử lý:** ```bash -# 1. Restart the pipeline +# 1. Restart pipeline docker compose -f docker-compose.prod.yml restart loki promtail -# 2. If Loki data corrupted +# 2. Nếu dữ liệu Loki bị hỏng docker compose -f docker-compose.prod.yml stop loki promtail docker volume rm goodgo-platform-ai_loki_data docker compose -f docker-compose.prod.yml up -d loki promtail -# Historical logs are lost but new logs will flow immediately +# Log lịch sử sẽ mất nhưng log mới sẽ chảy ngay lập tức -# 3. If Promtail can't access Docker socket +# 3. Nếu Promtail không truy cập được Docker socket ls -la /var/run/docker.sock -# Ensure the promtail container has the Docker socket mounted +# Đảm bảo container promtail có mount Docker socket ``` -### 3.10 5xx Error Rate Spike +### 3.10 Tăng đột biến tỷ lệ lỗi 5xx -**Symptoms:** -- Prometheus alert `ApiErrorRate5xxHigh` fires (> 1% 5xx for 5 min) -- Users reporting errors +**Triệu chứng:** +- Alert Prometheus `ApiErrorRate5xxHigh` kích hoạt (> 1% 5xx trong 5 phút) +- Người dùng báo lỗi -**Diagnosis:** +**Chẩn đoán:** ```bash -# Check which endpoints are returning 5xx +# Kiểm tra endpoint nào trả về 5xx curl -s "http://localhost:9090/api/v1/query" --data-urlencode \ 'query=topk(10, sum(rate(http_requests_total{job="goodgo-api", status_code=~"5.."}[5m])) by (route, method))' \ | jq '.data.result' -# Check API error logs +# Kiểm tra log lỗi API docker logs --tail=200 --since=5m goodgo-api 2>&1 | grep -i "error\|exception\|500" -# Check all dependency health +# Kiểm tra health của tất cả phụ thuộc curl -sf http://localhost:3001/health/ready | jq . ``` -**Resolution:** -1. If DB-related: see [Section 3.1](#31-database-connection-pool-exhaustion) -2. If Redis-related: see [Section 3.2](#32-redis-connection-failure) -3. If recent deployment: see [Section 4.4](#44-rollback-deployment) -4. If unknown: restart API and investigate logs +**Cách xử lý:** +1. Nếu liên quan đến DB: xem [Mục 3.1](#31-database-connection-pool-exhaustion) +2. Nếu liên quan đến Redis: xem [Mục 3.2](#32-redis-connection-failure) +3. Nếu là do deploy gần đây: xem [Mục 4.4](#44-rollback-deployment) +4. Nếu không rõ nguyên nhân: restart API và điều tra log --- -## 4. Recovery Procedures +## 4. Quy trình khôi phục -### 4.1 Database Restore from Backup +### 4.1 Khôi phục database từ backup -**Automated backups run daily at 02:00 UTC** via the `pg-backup` container. Retention: 7 days. Format: `pg_dump --format=custom --compress=6`. +**Backup tự động chạy hàng ngày lúc 02:00 UTC** qua container `pg-backup`. Retention: 7 ngày. Định dạng: `pg_dump --format=custom --compress=6`. -**Automated verification runs daily at 04:00 UTC** — restores to an isolated test database, verifies table existence, row counts, checksums, PostGIS extension, indexes, and enums. Reports are written to `/backups/verify-latest.json`. +**Xác minh tự động chạy hàng ngày lúc 04:00 UTC** — khôi phục vào một database test cô lập, kiểm tra sự tồn tại của table, số dòng, checksum, extension PostGIS, index và enum. Báo cáo được ghi vào `/backups/verify-latest.json`. -#### List Available Backups +#### Liệt kê các backup hiện có ```bash docker exec goodgo-pg-backup ls -lht /backups/goodgo_*.sql.gz ``` -#### Create an On-Demand Backup +#### Tạo backup theo yêu cầu ```bash docker exec goodgo-pg-backup /scripts/pg-backup.sh ``` -#### Full Restore Procedure +#### Quy trình khôi phục đầy đủ ```bash -# 1. Stop application services +# 1. Dừng các dịch vụ ứng dụng docker compose -f docker-compose.prod.yml stop api web ai-services -# 2. (Production) Stop PgBouncer to prevent stale connections +# 2. (Production) Dừng PgBouncer để tránh kết nối cũ docker compose -f docker-compose.prod.yml stop pgbouncer -# 3. Run the restore script +# 3. Chạy script restore docker exec -it goodgo-pg-backup /scripts/pg-restore.sh /backups/goodgo_YYYYMMDD_HHMMSS.sql.gz -# The script will: -# - Terminate active DB connections -# - DROP and recreate the database -# - Restore from the backup file +# Script sẽ: +# - Terminate các kết nối DB đang active +# - DROP và tạo lại database +# - Khôi phục từ file backup -# 4. Verify the restore +# 4. Xác minh việc khôi phục docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c '\dt' docker exec goodgo-postgres psql -U ${DB_USER} -d ${DB_NAME} -c 'SELECT count(*) FROM "User";' -# 5. Apply any pending migrations +# 5. Áp dụng các migration đang chờ (nếu có) docker compose -f docker-compose.prod.yml exec api npx prisma migrate deploy -# 6. Restart all services +# 6. Khởi động lại tất cả dịch vụ docker compose -f docker-compose.prod.yml up -d -# 7. Verify application health +# 7. Xác minh health của ứng dụng curl -sf http://localhost:3001/health/ready | jq . ``` -#### Verify a Backup Without Restoring +#### Xác minh backup mà không khôi phục ```bash -# Run verification against latest backup (creates temp DB, drops it after) +# Chạy verification trên backup mới nhất (tạo DB tạm, sau đó drop) docker compose run --rm pg-verify-backup -# Or verify a specific backup file +# Hoặc xác minh một file backup cụ thể docker exec goodgo-pg-backup /scripts/pg-verify-backup.sh /backups/goodgo_YYYYMMDD_HHMMSS.sql.gz -# Check latest verification report +# Kiểm tra báo cáo verification mới nhất docker exec goodgo-pg-backup cat /backups/verify-latest.json | jq . ``` **RPO/RTO:** -- RPO: ≤ 24 hours (daily backups; consider WAL archiving for lower RPO) -- RTO: ~15 minutes (local volume), ~30 minutes (off-site) +- RPO: ≤ 24 giờ (backup hàng ngày; cân nhắc WAL archiving để giảm RPO) +- RTO: ~15 phút (volume local), ~30 phút (off-site) -### 4.2 Redis Cache Flush & Warm-up +### 4.2 Xóa cache Redis và warm-up ```bash -# Flush all Redis data +# Xóa toàn bộ dữ liệu Redis docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" FLUSHALL -# Verify flush +# Xác minh việc xóa docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" DBSIZE -# Should return: (integer) 0 +# Phải trả về: (integer) 0 ``` -**Warm-up:** Redis uses `allkeys-lru` eviction. Cache warms naturally as users make requests. No manual warm-up script is needed — cache misses fall through to PostgreSQL. +**Warm-up:** Redis dùng eviction `allkeys-lru`. Cache tự ấm dần khi người dùng gửi request. Không cần script warm-up thủ công — cache miss sẽ đi thẳng xuống PostgreSQL. -**When to flush:** -- After database restore (stale cache references) -- After data corruption at the application level -- After schema changes that alter cached data structures +**Khi nào cần flush:** +- Sau khi restore database (cache tham chiếu cũ) +- Sau khi dữ liệu bị hỏng ở tầng ứng dụng +- Sau khi thay đổi schema làm thay đổi cấu trúc dữ liệu được cache -### 4.3 Rolling Restart Procedures +### 4.3 Quy trình rolling restart -#### Single Service Restart (Zero Downtime) +#### Restart từng dịch vụ (Zero Downtime) ```bash -# API — the --wait flag ensures health check passes before moving on +# API — cờ --wait đảm bảo health check pass trước khi tiếp tục docker compose -f docker-compose.prod.yml up -d --no-deps --wait api # Web @@ -670,78 +670,78 @@ docker compose -f docker-compose.prod.yml up -d --no-deps --wait web docker compose -f docker-compose.prod.yml up -d --no-deps --wait ai-services ``` -#### Full Stack Rolling Restart +#### Rolling restart toàn bộ stack ```bash -# Data services first (order matters for dependency chain) +# Các dịch vụ dữ liệu trước (thứ tự quan trọng theo chuỗi phụ thuộc) docker compose -f docker-compose.prod.yml restart redis docker compose -f docker-compose.prod.yml restart typesense -# Wait for data services to be healthy +# Chờ các dịch vụ dữ liệu healthy sleep 10 # Connection pooling docker compose -f docker-compose.prod.yml restart pgbouncer sleep 5 -# Application services +# Các dịch vụ ứng dụng docker compose -f docker-compose.prod.yml up -d --no-deps --wait api docker compose -f docker-compose.prod.yml up -d --no-deps --wait web docker compose -f docker-compose.prod.yml up -d --no-deps --wait ai-services -# Verify +# Xác minh curl -sf http://localhost:3001/health/ready | jq . ``` -#### Emergency: Restart Everything +#### Khẩn cấp: Restart mọi thứ ```bash docker compose -f docker-compose.prod.yml down docker compose -f docker-compose.prod.yml up -d --wait ``` -### 4.4 Rollback Deployment +### 4.4 Rollback deployment -#### How Rollback Images Work +#### Cách hoạt động của Rollback Image -Every deploy (both CI/CD and manual) tags the current running images as `:rollback` **before** pulling new ones. This ensures the previous version is preserved even if `docker image prune` runs. The `:rollback` tags are only cleaned up after smoke tests pass. +Mỗi lần deploy (cả CI/CD lẫn thủ công) đều gắn tag `:rollback` cho image hiện đang chạy **trước khi** pull image mới. Điều này đảm bảo phiên bản trước được giữ lại ngay cả khi `docker image prune` chạy. Các tag `:rollback` chỉ được dọn dẹp sau khi smoke test pass. -Image lifecycle during deploy: -1. `docker tag goodgo-api:rollback` (preserves previous version) -2. `docker compose pull` (fetches new images) -3. `docker compose up` (starts new version) -4. Smoke tests run -5. **If smoke tests pass:** `:rollback` tags are removed, `docker image prune` runs -6. **If smoke tests fail:** `:rollback` images are retagged to match the compose template and services are restarted +Vòng đời image trong quá trình deploy: +1. `docker tag goodgo-api:rollback` (giữ lại phiên bản trước) +2. `docker compose pull` (kéo image mới) +3. `docker compose up` (khởi động phiên bản mới) +4. Chạy smoke test +5. **Nếu smoke test pass:** xóa tag `:rollback`, chạy `docker image prune` +6. **Nếu smoke test thất bại:** các image `:rollback` được đổi tag để khớp với template của compose và các dịch vụ được khởi động lại -#### Automatic Rollback (CI/CD) +#### Rollback tự động (CI/CD) -The CI/CD pipeline (`.github/workflows/deploy.yml`) automatically triggers rollback if smoke tests fail. The rollback job: -1. Stops the broken containers -2. Retags `:rollback` images to match the compose image template (`${REGISTRY_URL}/goodgo-{svc}:${IMAGE_TAG}`) -3. Restarts compose — which now resolves to the previous (working) images -4. Sends a Slack notification to `#deployments` +Pipeline CI/CD (`.github/workflows/deploy.yml`) tự động kích hoạt rollback nếu smoke test thất bại. Job rollback sẽ: +1. Dừng các container bị lỗi +2. Đổi tag các image `:rollback` để khớp với template image của compose (`${REGISTRY_URL}/goodgo-{svc}:${IMAGE_TAG}`) +3. Khởi động lại compose — lúc này sẽ resolve về image trước đó (đang hoạt động) +4. Gửi thông báo Slack tới `#deployments` -No manual intervention is needed for CI-triggered deploys. +Không cần can thiệp thủ công cho các deploy do CI kích hoạt. -#### Quick Rollback Using :rollback Tags (Manual) +#### Rollback nhanh dùng tag :rollback (Thủ công) ```bash -# SSH into the host +# SSH vào host ssh deploy@$PRODUCTION_HOST cd ~/goodgo -# Verify rollback images exist +# Xác minh các image rollback có tồn tại for svc in goodgo-api goodgo-web goodgo-ai-services; do docker image inspect "${svc}:rollback" > /dev/null 2>&1 \ && echo "OK: ${svc}:rollback" \ || echo "MISSING: ${svc}:rollback" done -# Stop current containers +# Dừng các container hiện tại docker compose -f docker-compose.prod.yml stop api web ai-services -# Retag rollback images to match compose template +# Đổi tag image rollback để khớp với template compose export REGISTRY_URL=ghcr.io/goodgo export IMAGE_TAG=$(docker inspect --format='{{index .Config.Labels "org.opencontainers.image.revision"}}' goodgo-api 2>/dev/null || echo "latest") @@ -749,31 +749,31 @@ for svc in goodgo-api goodgo-web goodgo-ai-services; do docker tag "${svc}:rollback" "${REGISTRY_URL}/${svc}:${IMAGE_TAG}" done -# Restart with rollback images +# Khởi động lại với image rollback docker compose -f docker-compose.prod.yml up -d --no-deps --wait api web ai-services -# Verify +# Xác minh curl -sf http://localhost:3001/health && echo "Rollback successful" ``` -#### Rollback Using deploy-production.sh (Manual Script) +#### Rollback dùng deploy-production.sh (Script thủ công) -The manual deploy script (`scripts/deploy-production.sh`) has built-in rollback. If the health check or smoke test fails, it automatically restores from `:rollback` tagged images and restarts services. +Script deploy thủ công (`scripts/deploy-production.sh`) có tích hợp sẵn rollback. Nếu health check hoặc smoke test thất bại, script sẽ tự động khôi phục từ các image được gắn tag `:rollback` và khởi động lại dịch vụ. ```bash -# Run the manual deploy — rollback is automatic on failure +# Chạy deploy thủ công — rollback tự động khi thất bại cd ~/goodgo ./scripts/deploy-production.sh ``` -#### Rollback to a Specific Git Commit / Image Tag +#### Rollback về một Git commit / image tag cụ thể ```bash -# Set the target tag (git SHA) +# Đặt tag mục tiêu (git SHA) export IMAGE_TAG= export REGISTRY_URL=ghcr.io/goodgo -# Pull specific version +# Pull phiên bản cụ thể docker compose -f docker-compose.prod.yml pull api web ai-services # Deploy @@ -781,331 +781,331 @@ docker compose -f docker-compose.prod.yml up -d --no-deps --wait api docker compose -f docker-compose.prod.yml up -d --no-deps --wait web docker compose -f docker-compose.prod.yml up -d --no-deps --wait ai-services -# Verify +# Xác minh curl -sf http://localhost:3001/health/ready | jq . ``` -#### Rollback Database Migrations +#### Rollback migration database ```bash -# WARNING: Prisma does not support automatic down-migrations. -# For migration rollback, restore from the pre-migration backup: +# CẢNH BÁO: Prisma không hỗ trợ down-migration tự động. +# Để rollback migration, khôi phục từ backup trước khi migration: -# 1. Stop application +# 1. Dừng ứng dụng docker compose -f docker-compose.prod.yml stop api web ai-services pgbouncer -# 2. Restore from backup taken before the migration +# 2. Khôi phục từ backup đã tạo trước khi migration docker exec -it goodgo-pg-backup /scripts/pg-restore.sh /backups/.sql.gz -# 3. Deploy the previous code version (older IMAGE_TAG) +# 3. Deploy phiên bản code trước đó (IMAGE_TAG cũ hơn) export IMAGE_TAG= docker compose -f docker-compose.prod.yml up -d --wait ``` -### 4.5 Typesense Reindex from PostgreSQL +### 4.5 Reindex Typesense từ PostgreSQL -If Typesense data is lost or corrupted, rebuild the search index from PostgreSQL: +Nếu dữ liệu Typesense bị mất hoặc hỏng, rebuild index tìm kiếm từ PostgreSQL: ```bash -# 1. Ensure Typesense is running and healthy +# 1. Đảm bảo Typesense đang chạy và healthy curl -sf -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" http://localhost:8108/health -# 2. Run reindex +# 2. Chạy reindex docker compose -f docker-compose.prod.yml exec api npx ts-node scripts/typesense-reindex.ts -# Or from host: +# Hoặc từ host: pnpm run typesense:reindex -# 3. Verify collections +# 3. Xác minh collection curl -sf -H "X-TYPESENSE-API-KEY: ${TYPESENSE_API_KEY}" http://localhost:8108/collections | jq '.[].name' ``` -### 4.6 Full Host Recovery +### 4.6 Khôi phục toàn bộ host -For complete host failure or migration to a new server: +Dành cho trường hợp host bị lỗi hoàn toàn hoặc di chuyển sang máy chủ mới: ```bash -# 1. Provision new host with Docker + Docker Compose -# Requirements: Docker >= 24, Docker Compose v2, 8 GB RAM minimum +# 1. Cung cấp host mới với Docker + Docker Compose +# Yêu cầu: Docker >= 24, Docker Compose v2, tối thiểu 8 GB RAM -# 2. Clone repository and configure +# 2. Clone repository và cấu hình git clone ~/goodgo && cd ~/goodgo cp .env.example .env -# Edit .env with production secrets (from secrets manager) +# Chỉnh sửa .env với các secret production (từ secrets manager) -# 3. Restore PostgreSQL backup from off-site storage -# Transfer backup file to the new host +# 3. Khôi phục backup PostgreSQL từ bộ lưu trữ off-site +# Chuyển file backup sang host mới scp backups/goodgo_latest.sql.gz deploy@newhost:~/goodgo/backups/ -# 4. Start infrastructure services +# 4. Khởi động các dịch vụ hạ tầng docker compose -f docker-compose.prod.yml up -d postgres redis typesense minio -# 5. Wait for PostgreSQL to be ready, then restore +# 5. Chờ PostgreSQL sẵn sàng, sau đó restore docker compose -f docker-compose.prod.yml exec postgres pg_isready docker exec goodgo-pg-backup /scripts/pg-restore.sh /backups/goodgo_latest.sql.gz -# 6. Start application services +# 6. Khởi động các dịch vụ ứng dụng docker compose -f docker-compose.prod.yml up -d -# 7. Run migrations (if backup predates latest code) +# 7. Chạy migration (nếu backup cũ hơn code mới nhất) docker compose -f docker-compose.prod.yml exec api npx prisma migrate deploy -# 8. Rebuild Typesense index +# 8. Rebuild index Typesense pnpm run typesense:reindex -# 9. Flush Redis (stale cache from old host) +# 9. Flush Redis (cache cũ từ host cũ) docker exec goodgo-redis redis-cli -a "${REDIS_PASSWORD}" FLUSHALL -# 10. Verify everything +# 10. Xác minh mọi thứ curl -sf http://localhost:3001/health/ready | jq . curl -sf http://localhost:3000 > /dev/null && echo "Web OK" -# Expected RTO: ~60 minutes (depends on backup transfer speed) +# RTO dự kiến: ~60 phút (phụ thuộc tốc độ truyền backup) ``` --- -## 5. Escalation Matrix +## 5. Ma trận leo thang -| Severity | Condition | First Responder | Escalation | SLA | +| Mức độ | Điều kiện | Người phản hồi đầu tiên | Leo thang | SLA | |----------|-----------|-----------------|------------|-----| -| **P0 — Critical** | Full outage, data loss, payment corruption | On-call SRE | CTO + CEO within 15 min | Acknowledge: 5 min, Resolve: 1 hour | -| **P1 — High** | Partial outage, SLO breach (p99 > 3s), 5xx > 5% | On-call SRE | Engineering lead within 30 min | Acknowledge: 15 min, Resolve: 4 hours | -| **P2 — Medium** | Degraded performance, single service down (non-critical), p99 > 1s | On-call SRE | Team lead next business day | Acknowledge: 1 hour, Resolve: 24 hours | -| **P3 — Low** | Cosmetic issues, monitoring gaps, non-urgent improvements | Assigned engineer | Sprint planning | Next sprint | +| **P0 — Nghiêm trọng** | Ngừng dịch vụ hoàn toàn, mất dữ liệu, hỏng thanh toán | SRE on-call | CTO + CEO trong 15 phút | Acknowledge: 5 phút, Resolve: 1 giờ | +| **P1 — Cao** | Ngừng một phần, vi phạm SLO (p99 > 3s), 5xx > 5% | SRE on-call | Engineering lead trong 30 phút | Acknowledge: 15 phút, Resolve: 4 giờ | +| **P2 — Trung bình** | Hiệu năng suy giảm, một dịch vụ (không trọng yếu) bị down, p99 > 1s | SRE on-call | Team lead vào ngày làm việc kế tiếp | Acknowledge: 1 giờ, Resolve: 24 giờ | +| **P3 — Thấp** | Vấn đề về thẩm mỹ, thiếu giám sát, cải tiến không cấp bách | Kỹ sư được giao | Sprint planning | Sprint tiếp theo | -### Contact Channels +### Kênh liên lạc -| Role | Channel | +| Vai trò | Kênh | |------|---------| -| On-call SRE | Slack `#sre-oncall` + PagerDuty | +| SRE on-call | Slack `#sre-oncall` + PagerDuty | | Engineering Lead | Slack `#engineering` | -| CTO | Slack DM / Phone (see PagerDuty) | -| Payment Issues | Slack `#payments` + VNPay/MoMo support portals | -| Infrastructure | Slack `#infrastructure` | +| CTO | Slack DM / Điện thoại (xem PagerDuty) | +| Vấn đề thanh toán | Slack `#payments` + cổng hỗ trợ VNPay/MoMo | +| Hạ tầng | Slack `#infrastructure` | -### Slack Notifications +### Thông báo Slack -The deploy pipeline automatically notifies `#deployments` (via `SLACK_WEBHOOK_URL`) on: -- Production deploy success -- Staging smoke test failure -- Production rollback triggered +Pipeline deploy tự động thông báo tới `#deployments` (qua `SLACK_WEBHOOK_URL`) khi: +- Deploy production thành công +- Smoke test staging thất bại +- Rollback production được kích hoạt --- -## 6. Monitoring Dashboards +## 6. Dashboard giám sát -All dashboards are provisioned automatically via `monitoring/grafana/provisioning/` and are available in the **GoodGo** folder in Grafana. +Tất cả dashboard được provision tự động qua `monitoring/grafana/provisioning/` và có sẵn trong thư mục **GoodGo** trên Grafana. -| Dashboard | Grafana Path | Purpose | +| Dashboard | Đường dẫn Grafana | Mục đích | |-----------|--------------|---------| -| **API Overview** | `api-overview` | Request rates, status codes, active connections | -| **API Latency** | `api-latency` | p50/p95/p99 latency by endpoint, latency heatmaps | -| **Database** | `database` | PostgreSQL connections, query performance, PgBouncer stats | -| **Search** | `search` | Typesense query rates, latency, index sizes | -| **Business Metrics** | `business-metrics` | Listings, inquiries, payments, user registrations | -| **Web Vitals** | `web-vitals` | Core Web Vitals (LCP, FID, CLS), page load times | -| **Logs** | `logs` | Loki log explorer with filters by service, level, correlation ID | +| **API Overview** | `api-overview` | Tốc độ request, status code, kết nối active | +| **API Latency** | `api-latency` | Latency p50/p95/p99 theo endpoint, heatmap latency | +| **Database** | `database` | Kết nối PostgreSQL, hiệu năng truy vấn, thống kê PgBouncer | +| **Search** | `search` | Tốc độ truy vấn Typesense, latency, kích thước index | +| **Business Metrics** | `business-metrics` | Tin đăng, inquiry, thanh toán, đăng ký người dùng | +| **Web Vitals** | `web-vitals` | Core Web Vitals (LCP, FID, CLS), thời gian load trang | +| **Logs** | `logs` | Explorer log Loki với filter theo service, level, correlation ID | -**Access:** `http://localhost:3002` (default credentials in `.env`: `GRAFANA_ADMIN_USER` / `GRAFANA_ADMIN_PASSWORD`) +**Truy cập:** `http://localhost:3002` (credential mặc định trong `.env`: `GRAFANA_ADMIN_USER` / `GRAFANA_ADMIN_PASSWORD`) -**Data Sources:** -- **Prometheus** (`http://prometheus:9090`) — Metrics (default) -- **Loki** (`http://loki:3100`) — Logs, with correlation ID linking to Prometheus -- **Alertmanager** (`http://alertmanager:9093`) — Alert state and silences +**Nguồn dữ liệu:** +- **Prometheus** (`http://prometheus:9090`) — Metric (mặc định) +- **Loki** (`http://loki:3100`) — Log, có correlation ID liên kết với Prometheus +- **Alertmanager** (`http://alertmanager:9093`) — Trạng thái alert và silence --- -## 7. Useful PromQL Queries +## 7. Truy vấn PromQL hữu ích -### API Performance +### Hiệu năng API ```promql -# Overall p99 latency +# Latency p99 tổng thể histogram_quantile(0.99, sum(rate(goodgo_api_request_duration_seconds_bucket{job="goodgo-api"}[5m])) by (le)) -# Per-endpoint p99 latency (top 10 slowest) +# Latency p99 theo từng endpoint (top 10 chậm nhất) topk(10, histogram_quantile(0.99, sum(rate(goodgo_api_request_duration_seconds_bucket{job="goodgo-api"}[5m])) by (le, route, method))) -# Request rate by status code +# Tốc độ request theo status code sum(rate(http_requests_total{job="goodgo-api"}[5m])) by (status_code) -# 5xx error percentage +# Phần trăm lỗi 5xx (sum(rate(http_requests_total{job="goodgo-api", status_code=~"5.."}[5m])) / sum(rate(http_requests_total{job="goodgo-api"}[5m]))) * 100 ``` ### Database ```promql -# Active connections +# Kết nối active pg_stat_activity_count{datname="goodgo", state="active"} -# Connection pool utilization (if PgBouncer metrics are scraped) -# Manual check via: SHOW POOLS in PgBouncer admin console +# Tỷ lệ sử dụng connection pool (nếu metric PgBouncer được scrape) +# Kiểm tra thủ công qua: SHOW POOLS trong admin console PgBouncer ``` -### Infrastructure +### Hạ tầng ```promql -# Container memory usage +# Sử dụng memory của container container_memory_usage_bytes{name=~"goodgo-.*"} -# Container CPU usage +# Sử dụng CPU của container rate(container_cpu_usage_seconds_total{name=~"goodgo-.*"}[5m]) ``` --- -## 8. Environment Quick Reference +## 8. Tham chiếu nhanh môi trường -### Key Environment Variables +### Biến môi trường chính -| Variable | Required | Description | +| Biến | Bắt buộc | Mô tả | |----------|----------|-------------| -| `DATABASE_URL` | Yes | PostgreSQL via PgBouncer (`postgresql://user:pass@pgbouncer:6432/db`) | -| `DATABASE_URL_DIRECT` | Yes (prod) | Direct PostgreSQL for migrations (`postgresql://user:pass@postgres:5432/db`) | -| `JWT_SECRET` | Yes | JWT signing secret | -| `JWT_REFRESH_SECRET` | Yes | Refresh token signing secret | -| `REDIS_URL` | Yes | Redis connection (`redis://:password@redis:6379`) | -| `REDIS_PASSWORD` | Yes (prod) | Redis auth password | -| `TYPESENSE_API_KEY` | Yes | Typesense admin API key | -| `MINIO_ACCESS_KEY` | Yes | MinIO root user | -| `MINIO_SECRET_KEY` | Yes | MinIO root password | -| `VNPAY_*` | Yes | VNPay payment gateway configuration | -| `AI_API_KEY` | Yes | AI services authentication | -| `GRAFANA_ADMIN_USER` | Yes (prod) | Grafana admin username | -| `GRAFANA_ADMIN_PASSWORD` | Yes (prod) | Grafana admin password | -| `PGBOUNCER_POOL_SIZE` | No | PgBouncer pool size (default: 20) | -| `PGBOUNCER_MAX_CLIENT_CONN` | No | Max PgBouncer client connections (default: 200) | -| `BACKUP_RETENTION_DAYS` | No | Backup retention period (default: 7) | -| `IMAGE_TAG` | No (prod) | Container image tag (default: `latest`) | +| `DATABASE_URL` | Có | PostgreSQL qua PgBouncer (`postgresql://user:pass@pgbouncer:6432/db`) | +| `DATABASE_URL_DIRECT` | Có (prod) | PostgreSQL trực tiếp cho migration (`postgresql://user:pass@postgres:5432/db`) | +| `JWT_SECRET` | Có | Secret ký JWT | +| `JWT_REFRESH_SECRET` | Có | Secret ký refresh token | +| `REDIS_URL` | Có | Kết nối Redis (`redis://:password@redis:6379`) | +| `REDIS_PASSWORD` | Có (prod) | Mật khẩu auth Redis | +| `TYPESENSE_API_KEY` | Có | API key admin của Typesense | +| `MINIO_ACCESS_KEY` | Có | Root user của MinIO | +| `MINIO_SECRET_KEY` | Có | Mật khẩu root của MinIO | +| `VNPAY_*` | Có | Cấu hình payment gateway VNPay | +| `AI_API_KEY` | Có | Xác thực AI services | +| `GRAFANA_ADMIN_USER` | Có (prod) | Username admin Grafana | +| `GRAFANA_ADMIN_PASSWORD` | Có (prod) | Mật khẩu admin Grafana | +| `PGBOUNCER_POOL_SIZE` | Không | Kích thước pool PgBouncer (mặc định: 20) | +| `PGBOUNCER_MAX_CLIENT_CONN` | Không | Số client connection tối đa của PgBouncer (mặc định: 200) | +| `BACKUP_RETENTION_DAYS` | Không | Thời gian lưu giữ backup (mặc định: 7) | +| `IMAGE_TAG` | Không (prod) | Tag image container (mặc định: `latest`) | -### Port Map +### Bản đồ cổng -| Port | Service | Exposed | +| Cổng | Dịch vụ | Phơi bày | |------|---------|---------| -| 3000 | Web (Next.js) | External | -| 3001 | API (NestJS) | External | -| 3002 | Grafana | External (admin only) | -| 5432 | PostgreSQL | Internal | -| 6432 | PgBouncer | Internal | -| 6379 | Redis | Internal | -| 8000 | AI Services | Internal | -| 8108 | Typesense | Internal | -| 9000 | MinIO API | Internal | -| 9001 | MinIO Console | Internal | -| 9090 | Prometheus | Internal | -| 3100 | Loki | Internal | +| 3000 | Web (Next.js) | Bên ngoài | +| 3001 | API (NestJS) | Bên ngoài | +| 3002 | Grafana | Bên ngoài (chỉ admin) | +| 5432 | PostgreSQL | Nội bộ | +| 6432 | PgBouncer | Nội bộ | +| 6379 | Redis | Nội bộ | +| 8000 | AI Services | Nội bộ | +| 8108 | Typesense | Nội bộ | +| 9000 | MinIO API | Nội bộ | +| 9001 | MinIO Console | Nội bộ | +| 9090 | Prometheus | Nội bộ | +| 3100 | Loki | Nội bộ | -### Docker Volumes +### Docker Volume -| Volume | Service | Purpose | +| Volume | Dịch vụ | Mục đích | |--------|---------|---------| -| `pgdata` | PostgreSQL | Database files | -| `redis_data` | Redis | AOF persistence | -| `typesense_data` | Typesense | Search index data | -| `minio_data` | MinIO | Object storage (images, files) | -| `pg_backups` | pg-backup | Database backup files | -| `loki_data` | Loki | Log storage (15-day retention) | -| `prometheus_data` | Prometheus | Metrics (30-day retention prod / 15-day dev) | -| `grafana_data` | Grafana | Dashboard state, user preferences | +| `pgdata` | PostgreSQL | File database | +| `redis_data` | Redis | Bền vững AOF | +| `typesense_data` | Typesense | Dữ liệu index tìm kiếm | +| `minio_data` | MinIO | Object storage (ảnh, file) | +| `pg_backups` | pg-backup | File backup database | +| `loki_data` | Loki | Lưu trữ log (retention 15 ngày) | +| `prometheus_data` | Prometheus | Metric (retention 30 ngày prod / 15 ngày dev) | +| `grafana_data` | Grafana | Trạng thái dashboard, tùy chọn người dùng | --- -## 9. Disaster Recovery Validation +## 9. Xác thực Disaster Recovery -### Automated Verification +### Xác minh tự động -Backup verification runs **daily at 04:00 UTC** inside the `pg-backup` container. It restores the latest backup to an isolated test database and checks: +Xác minh backup chạy **hàng ngày lúc 04:00 UTC** bên trong container `pg-backup`. Nó khôi phục backup mới nhất vào một database test cô lập và kiểm tra: -- Table existence (all 22 Prisma models) -- Row count comparison against live database -- Data checksums on critical tables (User, Property, Listing, Payment, Subscription, Transaction, Plan) -- PostGIS extension availability -- Index count match -- Enum type count match +- Sự tồn tại của table (tất cả 22 Prisma model) +- So sánh số dòng với database live +- Checksum dữ liệu trên các bảng quan trọng (User, Property, Listing, Payment, Subscription, Transaction, Plan) +- Khả dụng của extension PostGIS +- Khớp số lượng index +- Khớp số lượng enum type -**Check latest verification report:** +**Kiểm tra báo cáo xác minh mới nhất:** ```bash docker exec goodgo-pg-backup cat /backups/verify-latest.json | jq . ``` -**Check verification logs:** +**Kiểm tra log xác minh:** ```bash docker exec goodgo-pg-backup cat /var/log/pg-verify.log ``` -### Manual DR Validation Procedure +### Quy trình xác thực DR thủ công -Run this quarterly (or after major schema changes) to validate the full DR process end-to-end. +Chạy hàng quý (hoặc sau khi thay đổi schema lớn) để xác thực toàn bộ quy trình DR end-to-end. -#### Step 1: Verify Backups Exist and Are Recent +#### Bước 1: Xác minh backup tồn tại và mới ```bash -# List backups with timestamps and sizes +# Liệt kê backup kèm timestamp và kích thước docker exec goodgo-pg-backup ls -lht /backups/goodgo_*.sql.gz -# Verify latest backup is < 25 hours old +# Xác minh backup mới nhất dưới 25 giờ tuổi LATEST=$(docker exec goodgo-pg-backup ls -t /backups/goodgo_*.sql.gz | head -1) echo "Latest backup: $LATEST" ``` -#### Step 2: Run Verification Against Latest Backup +#### Bước 2: Chạy xác minh trên backup mới nhất ```bash -# Automated verification (creates temp DB, validates, drops) +# Xác minh tự động (tạo DB tạm, validate, drop) docker exec -e REPORT_FILE=/backups/verify-latest.json goodgo-pg-backup \ /scripts/pg-verify-backup.sh -# Review results +# Xem xét kết quả docker exec goodgo-pg-backup cat /backups/verify-latest.json | jq . ``` -**Expected output:** All checks pass, restore completes in < 60 seconds for typical dataset. +**Kết quả mong đợi:** Tất cả các kiểm tra pass, việc restore hoàn thành trong < 60 giây với dataset thông thường. -#### Step 3: Test Full Restore (Staging Only) +#### Bước 3: Test restore đầy đủ (chỉ trên Staging) -> ⚠️ **WARNING:** Only perform this on a staging or isolated environment. Never on production. +> ⚠️ **CẢNH BÁO:** Chỉ thực hiện trên môi trường staging hoặc môi trường cô lập. Không bao giờ trên production. ```bash -# 1. Create a separate test environment +# 1. Tạo môi trường test riêng biệt docker compose -f docker-compose.yml -p goodgo-dr-test up -d postgres -# 2. Wait for PostgreSQL to be ready +# 2. Chờ PostgreSQL sẵn sàng docker exec goodgo-dr-test-postgres-1 pg_isready -# 3. Run restore against the test environment +# 3. Chạy restore vào môi trường test PGHOST=localhost PGPORT= PGUSER=goodgo PGPASSWORD= \ /scripts/pg-restore.sh /backups/.sql.gz -# 4. Verify key tables +# 4. Xác minh các bảng quan trọng docker exec goodgo-dr-test-postgres-1 psql -U goodgo -d goodgo -c \ "SELECT count(*) FROM \"User\"; SELECT count(*) FROM \"Property\"; SELECT count(*) FROM \"Listing\";" -# 5. Clean up test environment +# 5. Dọn dẹp môi trường test docker compose -f docker-compose.yml -p goodgo-dr-test down -v ``` -#### Step 4: Validate Service Recovery Chain +#### Bước 4: Xác thực chuỗi khôi phục dịch vụ -Test that all services can start from a clean state with restored data: +Kiểm tra rằng tất cả dịch vụ có thể khởi động từ trạng thái sạch với dữ liệu đã khôi phục: ```bash -# 1. Note current service status +# 1. Ghi chú trạng thái dịch vụ hiện tại docker compose -f docker-compose.prod.yml ps --format "table {{.Name}}\t{{.Status}}\t{{.Health}}" -# 2. Restart all services in dependency order +# 2. Khởi động lại tất cả dịch vụ theo thứ tự phụ thuộc docker compose -f docker-compose.prod.yml restart postgres -sleep 10 # Wait for PostgreSQL +sleep 10 # Chờ PostgreSQL docker compose -f docker-compose.prod.yml restart pgbouncer redis typesense -sleep 10 # Wait for data services +sleep 10 # Chờ các dịch vụ dữ liệu docker compose -f docker-compose.prod.yml restart api web ai-services -sleep 15 # Wait for application services +sleep 15 # Chờ các dịch vụ ứng dụng -# 3. Verify all health checks +# 3. Xác minh tất cả health check curl -sf http://localhost:3001/health/ready | jq . curl -sf http://localhost:3000 > /dev/null && echo "Web OK" curl -sf http://localhost:9090/-/healthy && echo "Prometheus OK" @@ -1113,114 +1113,114 @@ curl -sf http://localhost:9093/-/healthy && echo "Alertmanager OK" curl -sf http://localhost:3002/api/health | jq . ``` -#### Step 5: Validate Alerting Pipeline +#### Bước 5: Xác thực pipeline cảnh báo ```bash -# 1. Check Prometheus is loading alert rules +# 1. Kiểm tra Prometheus đang load các alert rule curl -sf http://localhost:9090/api/v1/rules | jq '.data.groups | length' -# Expected: 7 groups +# Mong đợi: 7 group -# 2. Check current alerts (should be empty if healthy) +# 2. Kiểm tra các alert hiện tại (phải rỗng nếu khỏe mạnh) curl -sf http://localhost:9090/api/v1/alerts | jq '.data.alerts | length' -# 3. Check Alertmanager is receiving from Prometheus +# 3. Kiểm tra Alertmanager đang nhận từ Prometheus curl -sf http://localhost:9093/api/v2/status | jq '.cluster' -# 4. Verify Alertmanager config is loaded +# 4. Xác minh cấu hình Alertmanager đã được load curl -sf http://localhost:9093/api/v2/status | jq '.config' ``` -### DR Validation Checklist +### Danh sách kiểm tra xác thực DR -Use this checklist during quarterly DR reviews: +Dùng danh sách này trong các đợt review DR hàng quý: -- [ ] Latest backup is < 25 hours old -- [ ] Automated verification report shows all checks passed -- [ ] Manual restore to test DB succeeds with correct row counts -- [ ] Full service restart completes within RTO target (< 30 min) -- [ ] All health endpoints respond after restart -- [ ] Prometheus alert rules are loaded (7 groups) -- [ ] Alertmanager is reachable and configured -- [ ] Slack notification channel is receiving test alerts -- [ ] Grafana dashboards show data after restart -- [ ] Typesense search returns results after restart +- [ ] Backup mới nhất dưới 25 giờ tuổi +- [ ] Báo cáo xác minh tự động cho thấy tất cả kiểm tra pass +- [ ] Restore thủ công vào DB test thành công với số dòng chính xác +- [ ] Restart đầy đủ dịch vụ hoàn thành trong mục tiêu RTO (< 30 phút) +- [ ] Tất cả các health endpoint phản hồi sau khi restart +- [ ] Alert rule Prometheus đã được load (7 group) +- [ ] Alertmanager có thể truy cập và đã được cấu hình +- [ ] Kênh thông báo Slack nhận được cảnh báo test +- [ ] Dashboard Grafana hiển thị dữ liệu sau khi restart +- [ ] Tìm kiếm Typesense trả về kết quả sau khi restart -### RPO/RTO Summary +### Tóm tắt RPO/RTO -| Metric | Target | Actual (Measured) | Notes | +| Chỉ số | Mục tiêu | Thực tế (đo được) | Ghi chú | |--------|--------|-------------------|-------| -| **RPO** | ≤ 24 hours | ~24h (daily at 02:00 UTC) | Reduce with WAL archiving | -| **RTO — Local backup** | ≤ 15 minutes | Measure during DR test | Restore + service restart | -| **RTO — Off-site backup** | ≤ 30 minutes | Measure during DR test | Add transfer time | -| **RTO — Full host recovery** | ≤ 60 minutes | Measure during DR test | New host + restore + deploy | +| **RPO** | ≤ 24 giờ | ~24h (hàng ngày lúc 02:00 UTC) | Giảm bằng WAL archiving | +| **RTO — Backup local** | ≤ 15 phút | Đo trong DR test | Restore + restart dịch vụ | +| **RTO — Backup off-site** | ≤ 30 phút | Đo trong DR test | Cộng thêm thời gian chuyển dữ liệu | +| **RTO — Khôi phục toàn bộ host** | ≤ 60 phút | Đo trong DR test | Host mới + restore + deploy | --- -## Appendix: Alert Rules Reference +## Phụ lục: Tham chiếu Alert Rule -### API & Error Alerts +### Alert API & Lỗi -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `ApiLatencyP99High` | p99 > 1s | Warning | 5 min | -| `ApiEndpointLatencyP99High` | Per-route p99 > 2s | Warning | 5 min | -| `ApiLatencyP99Critical` | p99 > 3s (SLO breach) | Critical | 3 min | -| `ApiErrorRate5xxHigh` | 5xx rate > 1% | Warning | 5 min | -| `ApiErrorRate5xxCritical` | 5xx rate > 5% | Critical | 3 min | -| `ApiNoTraffic` | Request rate = 0 | Warning | 10 min | +| `ApiLatencyP99High` | p99 > 1s | Warning | 5 phút | +| `ApiEndpointLatencyP99High` | p99 theo từng route > 2s | Warning | 5 phút | +| `ApiLatencyP99Critical` | p99 > 3s (vi phạm SLO) | Critical | 3 phút | +| `ApiErrorRate5xxHigh` | Tỷ lệ 5xx > 1% | Warning | 5 phút | +| `ApiErrorRate5xxCritical` | Tỷ lệ 5xx > 5% | Critical | 3 phút | +| `ApiNoTraffic` | Tốc độ request = 0 | Warning | 10 phút | -### Database Alerts +### Alert Database -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `PostgresActiveConnectionsHigh` | Active connections > 15 | Warning | 5 min | -| `PostgresConnectionPoolCritical` | Total connections > 180 | Critical | 2 min | -| `PostgresSlowQueries` | Lock-waiting queries > 5 | Warning | 5 min | -| `PostgresDown` | API scrape target down | Critical | 1 min | +| `PostgresActiveConnectionsHigh` | Kết nối active > 15 | Warning | 5 phút | +| `PostgresConnectionPoolCritical` | Tổng số kết nối > 180 | Critical | 2 phút | +| `PostgresSlowQueries` | Truy vấn chờ lock > 5 | Warning | 5 phút | +| `PostgresDown` | Scrape target của API down | Critical | 1 phút | -### Redis Alerts +### Alert Redis -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `RedisMemoryHigh` | Memory usage > 80% | Warning | 5 min | -| `RedisMemoryCritical` | Memory usage > 95% | Critical | 2 min | -| `RedisConnectedClientsHigh` | Clients > 150 | Warning | 5 min | -| `RedisRejectedConnections` | Rejected connections > 0 | Critical | 1 min | +| `RedisMemoryHigh` | Sử dụng memory > 80% | Warning | 5 phút | +| `RedisMemoryCritical` | Sử dụng memory > 95% | Critical | 2 phút | +| `RedisConnectedClientsHigh` | Số client > 150 | Warning | 5 phút | +| `RedisRejectedConnections` | Kết nối bị từ chối > 0 | Critical | 1 phút | -### Container Resource Alerts +### Alert Tài nguyên Container -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `ContainerRestartLoop` | > 3 restarts in 15 min | Critical | 5 min | -| `ContainerMemoryHigh` | Memory > 85% of limit | Warning | 5 min | -| `ContainerCPUThrottled` | CPU throttle rate > 0.5s/s | Warning | 10 min | +| `ContainerRestartLoop` | > 3 lần restart trong 15 phút | Critical | 5 phút | +| `ContainerMemoryHigh` | Memory > 85% giới hạn | Warning | 5 phút | +| `ContainerCPUThrottled` | Tỷ lệ CPU throttle > 0.5s/s | Warning | 10 phút | -### Disk & Infrastructure Alerts +### Alert Đĩa & Hạ tầng -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `HostDiskUsageHigh` | Root disk > 80% | Warning | 10 min | -| `HostDiskUsageCritical` | Root disk > 90% | Critical | 5 min | -| `ApiHealthCheckFailing` | Health probe fails | Critical | 2 min | -| `PrometheusTargetDown` | Scrape target down | Warning | 5 min | +| `HostDiskUsageHigh` | Đĩa root > 80% | Warning | 10 phút | +| `HostDiskUsageCritical` | Đĩa root > 90% | Critical | 5 phút | +| `ApiHealthCheckFailing` | Health probe thất bại | Critical | 2 phút | +| `PrometheusTargetDown` | Scrape target down | Warning | 5 phút | -### Backup Alerts +### Alert Backup -| Alert | Expression | Severity | Duration | +| Alert | Biểu thức | Mức độ | Thời lượng | |-------|-----------|----------|----------| -| `BackupTooOld` | Last backup > 25 hours ago | Warning | 5 min | -| `BackupVerificationFailed` | Verify result = fail | Warning | 1 min | +| `BackupTooOld` | Backup cuối > 25 giờ trước | Warning | 5 phút | +| `BackupVerificationFailed` | Kết quả verify = fail | Warning | 1 phút | -### Alert Routing +### Routing Alert -Alerts are routed via Alertmanager (`monitoring/alertmanager/alertmanager.yml`): +Alert được route qua Alertmanager (`monitoring/alertmanager/alertmanager.yml`): -| Channel | Routes | Repeat Interval | +| Kênh | Route | Khoảng lặp lại | |---------|--------|-----------------| -| `#sre-oncall` (Slack) | All warning alerts | 4 hours | -| `#sre-oncall` (Slack) | All critical alerts (priority) | 1 hour | -| `#infrastructure` (Slack) | Backup-related alerts | 6 hours | +| `#sre-oncall` (Slack) | Tất cả alert warning | 4 giờ | +| `#sre-oncall` (Slack) | Tất cả alert critical (ưu tiên) | 1 giờ | +| `#infrastructure` (Slack) | Alert liên quan backup | 6 giờ | -**Inhibition:** Warning alerts are suppressed when a critical alert for the same service is already firing. +**Inhibition:** Các alert warning bị chặn khi đã có alert critical cho cùng một dịch vụ đang kích hoạt. -Alert rules are defined in `monitoring/prometheus/alert-rules.yml` and evaluated every 15 seconds. +Alert rule được định nghĩa trong `monitoring/prometheus/alert-rules.yml` và được đánh giá mỗi 15 giây. diff --git a/docs/api-endpoints.md b/docs/api-endpoints.md index 25f81cf..e776df5 100644 --- a/docs/api-endpoints.md +++ b/docs/api-endpoints.md @@ -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 và 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 | Liệt 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 | Liệt 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 | Liệt 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 | Liệt 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 ` 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 ` | +| **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` diff --git a/docs/architecture/CODEBASE_OVERVIEW.md b/docs/architecture/CODEBASE_OVERVIEW.md index c548c37..97bdcaa 100644 --- a/docs/architecture/CODEBASE_OVERVIEW.md +++ b/docs/architecture/CODEBASE_OVERVIEW.md @@ -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 tiền +- **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 diff --git a/docs/architecture/FILE_MAPPING_GUIDE.md b/docs/architecture/FILE_MAPPING_GUIDE.md index 519152d..f1c129f 100644 --- a/docs/architecture/FILE_MAPPING_GUIDE.md +++ b/docs/architecture/FILE_MAPPING_GUIDE.md @@ -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/*` và `/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 { } ``` -#### 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. ``` -##### 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: