Files
loyalty-agent-service/plan/master_plan.md

230 lines
11 KiB
Markdown

# Master Plan: Loyalty Agent Service
_Focus hiện tại: MCP Orchestrator cho Reward Core API, dựa trên `loyalty-mcp-server/src/main/resources/specs/reward.json`._
Core Reward API đang expose **11 CSR resources chính** theo cùng một pattern Maker-Checker:
1. `Transaction Category`
2. `Transaction Code`
3. `Statement Output Pool (SOP)`
4. `Pool Definition`
5. `Pool Conversion Rate`
6. `Currency Rate`
7. `Event Maintenance`
8. `Deduction Sequences`
9. `Counter Definition`
10. `Campaign`
11. `Campaign Rule`
Ngoài nhóm CSR trên, spec còn có các endpoint hỗ trợ rất quan trọng cho Agent như `id/generate`, `id/check`, `list`, `count`, `history`, `list-by-ids`, `list-by-codes`, `list-by-pool`, `precision-by-pools`, `find-default`, `exists-default`, `verifyCriteria`, `amount-to-use-view`, `decide-tier-view`.
Vì Core API không sửa được, Loyalty Agent Service/MCP Server sẽ đóng vai trò **orchestrator + DTO builder + validator**: hướng dẫn user điền thông tin, tra cứu dữ liệu phụ thuộc, build DTO hợp lệ, validate trước, rồi mới gọi endpoint CSR tương ứng.
---
## Phase 1: Reward MCP Orchestrator
_Mục tiêu: biến Reward OpenAPI thành bộ MCP tools dùng được trong hội thoại, ưu tiên luồng tạo Campaign/Rule/Pool end-to-end._
### 1.1. Foundation Tools dùng chung
Các resource CSR có pattern giống nhau, nên cần build một lớp client/tool generator hoặc wrapper dùng chung thay vì viết thủ công từng API.
- `generate_id(resource)`: gọi `/api/{resource}/csr/id/generate`.
- `check_id(resource, id)`: gọi `/api/{resource}/csr/id/check/{id}`.
- `get_by_id(resource, id)` hoặc `get_by_record_no(resource, recordNo)`.
- `list(resource, criteria, page, size, sort)`.
- `count(resource, criteria)`.
- `create_draft(resource, dto)`.
- `edit_draft(resource, dto)`.
- `approve/reject/bulk-approve/bulk-reject` chỉ expose sau, vì đây là hành động nhạy cảm.
- `history(resource, criteria)``rejection_reason(recordNo)` dùng để giải thích trạng thái Maker-Checker cho user.
Nguyên tắc: trong giai đoạn đầu, Agent ưu tiên tạo draft, không tự approve.
### 1.2. DTO Builder & Validation Layer
MCP Server cần giữ local draft theo conversation/session để user có thể build DTO từng bước.
- Mỗi draft có `draftId`, `resource`, `dto`, `missingRequiredFields`, `warnings`, `lastCoreValidation`.
- Không đưa các field `readOnly` vào request: `status`, `lastUpdateBy`, `lastUpdateDate`, `lastApproveBy`, `lastApproveDate`, `lastUpdateByName`, `lastApproveByName`.
- Validate required fields theo schema trước khi gọi Core API.
- Validate enum, maxLength/minLength, date/date-time format.
- Với field `$ref: ReferenceData`, Agent phải tra cứu hoặc xác nhận object reference, không chỉ nhét string trần nếu Core client yêu cầu object.
- Với nested DTO trong `CampaignRuleDto`, build theo template theo `ruleType` thay vì hỏi tất cả field.
Required fields quan trọng theo spec:
- `Campaign`: `campaignId`, `name`.
- `CampaignRuleDto`: `campaignId`, `ruleId`, `ruleName`.
- `PoolDefinitionDto`: `poolId`, `poolName`.
- `TransactionCodeDto`: `code`, `description`.
- `TransactionCategoryDto`: `code`, `name`.
- `PoolConversionRateDto`: `code`, `description`.
- `CurrencyRateDto`: `pcrCode`, `effectiveFrom`, `effectiveTo`, `buyRate`, `sellRate`.
- `EventMaintenanceDto`: `eventId`, `description`, `occursNext`.
- `DeductionSequencesDto`: `sequenceId`, `sequenceName`, `effectiveFrom`, `effectiveTo`, `isDefault`.
- `CounterDefinitionDto`: `counterId`, `counterName`, `effectiveFrom`, `effectiveTo`, `entity`, `bucketPeriodUnit`, `whatToCount`, `resetType`, `resetValue`, `updateStateWhen`, `lateValuePosting`.
### 1.3. Dependency Graph thực tế
Không hard-code rằng Campaign Rule nối trực tiếp với Event. Trong schema hiện tại, `CampaignRuleDto` không có `eventId`; nó nối chủ yếu qua:
- `campaignId`
- `poolId` / `subPoolId`
- `campaignTcLinkages`
- `campaignCriteria`
- `campaignFormula*`
- `campaignRuleSchedule`
- `marketingRewardRequest`
- reward content theo channel `SMS`, `EMAIL`, `NOTIFY`
Dependency graph đề xuất:
1. **Reference/Lookup layer**
- `amount-to-use-view/list`
- `decide-tier-view/list`
- transaction code lookup: `/api/transaction-code/list-by-codes`
- pool lookup: `/api/pool-definition/list-by-ids`, `/api/pool-definition/precision-by-pools`
- deduction sequence default: `/api/deduction-seq/find-default`
2. **Parameter layer**
- `Transaction Category`
- `Transaction Code`
- `Pool Conversion Rate`
- `Currency Rate`
3. **Pool layer**
- `Statement Output Pool`
- `Pool Definition`
- optional `Counter Definition` nếu rule dùng cap/limit/counter formula
4. **Campaign layer**
- `Campaign`
5. **Rule layer**
- `Campaign Rule`
- validate criteria bằng `/api/campaign-rule/campaign-criteria/verify`
- kiểm tra liên kết bằng `/api/campaign-rule/list-by-pool`, `/api/campaign-rule/rule-linked-by-transaction-code`, `/api/campaign-rule/find-matching-rules`
6. **Standalone/scheduled support**
- `Event Maintenance`
- `Deduction Sequences`
### 1.4. Scope triển khai Phase 1
Không làm cả 11 resource ngang nhau ngay. Ưu tiên theo giá trị end-to-end:
**Milestone 1: Read/Lookup Tools**
- Implement tool list/search cho `Campaign`, `Campaign Rule`, `Pool Definition`, `Transaction Code`.
- Implement `generate_id``check_id` cho các resource chính.
- Implement helper lookup: `list-by-codes`, `list-by-ids`, `precision-by-pools`, `amount-to-use-view/list`, `decide-tier-view/list`.
- Output tool phải trả dữ liệu ngắn gọn để Agent dùng tiếp, không dump DTO lớn.
**Milestone 2: Pool Setup**
- Tool tạo draft `PoolConversionRateDto`.
- Tool tạo draft `PoolDefinitionDto`.
- Tool tạo draft `StatementOutputPoolDto` nếu workflow statement cần SOP.
- Validate expiry policy: `FD`, `NE`, `ARD`, `MF`, `QF`, `YF`, `SP`, `AOM`.
- Validate pool type: `BPT`, `CR`, `GFT`, `MI`, `LDR`.
**Milestone 3: Campaign Setup**
- Tool tạo draft `Campaign`.
- Agent tự generate/check `campaignId` nếu user chưa có mã.
- Giữ template tối thiểu: `campaignId`, `name`, `ownerName`, `description`, `campaignType`, `effectiveFrom`, `effectiveTo`.
- Không yêu cầu user nhập `numOfRule`; field này nên derive/hiển thị từ Core nếu có.
**Milestone 4: Campaign Rule Setup**
- Tool tạo draft `CampaignRuleDto`.
- Template theo `ruleType`: `AWD`, `RED`, `IRED`, `ADJ`, `CEP`, `REP`, `TEP`, `MAWD`.
- Với earning/award flow, ưu tiên support:
- `campaignId`
- `ruleId`, `ruleName`
- `poolId`
- `campaignTcLinkages`
- `campaignCriteria`
- `campaignFormulaSetting`
- một trong các `campaignFormulaOne/Two/Four/Five/Six/Eight/Ten/Eleven`
- `campaignAwardLimits` nếu có cap/counter
- Gọi `verifyCriteria` trước khi submit draft nếu user có nhập criteria expression.
**Milestone 5: Approval Visibility**
- Tool xem trạng thái draft, history, rejection reason.
- Tool giải thích record đang ở trạng thái nào và cần maker/checker làm gì tiếp theo.
- Chưa expose approve/reject mặc định; chỉ bật khi có phân quyền và xác nhận rõ.
---
## Phase 2: Memory & Conversation State
_Mục tiêu: Agent nhớ chính xác DTO đang build, các reference đã chọn, và trạng thái Maker-Checker._
- Lưu conversation memory và local draft state trong DB.
- Context locking theo draft: khi user đang build `CampaignRuleDto`, Agent không tự chuyển sang draft khác trừ khi user xác nhận.
- Cho phép nested flow có kiểm soát: nếu đang build rule nhưng thiếu pool, Agent có thể tạo sub-draft `PoolDefinitionDto`, hoàn tất xong quay lại rule.
- Lưu các reference đã tạo/chọn gần nhất: `campaignId`, `ruleId`, `poolId`, `transactionCode`, `counterId`, `pcrCode`.
- Khi user nói "dùng pool vừa tạo", Agent phải resolve từ memory thành reference rõ ràng và hỏi lại nếu có nhiều pool gần đây.
- Mỗi draft cần có audit trail: user intent, fields collected, validation result, endpoint đã gọi, response recordNo/status.
---
## Phase 3: UI/Dashboard hỗ trợ Agent
_Mục tiêu: giảm hội thoại dài bằng UI chuyên biệt cho DTO lớn._
- **Draft Inspector:** hiển thị DTO hiện tại, missing fields, warnings, Core response.
- **Dependency Viewer:** hiển thị Campaign -> Campaign Rule -> Pool -> Transaction Code/Counter/Formula.
- **Interactive Forms:** form động sinh từ schema cho các DTO lớn như `CampaignRuleDto`.
- **Criteria Builder:** UI hỗ trợ build và verify `campaignCriteria.criteria`.
- **Formula Builder:** UI chọn formula type và chỉ hiện field liên quan.
- **Maker-Checker Timeline:** show draft/history/rejection reason để user biết đang chờ bước nào.
- Dùng WebSocket hiện tại để sync draft state real-time giữa chat và UI.
---
## Phase 4: Auto-Pilot & Simulation
_Mục tiêu: từ intent tự nhiên tạo được campaign/rule/pool hoàn chỉnh nhưng vẫn kiểm soát được rủi ro._
- Intent template: "Tạo campaign nhân đôi điểm sinh nhật", "Tạo campaign hoàn tiền 5%", "Tạo rule tặng điểm theo tier".
- Agent tự lập execution plan trước khi gọi API: cần tạo/check resource nào, endpoint nào, payload summary nào.
- Auto-create draft theo thứ tự phụ thuộc, dừng lại khi thiếu field bắt buộc hoặc Core reject.
- Simulation trước approve:
- sample transaction
- matched transaction code
- pool impacted
- formula result
- cap/limit/counter impact
- Human confirmation bắt buộc trước các hành động tạo nhiều draft hoặc gửi approve/reject.
---
## Nguyên tắc triển khai
- OpenAPI spec là source of truth; không đoán DTO field ngoài schema.
- Tool output phải ngắn, có cấu trúc, dễ đưa lại vào Agent context.
- Mutating tools phải idempotent ở tầng Agent/MCP nếu có thể: có `draftId`, correlation id, request summary.
- Mọi create/edit draft đều chạy local validation trước, rồi mới gọi Core.
- Với action nhạy cảm (`approve`, `reject`, `bulk-*`, `delete`), bắt buộc xác nhận rõ từ user.
- Không để Agent tự tạo/chỉnh quá nhiều resource ngầm nếu chưa trình bày execution plan.
---
## Backlog kỹ thuật gần nhất
- [ ] Parse `reward.json` thành metadata nội bộ: resources, schemas, required fields, enums, readOnly fields, endpoints.
- [ ] Implement generic Reward API client cho CSR pattern.
- [ ] Implement MCP tools read-only cho Campaign/Rule/Pool/Transaction Code.
- [ ] Implement local draft store cho `Campaign`, `PoolDefinitionDto`, `CampaignRuleDto`.
- [ ] Implement validator dùng OpenAPI schema.
- [ ] Implement create-draft flow cho Pool Definition.
- [ ] Implement create-draft flow cho Campaign.
- [ ] Implement create-draft flow cho Campaign Rule với `verifyCriteria`.
- [ ] Add integration tests dùng mock Reward Core API.
- [ ] Add UI Draft Inspector sau khi backend flow ổn định.