260518:1640 204 and 302 refactor #11
CI / CD Pipeline / build (push) Successful in 5m12s
CI / CD Pipeline / deploy (push) Successful in 1m58s

This commit is contained in:
admin
2026-05-18 16:40:16 +07:00
parent 0ed27f477f
commit 7e6ad0d346
9 changed files with 1125 additions and 142 deletions
+1
View File
@@ -1 +1,2 @@
pnpm lint-staged
pnpm test pnpm test
+83
View File
@@ -0,0 +1,83 @@
---
auto_execution_mode: 0
description: Manual real-app verification — ตรวจแอปจริงหลัง build pass เพื่อยืนยันว่าทำงานถูกต้องใน environment จริง (ไม่ใช่แค่ unit test)
---
# Workflow: check-real-app
ใช้เมื่อ build/lint/test ผ่านแล้ว แต่ต้องการยืนยันว่าแอปจริงทำงานถูกต้อง
เน้นการตรวจที่ unit test ตรวจไม่ได้: UI flow, API response จริง, console errors, network requests
## ขั้นตอน
### 1. เริ่ม Dev Server (ถ้ายังไม่รัน)
ตรวจก่อนว่ามี dev server รันอยู่แล้วหรือไม่ เพื่อป้องกันรันซ้ำ:
```bash
# Backend
pnpm --filter backend run start:dev
# Frontend
pnpm --filter frontend run dev
```
### 2. ตรวจ Endpoint / หน้าที่เปลี่ยน
- เปิด URL ที่เกี่ยวข้องกับงานที่เพิ่ง implement
- ตรวจ API endpoint ด้วย curl หรือ browser dev tools
- ดู network tab ว่า request/response ถูกต้อง
```bash
# ตัวอย่างตรวจ API จริง
curl -X GET http://localhost:3001/api/[endpoint] \
-H "Authorization: Bearer <token>" | jq .
```
### 3. ตรวจ Console / Log
- **Frontend**: เปิด browser DevTools → Console tab — ต้องไม่มี error หรือ warning ที่ไม่คาดเดา
- **Backend**: ดู terminal log — ตรวจว่าไม่มี unhandled exception หรือ SQL error
### 4. ตรวจ Happy Path + Edge Case หลัก
ตรวจ flow ที่เกี่ยวข้องอย่างน้อย:
- [ ] Happy path ทำงานถูกต้อง
- [ ] Input ผิดรูปแบบ → แสดง error message ที่เหมาะสม
- [ ] Unauthorized access → redirect/403 ถูกต้อง
- [ ] หน้าที่ไม่ได้แก้ยังทำงานปกติ (regression check)
### 5. ตรวจ NAP-DMS Specific
- [ ] UUID ใน URL และ response เป็น string format ถูกต้อง (ไม่ใช่ integer)
- [ ] ไม่มี `NaN` หรือ `undefined` ใน form values หรือ API payload
- [ ] Thai/English text แสดงผลถูกต้อง (i18n)
- [ ] RBAC: role ที่ไม่มีสิทธิ์ไม่เห็น/เข้าถึงไม่ได้
## 🚫 No Fake Evidence Rule
> **ห้ามรายงานว่าตรวจแอปจริงแล้ว ถ้าไม่ได้เปิดแอปและตรวจจริง**
> ถ้าตรวจไม่ได้ (เช่น ไม่มี DB, ไม่มี token) ให้ระบุเหตุผลชัดเจน
## ✅ Mandatory Output
รายงานท้ายงานต้องมีครบ:
### Commands run
```
✅ curl GET /api/correspondences → 200 OK, returned 3 records
✅ curl POST /api/correspondences → 201 Created, uuid: "019..."
❌ ไม่ได้ตรวจ: file upload flow → เหตุผล: ต้องการ ClamAV service ที่ไม่มีใน local
```
### Evidence
- URL ที่ตรวจ + HTTP status code
- Screenshot หรือ response body (ถ้า sensitive ให้ mask)
- Console log ที่พบ (ถ้ามี error ต้องระบุ)
### Limitations / Risks
- flow หรือ endpoint ที่ยังไม่ได้ตรวจ + เหตุผล
- ความเสี่ยงที่ควรตรวจใน staging ก่อน deploy
### Next steps
- งานที่ต้องทำต่อ หรือ flag สำหรับ QA
+100
View File
@@ -0,0 +1,100 @@
---
auto_execution_mode: 0
description: Resume pending multi-session work — อ่าน context เดิม, หา last checkpoint, สรุปสถานะปัจจุบัน และวางแผนต่อ โดยไม่ทำงานซ้ำ
---
# Workflow: resume-pending-work
ใช้เมื่อกลับมาทำงานที่ค้างไว้ข้าม session — เช่น งานใหญ่ที่แบ่งเป็น phase, งาน migration, หรืองานที่หยุดกลางคัน
## ขั้นตอน
### 1. อ่าน Context เดิม
ตรวจแหล่งข้อมูลเหล่านี้ตามลำดับ:
```
1. Memory system — ดู system-retrieved memories ที่เกี่ยวข้อง
2. specs/200-fullstacks/<feature>/tasks.md — ดู task status ล่าสุด
3. git log --oneline -20 — ดู commits ล่าสุด
4. progress.txt หรือ PROGRESS.md (ถ้ามี) — ดู notes ที่ทิ้งไว้
```
### 2. หา Last Checkpoint
ระบุให้ชัดว่า:
- **ทำไปถึงไหนแล้ว** — phase/task/file ที่ complete แล้ว
- **ค้างอยู่ที่ไหน** — step ที่กำลังทำอยู่ตอนหยุด
- **ยังไม่ได้ทำอะไร** — tasks ที่เหลือ
### 3. ตรวจสถานะ Build ปัจจุบัน
ก่อนทำงานต่อ ต้องรู้ว่า codebase ปัจจุบัน clean หรือไม่:
```bash
# ตรวจ TypeScript errors
pnpm --filter backend run build 2>&1 | tail -20
pnpm --filter frontend run build 2>&1 | tail -20
# ดู uncommitted changes
git status --short
git diff --stat HEAD
```
### 4. สรุปสถานะและวางแผนต่อ
ก่อนลงมือ ให้สรุปให้ผู้ใช้เห็นก่อน:
```
✅ เสร็จแล้ว:
- Phase 1: Entity + Migration (commit abc1234)
- Phase 2: Service layer (commit def5678)
🔄 ค้างอยู่:
- Phase 3: Controller — เขียนครึ่งนึง, ยังไม่มี tests
⏳ ยังไม่ได้ทำ:
- Phase 4: Frontend integration
- Phase 5: E2E tests
🚩 Issues ที่พบ:
- build error ที่ correspondence.service.ts:142
```
จากนั้นถามผู้ใช้ว่าต้องการ:
- ทำงานต่อจาก checkpoint เดิม
- Skip ขั้นตอนที่ค้าง (พร้อมระบุ risk)
- Re-verify งานที่ทำไปแล้วก่อน
### 5. ตรวจ NAP-DMS Specific
ก่อน resume ให้ตรวจ:
- [ ] ADR ที่เกี่ยวข้องยังไม่เปลี่ยนแปลง (ดู git log ที่ `specs/06-Decision-Records/`)
- [ ] Schema ที่ใช้อยู่ตรงกับ `lcbp3-v1.9.0-schema-02-tables.sql`
- [ ] ไม่มี merge conflict หรือ stash ค้าง
## 🚫 No Fake Resume Rule
> **ห้ามบอกว่า "ทำต่อจากตรงนี้" โดยไม่ได้อ่าน context เดิมจริง**
> ต้องระบุหลักฐานที่ชัดเจนว่า checkpoint อยู่ที่ไหน
## ✅ Mandatory Output
### Last checkpoint summary
```
- เสร็จแล้ว: [phase/commit/task]
- ค้างอยู่: [file:line หรือ task ที่หยุด]
- ยังไม่ได้ทำ: [tasks ที่เหลือ]
```
### Build status
```
✅ backend build → clean
❌ frontend build → 2 errors (ระบุ errors)
```
### Plan ต่อ
แผน 3-5 ข้อที่จะทำในส่วนที่เหลือ พร้อม verification method
### Risks / Blockers
สิ่งที่อาจ block งาน หรือต้องระวังก่อนทำต่อ
+37
View File
@@ -6,8 +6,45 @@ description: A comprehensive verification system for LCBP3-DMS development sessi
This workflow invokes the verification-loop skill to perform comprehensive verification of LCBP3-DMS code changes. This workflow invokes the verification-loop skill to perform comprehensive verification of LCBP3-DMS code changes.
Invoke the verification-loop skill when: Invoke the verification-loop skill when:
- After completing a feature or significant code change - After completing a feature or significant code change
- Before creating a PR - Before creating a PR
- When you want to ensure quality gates pass - When you want to ensure quality gates pass
- After refactoring - After refactoring
- Before deploying to staging/production - Before deploying to staging/production
## 🚫 No Fake Evidence Rule
> **ห้ามรายงานว่า test ผ่าน / build สำเร็จ ถ้าไม่ได้รันจริง**
> ถ้ารันไม่ได้ ให้ระบุเหตุผลอย่างชัดเจนแทน
## ✅ Mandatory Output (ทุก verification ต้องมีครบ)
รายงานท้ายงานต้องมี 5 หัวข้อนี้เสมอ:
### 1. Pipeline trace
ลำดับขั้นตอนที่ทำจริง: Understand → Plan → Execute → Verify → Handoff
### 2. Commands run
รายการคำสั่งที่รันจริงพร้อมผลสรุป:
```
✅ pnpm run build → Pass (0 errors)
✅ pnpm run lint → Pass (0 warnings)
✅ pnpm run test → 42 passed, 0 failed
❌ ไม่ได้รัน: e2e tests → เหตุผล: ต้องการ DB จริง, ไม่มีใน CI environment
```
### 3. Verification / Evidence
หลักฐานจริง เช่น build output, test result, diff, screenshot, link
### 4. Limitations / Risks
สิ่งที่ยังไม่ได้ตรวจ, ความเสี่ยง, ข้อจำกัดของ environment
### 5. Next steps
งานที่ต้องทำต่อหลัง verification
+178 -98
View File
@@ -1,7 +1,7 @@
# NAP-DMS Project Context & Rules # NAP-DMS Project Context & Rules
- For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools) - For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools)
- Version: 1.9.3 | Last synced from repo: 2026-05-15 - Version: 1.9.5 | Last synced from repo: 2026-05-18
- Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3)
- Skill pack: `.agents/skills/` (v1.9.0, 21 skills) — see [`skills/README.md`](./.agents/skills/README.md) + [`skills/_LCBP3-CONTEXT.md`](./.agents/skills/_LCBP3-CONTEXT.md) - Skill pack: `.agents/skills/` (v1.9.0, 21 skills) — see [`skills/README.md`](./.agents/skills/README.md) + [`skills/_LCBP3-CONTEXT.md`](./.agents/skills/_LCBP3-CONTEXT.md)
@@ -9,20 +9,9 @@
## 🧠 Role & Persona ## 🧠 Role & Persona
Act as a **Senior Full Stack Developer** specialized in: Act as **Senior Full Stack Developer** specialized in NestJS, Next.js, TypeScript, DMS. Focus: Data Integrity, Security, Maintainability, Performance.
- NestJS, Next.js, TypeScript You are a **Document Intelligence Engine** — not a general chatbot. Every response must be **precise**, **spec-compliant**, and **production-ready**.
- Document Management Systems (DMS)
Focus:
- Data Integrity
- Security
- Maintainability
- Performance
You are a **Document Intelligence Engine** — not a general chatbot.
Every response must be **precise**, **spec-compliant**, and **production-ready**.
--- ---
@@ -51,23 +40,23 @@ If significant logic changes are made, summarize what was done for the user afte
## ⚙️ DMS Workflow Engine Protocol ## ⚙️ DMS Workflow Engine Protocol
กฎนี้ใช้คุมการเขียน Logic ส่วนการไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกันปัญหา Race Condition และรักษาความถูกต้องของสถานะเอกสาร: กฎนี้ใช้คุม Logic การไหลของเอกสาร (RFA, Transmittal, Correspondence) เพื่อป้องกัน Race Condition และรักษาความถูกต้องของสถานะ:
- **State Management:** ทุกการเปลี่ยนสถานะของ Workflow ต้องตรวจสอบสถานะปัจจุบันจากฐานข้อมูลก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดูตัวอย่างใน `05-06-code-snippets.md` `[workflow-transition]`) - **State Management:** ตรวจสอบสถานะปัจจุบันจาก DB ก่อนเสมอ เพื่อป้องกันการอนุมัติซ้ำซ้อน (ดู `05-06-code-snippets.md` `[workflow-transition]`)
- **Concurrency Control:** หากมีการจนเลขที่เอกสาร (Document Numbering) ต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น ห้ามใช้ logic ฝั่งแอปพลิเคชันเพียงอย่างเดียว (ADR-002) - **Concurrency Control:** การจนเลขที่เอกสารต้องใช้ **Redis Redlock** หรือ **TypeORM `@VersionColumn`** เท่านั้น (ADR-002)
- **Background Jobs:** งานที่ต้องใช้เวลานานหรือการแจ้งเตือน (Email/Notification) ต้องถูกส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline ใน Service (ADR-008) - **Background Jobs:** งานนานหรือการแจ้งเตือนต้องส่งไปทำที่ **BullMQ** ห้ามเขียนแบบ Inline (ADR-008)
- **Term Consistency:** ห้ามใช้คำทั่วไปอย่าง "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** ตามที่กำหนดใน Glossary - **Term Consistency:** ห้ามใช้ "Approval Flow" ให้ใช้ **"Workflow Engine"** และห้ามใช้ "Letter" ให้ใช้ **"Correspondence"** (หมายเหตุ: "จดหมาย" ในคอมเมนต์ภาษาไทย = Correspondence ที่ครอบคลุมทุกประเภท)
--- ---
## 🛡️ Security & Integrity Audit Protocol ## 🛡️ Security & Integrity Audit Protocol
กฎนี้จะช่วยให้ AI ทำหน้าที่เป็น Gatekeeper ก่อนที่คุณจะ Commit โค้ด โดยเน้นไปที่ **Tier 1 — CRITICAL**: กฎนี้ให้ AI เป็น Gatekeeper ก่อน Commit โดยเน้น **Tier 1 — CRITICAL**:
- **UUID Validation:** ทุกครั้งที่มีการรับค่า ID จาก API หรือ URL ต้องตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` หรือตัวดำเนินการทางคณิตศาสตร์กับค่านี้เด็ดขาด (ADR-019) - **UUID Validation:** ตรวจสอบว่าเป็น **UUIDv7** และห้ามใช้ `parseInt()` บน UUID (ADR-019)
- **RBAC Check:** การสร้าง API ใหม่ต้องมี **CASL Guard** และตรวจสอบสิทธิ์แบบ 4-Level RBAC Matrix เสมอ (ADR-016) - **RBAC Check:** API ใหม่ต้องมี **CASL Guard** และตรวจสอบ 4-Level RBAC Matrix (ADR-016)
- **Data Isolation:** หากมีการใช้ฟีเจอร์ AI ต้องมั่นใจว่ารันผ่าน **Ollama บน Admin Desktop** เท่านั้น และห้ามให้ AI เข้าถึง Database หรือ Storage โดยตรง (ต้องผ่าน DMS API เท่านั้น) (ADR-023) - **Data Isolation:** AI ต้องรันผ่าน **Ollama บน Admin Desktop** เท่านั้น ห้ามเข้าถึง DB/storage โดยตรง (ADR-023)
- **Input Sanitization:** ไฟล์อัปโหลดต้องผ่านการตรวจสอบแบบ **Two-Phase** (Temp → Commit) และต้องสแกนด้วย **ClamAV** ก่อนย้ายเข้า Permanent Storage (ADR-016) - **Input Sanitization:** ไฟล์อัปโหลดต้องผ่าน **Two-Phase** (Temp → Commit) และสแกนด้วย **ClamAV** (ADR-016)
--- ---
@@ -75,7 +64,7 @@ If significant logic changes are made, summarize what was done for the user afte
### 🔴 Tier 1 — CRITICAL (CI BLOCKER) ### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
Build fails immediately if violated: Build fails หากละเมิด:
- Security (Auth, RBAC, Validation) - Security (Auth, RBAC, Validation)
- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID - UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID
@@ -87,7 +76,7 @@ Build fails immediately if violated:
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) ### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
Must fix before merge: Must fix ก่อน merge:
- Architecture patterns (thin controller, business logic in service) - Architecture patterns (thin controller, business logic in service)
- Test coverage (80%+ business logic, 70%+ backend overall) - Test coverage (80%+ business logic, 70%+ backend overall)
@@ -95,7 +84,16 @@ Must fix before merge:
- Naming conventions - Naming conventions
- **TypeScript Standards:** Missing JSDoc, explicit types, or file headers - **TypeScript Standards:** Missing JSDoc, explicit types, or file headers
### 🟢 Tier 3 — GUIDELINES ### 🟢 Tier 3 — SPECIALIZED WORK
Requires domain-specific knowledge:
- **ADR-021 Integration:** Workflow Engine & Context implementation
- **AI Integration:** ADR-023/023A boundary enforcement and pipeline usage
- **Complex Business Logic:** Multi-step workflows with state management
- **Performance Optimization:** Database queries, caching strategies, bulk operations
### 🔵 Tier 4 — GUIDELINES
Best practice — follow when possible: Best practice — follow when possible:
@@ -261,36 +259,36 @@ Full details: `specs/06-Decision-Records/ADR-016-security-authentication.md`
### 📝 Core Standards ### 📝 Core Standards
- **Strict Mode** — all strict checks enforced. - **Strict Mode** — all strict checks enforced
- **ZERO `any` types** — use proper types or `unknown` + narrowing. - **ZERO `any` types** — use proper types or `unknown` + narrowing
- **ZERO `console.log`** — use NestJS `Logger` (backend) or remove before commit (frontend). - **ZERO `console.log`** — use NestJS `Logger` (backend) or remove (frontend)
- **English for Code** — use English for all code identifiers, variables, and logic. - **English for Code** — use English for all code identifiers, variables, and logic
- **Thai for Comments** — use Thai for comments, documentation, and JSDoc. - **Thai for Comments** — use Thai for comments, documentation, and JSDoc
- **Explicit Typing** — explicitly define types for all variables, parameters, and return values. - **Explicit Typing** — explicitly define types for all variables, parameters, and return values
- **JSDoc** — use JSDoc for all public classes and methods. - **JSDoc** — use JSDoc for all public classes and methods
### 🏗️ File & Function Structure ### 🏗️ File & Function Structure
- **File Headers** — every file MUST start with `// File: path/filename` on the first line. - **File Headers** — every file MUST start with `// File: path/filename` on the first line
- **Change Log** — include `// Change Log` at the top of the file to track modifications. - **Change Log** — include `// Change Log` at the top of the file to track modifications
- **Single Export** — export **only one main symbol** (class, interface, or function) per file. - **Single Export** — export **only one main symbol** per file
- **Function Style** — avoid unnecessary blank lines inside functions to maintain compactness. - **Function Style** — avoid unnecessary blank lines inside functions to maintain compactness
--- ---
## 🏷️ Domain Terminology ## 🏷️ Domain Terminology
| ✅ Use | ❌ Don't Use | | ✅ Use | ❌ Don't Use | คำอธิบายเพิ่มเติม |
| ------------------ | ------------------------------------- | | ------------------ | ------------------------------------- | ------------------------------------------------ |
| Correspondence | Letter, Communication, Document | | Correspondence | Letter, Communication, Document | ครอบคลุมทุกประเภท: Letter, RFA, Memo, ฯลฯ |
| RFA | Approval Request, Submit for Approval | | RFA | Approval Request, Submit for Approval | เอกสารขออนุมัติ (ชนิดหนึ่งของ Correspondence) |
| Transmittal | Delivery Note, Cover Letter | | Transmittal | Delivery Note, Cover Letter | เอกสารนำส่ง (ชนิดหนึ่งของ Correspondence) |
| Circulation | Distribution, Routing | | Circulation | Distribution, Routing | ใบเวียนเอกสารภายใน (ชนิดหนึ่งของ Correspondence) |
| Shop Drawing | Construction Drawing | | Shop Drawing | Construction Drawing | แบบก่อสร้าง |
| Contract Drawing | Design Drawing, Blueprint | | Contract Drawing | Design Drawing, Blueprint | แบบคู่สัญญา |
| Workflow Engine | Approval Flow, Process Engine | | Workflow Engine | Approval Flow, Process Engine | เครื่องมือจัดการลำดับงาน |
| Document Numbering | Document ID, Auto Number | | Document Numbering | Document ID, Auto Number | ระบบจัดการเลขที่เอกสาร |
| RBAC | Permission System (generic) | | RBAC | Permission System (generic) | การควบคุมสิทธิ์ตามบทบาท |
Full glossary: `specs/00-overview/00-02-glossary.md` Full glossary: `specs/00-overview/00-02-glossary.md`
@@ -307,7 +305,7 @@ Full glossary: `specs/00-overview/00-02-glossary.md`
| `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors | | `any` TypeScript type | Proper types / generics | Defeats strict mode; hides runtime type errors |
| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage | | `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | Log flooding in production; risk of data leakage |
| `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable | | `req: any` in controllers | `RequestWithUser` typed interface | Type safety lost; auth context unreachable |
| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"019505…"` parsed to integer `19` — silently wrong | | `parseInt()` on UUID values | Use UUID string directly (ADR-019) | `"0195…"` parsed to integer `19` — silently wrong |
| Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks | | Exposing INT PK in API responses | UUIDv7 `publicId` (ADR-019) | Leaks row count; enables DB enumeration attacks |
| AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer | | AI accessing DB/storage directly | AI → DMS API → DB (ADR-023/023A) | Bypasses RBAC, audit trail, and validation layer |
| Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail | | Direct file operations bypassing StorageService | `StorageService` for all file moves | Orphaned files; broken ClamAV scan; no audit trail |
@@ -322,8 +320,6 @@ Full glossary: `specs/00-overview/00-02-glossary.md`
## 🚧 Out of Scope — Never Do Without Explicit Approval ## 🚧 Out of Scope — Never Do Without Explicit Approval
The following actions MUST NOT be performed autonomously. **Stop and ask for confirmation** before proceeding:
| ❌ Never Do Autonomously | ⚠️ Why Approval Is Required | | ❌ Never Do Autonomously | ⚠️ Why Approval Is Required |
| --------------------------------------------------------------- | ---------------------------------------------------------------- | | --------------------------------------------------------------- | ---------------------------------------------------------------- |
| `DROP` or `RENAME` a column / table | Irreversible data loss — requires DBA + PM sign-off | | `DROP` or `RENAME` a column / table | Irreversible data loss — requires DBA + PM sign-off |
@@ -384,24 +380,40 @@ The following actions MUST NOT be performed autonomously. **Stop and ask for con
- All existing tests still pass (no regressions) - All existing tests still pass (no regressions)
- If logic changed: at least 1 regression test added - If logic changed: at least 1 regression test added
### 🟣 ADR-021 Integration Work - Workflow Engine & Context ### Specialized Work — ADR-021, AI Integration, Complex Logic
**MUST complete:** **MUST complete:**
1. **Read ADR-021** - Integrated workflow & step attachments 1. **Domain Knowledge Check** - Read relevant ADRs (ADR-021, ADR-023/023A)
2. **Check ADR-001** - Unified workflow engine patterns 2. **Pattern Verification** - Check existing implementations in codebase
3. **Verify WorkflowEngineService** - Polymorphic instance handling 3. **Specialized Requirements** - Follow domain-specific patterns
4. **Add workflow fields** - Expose workflowInstanceId, workflowState, availableActions 4. **Complex Logic Testing** - Multi-scenario test coverage
5. **Include IntegratedBanner** - Frontend workflow lifecycle display 5. **Performance Validation** - Load testing if applicable
6. **Test workflow transitions** - State changes and action validation
**For ADR-021 Integration:**
- Read ADR-021 - Integrated workflow & step attachments
- Check ADR-001 - Unified workflow engine patterns
- Verify WorkflowEngineService - Polymorphic instance handling
- Add workflow fields - Expose workflowInstanceId, workflowState, availableActions
- Include IntegratedBanner - Frontend workflow lifecycle display
- Test workflow transitions - State changes and action validation
**For AI Integration (ADR-023/023A):**
- Verify AI boundary enforcement - No direct DB/storage access
- Check BullMQ 2-queue setup - ai-realtime + ai-batch
- Validate Qdrant multi-tenancy - projectPublicId filter required
- Test human-in-the-loop validation workflows
- Audit AI interaction logging
**Expected output:** **Expected output:**
- Backend services expose workflow context fields - Backend services expose specialized context fields
- Frontend pages use IntegratedBanner + WorkflowLifecycle - Frontend components use domain-specific patterns
- Workflow instance creation and state management - Complex state management with proper validation
- Proper RBAC guards on workflow actions - Performance metrics within acceptable thresholds
- Unit tests for workflow transitions - Comprehensive test coverage for edge cases
--- ---
@@ -409,47 +421,114 @@ The following actions MUST NOT be performed autonomously. **Stop and ask for con
When user asks about... check these files: When user asks about... check these files:
| Request | Files to Check | Expected Response | | Request | Status | Files to Check | Expected Response |
| ----------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | | --------------------------- | ------ | ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | | "สร้าง API ใหม่" | ✅ | `05-02-backend-guidelines.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard |
| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments | | "แก้ฟอร์ม frontend" | ✅ | `05-03-frontend-guidelines.md`, `01-06-edge-cases-and-rules.md` | RHF+Zod + TanStack Query + Thai comments |
| "เพิ่ม field ใหม่" | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity | | "เพิ่ม field ใหม่" | ✅ | `ADR-009`, `03-01-data-dictionary.md`, `lcbp3-v1.9.0-schema-02-tables.sql` | Edit SQL directly + update Data Dictionary + Entity |
| "ตรวจสอบ UUID" | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor | | "ตรวจสอบ UUID" | ✅ | `ADR-019`, `05-07-hybrid-uuid-implementation-plan.md` | UUIDv7 MariaDB native UUID + TransformInterceptor |
| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow | | "สร้าง migration" | ✅ | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow |
| "ตรวจสอบ permission" | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix | | "ตรวจสอบ permission" | ✅ | `lcbp3-v1.9.0-seed-permissions.sql`, `ADR-016` | CASL 4-Level RBAC matrix |
| "deploy production" | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy | | "deploy production" | ✅ | `04-08-release-management-policy.md`, `ADR-015` | Release Gates + Blue-Green strategy |
| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns | | "เพิ่ม test" | ✅ | `05-04-testing-strategy.md` | Coverage goals + test patterns |
| "AI integration" | `ADR-023`, `ADR-023A` | AI boundary + 2-model stack + BullMQ queue policy | | "AI integration" | ✅ | `ADR-023`, `ADR-023A` | AI boundary + 2-model stack + BullMQ queue policy |
| "Error handling" | `ADR-007` | Layered error classification + recovery | | "Error handling" | ✅ | `ADR-007` | Layered error classification + recovery |
| "File upload" | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist | | "File upload" | ✅ | `ADR-016`, `05-02-backend-guidelines.md`, `03-Data-and-Storage/03-03-file-storage.md` | Two-phase upload → temp → commit; ClamAV + whitelist |
| "Notifications / Queue" | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter | | "Notifications / Queue" | ✅ | `ADR-008`, `05-02-backend-guidelines.md` | BullMQ job — never inline; check retry + dead-letter |
| "Add i18n / translate" | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text | | "Add i18n / translate" | ✅ | `05-08-i18n-guidelines.md` | i18n keys only — no hardcoded text |
| "Workflow / DSL" | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService | | "Workflow / DSL" | ✅ | `ADR-001`, `01-03-modules/01-03-06-unified-workflow.md` | DSL state machine + WorkflowEngineService |
| "Document numbering" | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) | | "Document numbering" | ✅ | `ADR-002`, `01-02-business-rules/01-02-02-doc-numbering-rules.md` | Redis Redlock + DB optimistic lock (double-lock) |
| "ตรวจสอบ Workflow" | `01-06-edge-cases-and-rules.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร | | "ตรวจสอบ Workflow" | ✅ | `01-06-edge-cases-and-rules.md`, `05-02-backend-guidelines.md`, `ADR-001`, `ADR-002` | เช็คการเปลี่ยน State, คิว BullMQ และการล็อกเลขที่เอกสาร |
| "Transmittal submit" | ADR-021, TransmittalService | submit() with EC-RFA-004 validation | | "Transmittal submit" | 📋 | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | submit() with EC-RFA-004 validation |
| "Circulation reassign" | ADR-021, CirculationService | reassignRouting() with EC-CIRC-001 | | "Circulation reassign" | 📋 | `ADR-021`, `specs/200-fullstacks/201-transmittals-circulation/` | reassignRouting() with EC-CIRC-001 |
| "Audit ความปลอดภัย" | `ADR-016`, `ADR-019`, `ADR-023`, `ADR-023A` | ตรวจสอบ UUID pattern, CASL Guard, AI Boundary และ Qdrant multi-tenancy | | "สร้าง workflow ใหม่" | 📋 | `ADR-001`, `ADR-021`, `specs/200-fullstacks/203-unified-workflow-engine/` | DSL workflow definition + WorkflowEngineService setup |
| "แก้ bug / bugfix" | `.agents/workflows/bugfix.md`, `error-catalog.md` | ใช้ bugfix workflow สำหรับเคสที่สาเหตุชัดเจน | | "ตรวจสอบ AI boundary" | ✅ | `ADR-023`, `ADR-023A` | Verify Ollama isolation + BullMQ queues + Qdrant projectPublicId filter |
| "จัดการ document numbering" | ✅ | `ADR-002`, `specs/03-Data-and-Storage/03-04-document-numbering.md` | Redis Redlock + template system + preview/override workflows |
| "Audit ความปลอดภัย" | ✅ | `ADR-016`, `ADR-019`, `ADR-023`, `ADR-023A` | ตรวจสอบ UUID pattern, CASL Guard, AI Boundary และ Qdrant multi-tenancy |
| "แก้ bug / bugfix" | ✅ | `.agents/workflows/bugfix.md`, `error-catalog.md` | ใช้ bugfix workflow สำหรับเคสที่สาเหตุชัดเจน |
| "ตรวจแอปจริง" | ✅ | `.windsurf/workflows/check-real-app.md` | ตรวจ endpoint/UI/console หลัง build pass — No Fake Evidence |
| "งานค้าง / resume" | ✅ | `.windsurf/workflows/resume-pending-work.md` | อ่าน checkpoint เดิม → ตรวจ build → วางแผนต่อโดยไม่ทำงานซ้ำ |
## 🛠️ Final Checklist (Tier 1 & Tier 2) **Status Legend:**
- ✅ Implemented and verified
- 📋 Spec exists, implementation in progress
- 🔄 In development
- ❌ Not yet started
## 🛠️ Final Checklists
### 🔴 Tier 1 — CRITICAL (CI BLOCKER)
**Security & Data Integrity:**
- [ ] **UUID Strategy:** Use `publicId` only, no `parseInt()` on UUID values (ADR-019)
- [ ] **RBAC Guards:** CASL guards on all endpoints, 4-level matrix checked (ADR-016)
- [ ] **AI Boundary:** Ollama isolation, no direct DB/storage access (ADR-023/023A)
- [ ] **Input Validation:** Zod (frontend) + class-validator (backend DTO)
- [ ] **File Upload:** Two-phase (Temp → Commit), ClamAV scan, whitelist enforced
- [ ] **Idempotency:** `Idempotency-Key` header validated on critical POST/PUT/PATCH
- [ ] **Error Handling:** Layered classification (Validation, Business, System) with user-friendly messages (ADR-007)
**Code Quality:**
- [ ] No `any` types in TypeScript (use interfaces/types)
- [ ] No `console.log` in committed code (use NestJS Logger)
- [ ] Database schema verified before writing queries
- [ ] SQL injection prevention checked
### 🟡 Tier 2 — IMPORTANT (CODE REVIEW)
**Architecture & Standards:**
- [ ] **File header `// File: path/filename` present** - [ ] **File header `// File: path/filename` present**
- [ ] **`// Change Log` section included at top** - [ ] **`// Change Log` section included at top**
- [ ] No `any` types in TypeScript (use interfaces/types)
- [ ] No `console.log` in committed code (use Logger)
- [ ] Business logic comments in Thai, technical comments in English
- [ ] Code identifiers in English
- [ ] **JSDoc present for public classes and methods** - [ ] **JSDoc present for public classes and methods**
- [ ] **One main export per file** - [ ] **One main export per file**
- [ ] Schema changes via SQL directly (not migration) - [ ] Business logic in services, thin controllers pattern
- [ ] Schema changes via SQL directly (ADR-009)
- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) - [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+)
- [ ] Relevant ADRs checked (ADR-007, ADR-009, ADR-019, ADR-021, ADR-023, ADR-023A for AI work)
- [ ] Glossary terms used correctly
- [ ] Error handling complete (Logger + HttpException)
- [ ] i18n keys used instead of hardcode text
- [ ] Cache invalidation when data modified - [ ] Cache invalidation when data modified
- [ ] Security checklist passed (OWASP Top 10) - [ ] Naming conventions followed
**Localization & Comments:**
- [ ] Business logic comments in Thai, technical comments in English
- [ ] Code identifiers in English
- [ ] i18n keys used instead of hardcode text
### 🟢 Tier 3 — SPECIALIZED WORK
**Workflow Integration (ADR-021):**
- [ ] WorkflowEngineService polymorphic handling verified
- [ ] Workflow fields exposed (workflowInstanceId, workflowState, availableActions)
- [ ] IntegratedBanner + WorkflowLifecycle components used
- [ ] Workflow transitions tested with state validation
- [ ] RBAC guards on workflow actions
**AI Integration (ADR-023/023A):**
- [ ] **BullMQ Usage:** Background jobs via BullMQ, no inline processing
- [ ] **Qdrant Multi-tenancy:** `projectPublicId` filter enforced
- [ ] **Human-in-the-loop:** AI outputs validated before use
- [ ] **Audit Logging:** All AI interactions logged to `ai_audit_logs`
- [ ] **2-Model Stack:** gemma4:e4b Q8_0 + nomic-embed-text verified
**Performance & Complex Logic:**
- [ ] Performance metrics within targets (P95 ≤ 5s for ≤10MB uploads)
- [ ] Multi-scenario test coverage for edge cases
- [ ] Load testing completed if applicable
- [ ] Complex state management properly validated
### 🔵 Tier 4 — GUIDELINES
**Code Style:**
- [ ] Code formatting follows Prettier rules
- [ ] Comment completeness where helpful
- [ ] Minor optimizations considered but not required
--- ---
@@ -487,7 +566,8 @@ This file is a **quick reference**. For detailed information:
## 🔄 Change Log ## 🔄 Change Log
| Version | Date | Changes | Updated By | | Version | Date | Changes | Updated By |
| ------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- | | ------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------- |
| 1.9.5 | 2026-05-18 | **Grill-with-Docs Session:** Domain terminology clarified (Correspondence = all doc types), Tier 3: SPECIALIZED WORK added, Context-Aware Triggers with Status column, Tier-specific Final Checklists | Windsurf AI |
| 1.9.4 | 2026-05-16 | Added ADR-015 Release Strategy to Key Spec Files table (Blue-Green deployment + release gates) | Human Dev | | 1.9.4 | 2026-05-16 | Added ADR-015 Release Strategy to Key Spec Files table (Blue-Green deployment + release gates) | Human Dev |
| 1.9.3 | 2026-05-15 | ADR-023A: Model revision — gemma4:9b+Typhoon→gemma4:e4b Q8_0 (2-model stack), BullMQ 2-queue split, RAG full-doc embed, OCR auto-detect, n8n→DMS API boundary, QdrantService multi-tenancy contract | Windsurf AI | | 1.9.3 | 2026-05-15 | ADR-023A: Model revision — gemma4:9b+Typhoon→gemma4:e4b Q8_0 (2-model stack), BullMQ 2-queue split, RAG full-doc embed, OCR auto-detect, n8n→DMS API boundary, QdrantService multi-tenancy contract | Windsurf AI |
| 1.9.2 | 2026-05-14 | Consolidated legacy AI ADRs (017, 017B, 018, 020, 022) into master ADR-023: Unified AI Architecture | Antigravity AI | | 1.9.2 | 2026-05-14 | Consolidated legacy AI ADRs (017, 017B, 018, 020, 022) into master ADR-023: Unified AI Architecture | Antigravity AI |
+560 -23
View File
@@ -1,29 +1,566 @@
# Architecture # LCBP3-DMS Architecture Documentation
## Current Structure ---
- `backend/`: NestJS application with shared `CommonModule`, TypeORM entities, BullMQ queue integration, and feature modules such as `rfa`, `review-team`, `response-code`, `delegation`, `reminder`, and `distribution`. **title:** 'LCBP3-DMS Architecture Documentation'
- `frontend/`: Next.js dashboard application with route groups under `app`, shared components under `components`, and feature hooks under `hooks`. **version:** 1.9.2
- `specs/`: Core specifications plus categorized feature work. The active RFA approval refactor lives in `specs/200-fullstacks/204-rfa-approval-refactor`. **status:** active
**owner:** Nattanin Peancharoen
**last_updated:** 2026-05-18
**related:**
## Unified AI Architecture - specs/02-Architecture/02-01-system-context.md
- specs/02-Architecture/02-02-software-architecture.md
- specs/02-Architecture/02-03-network-design.md
- specs/02-Architecture/02-04-api-design.md
- specs/06-Decision-Records/
- `backend/src/modules/ai`: ADR-023 gateway module for AI boundaries. It now owns AI queue registration, n8n service-account validation, the AI-scoped Qdrant gateway, and `MigrationReviewRecord` mapping for `migration_review_queue`. ---
- `backend/src/modules/ai/ai-ingest.service.ts`: publicId-based legacy migration staging service. It accepts n8n/API batches, stores files through `FileStorageService`, creates `migration_review_queue` records, and delegates final import to `MigrationService` after human review.
- `backend/src/modules/ai/workflows/folder-watcher.json`: n8n workflow template for watched-folder ingestion into `/api/ai/legacy-migration/ingest`.
- AI BullMQ queues are centralized in `backend/src/modules/common/constants/queue.constants.ts`: `ai-ingest`, `ai-rag-query`, and `ai-vector-deletion`.
- `frontend/app/(dashboard)/ai-staging`: dashboard route for reviewing AI staging records with constrained project/category/organization dropdowns before approval.
- `frontend/lib/api/ai.ts` and `frontend/components/ai/AiStatusBanner.tsx`: frontend ADR-023 hooks and graceful-degradation banner for AI staging.
- Schema changes for the AI staging queue and AI development feedback log are tracked as SQL delta `specs/03-Data-and-Storage/deltas/12-unified-ai-architecture.sql` per ADR-009.
- Existing RAG ingestion code still lives under `backend/src/modules/rag`; US2 will migrate query orchestration to the ADR-023 AI queue path without replacing the existing ingestion processors in this foundation slice.
- ADR-023A Phase 1 removed the cloud LLM client from `backend/src/modules/rag`; RAG generation now uses `LocalLlmService` with Ollama only, and SQL deltas `14-add-migration-review-queue.sql` plus `15-add-ai-processing-status.sql` track the AI model revision schema changes.
- ADR-023A Phase 2 adds `ai-realtime` and `ai-batch` queue constants, processors, and module registration. `AiRealtimeProcessor` pauses `ai-batch` while interactive work is active, `AiModule.onModuleInit()` auto-resumes stale paused batch queues, and `OllamaService`/`OcrService` provide the local 2-model/OCR foundation for later user stories.
- ADR-023A Phase 3 adds AI Suggest queueing through `/api/ai/suggest`, `/api/ai/jobs/:jobId/status`, `CreateAiJobDto`, and best-effort central commit hooks in `FileStorageService.commit()` when project-scoped metadata is available. `attachments.ai_processing_status` is the current schema-aligned progress field for queued AI work.
## RFA Approval Refactor ## 📋 Table of Contents
- `review-team`: review team CRUD, member assignment, review task creation, aggregate status, consensus, and veto override. 1. [System Context & Architecture](#1-system-context--architecture)
- `response-code`: response code lookup, matrix rules, implications, and notification triggering. 2. [Software Architecture & Design](#2-software-architecture--design)
- `delegation`, `reminder`, `distribution`: supporting modules for proxy assignment, scheduled reminders, and post-approval distribution. Delegation resolution is applied during parallel review task creation while preserving `delegatedFromUserId` for audit/display. 3. [Network Design & Security](#3-network-design--security)
- `distribution`: schema-aligned Distribution Matrix CRUD, BullMQ queueing, approval listener integration, draft Transmittal creation, and `/distribution-matrices` admin UI. 4. [API Design & Error Handling](#4-api-design--error-handling)
- Queue names are centralized in `backend/src/modules/common/constants/queue.constants.ts`. 5. [AI Architecture (ADR-023/023A)](#5-ai-architecture-adr-023023a)
6. [Architecture Decision Records (ADRs)](#6-architecture-decision-records-adrs)
---
## 1. System Context & Architecture
### 1.1 System Overview
ระบบ LCBP3-DMS (Laem Chabang Port Phase 3 - Document Management System) ถูกออกแบบด้วยสถาปัตยกรรมแบบ **Headless/API-First Architecture** โดยทำงานแบบ **On-Premise 100%** บนเครื่องเซอร์ฟเวอร์ QNAP และ ASUSTOR
### 1.2 Architecture Principles
1. **Data Integrity First:** ความถูกต้องของข้อมูลต้องมาก่อนทุกอย่าง
2. **Security by Design & Container Isolation:** รักษาความปลอดภัยที่ทุกชั้น และแยกส่วนการทำงานของแต่ละระบบอย่างชัดเจน
3. **On-Premise First:** ข้อมูลและระบบงานทั้งหมดต้องอยู่ภายในเครือข่ายของโครงการเท่านั้น
4. **Resilience:** ทนทานต่อ Failure และ Recovery ได้รวดเร็ว
5. **Observability:** ติดตามและวิเคราะห์สถานะระบบได้ง่าย
### 1.3 Hardware Infrastructure
| Component | Specification | Role | IP Address |
| --------------------- | ----------------------------------------- | ----------------------------------- | ------------ |
| **Primary Server** | QNAP TS-473A (AMD Ryzen V1500B, 32GB RAM) | Primary NAS for DMS, Container Host | 192.168.10.8 |
| **Backup Server** | ASUSTOR AS5304T | Backup / Secondary NAS | 192.168.10.9 |
| **Network Interface** | LACP bonding (IEEE 802.3ad) | High availability & bandwidth | - |
### 1.4 Container Isolation & Environment
```mermaid
graph TB
subgraph PublicZone["🌐 PUBLIC ZONE"]
NPM["NPM (Reverse Proxy)<br/>Ports: 80, 443"]
end
subgraph AppZone["📱 APPLICATION ZONE (Docker Network 'lcbp3')"]
Frontend["Next.js"]
Backend["NestJS"]
N8N["n8n"]
Gitea["Gitea"]
end
subgraph DataZone["💾 DATA ZONE (Internal Only)"]
MariaDB["MariaDB"]
Redis["Redis"]
ES["Elasticsearch"]
end
PublicZone -->|HTTPS Only| AppZone
AppZone -->|Internal API| DataZone
```
### 1.5 Core Services Architecture
| Service | Application Name | Domain | Technology | Purpose |
| ------------ | ---------------- | ------------------- | ------------------- | ------------------ |
| **Frontend** | lcbp3-frontend | lcbp3.np-dms.work | Next.js 16.2.0 | Web UI |
| **Backend** | lcbp3-backend | backend.np-dms.work | NestJS 11 | API Server & Logic |
| **Database** | lcbp3-db | db.np-dms.work | MariaDB 11.8 | Primary Data |
| **Proxy** | lcbp3-npm | npm.np-dms.work | Nginx Proxy Mgr | Gateway & SSL |
| **Workflow** | lcbp3-n8n | n8n.np-dms.work | n8n | Process Automation |
| **Git** | git | git.np-dms.work | Gitea | Code Repository |
| **Cache** | - | - | Redis | Caching, Locking |
| **Search** | - | - | Elasticsearch 9.3.4 | Full-text Indexing |
### 1.6 Data Flow & Interactions
```mermaid
sequenceDiagram
participant Client as Client
participant NPM as Nginx Proxy
participant BE as Backend (NestJS)
participant Redis as Redis Cache
participant DB as MariaDB
Client->>NPM: HTTP Request + JWT
NPM->>BE: Forward Request
BE->>BE: Rate Limit Check & Validate Input
BE->>Redis: Get User Permissions (RBAC Cache)
Redis-->>BE: Permission Data
BE->>BE: Verify Permission
BE->>DB: Process Logic & Save
BE->>Redis: Invalidate affected Cache
BE-->>Client: JSON Response
```
### 1.7 Backup & Disaster Recovery
- **Database Backup:** ทำ Automated Backup รายวันด้วย QNAP HBS 3
- **File Backup:** ทำ Snapshot จาก `/share/dms-data` บน QNAP ไปยัง ASUSTOR
- **Recovery Standard:** หาก NAS พัง สามารถ Restore Config และรัน `docker-compose up` ขึ้นใหม่ได้ทันที
---
## 2. Software Architecture & Design
### 2.1 Backend Module Architecture (NestJS)
```mermaid
graph TB
subgraph "Core Modules"
Common[CommonModule<br/>Shared Services]
Auth[AuthModule<br/>JWT & Guards]
User[UserModule<br/>User Management]
end
subgraph "Business Modules"
Project[ProjectModule<br/>Projects & Contracts]
Corr[CorrespondenceModule<br/>Correspondences]
RFA[RfaModule<br/>RFA Management]
Drawing[DrawingModule<br/>Shop & Contract Drawings]
Circ[CirculationModule<br/>Circulation Sheets]
end
subgraph "Supporting Modules"
Workflow[WorkflowEngineModule<br/>Unified Workflow]
Numbering[DocumentNumberingModule<br/>Auto Numbering]
Search[SearchModule<br/>Elasticsearch]
end
Corr --> Workflow
RFA --> Workflow
Circ --> Workflow
Corr --> Numbering
RFA --> Numbering
Search --> Corr
Search --> RFA
Search --> Drawing
```
### 2.2 Key Architectural Patterns
#### Unified Workflow Engine (DSL-Based)
ระบบการเดินเอกสารใช้ Engine กลางเดียวกัน ผ่าน **Workflow DSL (JSON Configuration)**
- **Separation of Concerns:** Modules เก็บเฉพาะข้อมูล (Data) ส่วน Flow/State ถูกจัดการโดย Engine
- **Versioning:** อาศัย Workflow Definition Version ป้องกันความขัดแย้งของ State
#### Double-Locking Mechanism (Auto Numbering)
เพื่อป้องกัน Race Condition ในการขอเลขเอกสารพร้อมกัน:
- **Layer 1:** Redis Distributed Lock (ล็อคการเข้าถึงในระดับ Server/Network)
- **Layer 2:** Optimistic Database Lock ผ่าน `@VersionColumn()` (ป้องกันระดับ Data Record)
#### Idempotency
ทุก API ที่แก้ไขสถานะจะต้องส่ง `Idempotency-Key` ป้องกันผู้ใช้กดยืนยันซ้ำสองรอบ
### 2.3 File Upload Flow (Two-Phase Storage)
```mermaid
sequenceDiagram
participant Client as Client
participant BE as Backend
participant Temp as Temp Storage
participant Virus as ClamAV
participant Perm as Permanent Storage
Client->>BE: Upload File
BE->>Virus: Scan File
Virus-->>BE: Clean
BE->>Temp: Save to temp/
BE-->>Client: Return temp_id
Client->>BE: Create Document (with temp_id)
BE->>BE: Validate & Save to DB
BE->>Perm: Move temp/ → permanent/
BE->>Temp: Cleanup temp file
BE-->>Client: Success
```
### 2.4 Security Architecture
#### Rate Limiting (Redis-backed)
| Endpoint Type | Limit | Scope |
| ---------------- | ------------- | ----- |
| Anonymous | 100 req/hour | IP |
| File Upload | 50 req/hour | User |
| Document Control | 2000 req/hour | User |
| Admin | 5000 req/hour | User |
#### Authorization checking flow (CASL)
1. ดึง JWT Token ตรวจสอบความถูกต้อง
2. โหลด User Permissions จาก Redis
3. ตรวจสอบเงื่อนไขตาม Context (Global, Organization, Project, Contract)
4. พิจารณาอนุญาตหากระดับใดระดับหนึ่งอนุญาต
### 2.5 Resilience & Error Handling
- **Circuit Breaker:** ใช้งานครอบ API ภายนอก (Email, LINE Notify)
- **Retry Mechanism:** สำหรับกระบวนการสำคัญชั่วคราว
- **Graceful Degradation:** หาก Search Engine ล่ม ระบบสลับไปใช้ Database Query พื้นฐานชั่วคราวได้
---
## 3. Network Design & Security
### 3.1 Network Segmentation (VLANs)
| VLAN ID | Name | Purpose | Subnet | Gateway | Notes |
| ------- | ------ | ------------------ | --------------- | ------------ | ----------------------------------------- |
| 10 | SERVER | Server & Storage | 192.168.10.0/24 | 192.168.10.1 | Servers (QNAP, ASUSTOR). Static IPs ONLY. |
| 20 | MGMT | Management & Admin | 192.168.20.0/24 | 192.168.20.1 | Network devices, Admin PC. |
| 30 | USER | User Devices | 192.168.30.0/24 | 192.168.30.1 | Staff PC, Printers. |
| 40 | CCTV | Surveillance | 192.168.40.0/24 | 192.168.40.1 | Cameras, NVR. Isolated. |
| 50 | VOICE | IP Phones | 192.168.50.0/24 | 192.168.50.1 | SIP traffic. Isolated. |
| 60 | DMZ | Public Services | 192.168.60.0/24 | 192.168.60.1 | DMZ. Isolated from Internal. |
| 70 | GUEST | Guest Wi-Fi | 192.168.70.0/24 | 192.168.70.1 | Isolated Internet Access only. |
### 3.2 Security Zones
```mermaid
flowchart TB
subgraph PublicZone["🌐 PUBLIC ZONE"]
NPM["NPM (Reverse Proxy)<br/>Ports: 80, 443"]
end
subgraph AppZone["📱 APPLICATION ZONE (Docker Network 'lcbp3')"]
Frontend["Next.js"]
Backend["NestJS"]
N8N["n8n"]
Gitea["Gitea"]
end
subgraph DataZone["💾 DATA ZONE (QNAP - Internal Only)"]
MariaDB["MariaDB"]
Redis["Redis"]
ES["Elasticsearch"]
end
subgraph InfraZone["🛠️ INFRASTRUCTURE ZONE (ASUSTOR)"]
Backup["Backup Services"]
Registry["Docker Registry"]
Monitoring["Prometheus + Grafana"]
end
PublicZone -->|HTTPS Only| AppZone
AppZone -->|Internal API| DataZone
DataZone -.->|Backup| InfraZone
AppZone -.->|Metrics| InfraZone
```
### 3.3 Network Topology
```mermaid
graph TB
subgraph Internet
WAN[("Internet<br/>WAN")]
end
subgraph Router["ER7206 Router"]
R[("ER7206<br/>192.168.20.1")]
end
subgraph CoreSwitch["SG3210X-M2 Core Switch"]
CS[("SG3210X-M2<br/>192.168.20.4")]
end
subgraph Servers["VLAN 10 - Servers"]
QNAP[(" QNAP<br/>192.168.10.8")]
ASUSTOR[(" ASUSTOR<br/>192.168.10.9")]
end
WAN -->|Port 2| R
R -->|SFP Port 1| CS
CS -->|Port 3-4 LACP| QNAP
CS -->|Port 5-6 LACP| ASUSTOR
```
### 3.4 Firewall Rules (ACLs)
กฎของ Firewall จะถูกกำหนดตามหลักการอนุญาตแค่สิ่งที่ต้องการ (Default Deny)
| Priority | Rule | Policy | Source | Destination | Ports |
| -------- | ---------------------- | ------ | ----------------- | ----------------- | -------------------- |
| 1 | Allow-User-DHCP | Allow | Network → VLAN 30 | IP → 192.168.30.1 | DHCP |
| 2 | Allow-Guest-DHCP | Allow | Network → VLAN 70 | IP → 192.168.70.1 | DHCP |
| 3 | Isolate-Servers | Deny | Network → VLAN 10 | Network → VLAN 30 | All |
| 4 | Block-User-to-Mgmt | Deny | Network → VLAN 30 | Network → VLAN 20 | All |
| 5 | Allow-User-to-Services | Allow | Network → VLAN 30 | IP → QNAP | Web (443,8443,80,81) |
| 100 | Default | Deny | Any | Any | All |
### 3.5 QoS (Quality of Service) Settings
| Priority | DSCP Value | Traffic Type | Application |
| ----------- | ---------- | --------------------- | ---------------------- |
| Highest (7) | EF (46) | Voice (SIP/RTP) | IP Phones (VLAN 50) |
| High (6) | AF41 (34) | Video Surveillance | CCTV Cameras (VLAN 40) |
| Medium (5) | AF31 (26) | Critical Applications | DMS Backend, Database |
| Low (4) | AF21 (18) | Best Effort | Web browsing, Email |
---
## 4. API Design & Error Handling
### 4.1 API Design Principles
#### API-First Approach
- **ออกแบบ API ก่อนการ Implement:** ทำการออกแบบ API Endpoint และ Data Contract ให้ชัดเจนก่อนเริ่มเขียนโค้ด
- **Documentation-Driven:** ใช้ OpenAPI/Swagger เป็นเอกสารอ้างอิงหลัก
- **Contract Testing:** ทดสอบ API ตาม Contract ที่กำหนดไว้
#### RESTful Principles
- ใช้ HTTP Methods อย่างถูกต้อง: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`
- ใช้ HTTP Status Codes ที่เหมาะสม
- Resource-Based URL Design
- Stateless Communication
### 4.2 Authentication & Authorization
#### JWT-Based Authentication
- **Token Management:**
- Access Token Expiration: 8 ชั่วโมง
- Refresh Token Expiration: 7 วัน
- Token Rotation: รองรับการหมุนเวียน Refresh Token
#### Authorization (RBAC) (CASL)
ใช้ระบบ 4-Level Permission Hierarchy (Global, Organization, Project, Contract)
```typescript
@RequirePermission('correspondence.create')
@Post('correspondences')
async createCorrespondence(@Body() dto: CreateCorrespondenceDto) {
// Implementation
}
```
### 4.3 API Conventions
#### Base URL Structure
```
https://backend.np-dms.work/api/v1/{resource}
```
#### HTTP Methods & Usage
| Method | Usage | Idempotent | Example |
| -------- | ------------------------------ | ---------- | -------------------------------------- |
| `GET` | ดึงข้อมูล (Read) | ✅ Yes | `GET /api/v1/correspondences` |
| `POST` | สร้างข้อมูลใหม่ (Create) | ❌ No\* | `POST /api/v1/correspondences` |
| `PUT` | อัปเดตทั้งหมด (Full Update) | ✅ Yes | `PUT /api/v1/correspondences/:uuid` |
| `PATCH` | อัปเดตบางส่วน (Partial Update) | ✅ Yes | `PATCH /api/v1/correspondences/:uuid` |
| `DELETE` | ลบข้อมูล (Soft Delete) | ✅ Yes | `DELETE /api/v1/correspondences/:uuid` |
### 4.4 Request Format
**Request Headers:**
```http
Content-Type: application/json
Authorization: Bearer <access_token>
Idempotency-Key: <uuid> # POST/PUT/DELETE
```
### 4.5 Response Formats
#### Success Response
```typescript
{
"data": {
"uuid": "019505a1-7c3e-7000-8000-abc123def456",
"document_number": "CORR-2024-0001",
"subject": "...",
},
"meta": {
"timestamp": "2024-01-01T00:00:00Z",
"version": "1.0"
}
}
```
#### Error Response Format
```typescript
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Validation failed on input data",
"statusCode": 400,
"timestamp": "2024-01-01T00:00:00Z",
"path": "/api/correspondences",
"details": [
{
"field": "subject",
"message": "Subject is required",
"value": null
}
]
}
}
```
### 4.6 Error Handling Strategy
#### Global Exception Filter
คลาสจัดการ Error หลักที่จะจับและดัดแปลง Error ส่งคืน Client อย่างสม่ำเสมอ
#### Custom Business Exception
สำหรับจัดการข้อผิดพลาดเชิงความสัมพันธ์ หรือเงื่อนไขธุรกิจ
```typescript
throw new BusinessException('Cannot approve correspondence in current status', 'INVALID_WORKFLOW_TRANSITION');
```
### 4.7 API Security & Rate Limiting
#### File Upload Security
- **Virus Scanning:** ใช้ ClamAV scan ทุกไฟล์
- **File Type Validation:** White-list (PDF, DWG, DOCX, XLSX, ZIP)
- **File Size Limit:** 50MB per file
- **Two-Phase Storage:** Upload to `temp/` → Commit to `permanent/`
---
## 5. AI Architecture (ADR-023/023A)
### 5.1 AI Integration Architecture
```mermaid
graph TB
subgraph "Frontend"
UI["Document Review Form"]
end
subgraph "Backend (NestJS)"
Gateway["AI Gateway API"]
Queue["BullMQ Queues"]
Validation["Human Validation"]
end
subgraph "Admin Desktop (Desk-5439)"
Ollama["Ollama Engine<br/>gemma4:e4b Q8_0 + nomic-embed-text"]
OCR["PaddleOCR + PyThaiNLP"]
end
subgraph "Vector Database"
Qdrant["Qdrant<br/>Project-scoped Embeddings"]
end
UI --> Gateway
Gateway --> Queue
Queue --> Ollama
Ollama --> Validation
Validation --> Gateway
Gateway --> Qdrant
```
### 5.2 Key Components
| Component | Location | Purpose |
| ----------------- | ------------------------- | ------------------------------------------------------- |
| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging |
| **BullMQ Queues** | Backend (NestJS) | ai-realtime (RAG/Suggest), ai-batch (OCR/Extract/Embed) |
| **Ollama Engine** | Admin Desktop (Desk-5439) | gemma4:e4b Q8_0 (LLM) + nomic-embed-text (Embedding) |
| **OCR Engine** | Admin Desktop (Desk-5439) | PaddleOCR + PyThaiNLP (Thai/English text extraction) |
| **Qdrant** | QNAP NAS | Vector storage with project isolation |
### 5.3 AI Architecture Rules
- **AI Isolation:** All AI processing on Admin Desktop only (Desk-5439)
- **Data Privacy:** No cloud AI services, on-premises only
- **Audit Trail:** Log all AI interactions and human validations
- **Rate Limiting:** Prevent AI abuse and resource exhaustion
- **Validation:** All AI outputs must be validated before use
- **Multi-tenant Isolation:** Qdrant queries MUST include projectPublicId filter
### 5.4 2-Model Stack (ADR-023A)
- **gemma4:e4b Q8_0** (~4.0GB VRAM) - Main LLM for classification, tagging, extraction
- **nomic-embed-text** (~0.3GB VRAM) - Text embedding for RAG
- **Total VRAM Peak:** ~4.3GB
---
## 6. Architecture Decision Records (ADRs)
### 6.1 Key ADRs Implemented
| ADR | Title | Status | Description |
| ------------ | --------------------------- | --------- | -------------------------------------- |
| **ADR-001** | Unified Workflow Engine | ✅ Active | DSL-based workflow implementation |
| **ADR-002** | Document Numbering Strategy | ✅ Active | Document number generation + locking |
| **ADR-007** | Error Handling Strategy | ✅ Active | Layered error classification |
| **ADR-008** | Email Notification Strategy | ✅ Active | BullMQ + multi-channel notification |
| **ADR-009** | Database Migration Strategy | ✅ Active | Schema changes — edit SQL directly |
| **ADR-016** | Security Authentication | ✅ Active | Auth, RBAC, file upload security |
| **ADR-019** | Hybrid Identifier Strategy | ✅ Active | INT PK + UUIDv7 Public API |
| **ADR-021** | Workflow Context | ✅ Active | Integrated workflow & step attachments |
| **ADR-023** | Unified AI Architecture | ✅ Active | AI boundaries and pipeline |
| **ADR-023A** | AI Model Revision | ✅ Active | 2-Model stack with BullMQ queues |
### 6.2 ADR References
For detailed architectural decisions, please refer to:
- `specs/06-Decision-Records/` - Complete ADR documentation
- `AGENTS.md` - Quick-reference rules and enforcement
---
## 📚 Related Documentation
- **System Context:** `specs/02-Architecture/02-01-system-context.md`
- **Software Architecture:** `specs/02-Architecture/02-02-software-architecture.md`
- **Network Design:** `specs/02-Architecture/02-03-network-design.md`
- **API Design:** `specs/02-Architecture/02-04-api-design.md`
- **Decision Records:** `specs/06-Decision-Records/`
- **Data Schema:** `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-*.sql`
- **Engineering Guidelines:** `specs/05-Engineering-Guidelines/`
---
## 🔄 Version History
| Version | Date | Changes |
| --------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------- |
| **1.9.2** | 2026-05-18 | Complete restructure following specs/02-Architecture format, added comprehensive diagrams, updated AI Architecture (ADR-023/023A) |
| **1.9.0** | 2026-05-13 | AI Architecture consolidation, Agent Infrastructure standardization |
| **1.8.0** | 2026-02-23 | Initial architecture documentation |
---
_This document is maintained as part of the LCBP3-DMS project specification suite._
+1 -1
View File
@@ -1,6 +1,6 @@
# 📝 Contributing to LCBP3-DMS Specifications # 📝 Contributing to LCBP3-DMS Specifications
> แนวทางการมีส่วนร่วมในการพัฒนาเอกสาร Specifications ของโครงการ LCBP3-DMS > แนวทางการมีส่วนร่วมในการพัฒนาเอกสาร Specifications ของโครงการ LCBP3-DMS (v1.9.2)
ยินดีต้อนรับสู่คู่มือการมีส่วนร่วมในการพัฒนาเอกสาร Specifications! เอกสารนี้จะช่วยให้คุณเข้าใจวิธีการสร้าง แก้ไข และปรับปรุงเอกสารข้อกำหนดของโครงการได้อย่างมีประสิทธิภาพ ยินดีต้อนรับสู่คู่มือการมีส่วนร่วมในการพัฒนาเอกสาร Specifications! เอกสารนี้จะช่วยให้คุณเข้าใจวิธีการสร้าง แก้ไข และปรับปรุงเอกสารข้อกำหนดของโครงการได้อย่างมีประสิทธิภาพ
+3 -3
View File
@@ -3,16 +3,16 @@
> **Laem Chabang Port Phase 3 - Document Management System** > **Laem Chabang Port Phase 3 - Document Management System**
> ระบบบริหารจัดการเอกสารโครงการแบบครบวงจร สำหรับโครงการก่อสร้างท่าเรือแหลมฉบังระยะที่ 3 > ระบบบริหารจัดการเอกสารโครงการแบบครบวงจร สำหรับโครงการก่อสร้างท่าเรือแหลมฉบังระยะที่ 3
[![Version](https://img.shields.io/badge/version-1.9.0-blue.svg)](./CHANGELOG.md) [![Version](https://img.shields.io/badge/version-1.9.2-blue.svg)](./CHANGELOG.md)
[![License](https://img.shields.io/badge/license-Internal-red.svg)]() [![License](https://img.shields.io/badge/license-Internal-red.svg)]()
[![Status](https://img.shields.io/badge/status-Production%20Ready-brightgreen.svg)]() [![Status](https://img.shields.io/badge/status-Production%20Ready-brightgreen.svg)]()
[![Docs](https://img.shields.io/badge/docs-10%2F10%20Gaps%20Closed-success.svg)](./specs/00-Overview/README.md) [![Docs](https://img.shields.io/badge/docs-10%2F10%20Gaps%20Closed-success.svg)](./specs/00-Overview/README.md)
--- ---
## 📈 Current Status (As of 2026-05-13) ## 📈 Current Status (As of 2026-05-18)
**Version 1.9.0RFA Migration & Universal Agent Infrastructure** **Version 1.9.2AI Model Revision & Hybrid Staging (ADR-023A)**
> v1.8.11 shipped May 5; v1.9.0 (RFA Migration & Agent-Agnostic Infra) shipped May 13. > v1.8.11 shipped May 5; v1.9.0 (RFA Migration & Agent-Agnostic Infra) shipped May 13.
+145
View File
@@ -0,0 +1,145 @@
# Local Dev Setup Guide
> วิธีตั้งค่าและรัน Development Environment สำหรับ LCBP3 NAP-DMS
> อัปเดตล่าสุด: 2026-05-18
---
## Prerequisites
| Tool | Required Version |
|---|---|
| **Node.js** | `>=24.0.0` |
| **pnpm** | `>=10.33.0` |
| **Docker Desktop** | สำหรับ services stack |
ตรวจสอบ version:
```bash
node -v
pnpm -v
docker -v
```
---
## 1. Services Stack (Docker Compose)
รัน `docker-compose up -d` ใน `backend/`:
```bash
docker compose up -d
```
| Service | Port | Credentials |
|---|---|---|
| **MariaDB** | `3306` | user: `admin` / pass: `Center2025` / DB: `lcbp3_dev` |
| **Redis** | `16379` | password: `Center2025` |
| **Elasticsearch** | `9200` | No auth (dev mode) |
| **Qdrant** | `6333` | No auth |
| **phpMyAdmin** | `8080` | optional — ใช้ดู DB ผ่านเว็บ |
---
## 2. Environment Files
### Backend — `backend/.env`
Copy จาก `.env.example`:
```bash
cp backend/.env.example backend/.env
```
ค่าหลักที่ต้องแก้:
```dotenv
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=admin
DB_PASSWORD=Center2025
DB_DATABASE=lcbp3_dev
REDIS_HOST=localhost
REDIS_PORT=16379
REDIS_PASSWORD=Center2025
JWT_SECRET=<สร้างด้วย openssl rand -base64 32>
# AI services (ถ้าไม่ใช้ AI ให้ปล่อยค่าเดิมได้)
OLLAMA_URL=http://192.168.10.100:11434
AI_HOST_URL=http://192.168.10.100:11434
AI_QDRANT_URL=http://192.168.10.100:6333
```
### Frontend — `frontend/.env.local`
Copy จาก `.env.example`:
```bash
cp frontend/.env.example frontend/.env.local
```
ค่าหลักที่ต้องแก้:
```dotenv
NEXT_PUBLIC_API_URL=http://localhost:3001/api
AUTH_SECRET=<สร้างด้วย openssl rand -base64 32>
```
---
## 3. Install Dependencies
จาก root ของ project:
```bash
pnpm install
```
---
## 4. Start Dev Servers
```bash
# รันทั้ง backend + frontend พร้อมกัน (recommended)
pnpm dev
# หรือแยกรัน
pnpm dev:backend # NestJS → http://localhost:3001
pnpm dev:frontend # Next.js → http://localhost:3000
```
---
## 5. Seed Database (ครั้งแรก)
ถ้า DB ว่างหรือเพิ่ง setup ใหม่:
```bash
pnpm --filter backend seed
```
---
## Checklist ก่อน run
- [ ] Node.js `>=24` + pnpm `>=10.33.0` ติดตั้งแล้ว
- [ ] `docker compose up -d` รันใน `backend/` และ services ทุกตัว healthy
- [ ] `backend/.env` สร้างแล้ว และตั้ง `JWT_SECRET`
- [ ] `frontend/.env.local` สร้างแล้ว และตั้ง `AUTH_SECRET`
- [ ] `pnpm install` ที่ root สำเร็จ
- [ ] `pnpm --filter backend seed` รันแล้ว (ครั้งแรก)
- [ ] `pnpm dev` และ backend + frontend start สำเร็จ
---
## Dev URLs
| Service | URL |
|---|---|
| **Frontend** | http://localhost:3000 |
| **Backend API** | http://localhost:3001/api |
| **Swagger UI** | http://localhost:3001/api/docs |
| **phpMyAdmin** | http://localhost:8080 |
| **Elasticsearch** | http://localhost:9200 |
| **Qdrant Dashboard** | http://localhost:6333/dashboard |