chore: update project documentation, audit reports, and initialize IDE configuration files
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 29s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m42s
Deploy / Build Web Image (push) Failing after 27s
Deploy / Build AI Services Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 43s
Deploy / Build API Image (push) Failing after 1m31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Security Scanning / Trivy Scan — API Image (push) Failing after 5m35s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 3m45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Security Scanning / Trivy Scan — Web Image (push) Failing after 13m51s
Security Scanning / Trivy Filesystem Scan (push) Failing after 14m46s
Security Scanning / Security Gate (push) Has been cancelled

This commit is contained in:
Ho Ngoc Hai
2026-04-19 03:12:54 +07:00
parent 3be106074d
commit 11f2bf26e6
101 changed files with 21312 additions and 20672 deletions

View File

@@ -1,8 +1,8 @@
# Architecture
# Kiến Trúc Hệ Thống
## System Overview
## Tổng Quan Hệ Thống
GoodGo Platform AI is a monorepo containing a NestJS backend, Next.js frontend, Python AI services, and MCP (Model Context Protocol) servers. The system is orchestrated with Turborepo and pnpm workspaces.
GoodGo Platform AI là một monorepo bao gồm backend NestJS, frontend Next.js, các dịch vụ AI bằng Python, và các máy chủ MCP (Model Context Protocol). Hệ thống được điều phối bằng Turborepo pnpm workspaces.
```
┌──────────────────────────────────────────┐
@@ -57,52 +57,52 @@ GoodGo Platform AI is a monorepo containing a NestJS backend, Next.js frontend,
└──────────────────────────────────────┘
```
## Module Architecture
## Kiến Trúc Module
Each API module follows a layered Domain-Driven Design structure:
Mỗi module API tuân theo cấu trúc phân lớp theo Domain-Driven Design:
```
modules/{module-name}/
├── presentation/ # HTTP layer
│ ├── controllers/ # Route handlers
│ └── dtos/ # Request/response DTOs (class-validator)
├── application/ # Business orchestration
│ ├── commands/ # Write operations (CQRS)
│ ├── queries/ # Read operations (CQRS)
│ ├── handlers/ # Command/query handlers
│ └── services/ # Application services
├── domain/ # Core business logic
│ ├── entities/ # Domain entities & value objects
│ ├── repositories/ # Repository interfaces (abstractions)
│ └── events/ # Domain events
├── infrastructure/ # External integrations
│ ├── repositories/ # Prisma repository implementations
│ └── services/ # External service adapters
└── {module-name}.module.ts # NestJS module definition
├── presentation/ # Tầng HTTP
│ ├── controllers/ # Xử lý route
│ └── dtos/ # DTO yêu cầu/phản hồi (class-validator)
├── application/ # Điều phối nghiệp vụ
│ ├── commands/ # Thao tác ghi (CQRS)
│ ├── queries/ # Thao tác đọc (CQRS)
│ ├── handlers/ # Handler cho command/query
│ └── services/ # Dịch vụ ứng dụng
├── domain/ # Lõi logic nghiệp vụ
│ ├── entities/ # Entity domain & value object
│ ├── repositories/ # Giao diện repository (trừu tượng hoá)
│ └── events/ # Domain event
├── infrastructure/ # Tích hợp bên ngoài
│ ├── repositories/ # Triển khai repository bằng Prisma
│ └── services/ # Adapter cho dịch vụ ngoài
└── {module-name}.module.ts # Định nghĩa module NestJS
```
### CQRS Pattern
### Mẫu CQRS
The platform uses NestJS CQRS (`@nestjs/cqrs`) for complex operations:
Nền tảng sử dụng NestJS CQRS (`@nestjs/cqrs`) cho các thao tác phức tạp:
- **Commands** — mutate state (create listing, process payment, register user)
- **Queries** — read state (search properties, get analytics)
- **Events** — cross-module communication (listing published → index in Typesense, payment completed → send notification)
- **Commands** — thay đổi trạng thái (tạo tin đăng, xử lý thanh toán, đăng ký người dùng)
- **Queries** — đọc trạng thái (tìm kiếm bất động sản, lấy phân tích)
- **Events** — giao tiếp liên module (tin đăng được duyệt → đánh chỉ mục vào Typesense, thanh toán hoàn tất → gửi thông báo)
### Shared Module
### Module Shared
The `shared/` module provides cross-cutting concerns:
Module `shared/` cung cấp các mối quan tâm xuyên suốt:
- **Prisma service** — database connection and client
- **Redis service** — caching and session management
- **Prisma service** — kết nối cơ sở dữ liệu và client
- **Redis service** — bộ nhớ đệm và quản lý phiên
- **Guards** — JWT auth guard, roles guard, throttle guard
- **Pipes** — global validation pipe (whitelist mode)
- **Filters** — exception filters for consistent error responses
- **Pipes** — pipe xác thực toàn cục (chế độ whitelist)
- **Filters** — exception filter cho phản hồi lỗi nhất quán
- **Decorators** — `@CurrentUser()`, `@Roles()`, `@Public()`
## Data Flow
## Luồng Dữ Liệu
### Property Listing Lifecycle
### Vòng Đời Tin Đăng Bất Động Sản
```
DRAFT → PENDING_REVIEW → ACTIVE → RESERVED → SOLD/RENTED
@@ -111,14 +111,14 @@ DRAFT → PENDING_REVIEW → ACTIVE → RESERVED → SOLD/RENTED
REJECTED EXPIRED
```
1. **Seller/Agent** creates listing (status: `DRAFT`)
2. **Seller** submits for review`PENDING_REVIEW`
3. **Admin** moderates (AI moderation score assists) → `ACTIVE` or `REJECTED`
4. Active listings are indexed in Typesense for search
5. **Buyer** makes inquiry → `Inquiry` record created
6. Transaction workflow: `OFFER_MADE → DEPOSIT_PAID → CONTRACT_SIGNING → COMPLETED`
1. **Người bán/Đại lý** tạo tin đăng (trạng thái: `DRAFT`)
2. **Người bán** gửi để duyệt`PENDING_REVIEW`
3. **Quản trị viên** kiểm duyệt (điểm kiểm duyệt AI hỗ trợ) → `ACTIVE` hoặc `REJECTED`
4. Các tin đăng đang hoạt động được đánh chỉ mục vào Typesense để tìm kiếm
5. **Người mua** gửi yêu cầu → bản ghi `Inquiry` được tạo
6. Quy trình giao dịch: `OFFER_MADE → DEPOSIT_PAID → CONTRACT_SIGNING → COMPLETED`
### Search Flow
### Luồng Tìm Kiếm
```
User Query → NestJS Search Module → Typesense
@@ -128,7 +128,7 @@ User Query → NestJS Search Module → Typesense
└─ Geo-spatial (lat/long + radius)
```
### Payment Flow
### Luồng Thanh Toán
```
User → API (create payment) → Provider (VNPay/MoMo/ZaloPay)
@@ -140,7 +140,7 @@ Provider callback → API → Verify signature → Update Payment status
SUCCESS / FAILED
```
### AI Valuation Flow
### Luồng Định Giá AI
```
API Request → MCP Valuation Server → AI Service (FastAPI)
@@ -155,9 +155,9 @@ API Request → MCP Valuation Server → AI Service (FastAPI)
└─────────────┘
```
## Database Schema
## Sơ Đồ Cơ Sở Dữ Liệu
### Core Models
### Các Model Cốt Lõi
```
User ──┬── Agent (1:1, for AGENT role users)
@@ -183,16 +183,16 @@ Plan ── Subscription (1:N)
MarketIndex (standalone — city/district/month aggregates)
```
### Key Design Decisions
### Các Quyết Định Thiết Kế Chính
- **PostGIS** for spatial queries — property locations stored as `Point` geometry
- **JSON columns** for flexible data: amenities, nearby POIs, KYC data, subscription features
- **Token family tracking** for secure refresh token rotation (detects reuse attacks)
- **Soft statuses** over soft deleteslistings use status workflow, not `deletedAt`
- **PostGIS** cho các truy vấn không gian — vị trí bất động sản được lưu dạng hình học `Point`
- **Cột JSON** cho dữ liệu linh hoạt: tiện ích, điểm POI lân cận, dữ liệu KYC, tính năng gói đăng ký
- **Theo dõi token family** để xoay vòng refresh token an toàn (phát hiện tấn công tái sử dụng)
- **Soft status** thay vì soft delete — tin đăng sử dụng quy trình trạng thái, không dùng `deletedAt`
## MCP Servers
## Máy Chủ MCP
Three Model Context Protocol servers provide AI tool interfaces:
Ba máy chủ Model Context Protocol cung cấp giao diện công cụ cho AI:
| Server | Tools | Data Source |
|--------|-------|-------------|
@@ -200,46 +200,46 @@ Three Model Context Protocol servers provide AI tool interfaces:
| **Market Analytics** | `get_market_report`, `analyze_trends`, `get_price_indices` | PostgreSQL |
| **Valuation** | `estimate_valuation`, `extract_features`, `compare_valuations` | AI Services (FastAPI) |
MCP servers are registered via `McpModule` in NestJS, managed by `McpRegistryService`, and exposed through `McpTransportController` over HTTP.
Các máy chủ MCP được đăng ký qua `McpModule` trong NestJS, quản lý bởi `McpRegistryService`, và được phơi ra qua `McpTransportController` qua HTTP.
## AI Services
## Dịch Vụ AI
Python FastAPI microservice (`libs/ai-services/`) provides:
Microservice Python FastAPI (`libs/ai-services/`) cung cấp:
| Endpoint | Model | Purpose |
|----------|-------|---------|
| `POST /avm/estimate` | XGBoost | Property price estimation with confidence score |
| `POST /moderation/check` | Claude API | Content moderation for listing descriptions |
| `GET /health` | — | Health check |
| `POST /avm/estimate` | XGBoost | Ước tính giá bất động sản kèm điểm tin cậy |
| `POST /moderation/check` | Claude API | Kiểm duyệt nội dung mô tả tin đăng |
| `GET /health` | — | Kiểm tra tình trạng hoạt động |
- **Underthesea** handles Vietnamese text tokenization and NLP preprocessing
- XGBoost model uses engineered features (area, location, property type, amenities)
- **Underthesea** xử lý phân tách từ và tiền xử lý NLP tiếng Việt
- Mô hình XGBoost sử dụng các đặc trưng được thiết kế (diện tích, vị trí, loại bất động sản, tiện ích)
## Security
## Bảo Mật
- **JWT + Refresh Token Rotation** — 15-minute access tokens, 7-day refresh tokens with family-based rotation
- **OAuth** — Google and Zalo social login
- **Rate Limiting** — 60 req/60s default, 10 req/60s for auth endpoints
- **Helmet** — HTTP security headers
- **CORS** — Configurable origins via `CORS_ORIGINS`
- **JWT + Refresh Token Rotation** — access token có hiệu lực 15 phút, refresh token 7 ngày với xoay vòng dựa trên token family
- **OAuth** — đăng nhập mạng xã hội qua Google Zalo
- **Rate Limiting** — mặc định 60 yêu cầu/60 giây, 10 yêu cầu/60 giây cho các endpoint xác thực
- **Helmet** — các header bảo mật HTTP
- **CORS** — các origin được cấu hình linh hoạt qua `CORS_ORIGINS`
- **Input Validation** — class-validator (backend), Zod (frontend)
- **Content Sanitization** — sanitize-html for user-generated content
- **KYC** — Agent verification workflow (NONE → PENDING → VERIFIED/REJECTED)
- **Content Sanitization** — sanitize-html cho nội dung người dùng tạo
- **KYC** — quy trình xác minh đại lý (NONE → PENDING → VERIFIED/REJECTED)
## Monitoring
## Giám Sát
- **Prometheus** scrapes `/api/v1/metrics` endpoint every 15 seconds
- **Grafana** dashboards auto-provisioned from `monitoring/grafana/dashboards/`
- **Loki + Promtail** aggregate container logs; viewable in Grafana
- **Pino** structured JSON logging with configurable log levels
- Metrics include HTTP request duration, error rates, web vitals, and custom business metrics
- Log retention: 15 days (configured in `monitoring/loki/loki-config.yml`)
- **Prometheus** thu thập dữ liệu từ endpoint `/api/v1/metrics` mỗi 15 giây
- **Grafana** các dashboard được cung cấp tự động từ `monitoring/grafana/dashboards/`
- **Loki + Promtail** tổng hợp log container; có thể xem trong Grafana
- **Pino** ghi log JSON có cấu trúc với cấp độ log có th cấu hình
- Các chỉ số bao gồm thời gian xử lý yêu cầu HTTP, tỷ lệ lỗi, web vitals, và các chỉ số nghiệp vụ tùy chỉnh
- Thời gian lưu giữ log: 15 ngày (được cấu hình trong `monitoring/loki/loki-config.yml`)
## Event System
## Hệ Thống Sự Kiện
The platform uses `@nestjs/event-emitter` for loose coupling between modules:
Nền tảng sử dụng `@nestjs/event-emitter` để kết nối lỏng lẻo giữa các module:
- `listing.published` → Typesense indexer updates search index
- `payment.completed`Notification service sends confirmation
- `inquiry.created`Agent notification triggered
- `user.registered`Welcome email sent
- `listing.published` → Typesense indexer cập nhật chỉ mục tìm kiếm
- `payment.completed`Dịch vụ thông báo gửi xác nhận
- `inquiry.created`Kích hoạt thông báo cho đại lý
- `user.registered`Gửi email chào mừng