Initial Matching App

This commit is contained in:
phattt2901 2025-04-25 14:02:04 +07:00
commit 05426244ed
10 changed files with 887 additions and 0 deletions

232
Zee.md Normal file
View File

@ -0,0 +1,232 @@
---
created: 2025-04-25T12:45
updated: 2025-04-25T12:45
---
**Tài liệu Thiết kế Tổng quát - Dự án Matchmaking Microsite**
**Phiên bản:** 1.0 **Ngày:** 2025-04-25
# Content
**1. Giới thiệu (Introduction)**
- **Mục đích dự án**: Xây dựng một microsite phục vụ chiến dịch matchmaking ("Team Ngọt Ngào và Thanh Dịu").  
- **Mục tiêu chính**: Cho phép người dùng đăng ký thông tin cá nhân và sở thích, hệ thống tự động tìm kiếm và đề xuất 3 hồ sơ phù hợp dựa trên các tiêu chí định sẵn, quản lý quy trình thông báo qua email, và trao giải thưởng cho người may mắn.  
- **Đối tượng người dùng**: Các cá nhân muốn tham gia chương trình ghép đôi.
- **Quy mô dự kiến**: Khoảng 20,000+ người tham gia, 5,000 lượt matching.  
**2. Nguyên tắc & Kiến trúc tổng thể (Principles & High-Level Architecture)**
- **Nguyên tắc thiết kế**:
- User-Centric: Ưu tiên trải nghiệm người dùng, giảm thiểu sự phức tạp.
- Data-Centric / Data Oriented Programming (DOP): Thiết kế xoay quanh luồng dữ liệu và các biến đổi dữ liệu.
- Domain-Driven Design (DDD): Áp dụng các khái niệm cốt lõi của DDD (Bounded Context, Aggregates, Domain Events).
- **Thành phần kiến trúc chính (Core Components)**:
- `Resource`: Các Aggregate DDD đại diện cho đối tượng nghiệp vụ (dữ liệu, trạng thái, hành vi).
- `Transaction`: Các Saga/Process Manager điều phối luồng nghiệp vụ phức tạp, liên quan đến nhiều Resource.
- `Adapter`: Xử lý giao tiếp với các hệ thống bên ngoài (Database, Email Service, File Storage).
- `Helper`: Các thư viện, tiện ích dùng chung.
- `UIUX`: Lớp giao diện người dùng (Frontend).
- **Phân cấp độ chi tiết (Architectural Granularity - U-Hierarchy)**:
- `ubit`: Đơn vị logic nhỏ nhất (hàm, type, hằng số).
- `ubrick`: Tập hợp các ubit liên quan (module validate, nhóm hàm tiện ích).
- `ublock`: Thành phần có thể hoạt động độc lập tương đối (quản lý một Resource, một Adapter cụ thể).
- `ubundle`: Tính năng hoàn chỉnh cho người dùng (sự kết hợp của nhiều ublock).
- **Công nghệ lựa chọn (Technology Stack)**:
- Backend: Go
- Database: PostgreSQL (có thể cân nhắc JSONB cho một số trường linh hoạt).
- Frontend: **HTMX (Ưu tiên)** - Backend sẽ render HTML fragments là chủ yếu. JavaScript sẽ được dùng hạn chế cho các xử lý phức tạp hoặc Admin UI.
- Khác: Có thể tích hợp Workflow Engine/Rule Engine cho logic matching phức tạp (cân nhắc).
**3. Resources (Đối tượng nghiệp vụ cốt lõi)**
Các Aggregate chính của hệ thống:
- **`Profile`**: Lưu thông tin người tham gia.
- **Cấu trúc dữ liệu**: (Chi tiết như đã định nghĩa ở các thảo luận trước, bao gồm: `id`, `fullName`, `dateOfBirth`, `gender`, `preferredGender`, `phoneNumber`, `email`, `facebookLink`, `photoReference`, `location`, `team`, `hobbies`, `thingsNotTried`, `hopesForPartner`, `dealbreakers`, `messageToPartner`, `zodiacSign`, `accessCode`, `personalLink`, `acceptedTerms`, `registrationTimestamp`, `status`, `isLuckyWinner`, `createdAt`, `updatedAt`).  
- **ubits/ubricks ví dụ**: `ProfileDataValidation`, `ZodiacCalculator`, `AccessCredentialGenerator`, `ProfileStateMachine`, `validateEmail`, `checkHobbyCount`.  
- **`MatchOutcome`**: Lưu kết quả matching cho một `Profile`.
- **Cấu trúc dữ liệu**: (Chi tiết như đã định nghĩa, bao gồm: `id`, `profileId`, `potentialMatchProfileIds`, `matchScores`?, `status`, `selectedProfileId`, `generationTimestamp`, `accessedTimestamp`, `selectionTimestamp`, `createdAt`, `updatedAt`).  
- **ubits/ubricks ví dụ**: `MatchOutcomeStateMachine`, `PotentialMatchFormatter`, `AccessValidator`.  
- **`GiftAllocation`**: Ghi nhận việc phân bổ quà tặng.
- **Cấu trúc dữ liệu**: (Chi tiết như đã định nghĩa, bao gồm: `id`, `profileId`, `giftId`, `allocationTimestamp`, `notificationStatus`, `notificationSentTimestamp`, `createdAt`, `updatedAt`).
- **ubits/ubricks ví dụ**: `NotificationStatusManager`.
- **`Gift`**: Lưu thông tin các loại quà tặng (cấu hình).
- **Cấu trúc dữ liệu**: (Chi tiết như đã định nghĩa, bao gồm: `id`, `name`, `description`, `imageUrl`?, `isActive`, `createdAt`, `updatedAt`).
- **ubits/ubricks ví dụ**: `GiftDataValidator`.
**4. Luồng nghiệp vụ & Transactions (Workflows & Transactions)**
Các quy trình chính được điều phối bởi Transactions:
- **`UserRegistrationTransaction`**: Xử lý đăng ký, tạo `Profile`, gửi email xác nhận. Tác động: Tạo `Profile`; dùng `PersistenceAdapter`, `EmailAdapter`, `FileStorageAdapter`.  
- **`MatchingTransaction`**: Chạy logic matching (theo batch/trigger), tạo `MatchOutcome`. Tác động: Đọc `Profile`, Tạo `MatchOutcome`; dùng `PersistenceAdapter`.  
- **`ResultNotificationTransaction`**: Gửi email thông báo kết quả. Tác động: Đọc `Profile`/`MatchOutcome`, Cập nhật `Profile` (status); dùng `PersistenceAdapter`, `EmailAdapter`.  
- **`MatchSelectionTransaction`**: Xử lý việc người dùng chọn/từ chối kết quả. Tác động: Đọc/Cập nhật `Profile`/`MatchOutcome`; dùng `PersistenceAdapter`.  
- **`GiftAllocationTransaction`**: Chạy lucky draw, tạo `GiftAllocation`. Tác động: Đọc `Profile`/`Gift`, Tạo `GiftAllocation`, Cập nhật `Profile`; dùng `PersistenceAdapter`.  
- **`GiftNotificationTransaction`**: Gửi email thông báo trúng thưởng. Tác động: Đọc `GiftAllocation`/`Profile`/`Gift`, Cập nhật `GiftAllocation`; dùng `PersistenceAdapter`, `EmailAdapter`.  
**5. Giao diện người dùng (UIUX - Frontend)**
- **Công nghệ ưu tiên**: HTMX.
- **User-Facing Pages**:
1. Homepage (Giới thiệu, thông tin, CTA đăng ký).  
2. Registration Page (Form đăng ký chi tiết).  
3. Result Page (Nhập code/truy cập link, hiển thị kết quả, xử lý lựa chọn).  
- _Popups phụ trợ_: Điều khoản, Thông tin đội, Tiêu chí ảnh.  
- **Admin Pages**:
1. Login Page.
2. Reporting Page (Thống kê user, team, match count).  
3. Timeline/Campaign Management Page (Quản lý trạng thái, trigger actions).
4. Gift Management Page (Quản lý quà, xem người trúng thưởng).  
**6. API Endpoints**
- **Tiếp cận**: Backend (Go) sẽ trả về chủ yếu là **HTML fragments** cho các tương tác người dùng qua HTMX. Các endpoints trả về **JSON** sẽ được duy trì cho Admin Dashboard và các xử lý AJAX phức tạp (nếu có).
- **Danh sách endpoints chính (đã liệt kê chi tiết trước đó)**:
- Public/User-Facing: `GET /campaign/config`, `POST /profiles`, `POST /photos/upload` (cần thiết kế kỹ), `POST /results/access`, `GET /results/{token}`, `POST /results/select`, `POST /results/decline`.
- Admin (Yêu cầu Auth): `POST /admin/auth/login`, `GET /admin/reports/summary`, `GET /admin/campaign/status`, `POST /admin/campaign/actions/{action}`, `GET/POST/PUT/DELETE /admin/gifts`, `GET /admin/giveaway/allocations`, `POST /admin/giveaway/actions/run-draw`.
**7. Mô hình triển khai (Deployment Model)**
- **Containerization**: Backend (Go) và Frontend (HTMX/Static Assets) sẽ được đóng gói bằng **Docker**.
- **Hosting**: Triển khai trên nền tảng **Cloud** (ví dụ: AWS, GCP, Azure).
- **Database**: Sử dụng **Managed PostgreSQL Service** của Cloud provider.
- **Frontend Serving**: Backend container sẽ render và phục vụ HTML fragments là chính. Tài nguyên tĩnh cơ bản (CSS, JS nhỏ) đi kèm hoặc qua **CDN/Object Storage**.
- **Load Balancing**: Sử dụng Load Balancer của Cloud provider.
**8. Structure of the project**
matchmaking-microsite/
├── cmd/
│ └── api/
│ └── main.go
├── internal/
│ ├── resource/ # === Component: Resource ===
│ │ ├── profile/ # -> ublock: Quản lý Aggregate 'Profile'
│ │ │ ├── profile_aggregate.go # -> ubrick: Struct Profile chính, methods cơ bản
│ │ │ ├── profile_state.go # -> ubrick: Quản lý trạng thái (enum, transitions)
│ │ │ ├── profile_validation.go# -> ubrick: Logic validate (chứa ubit validators)
│ │ │ ├── profile_access.go # -> ubrick: Tạo và quản lý accessCode/personalLink
│ │ │ ├── profile_zodiac.go # -> ubrick: Tính Cung Hoàng Đạo
│ │ │ └── profile_types.go # -> ubit(s): Định nghĩa các kiểu dữ liệu phụ (enum Gender, Team...)
│ │ ├── matchoutcome/ # -> ublock: Quản lý Aggregate 'MatchOutcome'
│ │ │ ├── matchoutcome_aggregate.go # -> ubrick: Struct MatchOutcome chính, methods
│ │ │ ├── matchoutcome_state.go # -> ubrick: Quản lý trạng thái
│ │ │ ├── matchoutcome_formatter.go # -> ubrick: Chuẩn bị dữ liệu tóm tắt (PotentialMatchSummary)
│ │ │ └── matchoutcome_types.go # -> ubit(s): Định nghĩa Status enum, Summary struct
│ │ ├── giftallocation/ # -> ublock: Quản lý Aggregate 'GiftAllocation'
│ │ │ ├── giftallocation_aggregate.go # -> ubrick: Struct GiftAllocation chính, methods
│ │ │ └── giftallocation_notifier.go # -> ubrick: Quản lý trạng thái thông báo
│ │ │ └── giftallocation_types.go # -> ubit(s): Định nghĩa NotificationStatus enum
│ │ └── gift/ # -> ublock: Quản lý Aggregate 'Gift' (cấu hình)
│ │ ├── gift_aggregate.go # -> ubrick: Struct Gift chính, methods cơ bản
│ │ └── gift_validator.go # -> ubrick: Validate dữ liệu Gift
│ ├── transaction/ # === Component: Transaction (Giữ cấu trúc cũ) ===
│ │ ├── registration/
│ │ │ └── saga.go
│ │ ├── matching/
│ │ │ └── saga.go
│ │ │ └── filter.go # (Ví dụ về ubrick chứa logic filter chi tiết)
│ │ ├── resultnotif/
│ │ │ └── saga.go
│ │ └── giftalloc/
│ │ └── saga.go
│ ├── adapter/ # === Component: Adapter (Giữ cấu trúc cũ) ===
│ │ ├── postgres/
│ │ │ ├── connection.go
│ │ │ ├── profile_repo.go
│ │ │ ├── match_repo.go
│ │ │ ├── gift_repo.go
│ │ │ └── models.go
│ │ ├── email/
│ │ │ ├── client.go
│ │ │ └── templates.go
│ │ └── filestorage/
│ │ ├── s3_client.go
│ │ └── validation.go
│ ├── helper/ # === Component: Helper (Giữ cấu trúc cũ) ===
│ │ ├── config/
│ │ │ └── load.go
│ │ ├── logger/
│ │ │ └── log.go
│ │ ├── validation/
│ │ │ └── common.go
│ │ ├── datetime/
│ │ │ └── calc.go
│ │ └── security/
│ │ └── hash.go
│ └── api/ # === Phần xử lý HTTP API (Giữ cấu trúc cũ) ===
│ ├── handler/
│ │ ├── profile.go
│ │ ├── result.go
│ │ ├── admin.go
│ │ └── middleware.go
│ ├── router.go
│ └── dto/
│ ├── request.go
│ └── response.go
├── configs/
│ ├── config.dev.yaml
│ └── config.prod.yaml
├── migrations/
│ └── 001_create_tables.sql
├── go.mod
├── go.sum
├── .gitignore
└── README.md
**9. Các khía cạnh HLD cần làm rõ thêm (Further HLD Considerations)**
Các lĩnh vực cần được định nghĩa chi tiết hơn trong giai đoạn LLD hoặc cần làm rõ chiến lược ở HLD:
- Yêu cầu Phi chức năng chi tiết (Response time, Availability, Data retention).
- Mô hình Bảo mật chi tiết (JWT handling, Access code/link verification logic).
- Tiếp cận chi tiết về Quyền riêng tư Dữ liệu (PII handling).
- Luồng Matching chi tiết ở mức khái niệm (các bước lọc/tính điểm).
- Chiến lược xử lý lỗi, logging, monitoring chi tiết.
- Thiết kế Database Schema vật lý (tables, indexes).
- Chi tiết thuật toán/logic nghiệp vụ cụ thể.
# LƯU Ý:
Khái niệm **U-Hierarchy** (hay "kiến trúc phân cấp chữ U") được chúng ta áp dụng trong dự án này như một **phương pháp để cấu trúc và phân cấp độ chi tiết bên trong** các thành phần kiến trúc chính (như Resource, Transaction, Adapter, Helper, UIUX). Mục tiêu là để thúc đẩy **tính module**, **khả năng tái sử dụng**, và **thiết kế có cấu trúc rõ ràng** cho mã nguồn và các thành phần logic.
Nó bao gồm các cấp độ sau, đi từ nhỏ nhất đến lớn nhất:
1. **ubit**:
- Là đơn vị logic **nhỏ nhất, không thể chia nhỏ hơn** một cách có ý nghĩa trong ngữ cảnh thiết kế.
- Ví dụ: Một hàm (function) đơn lẻ, một định nghĩa kiểu dữ liệu (struct/type), một hằng số (constant), một quy tắc validation cụ thể, một cấu hình đơn lẻ.
2. **ubrick**:
- Là sự **kết hợp của nhiều `ubit` có liên quan** với nhau, cùng phục vụ một mục đích chung hoặc xử lý một khía cạnh cụ thể, gắn kết.
- Ví dụ: Một module chứa tất cả các hàm validation cho Resource `Profile` (`ProfileDataValidation`), một nhóm các hàm tiện ích xử lý chuỗi, một tập hợp các phương thức client để gọi API của một dịch vụ bên ngoài cụ thể.
3. **ublock**:
- Là sự **kết hợp của nhiều `ubrick`** (và có thể cả các `ubit` đơn lẻ), được thiết kế để hoạt động cùng nhau một cách chặt chẽ và quản lý một phần chức năng riêng biệt. Một `ublock` thường có khả năng hoạt động nội bộ ở một mức độ nào đó cho nhiệm vụ cốt lõi của nó.
- Ví dụ: Toàn bộ `Adapter` cho PostgreSQL (`postgres/`), bao gồm quản lý kết nối, các repository cho từng Resource. Hoặc toàn bộ module quản lý logic cho Resource `Profile` (`resource/profile/`).
4. **ubundle**:
- Là sự **kết hợp của nhiều `ublock`** (và có thể cả `ubrick`/`ubit`), cùng nhau cung cấp một **tính năng hoàn chỉnh có thể thấy được bởi người dùng** hoặc một khả năng nghiệp vụ quan trọng.
- Ví dụ: Tính năng "Đăng ký người dùng" hoàn chỉnh bao gồm các `ublock` từ `UIUX` (form đăng ký), `API handler`, `Transaction` (điều phối đăng ký), `Resource` (`Profile`), và `Adapter` (lưu DB, gửi email). Hoặc toàn bộ "Hệ thống Báo cáo Admin".
Tóm lại, U-Hierarchy giúp chúng ta suy nghĩ về cách "đóng gói" các đơn vị logic từ nhỏ đến lớn, tạo ra các lớp trừu tượng rõ ràng và quản lý sự phức tạp khi xây dựng các thành phần lớn của hệ thống.

80
docs/adapter.md Normal file
View File

@ -0,0 +1,80 @@
# FORMAT
# System Connections
## 1. External Connections
### 1.1. Database (PostgreSQL)
* **Purpose:** Lưu trữ các Aggregate nghiệp vụ (Profile, MatchOutcome, Gift, GiftAllocation)
* **Type:** Relational Database (PostgreSQL)
* **Connection Details:** DSN qua biến môi trường (`host`, `port`, `user`, `password`, `dbname`)
* **Authentication:** Credential DB
* **Adapter Module:** `internal/adapter/postgres/connection.go`
* **Notes:** Hỗ trợ JSONB cho các trường linh hoạt
### 1.2. Email Service
* **Purpose:** Gửi email xác nhận, kết quả match, thông báo quà tặng
* **Type:** SMTP/REST
* **Connection Details:** Cấu hình SMTP server hoặc API endpoint qua env vars
* **Authentication:** Basic Auth/API Key qua env vars
* **Adapter Module:** `internal/adapter/email/client.go`
* **Notes:** Templates tại `internal/adapter/email/templates.go`
### 1.3. File Storage (AWS S3)
* **Purpose:** Lưu trữ ảnh người dùng
* **Type:** Object Storage (Amazon S3)
* **Connection Details:** S3 bucket và credentials qua env vars
* **Authentication:** AWS IAM Role/Access Keys
* **Adapter Module:** `internal/adapter/filestorage/s3_client.go`
* **Notes:** Validation logic tại `internal/adapter/filestorage/validation.go`
## 2. Internal Connections
### 2.1. API Handlers <-> Persistence Adapter
* **Purpose:** Thao tác dữ liệu nghiệp vụ
* **Interaction Type:** Direct function calls
* **Details:** Ví dụ: `handler.profile` gọi các method của `ProfileRepository`
### 2.2. Transactions <-> Adapters
* **UserRegistrationTransaction:** PersistenceAdapter, EmailAdapter, FileStorageAdapter
* **MatchingTransaction:** PersistenceAdapter
* **ResultNotificationTransaction:** PersistenceAdapter, EmailAdapter
* **MatchSelectionTransaction:** PersistenceAdapter
* **GiftAllocationTransaction:** PersistenceAdapter
* **GiftNotificationTransaction:** PersistenceAdapter, EmailAdapter
# Adapters
## 1. Persistence Adapter (PostgreSQL)
### Profile Repository
- `SaveProfile(profile Profile) error`
- `GetProfileByID(id string) (Profile, error)`
- `GetProfileByAccessCode(code string) (Profile, error)`
### MatchOutcome Repository
- `SaveMatchOutcome(outcome MatchOutcome) error`
- `GetMatchOutcomeByProfileID(profileID string) (MatchOutcome, error)`
- `UpdateMatchOutcomeStatus(id string, status string) error`
### Gift Repository
- `GetActiveGifts() ([]Gift, error)`
- `GetGiftByID(id string) (Gift, error)`
## 2. Email Adapter
### Email Client
- `SendConfirmationEmail(to string, name string, accessCode string) error`
- `SendMatchResultEmail(to string, profile Profile, matches []Profile) error`
- `SendGiftNotificationEmail(to string, profile Profile, gift Gift) error`
### Email Templates
- Pre-defined templates for each email type with support for variables
## 3. File Storage Adapter (S3)
### Photo Storage
- `UploadPhoto(file []byte, filename string) (string, error)`
- `GetPhotoURL(reference string) (string, error)`
- `ValidatePhoto(file []byte) error`
---

146
docs/architecture.md Normal file
View File

@ -0,0 +1,146 @@
# FORMAT
# Title: System Architecture
# 1. Architecture Overview
## Nguyên tắc thiết kế
- **User-Centric**: Ưu tiên trải nghiệm người dùng, giảm thiểu sự phức tạp
- **Data-Oriented Programming (DOP)**: Thiết kế xoay quanh luồng dữ liệu và các biến đổi dữ liệu
- **Domain-Driven Design (DDD)**: Áp dụng các khái niệm cốt lõi (Bounded Context, Aggregates, Domain Events)
## Thành phần kiến trúc chính
- `Resource`: Các Aggregate DDD đại diện cho đối tượng nghiệp vụ
- `Transaction`: Các Saga/Process Manager điều phối luồng nghiệp vụ phức tạp
- `Adapter`: Xử lý giao tiếp với các hệ thống bên ngoài
- `Helper`: Các thư viện, tiện ích dùng chung
- `UIUX`: Lớp giao diện người dùng
## Phân cấp độ chi tiết (U-Hierarchy)
- `ubit`: Đơn vị logic nhỏ nhất (hàm, type, hằng số)
- `ubrick`: Tập hợp các ubit liên quan
- `ublock`: Thành phần hoạt động độc lập tương đối
- `ubundle`: Tính năng hoàn chỉnh cho người dùng
## Công nghệ
- **Backend**: Go
- **Database**: PostgreSQL (có thể dùng JSONB cho một số trường linh hoạt)
- **Frontend**: HTMX (ưu tiên), JavaScript hạn chế
- **Deployment**: Docker, triển khai trên Cloud (AWS/GCP/Azure)
- **CI/CD Integration**: GitHub Actions
- **Database**: Managed PostgreSQL Service
- **Frontend Serving**: Backend render HTML fragments, CDN cho static assets
# 2. Project Structure
## Directory Tree
matchmaking-microsite/
├── cmd/
│ └── api/
│ └── main.go
├── internal/
│ ├── resource/
│ │ ├── profile/
│ │ │ ├── profile_aggregate.go
│ │ │ ├── profile_state.go
│ │ │ ├── profile_validation.go
│ │ │ ├── profile_access.go
│ │ │ ├── profile_zodiac.go
│ │ │ └── profile_types.go
│ │ ├── matchoutcome/
│ │ │ ├── matchoutcome_aggregate.go
│ │ │ ├── matchoutcome_state.go
│ │ │ ├── matchoutcome_formatter.go
│ │ │ └── matchoutcome_types.go
│ │ ├── giftallocation/
│ │ │ ├── giftallocation_aggregate.go
│ │ │ └── giftallocation_notifier.go
│ │ └── gift/
│ │ ├── gift_aggregate.go
│ │ └── gift_validator.go
│ ├── transaction/
│ │ ├── registration/
│ │ │ └── saga.go
│ │ ├── matching/
│ │ │ ├── saga.go
│ │ │ └── filter.go
│ │ ├── resultnotif/
│ │ │ └── saga.go
│ │ └── giftalloc/
│ │ └── saga.go
│ ├── adapter/
│ │ ├── postgres/
│ │ │ ├── connection.go
│ │ │ ├── profile_repo.go
│ │ │ ├── match_repo.go
│ │ │ ├── gift_repo.go
│ │ │ └── models.go
│ │ ├── email/
│ │ │ ├── client.go
│ │ │ └── templates.go
│ │ └── filestorage/
│ │ ├── s3_client.go
│ │ └── validation.go
│ ├── helper/
│ │ ├── config/
│ │ │ └── load.go
│ │ ├── logger/
│ │ │ └── log.go
│ │ ├── validation/
│ │ │ └── common.go
│ │ ├── datetime/
│ │ │ └── calc.go
│ │ └── security/
│ │ └── hash.go
│ └── api/
│ ├── handler/
│ │ ├── profile.go
│ │ ├── result.go
│ │ ├── admin.go
│ │ └── middleware.go
│ ├── router.go
│ └── dto/
│ ├── request.go
│ └── response.go
├── configs/
│ ├── config.dev.yaml
│ └── config.prod.yaml
├── migrations/
│ └── 001_create_tables.sql
├── go.mod
├── go.sum
├── .gitignore
└── README.md
## Structure Explanation
Cấu trúc tổ chức theo mô hình Domain-Driven Design: `cmd` chứa entrypoint, `internal` phân chia theo domain (resource, transaction, adapter, helper, api) đảm bảo tách biệt concern. Thư mục ngoài (`configs`, `migrations`, `go.mod`, `README.md`) phục vụ cấu hình, database migration và thông tin dự án.
# 3. Key Components
[Detailed description of the important components of the system. For each component, can include:]
## 3.1. [Component Name]
* **Description:** [Detailed description of the component's function and responsibilities.]
* **Location in Directory Tree (if relevant):** `[Directory path]`
* **Dependencies:** `[List of components this component depends on.]`
* **Interactions with Other Components:** `[Description of how this component interacts with other parts of the system.]`
## 3.2. [Another Component Name]
* **Description:** [...]
* **Location in Directory Tree (if relevant):** [...]
* **Dependencies:** [...]
* **Interactions with Other Components:** [...]
# 4. Main Data Flow
[Description of the most important data flows in the system, such as user creation flow, order processing flow. Can use a Mermaid diagram for visualization.]
```mermaid
flowchart LR
  UI -->|Events| BLoC
  BLoC -->|Calls| UseCase
  UseCase -->|Uses| Repository
  Repository -->|Calls| DataSource
  DataSource -->|API/DB| Backend
```
---

7
docs/changelog.md Normal file
View File

@ -0,0 +1,7 @@
# FORMAT
# [YYYY-MM-DD HH:MM] : [Folder name] : [change description]
---
# CHANGELOG
[2025-04-25 15:00] : md : Updated documentation files based on matching_app templates
[2025-04-25 14:01] : md : Created all documentation template files

46
docs/general.md Normal file
View File

@ -0,0 +1,46 @@
# FORMAT
# Title: Matchmaking Microsite
# Short Description: Microsite chiến dịch “Team Ngọt Ngào và Thanh Dịu”, cho phép người dùng đăng ký thông tin cá nhân, matching tự động, thông báo qua email và quay thưởng.
# Core Purpose: Cung cấp nền tảng ghép đôi tự động dựa trên sở thích và tiêu chí người dùng, quản lý thông báo và trao giải thưởng cho người may mắn.
# Key Features Overview:
# - Đăng ký hồ sơ người dùng
# - Ghép đôi tự động với 3 kết quả phù hợp
# - Thông báo qua email (xác nhận, kết quả, quà tặng)
# - Trang kết quả tương tác (HTMX)
# - Quay thưởng và phân bổ quà tặng
# - **Database Connectivity:** Kết nối PostgreSQL qua biến môi trường (host, port, user, password, dbname)
# - **Environment Management:** Hỗ trợ development, staging, production
# - **CI/CD Integration:** Sử dụng GitHub Actions
## Core Technologies
- Go
- PostgreSQL
- HTMX
- Docker
- Cloud (VPS Storage)
- CI/CD (GitHub Actions)
# Target Audience: Cá nhân muốn tham gia chương trình ghép đôi
# Key Document References:
# - **Roadmap:** ./roadmap.md
# - **Architecture:** ./architecture.md
# - **Technical Specifications:** ./spec.md
# - **Database Schema:** ./schema.md
# - **Adapters/Connections:** ./adapter.md
# - **Queries:** ./query.md
# - **UX/UI Design:** ./ux.md
# - **Source Code Repository:** [Link to Git Repo]
# - **Project Management Tool:** [Link to Tool]
# Project Members:
# - [Member Name 1]: [Role]
# - [Member Name 2]: [Role]
# - ...
# (Optional) Reference Projects: [Link hoặc mô tả dự án tương tự]
---

35
docs/query.md Normal file
View File

@ -0,0 +1,35 @@
# FORMAT
# DATABASE QUERIES
## [Short Name/Description of Query]
### Purpose: [Specific purpose of this query.]
### Usage Context: [When and why this query is used.]
### Complexity: [Simple/Medium/Complex]
### Related Tables:
* `[Table Name 1]`
* `[Table Name 2]`
* ...
### Query (`sql` block):
```sql
[Full SQL query]
```
### Explanation:
[Detailed explanation of the query logic, each clause, and how it works.]
### Notes/Considerations:
[Important points about performance, constraints, ...]
### (Optional) SQL Dialect: [e.g., PostgreSQL]
### (Optional) Parameters:
[Parameter Name]: [Data Type] - [Description]
### (Optional) Expected Result/Sample Output:
---

69
docs/roadmap.md Normal file
View File

@ -0,0 +1,69 @@
# FORMAT
# ROADMAP
## Milestones/Features:
### 1. Infrastructure & Environment Setup
Thiết lập cơ sở hạ tầng và môi trường cho dự án.
* **Tasks:**
* [ ] Khởi tạo project Go và cấu hình module (Completed: )
* [ ] Thiết lập Docker/Docker Compose (Completed: )
* [ ] Cấu hình PostgreSQL cho dev/staging/prod (Completed: )
* [ ] Thiết lập CI/CD với GitHub Actions (Completed: )
### 2. User Registration Flow
Xây dựng tính năng đăng ký người dùng và lưu trữ hồ sơ.
* **Tasks:**
* [ ] Thiết kế schema và repository cho `Profile` (Completed: )
* [ ] Triển khai API `POST /profiles` và handler (Completed: )
* [ ] Tích hợp upload ảnh lên S3 (Completed: )
* [ ] Gửi email xác nhận đăng ký (Completed: )
### 3. Matching Engine
Phát triển logic ghép đôi và lưu kết quả.
* **Tasks:**
* [ ] Xây dựng ubit/ubrick tính toán điểm và filter (Completed: )
* [ ] Triển khai saga `MatchingTransaction` (Completed: )
* [ ] Tạo và lưu `MatchOutcome` (Completed: )
* [ ] Xây dựng batch job hoặc trigger real-time (Completed: )
### 4. Result Interaction
Xây dựng giao diện và API cho kết quả match.
* **Tasks:**
* [ ] Tạo Result Page với HTMX (Completed: )
* [ ] Triển khai `GET /results/{token}` (Completed: )
* [ ] API `POST /results/select``POST /results/decline` (Completed: )
* [ ] Cập nhật state trong `MatchOutcome` (Completed: )
### 5. Notifications & Gift Draw
Gửi email kết quả và thực hiện quay thưởng.
* **Tasks:**
* [ ] Saga `ResultNotificationTransaction` email kết quả (Completed: )
* [ ] Saga `GiftAllocationTransaction` quay thưởng và lưu `GiftAllocation` (Completed: )
* [ ] Saga `GiftNotificationTransaction` email trúng thưởng (Completed: )
* [ ] Thiết kế và seed dữ liệu `Gift` (Completed: )
### 6. Admin Dashboard
Xây dựng giao diện quản trị và báo cáo.
* **Tasks:**
* [ ] Implement auth endpoint `POST /admin/auth/login` (Completed: )
* [ ] Reporting Dashboard summary và báo cáo theo team (Completed: )
* [ ] Campaign Management UI & API (Completed: )
* [ ] Gift Management CRUD (Completed: )
### 7. QA, Testing & Monitoring
Đảm bảo chất lượng và vận hành.
* **Tasks:**
* [ ] Viết unit/integration tests (Completed: )
* [ ] Thiết lập monitoring và alert (Completed: )
* [ ] Load testing ≥100 req/s (Completed: )
### 8. Deployment & Handover
Triển khai lên môi trường production và bàn giao.
* **Tasks:**
* [ ] Build & deploy Docker containers lên Cloud (Completed: )
* [ ] Cấu hình load balancer, CDN (Completed: )
* [ ] Cập nhật README và hướng dẫn vận hành (Completed: )
* [ ] Bàn giao tài liệu và training (Completed: )
---

114
docs/schema.md Normal file
View File

@ -0,0 +1,114 @@
# FORMAT
# DATA SCHEMA AND STRUCTURES
## 1. Database Schema
### Table: [Table Name]
#### Description: [Brief description of the table's purpose]
#### Columns:
* **[Column Name]** (`[Data Type]`): [Brief description]. Constraints: `[Constraint(s)]`. [PK/FK (references Table(Column))] [Index (Type)]
#### Relationships:
* `[Table Name]` `[Relationship Type]` `[Another Table Name]` (on `[Column Name]` -> `[Another Table Name].[Column Name]`)
#### Indexes:
* `[Index Name]` on `[Column(s)]` (`[Index Type]`)
## 2. Generic Data Declarations
### 2.1. [Data Structure Name]
#### Description: [Brief description of the purpose of this data structure.]
#### Fields:
* **[Field Name]** (`[Data Type]`): [Brief description of the field]. [Constraints/Rules]
#### Example (Optional):
```json
{
"[field name]": "[example value]",
"[another field]": "[example value]"
}
```
## 3. Application-Specific Data Structures
### 3.1. Profile Aggregate
#### Description: Aggregate for storing user profile information.
#### Fields:
```go
type Profile struct {
ID string
FullName string
DateOfBirth time.Time
Gender string
PreferredGender string
PhoneNumber string
Email string
FacebookLink string
PhotoReference string
Location string
Team string
Hobbies []string
ThingsNotTried []string
HopesForPartner string
Dealbreakers string
MessageToPartner string
ZodiacSign string
AccessCode string
PersonalLink string
AcceptedTerms bool
RegistrationTimestamp time.Time
Status string
IsLuckyWinner bool
CreatedAt time.Time
UpdatedAt time.Time
}
```
### 3.2. MatchOutcome Aggregate
#### Description: Aggregate for storing match outcome information.
#### Fields:
```go
type MatchOutcome struct {
ID string
ProfileID string
PotentialMatchProfileIDs []string
MatchScores map[string]float64 // Optional
Status string
SelectedProfileID string
GenerationTimestamp time.Time
AccessedTimestamp time.Time
SelectionTimestamp time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
```
### 3.3. GiftAllocation Aggregate
#### Description: Aggregate for storing gift allocation information.
#### Fields:
```go
type GiftAllocation struct {
ID string
ProfileID string
GiftID string
AllocationTimestamp time.Time
NotificationStatus string
NotificationSentTimestamp time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
```
### 3.4. Gift Aggregate
#### Description: Aggregate for storing gift information.
#### Fields:
```go
type Gift struct {
ID string
Name string
Description string
ImageURL string // Optional
IsActive bool
CreatedAt time.Time
UpdatedAt time.Time
}
```
---

62
docs/spec.md Normal file
View File

@ -0,0 +1,62 @@
# Thông số kỹ thuật
## File: Zee.md
### Function:
#### Description:
#### Logic:
#### Input:
#### Output:
#### Error Handling:
#### Preconditions:
#### Postconditions:
#### Internal Dependencies:
## Core Technologies
- **Backend**: Go
- **Database**: PostgreSQL
- **Frontend**: HTMX
- **Containerization**: Docker
- **Cloud Hosting**: VPS Storage
## 1. Yêu cầu hệ thống
- **Quy mô dự kiến**: 20,000+ người tham gia, 5,000 lượt matching
- **Hiệu suất**: Xử lý đồng thời 100+ request/s
- **Độ trễ API**: <500ms cho 95% request
- **Thời gian matching**: <5 phút sau khi đăng
## 2. API Endpoints
### Public APIs
- `GET /campaign/config` - Lấy cấu hình campaign
- `POST /profiles` - Đăng ký profile mới
- `POST /photos/upload` - Upload ảnh
- `POST /results/access` - Truy cập kết quả bằng access code
- `GET /results/{token}` - Xem kết quả matching
- `POST /results/select` - Chọn match
- `POST /results/decline` - Từ chối match
### Admin APIs
- `POST /admin/auth/login` - Đăng nhập admin
- `GET /admin/reports/summary` - Báo cáo tổng quan
- `GET /admin/campaign/status` - Trạng thái campaign
- `POST /admin/campaign/actions/{action}` - Thực hiện action campaign
- `GET/POST/PUT/DELETE /admin/gifts` - Quản lý quà tặng
- `GET /admin/giveaway/allocations` - Danh sách phân bổ quà
- `POST /admin/giveaway/actions/run-draw` - Chạy quay thưởng
## 3. Transaction Workflows
1. **UserRegistrationTransaction**: Đăng ký → Tạo Profile → Gửi email xác nhận
2. **MatchingTransaction**: Chạy matching → Tạo MatchOutcome
3. **ResultNotificationTransaction**: Gửi thông báo kết quả
4. **MatchSelectionTransaction**: Xử lý lựa chọn/từ chối
5. **GiftAllocationTransaction**: Quay thưởng → Tạo GiftAllocation
6. **GiftNotificationTransaction**: Gửi thông báo trúng thưởng
## Overall Flow:
```mermaid
sequenceDiagram
 
```
###
---

96
docs/ux.md Normal file
View File

@ -0,0 +1,96 @@
# FORMAT
# UX/UI DOCUMENTATION
## Page: [Page/Screen Name]
### Description: [Brief overview of the page's purpose.]
### Elements:
* **[Element Name 1]** (`[Type of Element]`): [Brief description and key properties/states.]
* **[Element Name 2]** (`[Type of Element]`): [Brief description and key properties/states.]
* ...
### Flow:
1. [User Action 1] -> [Resulting UI Change/Navigation]
2. [User Action 2] -> [Resulting UI Change/Data Update]
3. ... (Can also link to flow diagrams)
### User Stories/Scenarios Supported:
* [Link/Reference to User Story/Scenario 1]
* [Link/Reference to User Story/Scenario 2]
### Accessibility Notes:
* [Brief notes on accessibility considerations for this page.]
### References:
* [Link to Figma/Sketch/Adobe XD file]
* [Link to related specifications]
## Thiết kế giao diện
## 1. User-Facing Pages
### Homepage
- Giới thiệu campaign
- Thông tin về các team
- CTA đăng ký
### Registration Page
- Form đăng ký chi tiết
- Upload ảnh
- Đồng ý điều khoản
### Result Page
- Nhập access code hoặc truy cập qua personal link
- Hiển thị 3 kết quả matching
- Nút chọn/từ chối
## 2. Admin Pages
### Login Page
- Form đăng nhập admin
### Reporting Dashboard
- Thống kê người dùng
- Số lượng matching theo team
- Biểu đồ hoạt động
### Campaign Management
- Timeline campaign
- Trigger các action (bắt đầu matching, gửi thông báo...)
### Gift Management
- Danh sách quà tặng
- Thêm/sửa/xóa quà
- Danh sách người trúng thưởng
## 3. UI Components
- **Form Controls**: Input, Select, Checkbox, File Upload
- **Cards**: Hiển thị profile matching
- **Modals**: Điều khoản, thông báo
- **Loading Indicators**: Khi xử lý matching
## 4. UX Flow
1. Đăng ký → Xác nhận email
2. Chờ matching → Nhận thông báo
3. Xem kết quả → Chọn/từ chối
4. (Nếu trúng) Nhận thông báo quà tặng
## Color Scheme
| Purpose | Color Code |
|----------------|------------|
| Primary | #4361EE |
| Success | #4CC9F0 |
| Warning | #F8961E |
| Danger | #F72585 |
| [Other Purpose] | [Color Code] |
## Component Library
### Component: [Name]
#### Description: [Brief description of the Goal Card component's purpose.]
#### Props/Parameters:
* `title` (`string`): [Description of the title prop.]
* `progress` (`number`): [Description of the progress prop (e.g., 0.0 to 1.0).]
* `deadline` (`string`): [Description of the deadline prop (e.g., format).]
#### States:
* Default
* Completed (visual changes)
#### Usage Guidelines:
[Brief instructions on when and how to use the Goal Card]
---