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,137 +1,137 @@
# Test Coverage Documentation
# Tài Liệu Độ Phủ Kiểm Thử
## Overview
## Tổng Quan
This directory contains comprehensive documentation for writing tests for **17 untested source files** across the inquiries, leads, and reviews modules of the GoodGo Platform API.
Thư mục này chứa tài liệu toàn diện hướng dẫn viết kiểm thử cho **17 tệp nguồn chưa được kiểm thử** thuộc các module inquiries, leads reviews của GoodGo Platform API.
## Files Included
## Các Tệp Bao Gồm
### 1. **TEST_COVERAGE_ANALYSIS.md** (1,841 lines, 55KB)
- **Complete implementations** of all 17 untested files
- Full source code for each file
- Detailed explanation of what each method does
- Test scenarios for each component
- Reference test patterns from existing test files
- Comprehensive test patterns and examples
### 1. **TEST_COVERAGE_ANALYSIS.md** (1.841 dòng, 55KB)
- **Triển khai đầy đủ** của tất cả 17 tệp chưa được kiểm thử
- Mã nguồn hoàn chỉnh cho từng tệp
- Giải thích chi tiết chức năng của từng phương thức
- Các kịch bản kiểm thử cho từng thành phần
- Tham chiếu các mẫu kiểm thử từ các tệp kiểm thử hiện có
- Mẫu và ví dụ kiểm thử toàn diện
### 2. **TEST_COVERAGE_QUICK_REFERENCE.md** (301 lines, 9.1KB)
- Quick lookup guide for all 17 files
- Test checklists by file type (repositories, VOs, DTOs, controllers)
- Module-specific test scenarios
- Priority matrix (critical, high, medium)
- Recommended test execution order
- Mock setup templates
- Key formulas to verify
### 2. **TEST_COVERAGE_QUICK_REFERENCE.md** (301 dòng, 9,1KB)
- Hướng dẫn tra cứu nhanh cho tất cả 17 tệp
- Danh sách kiểm tra theo loại tệp (repositories, VOs, DTOs, controllers)
- Các kịch bản kiểm thử theo module
- Ma trận ưu tiên (critical, high, medium)
- Thứ tự thực thi kiểm thử được khuyến nghị
- Mẫu thiết lập mock
- Các công thức quan trọng cần xác minh
### 3. **TEST_TEMPLATES.md** (500+ lines)
- Ready-to-use test templates for:
- Repository tests
- Value Object tests
- DTO tests
- Controller tests
- Helper tests for pagination calculations
- Helper tests for aggregation formulas
- DTO validation helper tests
### 3. **TEST_TEMPLATES.md** (500+ dòng)
- Mẫu kiểm thử sẵn dùng cho:
- Kiểm thử Repository
- Kiểm thử Value Object
- Kiểm thử DTO
- Kiểm thử Controller
- Kiểm thử helper cho tính toán phân trang
- Kiểm thử helper cho công thức tổng hợp
- Kiểm thử helper xác thực DTO
## Quick Start
## Bắt Đầu Nhanh
### For a quick overview:
1. Read the **Quick Reference** first (5-10 minutes)
2. Identify which file type you want to test
3. Jump to the appropriate section in **TEST_TEMPLATES.md**
4. Copy the template and adapt it to your file
### Để có cái nhìn tổng quan nhanh:
1. Đọc **Quick Reference** trước (510 phút)
2. Xác định loại tệp bạn muốn kiểm thử
3. Chuyển đến mục tương ứng trong **TEST_TEMPLATES.md**
4. Sao chép mẫu và điều chỉnh cho tệp của bạn
### For comprehensive understanding:
1. Start with the **Quick Reference** overview
2. Read the relevant module section in **TEST_COVERAGE_ANALYSIS.md**
3. Use **TEST_TEMPLATES.md** as implementation guide
4. Reference the example test patterns in the Analysis document
### Để hiểu sâu hơn:
1. Bắt đầu với tổng quan **Quick Reference**
2. Đọc phần module liên quan trong **TEST_COVERAGE_ANALYSIS.md**
3. Sử dụng **TEST_TEMPLATES.md** làm hướng dẫn triển khai
4. Tham chiếu các mẫu kiểm thử ví dụ trong tài liệu Analysis
## File Organization by Module
## Tổ Chức Tệp Theo Module
### Inquiries Module (4 files)
### Module Inquiries (4 tệp)
```
✗ prisma-inquiry.repository.ts — 6 methods, pagination, relationships
✗ inquiries.controller.ts — 4 endpoints, guards
✗ create-inquiry.dto.ts — 3 validations
✗ list-inquiries.dto.ts — 2 validations (pagination)
✗ prisma-inquiry.repository.ts — 6 phương thức, phân trang, quan hệ
✗ inquiries.controller.ts — 4 endpoint, guards
✗ create-inquiry.dto.ts — 3 validation
✗ list-inquiries.dto.ts — 2 validation (phân trang)
```
### Leads Module (6 files)
### Module Leads (6 tệp)
```
✗ prisma-lead.repository.ts — 6 methods, stats aggregation
✗ lead-score.vo.ts — Range validation (0-100)
✗ leads.controller.ts — 5 endpoints, role guards
✗ create-lead.dto.ts — 6 validations
✗ list-leads.dto.ts — Status enum, pagination
✗ update-lead-status.dto.ts — Status enum
✗ prisma-lead.repository.ts — 6 phương thức, tổng hợp thống kê
✗ lead-score.vo.ts — Xác thực khoảng giá trị (0-100)
✗ leads.controller.ts — 5 endpoint, role guards
✗ create-lead.dto.ts — 6 validation
✗ list-leads.dto.ts — Enum trạng thái, phân trang
✗ update-lead-status.dto.ts — Enum trạng thái
```
### Reviews Module (5 files)
### Module Reviews (5 tệp)
```
✗ prisma-review.repository.ts — 7 methods, distribution stats
✗ rating.vo.ts — Integer range validation (1-5)
✗ reviews.controller.ts — 5 endpoints, mixed auth
✗ create-review.dto.ts — 4 validations
✗ list-reviews.dto.ts — 2 DTO classes, pagination
✗ prisma-review.repository.ts — 7 phương thức, thống kê phân phối
✗ rating.vo.ts — Xác thực khoảng số nguyên (1-5)
✗ reviews.controller.ts — 5 endpoint, xác thực hỗn hợp
✗ create-review.dto.ts — 4 validation
✗ list-reviews.dto.ts — 2 lớp DTO, phân trang
```
## Testing Priority Levels
## Mức Độ Ưu Tiên Kiểm Thử
### 🔴 CRITICAL (Business Logic)
1. **PrismaReviewRepository.getStats()**Distribution calculation is complex
2. **PrismaLeadRepository.getStatsByAgent()** — Conversion rate formula
3. **Rating.vo**Must validate 1-5 integers only
4. **LeadScore.vo**Must validate 0-100 range
### 🔴 CRITICAL (Logic Nghiệp Vụ)
1. **PrismaReviewRepository.getStats()**Tính toán phân phối phức tạp
2. **PrismaLeadRepository.getStatsByAgent()** — Công thức tỷ lệ chuyển đổi
3. **Rating.vo**Phải xác thực chỉ số nguyên từ 15
4. **LeadScore.vo**Phải xác thực khoảng 0100
**Start here** — These are the most business-critical validations
**Bắt đầu từ đây** — Đây là các validation quan trọng nhất cho nghiệp vụ
### 🟡 HIGH (Data Integrity)
1. Repository CRUD operations
2. Pagination calculations
3. Relationship mapping (user joins, listing traversal)
4. Controller command/query dispatch
### 🟡 HIGH (Tính Toàn Vẹn Dữ Liệu)
1. Các thao tác CRUD của Repository
2. Tính toán phân trang
3. Ánh xạ quan hệ (user joins, duyệt listing)
4. Điều phối command/query từ Controller
**Test second** — These ensure data consistency
**Kiểm thử tiếp theo** — Đảm bảo tính nhất quán của dữ liệu
### 🟢 MEDIUM (Validation & Guards)
1. DTO field validations
2. Enum constraints
3. Optional field handling
4. Authentication/Authorization guards
1. Xác thực trường DTO
2. Ràng buộc Enum
3. Xử lý trường tùy chọn
4. Guards xác thực/phân quyền
**Test last** — These are framework-level concerns
**Kiểm thử sau cùng** — Đây là các mối quan tâm ở tầng framework
## Test Execution Roadmap
## Lộ Trình Thực Thi Kiểm Thử
### Week 1: Value Objects & DTOs (8-10 test files)
- [ ] LeadScore.vo.ts (1 file, 4-5 test cases)
- [ ] Rating.vo.ts (1 file, 4-5 test cases)
- [ ] All 10 DTO files (using templates, minimal variations)
### Tuần 1: Value Objects & DTOs (810 tệp kiểm thử)
- [ ] LeadScore.vo.ts (1 tệp, 45 test case)
- [ ] Rating.vo.ts (1 tệp, 45 test case)
- [ ] Tất cả 10 tệp DTO (dùng mẫu, biến thể tối thiểu)
**Estimated time:** 3-5 hours total
**Thời gian ước tính:** 35 giờ tổng cộng
### Week 2: Controllers (2 test files)
- [ ] InquiriesController (4 endpoints + guards)
- [ ] LeadsController (5 endpoints + guards)
- [ ] ReviewsController (5 endpoints + mixed auth)
### Tuần 2: Controllers (2 tệp kiểm thử)
- [ ] InquiriesController (4 endpoint + guards)
- [ ] LeadsController (5 endpoint + guards)
- [ ] ReviewsController (5 endpoint + xác thực hỗn hợp)
**Estimated time:** 2-3 hours total
**Thời gian ước tính:** 23 giờ tổng cộng
### Week 3: Repositories (3 test files)
- [ ] PrismaInquiryRepository (6 methods)
- [ ] PrismaLeadRepository (6 methods + aggregation)
- [ ] PrismaReviewRepository (7 methods + distribution)
### Tuần 3: Repositories (3 tệp kiểm thử)
- [ ] PrismaInquiryRepository (6 phương thức)
- [ ] PrismaLeadRepository (6 phương thức + tổng hợp)
- [ ] PrismaReviewRepository (7 phương thức + phân phối)
**Estimated time:** 4-6 hours total
**Thời gian ước tính:** 46 giờ tổng cộng
### Total Estimated Time: 9-14 hours
### Tổng Thời Gian Ước Tính: 914 giờ
## Key Testing Patterns
## Các Mẫu Kiểm Thử Quan Trọng
### Repositories
```typescript
// Mock all Prisma methods in beforeEach
// Mock tất cả phương thức Prisma trong beforeEach
mockPrisma = {
[model]: {
findUnique: vi.fn(),
@@ -142,18 +142,18 @@ mockPrisma = {
}
};
// Test happy path and error cases
// Verify pagination calculations
// Verify data transformation (toDomain)
// Kiểm thử luồng thành công và trường hợp lỗi
// Xác minh tính toán phân trang
// Xác minh chuyển đổi dữ liệu (toDomain)
```
### Value Objects
```typescript
// Test valid cases
// Kiểm thử các trường hợp hợp lệ
const result = ValueObject.create(validValue);
expect(result.isOk()).toBe(true);
// Test invalid cases
// Kiểm thử các trường hợp không hợp lệ
const result = ValueObject.create(invalidValue);
expect(result.isErr()).toBe(true);
expect(result.unwrapErr()).toBe('error message');
@@ -161,57 +161,57 @@ expect(result.unwrapErr()).toBe('error message');
### DTOs
```typescript
// Use validate() from class-validator
// Sử dụng validate() từ class-validator
const errors = await validate(dto);
expect(errors).toHaveLength(0); // or > 0 for invalid cases
expect(errors).toHaveLength(0); // hoặc > 0 cho trường hợp không hợp lệ
// Test type transformation with class-transformer
// Test optional field handling
// Kiểm thử chuyển đổi kiểu với class-transformer
// Kiểm thử xử lý trường tùy chọn
```
### Controllers
```typescript
// Mock CommandBus and QueryBus
// Mock CommandBus QueryBus
mockCommandBus.execute.mockResolvedValue(expectedResult);
// Verify command/query construction
// Xác minh cấu trúc command/query
const command = mockCommandBus.execute.mock.calls[0][0];
expect(command.userId).toBe(expectedUserId);
```
## Critical Formulas to Test
## Các Công Thức Quan Trọng Cần Kiểm Thử
### Pagination
### Phân Trang
```
skip = (page - 1) * take
totalPages = Math.ceil(total / take)
take = Math.min(limit, 100) // Clamped to 100 max
take = Math.min(limit, 100) // Giới hạn tối đa 100
```
### Lead Statistics
### Thống Kê Lead
```
conversionRate = (CONVERTED_count / total_leads) * 100 // 2 decimals
avgScore = (sum_of_scores / non_null_count) // 1 decimal, null if no scores
conversionRate = (CONVERTED_count / total_leads) * 100 // 2 chữ số thập phân
avgScore = (sum_of_scores / non_null_count) // 1 chữ số thập phân, null nếu không có điểm
```
### Review Statistics
### Thống Kê Review
```
averageRating = (sum_of_ratings / total_reviews) // 1 decimal
averageRating = (sum_of_ratings / total_reviews) // 1 chữ số thập phân
distribution = { 1: count, 2: count, 3: count, 4: count, 5: count }
```
## Import Statements You'll Need
## Các Câu Lệnh Import Cần Dùng
```typescript
// Testing utilities
// Tiện ích kiểm thử
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { validate } from 'class-validator';
import { plainToClass } from 'class-transformer';
// NestJS utilities (for controller tests)
// Tiện ích NestJS (dùng cho kiểm thử controller)
import type { EventBus, CommandBus, QueryBus } from '@nestjs/cqrs';
// Domain classes
// Các lớp domain
import { InquiryEntity } from './domain/entities/inquiry.entity';
import { LeadEntity } from './domain/entities/lead.entity';
import { ReviewEntity } from './domain/entities/review.entity';
@@ -219,88 +219,88 @@ import { LeadScore } from './domain/value-objects/lead-score.vo';
import { Rating } from './domain/value-objects/rating.vo';
```
## Common Test Data
## Dữ Liệu Kiểm Thử Thông Dụng
### User IDs
### ID Người Dùng
```
user-1, user-2, user-3, user-agent-1
```
### Lead Statuses
### Trạng Thái Lead
```
NEW, CONTACTED, QUALIFIED, NEGOTIATING, CONVERTED, LOST
```
### Pagination Defaults
### Giá Trị Mặc Định Phân Trang
```
page: 1, limit: 20 (max 100)
page: 1, limit: 20 (tối đa 100)
```
### Rating Range
### Khoảng Đánh Giá
```
1-5 stars (integer only)
1-5 sao (chỉ số nguyên)
```
### Lead Score Range
### Khoảng Điểm Lead
```
0-100 (any number)
0-100 (bất kỳ số nào)
```
## References
## Tài Liệu Tham Khảo
### Existing Test Files (Use as Reference)
- `src/modules/inquiries/application/__tests__/create-inquiry.handler.spec.ts` (20 lines pattern)
- `src/modules/leads/application/__tests__/create-lead.handler.spec.ts` (20 lines pattern)
- `src/modules/reviews/presentation/__tests__/reviews.controller.spec.ts` (135 lines pattern)
### Các Tệp Kiểm Thử Hiện Có (Dùng Làm Tham Chiếu)
- `src/modules/inquiries/application/__tests__/create-inquiry.handler.spec.ts` (mẫu 20 dòng)
- `src/modules/leads/application/__tests__/create-lead.handler.spec.ts` (mẫu 20 dòng)
- `src/modules/reviews/presentation/__tests__/reviews.controller.spec.ts` (mẫu 135 dòng)
### Full Implementations
All 17 file implementations are in `TEST_COVERAGE_ANALYSIS.md` with line-by-line explanations.
### Triển Khai Đầy Đủ
Tất cả 17 triển khai tệp có trong `TEST_COVERAGE_ANALYSIS.md` với giải thích từng dòng.
## Troubleshooting
## Xử Lý Sự Cố
### Issue: "Cannot find module" when mocking
**Solution:** Use `as any` casting for mocked dependencies
### Vấn đề: "Cannot find module" khi mock
**Giải pháp:** Sử dụng ép kiểu `as any` cho các dependency được mock
```typescript
const repo = new PrismaInquiryRepository(mockPrisma as any);
```
### Issue: Validation tests not working
**Solution:** Make sure you're using `plainToClass` for DTOs with transformers
### Vấn đề: Kiểm thử validation không hoạt động
**Giải pháp:** Đảm bảo dùng `plainToClass` cho các DTO có transformer
```typescript
const dto = plainToClass(CreateLeadDto, plainObject);
```
### Issue: Pagination calculations don't match
**Solution:** Remember that limit is clamped to 100
### Vấn đề: Tính toán phân trang không khớp
**Giải pháp:** Nhớ rằng limit được giới hạn ở 100
```typescript
const take = Math.min(limit, 100); // Always do this
const take = Math.min(limit, 100); // Luôn thực hiện bước này
```
### Issue: Stats calculations have rounding errors
**Solution:** Check decimal place requirements:
- conversionRate: 2 decimals (multiply by 10000, divide by 100)
- avgScore: 1 decimal (multiply by 10, divide by 10)
- averageRating: 1 decimal (multiply by 10, divide by 10)
### Vấn đề: Tính toán thống kê có lỗi làm tròn
**Giải pháp:** Kiểm tra yêu cầu số chữ số thập phân:
- conversionRate: 2 chữ số thập phân (nhân với 10000, chia cho 100)
- avgScore: 1 chữ số thập phân (nhân với 10, chia cho 10)
- averageRating: 1 chữ số thập phân (nhân với 10, chia cho 10)
## Next Steps
## Các Bước Tiếp Theo
1. **Pick your starting file** from Week 1 (recommend LeadScore.vo first — simplest)
2. **Open the template** matching that file type in TEST_TEMPLATES.md
3. **Copy the template** to your test file location
4. **Adapt the template** with your specific imports and data
5. **Run tests** and verify they pass
6. **Move to next file** following the roadmap
1. **Chọn tệp bắt đầu** từ Tuần 1 (khuyến nghị LeadScore.vo trước — đơn giản nhất)
2. **Mở mẫu** tương ứng với loại tệp đó trong TEST_TEMPLATES.md
3. **Sao chép mẫu** vào vị trí tệp kiểm thử của bạn
4. **Điều chỉnh mẫu** với các import và dữ liệu cụ thể của bạn
5. **Chạy kiểm thử** và xác minh chúng đạt
6. **Chuyển sang tệp tiếp theo** theo lộ trình
## Support Resources
## Tài Nguyên Hỗ Trợ
- Full implementations: See **TEST_COVERAGE_ANALYSIS.md**
- Quick lookup: See **TEST_COVERAGE_QUICK_REFERENCE.md**
- Code templates: See **TEST_TEMPLATES.md**
- Reference tests: Check existing spec files in the modules
- Triển khai đầy đủ: Xem **TEST_COVERAGE_ANALYSIS.md**
- Tra cứu nhanh: Xem **TEST_COVERAGE_QUICK_REFERENCE.md**
- Mẫu mã: Xem **TEST_TEMPLATES.md**
- Kiểm thử tham chiếu: Xem các tệp spec hiện có trong các module
---
**Last Updated:** 2026-04-11
**Total Files Documented:** 17 untested source files
**Total Documentation:** 2,142 lines of analysis and templates
**Estimated Testing Time:** 9-14 hours total
**Cập Nhật Lần Cuối:** 2026-04-11
**Tổng Số Tệp Được Ghi Lại:** 17 tệp nguồn chưa được kiểm thử
**Tổng Tài Liệu:** 2.142 dòng phân tích và mẫu
**Thời Gian Kiểm Thử Ước Tính:** 914 giờ tổng cộng