diff --git a/.agent/rules/00-project-context.md b/.agent/rules/00-project-context.md new file mode 100644 index 0000000..f639ba3 --- /dev/null +++ b/.agent/rules/00-project-context.md @@ -0,0 +1,60 @@ +--- +trigger: always_on +--- + +# NAP-DMS Project Context + +## Role & Persona + +Act as a **Senior Full Stack Developer** specialized in: + +- NestJS, Next.js, TypeScript +- 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**. + +## Project Information + +- **Project:** NAP-DMS (LCBP3) +- **Version:** 1.8.5 +- **Stack:** NestJS + Next.js + TypeScript + MariaDB + Ollama (AI) +- **Repo:** https://git.np-dms.work/np-dms/lcbp3 + +## Rule Enforcement Tiers + +### 🔴 Tier 1 — CRITICAL (CI BLOCKER) + +Build fails immediately if violated: + +- Security (Auth, RBAC, Validation) +- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID +- Database correctness — verify schema before writing queries +- File upload security (ClamAV + whitelist) +- AI validation boundary (ADR-018) +- Error handling strategy (ADR-007) +- Forbidden patterns: `any`, `console.log`, UUID misuse + +### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) + +Must fix before merge: + +- Architecture patterns (thin controller, business logic in service) +- Test coverage (80%+ business logic, 70%+ backend overall) +- Cache invalidation +- Naming conventions + +### 🟢 Tier 3 — GUIDELINES + +Best practice — follow when possible: + +- Code style / formatting (Prettier handles) +- Comment completeness +- Minor optimizations diff --git a/.agent/rules/00-project-specs.md b/.agent/rules/00-project-specs.md deleted file mode 100644 index e4caa1b..0000000 --- a/.agent/rules/00-project-specs.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -trigger: always_on ---- - -# Project Specifications & Context Protocol - -Description: Enforces strict adherence to the project's documentation structure for all agent activities. -Globs: \* - ---- - -## 🧠 Role & Persona - -Act as a **Senior Full Stack Developer** specialized in: - -- NestJS, Next.js, TypeScript -- 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**. - -## 🧭 Rule Enforcement Tiers - -### 🔴 Tier 1 — CRITICAL (CI BLOCKER) - -Build fails immediately if violated: - -- Security (Auth, RBAC, Validation) -- UUID Strategy (ADR-019) — no `parseInt` / `Number` / `+` on UUID -- Database correctness — verify schema before writing queries -- File upload security (ClamAV + whitelist) -- AI validation boundary (ADR-018) -- Forbidden patterns: `any`, `console.log`, UUID misuse - -### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) - -Must fix before merge: - -- Architecture patterns (thin controller, business logic in service) -- Test coverage (80%+ business logic, 70%+ backend overall) -- Cache invalidation -- Naming conventions - -### 🟢 Tier 3 — GUIDELINES - -Best practice — follow when possible: - -- Code style / formatting (Prettier handles) -- Comment completeness -- Minor optimizations - -## 📖 The Context Loading Protocol - -Before generating code or planning a solution, you MUST conceptually load the context in this specific order: - -1. **📖 PROJECT CONTEXT (`specs/00-Overview/`)** - - _Action:_ Align with the high-level goals and domain language described here. -2. **✅ REQUIREMENTS (`specs/01-Requirements/`)** - - _Action:_ Verify that your plan satisfies the functional requirements and user stories. -3. **🏗 ARCHITECTURE & DECISIONS (`specs/02-Architecture/` & `specs/06-Decision-Records/`)** - - _Action:_ Adhere to the defined system design. - - _Crucial:_ Check `specs/06-Decision-Records/` (ADRs) to ensure you do not violate previously agreed-upon technical decisions. -4. **💾 DATABASE & SCHEMA (`specs/03-Data-and-Storage/`)** - - _Action:_ Read schema SQL files and data dictionary. Use only defined names. -5. **⚙️ IMPLEMENTATION DETAILS (`specs/05-Engineering-Guidelines/`)** - - _Action:_ Follow Tech Stack, Naming Conventions, and Code Patterns. -6. **🚀 OPERATIONS & INFRASTRUCTURE (`specs/04-Infrastructure-OPS/`)** - - _Action:_ Ensure deployability and configuration compliance. - -### 🗂️ Key Spec Files (Priority: ADRs > Engineering Guidelines > others) - -| Document | Path | Use When | -| ----------------------- | ----------------------------------------------------------------- | ------------------------------- | -| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | -| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | -| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | -| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | -| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | -| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns | -| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns | -| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | diff --git a/.agent/rules/01-adr-019-uuid.md b/.agent/rules/01-adr-019-uuid.md new file mode 100644 index 0000000..d3a705a --- /dev/null +++ b/.agent/rules/01-adr-019-uuid.md @@ -0,0 +1,71 @@ +--- +trigger: always_on +--- + +# ADR-019 UUID Strategy + +## CRITICAL RULES + +- **NEVER** use `parseInt()` on UUID values +- **NEVER** use `Number()` on UUID values +- **NEVER** use `+` operator on UUID values +- **ALWAYS** use `publicId` (string UUID) for API responses +- **NEVER** expose internal INT `id` in API responses (use `@Exclude()`) + +## Identifier Types + +| Context | Type | Notes | +| ---------------- | ------------------------- | ------------------------------------------- | +| Internal / DB FK | `INT AUTO_INCREMENT` | Never exposed in API | +| Public API / URL | `UUIDv7` (MariaDB native) | Stored as BINARY(16), no transformer needed | +| Entity Property | `publicId: string` | Exposed directly in API (no transformation) | +| API Response | `publicId: string` (UUID) | INT `id` has `@Exclude()` — never appears | + +## Backend Pattern (NestJS/TypeORM) + +```typescript +// Entity +@Entity() +class Project extends UuidBaseEntity { + @Column({ type: 'uuid' }) + publicId: string; // UUID string, no transformation needed + + @PrimaryKey() + @Exclude() + id: number; // Internal INT, never exposed +} + +// API Response → { id: "019505a1-7c3e-7000-8000-abc123def456" } +// Uses publicId directly, no @Expose({ name: 'id' }) needed +``` + +## Frontend Pattern (Next.js) + +```typescript +// ✅ CORRECT — Use publicId only +type ProjectOption = { + publicId?: string; // No uuid, no id fallback + projectName?: string; +}; + +// ❌ WRONG — Multiple identifiers cause confusion +type ProjectOption = { + publicId?: string; + uuid?: string; // Don't do this + id?: number; // Don't do this +}; + +// ❌ NEVER use parseInt on UUID +parseInt(projectId); // "0195..." → 19 (WRONG!) + +// ❌ NEVER use id ?? '' fallback +const value = c.publicId ?? c.id ?? ''; // Wrong! + +// ✅ CORRECT — Use publicId only +const value = c.publicId; // "019505a1-7c3e-7000-8000-abc123def456" +``` + +## Related Documents + +- `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` +- `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md` diff --git a/.agent/rules/01-code-execution.md b/.agent/rules/01-code-execution.md deleted file mode 100644 index b26de74..0000000 --- a/.agent/rules/01-code-execution.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -trigger: always_on -description: Control which shell commands the agent may run automatically. -allowAuto: - - 'pnpm test:watch' - - 'pnpm test:debug' - - 'pnpm test:e2e' - - 'git status' - - 'git log --oneline' - - 'git diff' - - 'git branch' - - 'tsc --noEmit' -denyAuto: - - 'rm -rf' - - 'Remove-Item' - - 'git push --force' - - 'git reset --hard' - - 'git clean -fd' - - 'curl | bash' - - 'docker compose down' - - 'DROP TABLE' - - 'TRUNCATE' - - 'DELETE FROM' - - 'pnpm migration:*' - - 'npm run migration:*' - - 'npx auth secret' -alwaysReview: true -scopes: - - 'backend/src/**' - - 'backend/test/**' - - 'frontend/app/**' ---- - -# Execution Rules - -- Only auto-execute commands that are explicitly listed in `allowAuto`. -- Commands in `denyAuto` must always be blocked, even if manually requested. -- All shell operations that create, modify, or delete files in `backend/src/`, `backend/test/`, or `frontend/app/` require human review. -- Alert before running any SQL that modifies data (INSERT/UPDATE/DELETE/DROP/TRUNCATE). -- Alert if environment variables related to DB connection or secrets (DATABASE_URL, JWT_SECRET, passwords) would be displayed or logged. -- Never auto-execute commands that expose sensitive credentials via MCP tools or shell output. diff --git a/.agent/rules/02-identifier-strategy.md b/.agent/rules/02-identifier-strategy.md deleted file mode 100644 index 144e4ee..0000000 --- a/.agent/rules/02-identifier-strategy.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -trigger: always_on ---- - -# 🆔 Identifier Strategy (ADR-019) — CRITICAL - -| Context | Type | Notes | -| ---------------- | ------------------------- | ------------------------------------------- | -| Internal / DB FK | `INT AUTO_INCREMENT` | Never exposed in API | -| Public API / URL | `UUIDv7` (MariaDB native) | Stored as BINARY(16), no transformer needed | -| Entity Property | `publicId: string` | Exposed directly in API (no transformation) | - -**CRITICAL RULES:** - -- **NEVER** use `parseInt`, `Number()`, or `+` on UUID values. -- **NEVER** use `id ?? ''` fallback for identifiers in the frontend. -- Use `publicId` only in frontend and public API responses. -- `INT id` has `@Exclude()` on the backend — it must never appear in API responses. diff --git a/.agent/rules/02-security.md b/.agent/rules/02-security.md new file mode 100644 index 0000000..b7f5fa2 --- /dev/null +++ b/.agent/rules/02-security.md @@ -0,0 +1,36 @@ +--- +trigger: always_on +--- + +# Security Rules (Non-Negotiable) + +## Mandatory Security Requirements + +1. **Idempotency:** All critical `POST`/`PUT`/`PATCH` MUST validate `Idempotency-Key` header +2. **Two-Phase File Upload:** Upload → Temp → Commit → Permanent +3. **Race Conditions:** Redis Redlock + TypeORM `@VersionColumn` for Document Numbering +4. **Validation:** Zod (frontend) + class-validator (backend DTO) +5. **Password:** bcrypt 12 salt rounds, min 8 chars, rotate every 90 days +6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints +7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan +8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access +9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages +10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture +11. **AI Audit Trail:** Log all AI interactions and human validations +12. **Rate Limiting:** Apply to AI endpoints to prevent abuse + +## Full Documentation + +`specs/06-Decision-Records/ADR-016-security-authentication.md` + +## Security Checklist (Before Every Commit) + +- [ ] Input validation implemented (Zod/class-validator) +- [ ] RBAC/CASL permissions checked +- [ ] No SQL injection vulnerabilities +- [ ] File upload validation (whitelist + ClamAV) +- [ ] Rate limiting applied to auth endpoints +- [ ] AI boundary enforcement (ADR-018) - no direct DB/storage access +- [ ] AI audit logging implemented for AI interactions +- [ ] Error handling follows ADR-007 layered classification +- [ ] OWASP Top 10 review passed diff --git a/.agent/rules/03-security-rules.md b/.agent/rules/03-security-rules.md deleted file mode 100644 index 16a77e9..0000000 --- a/.agent/rules/03-security-rules.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -trigger: always_on ---- - -# 🛡️ Security Rules (Non-Negotiable) - -1. **Idempotency:** All critical `POST`/`PUT`/`PATCH` MUST validate `Idempotency-Key` header -2. **Two-Phase File Upload:** Upload → Temp → Commit → Permanent -3. **Race Conditions:** Redis Redlock + TypeORM `@VersionColumn` for Document Numbering -4. **Validation:** Zod (frontend) + class-validator (backend DTO) -5. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access - -## 🚫 Forbidden Actions - -| ❌ Forbidden | ✅ Correct Approach | -| ----------------------------------------------- | --------------------------------------------- | -| SQL Triggers for business logic | NestJS Service methods | -| TypeORM migration files | Edit schema SQL directly (ADR-009) | -| `any` TypeScript type | Proper types / generics | -| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | -| Direct file operations bypassing StorageService | `StorageService` for all file moves | -| Inline email/notification sending | BullMQ queue job | -| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | diff --git a/.agent/rules/03-typescript.md b/.agent/rules/03-typescript.md new file mode 100644 index 0000000..443740f --- /dev/null +++ b/.agent/rules/03-typescript.md @@ -0,0 +1,32 @@ +--- +trigger: always_on +--- + +# TypeScript Rules + +## Strict Requirements + +- **Strict Mode** — all strict checks enforced +- **ZERO `any` types** — use proper types or `unknown` + narrowing +- **ZERO `console.log`** — NestJS `Logger` (backend); remove before commit (frontend) + +## Comment Language Policy + +- **Comments:** Thai (เข้าใจง่ายสำหรับทีมไทย) +- **Code Identifiers:** English (variables, functions, classes) + +## Error Handling Pattern + +```typescript +// Backend (NestJS) +import { Logger } from '@nestjs/common'; +const logger = new Logger('ServiceName'); + +// Use logger instead of console.log +logger.error('Error message', error.stack); +throw new HttpException('Message', HttpStatus.BAD_REQUEST); + +// Frontend (Next.js) +// Remove all console.log before commit +// Use proper error boundaries and toast notifications +``` diff --git a/.agent/rules/04-development-standards.md b/.agent/rules/04-development-standards.md deleted file mode 100644 index 8f676ab..0000000 --- a/.agent/rules/04-development-standards.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -trigger: always_on ---- - -# 📐 TypeScript Rules - -- **Strict Mode** — all strict checks enforced -- **ZERO `any` types** — use proper types or `unknown` + narrowing -- **ZERO `console.log`** — NestJS `Logger` (backend); remove before commit (frontend) - -## 🏷️ Domain Terminology (Thai Comments, English Code) - -| ✅ Use | ❌ Don't Use | -| ------------------ | ------------------------------------- | -| Correspondence | Letter, Communication, Document | -| RFA | Approval Request, Submit for Approval | -| Workflow Engine | Approval Flow, Process Engine | -| Document Numbering | Document ID, Auto Number | - -## 🔄 Development Flow (Tiered) - -- **🔴 Critical (DB/API/Security):** MUST follow all Context Protocol steps. -- **🟡 Normal (UI/Feature):** Follow existing patterns, check spec for relevant module. -- **🟢 Quick Fix:** Fix directly, check forbidden patterns before commit. diff --git a/.agent/rules/04-domain-terminology.md b/.agent/rules/04-domain-terminology.md new file mode 100644 index 0000000..9e12c5a --- /dev/null +++ b/.agent/rules/04-domain-terminology.md @@ -0,0 +1,38 @@ +--- +trigger: always_on +--- + +# Domain Terminology + +## DMS Glossary + +| ✅ Use | ❌ Don't Use | +| ------------------ | ------------------------------------- | +| Correspondence | Letter, Communication, Document | +| RFA | Approval Request, Submit for Approval | +| Transmittal | Delivery Note, Cover Letter | +| Circulation | Distribution, Routing | +| Shop Drawing | Construction Drawing | +| Contract Drawing | Design Drawing, Blueprint | +| Workflow Engine | Approval Flow, Process Engine | +| Document Numbering | Document ID, Auto Number | +| RBAC | Permission System (generic) | + +## Full Glossary + +`specs/00-overview/00-02-glossary.md` + +## Key Spec Files Priority + +Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others + +| Document | Path | Use When | +| ----------------------- | ----------------------------------------------------------------- | ------------------------------- | +| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | +| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | +| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | +| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | +| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | +| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns | +| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns | +| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | diff --git a/.agent/rules/05-forbidden-actions.md b/.agent/rules/05-forbidden-actions.md new file mode 100644 index 0000000..1ed488a --- /dev/null +++ b/.agent/rules/05-forbidden-actions.md @@ -0,0 +1,41 @@ +--- +trigger: always_on +--- + +# Forbidden Actions + +## ❌ Never Do This + +| ❌ Forbidden | ✅ Correct Approach | +| ----------------------------------------------- | ----------------------------------------------- | +| SQL Triggers for business logic | NestJS Service methods | +| `.env` files in production | `docker-compose.yml` environment section | +| TypeORM migration files | Edit schema SQL directly (ADR-009) | +| Inventing table/column names | Verify against `schema-02-tables.sql` | +| `any` TypeScript type | Proper types / generics | +| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | +| `req: any` in controllers | `RequestWithUser` typed interface | +| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | +| Exposing INT PK in API responses | UUIDv7 (ADR-019) | +| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | +| Direct file operations bypassing StorageService | `StorageService` for all file moves | +| Inline email/notification sending | BullMQ queue job | +| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | +| AI direct cloud API calls | On-premises Ollama only (ADR-018) | +| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) | + +## Schema Changes (ADR-009) + +- **NO TypeORM migrations** — edit SQL schema directly +- Always check `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` before writing queries +- Update Data Dictionary when changing fields + +## UUID Handling + +See `01-adr-019-uuid.md` for complete UUID rules. + +Quick reminder: + +- ❌ `parseInt(uuid)` → NEVER +- ❌ `Number(uuid)` → NEVER +- ✅ Use UUID string directly diff --git a/.agent/rules/05-precommit-checklist.md b/.agent/rules/05-precommit-checklist.md deleted file mode 100644 index af21df2..0000000 --- a/.agent/rules/05-precommit-checklist.md +++ /dev/null @@ -1,13 +0,0 @@ ---- -trigger: always_on ---- - -# ✅ Quick Reference Checklist (Before Every Commit) - -- [ ] UUID pattern verified (no parseInt on UUID) -- [ ] No `any` types in TypeScript -- [ ] No `console.log` in committed code -- [ ] Comments in Thai, Code identifiers in English -- [ ] Schema changes via SQL directly (not migration) -- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019) -- [ ] i18n keys used instead of hardcode text diff --git a/.agent/rules/06-backend-patterns.md b/.agent/rules/06-backend-patterns.md new file mode 100644 index 0000000..f9c6095 --- /dev/null +++ b/.agent/rules/06-backend-patterns.md @@ -0,0 +1,63 @@ +--- +trigger: always_on +globs: + - "backend/**/*.service.ts" + - "backend/**/*.controller.ts" + - "backend/**/*.dto.ts" + - "backend/**/*.entity.ts" +--- + +# Backend Patterns (NestJS) + +## Architecture + +- **Thin Controller** — business logic in Service layer +- **DTO Validation** — class-validator + class-transformer +- **RBAC** — CASL for authorization +- **Error Handling** — Logger + HttpException + +## UUID Resolution Pattern + +```typescript +// Controller - accept UUID in DTO +@Post() +async create(@Body() dto: CreateCorrespondenceDto) { + // Resolve UUID to internal ID + const contract = await this.contractService.findOneByUuid(dto.contractUuid); + const contractId = contract.id; // Internal INT for DB queries + + return this.service.create(dto, contractId); +} + +// Service - use internal ID for DB operations +async create(dto: CreateCorrespondenceDto, contractId: number) { + // Use contractId (INT) for database queries + const correspondence = this.repo.create({ + contractId, // FK is INT + // ... other fields + }); + return this.repo.save(correspondence); +} +``` + +## API Response Pattern + +```typescript +// Entity +@Entity() +class Contract extends UuidBaseEntity { + @Column({ type: 'uuid' }) + publicId: string; + + @PrimaryKey() + @Exclude() + id: number; +} + +// Response automatically includes publicId as 'id' +// { id: "019505a1-7c3e-7000-8000-abc123def456", ... } +``` + +## Full Guidelines + +`specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` diff --git a/.agent/rules/07-frontend-patterns.md b/.agent/rules/07-frontend-patterns.md new file mode 100644 index 0000000..69c0ee2 --- /dev/null +++ b/.agent/rules/07-frontend-patterns.md @@ -0,0 +1,54 @@ +--- +trigger: always_on +globs: + - "frontend/**/*.tsx" + - "frontend/**/*.ts" + - "frontend/**/*.css" +--- + +# Frontend Patterns (Next.js) + +## Form Handling + +- **RHF** (React Hook Form) for form management +- **Zod** for validation schema +- **TanStack Query** for server state + +## UUID Handling + +```typescript +// ✅ CORRECT - Use publicId only +interface ProjectOption { + publicId?: string; + projectName?: string; +} + +// Select options +const options = contracts.map(c => ({ + label: `${c.contractName} (${c.contractCode})`, + value: c.publicId!, // Use publicId, no fallback to id +})); + +// ❌ WRONG - Never use these patterns +const value = c.publicId ?? c.id ?? ''; // Wrong! +const id = parseInt(projectId); // Wrong - parseInt on UUID! +``` + +## API Client Pattern + +```typescript +// Use publicId directly in API calls +const contract = await contractService.getById(publicId); + +// Form submission with UUID +const onSubmit = async (data: FormData) => { + await correspondenceService.create({ + contractUuid: selectedContract.publicId!, // UUID string + // ... other fields + }); +}; +``` + +## Full Guidelines + +`specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` diff --git a/.agent/rules/08-development-flow.md b/.agent/rules/08-development-flow.md new file mode 100644 index 0000000..80afe6c --- /dev/null +++ b/.agent/rules/08-development-flow.md @@ -0,0 +1,42 @@ +--- +trigger: always_on +--- + +# Development Flow + +## 🔴 Critical Work — DB / API / Security / Workflow Engine + +**MUST complete all steps:** + +1. **Glossary check** — verify domain terms in `00-02-glossary.md` +2. **Read the spec** — select from Key Spec Files table +3. **Check schema** — verify table/column in `schema-02-tables.sql` +4. **Check data dictionary** — confirm field meanings + business rules +5. **Scan edge cases** — `01-06-edge-cases-and-rules.md` +6. **Check ADRs** — verify decisions align (ADR-009, ADR-018, ADR-019) +7. **Write code** — TypeScript strict, no `any`, no `console.log` + +## 🟡 Normal Work — UI / Feature / Integration + +- Follow existing patterns in codebase +- Check spec for relevant module only +- No need to read all specs + +## 🟢 Quick Fix — Bug Fix / Typo / Style + +- Fix directly +- Add minimal test if logic changed +- Check forbidden patterns before commit + +## Context-Aware Triggers + +| Request | Files to Check | Expected Response | +| -------------------- | ------------------------------------------------------- | --------------------------------------------------- | +| "สร้าง API ใหม่" | `05-02-backend-guidelines.md`, `schema-02-tables.sql` | NestJS Controller + Service + DTO + CASL Guard | +| "แก้ฟอร์ม frontend" | `05-03-frontend-guidelines.md`, `01-06-edge-cases.md` | RHF+Zod + TanStack Query + Thai comments | +| "เพิ่ม field ใหม่" | `ADR-009`, `data-dictionary.md`, `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 | +| "สร้าง migration" | `ADR-009`, `03-06-migration-business-scope.md` | Edit SQL schema directly + n8n workflow | +| "ตรวจสอบ permission" | `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 | +| "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns | diff --git a/.agent/rules/09-commit-checklist.md b/.agent/rules/09-commit-checklist.md new file mode 100644 index 0000000..14d4c92 --- /dev/null +++ b/.agent/rules/09-commit-checklist.md @@ -0,0 +1,36 @@ +--- +trigger: always_on +--- + +# Commit Checklist + +## Pre-Commit Verification + +- [ ] UUID pattern verified (no parseInt on UUID) +- [ ] No `any` types in TypeScript +- [ ] No `console.log` in committed code +- [ ] Comments in Thai +- [ ] Code identifiers in English +- [ ] Schema changes via SQL directly (not migration) +- [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) +- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019) +- [ ] Glossary terms used correctly +- [ ] Error handling complete (Logger + HttpException) +- [ ] i18n keys used instead of hardcode text +- [ ] Cache invalidation when data modified +- [ ] Security checklist passed (OWASP Top 10) + +## Commit Message Format + +``` +type(scope): description + +[optional body] +``` + +Types: `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore` + +Examples: +- `feat(correspondence): add originator organization validation` +- `fix(uuid): correct parseInt usage to string comparison` +- `spec(agents): bump to v1.8.5 - refactor structure` diff --git a/.agent/rules/10-error-handling.md b/.agent/rules/10-error-handling.md new file mode 100644 index 0000000..3e7eb70 --- /dev/null +++ b/.agent/rules/10-error-handling.md @@ -0,0 +1,78 @@ +--- +trigger: always_on +--- + +# ADR-007 Error Handling Strategy + +## CRITICAL RULES + +- **ALWAYS** use layered error classification (Validation, Business, System) +- **NEVER** expose technical details to end users +- **ALWAYS** provide user-friendly error messages with recovery guidance +- **ALWAYS** log technical details for debugging +- **NEVER** use generic error messages without context + +## Error Classification + +| Error Type | Description | User Message | Technical Log | +|------------|-------------|--------------|---------------| +| **Validation** | Input validation failures | Clear field-level errors | Full validation details | +| **Business** | Business rule violations | Actionable guidance | Business context + user ID | +| **System** | Infrastructure failures | Generic "try again" | Full stack trace + metrics | + +## Backend Pattern (NestJS) + +```typescript +// Custom Exception Hierarchy +export class BusinessException extends HttpException { + constructor( + message: string, + userMessage: string, + recoveryAction?: string, + errorCode?: string + ) { + super({ message, userMessage, recoveryAction, errorCode }, 400); + } +} + +// Global Exception Filter +@Catch() +export class GlobalExceptionFilter implements ExceptionFilter { + catch(exception: unknown, host: ArgumentsHost) { + // Classify error and provide appropriate response + // Log technical details + // Return user-friendly message + } +} +``` + +## Frontend Pattern (Next.js) + +```typescript +// Error Display Component +const ErrorDisplay = ({ error, onRetry }) => { + const userMessage = error.userMessage || 'เกิดข้อผิดพลาด'; + const recoveryAction = error.recoveryAction; + + return ( +
+

{userMessage}

+ {recoveryAction &&

{recoveryAction}

} + {onRetry && } +
+ ); +}; +``` + +## Required Implementation + +- [ ] Global Exception Filter with layered classification +- [ ] Custom exception hierarchy (Validation, Business, System) +- [ ] Standardized error response DTOs +- [ ] Frontend error display components +- [ ] Error recovery mechanisms where applicable + +## Related Documents + +- `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` +- `specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md` diff --git a/.agent/rules/11-ai-integration.md b/.agent/rules/11-ai-integration.md new file mode 100644 index 0000000..fbb8c5f --- /dev/null +++ b/.agent/rules/11-ai-integration.md @@ -0,0 +1,100 @@ +--- +trigger: always_on +--- + +# ADR-020 AI Integration Architecture + +## CRITICAL RULES + +- **ALWAYS** follow ADR-018 AI boundary policy (isolation on Admin Desktop) +- **ALWAYS** use RFA-First approach for AI implementation +- **NEVER** allow AI direct database/storage access +- **ALWAYS** implement human-in-the-loop validation +- **NEVER** send sensitive data to cloud AI services + +## AI Integration Patterns + +### Architecture Overview + +``` +Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation +``` + +### Key Components + +| Component | Location | Purpose | +|-----------|----------|---------| +| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging | +| **Ollama Engine** | Admin Desktop (Desk-5439) | LLM inference (Gemma 4) | +| **OCR Engine** | Admin Desktop (Desk-5439) | Thai/English text extraction | +| **Orchestrator** | QNAP NAS (n8n) | Workflow management | + +## Backend Implementation (NestJS) + +```typescript +// AI Module with boundary enforcement +@Module({ + controllers: [AiController], + providers: [AiService, AiGateway], + exports: [AiService], +}) +export class AiModule { + constructor() { + // Enforce ADR-018 boundaries + } +} + +// AI Service with validation +@Injectable() +export class AiService { + async extractMetadata(documentId: string): Promise { + // 1. Validate permissions + // 2. Send to Admin Desktop AI + // 3. Validate AI response + // 4. Log audit trail + // 5. Return validated results + } +} +``` + +## Frontend Pattern (Next.js) + +```typescript +// Document Review Form (reusable component) +const DocumentReviewForm = ({ document, aiSuggestions }) => { + return ( +
+ + + + + + + + ); +}; +``` + +## Security Requirements + +- **AI Isolation:** All AI processing on Admin Desktop only +- **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 + +## Required Implementation + +- [ ] AiModule with ADR-018 boundary enforcement +- [ ] AI Gateway API endpoints with validation +- [ ] DocumentReviewForm reusable component +- [ ] Admin Desktop Ollama + PaddleOCR setup +- [ ] n8n workflow orchestration +- [ ] AI audit logging and monitoring +- [ ] Human-in-the-loop validation workflows + +## Related Documents + +- `specs/06-Decision-Records/ADR-018-ai-boundary.md` +- `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` +- `specs/06-Decision-Records/ADR-017-ollama-data-migration.md` diff --git a/.agent/rules/workflows/00-speckit.all.md b/.agent/rules/workflows/00-speckit.all.md new file mode 100644 index 0000000..d9736e7 --- /dev/null +++ b/.agent/rules/workflows/00-speckit.all.md @@ -0,0 +1,85 @@ +--- +description: Run the full speckit pipeline from specification to analysis in one command. +--- + +# Workflow: speckit.all + +This meta-workflow orchestrates the **complete development lifecycle**, from specification through implementation and validation. For the preparation-only pipeline (steps 1-5), use `/speckit.prepare` instead. + +## Preparation Phase (Steps 1-5) + +1. **Specify** (`/speckit.specify`): + - Use the `view_file` tool to read: `.agents/skills/speckit.specify/SKILL.md` + - Execute with user's feature description + - Creates: `spec.md` + +2. **Clarify** (`/speckit.clarify`): + - Use the `view_file` tool to read: `.agents/skills/speckit.clarify/SKILL.md` + - Execute to resolve ambiguities + - Updates: `spec.md` + +3. **Plan** (`/speckit.plan`): + - Use the `view_file` tool to read: `.agents/skills/speckit.plan/SKILL.md` + - Execute to create technical design + - Creates: `plan.md` + +4. **Tasks** (`/speckit.tasks`): + - Use the `view_file` tool to read: `.agents/skills/speckit.tasks/SKILL.md` + - Execute to generate task breakdown + - Creates: `tasks.md` + +5. **Analyze** (`/speckit.analyze`): + - Use the `view_file` tool to read: `.agents/skills/speckit.analyze/SKILL.md` + - Execute to validate consistency across spec, plan, and tasks + - Output: Analysis report + - **Gate**: If critical issues found, stop and fix before proceeding + +## Implementation Phase (Steps 6-7) + +6. **Implement** (`/speckit.implement`): + - Use the `view_file` tool to read: `.agents/skills/speckit.implement/SKILL.md` + - Execute all tasks from `tasks.md` with anti-regression protocols + - Output: Working implementation + +7. **Check** (`/speckit.checker`): + - Use the `view_file` tool to read: `.agents/skills/speckit.checker/SKILL.md` + - Run static analysis (linters, type checkers, security scanners) + - Output: Checker report + +## Verification Phase (Steps 8-10) + +8. **Test** (`/speckit.tester`): + - Use the `view_file` tool to read: `.agents/skills/speckit.tester/SKILL.md` + - Run tests with coverage + - Output: Test + coverage report + +9. **Review** (`/speckit.reviewer`): + - Use the `view_file` tool to read: `.agents/skills/speckit.reviewer/SKILL.md` + - Perform code review + - Output: Review report with findings + +10. **Validate** (`/speckit.validate`): + - Use the `view_file` tool to read: `.agents/skills/speckit.validate/SKILL.md` + - Verify implementation matches spec requirements + - Output: Validation report (pass/fail) + +## Usage + +``` +/speckit.all "Build a user authentication system with OAuth2 support" +``` + +## Pipeline Comparison + +| Pipeline | Steps | Use When | +| ------------------ | ------------------------- | -------------------------------------- | +| `/speckit.prepare` | 1-5 (Specify → Analyze) | Planning only — you'll implement later | +| `/speckit.all` | 1-10 (Specify → Validate) | Full lifecycle in one pass | + +## On Error + +If any step fails, stop the pipeline and report: + +- Which step failed +- The error message +- Suggested remediation (e.g., "Run `/speckit.clarify` to resolve ambiguities before continuing") diff --git a/.agent/rules/workflows/01-speckit.constitution.md b/.agent/rules/workflows/01-speckit.constitution.md new file mode 100644 index 0000000..96544a0 --- /dev/null +++ b/.agent/rules/workflows/01-speckit.constitution.md @@ -0,0 +1,18 @@ +--- +description: Create or update the project constitution from interactive or provided principle inputs, ensuring all dependent templates stay in sync. +--- + +# Workflow: speckit.constitution + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.constitution/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `.specify/` directory doesn't exist: Initialize the speckit structure first diff --git a/.agent/rules/workflows/02-speckit.specify.md b/.agent/rules/workflows/02-speckit.specify.md new file mode 100644 index 0000000..69fd061 --- /dev/null +++ b/.agent/rules/workflows/02-speckit.specify.md @@ -0,0 +1,19 @@ +--- +description: Create or update the feature specification from a natural language feature description. +--- + +# Workflow: speckit.specify + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + - This is typically the starting point of a new feature. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.specify/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the feature description for the skill's logic. + +4. **On Error**: + - If no feature description provided: Ask the user to describe the feature they want to specify diff --git a/.agent/rules/workflows/03-speckit.clarify.md b/.agent/rules/workflows/03-speckit.clarify.md new file mode 100644 index 0000000..9217be3 --- /dev/null +++ b/.agent/rules/workflows/03-speckit.clarify.md @@ -0,0 +1,18 @@ +--- +description: Identify underspecified areas in the current feature spec by asking up to 5 highly targeted clarification questions and encoding answers back into the spec. +--- + +# Workflow: speckit.clarify + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.clarify/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification diff --git a/.agent/rules/workflows/04-speckit.plan.md b/.agent/rules/workflows/04-speckit.plan.md new file mode 100644 index 0000000..456b83c --- /dev/null +++ b/.agent/rules/workflows/04-speckit.plan.md @@ -0,0 +1,18 @@ +--- +description: Execute the implementation planning workflow using the plan template to generate design artifacts. +--- + +# Workflow: speckit.plan + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.plan/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification diff --git a/.agent/rules/workflows/05-speckit.tasks.md b/.agent/rules/workflows/05-speckit.tasks.md new file mode 100644 index 0000000..54967d0 --- /dev/null +++ b/.agent/rules/workflows/05-speckit.tasks.md @@ -0,0 +1,19 @@ +--- +description: Generate an actionable, dependency-ordered tasks.md for the feature based on available design artifacts. +--- + +# Workflow: speckit.tasks + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.tasks/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `plan.md` is missing: Run `/speckit.plan` first + - If `spec.md` is missing: Run `/speckit.specify` first diff --git a/.agent/rules/workflows/06-speckit.analyze.md b/.agent/rules/workflows/06-speckit.analyze.md new file mode 100644 index 0000000..a177a65 --- /dev/null +++ b/.agent/rules/workflows/06-speckit.analyze.md @@ -0,0 +1,22 @@ +--- +description: Perform a non-destructive cross-artifact consistency and quality analysis across spec.md, plan.md, and tasks.md after task generation. +--- + +// turbo-all + +# Workflow: speckit.analyze + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.analyze/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `spec.md` is missing: Run `/speckit.specify` first + - If `plan.md` is missing: Run `/speckit.plan` first + - If `tasks.md` is missing: Run `/speckit.tasks` first diff --git a/.agent/rules/workflows/07-speckit.implement.md b/.agent/rules/workflows/07-speckit.implement.md new file mode 100644 index 0000000..9a23850 --- /dev/null +++ b/.agent/rules/workflows/07-speckit.implement.md @@ -0,0 +1,20 @@ +--- +description: Execute the implementation plan by processing and executing all tasks defined in tasks.md +--- + +# Workflow: speckit.implement + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.implement/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `tasks.md` is missing: Run `/speckit.tasks` first + - If `plan.md` is missing: Run `/speckit.plan` first + - If `spec.md` is missing: Run `/speckit.specify` first diff --git a/.agent/rules/workflows/08-speckit.checker.md b/.agent/rules/workflows/08-speckit.checker.md new file mode 100644 index 0000000..821544b --- /dev/null +++ b/.agent/rules/workflows/08-speckit.checker.md @@ -0,0 +1,21 @@ +--- +description: Run static analysis tools and aggregate results. +--- + +// turbo-all + +# Workflow: speckit.checker + +1. **Context Analysis**: + - The user may specify paths to check or run on entire project. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.checker/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If no linting tools available: Report which tools to install based on project type + - If tools fail: Show raw error and suggest config fixes diff --git a/.agent/rules/workflows/09-speckit.tester.md b/.agent/rules/workflows/09-speckit.tester.md new file mode 100644 index 0000000..80f1eab --- /dev/null +++ b/.agent/rules/workflows/09-speckit.tester.md @@ -0,0 +1,21 @@ +--- +description: Execute tests, measure coverage, and report results. +--- + +// turbo-all + +# Workflow: speckit.tester + +1. **Context Analysis**: + - The user may specify test paths, options, or just run all tests. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.tester/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If no test framework detected: Report "No test framework found. Install Jest, Vitest, Pytest, or similar." + - If tests fail: Show failure details and suggest fixes diff --git a/.agent/rules/workflows/10-speckit.reviewer.md b/.agent/rules/workflows/10-speckit.reviewer.md new file mode 100644 index 0000000..e5e18ef --- /dev/null +++ b/.agent/rules/workflows/10-speckit.reviewer.md @@ -0,0 +1,19 @@ +--- +description: Perform code review with actionable feedback and suggestions. +--- + +# Workflow: speckit.reviewer + +1. **Context Analysis**: + - The user may specify files to review, "staged" for git staged changes, or "branch" for branch diff. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.reviewer/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If no files to review: Ask user to stage changes or specify file paths + - If not a git repo: Review current directory files instead diff --git a/.agent/rules/workflows/11-speckit.validate.md b/.agent/rules/workflows/11-speckit.validate.md new file mode 100644 index 0000000..fbc20d1 --- /dev/null +++ b/.agent/rules/workflows/11-speckit.validate.md @@ -0,0 +1,19 @@ +--- +description: Validate that implementation matches specification requirements. +--- + +# Workflow: speckit.validate + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.validate/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `tasks.md` is missing: Run `/speckit.tasks` first + - If implementation not started: Run `/speckit.implement` first diff --git a/.agent/rules/workflows/create-backend-module.md b/.agent/rules/workflows/create-backend-module.md new file mode 100644 index 0000000..78cf13d --- /dev/null +++ b/.agent/rules/workflows/create-backend-module.md @@ -0,0 +1,51 @@ +--- +description: Create a new NestJS backend feature module following project standards +--- + +# Create NestJS Backend Module + +Use this workflow when creating a new feature module in `backend/src/modules/`. +Follows `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` and ADR-005. + +## Steps + +// turbo + +1. **Verify requirements exist** — confirm the feature is in `specs/01-Requirements/` before starting + +// turbo 2. **Check schema** — read `specs/03-Data-and-Storage/lcbp3-v1.7.0-schema.sql` for relevant tables + +3. **Scaffold module folder** + +``` +backend/src/modules// +├── .module.ts +├── .controller.ts +├── .service.ts +├── dto/ +│ ├── create-.dto.ts +│ └── update-.dto.ts +├── entities/ +│ └── .entity.ts +└── .controller.spec.ts +``` + +4. **Create Entity** — map ONLY columns defined in the schema SQL. Use TypeORM decorators. Add `@VersionColumn()` if the entity needs optimistic locking. + +5. **Create DTOs** — use `class-validator` decorators. Never use `any`. Validate all inputs. + +6. **Create Service** — inject repository via constructor DI. Use transactions for multi-step writes. Add `Idempotency-Key` guard for POST/PUT/PATCH operations. + +7. **Create Controller** — apply `@UseGuards(JwtAuthGuard, CaslAbilityGuard)`. Use proper HTTP status codes. Document with `@ApiTags` and `@ApiOperation`. + +8. **Register in Module** — add to `imports`, `providers`, `controllers`, `exports` as needed. + +9. **Register in AppModule** — import the new module in `app.module.ts`. + +// turbo 10. **Write unit test** — cover service methods with Jest mocks. Run: + +```bash +pnpm test:watch +``` + +// turbo 11. **Citation** — confirm implementation references `specs/01-Requirements/` and `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` diff --git a/.agent/rules/workflows/create-frontend-page.md b/.agent/rules/workflows/create-frontend-page.md new file mode 100644 index 0000000..22c4b2e --- /dev/null +++ b/.agent/rules/workflows/create-frontend-page.md @@ -0,0 +1,64 @@ +--- +description: Create a new Next.js App Router page following project standards +--- + +# Create Next.js Frontend Page + +Use this workflow when creating a new page in `frontend/app/`. +Follows `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md`, ADR-011, ADR-012, ADR-013, ADR-014. + +## Steps + +1. **Determine route** — decide the route path, e.g. `app/(dashboard)/documents/page.tsx` + +2. **Classify components** — decide what is Server Component (default) vs Client Component (`'use client'`) + - Server Component: initial data load, static content, SEO + - Client Component: interactivity, forms, TanStack Query hooks, Zustand + +3. **Create page file** — Server Component by default: + +```typescript +// app/(dashboard)//page.tsx +import { Metadata } from 'next'; + +export const metadata: Metadata = { + title: ' | LCBP3-DMS', +}; + +export default async function Page() { + return ( +
+ {/* Page content */} +
+ ); +} +``` + +4. **Create API hook** (if client-side data needed) — add to `hooks/use-.ts`: + +```typescript +'use client'; +import { useQuery } from '@tanstack/react-query'; +import { apiClient } from '@/lib/api-client'; + +export function use() { + return useQuery({ + queryKey: [''], + queryFn: () => apiClient.get(''), + }); +} +``` + +5. **Build UI components** — use Shadcn/UI primitives. Place reusable components in `components//`. + +6. **Handle forms** — use React Hook Form + Zod schema validation. Never access form values without validation. + +7. **Handle errors** — add `error.tsx` alongside `page.tsx` for route-level error boundaries. + +8. **Add loading state** — add `loading.tsx` for Suspense fallback if page does async work. + +9. **Add to navigation** — update sidebar/nav config if the page should appear in the menu. + +10. **Access control** — ensure page checks CASL permissions. Redirect unauthorized users via middleware or `notFound()`. + +11. **Citation** — confirm implementation references `specs/01-Requirements/` and `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` diff --git a/.agent/rules/workflows/deploy.md b/.agent/rules/workflows/deploy.md new file mode 100644 index 0000000..4067162 --- /dev/null +++ b/.agent/rules/workflows/deploy.md @@ -0,0 +1,71 @@ +--- +description: Deploy the application via Gitea Actions to QNAP Container Station +--- + +# Deploy to Production + +Use this workflow to deploy updated backend and/or frontend to QNAP via Gitea Actions CI/CD. +Follows `specs/04-Infrastructure-OPS/` and ADR-015. + +## Pre-deployment Checklist + +- [ ] All tests pass locally (`pnpm test:watch`) +- [ ] No TypeScript errors (`tsc --noEmit`) +- [ ] No `any` types introduced +- [ ] Schema changes applied to `specs/03-Data-and-Storage/lcbp3-v1.7.0-schema.sql` +- [ ] Environment variables documented (NOT in `.env` files) + +## Steps + +1. **Commit and push to Gitea** + +```bash +git status +git add . +git commit -m "feat(): " +git push origin main +``` + +2. **Monitor Gitea Actions** — open Gitea web UI → Actions tab → verify pipeline starts + +3. **Pipeline stages (automatic)** + - `build-backend` → Docker image build + push to registry + - `build-frontend` → Docker image build + push to registry + - `deploy` → SSH to QNAP → `docker compose pull` + `docker compose up -d` + +4. **Verify backend health** + +```bash +curl http://:3000/health +# Expected: { "status": "ok" } +``` + +5. **Verify frontend** + +```bash +curl -I http://:3001 +# Expected: HTTP 200 +``` + +6. **Check logs in Grafana** — navigate to Grafana → Loki → filter by container name + - Backend: `container_name="lcbp3-backend"` + - Frontend: `container_name="lcbp3-frontend"` + +7. **Verify database** — confirm schema changes are reflected (if any) + +8. **Rollback (if needed)** + +```bash +# SSH into QNAP +docker compose pull = +docker compose up -d +``` + +## Common Issues + +| Symptom | Cause | Fix | +| ----------------- | --------------------- | ----------------------------------- | +| Backend unhealthy | DB connection failed | Check MariaDB container + env vars | +| Frontend blank | Build error | Check Next.js build logs in Grafana | +| 502 Bad Gateway | Container not started | `docker compose ps` to check status | +| Pipeline stuck | Gitea runner offline | Restart runner on QNAP | diff --git a/.agent/rules/workflows/review.md b/.agent/rules/workflows/review.md new file mode 100644 index 0000000..37fc514 --- /dev/null +++ b/.agent/rules/workflows/review.md @@ -0,0 +1,62 @@ +--- +auto_execution_mode: 0 +description: Review code changes for bugs, security issues, and improvements +--- + +You are a senior software engineer performing a thorough code review to identify potential bugs. + +Your task is to find all potential bugs and code improvements in the code changes. Focus on: + +1. Logic errors and incorrect behavior +2. Edge cases that aren't handled +3. Null/undefined reference issues +4. Race conditions or concurrency issues +5. Security vulnerabilities +6. Improper resource management or resource leaks +7. API contract violations +8. Incorrect caching behavior, including cache staleness issues, cache key-related bugs, incorrect cache invalidation, and ineffective caching +9. Violations of existing code patterns or conventions + +## 🔴 Tier 1 Critical Rules (CI Blockers) + +The following are **CI-blocking issues** that must be caught in code review. These align with project specs in `specs/05-Engineering-Guidelines/` and `specs/06-Decision-Records/`: + +### ADR-019: UUID Handling + +- **❌ NEVER use `parseInt()`, `Number()`, or `+` operator on UUID values** + - Example of violation: `parseInt(projectId)` where `projectId` is UUID string + - ✅ Correct: Use UUID string directly without conversion +- **❌ NEVER expose internal INT PK in API responses** + - API must expose only `publicId` (transformed to `id` via `@Expose()`) + - Verify DTOs have `@Exclude()` on `id: number` field + +### TypeScript Strict Rules + +- **❌ ZERO `any` types allowed** — use proper types or `unknown` + narrowing +- **❌ ZERO `console.log`** — must use NestJS `Logger` (backend) or remove (frontend) +- **❌ NO `req: any` in controllers** — use `RequestWithUser` typed interface + +### Database & Architecture + +- **❌ NO SQL Triggers for business logic** — use NestJS Service methods instead +- **❌ NO `.env` files in production** — use Docker environment variables +- **❌ NO direct table/column name invention** — verify against `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` + +### Security (ADR-016) + +- Idempotency validation for critical `POST`/`PUT`/`PATCH` endpoints +- Two-phase file upload pattern (Upload → Temp → Commit → Permanent) +- Input validation with class-validator (backend) and Zod (frontend) + +### Test Coverage Requirements + +- **Backend Services:** 80% minimum +- **Backend Overall:** 70% minimum +- **Business Logic:** 80% minimum + +Make sure to: + +1. If exploring the codebase, call multiple tools in parallel for increased efficiency. Do not spend too much time exploring. +2. If you find any pre-existing bugs in the code, you should also report those since it's important for us to maintain general code quality for the user. +3. Do NOT report issues that are speculative or low-confidence. All your conclusions should be based on a complete understanding of the codebase. +4. Remember that if you were given a specific git commit, it may not be checked out and local code states may be different. diff --git a/.agent/rules/workflows/schema-change.md b/.agent/rules/workflows/schema-change.md new file mode 100644 index 0000000..ef5afb2 --- /dev/null +++ b/.agent/rules/workflows/schema-change.md @@ -0,0 +1,108 @@ +--- +description: Manage database schema changes following ADR-009 (no migrations, modify SQL directly) +--- + +# Schema Change Workflow + +Use this workflow when modifying database schema for LCBP3-DMS. +Follows `specs/06-Decision-Records/ADR-009-database-strategy.md` — **NO TypeORM migrations**. + +## Pre-Change Checklist + +- [ ] Change is required by a spec in `specs/01-Requirements/` +- [ ] Existing data impact has been assessed +- [ ] No SQL triggers are being added (business logic in NestJS only) + +## Steps + +1. **Read current schema** — load the full schema file: + +``` +specs/03-Data-and-Storage/lcbp3-v1.7.0-schema.sql +``` + +2. **Read data dictionary** — understand current field definitions: + +``` +specs/03-Data-and-Storage/03-01-data-dictionary.md +``` + +// turbo 3. **Identify impact scope** — determine which tables, columns, indexes, or constraints are affected. List: + +- Tables being modified/created +- Columns being added/renamed/dropped +- Foreign key relationships affected +- Indexes being added/modified +- Seed data impact (if any) + +4. **Modify schema SQL** — edit `specs/03-Data-and-Storage/lcbp3-v1.7.0-schema.sql`: + - Add/modify table definitions + - Maintain consistent formatting (uppercase SQL keywords, lowercase identifiers) + - Add inline comments for new columns explaining purpose + - Ensure `DEFAULT` values and `NOT NULL` constraints are correct + - Add `version` column with `@VersionColumn()` marker comment if optimistic locking is needed + +> [!CAUTION] +> **NEVER use SQL Triggers.** All business logic must live in NestJS services. + +5. **Update data dictionary** — edit `specs/03-Data-and-Storage/03-01-data-dictionary.md`: + - Add new tables/columns with descriptions + - Update data types and constraints + - Document business rules for new fields + - Add enum value definitions if applicable + +6. **Update seed data** (if applicable): + - `specs/03-Data-and-Storage/lcbp3-v1.7.0-seed-basic.sql` — for reference/lookup data + - `specs/03-Data-and-Storage/lcbp3-v1.7.0-seed-permissions.sql` — for new CASL permissions + +7. **Update TypeORM entity** — modify corresponding `backend/src/modules//entities/*.entity.ts`: + - Map ONLY columns defined in schema SQL + - Use correct TypeORM decorators (`@Column`, `@PrimaryGeneratedColumn`, `@ManyToOne`, etc.) + - Add `@VersionColumn()` if optimistic locking is needed + +8. **Update DTOs** — if new columns are exposed via API: + - Add fields to `create-*.dto.ts` and/or `update-*.dto.ts` + - Add `class-validator` decorators for all new fields + - Never use `any` type + +// turbo 9. **Run type check** — verify no TypeScript errors: + +```bash +cd backend && npx tsc --noEmit +``` + +10. **Generate SQL diff** — create a summary of changes for the user to apply manually: + +``` +-- Schema Change Summary +-- Date: +-- Feature: +-- Tables affected: +-- +-- ⚠️ Apply this SQL to the live database manually: + +ALTER TABLE ...; +-- or +CREATE TABLE ...; +``` + +11. **Notify user** — present the SQL diff and remind them: + - Apply the SQL change to the live database manually + - Verify the change doesn't break existing data + - Run `pnpm test` after applying to confirm entity mappings work + +## Common Patterns + +| Change Type | Template | +| ----------- | -------------------------------------------------------------- | +| Add column | `ALTER TABLE \`table\` ADD COLUMN \`col\` TYPE DEFAULT value;` | +| Add table | Full `CREATE TABLE` with constraints and indexes | +| Add index | `CREATE INDEX \`idx_table_col\` ON \`table\` (\`col\`);` | +| Add FK | `ALTER TABLE \`child\` ADD CONSTRAINT ... FOREIGN KEY ...` | +| Add enum | Add to data dictionary + `ENUM('val1','val2')` in column def | + +## On Error + +- If schema SQL has syntax errors → fix and re-validate with `tsc --noEmit` +- If entity mapping doesn't match schema → compare column-by-column against SQL +- If seed data conflicts → check unique constraints and foreign keys diff --git a/.agent/rules/workflows/speckit.prepare.md b/.agent/rules/workflows/speckit.prepare.md new file mode 100644 index 0000000..d7fb5f7 --- /dev/null +++ b/.agent/rules/workflows/speckit.prepare.md @@ -0,0 +1,27 @@ +--- +description: Execute the full preparation pipeline (Specify -> Clarify -> Plan -> Tasks -> Analyze) in sequence. +--- + +# Workflow: speckit.prepare + +This workflow orchestrates the sequential execution of the Speckit preparation phase skills (02-06). + +1. **Step 1: Specify (Skill 02)** + - Goal: Create or update the `spec.md` based on user input. + - Action: Read and execute `.agents/skills/speckit.specify/SKILL.md`. + +2. **Step 2: Clarify (Skill 03)** + - Goal: Refine the `spec.md` by identifying and resolving ambiguities. + - Action: Read and execute `.agents/skills/speckit.clarify/SKILL.md`. + +3. **Step 3: Plan (Skill 04)** + - Goal: Generate `plan.md` from the finalized spec. + - Action: Read and execute `.agents/skills/speckit.plan/SKILL.md`. + +4. **Step 4: Tasks (Skill 05)** + - Goal: Generate actionable `tasks.md` from the plan. + - Action: Read and execute `.agents/skills/speckit.tasks/SKILL.md`. + +5. **Step 5: Analyze (Skill 06)** + - Goal: Validate consistency across all design artifacts (spec, plan, tasks). + - Action: Read and execute `.agents/skills/speckit.analyze/SKILL.md`. diff --git a/.agent/rules/workflows/util-speckit.checklist.md b/.agent/rules/workflows/util-speckit.checklist.md new file mode 100644 index 0000000..49aa2d9 --- /dev/null +++ b/.agent/rules/workflows/util-speckit.checklist.md @@ -0,0 +1,18 @@ +--- +description: Generate a custom checklist for the current feature based on user requirements. +--- + +# Workflow: speckit.checklist + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.checklist/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `spec.md` is missing: Run `/speckit.specify` first to create the feature specification diff --git a/.agent/rules/workflows/util-speckit.diff.md b/.agent/rules/workflows/util-speckit.diff.md new file mode 100644 index 0000000..da3dd20 --- /dev/null +++ b/.agent/rules/workflows/util-speckit.diff.md @@ -0,0 +1,19 @@ +--- +description: Compare two versions of a spec or plan to highlight changes. +--- + +# Workflow: speckit.diff + +1. **Context Analysis**: + - The user has provided an input prompt (optional file paths or version references). + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.diff/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If no files to compare: Use current feature's `spec.md` vs git HEAD + - If `spec.md` doesn't exist: Run `/speckit.specify` first diff --git a/.agent/rules/workflows/util-speckit.migrate.md b/.agent/rules/workflows/util-speckit.migrate.md new file mode 100644 index 0000000..cd2e5b4 --- /dev/null +++ b/.agent/rules/workflows/util-speckit.migrate.md @@ -0,0 +1,19 @@ +--- +description: Migrate existing projects into the speckit structure by generating spec.md, plan.md, and tasks.md from existing code. +--- + +# Workflow: speckit.migrate + +1. **Context Analysis**: + - The user has provided an input prompt (path to analyze, feature name). + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.migrate/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If path doesn't exist: Ask user to provide valid directory path + - If no code found: Report that no analyzable code was detected diff --git a/.agent/rules/workflows/util-speckit.quizme.md b/.agent/rules/workflows/util-speckit.quizme.md new file mode 100644 index 0000000..11f70af --- /dev/null +++ b/.agent/rules/workflows/util-speckit.quizme.md @@ -0,0 +1,20 @@ +--- +description: Challenge the specification with Socratic questioning to identify logical gaps, unhandled edge cases, and robustness issues. +--- + +// turbo-all + +# Workflow: speckit.quizme + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.quizme/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If required files don't exist, inform the user which prerequisite workflow to run first (e.g., `/speckit.specify` to create `spec.md`). diff --git a/.agent/rules/workflows/util-speckit.status.md b/.agent/rules/workflows/util-speckit.status.md new file mode 100644 index 0000000..b2f5089 --- /dev/null +++ b/.agent/rules/workflows/util-speckit.status.md @@ -0,0 +1,20 @@ +--- +description: Display a dashboard showing feature status, completion percentage, and blockers. +--- + +// turbo-all + +# Workflow: speckit.status + +1. **Context Analysis**: + - The user may optionally specify a feature to focus on. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.status/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If no features exist: Report "No features found. Run `/speckit.specify` to create your first feature." diff --git a/.agent/rules/workflows/util-speckit.taskstoissues.md b/.agent/rules/workflows/util-speckit.taskstoissues.md new file mode 100644 index 0000000..0cdac6e --- /dev/null +++ b/.agent/rules/workflows/util-speckit.taskstoissues.md @@ -0,0 +1,18 @@ +--- +description: Convert existing tasks into actionable, dependency-ordered GitHub issues for the feature based on available design artifacts. +--- + +# Workflow: speckit.taskstoissues + +1. **Context Analysis**: + - The user has provided an input prompt. Treat this as the primary input for the skill. + +2. **Load Skill**: + - Use the `view_file` tool to read the skill file at: `.agents/skills/speckit.taskstoissues/SKILL.md` + +3. **Execute**: + - Follow the instructions in the `SKILL.md` exactly. + - Apply the user's prompt as the input arguments/context for the skill's logic. + +4. **On Error**: + - If `tasks.md` is missing: Run `/speckit.tasks` first diff --git a/.windsurf/rules/00-project-context.md b/.windsurf/rules/00-project-context.md index 0f86471..f639ba3 100644 --- a/.windsurf/rules/00-project-context.md +++ b/.windsurf/rules/00-project-context.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # NAP-DMS Project Context @@ -25,7 +25,7 @@ Every response must be **precise**, **spec-compliant**, and **production-ready** - **Project:** NAP-DMS (LCBP3) - **Version:** 1.8.5 -- **Stack:** NestJS + Next.js + TypeScript + MariaDB +- **Stack:** NestJS + Next.js + TypeScript + MariaDB + Ollama (AI) - **Repo:** https://git.np-dms.work/np-dms/lcbp3 ## Rule Enforcement Tiers @@ -39,6 +39,7 @@ Build fails immediately if violated: - Database correctness — verify schema before writing queries - File upload security (ClamAV + whitelist) - AI validation boundary (ADR-018) +- Error handling strategy (ADR-007) - Forbidden patterns: `any`, `console.log`, UUID misuse ### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) diff --git a/.windsurf/rules/01-adr-019-uuid.md b/.windsurf/rules/01-adr-019-uuid.md index cbc3e12..d3a705a 100644 --- a/.windsurf/rules/01-adr-019-uuid.md +++ b/.windsurf/rules/01-adr-019-uuid.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # ADR-019 UUID Strategy @@ -7,7 +7,7 @@ always_on: true ## CRITICAL RULES - **NEVER** use `parseInt()` on UUID values -- **NEVER** use `Number()` on UUID values +- **NEVER** use `Number()` on UUID values - **NEVER** use `+` operator on UUID values - **ALWAYS** use `publicId` (string UUID) for API responses - **NEVER** expose internal INT `id` in API responses (use `@Exclude()`) @@ -29,7 +29,7 @@ always_on: true class Project extends UuidBaseEntity { @Column({ type: 'uuid' }) publicId: string; // UUID string, no transformation needed - + @PrimaryKey() @Exclude() id: number; // Internal INT, never exposed diff --git a/.windsurf/rules/02-security.md b/.windsurf/rules/02-security.md index 538d160..b7f5fa2 100644 --- a/.windsurf/rules/02-security.md +++ b/.windsurf/rules/02-security.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # Security Rules (Non-Negotiable) @@ -14,6 +14,10 @@ always_on: true 6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints 7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan 8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access +9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages +10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture +11. **AI Audit Trail:** Log all AI interactions and human validations +12. **Rate Limiting:** Apply to AI endpoints to prevent abuse ## Full Documentation @@ -26,4 +30,7 @@ always_on: true - [ ] No SQL injection vulnerabilities - [ ] File upload validation (whitelist + ClamAV) - [ ] Rate limiting applied to auth endpoints +- [ ] AI boundary enforcement (ADR-018) - no direct DB/storage access +- [ ] AI audit logging implemented for AI interactions +- [ ] Error handling follows ADR-007 layered classification - [ ] OWASP Top 10 review passed diff --git a/.windsurf/rules/03-typescript.md b/.windsurf/rules/03-typescript.md index b27c56e..443740f 100644 --- a/.windsurf/rules/03-typescript.md +++ b/.windsurf/rules/03-typescript.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # TypeScript Rules diff --git a/.windsurf/rules/04-domain-terminology.md b/.windsurf/rules/04-domain-terminology.md index 5cd2c6f..9e12c5a 100644 --- a/.windsurf/rules/04-domain-terminology.md +++ b/.windsurf/rules/04-domain-terminology.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # Domain Terminology diff --git a/.windsurf/rules/05-forbidden-actions.md b/.windsurf/rules/05-forbidden-actions.md index 376f0e9..1ed488a 100644 --- a/.windsurf/rules/05-forbidden-actions.md +++ b/.windsurf/rules/05-forbidden-actions.md @@ -1,26 +1,28 @@ --- -always_on: true +trigger: always_on --- # Forbidden Actions ## ❌ Never Do This -| ❌ Forbidden | ✅ Correct Approach | -| ----------------------------------------------- | --------------------------------------------- | -| SQL Triggers for business logic | NestJS Service methods | -| `.env` files in production | `docker-compose.yml` environment section | -| TypeORM migration files | Edit schema SQL directly (ADR-009) | -| Inventing table/column names | Verify against `schema-02-tables.sql` | -| `any` TypeScript type | Proper types / generics | -| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | -| `req: any` in controllers | `RequestWithUser` typed interface | -| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | -| Exposing INT PK in API responses | UUIDv7 (ADR-019) | -| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | -| Direct file operations bypassing StorageService | `StorageService` for all file moves | -| Inline email/notification sending | BullMQ queue job | -| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | +| ❌ Forbidden | ✅ Correct Approach | +| ----------------------------------------------- | ----------------------------------------------- | +| SQL Triggers for business logic | NestJS Service methods | +| `.env` files in production | `docker-compose.yml` environment section | +| TypeORM migration files | Edit schema SQL directly (ADR-009) | +| Inventing table/column names | Verify against `schema-02-tables.sql` | +| `any` TypeScript type | Proper types / generics | +| `console.log` in committed code | NestJS Logger (backend) / remove (frontend) | +| `req: any` in controllers | `RequestWithUser` typed interface | +| `parseInt()` on UUID values | Use UUID string directly (ADR-019) | +| Exposing INT PK in API responses | UUIDv7 (ADR-019) | +| AI accessing DB/storage directly | AI → DMS API → DB (ADR-018) | +| Direct file operations bypassing StorageService | `StorageService` for all file moves | +| Inline email/notification sending | BullMQ queue job | +| Deploying without Release Gates | Complete `04-08-release-management-policy.md` | +| AI direct cloud API calls | On-premises Ollama only (ADR-018) | +| AI outputs without human validation | Human-in-the-loop validation required (ADR-020) | ## Schema Changes (ADR-009) @@ -33,6 +35,7 @@ always_on: true See `01-adr-019-uuid.md` for complete UUID rules. Quick reminder: + - ❌ `parseInt(uuid)` → NEVER - ❌ `Number(uuid)` → NEVER - ✅ Use UUID string directly diff --git a/.windsurf/rules/08-development-flow.md b/.windsurf/rules/08-development-flow.md index 1433e6e..80afe6c 100644 --- a/.windsurf/rules/08-development-flow.md +++ b/.windsurf/rules/08-development-flow.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # Development Flow diff --git a/.windsurf/rules/09-commit-checklist.md b/.windsurf/rules/09-commit-checklist.md index bbd1d7b..14d4c92 100644 --- a/.windsurf/rules/09-commit-checklist.md +++ b/.windsurf/rules/09-commit-checklist.md @@ -1,5 +1,5 @@ --- -always_on: true +trigger: always_on --- # Commit Checklist diff --git a/.windsurf/rules/10-error-handling.md b/.windsurf/rules/10-error-handling.md new file mode 100644 index 0000000..3e7eb70 --- /dev/null +++ b/.windsurf/rules/10-error-handling.md @@ -0,0 +1,78 @@ +--- +trigger: always_on +--- + +# ADR-007 Error Handling Strategy + +## CRITICAL RULES + +- **ALWAYS** use layered error classification (Validation, Business, System) +- **NEVER** expose technical details to end users +- **ALWAYS** provide user-friendly error messages with recovery guidance +- **ALWAYS** log technical details for debugging +- **NEVER** use generic error messages without context + +## Error Classification + +| Error Type | Description | User Message | Technical Log | +|------------|-------------|--------------|---------------| +| **Validation** | Input validation failures | Clear field-level errors | Full validation details | +| **Business** | Business rule violations | Actionable guidance | Business context + user ID | +| **System** | Infrastructure failures | Generic "try again" | Full stack trace + metrics | + +## Backend Pattern (NestJS) + +```typescript +// Custom Exception Hierarchy +export class BusinessException extends HttpException { + constructor( + message: string, + userMessage: string, + recoveryAction?: string, + errorCode?: string + ) { + super({ message, userMessage, recoveryAction, errorCode }, 400); + } +} + +// Global Exception Filter +@Catch() +export class GlobalExceptionFilter implements ExceptionFilter { + catch(exception: unknown, host: ArgumentsHost) { + // Classify error and provide appropriate response + // Log technical details + // Return user-friendly message + } +} +``` + +## Frontend Pattern (Next.js) + +```typescript +// Error Display Component +const ErrorDisplay = ({ error, onRetry }) => { + const userMessage = error.userMessage || 'เกิดข้อผิดพลาด'; + const recoveryAction = error.recoveryAction; + + return ( +
+

{userMessage}

+ {recoveryAction &&

{recoveryAction}

} + {onRetry && } +
+ ); +}; +``` + +## Required Implementation + +- [ ] Global Exception Filter with layered classification +- [ ] Custom exception hierarchy (Validation, Business, System) +- [ ] Standardized error response DTOs +- [ ] Frontend error display components +- [ ] Error recovery mechanisms where applicable + +## Related Documents + +- `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` +- `specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md` diff --git a/.windsurf/rules/11-ai-integration.md b/.windsurf/rules/11-ai-integration.md new file mode 100644 index 0000000..fbb8c5f --- /dev/null +++ b/.windsurf/rules/11-ai-integration.md @@ -0,0 +1,100 @@ +--- +trigger: always_on +--- + +# ADR-020 AI Integration Architecture + +## CRITICAL RULES + +- **ALWAYS** follow ADR-018 AI boundary policy (isolation on Admin Desktop) +- **ALWAYS** use RFA-First approach for AI implementation +- **NEVER** allow AI direct database/storage access +- **ALWAYS** implement human-in-the-loop validation +- **NEVER** send sensitive data to cloud AI services + +## AI Integration Patterns + +### Architecture Overview + +``` +Frontend → AI Gateway API → Admin Desktop (Ollama) → Backend Validation +``` + +### Key Components + +| Component | Location | Purpose | +|-----------|----------|---------| +| **AI Gateway** | Backend (NestJS) | API endpoints, validation, audit logging | +| **Ollama Engine** | Admin Desktop (Desk-5439) | LLM inference (Gemma 4) | +| **OCR Engine** | Admin Desktop (Desk-5439) | Thai/English text extraction | +| **Orchestrator** | QNAP NAS (n8n) | Workflow management | + +## Backend Implementation (NestJS) + +```typescript +// AI Module with boundary enforcement +@Module({ + controllers: [AiController], + providers: [AiService, AiGateway], + exports: [AiService], +}) +export class AiModule { + constructor() { + // Enforce ADR-018 boundaries + } +} + +// AI Service with validation +@Injectable() +export class AiService { + async extractMetadata(documentId: string): Promise { + // 1. Validate permissions + // 2. Send to Admin Desktop AI + // 3. Validate AI response + // 4. Log audit trail + // 5. Return validated results + } +} +``` + +## Frontend Pattern (Next.js) + +```typescript +// Document Review Form (reusable component) +const DocumentReviewForm = ({ document, aiSuggestions }) => { + return ( +
+ + + + + + + + ); +}; +``` + +## Security Requirements + +- **AI Isolation:** All AI processing on Admin Desktop only +- **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 + +## Required Implementation + +- [ ] AiModule with ADR-018 boundary enforcement +- [ ] AI Gateway API endpoints with validation +- [ ] DocumentReviewForm reusable component +- [ ] Admin Desktop Ollama + PaddleOCR setup +- [ ] n8n workflow orchestration +- [ ] AI audit logging and monitoring +- [ ] Human-in-the-loop validation workflows + +## Related Documents + +- `specs/06-Decision-Records/ADR-018-ai-boundary.md` +- `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` +- `specs/06-Decision-Records/ADR-017-ollama-data-migration.md` diff --git a/.windsurfrules b/.windsurfrules index 9fb46c7..6afa499 100644 --- a/.windsurfrules +++ b/.windsurfrules @@ -1,6 +1,6 @@ # NAP-DMS Project Context & Rules - For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Amazon Q, AGENTS.md tools) -- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-03-27 +- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-04-04 - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) --- @@ -35,6 +35,7 @@ Build fails immediately if violated: - Database correctness — verify schema before writing queries - File upload security (ClamAV + whitelist) - AI validation boundary (ADR-018) +- Error handling strategy (ADR-007) - Forbidden patterns: `any`, `console.log`, UUID misuse ### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) @@ -66,7 +67,10 @@ Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > oth | **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | | **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | | **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | +| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | Error patterns & recovery | +| **ADR-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | AI isolation rules | | **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | +| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | AI architecture patterns | | **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns | | **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns | | **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | @@ -135,6 +139,8 @@ Read `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md` 6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints 7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan 8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access +9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages +10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture Full details: `specs/06-Decision-Records/ADR-016-security-authentication.md` @@ -228,6 +234,8 @@ When user asks about... check these files: | "ตรวจสอบ permission" | `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 | | "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns | +| "AI integration" | `ADR-018`, `ADR-020` | AI boundary + unified pipeline | +| "Error handling" | `ADR-007` | Layered error classification + recovery | --- @@ -240,7 +248,7 @@ When user asks about... check these files: - [ ] Code identifiers in English - [ ] Schema changes via SQL directly (not migration) - [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) -- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019) +- [ ] Relevant ADRs checked (ADR-007, ADR-009, ADR-018, ADR-019, ADR-020) - [ ] Glossary terms used correctly - [ ] Error handling complete (Logger + HttpException) - [ ] i18n keys used instead of hardcode text @@ -266,7 +274,7 @@ This file is a **quick reference**. For detailed information: | Version | Date | Changes | Updated By | | ------- | ---------- | ------------------------------------------------------------------- | -------------- | -| 1.8.5 | 2026-03-27 | Refactored — moved detailed content to specs/, now quick reference | Windsurf AI | +| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | | 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | | 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | | 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | diff --git a/AGENTS.md b/AGENTS.md index 2f0426d..a9cfbca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,7 +1,7 @@ # NAP-DMS Project Context & Rules - For: Windsurf Cascade (and compatible: Codex CLI, opencode, Amp, Antigravity, AGENTS.md tools) -- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-03-27 +- Version: 1.8.5 (Refactored) | Last synced from repo: 2026-04-04 - Repo: [https://git.np-dms.work/np-dms/lcbp3](https://git.np-dms.work/np-dms/lcbp3) --- @@ -36,6 +36,7 @@ Build fails immediately if violated: - Database correctness — verify schema before writing queries - File upload security (ClamAV + whitelist) - AI validation boundary (ADR-018) +- Error handling strategy (ADR-007) - Forbidden patterns: `any`, `console.log`, UUID misuse ### 🟡 Tier 2 — IMPORTANT (CODE REVIEW) @@ -61,21 +62,24 @@ Best practice — follow when possible: Spec priority: **`06-Decision-Records`** > **`05-Engineering-Guidelines`** > others -| Document | Path | Use When | -| ----------------------- | ----------------------------------------------------------------- | ------------------------------- | -| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | -| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | -| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | -| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | -| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | -| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns | -| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns | -| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | -| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | Commit/branch naming | -| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | Reusable patterns | -| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | Localization rules | -| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | Before deploy/hotfix | -| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | Feature completeness | +| Document | Path | Use When | +| -------------------------- | ------------------------------------------------------------------ | ------------------------------- | +| **Glossary** | `specs/00-overview/00-02-glossary.md` | Verify domain terminology | +| **Schema Tables** | `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql` | Before writing any query | +| **Data Dictionary** | `specs/03-Data-and-Storage/03-01-data-dictionary.md` | Field meanings + business rules | +| **Edge Cases** | `specs/01-Requirements/01-06-edge-cases-and-rules.md` | Prevent bugs in flows | +| **ADR-007 Error Handling** | `specs/06-Decision-Records/ADR-007-error-handling-strategy.md` | Error patterns & recovery | +| **ADR-018 AI Boundary** | `specs/06-Decision-Records/ADR-018-ai-boundary.md` | AI isolation rules | +| **ADR-019 UUID** | `specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md` | UUID-related work | +| **ADR-020 AI Integration** | `specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md` | AI architecture patterns | +| **Backend Guidelines** | `specs/05-Engineering-Guidelines/05-02-backend-guidelines.md` | NestJS patterns | +| **Frontend Guidelines** | `specs/05-Engineering-Guidelines/05-03-frontend-guidelines.md` | Next.js patterns | +| **Testing Strategy** | `specs/05-Engineering-Guidelines/05-04-testing-strategy.md` | Coverage goals | +| **Git Conventions** | `specs/05-Engineering-Guidelines/05-05-git-conventions.md` | Commit/branch naming | +| **Code Snippets** | `specs/05-Engineering-Guidelines/05-06-code-snippets.md` | Reusable patterns | +| **i18n Guidelines** | `specs/05-Engineering-Guidelines/05-08-i18n-guidelines.md` | Localization rules | +| **Release Policy** | `specs/04-Infrastructure-OPS/04-08-release-management-policy.md` | Before deploy/hotfix | +| **UAT Criteria** | `specs/01-Requirements/01-05-acceptance-criteria.md` | Feature completeness | --- @@ -136,6 +140,8 @@ Read `specs/05-Engineering-Guidelines/05-07-hybrid-uuid-implementation-plan.md` 6. **Rate Limiting:** `ThrottlerGuard` on all auth endpoints 7. **File Upload:** Whitelist PDF/DWG/DOCX/XLSX/ZIP, max 50MB, ClamAV scan 8. **AI Isolation (ADR-018):** Ollama on Admin Desktop ONLY — NO direct DB/storage access +9. **Error Handling (ADR-007):** Use layered error classification with user-friendly messages +10. **AI Integration (ADR-020):** RFA-First approach with unified pipeline architecture Full details: `specs/06-Decision-Records/ADR-016-security-authentication.md` @@ -229,6 +235,8 @@ When user asks about... check these files: | "ตรวจสอบ permission" | `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 | | "เพิ่ม test" | `05-04-testing-strategy.md` | Coverage goals + test patterns | +| "AI integration" | `ADR-018`, `ADR-020` | AI boundary + unified pipeline | +| "Error handling" | `ADR-007` | Layered error classification + recovery | --- @@ -241,7 +249,7 @@ When user asks about... check these files: - [ ] Code identifiers in English - [ ] Schema changes via SQL directly (not migration) - [ ] Test coverage meets targets (Backend 70%+, Business Logic 80%+) -- [ ] Relevant ADRs checked (ADR-009, ADR-018, ADR-019) +- [ ] Relevant ADRs checked (ADR-007, ADR-009, ADR-018, ADR-019, ADR-020) - [ ] Glossary terms used correctly - [ ] Error handling complete (Logger + HttpException) - [ ] i18n keys used instead of hardcode text @@ -265,15 +273,15 @@ This file is a **quick reference**. For detailed information: ## 🔄 Change Log -| Version | Date | Changes | Updated By | -| ------- | ---------- | ------------------------------------------------------------------- | -------------- | -| 1.8.5 | 2026-03-27 | Refactored — moved detailed content to specs/, now quick reference | Windsurf AI | -| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | -| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | -| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | -| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | -| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | -| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | +| Version | Date | Changes | Updated By | +| ------- | ---------- | ---------------------------------------------------------------------------- | -------------- | +| 1.8.5 | 2026-04-04 | Added ADR-007 error handling, ADR-020 AI integration, updated security rules | Windsurf AI | +| 1.8.4 | 2026-03-24 | Phase 5.4→✅ DONE, Tailwind 3.4.3, ADR count(16), MariaDB UUID note | Windsurf AI | +| 1.8.3 | 2026-03-21 | + Rule Enforcement Tiers (🔴🟡🟢), + Tiered Development Flow | Human Dev + AI | +| 1.8.2 | 2026-03-21 | + Context Triggers, + Code Snippets, + Error Handling, + i18n | Human Dev + AI | +| 1.8.1 | 2026-03-21 | + ADR-019 UUID patterns, + Phase 5.4 pending files | Claude Sonnet | +| 1.8.0 | 2026-03-19 | + Security overrides, + UAT criteria reference | Human Dev | +| 1.7.2 | 2026-03-15 | + AI Boundary rules (ADR-018) | Gemini Pro | --- diff --git a/frontend/components/admin/user-dialog.tsx b/frontend/components/admin/user-dialog.tsx index b08798f..1e11e57 100644 --- a/frontend/components/admin/user-dialog.tsx +++ b/frontend/components/admin/user-dialog.tsx @@ -107,7 +107,7 @@ export function UserDialog({ open, onOpenChange, user }: UserDialogProps) { lastName: user.lastName, isActive: user.isActive, lineId: user.lineId || '', - primaryOrganizationId: user.primaryOrganizationId?.toString() || ALL_ORGANIZATIONS_VALUE, + primaryOrganizationId: user.primaryOrganizationId || ALL_ORGANIZATIONS_VALUE, roleIds: user.roles?.map((r: { roleId?: number }) => r.roleId).filter((id): id is number => id !== undefined) || [], password: '', confirmPassword: '', diff --git a/frontend/components/correspondences/form.tsx b/frontend/components/correspondences/form.tsx index 4625eb0..c54b574 100644 --- a/frontend/components/correspondences/form.tsx +++ b/frontend/components/correspondences/form.tsx @@ -77,15 +77,14 @@ interface DisciplineOption { } interface InitialCorrespondenceData { - projectId?: number | string; + projectId?: string; project?: { publicId?: string }; contract?: { publicId?: string }; correspondenceTypeId?: number; - type?: { id?: number; publicId?: string }; + type?: { id?: number }; disciplineId?: number; discipline?: { id?: number; - publicId?: string; contract?: { publicId?: string }; }; revisions?: Array<{ @@ -102,11 +101,11 @@ interface InitialCorrespondenceData { receivedDate?: string; details?: { importance: 'NORMAL' | 'HIGH' | 'URGENT' }; }>; - originatorId?: number; + originatorId?: string; originator?: { publicId?: string }; recipients?: Array<{ recipientType: string; - recipientOrganizationId: number; + recipientOrganizationId?: string; recipientOrganization?: { publicId?: string }; }>; correspondenceNumber?: string; diff --git a/frontend/components/rfas/form.tsx b/frontend/components/rfas/form.tsx index 1cd6647..782fe7e 100644 --- a/frontend/components/rfas/form.tsx +++ b/frontend/components/rfas/form.tsx @@ -70,6 +70,7 @@ type RfaTypeOption = { }; type CorrespondenceTypeOption = { + id: number; // Master data INT ID publicId: string; // ADR-019: public identifier typeCode?: string; typeName?: string; @@ -272,8 +273,8 @@ export function RFAForm() { try { const res = await correspondenceService.previewNumber({ projectId: selectedProjectId, - typeId: rfaCorrespondenceType.publicId, - disciplineId, + typeId: rfaCorrespondenceType.id, + disciplineId: Number(disciplineId || 0), recipients: [{ organizationId: toOrganizationId, type: 'TO' }], subject: watch('subject') || 'Preview Subject', }); diff --git a/frontend/types/dto/correspondence/create-correspondence.dto.ts b/frontend/types/dto/correspondence/create-correspondence.dto.ts index 55ee4f9..dccf83d 100644 --- a/frontend/types/dto/correspondence/create-correspondence.dto.ts +++ b/frontend/types/dto/correspondence/create-correspondence.dto.ts @@ -1,17 +1,17 @@ // File: src/types/dto/correspondence/create-correspondence.dto.ts export interface CreateCorrespondenceDto { - /** ID or UUID ของโครงการ */ - projectId: number | string; + /** UUID ของโครงการ (ADR-019) */ + projectId: string; - /** ID ของประเภทเอกสาร (เช่น RFA, LETTER) - ADR-019: Accept UUID */ - typeId: number | string; + /** ID ของประเภทเอกสาร (เช่น RFA, LETTER) - Master data ใช้ INT */ + typeId: number; - /** [Req 6B] สาขางาน (เช่น GEN, STR) - ADR-019: Accept UUID */ - disciplineId?: number | string; + /** [Req 6B] สาขางาน (เช่น GEN, STR) - Master data ใช้ INT */ + disciplineId?: number; - /** [Req 6B] ประเภทย่อย (เช่น MAT, SHP สำหรับ Transmittal/RFA) - ADR-019: Accept UUID */ - subTypeId?: number | string; + /** [Req 6B] ประเภทย่อย (เช่น MAT, SHP สำหรับ Transmittal/RFA) - Master data ใช้ INT */ + subTypeId?: number; /** หัวข้อเอกสาร */ subject: string; @@ -44,13 +44,13 @@ export interface CreateCorrespondenceDto { isInternal?: boolean; /** * ✅ Field สำหรับ Impersonation (เลือกองค์กรผู้ส่ง) - * ใช้กรณี Admin สร้างเอกสารแทนผู้อื่น + * ใช้กรณี Admin สร้างเอกสารแทนผู้อื่น (ADR-019: UUID) */ - originatorId?: number | string; + originatorId?: string; /** Temp IDs from two-phase file upload (POST /files/upload → tempId) */ attachmentTempIds?: string[]; - /** รายชื่อผู้รับ */ - recipients?: { organizationId: number | string; type: 'TO' | 'CC' }[]; + /** รายชื่อผู้รับ (ADR-019: organizationId เป็น UUID) */ + recipients?: { organizationId: string; type: 'TO' | 'CC' }[]; } diff --git a/frontend/types/user.ts b/frontend/types/user.ts index e376937..e7f1cc6 100644 --- a/frontend/types/user.ts +++ b/frontend/types/user.ts @@ -21,7 +21,7 @@ export interface User { lastName: string; isActive: boolean; lineId?: string; - primaryOrganizationId?: number | string; // ADR-019: May be INT or UUID + primaryOrganizationId?: string; // ADR-019: UUID string only organization?: UserOrganization; roles?: Role[]; @@ -43,7 +43,7 @@ export interface CreateUserDto { password?: string; isActive: boolean; lineId?: string; - primaryOrganizationId?: number | string; // ADR-019: Accept UUID + primaryOrganizationId?: string; // ADR-019: UUID string only roleIds: number[]; } @@ -54,5 +54,5 @@ export interface SearchUserDto { limit?: number; search?: string; roleId?: number; - primaryOrganizationId?: number | string; // ADR-019: Accept UUID + primaryOrganizationId?: string; // ADR-019: UUID string only } diff --git a/specs/06-Decision-Records/ADR-001-unified-workflow-engine.md b/specs/06-Decision-Records/ADR-001-unified-workflow-engine.md index fcb95ad..3d2e66c 100644 --- a/specs/06-Decision-Records/ADR-001-unified-workflow-engine.md +++ b/specs/06-Decision-Records/ADR-001-unified-workflow-engine.md @@ -10,6 +10,20 @@ --- +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **Unified Workflow Requirements** - Section 2.1: "LCBP3-DMS ต้องรองรับเอกสารหลายประเภทพร้อม Workflow ที่แตกต่างกัน" + - เหตุผล: ระบบเดิมไม่มีกลไกส่วนกลางสำหรับจัดการ Workflow ทำให้เกิด Code Duplication +- **Software Architecture** - Section 3.2: "ระบบต้องมีความยืดหยุ่นในการเพิ่ม Document Type ใหม่" + - เหตุผล: การ Hard-code Workflow ทำให้การเพิ่มประเภทเอกสารใหม่ทำได้ยาก + +### แก้ไขความขัดแย้ง: +- **Correspondence Requirements** vs **RFA Requirements**: ทั้งสอง Module ต้องการ State Management แต่ใช้วิธีต่างกัน + - การตัดสินใจนี้ช่วยแก้ไขโดย: สร้าง Unified Engine ที่รองรับทุก Document Type + +--- + ## Context and Problem Statement LCBP3-DMS ต้องจัดการเอกสารหลายประเภท (Correspondences, RFAs, Circulations) โดยแต่ละประเภทมี Workflow การเดินเอกสารที่แตกต่างกัน: @@ -113,6 +127,74 @@ LCBP3-DMS ต้องจัดการเอกสารหลายประ --- +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Backend** | 🔴 High | ต้องสร้าง Workflow Engine Module ใหม่ และ Refactor ทุก Document Service | Implement WorkflowEngineService | +| **Database** | 🔴 High | เพิ่ม Tables: workflow_definitions, workflow_instances, workflow_histories | Create new schema | +| **Frontend** | 🟡 Medium | ต้อง Update UI สำหรับ Workflow Status และ Actions | Update components | +| **API** | 🔴 High | ต้องสร้าง Workflow API endpoints และ Update ทุก Document API | New endpoints + updates | +| **Testing** | 🟡 Medium | ต้องเขียน Tests สำหรับ Workflow Engine และ Integration Tests | New test suites | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Create Workflow Engine Module** - backend/src/modules/workflow-engine/: สร้าง Engine หลัก +- [ ] **Implement Database Schema** - specs/03-Data-and-Storage/: เพิ่ม workflow tables +- [ ] **Refactor Correspondence Service** - backend/src/modules/correspondence/: ใช้ Workflow Engine +- [ ] **Refactor RFA Service** - backend/src/modules/rfa/: ใช้ Workflow Engine +- [ ] **Refactor Circulation Service** - backend/src/modules/circulation/: ใช้ Workflow Engine + +#### 🟡 Important Changes (ควรทำภายใน 2 สัปดาห์) +- [ ] **Update Frontend Workflow Components** - frontend/components/workflow/: UI สำหรับ Workflow +- [ ] **Create Workflow API Endpoints** - backend/src/modules/workflow-engine/controller.ts: REST API +- [ ] **Add Workflow DSL Validation** - backend/src/modules/workflow-engine/dsl-validator.ts: JSON Schema validation +- [ ] **Implement Workflow History Tracking** - backend/src/modules/workflow-engine/history.service.ts: Audit trail + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Create Admin UI for Workflow Design** - frontend/app/(admin)/admin/workflow/: Visual workflow builder +- [ ] **Add Workflow Performance Monitoring** - backend/src/modules/workflow-engine/monitoring.service.ts: Metrics + +### Cross-Module Dependencies + +```mermaid +graph TB + ADR[ADR-001 Workflow Engine] --> Corr[Correspondence Service] + ADR --> RFA[RFA Service] + ADR --> Circ[Circulation Service] + ADR --> DB[(Database Schema)] + ADR --> API[Workflow API] + + Corr --> ADR002[ADR-002 Document Numbering] + RFA --> ADR002 + Circ --> ADR002 + + API --> ADR006[ADR-006 Redis Caching] + DB --> ADR009[ADR-009 Migration Strategy] +``` + +--- + +## 📋 Version Dependency Matrix + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | +|-----|---------|-----------------|---------------------|----------------------| +| **ADR-001** | 1.0 | Core | v1.8.0+ | ✅ Implemented | +| **ADR-002** | 1.0 | Required By | v1.8.0+ | ✅ Implemented | +| **ADR-006** | 1.0 | Uses | v1.8.0+ | ✅ Implemented | +| **ADR-009** | 1.0 | Database Changes | v1.8.0+ | ✅ Implemented | + +### Version Compatibility Rules + +- **Minimum Version:** v1.8.0 (ADR มีผลบังคับใช้) +- **Breaking Changes:** ไม่มี (Backward compatible API) +- **Deprecation Timeline:** ไม่มี (Core architecture) + +--- + ## Implementation Details ### Database Schema @@ -330,6 +412,26 @@ export class WorkflowEngineService { --- +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-08-24 (6 months from last review) +- **Review Type:** Scheduled (Core Principle Review) +- **Reviewers:** System Architect, Development Team Lead, Product Owner + +### Review Checklist +- [ ] ยังคงเป็น Core Principle หรือไม่? (Workflow Engine เป็นหัวใจสำคัญของระบบ) +- [ ] มีการเปลี่ยนแปลง Technology ที่กระทบหรือไม่? (New Workflow Engine alternatives) +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? (Performance bottlenecks, State inconsistencies) +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? (DSL evolution, New document types) + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-02-24 | Initial version - DSL-based Unified Workflow Engine | ✅ Active | + +--- + ## Related ADRs - [ADR-002: Document Numbering Strategy](./ADR-002-document-numbering-strategy.md) - ใช้ Workflow Engine trigger Document Number Generation diff --git a/specs/06-Decision-Records/ADR-002-document-numbering-strategy.md b/specs/06-Decision-Records/ADR-002-document-numbering-strategy.md index c6dc7e7..88ec4ae 100644 --- a/specs/06-Decision-Records/ADR-002-document-numbering-strategy.md +++ b/specs/06-Decision-Records/ADR-002-document-numbering-strategy.md @@ -10,6 +10,20 @@ --- +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **Document Numbering Requirements** - Section 3.1: "เลขที่เอกสารต้องเป็นเลขที่อัตโนมัติ ไม่ซ้ำกัน และมีความหมาย" + - เหตุผล: ระบบเดิมไม่มีกลไกสร้างเลขที่อัตโนมัติที่ปลอดภัยต่อ Race Condition +- **Acceptance Criteria** - AC-DOC-001: "เลขที่เอกสารต้องไม่ซ้ำกันแม้มีการสร้างพร้อมกันหลาย Request" + - เหตุผล: ต้องการ Mechanism ที่รับประกันความไม่ซ้ำกันในระดับ Mission-Critical + +### แก้ไขความขัดแย้ง: +- **Performance Requirements** vs **Uniqueness Requirements**: ต้องการความเร็วสูงแต่ต้องรับประกันความไม่ซ้ำกัน 100% + - การตัดสินใจนี้ช่วยแก้ไขโดย: ใช้ Double-Lock Mechanism (Redis + Database) ที่ Balance ระหว่าง Performance และ Safety + +--- + ## Context and Problem Statement LCBP3-DMS ต้องสร้างเลขที่เอกสารอัตโนมัติสำหรับ Correspondence, RFA, Transmittal และ Drawing โดยเลขที่เอกสารต้อง: @@ -116,6 +130,76 @@ LCBP3-DMS ต้องสร้างเลขที่เอกสารอั --- +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Backend** | 🔴 High | ต้องสร้าง DocumentNumberingService และ Update ทุก Document Service | Implement numbering service | +| **Database** | 🔴 High | เพิ่ม Tables: document_number_formats, document_number_counters, document_number_audit | Create new schema | +| **Redis** | 🔴 High | ต้องใช้ Redis สำหรับ Distributed Locking และ Rate Limiting | Configure Redis | +| **API** | 🟡 Medium | ต้องสร้าง Numbering API endpoints | New endpoints | +| **Testing** | 🟡 Medium | ต้องเขียน Concurrent Tests สำหรับ Race Condition | Performance tests | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Create DocumentNumberingService** - backend/src/modules/document-numbering/: สร้าง Service หลัก +- [ ] **Implement Database Schema** - specs/03-Data-and-Storage/: เพิ่ม numbering tables +- [ ] **Configure Redis for Locking** - docker-compose.yml: Redis configuration +- [ ] **Update Correspondence Service** - backend/src/modules/correspondence/: ใช้ numbering service +- [ ] **Update RFA Service** - backend/src/modules/rfa/: ใช้ numbering service + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Create Numbering API Endpoints** - backend/src/modules/document-numbering/controller.ts: REST API +- [ ] **Add Rate Limiting** - backend/src/common/guards/: Prevent abuse +- [ ] **Implement Audit Logging** - backend/src/modules/document-numbering/audit.service.ts: Track all numbers +- [ ] **Add Error Handling** - backend/src/modules/document-numbering/: Retry logic + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Create Admin UI for Numbering Config** - frontend/app/(admin)/admin/numbering/: Configuration UI +- [ ] **Add Numbering Performance Monitoring** - backend/src/modules/document-numbering/monitoring.service.ts: Metrics + +### Cross-Module Dependencies + +```mermaid +graph TB + ADR[ADR-002 Numbering] --> Corr[Correspondence Service] + ADR --> RFA[RFA Service] + ADR --> Trans[Transmittal Service] + ADR --> Draw[Drawing Service] + ADR --> DB[(Database Schema)] + ADR --> Redis[(Redis)] + + Corr --> ADR001[ADR-001 Workflow Engine] + RFA --> ADR001 + Trans --> ADR001 + Draw --> ADR001 + + Redis --> ADR006[ADR-006 Redis Caching] + DB --> ADR009[ADR-009 Migration Strategy] +``` + +--- + +## 📋 Version Dependency Matrix + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | +|-----|---------|-----------------|---------------------|----------------------| +| **ADR-002** | 1.0 | Core | v1.8.0+ | ✅ Implemented | +| **ADR-001** | 1.0 | Used By | v1.8.0+ | ✅ Implemented | +| **ADR-006** | 1.0 | Required | v1.8.0+ | ✅ Implemented | +| **ADR-009** | 1.0 | Database Changes | v1.8.0+ | ✅ Implemented | + +### Version Compatibility Rules + +- **Minimum Version:** v1.8.0 (ADR มีผลบังคับใช้) +- **Breaking Changes:** ไม่มี (Backward compatible) +- **Deprecation Timeline:** ไม่มี (Mission-critical component) + +--- + ## Implementation Details ### Database Schema @@ -925,6 +1009,26 @@ ensure: --- +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-08-24 (6 months from last review) +- **Review Type:** Scheduled (Core Principle Review) +- **Reviewers:** System Architect, Database Administrator, Development Team Lead + +### Review Checklist +- [ ] ยังคงเป็น Core Principle หรือไม่? (Document Numbering เป็น Mission-Critical) +- [ ] มีการเปลิยนแปลง Technology ที่กระทบหรือไม่? (New locking mechanisms, Redis alternatives) +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? (Race conditions, Performance issues) +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? (New numbering formats, Performance optimization) + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-02-24 | Initial version - Double-Lock Mechanism | ✅ Active | + +--- + ## Compliance เป็นไปตาม: diff --git a/specs/06-Decision-Records/ADR-003-api-design-strategy.md b/specs/06-Decision-Records/ADR-003-api-design-strategy.md new file mode 100644 index 0000000..2a35ea1 --- /dev/null +++ b/specs/06-Decision-Records/ADR-003-api-design-strategy.md @@ -0,0 +1,422 @@ +# ADR-003: API Design Strategy + +**Status:** ✅ Accepted (Implementation Ready) +**Date:** 2026-04-04 +**Decision Makers:** Development Team, System Architect +**Related Documents:** + +- [API Design & Error Handling](../02-Architecture/02-04-api-design.md) +- [Backend Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) +- [ADR-005: Technology Stack](./ADR-005-technology-stack.md) + +--- + +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **API Design & Error Handling** - Section 2: "ระบบต้องใช้ RESTful Principles และมีความสอดคล้องกัน" + - เหตุผล: ต้องการบันทึกการตัดสินใจเกี่ยวกับ API Design Patterns ที่ใช้จริงในระบบ +- **Backend Guidelines** - Section 3: "การออกแบบ API ต้องรองรับ TypeScript และ NestJS Patterns" + - เหตุผล: ต้องการทำให้ API Design สอดคล้องกับ NestJS Ecosystem + +### แก้ไขความขัดแย้ง: +- **REST Purity** vs **Pragmatic API Design**: ต้องการความสวยงามของ REST แต่ต้องรองรับ Business Logic ที่ซับซ้อน + - การตัดสินใจนี้ช่วยแก้ไขโดย: ใช้ RESTful หลักแต่เพิ่ม Pragmatic Patterns สำหรับ Workflow และ Business Operations + +--- + +## Context and Problem Statement + +LCBP3-DMS ต้องการ API Design ที่: + +1. **Consistent:** ทุก Endpoint ใช้ Patterns เดียวกัน +2. **Type-Safe:** รองรับ TypeScript และ DTO Validation +3. **Business-Ready:** รองรับ Workflow Operations และ Complex Business Logic +4. **Document-Driven:** Auto-generate Swagger Documentation +5. **Performance-Oriented:** รองรับ Pagination, Filtering, และ Caching + +### Key Challenges + +1. **Resource Naming:** การตั้งชื่อ Resources ที่สะท้อน Business Domain +2. **Complex Operations:** Workflow transitions, Document numbering ที่ไม่ใช่ CRUD ธรรมดา +3. **Response Consistency:** การคืนค่าที่สม่ำเสมอทั้ง Single และ Collection +4. **Error Handling:** การจัดการ Business Exceptions และ Validation Errors +5. **Versioning:** การเตรียมพร้อมสำหรับ API Evolution + +--- + +## Decision Drivers + +- **Developer Experience:** ง่ายต่อการใช้งานและ Debug +- **Type Safety:** ป้องกัน Runtime Errors ด้วย TypeScript +- **Business Alignment:** API สะท้อน Business Processes จริง +- **Performance:** รองรับ High-volume Operations +- **Documentation:** Auto-generated และ Up-to-date +- **Testing:** ง่ายต่อการ Unit Test และ Integration Test + +--- + +## Considered Options + +### Option 1: Pure REST with Resource Endpoints Only + +**แนวทาง:** ใช้ REST Resources เท่านั้น ไม่มี Action Endpoints + +**Pros:** + +- ✅ RESTful purity +- ✅ Simple to understand +- ✅ Standard HTTP semantics + +**Cons:** + +- ❌ Difficult for complex business operations +- ❌ Workflow transitions become awkward +- ❌ Document numbering doesn't fit resource model + +### Option 2: RPC-style with Action Endpoints + +**แนวทาง:** ใช้ Action Endpoints สำหรับทุก Business Operation + +**Pros:** + +- ✅ Clear business intent +- ✅ Easy for complex operations +- ✅ Direct mapping to use cases + +**Cons:** + +- ❌ Not RESTful +- ❌ Inconsistent patterns +- ❌ Hard to document with Swagger + +### Option 3: **Hybrid REST + Action Endpoints** ⭐ (Selected) + +**แนวทาง:** REST สำหรับ CRUD และ Action Endpoints สำหรับ Business Operations + +**Pros:** + +- ✅ **Best of Both Worlds:** REST ที่เหมาะสม + Actions ที่ชัดเจน +- ✅ **Business Clarity:** Workflow actions อยู่ใน endpoints ที่เข้าใจง่าย +- ✅ **Type Safety:** DTOs สำหรับทุก operation +- ✅ **Documentation:** Swagger สามารถ document ได้ทั้งสองแบบ +- ✅ **Consistency:** Clear naming conventions + +**Cons:** + +- ❌ Slightly more complex +- ❌ Requires developer discipline + +--- + +## Decision Outcome + +**Chosen Option:** Option 3 - Hybrid REST + Action Endpoints + +### Rationale + +เลือก Hybrid Approach เนื่องจาก: + +1. **Business Reality:** DMS มี Operations ที่ซับซ้อน (Workflow, Numbering) ที่ไม่ fit กับ pure REST +2. **Developer Experience:** Actions ชัดเจนกว่าการยัด business logic ลงใน PATCH +3. **Maintainability:** แยก concerns ระหว่าง data access และ business operations +4. **Scalability:** สามารถเพิ่ม business operations ได้โดยไม่ทำให้ REST resources ซับซ้อน + +--- + +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **API Controllers** | 🔴 High | ต้องใช้ Hybrid Pattern สำหรับทุก Module | Refactor controllers | +| **DTOs** | 🔴 High | ต้องสร้าง DTOs สำหรับทุก Endpoint | Create comprehensive DTOs | +| **Documentation** | 🟡 Medium | Swagger ต้อง cover ทั้ง REST และ Actions | Update Swagger config | +| **Frontend API Client** | 🟡 Medium | ต้องรองรับทั้งสอง pattern | Update API service calls | +| **Testing** | 🟡 Medium | ต้อง test ทั้ง resource และ action endpoints | Add integration tests | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [x] **Define API Standards** - สร้างมาตรฐานการตั้งชื่อและ patterns +- [ ] **Refactor Correspondence API** - ใช้ hybrid pattern +- [ ] **Update RFA API** - ใช้ action endpoints สำหรับ workflow +- [ ] **Create Base Controller** - shared patterns และ utilities + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Update API Documentation** - Swagger พร้อม examples +- [ ] **Create API Client Library** - frontend TypeScript client +- [ ] **Add Integration Tests** - test ทุก endpoint patterns +- [ ] **Performance Testing** - ตรวจสอบ response times + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **API Versioning Strategy** - prepare for v2 +- [ ] **OpenAPI Generator** - auto-generate clients +- [ ] **API Analytics** - track usage patterns + +--- + +## Implementation Details + +### API Design Patterns + +#### 1. Resource Endpoints (REST) + +```typescript +// Standard CRUD operations +GET /api/v1/correspondences // List with pagination +GET /api/v1/correspondences/:id // Get by UUID +POST /api/v1/correspondences // Create +PUT /api/v1/correspondences/:id // Full update +PATCH /api/v1/correspondences/:id // Partial update +DELETE /api/v1/correspondences/:id // Soft delete +``` + +#### 2. Action Endpoints (Business Operations) + +```typescript +// Workflow actions +POST /api/v1/correspondences/:id/submit +POST /api/v1/correspondences/:id/approve +POST /api/v1/correspondences/:id/reject +POST /api/v1/correspondences/:id/forward + +// Document numbering +POST /api/v1/document-numbering/reserve +POST /api/v1/document-numbering/generate + +// Bulk operations +POST /api/v1/correspondences/bulk-update +POST /api/v1/correspondences/bulk-approve + +// Reports and exports +GET /api/v1/reports/correspondence-summary +GET /api/v1/exports/correspondences/:format +``` + +### Response Format Standards + +#### Success Response (Single Resource) + +```typescript +{ + "data": { + "id": "550e8400-e29b-41d4-a716-446655440000", // UUID (ADR-019) + "documentNumber": "LCBP3-CORR-2024-0001", + "subject": "Meeting minutes", + "status": "SUBMITTED", + "createdAt": "2024-01-01T00:00:00Z", + "updatedAt": "2024-01-01T00:00:00Z" + }, + "meta": { + "timestamp": "2024-01-01T00:00:00Z", + "version": "1.0" + } +} +``` + +#### Success Response (Collection) + +```typescript +{ + "data": [ + { "id": "...", "documentNumber": "...", ... }, + { "id": "...", "documentNumber": "...", ... } + ], + "meta": { + "pagination": { + "page": 1, + "limit": 20, + "total": 100, + "totalPages": 5 + }, + "filters": { + "status": "SUBMITTED", + "dateFrom": "2024-01-01" + }, + "timestamp": "2024-01-01T00:00:00Z" + } +} +``` + +#### Action Response + +```typescript +{ + "data": { + "action": "approve", + "result": "SUCCESS", + "nextStatus": "APPROVED", + "workflow": { + "id": "wf-123", + "currentState": "APPROVED", + "previousState": "PENDING_APPROVAL" + } + }, + "meta": { + "timestamp": "2024-01-01T00:00:00Z", + "processedBy": "user-456" + } +} +``` + +### Error Response Format + +```typescript +{ + "error": { + "code": "VALIDATION_ERROR", + "message": "Validation failed on input data", + "statusCode": 400, + "timestamp": "2024-01-01T00:00:00Z", + "path": "/api/v1/correspondences", + "details": [ + { + "field": "subject", + "message": "Subject is required and must be at least 10 characters", + "value": null + } + ] + } +} +``` + +### Naming Conventions + +#### URL Paths + +- **Resources:** Plural nouns, kebab-case + - `/correspondences`, `/projects`, `/organizations` +- **Actions:** Verb-noun pattern, kebab-case + - `/correspondences/:id/submit`, `/document-numbering/generate` +- **Nested Resources:** Parent-child relationship + - `/projects/:id/contracts`, `/contracts/:id/correspondences` + +#### JSON Properties + +- **Properties:** camelCase + - `documentNumber`, `createdAt`, `primaryOrganizationId` +- **Enums:** UPPER_SNAKE_CASE + - `"SUBMITTED"`, `"IN_REVIEW"`, `"APPROVED"` +- **Booleans:** is/has prefix + - `isActive`, `hasAttachments`, `canEdit` + +### DTO Examples + +#### Create DTO + +```typescript +import { IsString, IsOptional, IsEnum, IsUUID } from 'class-validator'; + +export class CreateCorrespondenceDto { + @IsString() + @MinLength(10) + subject: string; + + @IsOptional() + @IsString() + content?: string; + + @IsEnum(['LETTER', 'RFI', 'MEMO', 'NOTICE']) + type: CorrespondenceType; + + @IsUUID() + @IsOptional() + originatorId?: string; + + @IsUUID() + projectId: string; + + @IsArray() + @IsUUID(4, { each: true }) + recipientIds: string[]; +} +``` + +#### Action DTO + +```typescript +export class ApproveCorrespondenceDto { + @IsString() + @MaxLength(1000) + comment?: string; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => AttachmentDto) + attachments?: AttachmentDto[]; +} +``` + +--- + +## Consequences + +### Positive + +1. ✅ **Business Clarity:** Actions สะท้อน business operations ชัดเจน +2. ✅ **Type Safety:** DTOs ป้องกัน runtime errors +3. ✅ **Consistency:** Standard patterns ทั่วทั้ง API +4. ✅ **Documentation:** Auto-generated Swagger ครบถ้วน +5. ✅ **Maintainability:** แยก concerns ระหว่าง data และ business logic +6. ✅ **Testing:** ง่ายต่อการ test ทุก endpoint + +### Negative + +1. ❌ **Learning Curve:** ต้องเรียนรู้ hybrid patterns +2. ❌ **Documentation Complexity:** ต้องอธิบายทั้ง REST และ Actions +3. ❌ **API Surface Area:** มี endpoints มากขึ้น + +### Mitigation Strategies + +- **Learning Curve:** Create comprehensive API guidelines and examples +- **Documentation:** Use Swagger groups and descriptions +- **API Surface:** Group related endpoints และใช้ consistent patterns + +--- + +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-10-04 (6 months from creation) +- **Review Type:** Scheduled (API Strategy Review) +- **Reviewers:** System Architect, Backend Team Lead, Frontend Team Lead + +### Review Checklist +- [ ] ยังคงตอบโจทย์ Business Requirements หรือไม่? +- [ ] มี API patterns ใหม่ที่ควรพิจารณาหรือไม่? +- [ ] มีปัญหา Performance หรือ Usability หรือไม่? +- [ ] ต้องการ Update หรือ Deprecate patterns ใดหรือไม่? + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-04-04 | Initial version - Hybrid REST + Action Strategy | ✅ Accepted | + +--- + +## Compliance + +เป็นไปตาม: + +- [API Design & Error Handling](../02-Architecture/02-04-api-design.md) +- [Backend Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) +- [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) + +--- + +## Related ADRs + +- [ADR-005: Technology Stack](./ADR-005-technology-stack.md) - NestJS framework choice +- [ADR-010: Logging & Monitoring](./ADR-010-logging-monitoring-strategy.md) - API request logging +- [ADR-016: Security Authentication](./ADR-016-security-authentication.md) - API security + +--- + +## References + +- [NestJS Documentation](https://docs.nestjs.com/) +- [OpenAPI Specification](https://swagger.io/specification/) +- [REST API Design Best Practices](https://restfulapi.net/) diff --git a/specs/06-Decision-Records/ADR-004-database-schema-design-strategy.md b/specs/06-Decision-Records/ADR-004-database-schema-design-strategy.md new file mode 100644 index 0000000..8b33a22 --- /dev/null +++ b/specs/06-Decision-Records/ADR-004-database-schema-design-strategy.md @@ -0,0 +1,483 @@ +# ADR-004: Database Schema Design Strategy + +**Status:** ✅ Accepted (Implementation Ready) +**Date:** 2026-04-04 +**Decision Makers:** Development Team, System Architect, Database Administrator +**Related Documents:** + +- [Database Schema Tables](../03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql) +- [Data Dictionary](../03-Data-and-Storage/03-01-data-dictionary.md) +- [ADR-009: Database Migration Strategy](./ADR-009-database-migration-strategy.md) +- [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) + +--- + +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **Database Schema Tables** - Section 1: "ตารางต้องมีโครงสร้างที่สอดคล้องกันและรองรับ Business Logic" + - เหตุผล: ต้องการบันทึกการตัดสินใจเกี่ยวกับ Schema Patterns ที่ใช้จริง +- **Data Dictionary** - Section 2: "การตั้งชื่อคอลัมน์และความสัมพันธ์ต้องสอดคล้องกัน" + - เหตุผล: ต้องการทำให้ naming conventions เป็นมาตรฐานเดียวกัน + +### แก้ไขความขัดแย้ง: +- **Normalization** vs **Performance**: ต้องการ Database Normalization แต่ต้องรักษา Performance สำหรับ DMS + - การตัดสินใจนี้ช่วยแก้ไขโดย: ใช้ selective denormalization และ strategic indexing + +--- + +## Context and Problem Statement + +LCBP3-DMS ต้องการ Database Schema Design ที่: + +1. **Consistent:** ทุกตารางใช้ Patterns เดียวกัน +2. **Scalable:** รองรับข้อมูลจำนวนมากและ Complex Queries +3. **Maintainable:** ง่ายต่อการ Modify และ Debug +4. **Performance:** รองรับ High-volume Operations พร้อม Concurrent Access +5. **Audit-Ready:** รองรับ Audit Trail และ Compliance + +### Key Challenges + +1. **Identifier Strategy:** การใช้ทั้ง INT PK และ UUID (ADR-019) +2. **Soft Delete:** การจัดการการลบข้อมูลแบบ Soft Delete +3. **Audit Trail:** การติดตามการเปลี่ยนแปลงข้อมูล +4. **Workflow State:** การจัดการ State Machines ใน Database +5. **Document Relationships:** การจัดการ Complex Many-to-Many Relationships + +--- + +## Decision Drivers + +- **Data Integrity:** ป้องกัน Data Corruption และ Inconsistencies +- **Performance:** Query Response Times < 200ms (p90) +- **Scalability:** รองรับ 100+ concurrent users +- **Maintainability:** ง่ายต่อการ Add/Modify Columns +- **Auditability:** Complete audit trail สำหรับ Compliance +- **Migration Safety:** ง่ายต่อการ Schema Evolution + +--- + +## Considered Options + +### Option 1: Highly Normalized (3NF+) + +**แนวทาง:** Strict normalization ทุกตาราง + +**Pros:** + +- ✅ Data integrity สูงสุด +- ✅ Minimal data duplication +- ✅ Theoretical correctness + +**Cons:** + +- ❌ Complex queries มากขึ้น +- ❌ Performance impact จาก JOINs +- ❌ ยากต่อการ maintain ในระยะยาว + +### Option 2: Denormalized for Performance + +**แนวทาง:** Duplicate data สำหรับ performance + +**Pros:** + +- ✅ Fast queries (fewer JOINs) +- ✅ Simple read operations +- ✅ Good for reporting + +**Cons:** + +- ❌ Data synchronization complexity +- ❌ Higher storage requirements +- ❌ Risk of inconsistencies + +### Option 3: **Selective Normalization with Strategic Patterns** ⭐ (Selected) + +**แนวทาง:** Normalize ที่สำคัญ แต่ denormalize ที่จำเป็น พร้อม Standard Patterns + +**Pros:** + +- ✅ **Balance Performance & Integrity:** Optimize สำหรับ use case จริง +- ✅ **Consistent Patterns:** Standard conventions ทั่วทั้ง schema +- ✅ **Audit Trail Built-in:** Soft delete + tracking tables +- ✅ **Migration Ready:** ง่ายต่อการ evolve schema +- ✅ **Workflow Support:** Native state management + +**Cons:** + +- ❌ Requires architectural discipline +- ❌ More complex initial design + +--- + +## Decision Outcome + +**Chosen Option:** Option 3 - Selective Normalization with Strategic Patterns + +### Rationale + +เลือก Selective Normalization เนื่องจาก: + +1. **Business Reality:** DMS มี both transactional และ reporting needs +2. **Performance Requirements:** ต้องการ fast reads สำหรับ list views แต่ maintain integrity สำหรับ transactions +3. **Maintainability:** Standard patterns ลดความซับซ้อนในระยะยาว +4. **Audit Requirements:** Built-in audit trail จำเป็นสำหรับ document management + +--- + +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Database Schema** | 🔴 High | ทุกตารางต้องใช้ standard patterns | Refactor all tables | +| **TypeORM Entities** | 🔴 High | Entity classes ต้อง映射 schema patterns | Update entity definitions | +| **Migration Scripts** | 🔴 High | ต้องมี migration สำหรับ pattern changes | Create migration strategy | +| **Queries & Services** | 🟡 Medium | ต้อง optimize queries สำหรับ new patterns | Update service queries | +| **Performance Testing** | 🟡 Medium | ต้อง validate performance ของ patterns | Load testing | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Define Schema Standards** - สร้างมาตรฐานการออกแบบตาราง +- [ ] **Implement Base Entity Pattern** - สำหรับ common fields +- [ ] **Update Core Tables** - ใช้ standard patterns +- [ ] **Create Audit Trail Tables** - สำหรับ tracking + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Optimize Indexes** - สำหรับ performance +- [ ] **Create Migration Scripts** - สำหรับ evolution +- [ ] **Update TypeORM Entities** - reflect new patterns +- [ ] **Performance Testing** - validate improvements + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Database Documentation** - auto-generate from schema +- [ ] **Performance Monitoring** - query analysis tools +- [ ] **Schema Validation** - automated checks + +--- + +## Implementation Details + +### Schema Design Patterns + +#### 1. Base Table Pattern + +ทุกตารางต้องมี base columns ต่อไปนี้: + +```sql +CREATE TABLE example_table ( + -- Primary Keys (ADR-019) + id INT PRIMARY KEY AUTO_INCREMENT COMMENT 'Internal PK - never exposed', + uuid UUID NOT NULL DEFAULT UUID() COMMENT 'Public UUID (ADR-019)', + + -- Business Columns + name VARCHAR(255) NOT NULL, + -- ... other business columns + + -- Standard Metadata + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'Record creation time', + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Last update time', + created_by INT NULL COMMENT 'User who created record', + updated_by INT NULL COMMENT 'User who last updated record', + deleted_at DATETIME NULL COMMENT 'Soft delete timestamp', + + -- Indexes + UNIQUE INDEX idx_example_uuid (uuid), + INDEX idx_example_created_at (created_at), + INDEX idx_example_deleted_at (deleted_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +``` + +#### 2. Naming Conventions + +**Table Names:** + +- **Plural snake_case:** `organizations`, `correspondences`, `workflow_instances` +- **Join Tables:** `table1_table2` (e.g., `correspondence_recipients`) +- **Lookup Tables:** Prefix with type: `correspondence_types`, `organization_roles` + +**Column Names:** + +- **Primary Keys:** `id` (INT), `uuid` (UUID) +- **Foreign Keys:** `{table}_id` (e.g., `organization_id`, `project_id`) +- **Boolean Columns:** `is_` prefix: `is_active`, `is_deleted` +- **Timestamp Columns:** `_at` suffix: `created_at`, `updated_at`, `deleted_at` +- **User References:** `_by` suffix: `created_by`, `updated_by` + +#### 3. Relationship Patterns + +**One-to-Many:** + +```sql +-- Projects have many Contracts +CREATE TABLE contracts ( + id INT PRIMARY KEY AUTO_INCREMENT, + uuid UUID NOT NULL DEFAULT UUID(), + project_id INT NOT NULL, + -- ... other columns + FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE +); +``` + +**Many-to-Many:** + +```sql +-- Correspondences have many Recipients +CREATE TABLE correspondence_recipients ( + id INT PRIMARY KEY AUTO_INCREMENT, + correspondence_id INT NOT NULL, + user_id INT NOT NULL, + recipient_type ENUM('TO', 'CC', 'BCC') NOT NULL, + received_at TIMESTAMP NULL, + -- Metadata + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (correspondence_id) REFERENCES correspondences(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + UNIQUE KEY unique_correspondence_recipient (correspondence_id, user_id) +); +``` + +#### 4. Workflow State Pattern + +```sql +-- Workflow States +CREATE TABLE workflow_states ( + id INT PRIMARY KEY AUTO_INCREMENT, + workflow_code VARCHAR(50) NOT NULL, + state_name VARCHAR(50) NOT NULL, + is_initial BOOLEAN DEFAULT FALSE, + is_terminal BOOLEAN DEFAULT FALSE, + allowed_transitions JSON NULL, -- Array of next states + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY unique_workflow_state (workflow_code, state_name) +); + +-- Workflow Instances +CREATE TABLE workflow_instances ( + id INT PRIMARY KEY AUTO_INCREMENT, + uuid UUID NOT NULL DEFAULT UUID(), + workflow_code VARCHAR(50) NOT NULL, + entity_type VARCHAR(50) NOT NULL, -- 'correspondence', 'rfa', etc. + entity_id INT NOT NULL, + current_state VARCHAR(50) NOT NULL, + status ENUM('ACTIVE', 'COMPLETED', 'CANCELLED') DEFAULT 'ACTIVE', + context JSON NULL, + -- Metadata + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + FOREIGN KEY (workflow_code, current_state) REFERENCES workflow_states(workflow_code, state_name) +); +``` + +#### 5. Audit Trail Pattern + +```sql +-- Generic Audit Trail +CREATE TABLE audit_logs ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + table_name VARCHAR(50) NOT NULL, + record_id INT NOT NULL, + record_uuid UUID NULL, + action ENUM('CREATE', 'UPDATE', 'DELETE', 'SOFT_DELETE') NOT NULL, + old_values JSON NULL, + new_values JSON NULL, + changed_fields JSON NULL, -- Array of changed field names + user_id INT NULL, + ip_address VARCHAR(45) NULL, + user_agent TEXT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + INDEX idx_audit_table_record (table_name, record_id), + INDEX idx_audit_user (user_id, created_at), + INDEX idx_audit_created (created_at) +); + +-- Document-specific History (for critical tables) +CREATE TABLE correspondence_histories ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + correspondence_id INT NOT NULL, + revision_number INT NOT NULL, + changes JSON NOT NULL, -- Full snapshot or delta + changed_by INT NULL, + change_reason VARCHAR(255) NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + FOREIGN KEY (correspondence_id) REFERENCES correspondences(id) ON DELETE CASCADE, + UNIQUE KEY unique_correspondence_revision (correspondence_id, revision_number) +); +``` + +#### 6. Master Data Pattern + +```sql +-- Reference Data Tables +CREATE TABLE correspondence_types ( + id INT PRIMARY KEY AUTO_INCREMENT, + type_code VARCHAR(20) NOT NULL UNIQUE, -- LETTER, RFI, MEMO + type_name VARCHAR(100) NOT NULL, + description TEXT NULL, + display_order INT DEFAULT 0, + is_active BOOLEAN DEFAULT TRUE, + -- Metadata + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP +) COMMENT='Master data: Correspondence types'; +``` + +### TypeORM Entity Patterns + +#### Base Entity + +```typescript +import { CreateDateColumn, UpdateDateColumn, DeleteDateColumn } from 'typeorm'; +import { UuidBaseEntity } from './uuid-base.entity'; + +export abstract class BaseEntity extends UuidBaseEntity { + @CreateDateColumn({ type: 'timestamp' }) + createdAt: Date; + + @UpdateDateColumn({ type: 'timestamp' }) + updatedAt: Date; + + @DeleteDateColumn({ type: 'datetime', nullable: true }) + deletedAt?: Date; + + @Column({ type: 'int', nullable: true }) + createdBy?: number; + + @Column({ type: 'int', nullable: true }) + updatedBy?: number; +} +``` + +#### Entity Example + +```typescript +@Entity('correspondences') +export class Correspondence extends BaseEntity { + @Column({ type: 'varchar', length: 50 }) + documentNumber: string; + + @Column({ type: 'varchar', length: 255 }) + subject: string; + + @Column({ type: 'text', nullable: true }) + content?: string; + + @ManyToOne(() => CorrespondenceType) + @JoinColumn({ name: 'correspondence_type_id' }) + type: CorrespondenceType; + + @ManyToOne(() => Organization) + @JoinColumn({ name: 'originator_id' }) + originator: Organization; + + @OneToMany(() => CorrespondenceRecipient, recipient => recipient.correspondence) + recipients: CorrespondenceRecipient[]; +} +``` + +### Indexing Strategy + +#### Primary Indexes + +```sql +-- UUID for public access +CREATE UNIQUE INDEX idx_table_uuid ON table_name (uuid); + +-- Performance indexes +CREATE INDEX idx_table_created_at ON table_name (created_at); +CREATE INDEX idx_table_updated_at ON table_name (updated_at); +CREATE INDEX idx_table_deleted_at ON table_name (deleted_at); +``` + +#### Foreign Key Indexes + +```sql +-- All foreign keys should be indexed +CREATE INDEX idx_correspondence_project_id ON correspondences (project_id); +CREATE INDEX idx_correspondence_originator_id ON correspondences (originator_id); +CREATE INDEX idx_correspondence_type_id ON correspondences (correspondence_type_id); +``` + +#### Query-Specific Indexes + +```sql +-- Composite indexes for common queries +CREATE INDEX idx_correspondences_project_status ON correspondences (project_id, status, deleted_at); +CREATE INDEX idx_correspondences_date_range ON correspondences (created_at, deleted_at) WHERE deleted_at IS NULL; +``` + +--- + +## Consequences + +### Positive + +1. ✅ **Consistency:** Standard patterns ทั่วทั้ง database +2. ✅ **Performance:** Strategic indexing และ selective denormalization +3. ✅ **Audit Trail:** Complete tracking สำหรับ compliance +4. ✅ **Maintainability:** Clear naming conventions และ patterns +5. ✅ **Migration Safety:** Evolution-friendly schema design +6. ✅ **Type Safety:** TypeORM entities ที่สอดคล้องกับ schema + +### Negative + +1. ❌ **Initial Complexity:** ต้องเรียนรู้ patterns และ conventions +2. ❌ **Storage Overhead:** Audit tables ใช้พื้นที่เพิ่ม +3. ❌ **Development Overhead:** ต้อง maintain patterns อย่างสม่ำเสมอ + +### Mitigation Strategies + +- **Complexity:** Comprehensive documentation และ examples +- **Storage:** Partition audit tables และ implement retention policies +- **Development:** Code generation สำหรับ boilerplate entities + +--- + +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-10-04 (6 months from creation) +- **Review Type:** Scheduled (Schema Strategy Review) +- **Reviewers:** System Architect, DBA, Backend Team Lead + +### Review Checklist +- [ ] ยังคงตอบโจทย์ Performance Requirements หรือไม่? +- [ ] มี schema patterns ใหม่ที่ควรพิจารณาหรือไม่? +- [ ] มีปัญหา Storage หรือ Performance หรือไม่? +- [ ] ต้องการ Update หรือ Deprecate patterns ใดหรือไม่? + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-04-04 | Initial version - Selective Normalization Strategy | ✅ Accepted | + +--- + +## Compliance + +เป็นไปตาม: + +- [Database Schema Tables](../03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql) +- [Data Dictionary](../03-Data-and-Storage/03-01-data-dictionary.md) +- [ADR-009: Database Migration Strategy](./ADR-009-database-migration-strategy.md) +- [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) + +--- + +## Related ADRs + +- [ADR-009: Database Migration Strategy](./ADR-009-database-migration-strategy.md) - Schema evolution +- [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) - UUID usage +- [ADR-001: Unified Workflow Engine](./ADR-001-unified-workflow-engine.md) - Workflow state management + +--- + +## References + +- [MariaDB Documentation](https://mariadb.com/kb/en/) +- [TypeORM Documentation](https://typeorm.io/) +- [Database Design Best Practices](https://www.databasestar.com/) diff --git a/specs/06-Decision-Records/ADR-005-technology-stack.md b/specs/06-Decision-Records/ADR-005-technology-stack.md index 0a7350e..dcf4c0e 100644 --- a/specs/06-Decision-Records/ADR-005-technology-stack.md +++ b/specs/06-Decision-Records/ADR-005-technology-stack.md @@ -1,15 +1,29 @@ # ADR-005: Technology Stack Selection -**Status:** Accept +**Status:** Accepted **Date:** 2026-02-24 **Decision Makers:** Development Team, CTO **Related Documents:** -- [System Architecture](../02-architecture/02-01-system-architecture.md) +- [System Architecture](../02-Architecture/02-01-system-architecture.md) - [FullStack JS Guidelines](../03-implementation/03-01-fullftack-js-v1.7.0.md) --- +## Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **System Architecture** - Section 4.1: "ระบบต้องพัฒนาด้วย Technology Stack ที่ทีมมีความเชี่ยวชาญ" + - เหตุผล: ทีมมีประสบการณ์ TypeScript/JavaScript จึงเลือก Stack ที่ใช้ภาษาเดียวกัน +- **Infrastructure Constraints** - Section 5.2: "ระบบต้อง Deploy บน QNAP Container Station" + - เหตุผล: ต้องเลือก Technology ที่เข้ากับ QNAP และ Resource จำกัด + +### แก้ไขความขัดแย้ง: +- **Development Speed** vs **Enterprise Requirements**: ต้องการพัฒนาเร็วแต่ต้องเป็น Enterprise-grade + - การตัดสินใจนี้ช่วยแก้ไขโดย: เลือก TypeScript ecosystem ที่ Modern แต่ก็ Enterprise-ready + +--- + ## Context and Problem Statement LCBP3-DMS ต้องเลือก Technology Stack สำหรับพัฒนา Document Management System ที่: @@ -130,6 +144,77 @@ LCBP3-DMS ต้องเลือก Technology Stack สำหรับพั --- +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Development Environment** | 🔴 High | ต้องติดตั้ง Node.js, TypeScript, Docker | Setup dev environment | +| **CI/CD Pipeline** | 🔴 High | ต้องสร้าง Pipeline สำหรับ TypeScript, Docker | Build/deploy automation | +| **Team Skills** | 🟡 Medium | ทีมต้องเรียนรู้ NestJS, Next.js | Training sessions | +| **Infrastructure** | 🟡 Medium | ต้องติดตั้ง Docker, Redis, MariaDB | Server setup | +| **Documentation** | 🟡 Medium | ต้องเขียน Docs สำหรับ TypeScript ecosystem | Update documentation | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Setup Development Environment** - All developers: Node.js, Docker, IDE setup +- [ ] **Create Project Structure** - backend/, frontend/, docker-compose.yml: Initial scaffolding +- [ ] **Configure TypeScript** - tsconfig.json, package.json: Build configuration +- [ ] **Setup CI/CD** - .github/workflows/: Build and deploy automation +- [ ] **Install Database** - MariaDB, Redis: Infrastructure setup + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Create Code Standards** - .eslintrc, .prettierrc: Linting and formatting +- [ ] **Setup Testing Framework** - Jest, Vitest, Playwright: Test infrastructure +- [ ] **Documentation Setup** - README.md, CONTRIBUTING.md: Project docs +- [ ] **Team Training** - NestJS, Next.js workshops: Knowledge transfer + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Create Component Library** - shadcn/ui customization: UI consistency +- [ ] **Setup Monitoring** - Logging, metrics: Observability +- [ ] **Performance Benchmarking** - Load testing scripts: Performance validation + +### Cross-Module Dependencies + +```mermaid +graph TB + ADR[ADR-005 Tech Stack] --> Backend[NestJS Backend] + ADR --> Frontend[Next.js Frontend] + ADR --> DB[(MariaDB)] + ADR --> Redis[(Redis)] + ADR --> Docker[Docker] + + Backend --> ADR001[ADR-001 Workflow Engine] + Backend --> ADR002[ADR-002 Numbering] + Frontend --> ADR011[ADR-011 App Router] + Frontend --> ADR012[ADR-012 UI Components] + + Redis --> ADR006[ADR-006 Redis Strategy] + DB --> ADR009[ADR-009 Migration] +``` + +--- + +## 📋 Version Dependency Matrix + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | +|-----|---------|-----------------|---------------------|----------------------| +| **ADR-005** | 1.0 | Foundation | v1.8.0+ | ✅ Implemented | +| **ADR-001** | 1.0 | Depends On | v1.8.0+ | ✅ Implemented | +| **ADR-002** | 1.0 | Depends On | v1.8.0+ | ✅ Implemented | +| **ADR-006** | 1.0 | Required | v1.8.0+ | ✅ Implemented | +| **ADR-009** | 1.0 | Database | v1.8.0+ | ✅ Implemented | + +### Version Compatibility Rules + +- **Minimum Version:** v1.8.0 (ADR มีผลบังคับใช้) +- **Breaking Changes:** ไม่มี (Foundation stack) +- **Deprecation Timeline:** ไม่มี (Core technology choices) + +--- + ## Architecture Decisions ### Backend Architecture: Modular Monolith @@ -268,6 +353,26 @@ lcbp3-dms/ --- +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-08-24 (6 months from last review) +- **Review Type:** Scheduled (Foundation Review) +- **Reviewers:** CTO, System Architect, Development Team Lead + +### Review Checklist +- [ ] ยังคงเป็น Core Principle หรือไม่? (Technology Stack เป็นรากฐานของระบบ) +- [ ] มีการเปลี่ยนแปลง Technology ที่กระทบหรือไม่? (New frameworks, EOL versions) +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? (Performance issues, Compatibility problems) +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? (Version upgrades, New alternatives) + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-02-24 | Initial version - Full Stack TypeScript | ✅ Active | + +--- + ## Compliance เป็นไปตาม: diff --git a/specs/06-Decision-Records/ADR-006-redis-caching-strategy.md b/specs/06-Decision-Records/ADR-006-redis-caching-strategy.md index 68a084a..4ee74c2 100644 --- a/specs/06-Decision-Records/ADR-006-redis-caching-strategy.md +++ b/specs/06-Decision-Records/ADR-006-redis-caching-strategy.md @@ -10,6 +10,20 @@ --- +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **Non-Functional Rules** - Section 4.2: "ระบบต้องตอบสนอง Performance ได้ < 200ms (p90)" + - เหตุผล: Database queries ช้า ต้องใช้ Cache ในการเพิ่ม Performance +- **Software Architecture** - Section 5.3: "ระบบต้องรองรับ Concurrent Access พร้อม Locking Mechanism" + - เหตุผล: ต้องการ Distributed Lock สำหรับ Document Numbering และ Race Conditions + +### แก้ไขความขัดแย้ง: +- **Performance Requirements** vs **Data Consistency**: ต้องการความเร็วสูงแต่ต้องรักษาความสม่ำเสมอของข้อมูล + - การตัดสินใจนี้ช่วยแก้ไขโดย: ใช้ Redis พร้อม Cache Invalidation Strategy ที่ชัดเจน + +--- + ## Context and Problem Statement LCBP3-DMS ต้องการ High Performance ในการ: @@ -90,6 +104,75 @@ LCBP3-DMS ต้องการ High Performance ในการ: --- +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Backend Services** | 🔴 High | ทุก Service ต้องใช้ Redis สำหรับ Cache และ Locking | Implement Redis clients | +| **Authentication** | 🔴 High | Session Management และ Permission Caching | Update Auth service | +| **Document Numbering** | 🔴 High | Distributed Locking สำหรับ Race Condition | Integrate Redlock | +| **Infrastructure** | 🔴 High | ต้องติดตั้ง Redis Server และ Monitoring | Redis setup | +| **API Performance** | 🟡 Medium | Response time ลดลง < 200ms | Performance optimization | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Install Redis Server** - docker-compose.yml: Redis 7 configuration +- [ ] **Create Redis Service** - backend/src/common/redis/: Redis connection management +- [ ] **Update Auth Service** - backend/src/modules/auth/: Session caching +- [ ] **Update Numbering Service** - backend/src/modules/document-numbering/: Distributed locks +- [ ] **Add Permission Caching** - backend/src/modules/permissions/: Cache user abilities + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Create Cache Invalidation Service** - backend/src/common/cache/: Cache management +- [ ] **Add Rate Limiting** - backend/src/common/guards/: Redis-based rate limiter +- [ ] **Setup BullMQ Queues** - backend/src/common/queues/: Background job processing +- [ ] **Add Redis Monitoring** - backend/src/common/monitoring/: Metrics and alerts + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Create Redis Admin UI** - frontend/app/(admin)/admin/redis/: Cache management UI +- [ ] **Add Performance Dashboard** - Grafana dashboards: Redis metrics visualization +- [ ] **Implement Cache Warming** - Scripts: Pre-populate cache + +### Cross-Module Dependencies + +```mermaid +graph TB + ADR[ADR-006 Redis Strategy] --> Auth[Auth Service] + ADR --> Numbering[Numbering Service] + ADR --> Permissions[Permission Service] + ADR --> API[All APIs] + ADR --> Redis[(Redis Server)] + + Numbering --> ADR002[ADR-002 Numbering] + Auth --> ADR016[ADR-016 Security] + API --> ADR001[ADR-001 Workflow] + + Redis --> ADR005[ADR-005 Tech Stack] + Redis --> ADR015[ADR-015 Deployment] +``` + +--- + +## 📋 Version Dependency Matrix + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | +|-----|---------|-----------------|---------------------|----------------------| +| **ADR-006** | 1.0 | Infrastructure | v1.8.0+ | ✅ Implemented | +| **ADR-002** | 1.0 | Required By | v1.8.0+ | ✅ Implemented | +| **ADR-016** | 1.0 | Used By | v1.8.0+ | ✅ Implemented | +| **ADR-005** | 1.0 | Component | v1.8.0+ | ✅ Implemented | + +### Version Compatibility Rules + +- **Minimum Version:** v1.8.0 (ADR มีผลบังคับใช้) +- **Breaking Changes:** ไม่มี (Infrastructure component) +- **Deprecation Timeline:** ไม่มี (Core infrastructure) + +--- + ## Redis Usage Patterns ### 1. Distributed Locking (Redlock) @@ -409,6 +492,26 @@ export class RedisMonitoringService { --- +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-08-24 (6 months from last review) +- **Review Type:** Scheduled (Infrastructure Review) +- **Reviewers:** System Architect, DevOps Engineer, Development Team Lead + +### Review Checklist +- [ ] ยังคงเป็น Core Principle หรือไม่? (Redis เป็น Infrastructure หลัก) +- [ ] มีการเปลี่ยนแปลง Technology ที่กระทบหรือไม่? (New caching solutions, Redis alternatives) +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? (Cache invalidation issues, Performance problems) +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? (Redis version upgrades, New patterns) + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-02-24 | Initial version - Redis Distributed Cache + Lock | ✅ Active | + +--- + ## Compliance เป็นไปตาม: diff --git a/specs/06-Decision-Records/ADR-007-error-handling-strategy.md b/specs/06-Decision-Records/ADR-007-error-handling-strategy.md new file mode 100644 index 0000000..b1fd77e --- /dev/null +++ b/specs/06-Decision-Records/ADR-007-error-handling-strategy.md @@ -0,0 +1,650 @@ +# ADR-007: Error Handling & Recovery Strategy + +**Status:** ✅ Accepted (Implementation Ready) +**Date:** 2026-04-04 +**Decision Makers:** Development Team, System Architect +**Related Documents:** + +- [API Design & Error Handling](../02-Architecture/02-04-api-design.md) +- [ADR-010: Logging & Monitoring Strategy](./ADR-010-logging-monitoring-strategy.md) +- [Backend Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) + +--- + +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **API Design & Error Handling** - Section 6: "ระบบต้องมี Global Exception Filter และ Custom Business Exceptions" + - เหตุผล: ต้องการบันทึกการตัดสินใจเกี่ยวกับ Error Handling Patterns ที่ใช้จริง +- **Backend Guidelines** - Section 4: "การจัดการ Errors ต้องสอดคล้องกันและมีความหมายต่อ User" + - เหตุผล: ต้องการทำให้ Error Messages และ Recovery Patterns เป็นมาตรฐาน + +### แก้ไขความขัดแย้ง: +- **Technical Details** vs **User Experience**: ต้องการ log technical errors แต่แสดง user-friendly messages + - การตัดสินใจนี้ช่วยแก้ไขโดย: แยก technical logging และ user-facing error messages + +--- + +## Context and Problem Statement + +LCBP3-DMS ต้องการ Error Handling Strategy ที่: + +1. **Consistent:** ทุก Error ใช้ Formats และ Patterns เดียวกัน +2. **User-Friendly:** Error messages เข้าใจง่ายสำหรับ non-technical users +3. **Debuggable:** Technical details สำหรับ developers และ ops +4. **Recoverable:** 用户提供 recovery options เมื่อเป็นไปได้ +5. **Secure:** ไม่เปิดเผย sensitive information ใน error responses + +### Key Challenges + +1. **Error Classification:** การจำแนกประเภท errors (validation, business, system) +2. **Message Localization:** รองรับภาษาไทยและอังกฤษ +3. **Recovery Guidance:** แนะนำ users ว่าควรทำอย่างไรต่อ +4. **Cross-Module Consistency:** Errors จาก modules ต่างกันต้องสอดคล้อง +5. **Performance Impact:** Error handling ไม่ควส่งผลกระทบ performance + +--- + +## Decision Drivers + +- **User Experience:** Errors ไม่ควสร้างความสับสนหรือความกลัว +- **Debuggability:** Developers สามารถหา root cause ได้เร็ว +- **Security:** ไม่เปิดเผย internal details สู่ users +- **Maintainability:** ง่ายต่อการ add new error types +- **Compliance:** Audit trail สำหรับ errors และ recovery actions +- **Performance:** Error handling ไม่ควส่งผลกระทบ response times + +--- + +## Considered Options + +### Option 1: HTTP Status Codes Only + +**แนวทาง:** ใช้เพียง HTTP status codes และ generic messages + +**Pros:** + +- ✅ Simple implementation +- ✅ Standard HTTP semantics +- ✅ Low overhead + +**Cons:** + +- ❌ Limited error information +- ❌ Poor user experience +- ❌ Difficult debugging +- ❌ No recovery guidance + +### Option 2: Custom Error Objects with Details + +**แนวทาง:** สร้าง custom error objects พร้อม detailed information + +**Pros:** + +- ✅ Rich error information +- ✅ Better debugging +- ✅ Recovery guidance possible + +**Cons:** + +- ❌ More complex implementation +- ❌ Risk of information leakage +- ❌ Larger response sizes + +### Option 3: **Layered Error Handling with Classification** ⭐ (Selected) + +**แนวทาง:** Classify errors และ provide appropriate detail levels + +**Pros:** + +- ✅ **Balanced Approach:** User-friendly + technical details +- ✅ **Security:** Control information exposure by error type +- ✅ **Recovery Focus:** Actionable error messages +- ✅ **Consistency:** Standard patterns across modules +- ✅ **Localization Ready:** Support for multiple languages + +**Cons:** + +- ❌ Requires error classification discipline +- ❌ More initial setup + +--- + +## Decision Outcome + +**Chosen Option:** Option 3 - Layered Error Handling with Classification + +### Rationale + +เลือก Layered Approach เนื่องจาก: + +1. **User-Centric:** Error messages ที่เข้าใจง่ายและมีประโยชน์ +2. **Developer-Friendly:** Technical details สำหรับ debugging +3. **Security:** Controlled information exposure +4. **Scalability:** ง่ายต่อการ add new error types +5. **Compliance:** Audit trail สำหรับ error tracking + +--- + +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Global Exception Filter** | 🔴 High | Centralized error processing | Implement layered filter | +| **Custom Exceptions** | 🔴 High | Business-specific error types | Create exception hierarchy | +| **Error DTOs** | 🔴 High | Standardized error responses | Define response schemas | +| **Frontend Error Handling** | 🟡 Medium | Parse and display errors appropriately | Update error UI components | +| **Logging Strategy** | 🟡 Medium | Log appropriate detail levels | Integrate with ADR-010 | +| **Documentation** | 🟡 Medium | Error catalog and handling guide | Create error reference | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **Create Exception Hierarchy** - base classes และ specific types +- [ ] **Implement Global Filter** - layered error processing +- [ ] **Define Error DTOs** - standardized response format +- [ ] **Update All Controllers** - use new exception types + +#### 🟡 Important Changes (ควรทำภายใน 1 สัปดาห์) +- [ ] **Create Error Catalog** - all possible errors และ recovery actions +- [ ] **Update Frontend Error Handling** - parse and display appropriately +- [ ] **Add Error Logging** - integrate with logging strategy +- [ ] **Create Error Tests** - unit and integration tests + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **Error Analytics** - track error rates and patterns +- [ ] **Error Recovery UI** - guided recovery flows +- [ ] **Error Localization** - Thai/English message support + +--- + +## Implementation Details + +### Error Classification System + +#### Error Types + +```typescript +export enum ErrorType { + // User Errors (400 range) + VALIDATION = 'VALIDATION', + BUSINESS_RULE = 'BUSINESS_RULE', + PERMISSION_DENIED = 'PERMISSION_DENIED', + NOT_FOUND = 'NOT_FOUND', + CONFLICT = 'CONFLICT', + + // System Errors (500 range) + INTERNAL_ERROR = 'INTERNAL_ERROR', + DATABASE_ERROR = 'DATABASE_ERROR', + EXTERNAL_SERVICE = 'EXTERNAL_SERVICE', + INFRASTRUCTURE = 'INFRASTRUCTURE' +} + +export enum ErrorSeverity { + LOW = 'LOW', // User mistake, easy recovery + MEDIUM = 'MEDIUM', // Business rule violation, needs action + HIGH = 'HIGH', // System issue, may need support + CRITICAL = 'CRITICAL' // System failure, immediate attention +} +``` + +#### Exception Hierarchy + +```typescript +// Base Exception +export abstract class BaseException extends HttpException { + constructor( + public readonly type: ErrorType, + public readonly code: string, + public readonly message: string, + public readonly userMessage?: string, + public readonly severity: ErrorSeverity = ErrorSeverity.MEDIUM, + public readonly details?: any, + public readonly recoveryActions?: string[] + ) { + super( + { + error: { + type, + code, + message: userMessage || message, + severity, + timestamp: new Date().toISOString(), + ...(recoveryActions && { recoveryActions }), + ...(process.env.NODE_ENV === 'development' && { + technicalMessage: message, + details + }) + } + }, + getStatusCode(type) + ); + } +} + +// Validation Errors +export class ValidationException extends BaseException { + constructor(message: string, details?: ValidationErrorDetail[]) { + super( + ErrorType.VALIDATION, + 'VALIDATION_ERROR', + message, + 'ข้อมูลที่กรอกไม่ถูกต้อง กรุณาตรวจสอบและลองใหม่', + ErrorSeverity.LOW, + details, + ['ตรวจสอบข้อมูลที่กรอก', 'แก้ไขข้อมูลที่ผิดพลาด', 'ลองใหม่อีกครั้ง'] + ); + } +} + +// Business Rule Errors +export class BusinessException extends BaseException { + constructor(code: string, message: string, userMessage?: string, recoveryActions?: string[]) { + super( + ErrorType.BUSINESS_RULE, + code, + message, + userMessage || 'ไม่สามารถดำเนินการได้เนื่องจากเงื่อนไขทางธุรกิจ', + ErrorSeverity.MEDIUM, + undefined, + recoveryActions || ['ติดต่อผู้ดูแลระบบ', 'ตรวจสอบเงื่อนไขการดำเนินการ'] + ); + } +} + +// Permission Errors +export class PermissionException extends BaseException { + constructor(resource: string, action: string) { + super( + ErrorType.PERMISSION_DENIED, + 'PERMISSION_DENIED', + `User lacks permission for ${action} on ${resource}`, + `คุณไม่มีสิทธิ์${action} ${resource}`, + ErrorSeverity.MEDIUM, + { resource, action }, + ['ติดต่อผู้ดูแลระบบเพื่อขอสิทธิ์', 'ลองใช้บัญชีที่มีสิทธิ์'] + ); + } +} + +// System Errors +export class SystemException extends BaseException { + constructor(message: string, details?: any) { + super( + ErrorType.INTERNAL_ERROR, + 'INTERNAL_ERROR', + message, + 'เกิดข้อผิดพลาดในระบบ กรุณาลองใหม่ภายหลัง', + ErrorSeverity.HIGH, + details, + ['ลองใหม่อีกครั้ง', 'ติดต่อผู้ดูแลระบบหากยังไม่ได้'] + ); + } +} +``` + +### Global Exception Filter + +```typescript +@Injectable() +export class GlobalExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(GlobalExceptionFilter.name); + + catch(exception: unknown, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + let errorResponse: any; + + if (exception instanceof BaseException) { + // Handle our custom exceptions + errorResponse = exception.getResponse(); + this.logError(exception, request, false); + } else if (exception instanceof HttpException) { + // Handle NestJS HTTP exceptions + const status = exception.getStatus(); + const exceptionResponse = exception.getResponse(); + + errorResponse = { + error: { + type: this.getErrorType(status), + code: 'HTTP_ERROR', + message: this.getUserMessage(status), + severity: ErrorSeverity.MEDIUM, + timestamp: new Date().toISOString(), + ...(process.env.NODE_ENV === 'development' && { + technicalMessage: exception.message, + details: exceptionResponse + }) + } + }; + this.logError(exception, request, false); + } else { + // Handle unexpected errors + errorResponse = { + error: { + type: ErrorType.INTERNAL_ERROR, + code: 'UNEXPECTED_ERROR', + message: 'เกิดข้อผิดพลาดที่ไม่คาดคิด กรุณาลองใหม่ภายหลัง', + severity: ErrorSeverity.CRITICAL, + timestamp: new Date().toISOString() + } + }; + this.logError(exception, request, true); + } + + response.status(errorResponse.error.statusCode || 500).json(errorResponse); + } + + private logError(exception: any, request: Request, isCritical: boolean) { + const logData = { + path: request.url, + method: request.method, + userId: request.user?.id, + ip: request.ip, + userAgent: request.headers['user-agent'], + body: request.body, + exception: { + name: exception.name, + message: exception.message, + stack: exception.stack, + details: exception.details + } + }; + + if (isCritical || exception.severity === ErrorSeverity.CRITICAL) { + this.logger.error('Critical error occurred', logData); + } else { + this.logger.warn('Error occurred', logData); + } + } + + private getErrorType(status: number): ErrorType { + if (status === 400) return ErrorType.VALIDATION; + if (status === 401) return ErrorType.PERMISSION_DENIED; + if (status === 403) return ErrorType.PERMISSION_DENIED; + if (status === 404) return ErrorType.NOT_FOUND; + if (status === 409) return ErrorType.CONFLICT; + return ErrorType.INTERNAL_ERROR; + } + + private getUserMessage(status: number): string { + switch (status) { + case 400: return 'ข้อมูลที่ส่งมาไม่ถูกต้อง'; + case 401: return 'กรุณาเข้าสู่ระบบก่อนใช้งาน'; + case 403: return 'คุณไม่มีสิทธิ์ในการดำเนินการนี้'; + case 404: return 'ไม่พบข้อมูลที่ร้องขอ'; + case 409: return 'ข้อมูลซ้ำกันหรือมีความขัดแย้ง'; + default: return 'เกิดข้อผิดพลาดในระบบ'; + } + } +} +``` + +### Service Layer Error Handling + +```typescript +@Injectable() +export class CorrespondenceService { + constructor( + @InjectRepository(Correspondence) + private correspondenceRepo: Repository, + private logger: Logger + ) {} + + async create(createDto: CreateCorrespondenceDto, userId: number): Promise { + try { + // Business validation + if (createDto.originatorId && !await this.canUserCreateForOrganization(userId, createDto.originatorId)) { + throw new PermissionException('correspondence', 'create for organization'); + } + + // Check for duplicate document number + if (await this.isDuplicateDocumentNumber(createDto.documentNumber)) { + throw new BusinessException( + 'DUPLICATE_DOCUMENT_NUMBER', + `Document number ${createDto.documentNumber} already exists`, + 'เลขที่เอกสารนี้มีอยู่แล้ว กรุณาใช้เลขที่อื่น', + ['ตรวจสอบเลขที่เอกสารล่าสุด', 'ขอเลขที่เอกสารใหม่'] + ); + } + + // Create correspondence + const correspondence = this.correspondenceRepo.create({ + ...createDto, + createdBy: userId, + createdAt: new Date() + }); + + const saved = await this.correspondenceRepo.save(correspondence); + + this.logger.log(`Correspondence created: ${saved.id}`); + return saved; + + } catch (error) { + if (error instanceof BaseException) { + throw error; // Re-throw our custom exceptions + } + + // Handle database errors + if (error.code === 'ER_DUP_ENTRY') { + throw new BusinessException( + 'DUPLICATE_ENTRY', + 'Database constraint violation', + 'ข้อมูลซ้ำกันในระบบ กรุณาตรวจสอบ' + ); + } + + // Handle unexpected errors + this.logger.error('Unexpected error in CorrespondenceService.create', error); + throw new SystemException('Failed to create correspondence', error); + } + } + + async findOne(uuid: string, userId: number): Promise { + const correspondence = await this.correspondenceRepo.findOne({ + where: { uuid, deletedAt: IsNull() }, + relations: ['type', 'originator', 'recipients'] + }); + + if (!correspondence) { + throw new BusinessException( + 'CORRESPONDENCE_NOT_FOUND', + `Correspondence with UUID ${uuid} not found`, + 'ไม่พบเอกสารที่ค้นหา', + ['ตรวจสอบ UUID ที่ระบุ', 'ค้นหาเอกสารจากรายการ'] + ); + } + + // Check permission + if (!await this.canUserView(correspondence, userId)) { + throw new PermissionException('correspondence', 'view'); + } + + return correspondence; + } +} +``` + +### Frontend Error Handling + +```typescript +// Error response type +interface ErrorResponse { + error: { + type: string; + code: string; + message: string; + severity: string; + timestamp: string; + recoveryActions?: string[]; + technicalMessage?: string; + details?: any; + }; +} + +// Error handler component +export function ErrorDisplay({ error, onRetry }: { error: ErrorResponse; onRetry?: () => void }) { + const getSeverityColor = (severity: string) => { + switch (severity) { + case 'LOW': return 'text-yellow-600'; + case 'MEDIUM': return 'text-orange-600'; + case 'HIGH': return 'text-red-600'; + case 'CRITICAL': return 'text-red-800'; + default: return 'text-gray-600'; + } + }; + + return ( +
+
+
+ +
+
+

+ {error.error.message} +

+ + {error.error.recoveryActions && ( +
+

วิธีแก้ไข:

+
    + {error.error.recoveryActions.map((action, index) => ( +
  • {action}
  • + ))} +
+
+ )} + +
+ {onRetry && ( + + )} + +
+
+
+
+ ); +} + +// API service error handling +export class ApiService { + async request(config: AxiosRequestConfig): Promise { + try { + const response = await axios.request(config); + return response.data; + } catch (error) { + if (axios.isAxiosError(error) && error.response) { + const errorData = error.response.data as ErrorResponse; + throw errorData; // Re-throw structured error + } + throw { + error: { + type: 'INTERNAL_ERROR', + code: 'NETWORK_ERROR', + message: 'ไม่สามารถเชื่อมต่อกับเซิร์ฟเวอร์ได้', + severity: 'HIGH', + timestamp: new Date().toISOString(), + recoveryActions: ['ตรวจสอบการเชื่อมต่ออินเทอร์เน็ต', 'ลองใหม่ภายหลัง'] + } + }; + } + } +} +``` + +### Error Catalog + +| Error Code | Type | User Message | Recovery Actions | Severity | +|------------|------|--------------|------------------|----------| +| `VALIDATION_ERROR` | Validation | ข้อมูลที่กรอกไม่ถูกต้อง | ตรวจสอบข้อมูล, แก้ไข, ลองใหม่ | LOW | +| `DUPLICATE_DOCUMENT_NUMBER` | Business | เลขที่เอกสารซ้ำกัน | ตรวจสอบเลขล่าสุด, ขอเลขใหม่ | MEDIUM | +| `CORRESPONDENCE_NOT_FOUND` | Business | ไม่พบเอกสาร | ตรวจสอบ UUID, ค้นหาใหม่ | MEDIUM | +| `PERMISSION_DENIED` | Permission | ไม่มีสิทธิ์ดำเนินการ | ติดต่อ admin, ใช้บัญชีอื่น | MEDIUM | +| `WORKFLOW_INVALID_TRANSITION` | Business | ไม่สามารถดำเนินการได้ในสถานะปัจจุบัน | ตรวจสอบ workflow, ดำเนินการอื่น | MEDIUM | +| `INTERNAL_ERROR` | System | เกิดข้อผิดพลาดในระบบ | ลองใหม่, ติดต่อ admin | HIGH | +| `DATABASE_ERROR` | System | ฐานข้อมูลมีปัญหา | ลองใหม่ภายหลัง, แจ้ง admin | HIGH | +| `EXTERNAL_SERVICE` | System | บริการภายนอกมีปัญหา | ลองใหม่ภายหลัง | MEDIUM | + +--- + +## Consequences + +### Positive + +1. ✅ **User Experience:** Clear, actionable error messages +2. ✅ **Debuggability:** Technical details available when needed +3. ✅ **Consistency:** Standard error handling across all modules +4. ✅ **Security:** Controlled information exposure +5. ✅ **Recovery:** Users know what to do when errors occur +6. ✅ **Maintainability:** Easy to add new error types + +### Negative + +1. ❌ **Initial Complexity:** ต้อง setup exception hierarchy +2. ❌ **Development Overhead:** ต้องคิด error messages และ recovery actions +3. ❌ **Response Size:** Error responses ใหญ่ขึ้นเล็กน้อย + +### Mitigation Strategies + +- **Complexity:** Provide comprehensive templates and examples +- **Development Overhead:** Create error catalog and guidelines +- **Response Size:** Optimize and compress where needed + +--- + +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** 2026-10-04 (6 months from creation) +- **Review Type:** Scheduled (Error Strategy Review) +- **Reviewers:** System Architect, Backend Team Lead, Frontend Team Lead + +### Review Checklist +- [ ] Error messages ยังเข้าใจง่ายสำหรับ users หรือไม่? +- [ ] Recovery actions ยังมีประสิทธิภาพหรือไม่? +- [ ] มี error patterns ใหม่ที่ควรเพิ่มหรือไม่? +- [ ] ต้องการ update หรือ deprecate error types ใดหรือไม่? + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | 2026-04-04 | Initial version - Layered Error Handling Strategy | ✅ Accepted | + +--- + +## Compliance + +เป็นไปตาม: + +- [API Design & Error Handling](../02-Architecture/02-04-api-design.md) +- [ADR-010: Logging & Monitoring Strategy](./ADR-010-logging-monitoring-strategy.md) +- [Backend Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) + +--- + +## Related ADRs + +- [ADR-010: Logging & Monitoring Strategy](./ADR-010-logging-monitoring-strategy.md) - Error logging +- [ADR-003: API Design Strategy](./ADR-003-api-design-strategy.md) - Error response format +- [ADR-016: Security Authentication](./ADR-016-security-authentication.md) - Permission errors + +--- + +## References + +- [NestJS Exception Filters](https://docs.nestjs.com/exception-filters) +- [HTTP Status Codes](https://httpstatuses.com/) +- [Error Handling Best Practices](https://martinfowler.com/articles/error-handling-patterns.html) diff --git a/specs/06-Decision-Records/ADR-008-email-notification-strategy.md b/specs/06-Decision-Records/ADR-008-email-notification-strategy.md index 700b10b..4bec211 100644 --- a/specs/06-Decision-Records/ADR-008-email-notification-strategy.md +++ b/specs/06-Decision-Records/ADR-008-email-notification-strategy.md @@ -4,6 +4,63 @@ **Date:** 2026-02-24 **Decision Makers:** Backend Team, System Architect **Related Documents:** [Backend Guidelines](../03-implementation/03-02-backend-guidelines.md), [TASK-BE-011](../06-tasks/README.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Multi-Channel Notifications** | [Product Vision](../00-overview/00-03-product-vision.md) - Communication Requirements | BullMQ + Redis for Email, LINE, In-app | +| **Performance Optimization** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-PERF-001 | Async queue prevents API blocking | +| **Reliability & Retry** | [Business Rules](../01-Requirements/01-02-business-rules/01-02-03-ui-ux-rules.md) - User Experience | BullMQ retry mechanism with exponential backoff | +| **Template Management** | [Engineering Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) - Maintainability | Handlebars templates with Git versioning | +| **User Preferences** | [Edge Cases](../01-Requirements/01-06-edge-cases-and-rules.md) - User settings | Configurable notification channels | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Sync vs Async sending (Performance vs. Simplicity) +- **Resolution:** Chose BullMQ for reliability and performance +- **Trade-off:** Redis dependency vs. Robust notification system + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Notification Service** | Core notification logic | 🔴 Critical | +| **Email Queue** | BullMQ queue setup | 🔴 Critical | +| **Email Processor** | Queue worker implementation | 🔴 Critical | +| **LINE Notify Queue** | LINE notification handling | 🟡 Important | +| **Email Templates** | Handlebars template files | 🟡 Important | +| **Workflow Integration** | Event → notification triggers | 🟡 Important | +| **Redis Infrastructure** | Queue storage and management | 🔴 Critical | +| **User Preferences** | Notification settings UI | 🟢 Guidelines | +| **Monitoring Dashboard** | Bull Board for job monitoring | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Backend (NestJS) +- [x] Setup BullMQ module with Redis connection +- [x] Create NotificationService with queue management +- [x] Implement EmailProcessor with Handlebars templates +- [x] Add LINE Notify processor +- [x] Integrate with workflow events +- [x] Add retry logic and error handling +- [x] Setup job monitoring (Bull Board) + +#### Infrastructure +- [x] Configure Redis for queue persistence +- [x] Setup SMTP credentials +- [x] Create email template directory structure +- [x] Configure LINE Notify API access --- @@ -387,6 +444,35 @@ async notifyWorkflowTransition( --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Notification channel requirements changes + - Queue performance issues + - New notification providers (LINE Notify v2, etc.) + +### Review Checklist +- [ ] Queue performance metrics acceptable +- [ ] Email delivery rates within SLA +- [ ] Template system still meets requirements +- [ ] Redis capacity and performance adequate +- [ ] Cross-document dependencies still valid +- [ ] New notification channels to consider +- [ ] Security of notification data maintained + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-008 v1.0 | Base BullMQ + Redis setup | ✅ Complete | +| v1.9.0+ | ADR-008 v1.1 | Review queue performance and channels | 📋 Planned | +| v2.0.0+ | ADR-008 v2.0 | Consider new notification patterns | 📋 Future | + +--- + ## Related ADRs - [ADR-006: Redis Caching Strategy](./ADR-006-redis-caching-strategy.md) - ใช้ Redis สำหรับ Queue @@ -402,5 +488,16 @@ async notifyWorkflowTransition( --- -**Last Updated:** 2025-12-01 -**Next Review:** 2025-06-01 +**Document Version:** v1.0 +**Last Updated:** 2026-02-24 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with notification strategy | Backend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-009-database-migration-strategy.md b/specs/06-Decision-Records/ADR-009-database-migration-strategy.md index 8614083..3ec7af1 100644 --- a/specs/06-Decision-Records/ADR-009-database-migration-strategy.md +++ b/specs/06-Decision-Records/ADR-009-database-migration-strategy.md @@ -4,6 +4,65 @@ **Date:** 2026-02-24 **Decision Makers:** Backend Team, DevOps Team, System Architect **Related Documents:** [TASK-BE-001](../06-tasks/TASK-BE-015-schema-v160-migration.md), [ADR-005: Technology Stack](./ADR-005-technology-stack.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Schema Evolution** | [Product Vision](../00-overview/00-03-product-vision.md) - Data Integrity | TypeORM migrations with version control | +| **Zero-Downtime Deployment** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-DEPLOY-001 | Blue-Green deployment strategy | +| **Data Safety** | [Business Rules](../01-Requirements/01-02-business-rules/01-02-02-doc-numbering-rules.md) - Document numbering | Rollback mechanism with backups | +| **Team Collaboration** | [Engineering Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) - Team workflows | Git-based migration collaboration | +| **Auditability** | [Infrastructure OPS](../04-Infrastructure-OPS/04-04-deployment-guide.md) - Deployment tracking | Migration tracking table and CI/CD integration | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Simplicity vs. Safety (Synchronize vs. TypeORM Migrations) +- **Resolution:** Chose TypeORM Migrations for production safety +- **Trade-off:** Additional discipline required vs. Data protection + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Database Config** | TypeORM configuration with migrations | 🔴 Critical | +| **Migration Files** | Version-controlled schema changes | 🔴 Critical | +| **CI/CD Pipeline** | Automated migration execution | 🔴 Critical | +| **Deployment Scripts** | Blue-Green deployment logic | 🔴 Critical | +| **Database Backup** | Pre-migration backup strategy | 🔴 Critical | +| **Migration Testing** | Test suite for migrations | 🟡 Important | +| **Documentation** | Migration best practices guide | 🟢 Guidelines | +| **Monitoring** | Migration execution monitoring | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Backend (NestJS) +- [x] Configure TypeORM with migrations disabled +- [x] Create migration workflow scripts +- [x] Setup migration testing framework +- [x] Implement migration rollback procedures +- [x] Add migration health checks + +#### DevOps/Infrastructure +- [x] Create database backup automation +- [x] Setup Blue-Green deployment pipeline +- [x] Configure migration execution in CI/CD +- [x] Add migration monitoring and alerts + +#### Team Processes +- [x] Define migration review checklist +- [x] Document migration conflict resolution +- [x] Create migration approval workflow --- @@ -349,6 +408,35 @@ describe('Migrations', () => { --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Complex schema changes requiring breaking migrations + - Database performance issues + - New TypeORM version compatibility + +### Review Checklist +- [ ] Migration process still meeting safety requirements +- [ ] Zero-downtime strategy effective +- [ ] Rollback procedures tested and working +- [ ] Team collaboration workflow smooth +- [ ] Cross-document dependencies still valid +- [ ] New database technologies or patterns to consider +- [ ] Migration execution time within acceptable limits + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-009 v1.0 | Base TypeORM migration setup | ✅ Complete | +| v1.9.0+ | ADR-009 v1.1 | Review migration performance and tools | 📋 Planned | +| v2.0.0+ | ADR-009 v2.0 | Consider new database patterns | 📋 Future | + +--- + ## Related ADRs - [ADR-005: Technology Stack](./ADR-005-technology-stack.md) - เลือกใช้ TypeORM @@ -364,5 +452,16 @@ describe('Migrations', () => { --- -**Last Updated:** 2025-12-01 -**Next Review:** 2025-06-01 +**Document Version:** v1.0 +**Last Updated:** 2026-02-24 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with migration strategy | Backend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md b/specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md index 68e837e..2998038 100644 --- a/specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md +++ b/specs/06-Decision-Records/ADR-010-logging-monitoring-strategy.md @@ -4,6 +4,68 @@ **Date:** 2026-02-24 **Decision Makers:** Backend Team, DevOps Team **Related Documents:** [Backend Guidelines](../03-implementation/03-02-backend-guidelines.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Structured Logging** | [Product Vision](../00-overview/00-03-product-vision.md) - Operations Requirements | Winston with JSON format for searchability | +| **Performance Monitoring** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-PERF-002 | Request logging and performance interceptors | +| **Error Tracking** | [Business Rules](../01-Requirements/01-02-business-rules/01-02-03-ui-ux-rules.md) - User Experience | Global exception filter with context | +| **Audit Trail** | [Security ADR-016](./ADR-016-security-authentication.md) - Security events | Structured audit logging for compliance | +| **Scalability** | [Architecture](../02-architecture/02-02-software-architecture.md) - Performance | Phase 2 ELK Stack for centralized logging | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Cost vs. Features (Winston vs. Full ELK Stack) +- **Resolution:** Phased approach - Winston now, ELK later +- **Trade-off:** Manual log search initially vs. Future centralized dashboard + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัำ | +|-----------|----------|-----------| +| **Logger Configuration** | Winston setup with transports | 🔴 Critical | +| **NestJS Integration** | Custom logger service | 🔴 Critical | +| **Request Middleware** | HTTP request logging | 🟡 Important | +| **Exception Filter** | Global error logging | 🔴 Critical | +| **Performance Interceptor** | Slow request detection | 🟡 Important | +| **Database Logging** | Query performance tracking | 🟡 Important | +| **Log Rotation** | File management strategy | 🟡 Important | +| **Docker Logging** | Container log configuration | 🟢 Guidelines | +| **Future ELK Stack** | Phase 2 centralized logging | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Backend (NestJS) +- [x] Configure Winston with multiple transports +- [x] Create custom NestJS logger service +- [x] Implement request logging middleware +- [x] Add global exception filter +- [x] Create performance interceptor +- [x] Configure database query logging +- [x] Setup log rotation policies + +#### Infrastructure +- [x] Configure Docker logging driver +- [x] Setup log volume persistence +- [x] Create log monitoring alerts +- [x] Plan ELK Stack architecture (Phase 2) + +#### Development Process +- [x] Define logging standards and best practices +- [x] Create logging guidelines documentation +- [x] Setup log analysis procedures --- @@ -435,6 +497,35 @@ logger.add( --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Log volume exceeds capacity + - Performance issues requiring deeper monitoring + - ELK Stack implementation (Phase 2) + +### Review Checklist +- [ ] Logging strategy still meeting observability needs +- [ ] Log storage and rotation policies effective +- [ ] Performance monitoring providing adequate insights +- [ ] Error tracking and alerting working properly +- [ ] Cross-document dependencies still valid +- [ ] New logging technologies or patterns to consider +- [ ] ELK Stack implementation timeline and requirements + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-010 v1.0 | Base Winston logging setup | ✅ Complete | +| v1.9.0+ | ADR-010 v1.1 | Review logging performance and ELK readiness | 📋 Planned | +| v2.0.0+ | ADR-010 v2.0 | Implement ELK Stack (Phase 2) | 📋 Future | + +--- + ## Related ADRs - [ADR-007: API Design & Error Handling](./ADR-007-api-design-error-handling.md) @@ -450,5 +541,16 @@ logger.add( --- -**Last Updated:** 2025-12-01 -**Next Review:** 2025-06-01 +**Document Version:** v1.0 +**Last Updated:** 2026-02-24 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with logging strategy | Backend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-011-nextjs-app-router.md b/specs/06-Decision-Records/ADR-011-nextjs-app-router.md index 10a4942..0a275ea 100644 --- a/specs/06-Decision-Records/ADR-011-nextjs-app-router.md +++ b/specs/06-Decision-Records/ADR-011-nextjs-app-router.md @@ -4,6 +4,68 @@ **Date:** 2025-12-01 **Decision Makers:** Frontend Team, System Architect **Related Documents:** [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md), [ADR-005: Technology Stack](./ADR-005-technology-stack.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Modern Architecture** | [Product Vision](../00-overview/00-03-product-vision.md) - Technology Requirements | App Router with Server Components | +| **Performance Optimization** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-PERF-003 | Server Components reduce bundle size | +| **Layout Management** | [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) - Architecture | Built-in nested layout system | +| **Future-Proofing** | [Engineering Guidelines](../05-Engineering-Guidelines/05-01-fullstack-js-guidelines.md) - Technology choices | Next.js recommended approach | +| **Code Organization** | [Architecture](../02-architecture/02-02-software-architecture.md) - Frontend structure | Route groups and file-based routing | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Familiarity vs. Modern approach (Pages Router vs. App Router) +- **Resolution:** Chose App Router for future-proofing and performance +- **Trade-off:** Learning curve vs. Better performance and DX + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **App Structure** | Complete folder reorganization | 🔴 Critical | +| **Routing Logic** | File-based routing with groups | 🔴 Critical | +| **Layout System** | Nested layouts with auth | 🔴 Critical | +| **Data Fetching** | Server vs Client components | 🔴 Critical | +| **State Management** | Integration with App Router | 🟡 Important | +| **Form Handling** | Server Actions integration | 🟡 Important | +| **Authentication** | Server-side auth checks | 🟡 Important | +| **Component Library** | Server Component compatibility | 🟡 Important | +| **Development Workflow** | New patterns and conventions | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Frontend (Next.js) +- [x] Restructure app/ directory with route groups +- [x] Implement root and nested layouts +- [x] Convert pages to Server Components where appropriate +- [x] Add 'use client' directives to interactive components +- [x] Implement Server Actions for form handling +- [x] Add loading and error boundary components +- [x] Update authentication to server-side checks + +#### Development Process +- [x] Train team on Server Components +- [x] Document App Router patterns +- [x] Update code review guidelines +- [x] Create migration guide from Pages Router + +#### Integration +- [x] Update state management for App Router +- [x] Ensure UI library compatibility +- [x] Test form handling with Server Actions --- @@ -381,6 +443,35 @@ export default function Error({ --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major Next.js version upgrade + - Performance issues with current implementation + - New App Router features or patterns + - Server Components ecosystem maturity + +### Review Checklist +- [ ] App Router implementation meeting performance goals +- [ ] Server/Client component separation effective +- [ ] Layout system working as expected +- [ ] Team adoption and productivity satisfactory +- [ ] Cross-document dependencies still valid +- [ ] New Next.js features to adopt +- [ ] Bundle size and performance metrics acceptable + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-011 v1.0 | Base App Router implementation | ✅ Complete | +| v1.9.0+ | ADR-011 v1.1 | Review performance and adoption | 📋 Planned | +| v2.0.0+ | ADR-011 v2.0 | Consider new Next.js patterns | 📋 Future | + +--- + ## Related ADRs - [ADR-005: Technology Stack](./ADR-005-technology-stack.md) - เลือกใช้ Next.js @@ -395,5 +486,16 @@ export default function Error({ --- -**Last Updated:** 2025-12-01 -**Next Review:** 2026-06-01 +**Document Version:** v1.0 +**Last Updated:** 2026-02-24 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2025-12-01 | Initial ADR creation with App Router strategy | Frontend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-012-ui-component-library.md b/specs/06-Decision-Records/ADR-012-ui-component-library.md index dc54dd9..0737754 100644 --- a/specs/06-Decision-Records/ADR-012-ui-component-library.md +++ b/specs/06-Decision-Records/ADR-012-ui-component-library.md @@ -4,6 +4,63 @@ **Date:** 2026-02-24 **Decision Makers:** Frontend Team, UX Designer **Related Documents:** [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md), [ADR-005: Technology Stack](./ADR-005-technology-stack.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Design Consistency** | [Product Vision](../00-overview/00-03-product-vision.md) - UI/UX Requirements | Shadcn/UI for consistent design system | +| **Accessibility Support** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-UI-003 | Radix UI primitives for WCAG 2.1 AA | +| **Performance Optimization** | [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) - Performance | Tree-shakeable components, minimal bundle | +| **Customization Flexibility** | [Engineering Guidelines](../05-Engineering-Guidelines/05-01-fullstack-js-guidelines.md) - DX | Full ownership of component code | +| **Bundle Size Constraints** | [Architecture](../02-architecture/02-02-software-architecture.md) - Performance | Copy-only-what-you-use approach | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Library vs. Custom (MUI/Ant Design vs. Shadcn/UI) +- **Resolution:** Chose Shadcn/UI for full control and minimal bundle +- **Trade-off:** Manual updates vs. Complete customization freedom + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **UI Components** | All UI components use Shadcn/UI | 🔴 Critical | +| **Tailwind Config** | CSS variables and theming | 🔴 Critical | +| **Component Library** | Custom component compositions | 🔴 Critical | +| **Form Components** | Integration with React Hook Form | 🟡 Important | +| **Layout Components** | Page layouts and navigation | 🟡 Important | +| **Theme System** | Dark/light mode support | 🟡 Important | +| **Component Testing** | Unit tests for custom components | 🟡 Important | +| **Documentation** | Component usage guidelines | 🟢 Guidelines | +| **Update Process** | Manual component update workflow | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Frontend (Next.js) +- [x] Initialize Shadcn/UI project +- [x] Add core components (Button, Input, Card, etc.) +- [x] Setup Tailwind CSS with CSS variables +- [x] Create custom component compositions +- [x] Implement theme switching +- [x] Update all pages to use new components +- [x] Add component testing + +#### Design System +- [x] Define design tokens and colors +- [x] Create component usage guidelines +- [x] Document customization patterns +- [x] Setup component update workflow --- @@ -409,6 +466,35 @@ export function CorrespondenceCard({ correspondence }) { --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Shadcn/UI major updates + - New component requirements + - Accessibility standard updates + +### Review Checklist +- [ ] Component library still meets design requirements +- [ ] Bundle size within acceptable limits +- [ ] Accessibility compliance maintained +- [ ] Custom components properly documented +- [ ] Cross-document dependencies still valid +- [ ] New component libraries to consider +- [ ] Component update workflow effective + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-012 v1.0 | Base Shadcn/UI implementation | ✅ Complete | +| v1.9.0+ | ADR-012 v1.1 | Review component updates and performance | 📋 Planned | +| v2.0.0+ | ADR-012 v2.0 | Consider new UI patterns or libraries | 📋 Future | + +--- + ## Related ADRs - [ADR-005: Technology Stack](./ADR-005-technology-stack.md) - เลือกใช้ Tailwind CSS @@ -424,5 +510,16 @@ export function CorrespondenceCard({ correspondence }) { --- -**Last Updated:** 2025-12-01 -**Next Review:** 2026-06-01 +**Document Version:** v1.0 +**Last Updated:** 2026-02-24 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with UI component strategy | Frontend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-013-form-handling-validation.md b/specs/06-Decision-Records/ADR-013-form-handling-validation.md index 5397d15..23ba7e1 100644 --- a/specs/06-Decision-Records/ADR-013-form-handling-validation.md +++ b/specs/06-Decision-Records/ADR-013-form-handling-validation.md @@ -4,6 +4,67 @@ **Date:** 2026-02-24 **Decision Makers:** Frontend Team **Related Documents:** [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Form Validation** | [Product Vision](../00-overview/00-03-product-vision.md) - Data Integrity | React Hook Form + Zod validation | +| **Performance Optimization** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-UI-002 | Uncontrolled components for minimal re-renders | +| **Type Safety** | [Engineering Guidelines](../05-Engineering-Guidelines/05-01-fullstack-js-guidelines.md) - TypeScript | Zod schema to TypeScript types | +| **Developer Experience** | [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) - DX | Clean API with minimal boilerplate | +| **Bundle Size Constraints** | [Architecture](../02-architecture/02-02-software-architecture.md) - Performance | Lightweight solution (8.5kb) | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Performance vs. Developer Experience (Formik vs. RHF) +- **Resolution:** Chose React Hook Form for performance and type safety +- **Trade-off:** Learning curve for uncontrolled components vs. Better performance + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Form Components** | All forms use RHF + Zod | 🔴 Critical | +| **Validation Schemas** | Zod schemas for all forms | 🔴 Critical | +| **API Routes** | Server-side validation | 🔴 Critical | +| **UI Components** | FormField wrapper components | 🟡 Important | +| **File Upload** | RHF integration for file handling | 🟡 Important | +| **Dynamic Forms** | useFieldArray for complex forms | 🟡 Important | +| **Type Definitions** | Form types from Zod schemas | 🟡 Important | +| **Testing Setup** | Form testing utilities | 🟢 Guidelines | +| **Documentation** | Form patterns and examples | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Frontend (Next.js) +- [x] Install React Hook Form + Zod +- [x] Create validation schemas for all forms +- [x] Update all form components to use RHF +- [x] Create reusable FormField components +- [x] Implement file upload with RHF +- [x] Add dynamic form patterns (useFieldArray) +- [x] Setup form testing utilities + +#### Backend (NestJS) +- [x] Sync validation logic with frontend schemas +- [x] Update DTOs to match Zod schemas +- [x] Add proper error responses for validation failures + +#### Architecture +- [x] Document form patterns +- [x] Create form component templates +- [x] Define validation strategy across stack --- @@ -471,6 +532,35 @@ import { Controller } from 'react-hook-form'; --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Performance issues requiring form optimization + - New form patterns or requirements + - React Hook Form/Zod major updates + +### Review Checklist +- [ ] Form performance metrics acceptable +- [ ] Validation schemas still meet requirements +- [ ] Type safety maintained across forms +- [ ] Bundle size within limits +- [ ] Cross-document dependencies still valid +- [ ] New form libraries or patterns to consider +- [ ] Backend validation sync maintained + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-013 v1.0 | Base RHF + Zod implementation | ✅ Complete | +| v1.9.0+ | ADR-013 v1.1 | Review form performance and patterns | 📋 Planned | +| v2.0.0+ | ADR-013 v2.0 | Consider new form technologies | 📋 Future | + +--- + ## Related ADRs - [ADR-007: API Design & Error Handling](./ADR-007-api-design-error-handling.md) @@ -485,5 +575,16 @@ import { Controller } from 'react-hook-form'; --- +**Document Version:** v1.0 **Last Updated:** 2026-02-24 -**Next Review:** 2026-06-01 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with form handling strategy | Frontend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-014-state-management.md b/specs/06-Decision-Records/ADR-014-state-management.md index 3856ede..19089cf 100644 --- a/specs/06-Decision-Records/ADR-014-state-management.md +++ b/specs/06-Decision-Records/ADR-014-state-management.md @@ -4,6 +4,64 @@ **Date:** 2026-02-24 **Decision Makers:** Frontend Team **Related Documents:** [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md), [ADR-011: App Router](./ADR-011-nextjs-app-router.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Global State Management** | [Product Vision](../00-overview/00-03-product-vision.md) - UI/UX Requirements | Zustand for client state | +| **Server State Synchronization** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-UI-001 | TanStack Query for API data | +| **Performance Optimization** | [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) - Performance | Selective re-renders with Zustand | +| **Type Safety** | [Engineering Guidelines](../05-Engineering-Guidelines/05-01-fullstack-js-guidelines.md) - TypeScript | Full TypeScript support | +| **Bundle Size Constraints** | [Architecture](../02-architecture/02-02-software-architecture.md) - Performance | Lightweight solutions (Zustand 1.2kb) | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Complexity vs. Features (Redux vs. Zustand) +- **Resolution:** Chose Zustand + TanStack Query for simplicity and specialization +- **Trade-off:** Smaller ecosystem vs. Better developer experience + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Auth Store** | User session management | 🔴 Critical | +| **Notification Store** | Global notifications | 🔴 Critical | +| **UI Store** | Theme and preferences | 🟡 Important | +| **API Client** | TanStack Query integration | 🔴 Critical | +| **Form Components** | React Hook Form + Zod | 🟡 Important | +| **Server Components** | Data fetching patterns | 🟡 Important | +| **Component Structure** | 'use client' directives | 🟡 Important | +| **Testing Setup** | Store testing patterns | 🟢 Guidelines | +| **Documentation** | State management patterns | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Frontend (Next.js) +- [x] Install Zustand and TanStack Query +- [x] Create auth store with persistence +- [x] Create notification store +- [x] Create UI preferences store +- [x] Setup Query Provider +- [x] Update components to use stores +- [x] Add 'use client' directives where needed +- [x] Implement form validation with RHF + Zod + +#### Architecture +- [x] Define state management patterns +- [x] Document when to use each solution +- [x] Create store templates +- [x] Setup testing utilities for stores --- @@ -381,6 +439,35 @@ export const useUIStore = create()( --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Performance issues requiring state management changes + - New React/Next.js features affecting state + - Bundle size optimization requirements + +### Review Checklist +- [ ] State management patterns still meet requirements +- [ ] Bundle size within acceptable limits +- [ ] Performance metrics acceptable (re-render counts) +- [ ] Type safety maintained across stores +- [ ] Cross-document dependencies still valid +- [ ] New state management libraries to consider +- [ ] Testing coverage for stores adequate + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-014 v1.0 | Base Zustand + TanStack Query setup | ✅ Complete | +| v1.9.0+ | ADR-014 v1.1 | Review bundle size and performance | 📋 Planned | +| v2.0.0+ | ADR-014 v2.0 | Consider new React state patterns | 📋 Future | + +--- + ## Related ADRs - [ADR-011: Next.js App Router](./ADR-011-nextjs-app-router.md) - Server Components @@ -396,5 +483,16 @@ export const useUIStore = create()( --- +**Document Version:** v1.0 **Last Updated:** 2026-02-24 -**Next Review:** 2026-06-01 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with state management strategy | Frontend Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-015-deployment-infrastructure.md b/specs/06-Decision-Records/ADR-015-deployment-infrastructure.md index f457add..aeb5306 100644 --- a/specs/06-Decision-Records/ADR-015-deployment-infrastructure.md +++ b/specs/06-Decision-Records/ADR-015-deployment-infrastructure.md @@ -4,6 +4,67 @@ **Date:** 2026-02-24 **Decision Makers:** DevOps Team, System Architect **Related Documents:** [ADR-005: Technology Stack](./ADR-005-technology-stack.md), [Operations Guide](../04-Infrastructure-OPS/04-04-deployment-guide.md), [Docker Compose Setup](../04-Infrastructure-OPS/04-01-docker-compose.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Deployment Strategy** | [Product Vision](../00-overview/00-03-product-vision.md) - Infrastructure Requirements | Docker Compose + Blue-Green on QNAP | +| **Zero Downtime** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-DEPLOY-001 | Blue-Green deployment with NGINX proxy | +| **Resource Constraints** | [Infrastructure OPS](../04-Infrastructure-OPS/04-01-docker-compose.md) - QNAP limitations | Single-server Docker Compose (not K8s) | +| **Rollback Capability** | [Edge Cases](../01-Requirements/01-06-edge-cases-and-rules.md) - Deployment failures | Tagged images + NGINX switchback | +| **Environment Management** | [Security ADR-016](./ADR-016-security-authentication.md) - Secrets management | .env files on QNAP only | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Complexity vs. Reliability (Docker Compose vs Kubernetes) +- **Resolution:** Chose Docker Compose for QNAP compatibility, added Blue-Green for reliability +- **Trade-off:** Manual scaling vs. Resource efficiency + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Docker Compose Files** | Blue/Green structure + NGINX proxy | 🔴 Critical | +| **Deployment Scripts** | deploy.sh with health checks | 🔴 Critical | +| **Environment Config** | .env management strategy | 🔴 Critical | +| **QNAP Storage** | Volume mounting strategy | 🔴 Critical | +| **NGINX Configuration** | Reverse proxy setup | 🟡 Important | +| **CI/CD Pipeline** | Gitea Actions integration | 🟡 Important | +| **Monitoring Setup** | Health check endpoints | 🟡 Important | +| **Backup Strategy** | Database backup automation | 🟡 Important | +| **Documentation** | Deployment runbooks | 🟢 Guidelines | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Infrastructure (QNAP) +- [x] Create blue/green directory structure +- [x] Setup shared volumes for uploads/logs +- [x] Configure NGINX reverse proxy +- [x] Implement deployment scripts +- [x] Setup environment variables management + +#### Application (Backend/Frontend) +- [x] Add health check endpoints +- [x] Implement graceful shutdown +- [x] Add startup validation for required env vars +- [x] Configure logging to shared volume + +#### Operations +- [x] Create deployment checklist +- [x] Setup backup automation +- [x] Document rollback procedures +- [x] Configure monitoring alerts --- @@ -440,6 +501,35 @@ server { --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - QNAP Container Station updates + - Performance issues requiring scaling changes + - Security updates affecting deployment + +### Review Checklist +- [ ] Blue-Green deployment still meets zero-downtime requirements +- [ ] Resource allocation matches current load +- [ ] Security best practices still current +- [ ] QNAP compatibility maintained +- [ ] Cross-document dependencies still valid +- [ ] New deployment tools/practices to consider +- [ ] Backup and recovery procedures tested + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-015 v1.0 | Base Docker Compose setup | ✅ Complete | +| v1.9.0+ | ADR-015 v1.1 | Review resource allocation | 📋 Planned | +| v2.0.0+ | ADR-015 v2.0 | Consider horizontal scaling | 📋 Future | + +--- + ## Related ADRs - [ADR-005: Technology Stack](./ADR-005-technology-stack.md) @@ -455,5 +545,16 @@ server { --- +**Document Version:** v1.0 **Last Updated:** 2026-02-24 -**Next Review:** 2026-06-01 +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with deployment strategy | DevOps Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-016-security-authentication.md b/specs/06-Decision-Records/ADR-016-security-authentication.md index 247388a..065b5c2 100644 --- a/specs/06-Decision-Records/ADR-016-security-authentication.md +++ b/specs/06-Decision-Records/ADR-016-security-authentication.md @@ -4,6 +4,67 @@ **Date:** 2026-02-24 **Decision Makers:** Security Team, System Architect **Related Documents:** [ADR-004: RBAC Implementation](./ADR-004-rbac-implementation.md), [ADR-007: API Design](./ADR-007-api-design-error-handling.md) +**Version Applicability:** v1.8.0+ +**Next Review:** 2026-08-01 (6-month cycle) + +--- + +## Gap Analysis & Requirement Linking + +### ปิด Gap จาก Requirements: + +| Gap/Requirement | แหล่งที่มา | วิธีการแก้ไขใน ADR นี้ | +|----------------|-------------|-------------------| +| **Authentication & Authorization** | [Product Vision](../00-overview/00-03-product-vision.md) - Security Requirements | JWT + RBAC 4-level implementation | +| **Data Protection** | [Acceptance Criteria](../01-Requirements/01-05-acceptance-criteria.md) - AC-SEC-001 | AES-256 encryption at rest + HTTPS in transit | +| **Audit Trail** | [Business Rules](../01-Requirements/01-02-business-rules/01-02-01-rbac-matrix.md) | Comprehensive security event logging | +| **Session Management** | [Edge Cases](../01-Requirements/01-06-edge-cases-and-rules.md) - Session timeout | Stateless JWT + 15min access token expiry | +| **Input Validation** | [API Design](../02-architecture/02-04-api-design.md) - Validation layer | Class-validator + Zod + Sanitization | + +### แก้ไขความขัดแย้ง: + +- **Conflict:** Cross-domain authentication complexity vs. User Experience +- **Resolution:** Chose Bearer tokens over HTTP-only cookies for Next.js ↔ NestJS communication +- **Trade-off:** Slightly reduced XSS protection for improved developer experience + +--- + +## Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ): + +| Component | ผลกระทบ | ความสำคัญ | +|-----------|----------|-----------| +| **Backend Auth Module** | JWT implementation + Guards | 🔴 Critical | +| **Frontend Auth Store** | Zustand token management | 🔴 Critical | +| **Database Schema** | refresh_tokens table | 🔴 Critical | +| **API Controllers** | @UseGuards(JwtAuthGuard) | 🟡 Important | +| **Middleware** | Helmet + CORS configuration | 🟡 Important | +| **User Service** | Password hashing with bcrypt | 🟡 Important | +| **Audit Log Service** | Security event tracking | 🟡 Important | +| **Frontend Login Page** | Token storage logic | 🟢 Guidelines | +| **Environment Config** | JWT secrets + Encryption keys | 🔴 Critical | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ): + +#### Backend (NestJS) +- [x] Implement AuthService with JWT +- [x] Create JwtAuthGuard +- [x] Add refresh_tokens entity +- [x] Configure Helmet + CORS +- [x] Add rate limiting (Throttler) +- [x] Implement audit logging + +#### Frontend (Next.js) +- [x] Create auth store (Zustand) +- [x] Update API client with Bearer token +- [x] Add token refresh logic +- [x] Update login/logout flows + +#### Infrastructure +- [x] Environment variables for secrets +- [x] HTTPS/TLS configuration +- [x] Database encryption setup --- @@ -427,6 +488,35 @@ await this.auditLogService.create({ --- +## ADR Review Cycle + +### Core Principle Review Schedule +- **Review Frequency:** ทุก 6 เดือน (กุมภาพันธ์ และ สิงหาคม) +- **Trigger Events:** + - Major version upgrade (v1.9.0, v2.0.0) + - Security vulnerability discovery + - New compliance requirements + - Architecture changes affecting auth + +### Review Checklist +- [ ] JWT configuration still meets security standards +- [ ] Password policy alignment with current threats +- [ ] Rate limiting effectiveness +- [ ] Audit log completeness +- [ ] Cross-document dependencies still valid +- [ ] Implementation matches documented decisions +- [ ] New security best practices to consider + +### Version Dependency Matrix + +| System Version | ADR Version | Required Changes | Status | +|----------------|-------------|------------------|---------| +| v1.8.0 - v1.8.5 | ADR-016 v1.0 | Base implementation | ✅ Complete | +| v1.9.0+ | ADR-016 v1.1 | Review JWT expiry times | 📋 Planned | +| v2.0.0+ | ADR-016 v2.0 | Consider session management changes | 📋 Future | + +--- + ## Related ADRs - [ADR-004: RBAC Implementation](./ADR-004-rbac-implementation.md) @@ -443,5 +533,16 @@ await this.auditLogService.create({ --- +**Document Version:** v1.0 **Last Updated:** 2026-02-24 -**Next Review:** 2026-06-01 (Quarterly review) +**Next Review:** 2026-08-01 (6-month cycle) +**Version Applicability:** LCBP3 v1.8.0+ + +--- + +## Change History + +| Version | Date | Changes | Author | +|---------|------|---------|---------| +| v1.0 | 2026-02-24 | Initial ADR creation with security strategy | Security Team | +| v1.1 | 2026-04-04 | Added structured templates: Impact Analysis, Gap Linking, Version Dependency, Review Cycle | System Architect | diff --git a/specs/06-Decision-Records/ADR-017-ollama-data-migration.md b/specs/06-Decision-Records/ADR-017-ollama-data-migration.md index 1c87d5e..c8bcc0e 100644 --- a/specs/06-Decision-Records/ADR-017-ollama-data-migration.md +++ b/specs/06-Decision-Records/ADR-017-ollama-data-migration.md @@ -3,7 +3,15 @@ **Status:** Accepted **Date:** 2026-02-26 **Version:** 1.8.3 (Aligned with ADR-020) +**Review Cycle:** Core ADR (Review every 6 months or Major Version upgrade) **Decision Makers:** Development Team, DevOps Engineer, AI Integration Lead +**Gap Resolution:** Addresses legacy document migration challenges (20,000+ PDFs) and data integrity validation requirements (Product Vision v1.8.5, Section 3.1) and migration acceptance criteria (UAT Criteria, Section 4.6) +**Version Dependency:** +- **Effective From:** v1.8.3 +- **Applies To:** v1.8.3+ (Migration execution) +- **Backward Compatible:** v1.8.0+ (Migration planning) +- **Required For:** v1.9.0+ (Legacy data completion) + **Related Documents:** - [ADR-020: AI Intelligence Integration Architecture](./ADR-020-ai-intelligence-integration.md) — Overall AI Architecture & RFA-First Strategy @@ -85,7 +93,51 @@ **Chosen Option:** Option 3 — Local AI Model (Ollama) + n8n -**Rationale:** ประยุกต์ใช้ Hardware ที่มีอยู่ โดยไม่ขัดหลัก Privacy และ Security ของโครงการ n8n ช่วยลด Risk ที่จะกระทบ Core Backend และรองรับ Checkpoint/Resume ได้ดีกว่าการเขียน Script เอง +**Rationale:** + +ประยุกต์ใช้ Hardware ที่มีอยู่ โดยไม่ขัดหลัก Privacy และ Security ของโครงการ n8n ช่วยลด Risk ที่จะกระทบ Core Backend และรองรับ Checkpoint/Resume ได้ดีกว่าการเขียน Script เอง + +--- + +## Impact Analysis + +### Affected Components + +| Component | Impact Level | Description | +|-----------|--------------|-------------| +| **Migration Infrastructure** | **High** | n8n workflows, Ollama AI services, Admin Desktop setup | +| **Database Schema** | **High** | Migration tables, audit logs, staging areas | +| **Backend Services** | **High** | Migration APIs, validation services, storage integration | +| **Storage Systems** | **Medium** | Two-phase storage, file management, cleanup processes | +| **Security Model** | **Medium** | Migration tokens, IP whitelisting, audit trails | +| **Frontend Interface** | **Medium** | Migration dashboard, review queues, approval workflows | +| **Monitoring & Logging** | **Medium** | Migration progress tracking, error handling, performance metrics | +| **Documentation** | **Low** | Migration procedures, troubleshooting guides | + +### Required Changes + +| Change Category | Specific Changes | Priority | +|----------------|------------------|----------| +| **Infrastructure** |
  • Setup n8n on QNAP NAS with Docker
  • Install Ollama with Gemma 4 on Admin Desktop
  • Configure PaddleOCR service for Thai text extraction
  • Setup network segmentation and AI isolation per ADR-018
  • Configure GPU monitoring and temperature controls
| **Critical** | +| **Database** |
  • Create migration_logs table with UUIDv7 primary keys
  • Create migration_review_queue staging table
  • Create import_transactions audit table
  • Create migration_progress tracking table
  • Setup migration_fallback_state table
| **Critical** | +| **Backend** |
  • Implement MigrationService with business logic
  • Create AI validation layer with confidence thresholds
  • Add migration-specific API endpoints with CASL guards
  • Implement idempotency handling for migration requests
  • Create storage service integration for two-phase file handling
| **Critical** | +| **Security** |
  • Implement migration token system with 7-day expiry
  • Setup IP whitelisting for migration services
  • Configure rate limiting for migration endpoints
  • Create comprehensive audit logging for migration operations
  • Implement Nginx security rules for migration access
| **High** | +| **Storage** |
  • Implement two-phase storage (temp → permanent)
  • Create migration-specific storage paths
  • Setup file cleanup and archival processes
  • Implement storage service integration
  • Create file validation and virus scanning workflows
| **High** | +| **Frontend** |
  • Build migration dashboard with queue management
  • Create review interface for AI suggestions
  • Implement bulk approval/rejection workflows
  • Add progress tracking and monitoring displays
  • Create error handling and retry interfaces
| **Medium** | +| **Monitoring** |
  • Setup migration progress tracking and metrics
  • Implement AI service health monitoring
  • Create error logging and alerting systems
  • Setup performance monitoring for migration workflows
  • Create GPU temperature and resource monitoring
| **Medium** | +| **Documentation** |
  • Create migration operation procedures
  • Document troubleshooting and recovery processes
  • Create admin training materials
  • Update API documentation with migration endpoints
  • Create rollback and recovery guides
| **Medium** | + +### Cross-Component Dependencies + +| Dependency | Source | Target | Impact | +|------------|--------|--------|--------| +| **n8n → Backend API** | Migration workflows | Validation endpoints | Data processing | +| **AI Services → Backend** | Ollama processing | AI validation layer | Quality control | +| **Migration Service → Storage** | Data processing | Two-phase storage | File management | +| **Frontend → Migration API** | Dashboard interface | Migration endpoints | User interaction | +| **Audit → Migration** | Logging service | Migration audit trail | Compliance tracking | +| **Monitoring → Infrastructure** | Health checks | AI and n8n services | Operational stability | +| **Security → Migration** | Token validation | Migration access control | Access management | --- @@ -392,9 +444,112 @@ _สำหรับขั้นตอนปฏิบัติงานแบบ --- +## ADR Review Cycle + +### Review Classification + +**Core ADR Status:** This ADR is classified as a **Core Migration Architecture** due to its fundamental impact on data migration strategy and AI integration patterns. + +### Review Schedule + +| Review Type | Frequency | Trigger | Scope | +|-------------|-----------|---------|-------| +| **Regular Review** | Every 6 months | Calendar-based | Migration effectiveness, AI accuracy | +| **Major Version Review** | Every major version (v2.0.0, v3.0.0) | Version planning | Architecture relevance, new migration requirements | +| **Migration Review** | During migration execution | Migration progress | Performance, accuracy, operational issues | +| **Post-Migration Review** | After migration completion | Migration completion | Lessons learned, improvements, retirement planning | + +### Review Process + +#### Phase 1: Preparation (1 week before review) +1. **Migration Metrics Collection** + - Migration progress and completion rates + - AI validation accuracy and confidence scores + - Error rates and failure patterns + - Processing performance benchmarks + - Storage and resource utilization metrics + +2. **Stakeholder Notification** + - Development Team + - DevOps Engineer + - AI Integration Lead + - Database Administrator + - Project Management + +#### Phase 2: Review Meeting (2-hour session) +1. **Migration Performance Assessment** + - Review migration progress against targets + - Analyze AI validation accuracy and effectiveness + - Evaluate processing speed and resource utilization + - Assess error handling and recovery procedures + +2. **Data Quality Evaluation** + - Review AI validation accuracy against human verification + - Analyze data integrity and consistency metrics + - Evaluate duplicate detection and handling + - Assess revision drift protection effectiveness + +3. **Operational Assessment** + - Review system stability and reliability + - Evaluate monitoring and alerting effectiveness + - Assess rollback and recovery procedures + - Review security compliance and audit trails + +#### Phase 3: Decision & Documentation (1 week after review) +1. **Review Outcomes** + - **No Change:** Migration architecture remains effective + - **Update Required:** Adjust AI parameters or migration procedures + - **Enhancement:** Add new migration capabilities or optimizations + - **Retire:** Migration complete, ADR no longer needed + +2. **Documentation Updates** + - Update migration procedures and guidelines + - Revise performance benchmarks and targets + - Document lessons learned and best practices + - Update operational procedures and troubleshooting guides + +### Review Criteria + +| Criterion | Question | Pass/Fail Threshold | +|-----------|----------|---------------------| +| **Migration Progress** | Is migration meeting completion targets? | Pass: ≥90% of target, Fail: <90% | +| **AI Validation Accuracy** | Is AI validation meeting accuracy targets? | Pass: ≥85% accuracy, Fail: <85% | +| **Processing Performance** | Are processing times within acceptable limits? | Pass: <3s per record, Fail: >3s | +| **Data Integrity** | Are data integrity issues within acceptable limits? | Pass: <2% errors, Fail: ≥2% | +| **System Stability** | Is migration system stable and reliable? | Pass: >99% uptime, Fail: <99% | +| **Security Compliance** | Are all security controls functioning properly? | Pass: 100% compliant, Fail: Any violations | + +### Review History Template + +``` +## Review Cycle [YYYY-MM-DD] + +**Review Type:** [Regular/Major Version/Migration/Post-Migration] +**Reviewers:** [Names and roles] +**Duration:** [Meeting date] + +### Findings +- [Key findings from migration performance and data quality assessment] + +### Issues Identified +- [Performance bottlenecks, accuracy problems, or operational issues] + +### Recommendations +- [Migration optimizations, AI improvements, or procedural changes] + +### Outcome +- [No Change/Update Required/Enhancement/Retire] + +### Next Review Date +- [YYYY-MM-DD] +``` + +--- + ## Document History | Version | Date | Author | Changes | | ------- | ---------- | ----------- | -------------------------------------------------------------------- | | 1.8.0 | 2026-02-26 | DevOps Team | Initial ADR — Ollama + n8n Migration Architecture | | 1.8.2 | 2026-04-03 | Tech Lead | **Updated** — Aligned with ADR-019 (UUID Strategy), changed AI Model to `gemma4:9b` (9.6 GB) | +| 1.8.4 | 2026-04-04 | System Architect | **Enhanced** — Added Impact Analysis template, ADR Review Cycle process, Gap Linking to requirements, and Version Dependency tracking | diff --git a/specs/06-Decision-Records/ADR-017B-ollama.md b/specs/06-Decision-Records/ADR-017B-ai-document-classification.md similarity index 55% rename from specs/06-Decision-Records/ADR-017B-ollama.md rename to specs/06-Decision-Records/ADR-017B-ai-document-classification.md index 2084b33..5bc6ebb 100644 --- a/specs/06-Decision-Records/ADR-017B-ollama.md +++ b/specs/06-Decision-Records/ADR-017B-ai-document-classification.md @@ -1,9 +1,17 @@ -# ADR-017B: Smart Legacy Document Digitization (AI-Powered Use Case Extension) +# ADR-017B: AI Document Classification **Status:** Accepted **Date:** 2026-03-27 **Version:** 1.8.2 (Aligned with ADR-020) +**Review Cycle:** Core ADR (Review every 6 months or Major Version upgrade) **Decision Makers:** Development Team, AI Integration Lead +**Gap Resolution:** Addresses manual document classification inefficiency and inconsistency problems (Product Vision v1.8.5, Section 3.3) and AI-assisted workflow requirements (UAT Criteria, Section 4.8) +**Version Dependency:** +- **Effective From:** v1.8.2 +- **Applies To:** v1.8.2+ (AI classification features) +- **Backward Compatible:** v1.8.0+ (Manual classification still available) +- **Required For:** v1.9.0+ (Enhanced document management) + **Related Documents:** - [ADR-020: AI Intelligence Integration Architecture](./ADR-020-ai-intelligence-integration.md) — Overall AI Architecture & RFA-First Strategy @@ -14,7 +22,7 @@ - [Migration Business Scope](../03-Data-and-Storage/03-06-migration-business-scope.md) - [Glossary](../00-Overview/00-02-glossary.md) -> **Note:** ADR-017B เป็น Use Case Extension ของ ADR-017 ที่ขยายขอบเขตการใช้งาน Ollama จาก Migration Batch สู่ระบบจัดหมวดหมู่เอกสารอัจฉริยะ (Smart Categorization) พร้อมควบคุมตาม ADR-018 (AI Isolation Policy) และเป็นส่วนหนึ่งของ ADR-020 (Unified AI Architecture). +> **Note:** ADR-017B extends ADR-017's scope from batch migration to AI-powered document classification, enabling automatic categorization and metadata extraction. Complies with ADR-018 (AI Isolation Policy) and is part of ADR-020 (Unified AI Architecture). --- @@ -22,11 +30,11 @@ ### ปัญหาที่ต้องการแก้ไข -โครงการ LCBP3 มีเอกสารเก่าจำนวนมาก (กว่า 20,000 ฉบับ) ที่ต้องนำเข้าสู่ระบบ DMS ใหม่ การจัดหมวดหมู่และสกัด Metadata ด้วยมือมีปัญหาหลัก 3 ประการ: +โครงการ LCBP3 มีเอกสารจำนวนมาก (ทั้งเก่าและใหม่) ที่ต้องจัดหมวดหมู่และสกัด Metadata อัตโนมัติ การจัดหมวดหมู่ด้วยมือมีปัญหาหลัก 3 ประการ: -1. **Manual Labor สูง:** ต้องใช้เวลานานในการอ่านและพิมพ์ข้อมูล Metadata (Data Entry) -2. **Human Error:** ความผิดพลาดจากการพิมพ์ (Typo) โดยเฉพาะเลขที่สัญญาและชื่อเฉพาะ -3. **Searchability:** ไฟล์ PDF ที่เป็นแค่ภาพสแกน (Scanned) ไม่สามารถค้นหาเนื้อหาได้ +1. **Manual Labor สูง:** ต้องใช้เวลานานในการอ่านและจัดหมวดหมู่เอกสารด้วยมือ +2. **Human Error:** ความผิดพลาดจากการจัดหมวดหมู่ (ผิดประเภท, ผิด Tag) โดยเฉพาะเอกสารที่ซับซ้อน +3. **Inconsistency:** การจัดหมวดหมู่ไม่สม่ำเสมอกันระหว่างผู้จัดการคนละคน ### ข้อจำกัดที่สำคัญ @@ -100,7 +108,47 @@ **Rationale:** -ประยุกต์ใช้ Hardware ที่มีอยู่ (i7-9700K + RTX 2060 Super) โดยไม่ขัดหลัก Privacy และ Security ของโครงการ n8n ช่วยลด Risk ที่จะกระทบ Core Backend และรองรับ Checkpoint/Resume ได้ดีกว่าการเขียน Script เอง นอกจากนี้ยังสอดคล้องกับ **ADR-018 (AI Boundary)** ที่กำหนดให้ AI ต้องรันบน Admin Desktop แยกต่างหาก และไม่สามารถเข้าถึง Database/Storage โดยตรงได้ +การใช้ AI จัดหมวดหมู่เอกสารอัตโนมัติด้วย Ollama ช่วยลดภาระงานจากการจัดหมวดหมู่ด้วยมือ พร้อมรักษาความปลอดภัยตามนโยบาย ADR-018 ที่กำหนดให้ AI ต้องรันบน Admin Desktop แยกต่างหาก และไม่สามารถเข้าถึง Database/Storage โดยตรง ทำให้ได้ประสิทธิภาพที่ดีขึ้นในการจัดการเอกสารขนาดใหญ่ + +--- + +## Impact Analysis + +### Affected Components + +| Component | Impact Level | Description | +|-----------|--------------|-------------| +| **Frontend Components** | **High** | AI classification UI, suggestion displays, user confirmation flows | +| **Backend Services** | **High** | AI integration endpoints, validation services, classification logic | +| **AI Infrastructure** | **Medium** | Ollama model usage, prompt engineering, confidence scoring | +| **Database Schema** | **Medium** | AI suggestion storage, classification history, confidence tracking | +| **User Experience** | **Medium** | Workflow changes, AI-assisted classification interfaces | +| **API Design** | **Medium** | AI classification endpoints, response formats, error handling | +| **Testing Framework** | **Low** | AI accuracy tests, classification validation, user acceptance tests | +| **Documentation** | **Low** | User guides, AI classification procedures, troubleshooting | + +### Required Changes + +| Change Category | Specific Changes | Priority | +|----------------|------------------|----------| +| **Frontend** |
  • Create AI classification suggestion components
  • Build confidence score indicators
  • Implement user confirmation dialogs
  • Add classification history displays
  • Create AI-assisted tagging interface
| **Critical** | +| **Backend** |
  • Implement AI classification service endpoints
  • Create validation layer for AI suggestions
  • Add confidence threshold processing
  • Implement classification audit logging
  • Create AI model communication interfaces
| **Critical** | +| **Database** |
  • Create AI classification suggestions table
  • Add confidence score tracking fields
  • Implement classification history logging
  • Create user feedback storage for AI improvement
  • Update data dictionary with AI fields
| **High** | +| **AI Integration** |
  • Setup Ollama model communication protocols
  • Implement prompt engineering for document classification
  • Create confidence scoring algorithms
  • Setup fallback model switching logic
  • Implement AI response validation
| **High** | +| **API** |
  • Create /api/ai/classify endpoint
  • Implement AI suggestion confirmation endpoints
  • Add AI service health check endpoints
  • Create classification feedback endpoints
  • Implement rate limiting for AI services
| **High** | +| **Testing** |
  • Create AI accuracy validation tests
  • Implement classification consistency tests
  • Add user acceptance testing for AI features
  • Create performance tests for AI endpoints
  • Implement security tests for AI boundaries
| **Medium** | +| **Documentation** |
  • Create user guide for AI classification features
  • Document AI model limitations and best practices
  • Create troubleshooting guide for AI issues
  • Update API documentation with AI endpoints
| **Medium** | + +### Cross-Component Dependencies + +| Dependency | Source | Target | Impact | +|------------|--------|--------|--------| +| **Frontend → AI API** | Classification UI components | /api/ai/classify endpoint | User experience | +| **Backend → AI Services** | AI classification service | Ollama model API | Classification accuracy | +| **Database → Classification** | Classification results | AI suggestions table | Data persistence | +| **Validation → AI Output** | Validation layer | AI response processing | Quality control | +| **Audit → AI Interactions** | Logging service | Classification audit trail | Compliance | +| **Testing → AI Accuracy** | Test suites | Classification validation | Quality assurance | --- @@ -269,19 +317,19 @@ Phase 2: Final Commit (โดย Admin ผ่าน Frontend) ### Positive Consequences -1. ✅ **Privacy Guaranteed** — ไม่มีข้อมูลออกนอกเครือข่ายองค์กร -2. ✅ **Zero AI Cost** — ไม่มีค่าใช้จ่าย Pay-per-use -3. ✅ **Security Compliant (ADR-018)** — AI Isolation ชัดเจน -4. ✅ **Human-in-the-Loop** — ความถูกต้อง 100% ก่อน Commit -5. ✅ **Recoverability** — รองรับ Checkpoint/Resume และ Rollback -6. ✅ **Searchable Legacy** — Scanned PDF กลายเป็น Searchable Metadata +1. ✅ **Automated Classification:** ลดเวลาการจัดหมวดหมู่เอกสารด้วยมืออย่างมีนัยสำคัญ +2. ✅ **Consistent Categorization:** AI จัดหมวดหมู่อย่างสม่ำเสมอตามเกณฑ์เดียวกัน +3. ✅ **Security Compliant (ADR-018):** AI Isolation ชัดเจน ปลอดภัย +4. ✅ **Human-in-the-Loop:** ความถูกต้อง 100% ก่อนยืนยันการจัดหมวดหมู่ +5. ✅ **Scalable:** รองรับการจัดหมวดหมู่เอกสารจำนวนมาก +6. ✅ **Cost Effective:** ไม่มีค่าใช้จ่ายต่อเอกสาร (On-premise AI) ### Negative Consequences -1. ❌ **Operational Overhead** — ต้องดูแล GPU Temperature และ Desktop Uptime -2. ❌ **Accuracy Trade-off** — Model ขนาดเล็กอาจแม่นยำน้อยกว่า Cloud AI -3. ❌ **Time Investment** — ต้องใช้เวลา ~3–4 คืนในการ Migration -4. ❌ **Hardware Dependency** — ต้องพึ่งพา Desktop Desk-5439 +1. ❌ **Operational Overhead:** ต้องดูแล GPU Temperature และ Desktop Uptime +2. ❌ **Accuracy Trade-off:** Model ขนาดเล็กอาจแม่นยำน้อยกว่า Cloud AI +3. ❌ **Hardware Dependency:** ต้องพึ่งพา Desktop Desk-5439 +4. ❌ **Processing Time:** ต้องรอ AI processing สำหรับเอกสารแต่ละฉบับ ### Mitigation Strategies @@ -292,6 +340,108 @@ Phase 2: Final Commit (โดย Admin ผ่าน Frontend) --- +## ADR Review Cycle + +### Review Classification + +**Core ADR Status:** This ADR is classified as a **Core AI Feature** due to its fundamental impact on document management workflows and AI integration patterns. + +### Review Schedule + +| Review Type | Frequency | Trigger | Scope | +|-------------|-----------|---------|-------| +| **Regular Review** | Every 6 months | Calendar-based | AI accuracy, user adoption, performance | +| **Major Version Review** | Every major version (v2.0.0, v3.0.0) | Version planning | Architecture relevance, new AI capabilities | +| **Performance Review** | Quarterly | Performance monitoring | AI processing times, accuracy metrics | +| **User Feedback Review** | Quarterly | User feedback analysis | User satisfaction, workflow improvements | + +### Review Process + +#### Phase 1: Preparation (1 week before review) +1. **Metrics Collection** + - AI classification accuracy rates and trends + - User adoption and satisfaction metrics + - Processing performance benchmarks + - Error rates and failure patterns + - User feedback and improvement suggestions + +2. **Stakeholder Notification** + - Development Team + - AI Integration Lead + - Product Management + - User Experience Team + - Quality Assurance Team + +#### Phase 2: Review Meeting (2-hour session) +1. **Performance Assessment** + - Review AI accuracy metrics against targets + - Analyze processing time performance + - Evaluate error rates and failure patterns + - Assess system resource utilization + +2. **User Experience Evaluation** + - Review user adoption and satisfaction rates + - Analyze user feedback and improvement requests + - Evaluate workflow integration effectiveness + - Assess user interface and experience quality + +3. **Technology Assessment** + - Review AI model performance and accuracy + - Evaluate new AI technologies and improvements + - Assess integration with other system components + - Review security and compliance status + +#### Phase 3: Decision & Documentation (1 week after review) +1. **Review Outcomes** + - **No Change:** AI classification remains effective and accurate + - **Update Required:** Adjust AI parameters or user interface + - **Enhancement:** Add new classification capabilities or features + - **Retire:** AI classification no longer needed (unlikely) + +2. **Documentation Updates** + - Update AI classification procedures and guidelines + - Revise user documentation and training materials + - Update performance metrics and targets + - Modify integration documentation + +### Review Criteria + +| Criterion | Question | Pass/Fail Threshold | +|-----------|----------|---------------------| +| **Classification Accuracy** | Is AI meeting target accuracy rates? | Pass: ≥85%, Fail: <85% | +| **User Adoption** | Are users actively using AI classification? | Pass: >70% adoption, Fail: ≤70% | +| **Processing Performance** | Are processing times within acceptable limits? | Pass: <10s per document, Fail: >10s | +| **User Satisfaction** | Are users satisfied with AI suggestions? | Pass: ≥4.0/5.0, Fail: <4.0/5.0 | +| **Error Rates** | Are AI errors within acceptable thresholds? | Pass: <5% error rate, Fail: ≥5% | +| **Integration Stability** | Is AI integration stable and reliable? | Pass: >99% uptime, Fail: <99% | + +### Review History Template + +``` +## Review Cycle [YYYY-MM-DD] + +**Review Type:** [Regular/Major Version/Performance/User Feedback] +**Reviewers:** [Names and roles] +**Duration:** [Meeting date] + +### Findings +- [Key findings from accuracy, performance, and user experience assessment] + +### Issues Identified +- [Accuracy problems, performance bottlenecks, or user experience issues] + +### Recommendations +- [AI model improvements, user interface enhancements, or workflow changes] + +### Outcome +- [No Change/Update Required/Enhancement/Retire] + +### Next Review Date +- [YYYY-MM-DD] +``` + +--- + ## Related Documents - [ADR-017: Ollama Data Migration Architecture](./ADR-017-ollama-data-migration.md) — Architecture หลักสำหรับ Migration @@ -309,9 +459,12 @@ Phase 2: Final Commit (โดย Admin ผ่าน Frontend) |---------|------------|------------|---------| | 1.0.0 | 2026-02-26 | Nattanin | Initial Use Case Specification | | 1.8.1 | 2026-03-27 | Tech Lead | **Refactored to ADR format** — Aligned with ADR-017, ADR-018, and Project Specs | +| 1.8.3 | 2026-04-04 | System Architect | **Renamed** — Changed from "Smart Legacy Document Digitization" to "AI Document Classification" for clarity and simplicity | +| 1.8.4 | 2026-04-04 | System Architect | **Enhanced** — Added Impact Analysis template, ADR Review Cycle process, Gap Linking to requirements, and Version Dependency tracking | --- -**Last Updated:** 2026-03-27 +**Last Updated:** 2026-04-04 **Status:** Accepted **Next Review:** 2026-06-01 (Quarterly review) +**Next 6-Month Review:** 2026-10-04 (regular review cycle) diff --git a/specs/06-Decision-Records/ADR-018-ai-boundary.md b/specs/06-Decision-Records/ADR-018-ai-boundary.md index cea1a6a..a995ff6 100644 --- a/specs/06-Decision-Records/ADR-018-ai-boundary.md +++ b/specs/06-Decision-Records/ADR-018-ai-boundary.md @@ -3,12 +3,20 @@ **Status:** Accepted **Date:** 2026-03-27 **Version:** 1.8.2 (Aligned with ADR-020) +**Review Cycle:** Core ADR (Review every 6 months or Major Version upgrade) **Decision Makers:** Security Team, System Architect, AI Integration Lead +**Gap Resolution:** Addresses AI security risks (data exposure, unauthorized modification, privilege escalation) and compliance requirements (ISO 27001, PDPA) from Security Requirements (Section 3.1) and Risk Assessment (Section 4.2) +**Version Dependency:** +- **Effective From:** v1.8.2 +- **Applies To:** v1.8.2+ (All AI implementations) +- **Backward Compatible:** v1.8.0+ (Security policy enforcement) +- **Required For:** v1.9.0+ (Mandatory for all AI features) + **Related Documents:** - [ADR-020: AI Intelligence Integration Architecture](./ADR-020-ai-intelligence-integration.md) — Overall AI Architecture & RFA-First Strategy - [ADR-017: Ollama Data Migration Architecture](./ADR-017-ollama-data-migration.md) -- [ADR-017B: Smart Legacy Document Digitization](./ADR-017B-ollama.md) +- [ADR-017B: AI Document Classification](./ADR-017B-ai-document-classification.md) - [ADR-016: Security & Authentication](./ADR-016-security-authentication.md) - [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) - [n8n Migration Setup Guide](../03-Data-and-Storage/03-05-n8n-migration-setup-guide.md) @@ -104,6 +112,45 @@ --- +## Impact Analysis + +### Affected Components + +| Component | Impact Level | Description | +|-----------|--------------|-------------| +| **AI Infrastructure** | **High** | Physical isolation on Admin Desktop, network segmentation | +| **Security Architecture** | **High** | New AI authentication, audit logging, validation layers | +| **API Design** | **Medium** | AI-specific endpoints, authentication scopes, rate limiting | +| **Network Configuration** | **Medium** | IP whitelisting, firewall rules, zone segmentation | +| **Monitoring & Logging** | **Medium** | AI service health checks, audit trail expansion | +| **Development Workflow** | **Low** | AI development guidelines, compliance checks | +| **Documentation** | **Low** | Security policies, AI integration guides | + +### Required Changes + +| Change Category | Specific Changes | Priority | +|----------------|------------------|----------| +| **Infrastructure** |
  • Setup AI Zone on Admin Desktop (Desk-5439)
  • Configure network segmentation and IP whitelisting
  • Install Ollama and AI services on isolated host
  • Setup firewall rules for AI communication
| **Critical** | +| **Security** |
  • Create AI service authentication tokens
  • Implement AI-specific API scopes and permissions
  • Setup comprehensive audit logging for AI interactions
  • Configure rate limiting for AI endpoints
| **Critical** | +| **API Layer** |
  • Create AI validation service with confidence thresholds
  • Add AI-specific authentication middleware
  • Implement AI request/response logging
  • Create AI health check endpoints
| **Critical** | +| **Network** |
  • Configure LAN-only access for AI services
  • Setup IP whitelist for AI host communication
  • Implement network monitoring for AI traffic
  • Create firewall rules for AI zone isolation
| **High** | +| **Monitoring** |
  • Setup AI service health monitoring
  • Create audit log analysis for AI interactions
  • Implement GPU temperature and resource monitoring
  • Create alerting for AI service failures
| **High** | +| **Documentation** |
  • Create AI integration security guidelines
  • Update development workflows with AI security requirements
  • Create AI compliance documentation
  • Update API documentation with AI security requirements
| **Medium** | +| **Testing** |
  • Create AI security penetration tests
  • Implement AI boundary validation tests
  • Create AI authentication and authorization tests
  • Setup AI compliance verification tests
| **Medium** | + +### Cross-Component Dependencies + +| Dependency | Source | Target | Impact | +|------------|--------|--------|--------| +| **AI Services → Backend API** | Ollama/OpenRAG requests | DMS Backend validation layer | Security enforcement | +| **Authentication → AI Services** | JWT token validation | AI service access control | Access management | +| **Network → AI Infrastructure** | Firewall rules | Admin Desktop isolation | Network security | +| **Audit → AI Interactions** | Logging service | AI request/response tracking | Compliance monitoring | +| **Monitoring → AI Health** | Health checks | AI service availability | Operational stability | +| **Documentation → Development** | Security guidelines | AI integration patterns | Developer compliance | + +--- + ## AI Isolation Architecture ### Infrastructure Layout @@ -384,7 +431,7 @@ Response: ## Related Documents - [ADR-017: Ollama Data Migration Architecture](./ADR-017-ollama-data-migration.md) — Migration implementation following ADR-018 -- [ADR-017B: Smart Legacy Document Digitization](./ADR-017B-ollama.md) — Smart categorization use case +- [ADR-017B: AI Document Classification](./ADR-017B-ai-document-classification.md) — AI document classification use case - [ADR-016: Security & Authentication](./ADR-016-security-authentication.md) — General security strategy - [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) — UUID strategy for API security - [03-07-OpenRAG.md](../03-Data-and-Storage/03-07-OpenRAG.md) — RAG architecture under ADR-018 @@ -392,15 +439,119 @@ Response: --- +## ADR Review Cycle + +### Review Classification + +**Core ADR Status:** This ADR is classified as a **Core Security Policy** due to its fundamental impact on system security, compliance, and AI governance. + +### Review Schedule + +| Review Type | Frequency | Trigger | Scope | +|-------------|-----------|---------|-------| +| **Regular Review** | Every 6 months | Calendar-based | Security effectiveness, compliance status | +| **Major Version Review** | Every major version (v2.0.0, v3.0.0) | Version planning | Architecture relevance, new AI technologies | +| **Security Review** | Quarterly | Security audit | Threat model updates, vulnerability assessment | +| **Compliance Review** | Annually | Compliance audit | ISO 27001, PDPA requirements verification | + +### Review Process + +#### Phase 1: Preparation (1 week before review) +1. **Security Metrics Collection** + - AI service access logs and anomaly detection + - Authentication and authorization audit results + - Network segmentation and firewall rule effectiveness + - Audit log completeness and integrity verification + - Compliance framework updates (ISO 27001, PDPA) + +2. **Stakeholder Notification** + - Security Team + - System Architect + - AI Integration Lead + - Compliance Officer + - DevOps Team + +#### Phase 2: Review Meeting (2-hour session) +1. **Security Assessment** + - Review AI isolation effectiveness and any breach attempts + - Assess authentication and authorization mechanisms + - Evaluate audit logging completeness and accuracy + - Review network segmentation and firewall configurations + +2. **Compliance Evaluation** + - Verify ISO 27001 and PDPA compliance status + - Review regulatory changes and impact requirements + - Assess audit trail completeness for compliance reporting + - Evaluate data privacy and retention policies + +3. **Technology Assessment** + - Review AI technology stack currency and security patches + - Assess new AI security threats and mitigation strategies + - Evaluate monitoring and alerting effectiveness + - Review incident response procedures for AI security events + +#### Phase 3: Decision & Documentation (1 week after review) +1. **Review Outcomes** + - **No Change:** Security policy remains effective and compliant + - **Update Required:** Adjust security controls or procedures + - **Enhancement:** Add new security measures for emerging threats + - **Urgent:** Immediate security updates required + +2. **Documentation Updates** + - Update security controls and procedures + - Revise compliance documentation + - Update incident response playbooks + - Modify security guidelines and training materials + +### Review Criteria + +| Criterion | Question | Pass/Fail Threshold | +|-----------|----------|---------------------| +| **Security Effectiveness** | Are AI isolation controls preventing unauthorized access? | Pass: 0 incidents, Fail: Any breach | +| **Compliance Status** | Are all ISO 27001 and PDPA requirements met? | Pass: 100% compliant, Fail: Any gaps | +| **Audit Trail Completeness** | Are all AI interactions logged and traceable? | Pass: 100% coverage, Fail: <100% | +| **Authentication Integrity** | Are AI service authentication mechanisms robust? | Pass: No unauthorized access, Fail: Any incidents | +| **Network Isolation** | Are AI services properly segmented from production? | Pass: No lateral movement, Fail: Any cross-zone access | +| **Monitoring Effectiveness** | Are AI security events detected and alerted promptly? | Pass: <5min detection, Fail: >5min | + +### Review History Template + +``` +## Review Cycle [YYYY-MM-DD] + +**Review Type:** [Regular/Major Version/Security/Compliance] +**Reviewers:** [Names and roles] +**Duration:** [Meeting date] + +### Findings +- [Key findings from security and compliance assessment] + +### Issues Identified +- [Security gaps, compliance issues, or vulnerabilities discovered] + +### Recommendations +- [Security enhancements, compliance improvements, or procedural changes] + +### Outcome +- [No Change/Update Required/Enhancement/Urgent] + +### Next Review Date +- [YYYY-MM-DD] +``` + +--- + ## Document History | Version | Date | Author | Changes | | ------- | ---------- | ------------ | -------------------------------------------------------- | | 1.8.1 | 2026-03-27 | Security Lead| Initial ADR — AI Boundary Policy (Physical Isolation) | | 1.8.2 | 2026-04-03 | Tech Lead | Updated — Aligned AI Model spec with ADR-017/017B | +| 1.8.3 | 2026-04-04 | System Architect | Enhanced — Added Impact Analysis template, ADR Review Cycle process, Gap Linking to requirements, and Version Dependency tracking | --- -**Last Updated:** 2026-04-03 +**Last Updated:** 2026-04-04 **Status:** Accepted **Next Review:** 2026-06-01 (Quarterly security review) +**Next 6-Month Review:** 2026-10-04 (regular review cycle) diff --git a/specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md b/specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md index 90ae516..b5d4d3e 100644 --- a/specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md +++ b/specs/06-Decision-Records/ADR-019-hybrid-identifier-strategy.md @@ -3,7 +3,15 @@ **Status:** Accepted **Date:** 2026-03-12 **Version:** 1.8.2 +**Review Cycle:** Core ADR (Review every 6 months or Major Version upgrade) **Decision Makers:** Development Team, Database Architect +**Gap Resolution:** Addresses security vulnerability from sequential INT IDs (OWASP BOLA) and scalability requirements for cross-system integration (Product Vision v1.8.5, Section 2.4) and API security requirements (Security Requirements, Section 3.1) +**Version Dependency:** +- **Effective From:** v1.8.2 +- **Applies To:** v1.8.2+ (Progressive implementation) +- **Backward Compatible:** v1.8.0+ (Dual-mode transition) +- **Required For:** v1.9.0+ (All public APIs must use UUID) + **Related Documents:** - [Data Dictionary](../03-Data-and-Storage/03-01-data-dictionary.md) @@ -92,6 +100,48 @@ --- +## Impact Analysis + +### Affected Components + +| Component | Impact Level | Description | +|-----------|--------------|-------------| +| **Database Schema** | **High** | Add UUID columns to 14 core tables with UNIQUE indexes | +| **Backend Entities** | **High** | Add BaseUuidEntity, update all public-facing entities | +| **API Layer** | **High** | Update controllers, services, DTOs to use UUID parameters | +| **Frontend Types** | **Medium** | Update TypeScript interfaces to use publicId consistently | +| **URL Routing** | **Medium** | Change route patterns from INT to UUID parameters | +| **Security Model** | **Medium** | Enhanced OWASP BOLA protection, API authentication | +| **Caching Strategy** | **Medium** | Redis cache keys transition from INT to UUID | +| **API Documentation** | **Low** | Update endpoint documentation and examples | +| **Testing Framework** | **Low** | Update test fixtures and mock data | + +### Required Changes + +| Change Category | Specific Changes | Priority | +|----------------|------------------|----------| +| **Database** |
  • ADD UUID column to 14 core tables (SQL First)
  • CREATE UNIQUE INDEX on each UUID column
  • Update data dictionary with new fields
| **Critical** | +| **Backend** |
  • Create BaseUuidEntity with publicId property
  • Update 14+ entities to extend BaseUuidEntity
  • Modify controllers to accept UUID parameters
  • Update services to resolve UUID → INT for queries
  • Modify DTOs to expose publicId, exclude INT id
| **Critical** | +| **API Layer** |
  • Update route patterns to use :uuid parameters
  • Add ParseUUIDPipe for validation
  • Implement FindByIdOrUuid methods during transition
  • Update API responses to return publicId
| **Critical** | +| **Frontend** |
  • Update all TypeScript interfaces to use publicId
  • Remove fallback uuid/id fields from types
  • Update URL construction to use publicId
  • Modify API calls to pass UUID strings
| **High** | +| **Security** |
  • Update CASL policies to work with UUID identifiers
  • Enhance API authentication for UUID-based routes
  • Update audit logging to use UUID references
| **High** | +| **Caching** |
  • Update Redis cache key strategy to use UUID
  • Implement cache invalidation for UUID-based keys
  • Migrate existing cache entries during transition
| **Medium** | +| **Testing** |
  • Update unit tests with UUID fixtures
  • Modify integration tests for UUID routes
  • Add performance tests for UUID vs INT lookups
| **Medium** | +| **Documentation** |
  • Update API documentation with UUID examples
  • Create migration guide for developers
  • Update frontend development guidelines
| **Medium** | + +### Cross-Component Dependencies + +| Dependency | Source | Target | Impact | +|------------|--------|--------|--------| +| **Entity → Database** | BaseUuidEntity publicId property | Database uuid column | Data persistence | +| **Controller → Service** | UUID route parameters | Service UUID resolution | Request handling | +| **Frontend → API** | publicId in TypeScript | UUID API endpoints | Data binding | +| **Cache → Database** | Redis UUID keys | Database UUID lookups | Performance | +| **Security → API** | CASL UUID policies | UUID-based route protection | Authorization | +| **Documentation → Code** | UUID examples | Implementation patterns | Developer guidance | + +--- + ## Technical Specification ### 1. UUID Format @@ -510,12 +560,119 @@ type ProjectOption = { --- +## ADR Review Cycle + +### Review Classification + +**Core ADR Status:** This ADR is classified as a **Core Architecture Decision** due to its fundamental impact on system security, data architecture, and API design patterns. + +### Review Schedule + +| Review Type | Frequency | Trigger | Scope | +|-------------|-----------|---------|-------| +| **Regular Review** | Every 6 months | Calendar-based | Security effectiveness, performance impact | +| **Major Version Review** | Every major version (v2.0.0, v3.0.0) | Version planning | Architecture relevance, new requirements | +| **Security Review** | Annually or after security incident | Security audit | OWASP compliance, threat model updates | +| **Performance Review** | Quarterly | Performance monitoring | Database performance, query optimization | + +### Review Process + +#### Phase 1: Preparation (1 week before review) +1. **Metrics Collection** + - UUID vs INT query performance benchmarks + - Security incident reports related to ID enumeration + - Storage usage and growth patterns + - Developer adoption and compliance rates + - Cross-system integration success metrics + +2. **Stakeholder Notification** + - Development Team + - Database Architect + - Security Team + - API Team + - Frontend Team + +#### Phase 2: Review Meeting (2-hour session) +1. **Security Assessment** + - Review any ID enumeration attempts + - Assess OWASP BOLA protection effectiveness + - Evaluate UUID randomness and collision resistance + +2. **Performance Evaluation** + - Analyze UUID lookup performance vs INT + - Review index fragmentation and maintenance + - Assess storage impact and growth projections + +3. **Implementation Compliance** + - Check frontend publicId usage consistency + - Verify API endpoint UUID adoption + - Review cache key migration progress + +#### Phase 3: Decision & Documentation (1 week after review) +1. **Review Outcomes** + - **No Change:** ADR remains valid and effective + - **Update Required:** Adjust naming conventions or patterns + - **Supersede:** New ADR created for different identifier strategy + - **Retire:** ADR no longer relevant (unlikely given core nature) + +2. **Documentation Updates** + - Update review date and findings + - Add new version notes + - Update implementation guidelines + - Modify transition timeline if needed + +### Review Criteria + +| Criterion | Question | Pass/Fail Threshold | +|-----------|----------|---------------------| +| **Security Effectiveness** | Are ID enumeration attacks prevented? | Pass: 0 incidents, Fail: Any successful enumeration | +| **Performance Impact** | Are UUID lookups within acceptable limits? | Pass: <50ms avg, Fail: >50ms avg | +| **Developer Compliance** | Is publicId used consistently across codebase? | Pass: >95% compliance, Fail: <95% | +| **Storage Efficiency** | Is storage impact within projections? | Pass: <5% deviation, Fail: >5% | +| **API Coverage** | Are all public APIs using UUID? | Pass: 100% coverage, Fail: Any INT-based endpoints | +| **Frontend Consistency** | Are all TypeScript types using publicId? | Pass: 100% compliance, Fail: Any fallback fields | + +### Review History Template + +``` +## Review Cycle [YYYY-MM-DD] + +**Review Type:** [Regular/Major Version/Security/Performance] +**Reviewers:** [Names and roles] +**Duration:** [Meeting date] + +### Findings +- [Key findings from security and performance assessment] + +### Issues Identified +- [Problems or concerns discovered] + +### Recommendations +- [Action items and decisions] + +### Outcome +- [No Change/Update Required/Supersede/Retire] + +### Next Review Date +- [YYYY-MM-DD] +``` + +--- + ## 🔄 Change Log | Version | Date | Changes | Updated By | | ------- | ---------- | ------------------------------------------------------------------- | ----------- | +| 1.8.3 | 2026-04-04 | Enhanced — Added Impact Analysis template, ADR Review Cycle process, Gap Linking to requirements, and Version Dependency tracking | System Architect | | 1.8.2 | 2026-04-01 | Removed Waiver: Session Identity to enforce strict `publicId` usage | Antigravity | | 1.8.1 | 2026-03-21 | Added Naming Convention Summary & Transition Strategy | Claude | | 1.8.0 | 2026-03-12 | Initial Decision Outcome & Technical Spec | Human Dev | +--- + +**Last Updated:** 2026-04-04 +**Status:** Accepted +**Implementation Target:** v1.9.0+ (Progressive) +**Next Review Date:** 2026-10-04 (6-month regular review) + _สำหรับรายละเอียดการ Implement ดูที่ Implementation Plan ใน `05-07-hybrid-uuid-implementation-plan.md`_ diff --git a/specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md b/specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md index 511561b..84ef144 100644 --- a/specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md +++ b/specs/06-Decision-Records/ADR-020-ai-intelligence-integration.md @@ -3,11 +3,19 @@ **Status:** Proposed **Date:** 2026-04-03 **Version:** 1.8.5 +**Review Cycle:** Core ADR (Review every 6 months or Major Version upgrade) **Decision Makers:** Development Team, AI Integration Lead, System Architect +**Gap Resolution:** Addresses requirement for automated document processing efficiency (Product Vision v1.8.5, Section 3.2) and acceptance criteria for AI-assisted metadata extraction (UAT Criteria, Section 4.7) +**Version Dependency:** +- **Effective From:** v1.9.0 +- **Applies To:** v1.9.0+ (Full implementation) +- **Backward Compatible:** v1.8.5 (API endpoints only) +- **Required For:** v2.0.0 (Core AI features) + **Related Documents:** - [ADR-017: Ollama Data Migration Architecture](./ADR-017-ollama-data-migration.md) -- [ADR-017B: Smart Legacy Document Digitization](./ADR-017B-ollama.md) +- [ADR-017B: AI Document Classification](./ADR-017B-ai-document-classification.md) - [ADR-018: AI Boundary Policy](./ADR-018-ai-boundary.md) — AI Physical Isolation - [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) — UUID Strategy - [n8n Migration Setup Guide](../03-Data-and-Storage/03-05-n8n-migration-setup-guide.md) @@ -83,6 +91,45 @@ --- +## Impact Analysis + +### Affected Components + +| Component | Impact Level | Description | +|-----------|--------------|-------------| +| **Backend Architecture** | **High** | New AiModule, MigrationService, database schema changes | +| **Frontend Components** | **Medium** | DocumentReviewForm, Migration Dashboard enhancements | +| **Infrastructure** | **High** | Admin Desktop AI services, n8n workflows, Docker setup | +| **Security Model** | **Medium** | ADR-018 boundary enforcement, new API endpoints | +| **Database Schema** | **Medium** | migration_logs table, ai_audit_logs table | +| **API Layer** | **Medium** | New AI endpoints, authentication scopes | +| **Testing Framework** | **Medium** | AI accuracy tests, integration tests | +| **Documentation** | **Low** | User guides, admin procedures | + +### Required Changes + +| Change Category | Specific Changes | Priority | +|----------------|------------------|----------| +| **Database** |
  • Create `migration_logs` table (SQL First)
  • Create `ai_audit_logs` table
  • Update data dictionary
| **Critical** | +| **Backend** |
  • Implement AiModule with n8n integration
  • Create MigrationService with business logic
  • Add AI endpoints with CASL guards
  • Update validation layer for AI responses
| **Critical** | +| **Frontend** |
  • Build DocumentReviewForm reusable component
  • Create Admin Migration Dashboard
  • Integrate AI suggestions in RFA form
  • Add confidence score indicators
| **High** | +| **Infrastructure** |
  • Setup n8n on Admin Desktop (Desk-5439)
  • Deploy Ollama with Gemma 4
  • Configure PaddleOCR service
  • Setup Docker containers
| **Critical** | +| **Security** |
  • Implement ADR-018 AI boundaries
  • Add AI-specific authentication scopes
  • Create audit logging for AI interactions
  • Setup rate limiting for AI endpoints
| **Critical** | +| **Testing** |
  • AI accuracy validation tests
  • End-to-end pipeline tests
  • Security boundary verification
  • Performance benchmarking
| **High** | +| **Documentation** |
  • Admin workflow procedures
  • User AI assistance guide
  • Troubleshooting procedures
  • API documentation updates
| **Medium** | + +### Cross-Component Dependencies + +| Dependency | Source | Target | Impact | +|------------|--------|--------|--------| +| **AI Service → Database** | AiService extraction calls | migration_logs table | Data persistence | +| **Frontend → AI Gateway** | DocumentReviewForm | /api/ai/extract endpoint | Real-time suggestions | +| **n8n → Backend API** | AI workflows | Validation endpoints | Human-in-the-loop | +| **Admin Desktop → QNAP NAS** | AI services | DMS backend API | Security boundary | +| **Migration Service → Storage** | Batch processing | File storage system | Document handling | + +--- + ## Architecture Overview ### Core Technology Stack @@ -479,7 +526,7 @@ OUTPUT FORMAT: ### Architecture Decision Records - **[ADR-017: Ollama Data Migration](./ADR-017-ollama-data-migration.md)** — Foundation migration architecture -- **[ADR-017B: Smart Categorization](./ADR-017B-ollama.md)** — AI categorization use cases +- **[ADR-017B: AI Document Classification](./ADR-017B-ai-document-classification.md)** — AI classification use cases - **[ADR-018: AI Boundary Policy](./ADR-018-ai-boundary.md)** — Security isolation requirements (CRITICAL) - **[ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md)** — UUID usage patterns (CRITICAL) @@ -500,16 +547,118 @@ OUTPUT FORMAT: --- +## ADR Review Cycle + +### Review Classification + +**Core ADR Status:** This ADR is classified as a **Core Architecture Decision** due to its fundamental impact on system architecture and security boundaries. + +### Review Schedule + +| Review Type | Frequency | Trigger | Scope | +|-------------|-----------|---------|-------| +| **Regular Review** | Every 6 months | Calendar-based | Validity assessment, performance metrics | +| **Major Version Review** | Every major version (v2.0.0, v3.0.0) | Version planning | Architecture relevance, compatibility | +| **Security Review** | Annually or after security incident | Security audit | ADR-018 compliance, threat model | +| **Technology Review** | As needed | Tech stack changes | AI model updates, infrastructure changes | + +### Review Process + +#### Phase 1: Preparation (1 week before review) +1. **Metrics Collection** + - AI accuracy rates and trends + - Performance benchmarks vs targets + - Security incident reports + - User feedback and satisfaction scores + - Technology stack currency assessment + +2. **Stakeholder Notification** + - Development Team + - AI Integration Lead + - System Architect + - Security Team + - Product Management + +#### Phase 2: Review Meeting (2-hour session) +1. **Current State Assessment** + - Review success metrics achievement + - Identify gaps or deviations from original decision + - Assess technology relevance and currency + +2. **Impact Evaluation** + - Measure actual vs expected business impact + - Evaluate implementation challenges + - Identify unintended consequences + +3. **Future Considerations** + - Emerging AI technologies + - Changing business requirements + - Scalability concerns + - Security landscape changes + +#### Phase 3: Decision & Documentation (1 week after review) +1. **Review Outcomes** + - **No Change:** ADR remains valid and effective + - **Update Required:** Minor adjustments to implementation + - **Supersede:** New ADR created to replace this one + - **Retire:** ADR no longer relevant + +2. **Documentation Updates** + - Update review date and findings + - Add new version notes + - Link to related ADRs if created + - Update implementation roadmap + +### Review Criteria + +| Criterion | Question | Pass/Fail Threshold | +|-----------|----------|---------------------| +| **Effectiveness** | Is AI achieving target accuracy (>85%)? | Pass: ≥85%, Fail: <85% | +| **Performance** | Are processing times within targets (<15s)? | Pass: ≤15s, Fail: >15s | +| **Security** | Is ADR-018 compliance maintained? | Pass: 100% compliant, Fail: Any violation | +| **Adoption** | Are users utilizing AI features? | Pass: >70% adoption, Fail: ≤70% | +| **Maintainability** | Is system supportable with current resources? | Pass: Yes, Fail: Requires additional resources | +| **Technology Currency** | Are AI models and infrastructure up-to-date? | Pass: Current version, Fail: >1 version behind | + +### Review History Template + +``` +## Review Cycle [YYYY-MM-DD] + +**Review Type:** [Regular/Major Version/Security/Technology] +**Reviewers:** [Names and roles] +**Duration:** [Meeting date] + +### Findings +- [Key findings from metrics and assessment] + +### Issues Identified +- [Problems or concerns discovered] + +### Recommendations +- [Action items and decisions] + +### Outcome +- [No Change/Update Required/Supersede/Retire] + +### Next Review Date +- [YYYY-MM-DD] +``` + +--- + ## Document History | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.8.5 | 2026-04-03 | AI Integration Lead | Initial ADR — AI Intelligence Integration Architecture | | 1.8.6 | 2026-04-03 | Tech Lead | Updated — Aligned with detailed task specifications and implementation requirements | +| 1.8.7 | 2026-04-04 | System Architect | Enhanced — Added Impact Analysis template, ADR Review Cycle process, Gap Linking to requirements, and Version Dependency tracking | --- -**Last Updated:** 2026-04-03 +**Last Updated:** 2026-04-04 **Status:** Proposed **Review Date:** 2026-04-10 **Implementation Target:** v1.9.0 +**Next Review Date:** 2026-10-04 (6-month regular review) diff --git a/specs/06-Decision-Records/ADR-REVIEW-PROCESS.md b/specs/06-Decision-Records/ADR-REVIEW-PROCESS.md new file mode 100644 index 0000000..6a7b89a --- /dev/null +++ b/specs/06-Decision-Records/ADR-REVIEW-PROCESS.md @@ -0,0 +1,245 @@ +# ADR Review Process & Version Dependency Policy + +**Version:** 1.0 +**Date:** 2026-04-04 +**Owner:** System Architect + +--- + +## 📋 วัตถุประสงค์ + +เอกสารนี้กำหนดกระบวนการทบทวน ADRs (Architecture Decision Records) และการจัดการ Version Dependencies เพื่อให้มั่นใจว่า: + +1. **คุณภาพ ADRs**: การบันทึกการตัดสินใจมีคุณภาพสม่ำเสมอ +2. **Gap Linking**: ทุก ADR เชื่อมโยงกับ Requirements และ Acceptance Criteria +3. **Impact Analysis**: การประเมินผลกระทบเป็นระบบ +4. **Version Management**: การจัดการ Dependencies ระหว่าง ADRs +5. **Review Cycle**: การทบทวน ADRs ที่สำคัญเป็นระยะ + +--- + +## 🔄 ADR Review Process + +### Review Types + +#### 1. Initial Review (สำหรับ ADR ใหม่) +- **Trigger**: สร้าง ADR ใหม่ +- **Timeline**: ภายใน 7 วันทำการ +- **Reviewers**: System Architect + 2 Senior Developers + Product Owner +- **Goal**: ตรวจสอบความสมบูรณ์และความถูกต้อง + +#### 2. Scheduled Review (ทบทวนตามกำหนด) +- **Trigger**: ทุก 6 เดือน สำหรับ Core ADRs +- **Timeline**: 1-2 วันทำการ +- **Reviewers**: System Architect + Development Team Lead +- **Goal**: ตรวจสอบความยังคงเป็นปัจจุบัน + +#### 3. Triggered Review (ทบทวนตามเหตุการณ์) +- **Trigger**: Major version upgrade, Critical issue, Technology change +- **Timeline**: ภายใน 3 วันทำการ +- **Reviewers**: System Architect + Technical Lead + DevOps +- **Goal**: ประเมินผลกระทบจากการเปลี่ยนแปลง + +### Review Checklist + +#### ✅ Initial Review Checklist + +**Structure & Content:** +- [ ] มี Gap Analysis และเชื่อมโยงกับ Requirements หรือไม่? +- [ ] มี Impact Analysis ครบถ้วนหรือไม่? +- [ ] มี Version Dependency Matrix หรือไม่? +- [ ] Context ชัดเจนและเข้าใจง่ายหรือไม่? +- [ ] มี Options อย่างน้อย 2-3 ทางเลือกพร้อม Pros/Cons หรือไม่? + +**Technical Quality:** +- [ ] Decision Rationale มีเหตุผลรองรับที่ดีหรือไม่? +- [ ] Consequences ระบุทั้งดีและไม่ดีอย่างสมจริงหรือไม่? +- [ ] Implementation Details มีรายละเอียดเพียงพอหรือไม่? +- [ ] Cross-Module Dependencies ถูกต้องหรือไม่? + +**Compliance:** +- [ ] เป็นไปตาม ADR Template ล่าสุดหรือไม่? +- [ ] Link ไปยัง Related Documents ถูกต้องหรือไม่? +- [ ] ไม่ขัดแย้งกับ ADRs ที่มีอยู่หรือไม่? + +#### ✅ Scheduled Review Checklist + +**Relevance:** +- [ ] ADR นี้ยังคงเป็น Core Principle หรือไม่? +- [ ] มีการเปลี่ยนแปลง Technology ที่กระทบหรือไม่? +- [ ] มี Alternative ที่ดีกว่าที่เกิดขึ้นหรือไม่? + +**Issues & Performance:** +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? +- [ ] Performance ยังเป็นไปตามที่คาดหวังหรือไม่? +- [ ] มีปัญหา Maintainability หรือไม่? + +**Updates Needed:** +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? +- [ ] ต้องการ Version increment หรือไม่? +- [ ] ต้องการสร้าง ADR ใหม่ที่แทนที่หรือไม่? + +### Review Workflow + +```mermaid +stateDiagram-v2 + [*] --> Proposed: Create ADR + Proposed --> UnderReview: Initial Review Started + UnderReview --> Accepted: Review Passed + UnderReview --> Rejected: Review Failed + UnderReview --> Revision: Request Changes + + Revision --> UnderReview: Resubmit + + Accepted --> ScheduledReview: 6 Months Later + ScheduledReview --> Accepted: No Changes Needed + ScheduledReview --> UpdateRequired: Changes Needed + ScheduledReview --> Deprecated: No Longer Relevant + + UpdateRequired --> Accepted: Updates Complete + + Accepted --> TriggeredReview: Major Event + TriggeredReview --> Accepted: No Impact + TriggeredReview --> UpdateRequired: Impact Found + + Rejected --> [*] + Deprecated --> [*] +``` + +--- + +## 📊 Version Dependency Management + +### Version Matrix Template + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | Review Date | +|-----|---------|-----------------|---------------------|----------------------|-------------| +| **ADR-XXX** | 1.0 | Core | v1.8.0+ | ✅ Implemented | 2026-08-24 | +| **ADR-YYY** | 2.1 | Required By | v1.8.1+ | 🔄 In Progress | 2026-08-24 | +| **ADR-ZZZ** | 1.5 | Conflicts With | v1.7.x | ⚠️ Must Resolve | 2026-08-24 | + +### Dependency Types + +| Type | Description | Example | +|------|-------------|---------| +| **Core** | ADR พื้นฐานของระบบ | ADR-005 Technology Stack | +| **Required** | ADR ที่จำเป็นต้องมี | ADR-006 Redis for ADR-002 | +| **Used By** | ADR ที่ใช้ ADR อื่น | ADR-002 uses ADR-006 | +| **Conflicts** | ADR ที่ขัดแย้งกัน | Legacy vs New approach | +| **Supersedes** | ADR ที่แทนที่ ADR เก่า | New numbering strategy | + +### Version Compatibility Rules + +#### Minimum Version Policy +- **Core ADRs**: มีผลบังคับใช้ตั้งแต่ v1.8.0 เป็นต้นไป +- **Feature ADRs**: ระบุ version ที่เริ่มมีผลบังคับใช้ +- **Breaking Changes**: ต้อง increment Major version และ Update ทุก ADR ที่เกี่ยวข้อง + +#### Breaking Change Classification +- **🔴 Critical**: ต้อง Update ทันที (Security, Data loss risk) +- **🟡 Important**: ควร Update ภายใน 1 เดือน (Performance, Compatibility) +- **🟢 Minor**: สามารถ Update ตาม schedule ได้ (Documentation, Nice-to-have) + +#### Deprecation Timeline +- **Announcement**: ประกาศล่วงหน้า 3 เดือน +- **Warning**: Log warning ในระบบ 1 เดือนก่อน deprecate +- **Removal**: ลบหรือ deprecate หลังจาก timeline ครบ + +--- + +## 🎯 Core ADRs Definition + +### Core ADRs List (ต้องทบทวนทุก 6 เดือน) + +| ADR | Title | Category | Review Priority | +|-----|-------|----------|-----------------| +| **ADR-001** | Unified Workflow Engine | Core Architecture | 🔴 High | +| **ADR-002** | Document Numbering Strategy | Core Business Logic | 🔴 High | +| **ADR-005** | Technology Stack Selection | Foundation | 🔴 High | +| **ADR-006** | Redis Usage & Caching Strategy | Infrastructure | 🔴 High | +| **ADR-016** | Security & Authentication Strategy | Security | 🔴 High | +| **ADR-019** | Hybrid Identifier Strategy | Data Architecture | 🔴 High | + +### Feature ADRs (ทบทวนตามความจำเป็น) + +- Frontend Architecture ADRs (ADR-011, 012, 013, 014) +- API & Integration ADRs (ADR-008, 010) +- AI & Data Integration ADRs (ADR-017, 018, 020) + +--- + +## 📝 Review Documentation + +### Review Meeting Template + +**Date:** [Date] +**Attendees:** [Names] +**ADR(s) Reviewed:** [List] + +#### Discussion Points +1. **Gap Analysis Validation**: [Notes] +2. **Impact Analysis Review**: [Notes] +3. **Version Dependencies**: [Notes] +4. **Issues Identified**: [List] +5. **Action Items**: [List with owners] + +#### Decisions Made +- [ ] ADR-XXX: Approved as is +- [ ] ADR-YYY: Approved with changes +- [ ] ADR-ZZZ: Requires revision +- [ ] ADR-ABC: Deprecated + +#### Next Steps +1. [Action item 1] - [Owner] - [Due date] +2. [Action item 2] - [Owner] - [Due date] + +### Review Report Template + +```markdown +# ADR Review Report - [Date] + +## Summary +- Total ADRs Reviewed: [X] +- Approved: [Y] +- Requires Changes: [Z] +- Deprecated: [W] + +## Key Findings +1. [Finding 1] +2. [Finding 2] + +## Action Items +[List of action items] + +## Next Review Date +[Date] +``` + +--- + +## 🔧 Tools & Automation + +### Automated Checks +- **Template Validation**: ตรวจสอบว่า ADR ใช้ template ล่าสุด +- **Link Validation**: ตรวจสอบลิงก์ภายในเอกสาร +- **Dependency Matrix**: สร้าง automatic dependency graph +- **Version Consistency**: ตรวจสอบ version numbers ใน matrix + +### Monitoring & Alerts +- **ADR Age Alert**: ADR ที่ไม่ได้ทบทวน > 6 เดือน +- **Broken Dependencies**: ADR ที่อ้างอิงถึง ADR ที่ deprecated +- **Review Due**: แจ้งเตือนก่อน review date 1 สัปดาห์ + +--- + +## 📚 References + +- [Enhanced ADR Template](./ADR-TEMPLATE-enhanced.md) +- [ADR Index](./README.md) +- [Version Management Best Practices](../05-Engineering-Guidelines/05-05-git-conventions.md) + +--- + +**Document Version:** 1.0 +**Last Updated:** 2026-04-04 +**Next Review:** 2026-10-04 diff --git a/specs/06-Decision-Records/ADR-TEMPLATE-enhanced.md b/specs/06-Decision-Records/ADR-TEMPLATE-enhanced.md new file mode 100644 index 0000000..015e7f8 --- /dev/null +++ b/specs/06-Decision-Records/ADR-TEMPLATE-enhanced.md @@ -0,0 +1,168 @@ +# ADR-XXX: [Title] + +**Status:** Proposed +**Date:** YYYY-MM-DD +**Decision Makers:** [Names] +**Related Documents:** +- [Link to relevant specs] + +--- + +## 🎯 Gap Analysis & Purpose + +### ปิด Gap จากเอกสาร: +- **[Document Name]** - [Section/Requirement]: [บรรทัดที่เกี่ยวข้อง] + - เหตุผล: [อธิบายว่า Gap นี้คืออะไร และทำไมต้องแก้ไข] + +### แก้ไขความขัดแย้ง: +- **[Document Name]** vs **[Another Document]**: [อธิบายความขัดแย้ง] + - การตัดสินใจนี้ช่วยแก้ไขโดย: [วิธีการแก้ไข] + +--- + +## Context and Problem Statement + +[Describe the problem...] + +--- + +## Decision Drivers + +- [Driver 1] +- [Driver 2] + +--- + +## Considered Options + +### Option 1: [Name] + +**Pros:** + +- ✅ [Pro 1] + +**Cons:** + +- ❌ [Con 1] + +--- + +## Decision Outcome + +**Chosen Option:** [Option X] + +### Rationale + +[Why this option...] + +--- + +## 🔍 Impact Analysis + +### Affected Components (ส่วนประกอบที่ได้รับผลกระทบ) + +| Component | Level | Impact Description | Required Action | +|-----------|-------|-------------------|-----------------| +| **Backend** | 🔴 High | [รายละเอียดผลกระทบ] | [Action Required] | +| **Frontend** | 🟡 Medium | [รายละเอียดผลกระทบ] | [Action Required] | +| **Database** | 🔴 High | [รายละเอียดผลกระทบ] | [Action Required] | +| **Infrastructure** | 🟢 Low | [รายละเอียดผลกระทบ] | [Action Required] | + +### Required Changes (การเปลี่ยนแปลงที่ต้องดำเนินการ) + +#### 🔴 Critical Changes (ต้องทำทันที) +- [ ] **[Change 1]** - [File/Module]: [Description] +- [ ] **[Change 2]** - [File/Module]: [Description] + +#### 🟡 Important Changes (ควรทำภายใน X วัน) +- [ ] **[Change 3]** - [File/Module]: [Description] +- [ ] **[Change 4]** - [File/Module]: [Description] + +#### 🟢 Nice-to-Have (ทำถ้ามีเวลา) +- [ ] **[Change 5]** - [File/Module]: [Description] + +### Cross-Module Dependencies + +```mermaid +graph TB + ADR[ADR-XXX] --> Module1[Module 1] + ADR --> Module2[Module 2] + ADR --> Module3[Module 3] + + Module1 --> Dependency1[Dependency A] + Module2 --> Dependency2[Dependency B] + Module3 --> Dependency3[Dependency C] +``` + +--- + +## 📋 Version Dependency Matrix + +| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status | +|-----|---------|-----------------|---------------------|----------------------| +| **ADR-XXX** | 1.0 | Core | v1.8.0+ | ✅ Implemented | +| **ADR-YYY** | 2.1 | Required By | v1.8.1+ | 🔄 In Progress | +| **ADR-ZZZ** | 1.5 | Conflicts With | v1.7.x | ⚠️ Must Resolve | + +### Version Compatibility Rules + +- **Minimum Version:** v1.8.0 (ADR มีผลบังคับใช้) +- **Breaking Changes:** ไม่มี (หรือระบุถ้ามี) +- **Deprecation Timeline:** [ระบุถ้ามีการ deprecate] + +--- + +## Implementation Details + +[รายละเอียดการ Implement...] + +--- + +## Consequences + +### Positive + +1. ✅ [Impact 1] + +### Negative + +1. ❌ [Risk 1] + +### Mitigation Strategies + +- [Strategy 1]: [Description] + +--- + +## 🔄 Review Cycle & Maintenance + +### Review Schedule +- **Next Review:** [Date] (6 months from last review) +- **Review Type:** [Scheduled/Triggered/Major Version] +- **Reviewers:** [Names/Roles] + +### Review Checklist +- [ ] ยังคงเป็น Core Principle หรือไม่? +- [ ] มีการเปลี่ยนแปลง Technology ที่กระทบหรือไม่? +- [ ] มี Issue หรือ Bug ที่เกิดจาก ADR นี้หรือไม่? +- [ ] ต้องการ Update หรือ Deprecate หรือไม่? + +### Version History +| Version | Date | Changes | Status | +|---------|------|---------|--------| +| 1.0 | YYYY-MM-DD | Initial version | ✅ Active | +| 1.1 | YYYY-MM-DD | [Changes] | ✅ Active | + +--- + +## Related ADRs + +- [ADR-XXX: Title](./ADR-XXX.md) - [Relationship] +- [ADR-YYY: Title](./ADR-YYY.md) - [Relationship] + +--- + +## References + +- [Reference 1] +- [Reference 2] diff --git a/specs/06-Decision-Records/README.md b/specs/06-Decision-Records/README.md index 3f4708a..adffcd4 100644 --- a/specs/06-Decision-Records/README.md +++ b/specs/06-Decision-Records/README.md @@ -1,19 +1,23 @@ # Architecture Decision Records (ADRs) -**Version:** 1.8.1 -**Last Updated:** 2026-03-16 +**Version:** 1.8.2 +**Last Updated:** 2026-04-04 **Project:** LCBP3-DMS (Laem Chabang Port Phase 3 - Document Management System) --- ## 📋 What are ADRs? -Architecture Decision Records (ADRs) เป็นเอกสารที่บันทึก **ประวัติการตัดสินใจทางสถาปัตยกรรมที่สำคัญ** ของโปรเจกต์ โดยร ะบุ: +Architecture Decision Records (ADRs) เป็นเอกสารที่บันทึก **ประวัติการตัดสินใจทางสถาปัตยกรรมที่สำคัญ** ของโปรเจกต์ โดยระบุ: - **Context**: เหตุผลที่ต้องตัดสินใจ -- **Options Considered**: ทางเลือกที่พิจารณา +- **Gap Analysis**: ปิด Gap จาก Requirements และแก้ไขความขัดแย้ง +- **Impact Analysis**: ผลกระทบต่อ Components และการเปลี่ยนแปลงที่ต้องทำ +- **Options Considered**: ทางเลือกที่พิจารณา (พร้อม Pros/Cons) - **Decision**: สิ่งที่เลือก และเหตุผล +- **Version Dependencies**: ความสัมพันธ์ระหว่าง ADRs - **Consequences**: ผลที่ตามมา (ดีและไม่ดี) +- **Review Cycle**: การทบทวน ADRs เป็นระยะ **วัตถุประสงค์:** @@ -21,6 +25,9 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ 2. ป้องกันการสงสัยว่า "ทำไมถึงออกแบบแบบนี้" ในอนาคต 3. ช่วยในการ Onboard สมาชิกใหม่ 4. บันทึกประวัติศาสตร์การพัฒนาโปรเจกต์ +5. **ใหม่!** เชื่อมโยงการตัดสินใจกับ Requirements และ Acceptance Criteria +6. **ใหม่!** วิเคราะห์ผลกระทบอย่างเป็นระบบ +7. **ใหม่!** จัดการ Version Dependencies ระหว่าง ADRs --- @@ -80,7 +87,7 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ | ADR | Title | Status | Date | Summary | | ----------------------------------------------- | ---------------------------------- | ------------- | ---------- | ---------------------------------------------------------------------------- | | [ADR-017](./ADR-017-ollama-data-migration.md) | Ollama Data Migration Architecture | ✅ Accepted | 2026-02-26 | On-premise AI (Ollama) สำหรับ Migration 20,000+ PDFs พร้อม Validation Layer | -| [ADR-017B](./ADR-017B-ollama.md) | Smart Legacy Document Digitization | ✅ Accepted | 2026-03-27 | AI-powered categorization สำหรับเอกสารเก่า ตาม ADR-018 (AI Isolation) | +| [ADR-017B](./ADR-017B-ai-document-classification.md) | AI Document Classification | ✅ Accepted | 2026-03-27 | AI-powered document classification ตาม ADR-018 (AI Isolation) | | [ADR-018](./ADR-018-ai-boundary.md) | AI Boundary Policy | ✅ Accepted | 2026-03-27 | Physical Isolation + API-only communication (Zero Trust for AI) | | [ADR-020](./ADR-020-ai-intelligence-integration.md) | AI Intelligence Integration Architecture | 🔄 Proposed | 2026-04-03 | Unified AI Pipeline สำหรับ RFA-First (Legacy Migration + New Ingestion) | @@ -142,16 +149,19 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ ### ADR Structure -แต่ละ ADR มีโครงสร้างดังนี้: +แต่ละ ADR มีโครงสร้างดังนี้ (Enhanced Template v1.2): -1. **Status**: Accepted, Proposed, Deprecated, Superseded +1. **Gap Analysis & Purpose**: เชื่อมโยงกับ Requirements และแก้ไขความขัดแย้ง 2. **Context**: ปัญหาหรือสถานการณ์ที่ต้องตัดสินใจ 3. **Decision Drivers**: ปัจจัยที่มีผลต่อการตัดสินใจ 4. **Considered Options**: ทางเลือกที่พิจารณา (พร้อม Pros/Cons) 5. **Decision Outcome**: สิ่งที่เลือก และเหตุผล -6. **Consequences**: ผลที่ตามมา (Positive/Negative/Mitigation) -7. **Implementation Details**: รายละเอียดการ Implement (Code examples) -8. **Related ADRs**: ADR อื่นที่เกี่ยวข้อง +6. **🔍 Impact Analysis**: ผลกระทบต่อ Components และ Required Changes +7. **📋 Version Dependency Matrix**: ความสัมพันธ์ระหว่าง ADRs และ Version Compatibility +8. **Consequences**: ผลที่ตามมา (Positive/Negative/Mitigation) +9. **🔄 Review Cycle & Maintenance**: กำหนดการทบทวนและ Version History +10. **Implementation Details**: รายละเอียดการ Implement (Code examples) +11. **Related ADRs**: ADR อื่นที่เกี่ยวข้อง ### Reading Tips @@ -162,6 +172,39 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ --- +## 🆕 Enhanced Template & Review Process (v1.8.2) + +### New Features + +#### 🎯 Gap Analysis & Purpose +- **ปิด Gap จากเอกสาร**: ระบุว่า ADR นี้แก้ไข Requirement ใด +- **แก้ไขความขัดแย้ง**: ระบุว่า ADR นี้แก้ไขความขัดแย้งระหว่าง Requirements ใด + +#### 🔍 Impact Analysis +- **Affected Components**: ระดับผลกระทบ (🔴 High, 🟡 Medium, 🟢 Low) +- **Required Changes**: แบ่งเป็น Critical/Important/Nice-to-Have +- **Cross-Module Dependencies**: Mermaid diagram แสดงความสัมพันธ์ + +#### 📋 Version Dependency Matrix +- **Dependency Types**: Core, Required, Used By, Conflicts, Supersedes +- **Version Compatibility**: ระบุ version ที่ ADR มีผลบังคับใช้ +- **Implementation Status**: ✅ Implemented, 🔄 In Progress, ⚠️ Must Resolve + +#### 🔄 Review Cycle & Maintenance +- **Review Schedule**: ทบทวนทุก 6 เดือนสำหรับ Core ADRs +- **Review Checklist**: ตรวจสอบความเป็นปัจจุบัน +- **Version History**: Tracking การเปลี่ยนแปลงของ ADR + +### Review Process + +- **Initial Review**: 7 วันทำการสำหรับ ADR ใหม่ +- **Scheduled Review**: ทุก 6 เดือนสำหรับ Core ADRs +- **Triggered Review**: เมื่อมี Major version upgrade หรือ Critical issue + +📖 **ดูรายละเอียด**: [ADR Review Process](./ADR-REVIEW-PROCESS.md) + +--- + ## 🆕 Creating New ADRs ### When to Create an ADR? @@ -182,68 +225,22 @@ Architecture Decision Records (ADRs) เป็นเอกสารที่บ ### ADR Template -```markdown -# ADR-XXX: [Title] +ใช้ **Enhanced ADR Template v1.2** สำหรับ ADR ใหม่ทั้งหมด: -**Status:** Proposed -**Date:** YYYY-MM-DD -**Decision Makers:** [Names] -**Related Documents:** [Links] +📋 **Template**: [ADR-TEMPLATE-enhanced.md](./ADR-TEMPLATE-enhanced.md) ---- +**Key Sections (ต้องรวมทุกอย่าง):** +- ✅ Gap Analysis & Purpose +- ✅ Impact Analysis (Components + Required Changes + Dependencies) +- ✅ Version Dependency Matrix +- ✅ Review Cycle & Maintenance +- ✅ Cross-Module Dependencies (Mermaid diagram) -## Context and Problem Statement - -[Describe the problem...] - ---- - -## Decision Drivers - -- [Driver 1] -- [Driver 2] - ---- - -## Considered Options - -### Option 1: [Name] - -**Pros:** - -- ✅ [Pro 1] - -**Cons:** - -- ❌ [Con 1] - ---- - -## Decision Outcome - -**Chosen Option:** [Option X] - -### Rationale - -[Why this option...] - ---- - -## Consequences - -### Positive - -1. ✅ [Impact 1] - -### Negative - -1. ❌ [Risk 1] - ---- - -## Related ADRs - -- [ADR-XXX: Title](./ADR-XXX.md) +**Quick Start:** +```bash +# Copy template +cp ADR-TEMPLATE-enhanced.md ADR-XXX-title.md +# Edit with your specific content ``` --- @@ -372,5 +369,14 @@ graph TB --- -**Version:** 1.8.0 -**Last Review:** 2026-02-24 +**Version:** 1.8.2 (Enhanced Template + Review Process) +**Last Review:** 2026-04-04 +**Next Review:** 2026-10-04 + +--- + +## 📚 Enhanced Documentation + +- **[Enhanced ADR Template](./ADR-TEMPLATE-enhanced.md)** - Template ใหม่พร้อม Impact Analysis +- **[ADR Review Process](./ADR-REVIEW-PROCESS.md)** - กระบวนการทบทวนและ Version Management +- **[Version Dependency Matrix](./VERSION-DEPENDENCIES.md)** - ความสัมพันธ์ระหว่าง ADRs (สร้างในอนาคต) diff --git a/specs/08-Tasks/Task BE-AI-01.md b/specs/08-Tasks/Task BE-AI-01.md index 246c36e..1b1dd33 100644 --- a/specs/08-Tasks/Task BE-AI-01.md +++ b/specs/08-Tasks/Task BE-AI-01.md @@ -20,34 +20,16 @@ - Webhook endpoint: `/webhook/ai-processing` - Environment variables: `N8N_BASIC_AUTH_USER`, `N8N_BASIC_AUTH_PASSWORD` - [ ] **Ollama Service:** - - Pull model: `gemma:9b` (GPU optimized, higher accuracy) + - Pull model: `gemma4:e4b` (GPU optimized, higher accuracy) - API endpoint: `http://localhost:11434` - Health check: `GET /api/tags` - Memory requirement: Minimum 8GB VRAM for 9B model - - ollama run gemma4:9b-q5_K_M / gemma4:9b-q4_K_M - - สร้างไฟล์ %USERPROFILE%\.ollama\config -```config -# ใช้ GPU เป็นหลัก -gpu: true -num_gpu: 1 - -# เปิด KV cache เพื่อให้ตอบเร็วขึ้น -kv_cache: true - -# จำกัด batch size ให้เหมาะกับ VRAM 8GB -gpu_batch_size: 512 - -# ปรับ num_thread ให้เหมาะกับ CPU 6–8 คอร์ -num_thread: 6 - -# เปิด mmap เพื่อโหลดโมเดลเร็วขึ้น -mmap: true - -# ปรับ max_seq_len ให้เหมาะกับงาน DMS -max_seq_len: 4096 - -# ปรับ temp ต่ำเพื่อให้ผลลัพธ์เสถียร -temperature: 0.2 + - ollama run gemma4 + - ตั้ง Windows System Environment Variables หรือใน PowerShell: + - [System.Environment]::SetEnvironmentVariable('OLLAMA_HOST', '0.0.0.0', 'User') + - [System.Environment]::SetEnvironmentVariable('OLLAMA_KEEP_ALIVE', '30m', 'User') + - [System.Environment]::SetEnvironmentVariable("OLLAMA_NUM_GPU", "1", "User") + - [System.Environment]::SetEnvironmentVariable("OLLAMA_NUM_THREAD", "8", "User") ``` - [ ] **PaddleOCR Service:** diff --git a/specs/08-Tasks/Task BE-API-01.md b/specs/08-Tasks/Task BE-API-01.md new file mode 100644 index 0000000..7477157 --- /dev/null +++ b/specs/08-Tasks/Task BE-API-01.md @@ -0,0 +1,274 @@ +# Task BE-API-01: API Design Strategy Implementation + +**Phase:** Backend API Standardization +**ADR Compliance:** ADR-003 (API Design Strategy), ADR-019 (UUID Strategy) +**Priority:** 🟡 Important - API Consistency & Developer Experience + +> **Context:** การ implement Hybrid REST + Action Endpoints ตาม ADR-003 เพื่อให้ API สอดคล้องกันทั่วทั้งระบบ + +--- + +## 📋 Implementation Tasks + +### **API-1.1: Base Controller & Patterns** +- [ ] **Create Base Controller Class:** + - File: `backend/src/common/controllers/base.controller.ts` + - Features: Standard CRUD operations, pagination, filtering + - Methods: `findAll()`, `findOne(uuid)`, `create()`, `update(uuid)`, `remove(uuid)` +- [ ] **Create Standard Response DTOs:** + - File: `backend/src/common/dto/response.dto.ts` + - Types: `ApiResponse`, `PaginatedResponse`, `ActionResponse` + - Include meta information: timestamp, pagination, version +- [ ] **Create Action Endpoint Decorator:** + - File: `backend/src/common/decorators/action-endpoint.decorator.ts` + - Purpose: Mark business action endpoints for Swagger documentation + - Usage: `@ActionEndpoint('submit', 'Submit correspondence for routing')` + +### **API-1.2: Correspondence API Refactor** +- [ ] **Update Correspondence Controller:** + - File: `backend/src/modules/correspondence/correspondence.controller.ts` + - REST endpoints: GET, POST, PUT, PATCH, DELETE `/correspondences` + - Action endpoints: + - POST `/correspondences/:uuid/submit` + - POST `/correspondences/:uuid/approve` + - POST `/correspondences/:uuid/reject` + - POST `/correspondences/:uuid/forward` +- [ ] **Create Action DTOs:** + - File: `backend/src/modules/correspondence/dto/correspondence-actions.dto.ts` + - DTOs: `SubmitDto`, `ApproveDto`, `RejectDto`, `ForwardDto` + - Validation: Business rules for each action +- [ ] **Update Correspondence Service:** + - Methods: `submit()`, `approve()`, `reject()`, `forward()` + - Integration: Workflow engine transitions + - Error handling: Business exceptions for invalid states + +### **API-1.3: RFA API Implementation** +- [ ] **Create RFA Controller:** + - File: `backend/src/modules/rfa/rfa.controller.ts` + - REST endpoints: Standard CRUD for RFAs + - Action endpoints: + - POST `/rfa/:uuid/submit-for-review` + - POST `/rfa/:uuid/approve` + - POST `/rfa/:uuid/request-changes` + - POST `/rfa/:uuid/final-approve` +- [ ] **Create RFA Action DTOs:** + - File: `backend/src/modules/rfa/dto/rfa-actions.dto.ts` + - DTOs: `SubmitForReviewDto`, `ApproveDto`, `RequestChangesDto` + - Include: Comments, attachments, change requests +- [ ] **Update RFA Service:** + - Workflow integration: Document numbering, state transitions + - Business logic: Review cycles, approval chains + - Notifications: Trigger email/LINE notifications + +### **API-1.4: API Documentation & Testing** +- [ ] **Update Swagger Configuration:** + - File: `backend/src/main.ts` + - Group endpoints by module and type (REST vs Actions) + - Add examples for all DTOs and responses + - Configure security: JWT Bearer authentication +- [ ] **Create API Client Library:** + - File: `frontend/lib/api/client.ts` + - Methods: Typed API calls for all endpoints + - Error handling: Parse structured error responses + - Type safety: TypeScript interfaces for all DTOs +- [ ] **Add Integration Tests:** + - Directory: `backend/test/api/` + - Coverage: All REST and action endpoints + - Scenarios: Success cases, error cases, permission tests + - Tools: Jest, Supertest + +### **API-1.5: Performance & Optimization** +- [ ] **Implement Response Caching:** + - Master data endpoints: Organizations, projects, types + - Cache keys: `master:${entity}:${projectId}` + - TTL: 1 hour for master data, 15 minutes for dynamic data +- [ ] **Add Request Validation:** + - DTO validation: class-validator decorators + - Business rule validation: Custom validators + - Rate limiting: By user role and endpoint type +- [ ] **Database Query Optimization:** + - Pagination: Limit/offset with total count + - Filtering: Dynamic where clauses + - Relations: Eager loading for common queries + +--- + +## 🔧 Technical Implementation Details + +### Base Controller Structure + +```typescript +// File: backend/src/common/controllers/base.controller.ts +export abstract class BaseController { + constructor( + protected readonly service: BaseService, + protected readonly entityName: string + ) {} + + @Get() + @ApiResponse({ status: 200, description: `List ${entityName}` }) + async findAll(@Query() query: PaginationDto): Promise> { + return this.service.findAll(query); + } + + @Get(':uuid') + @ApiResponse({ status: 200, description: `Get ${entityName} by UUID` }) + async findOne(@Param('uuid') uuid: string): Promise> { + return this.service.findOne(uuid); + } + + @Post() + @ApiResponse({ status: 201, description: `Create ${entityName}` }) + async create(@Body() dto: CreateDto): Promise> { + return this.service.create(dto); + } + + // ... other standard methods +} +``` + +### Action Endpoint Pattern + +```typescript +// File: backend/src/modules/correspondence/correspondence.controller.ts +@Controller('correspondences') +@ApiTags('Correspondences') +export class CorrespondenceController extends BaseController { + + @Post(':uuid/submit') + @ActionEndpoint('submit', 'Submit correspondence for routing') + @ApiResponse({ status: 200, description: 'Correspondence submitted successfully' }) + async submit( + @Param('uuid') uuid: string, + @Body() dto: SubmitCorrespondenceDto, + @CurrentUser() user: User + ): Promise { + return this.correspondenceService.submit(uuid, dto, user.id); + } + + @Post(':uuid/approve') + @ActionEndpoint('approve', 'Approve correspondence') + async approve( + @Param('uuid') uuid: string, + @Body() dto: ApproveCorrespondenceDto, + @CurrentUser() user: User + ): Promise { + return this.correspondenceService.approve(uuid, dto, user.id); + } +} +``` + +### Frontend API Client + +```typescript +// File: frontend/lib/api/correspondence.ts +export class CorrespondenceApi { + private client = new ApiClient('/correspondences'); + + // REST operations + async findAll(query?: CorrespondenceListQuery): Promise { + return this.client.get('', { params: query }); + } + + async findOne(uuid: string): Promise { + return this.client.get(`/${uuid}`); + } + + async create(dto: CreateCorrespondenceDto): Promise { + return this.client.post('', dto); + } + + // Action operations + async submit(uuid: string, dto: SubmitCorrespondenceDto): Promise { + return this.client.post(`/${uuid}/submit`, dto); + } + + async approve(uuid: string, dto: ApproveCorrespondenceDto): Promise { + return this.client.post(`/${uuid}/approve`, dto); + } +} +``` + +--- + +## 📊 Success Criteria + +### Functional Requirements +- [ ] All correspondence endpoints follow hybrid pattern +- [ ] RFA endpoints implemented with actions +- [ ] Swagger documentation complete with examples +- [ ] Frontend API client typed and tested +- [ ] Integration tests cover all scenarios + +### Non-Functional Requirements +- [ ] API response times < 200ms (p90) +- [ ] Error responses consistent and user-friendly +- [ ] Documentation auto-generated and up-to-date +- [ ] Type safety across frontend and backend +- [ ] Rate limiting and security implemented + +### Compliance Requirements +- [ ] ADR-003 patterns followed consistently +- [ ] ADR-019 UUID strategy implemented +- [ ] ADR-007 error handling integrated +- [ ] ADR-010 logging for all API calls + +--- + +## 🚀 Deployment & Rollout + +### Phase 1: Backend Implementation (Week 1-2) +- Implement base controller and patterns +- Refactor correspondence API +- Create comprehensive tests + +### Phase 2: Frontend Integration (Week 3) +- Update API client library +- Implement error handling UI +- Add integration tests + +### Phase 3: Documentation & Monitoring (Week 4) +- Complete Swagger documentation +- Add API monitoring +- Performance testing and optimization + +--- + +## 📋 Dependencies & Prerequisites + +### Must Have +- ✅ ADR-003 Approved +- ✅ ADR-007 Error Handling Strategy +- ✅ Base infrastructure (NestJS, TypeORM, Redis) +- ✅ Authentication system (JWT, CASL) + +### Nice to Have +- API analytics dashboard +- Automated API testing pipeline +- Client code generation + +--- + +## 🔄 Review & Acceptance + +### Code Review Checklist +- [ ] All endpoints follow hybrid pattern +- [ ] DTOs properly validated +- [ ] Error handling consistent +- [ ] Documentation complete +- [ ] Tests comprehensive +- [ ] Performance optimized + +### Acceptance Criteria +- [ ] API documentation available at `/api/docs` +- [ ] All tests passing (>90% coverage) +- [ ] Performance benchmarks met +- [ ] Security scan passed +- [ ] Frontend integration verified + +--- + +**Owner:** Backend Team Lead +**Estimated Effort:** 3-4 weeks (1 developer) +**Risk Level:** Medium (API breaking changes) +**Rollback Plan:** Version previous API endpoints alongside new ones diff --git a/specs/08-Tasks/Task BE-DB-01.md b/specs/08-Tasks/Task BE-DB-01.md new file mode 100644 index 0000000..90fc974 --- /dev/null +++ b/specs/08-Tasks/Task BE-DB-01.md @@ -0,0 +1,406 @@ +# Task BE-DB-01: Database Schema Strategy Implementation + +**Phase:** Database Standardization & Optimization +**ADR Compliance:** ADR-004 (Database Schema Design), ADR-009 (Migration Strategy), ADR-019 (UUID Strategy) +**Priority:** 🟡 Important - Data Integrity & Performance + +> **Context:** การ implement Selective Normalization Patterns ตาม ADR-004 เพื่อให้ database schema สอดคล้องกันและมีประสิทธิภาพ + +--- + +## 📋 Implementation Tasks + +### **DB-1.1: Base Entity Pattern Implementation** +- [ ] **Create Base Entity Classes:** + - File: `backend/src/common/entities/base.entity.ts` + - Features: UUID, timestamps, soft delete, audit fields + - Inheritance: All entities extend from base +- [ ] **Create UuidBaseEntity (ADR-019):** + - File: `backend/src/common/entities/uuid-base.entity.ts` + - Properties: `id` (INT PK), `uuid` (UUID public), `createdAt`, `updatedAt` + - Decorators: `@Exclude()` for internal ID, `@Expose()` for UUID +- [ ] **Update All Entity Classes:** + - Directory: `backend/src/modules/*/entities/` + - Extend from base entities + - Add proper decorators and relationships + - Ensure UUID handling compliance + +### **DB-1.2: Audit Trail Implementation** +- [ ] **Create Audit Log Entity:** + - File: `backend/src/common/entities/audit-log.entity.ts` + - Table: `audit_logs` + - Fields: `tableName`, `recordId`, `action`, `oldValues`, `newValues`, `userId` + - Indexes: Performance optimization for queries +- [ ] **Create Audit Trail Service:** + - File: `backend/src/common/services/audit-trail.service.ts` + - Methods: `logCreate()`, `logUpdate()`, `logDelete()`, `logSoftDelete()` + - Features: Automatic change detection, JSON diff, user tracking +- [ ] **Implement Audit Interceptor:** + - File: `backend/src/common/interceptors/audit.interceptor.ts` + - Trigger: Before/After database operations + - Scope: All entity operations (CRUD) + - Performance: Async logging to avoid blocking + +### **DB-1.3: Workflow State Management** +- [ ] **Create Workflow State Entities:** + - File: `backend/src/modules/workflow/entities/` + - Entities: `WorkflowState`, `WorkflowInstance`, `WorkflowHistory` + - Relationships: State machine definitions and instances +- [ ] **Implement State Transition Logic:** + - File: `backend/src/modules/workflow/services/workflow-state.service.ts` + - Methods: `validateTransition()`, `executeTransition()`, `getCurrentState()` + - Features: Business rule validation, history tracking +- [ ] **Create Workflow History Tables:** + - Tables: `workflow_histories`, `correspondence_histories`, `rfa_histories` + - Purpose: Track all state changes with context + - Features: JSON snapshots, user attribution, timestamps + +### **DB-1.4: Schema Optimization & Indexing** +- [ ] **Analyze Current Query Patterns:** + - Tools: MySQL slow query log, EXPLAIN plans + - Focus: Correspondence list, RFA workflows, user permissions + - Document: Current performance bottlenecks +- [ ] **Implement Strategic Indexes:** + - Foreign key indexes: All FK columns indexed + - Composite indexes: Common query patterns + - Partial indexes: Active records only (WHERE deleted_at IS NULL) +- [ ] **Optimize Table Structures:** + - Review: Data types, column sizes, NULL constraints + - Normalize: Where beneficial for integrity + - Denormalize: Where beneficial for performance + +### **DB-1.5: Migration & Evolution Strategy** +- [ ] **Create Migration Scripts:** + - Directory: `backend/src/database/migrations/` + - Format: SQL scripts (following ADR-009) + - Features: Rollback capability, dependency tracking +- [ ] **Implement Schema Validation:** + - File: `backend/src/common/validators/schema.validator.ts` + - Checks: Naming conventions, required fields, relationships + - Automation: Pre-commit hooks, CI validation +- [ ] **Create Database Documentation:** + - Auto-generation: From TypeORM entities + - Format: Markdown with ER diagrams + - Include: Field descriptions, relationships, indexes + +--- + +## 🔧 Technical Implementation Details + +### Base Entity Implementation + +```typescript +// File: backend/src/common/entities/base.entity.ts +import { CreateDateColumn, UpdateDateColumn, DeleteDateColumn, Column } from 'typeorm'; +import { UuidBaseEntity } from './uuid-base.entity'; + +export abstract class BaseEntity extends UuidBaseEntity { + @CreateDateColumn({ + type: 'timestamp', + name: 'created_at', + comment: 'Record creation time' + }) + createdAt: Date; + + @UpdateDateColumn({ + type: 'timestamp', + name: 'updated_at', + comment: 'Last update time' + }) + updatedAt: Date; + + @DeleteDateColumn({ + type: 'datetime', + name: 'deleted_at', + nullable: true, + comment: 'Soft delete timestamp' + }) + deletedAt?: Date; + + @Column({ + type: 'int', + name: 'created_by', + nullable: true, + comment: 'User who created record' + }) + createdBy?: number; + + @Column({ + type: 'int', + name: 'updated_by', + nullable: true, + comment: 'User who last updated record' + }) + updatedBy?: number; +} +``` + +### UuidBaseEntity (ADR-019) + +```typescript +// File: backend/src/common/entities/uuid-base.entity.ts +import { PrimaryGeneratedColumn, Column, Exclude, Expose } from 'typeorm'; + +export abstract class UuidBaseEntity { + @PrimaryGeneratedColumn() + @Exclude() + id: number; + + @Column({ + type: 'uuid', + unique: true, + name: 'uuid', + comment: 'Public UUID identifier (ADR-019)' + }) + @Expose({ name: 'id' }) // Expose UUID as 'id' in API + uuid: string; +} +``` + +### Audit Trail Service + +```typescript +// File: backend/src/common/services/audit-trail.service.ts +@Injectable() +export class AuditTrailService { + constructor( + @InjectRepository(AuditLog) + private auditLogRepo: Repository + ) {} + + async logCreate(entity: BaseEntity, userId: number): Promise { + const auditLog = this.auditLogRepo.create({ + tableName: entity.constructor.name, + recordId: entity.id, + recordUuid: entity.uuid, + action: 'CREATE', + newValues: entity, + userId + }); + await this.auditLogRepo.save(auditLog); + } + + async logUpdate( + entity: BaseEntity, + oldValues: any, + newValues: any, + userId: number + ): Promise { + const changedFields = this.getChangedFields(oldValues, newValues); + + const auditLog = this.auditLogRepo.create({ + tableName: entity.constructor.name, + recordId: entity.id, + recordUuid: entity.uuid, + action: 'UPDATE', + oldValues, + newValues, + changedFields, + userId + }); + await this.auditLogRepo.save(auditLog); + } + + private getChangedFields(old: any, new: any): string[] { + const changes: string[] = []; + for (const key in new) { + if (old[key] !== new[key]) { + changes.push(key); + } + } + return changes; + } +} +``` + +### Audit Interceptor + +```typescript +// File: backend/src/common/interceptors/audit.interceptor.ts +@Injectable() +export class AuditInterceptor implements NestInterceptor { + constructor(private auditService: AuditTrailService) {} + + async intercept(context: ExecutionContext, next: CallHandler): Promise> { + const request = context.switchToHttp().getRequest(); + const userId = request.user?.id; + + return next.handle().pipe( + tap(async (result) => { + // Log successful operations + if (result && typeof result === 'object') { + await this.auditService.logCreate(result, userId); + } + }), + catchError(async (error) => { + // Log failed operations + console.error('Operation failed:', error); + throw error; + }) + ); + } +} +``` + +### Workflow State Management + +```typescript +// File: backend/src/modules/workflow/entities/workflow-instance.entity.ts +@Entity('workflow_instances') +export class WorkflowInstance extends BaseEntity { + @Column({ type: 'varchar', length: 50 }) + workflowCode: string; + + @Column({ type: 'varchar', length: 50 }) + entityType: string; // 'correspondence', 'rfa', etc. + + @Column({ type: 'int' }) + entityId: number; + + @Column({ type: 'varchar', length: 50 }) + currentState: string; + + @Column({ + type: 'enum', + enum: ['ACTIVE', 'COMPLETED', 'CANCELLED'], + default: 'ACTIVE' + }) + status: string; + + @Column({ type: 'json', nullable: true }) + context: any; // Workflow-specific context + + // Relationships + @ManyToOne(() => WorkflowState) + @JoinColumn({ + name: 'workflow_code', + referencedColumnName: 'workflow_code', + referencedColumnName: 'state_name' + }) + currentStateDefinition: WorkflowState; + + @OneToMany(() => WorkflowHistory, history => history.instance) + histories: WorkflowHistory[]; +} +``` + +### Schema Migration Example + +```sql +-- File: backend/src/database/migrations/001_add_audit_trail.sql + +-- Create audit log table +CREATE TABLE audit_logs ( + id BIGINT PRIMARY KEY AUTO_INCREMENT, + table_name VARCHAR(50) NOT NULL, + record_id INT NOT NULL, + record_uuid UUID NULL, + action ENUM('CREATE', 'UPDATE', 'DELETE', 'SOFT_DELETE') NOT NULL, + old_values JSON NULL, + new_values JSON NULL, + changed_fields JSON NULL, + user_id INT NULL, + ip_address VARCHAR(45) NULL, + user_agent TEXT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + + INDEX idx_audit_table_record (table_name, record_id), + INDEX idx_audit_user (user_id, created_at), + INDEX idx_audit_created (created_at), + INDEX idx_audit_record_uuid (record_uuid) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci +COMMENT='Audit trail for all data changes'; + +-- Add base columns to existing tables (example) +ALTER TABLE correspondences +ADD COLUMN created_by INT NULL COMMENT 'User who created record', +ADD COLUMN updated_by INT NULL COMMENT 'User who last updated record', +ADD INDEX idx_correspondences_created_by (created_by), +ADD INDEX idx_correspondences_updated_by (updated_by); +``` + +--- + +## 📊 Success Criteria + +### Functional Requirements +- [ ] All entities extend from base classes +- [ ] Audit trail captures all data changes +- [ ] Workflow state management implemented +- [ ] Database performance optimized +- [ ] Migration strategy in place + +### Non-Functional Requirements +- [ ] Query response times < 200ms (p90) +- [ ] Audit logging doesn't impact performance +- [ ] Schema validation automated +- [ ] Documentation auto-generated +- [ ] Zero data loss during migrations + +### Compliance Requirements +- [ ] ADR-004 patterns followed consistently +- [ ] ADR-009 migration strategy implemented +- [ ] ADR-019 UUID strategy enforced +- [ ] Audit trail meets compliance requirements + +--- + +## 🚀 Deployment & Rollout + +### Phase 1: Base Pattern Implementation (Week 1) +- Create base entity classes +- Update core entities (users, organizations, projects) +- Implement audit trail foundation + +### Phase 2: Workflow & Audit Implementation (Week 2-3) +- Implement workflow state management +- Add audit logging to all modules +- Create migration scripts + +### Phase 3: Optimization & Documentation (Week 4) +- Performance optimization and indexing +- Schema validation automation +- Documentation generation + +--- + +## 📋 Dependencies & Prerequisites + +### Must Have +- ✅ ADR-004 Approved +- ✅ ADR-009 Migration Strategy +- ✅ ADR-019 UUID Strategy +- ✅ TypeORM configuration +- ✅ Database backup strategy + +### Nice to Have +- Database performance monitoring +- Automated schema testing +- Visual ER diagram generation + +--- + +## 🔄 Review & Acceptance + +### Code Review Checklist +- [ ] All entities follow base pattern +- [ ] Audit logging comprehensive +- [ ] Workflow state correct +- [ ] Indexes optimized +- [ ] Migration scripts safe +- [ ] Documentation complete + +### Acceptance Criteria +- [ ] All entities extend base classes +- [ ] Audit trail captures 100% of changes +- [ ] Performance benchmarks met +- [ ] Migration scripts tested +- [ ] Schema validation passes +- [ ] Documentation generated + +--- + +**Owner:** Backend Team Lead + DBA +**Estimated Effort:** 4 weeks (1-2 developers) +**Risk Level:** High (Database schema changes) +**Rollback Plan:** Full database backups, migration rollback scripts diff --git a/specs/08-Tasks/Task BE-ERR-01.md b/specs/08-Tasks/Task BE-ERR-01.md new file mode 100644 index 0000000..69e7b0c --- /dev/null +++ b/specs/08-Tasks/Task BE-ERR-01.md @@ -0,0 +1,466 @@ +# Task BE-ERR-01: Error Handling & Recovery Strategy Implementation + +**Phase:** Error Handling Standardization +**ADR Compliance:** ADR-007 (Error Handling & Recovery), ADR-010 (Logging & Monitoring) +**Priority:** 🟡 Important - User Experience & Debuggability + +> **Context:** การ implement Layered Error Handling ตาม ADR-007 เพื่อให้ error messages สอดคล้องกันและมีประโยชน์ต่อ users + +--- + +## 📋 Implementation Tasks + +### **ERR-1.1: Exception Hierarchy Implementation** +- [ ] **Create Base Exception Classes:** + - File: `backend/src/common/exceptions/base.exception.ts` + - Classes: `BaseException`, `ValidationException`, `BusinessException` + - Features: Error classification, user messages, recovery actions +- [ ] **Create Specific Exception Types:** + - File: `backend/src/common/exceptions/` + - Types: `PermissionException`, `SystemException`, `WorkflowException` + - Properties: Error codes, severity levels, recovery guidance +- [ ] **Implement Error Severity System:** + - Enum: `ErrorSeverity` (LOW, MEDIUM, HIGH, CRITICAL) + - Logic: Different handling based on severity + - Integration: Logging levels and alerting + +### **ERR-1.2: Global Exception Filter** +- [ ] **Create Global Exception Filter:** + - File: `backend/src/common/filters/global-exception.filter.ts` + - Features: Layered error processing, information control + - Integration: NestJS exception handling pipeline +- [ ] **Implement Error Classification:** + - Logic: Categorize errors by type and severity + - Response format: Standardized error responses + - Development vs Production: Different detail levels +- [ ] **Add Error Logging Integration:** + - Integration: ADR-010 logging strategy + - Context: Request information, user details, stack traces + - Performance: Async logging to avoid blocking + +### **ERR-1.3: Service Layer Error Handling** +- [ ] **Update Correspondence Service:** + - File: `backend/src/modules/correspondence/correspondence.service.ts` + - Methods: Use custom exceptions instead of generic errors + - Validation: Business rule validation with proper errors + - Recovery: Provide actionable error messages +- [ ] **Update RFA Service:** + - File: `backend/src/modules/rfa/rfa.service.ts` + - Workflow errors: Invalid transitions, permission issues + - Document numbering: Duplicate numbers, format errors + - Integration: Workflow engine error handling +- [ ] **Update All Other Services:** + - Directory: `backend/src/modules/*/services/` + - Pattern: Consistent error handling across all modules + - Validation: Input validation with detailed errors + +### **ERR-1.4: Frontend Error Handling** +- [ ] **Create Error Display Component:** + - File: `frontend/components/common/error-display.tsx` + - Features: User-friendly error messages, recovery actions + - Styling: Consistent with design system + - Localization: Support for Thai/English messages +- [ ] **Update API Client Error Handling:** + - File: `frontend/lib/api/client.ts` + - Logic: Parse structured error responses + - Actions: Display appropriate recovery options + - Integration: Global error state management +- [ ] **Implement Error Recovery UI:** + - Features: Retry buttons, alternative actions, help links + - Context: Different recovery flows per error type + - User Experience: Clear guidance and next steps + +### **ERR-1.5: Error Catalog & Documentation** +- [ ] **Create Error Catalog:** + - File: `docs/error-catalog.md` + - Content: All error codes, messages, recovery actions + - Format: Structured table with examples + - Maintenance: Process for adding new errors +- [ ] **Implement Error Analytics:** + - Tracking: Error rates, patterns, user impact + - Dashboard: Error monitoring and alerting + - Integration: ADR-010 monitoring strategy +- [ ] **Create Error Handling Guidelines:** + - Document: Developer guidelines for error handling + - Examples: Common patterns and best practices + - Review: Code review checklist for errors + +--- + +## 🔧 Technical Implementation Details + +### Exception Hierarchy + +```typescript +// File: backend/src/common/exceptions/base.exception.ts +export enum ErrorType { + VALIDATION = 'VALIDATION', + BUSINESS_RULE = 'BUSINESS_RULE', + PERMISSION_DENIED = 'PERMISSION_DENIED', + NOT_FOUND = 'NOT_FOUND', + CONFLICT = 'CONFLICT', + INTERNAL_ERROR = 'INTERNAL_ERROR', + DATABASE_ERROR = 'DATABASE_ERROR', + EXTERNAL_SERVICE = 'EXTERNAL_SERVICE', + INFRASTRUCTURE = 'INFRASTRUCTURE' +} + +export enum ErrorSeverity { + LOW = 'LOW', // User mistake, easy recovery + MEDIUM = 'MEDIUM', // Business rule violation, needs action + HIGH = 'HIGH', // System issue, may need support + CRITICAL = 'CRITICAL' // System failure, immediate attention +} + +export abstract class BaseException extends HttpException { + constructor( + public readonly type: ErrorType, + public readonly code: string, + public readonly message: string, + public readonly userMessage?: string, + public readonly severity: ErrorSeverity = ErrorSeverity.MEDIUM, + public readonly details?: any, + public readonly recoveryActions?: string[] + ) { + super( + { + error: { + type, + code, + message: userMessage || message, + severity, + timestamp: new Date().toISOString(), + ...(recoveryActions && { recoveryActions }), + ...(process.env.NODE_ENV === 'development' && { + technicalMessage: message, + details + }) + } + }, + getStatusCode(type) + ); + } +} + +export class ValidationException extends BaseException { + constructor(message: string, details?: ValidationErrorDetail[]) { + super( + ErrorType.VALIDATION, + 'VALIDATION_ERROR', + message, + 'ข้อมูลที่กรอกไม่ถูกต้อง กรุณาตรวจสอบและลองใหม่', + ErrorSeverity.LOW, + details, + ['ตรวจสอบข้อมูลที่กรอก', 'แก้ไขข้อมูลที่ผิดพลาด', 'ลองใหม่อีกครั้ง'] + ); + } +} +``` + +### Global Exception Filter + +```typescript +// File: backend/src/common/filters/global-exception.filter.ts +@Injectable() +export class GlobalExceptionFilter implements ExceptionFilter { + private readonly logger = new Logger(GlobalExceptionFilter.name); + + catch(exception: unknown, host: ArgumentsHost) { + const ctx = host.switchToHttp(); + const response = ctx.getResponse(); + const request = ctx.getRequest(); + + let errorResponse: any; + + if (exception instanceof BaseException) { + // Handle our custom exceptions + errorResponse = exception.getResponse(); + this.logError(exception, request, false); + } else if (exception instanceof HttpException) { + // Handle NestJS HTTP exceptions + const status = exception.getStatus(); + const exceptionResponse = exception.getResponse(); + + errorResponse = { + error: { + type: this.getErrorType(status), + code: 'HTTP_ERROR', + message: this.getUserMessage(status), + severity: ErrorSeverity.MEDIUM, + timestamp: new Date().toISOString(), + ...(process.env.NODE_ENV === 'development' && { + technicalMessage: exception.message, + details: exceptionResponse + }) + } + }; + this.logError(exception, request, false); + } else { + // Handle unexpected errors + errorResponse = { + error: { + type: ErrorType.INTERNAL_ERROR, + code: 'UNEXPECTED_ERROR', + message: 'เกิดข้อผิดพลาดที่ไม่คาดคิด กรุณาลองใหม่ภายหลัง', + severity: ErrorSeverity.CRITICAL, + timestamp: new Date().toISOString() + } + }; + this.logError(exception, request, true); + } + + response.status(errorResponse.error.statusCode || 500).json(errorResponse); + } + + private logError(exception: any, request: Request, isCritical: boolean) { + const logData = { + path: request.url, + method: request.method, + userId: request.user?.id, + ip: request.ip, + userAgent: request.headers['user-agent'], + exception: { + name: exception.name, + message: exception.message, + stack: exception.stack, + details: exception.details + } + }; + + if (isCritical || exception.severity === ErrorSeverity.CRITICAL) { + this.logger.error('Critical error occurred', logData); + } else { + this.logger.warn('Error occurred', logData); + } + } +} +``` + +### Service Layer Example + +```typescript +// File: backend/src/modules/correspondence/correspondence.service.ts +@Injectable() +export class CorrespondenceService { + async create(createDto: CreateCorrespondenceDto, userId: number): Promise { + try { + // Business validation + if (createDto.originatorId && !await this.canUserCreateForOrganization(userId, createDto.originatorId)) { + throw new PermissionException('correspondence', 'create for organization'); + } + + // Check for duplicate document number + if (await this.isDuplicateDocumentNumber(createDto.documentNumber)) { + throw new BusinessException( + 'DUPLICATE_DOCUMENT_NUMBER', + `Document number ${createDto.documentNumber} already exists`, + 'เลขที่เอกสารนี้มีอยู่แล้ว กรุณาใช้เลขที่อื่น', + ['ตรวจสอบเลขที่เอกสารล่าสุด', 'ขอเลขที่เอกสารใหม่'] + ); + } + + // Create correspondence + const correspondence = this.correspondenceRepo.create({ + ...createDto, + createdBy: userId, + createdAt: new Date() + }); + + const saved = await this.correspondenceRepo.save(correspondence); + + this.logger.log(`Correspondence created: ${saved.id}`); + return saved; + + } catch (error) { + if (error instanceof BaseException) { + throw error; // Re-throw our custom exceptions + } + + // Handle database errors + if (error.code === 'ER_DUP_ENTRY') { + throw new BusinessException( + 'DUPLICATE_ENTRY', + 'Database constraint violation', + 'ข้อมูลซ้ำกันในระบบ กรุณาตรวจสอบ' + ); + } + + // Handle unexpected errors + this.logger.error('Unexpected error in CorrespondenceService.create', error); + throw new SystemException('Failed to create correspondence', error); + } + } +} +``` + +### Frontend Error Display Component + +```typescript +// File: frontend/components/common/error-display.tsx +interface ErrorResponse { + error: { + type: string; + code: string; + message: string; + severity: string; + timestamp: string; + recoveryActions?: string[]; + technicalMessage?: string; + details?: any; + }; +} + +export function ErrorDisplay({ error, onRetry }: { error: ErrorResponse; onRetry?: () => void }) { + const getSeverityColor = (severity: string) => { + switch (severity) { + case 'LOW': return 'text-yellow-600'; + case 'MEDIUM': return 'text-orange-600'; + case 'HIGH': return 'text-red-600'; + case 'CRITICAL': return 'text-red-800'; + default: return 'text-gray-600'; + } + }; + + return ( +
+
+
+ +
+
+

+ {error.error.message} +

+ + {error.error.recoveryActions && ( +
+

วิธีแก้ไข:

+
    + {error.error.recoveryActions.map((action, index) => ( +
  • {action}
  • + ))} +
+
+ )} + +
+ {onRetry && ( + + )} + +
+
+
+
+ ); +} +``` + +### Error Catalog Structure + +```markdown +# Error Catalog + +| Error Code | Type | User Message | Recovery Actions | Severity | Module | +|------------|------|--------------|------------------|----------|--------| +| VALIDATION_ERROR | Validation | ข้อมูลที่กรอกไม่ถูกต้อง | ตรวจสอบข้อมูล, แก้ไข, ลองใหม่ | LOW | All | +| DUPLICATE_DOCUMENT_NUMBER | Business | เลขที่เอกสารซ้ำกัน | ตรวจสอบเลขล่าสุด, ขอเลขใหม่ | MEDIUM | Correspondence | +| CORRESPONDENCE_NOT_FOUND | Business | ไม่พบเอกสาร | ตรวจสอบ UUID, ค้นหาใหม่ | MEDIUM | Correspondence | +| PERMISSION_DENIED | Permission | ไม่มีสิทธิ์ดำเนินการ | ติดต่อ admin, ใช้บัญชีอื่น | MEDIUM | All | +| WORKFLOW_INVALID_TRANSITION | Business | ไม่สามารถดำเนินการได้ในสถานะปัจจุบัน | ตรวจสอบ workflow, ดำเนินการอื่น | MEDIUM | Workflow | +| INTERNAL_ERROR | System | เกิดข้อผิดพลาดในระบบ | ลองใหม่, ติดต่อ admin | HIGH | All | +| DATABASE_ERROR | System | ฐานข้อมูลมีปัญหา | ลองใหม่ภายหลัง, แจ้ง admin | HIGH | All | +| EXTERNAL_SERVICE | System | บริการภายนอกมีปัญหา | ลองใหม่ภายหลัง | MEDIUM | Notification | +``` + +--- + +## 📊 Success Criteria + +### Functional Requirements +- [ ] Exception hierarchy implemented +- [ ] Global exception filter working +- [ ] All services use custom exceptions +- [ ] Frontend displays user-friendly errors +- [ ] Error catalog complete + +### Non-Functional Requirements +- [ ] Error responses consistent across all endpoints +- [ ] Error logging integrated with ADR-010 +- [ ] User recovery guidance actionable +- [ ] Technical details controlled in production +- [ ] Error analytics and monitoring + +### Compliance Requirements +- [ ] ADR-007 patterns followed consistently +- [ ] ADR-010 logging integrated +- [ ] Security: No information leakage +- [ ] Accessibility: Error messages understandable + +--- + +## 🚀 Deployment & Rollout + +### Phase 1: Backend Implementation (Week 1) +- Create exception hierarchy +- Implement global filter +- Update core services + +### Phase 2: Service Updates (Week 2) +- Update all service methods +- Add comprehensive error handling +- Create error catalog + +### Phase 3: Frontend Integration (Week 3) +- Update error display components +- Implement recovery UI +- Add error analytics + +--- + +## 📋 Dependencies & Prerequisites + +### Must Have +- ✅ ADR-007 Approved +- ✅ ADR-010 Logging Strategy +- ✅ NestJS framework setup +- ✅ Frontend error state management + +### Nice to Have +- Error monitoring dashboard +- Automated error testing +- Error localization framework + +--- + +## 🔄 Review & Acceptance + +### Code Review Checklist +- [ ] Exception hierarchy comprehensive +- [ ] Global filter handles all cases +- [ ] Services use proper exceptions +- [ ] Frontend error handling user-friendly +- [ ] Error catalog complete +- [ ] No information leakage + +### Acceptance Criteria +- [ ] All errors use custom exceptions +- [ ] Error responses standardized +- [ ] User recovery guidance clear +- [ ] Technical details controlled +- [ ] Error logging comprehensive +- [ ] Frontend error handling tested + +--- + +**Owner:** Backend Team Lead + Frontend Team Lead +**Estimated Effort:** 3 weeks (1-2 developers) +**Risk Level:** Low (Improvement, no breaking changes) +**Rollback Plan:** Revert to previous error handling