690404:1139 Modify ADR
CI / CD Pipeline / build (push) Successful in 4m34s
CI / CD Pipeline / deploy (push) Successful in 7m33s

This commit is contained in:
2026-04-04 11:39:56 +07:00
parent d775d5ad85
commit c95e0f537e
87 changed files with 7046 additions and 422 deletions
@@ -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
@@ -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
เป็นไปตาม:
@@ -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/)
@@ -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/)
@@ -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
เป็นไปตาม:
@@ -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
เป็นไปตาม:
@@ -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<Correspondence>,
private logger: Logger
) {}
async create(createDto: CreateCorrespondenceDto, userId: number): Promise<Correspondence> {
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<Correspondence> {
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 (
<div className="rounded-lg border border-red-200 bg-red-50 p-4">
<div className="flex items-center">
<div className="flex-shrink-0">
<ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
</div>
<div className="ml-3">
<h3 className={`text-sm font-medium ${getSeverityColor(error.error.severity)}`}>
{error.error.message}
</h3>
{error.error.recoveryActions && (
<div className="mt-2 text-sm text-gray-600">
<p className="font-medium">:</p>
<ul className="list-disc list-inside space-y-1">
{error.error.recoveryActions.map((action, index) => (
<li key={index}>{action}</li>
))}
</ul>
</div>
)}
<div className="mt-3 flex space-x-3">
{onRetry && (
<button
onClick={onRetry}
className="rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700"
>
</button>
)}
<button className="rounded bg-gray-600 px-3 py-1 text-sm text-white hover:bg-gray-700">
</button>
</div>
</div>
</div>
</div>
);
}
// API service error handling
export class ApiService {
async request<T>(config: AxiosRequestConfig): Promise<T> {
try {
const response = await axios.request<T>(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)
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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 |
@@ -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<UIState>()(
---
## 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<UIState>()(
---
**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 |
@@ -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 |
@@ -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 |
@@ -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** | <ul><li>Setup n8n on QNAP NAS with Docker</li><li>Install Ollama with Gemma 4 on Admin Desktop</li><li>Configure PaddleOCR service for Thai text extraction</li><li>Setup network segmentation and AI isolation per ADR-018</li><li>Configure GPU monitoring and temperature controls</li></ul> | **Critical** |
| **Database** | <ul><li>Create migration_logs table with UUIDv7 primary keys</li><li>Create migration_review_queue staging table</li><li>Create import_transactions audit table</li><li>Create migration_progress tracking table</li><li>Setup migration_fallback_state table</li></ul> | **Critical** |
| **Backend** | <ul><li>Implement MigrationService with business logic</li><li>Create AI validation layer with confidence thresholds</li><li>Add migration-specific API endpoints with CASL guards</li><li>Implement idempotency handling for migration requests</li><li>Create storage service integration for two-phase file handling</li></ul> | **Critical** |
| **Security** | <ul><li>Implement migration token system with 7-day expiry</li><li>Setup IP whitelisting for migration services</li><li>Configure rate limiting for migration endpoints</li><li>Create comprehensive audit logging for migration operations</li><li>Implement Nginx security rules for migration access</li></ul> | **High** |
| **Storage** | <ul><li>Implement two-phase storage (temp → permanent)</li><li>Create migration-specific storage paths</li><li>Setup file cleanup and archival processes</li><li>Implement storage service integration</li><li>Create file validation and virus scanning workflows</li></ul> | **High** |
| **Frontend** | <ul><li>Build migration dashboard with queue management</li><li>Create review interface for AI suggestions</li><li>Implement bulk approval/rejection workflows</li><li>Add progress tracking and monitoring displays</li><li>Create error handling and retry interfaces</li></ul> | **Medium** |
| **Monitoring** | <ul><li>Setup migration progress tracking and metrics</li><li>Implement AI service health monitoring</li><li>Create error logging and alerting systems</li><li>Setup performance monitoring for migration workflows</li><li>Create GPU temperature and resource monitoring</li></ul> | **Medium** |
| **Documentation** | <ul><li>Create migration operation procedures</li><li>Document troubleshooting and recovery processes</li><li>Create admin training materials</li><li>Update API documentation with migration endpoints</li><li>Create rollback and recovery guides</li></ul> | **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 |
@@ -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** | <ul><li>Create AI classification suggestion components</li><li>Build confidence score indicators</li><li>Implement user confirmation dialogs</li><li>Add classification history displays</li><li>Create AI-assisted tagging interface</li></ul> | **Critical** |
| **Backend** | <ul><li>Implement AI classification service endpoints</li><li>Create validation layer for AI suggestions</li><li>Add confidence threshold processing</li><li>Implement classification audit logging</li><li>Create AI model communication interfaces</li></ul> | **Critical** |
| **Database** | <ul><li>Create AI classification suggestions table</li><li>Add confidence score tracking fields</li><li>Implement classification history logging</li><li>Create user feedback storage for AI improvement</li><li>Update data dictionary with AI fields</li></ul> | **High** |
| **AI Integration** | <ul><li>Setup Ollama model communication protocols</li><li>Implement prompt engineering for document classification</li><li>Create confidence scoring algorithms</li><li>Setup fallback model switching logic</li><li>Implement AI response validation</li></ul> | **High** |
| **API** | <ul><li>Create /api/ai/classify endpoint</li><li>Implement AI suggestion confirmation endpoints</li><li>Add AI service health check endpoints</li><li>Create classification feedback endpoints</li><li>Implement rate limiting for AI services</li></ul> | **High** |
| **Testing** | <ul><li>Create AI accuracy validation tests</li><li>Implement classification consistency tests</li><li>Add user acceptance testing for AI features</li><li>Create performance tests for AI endpoints</li><li>Implement security tests for AI boundaries</li></ul> | **Medium** |
| **Documentation** | <ul><li>Create user guide for AI classification features</li><li>Document AI model limitations and best practices</li><li>Create troubleshooting guide for AI issues</li><li>Update API documentation with AI endpoints</li></ul> | **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)
@@ -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** | <ul><li>Setup AI Zone on Admin Desktop (Desk-5439)</li><li>Configure network segmentation and IP whitelisting</li><li>Install Ollama and AI services on isolated host</li><li>Setup firewall rules for AI communication</li></ul> | **Critical** |
| **Security** | <ul><li>Create AI service authentication tokens</li><li>Implement AI-specific API scopes and permissions</li><li>Setup comprehensive audit logging for AI interactions</li><li>Configure rate limiting for AI endpoints</li></ul> | **Critical** |
| **API Layer** | <ul><li>Create AI validation service with confidence thresholds</li><li>Add AI-specific authentication middleware</li><li>Implement AI request/response logging</li><li>Create AI health check endpoints</li></ul> | **Critical** |
| **Network** | <ul><li>Configure LAN-only access for AI services</li><li>Setup IP whitelist for AI host communication</li><li>Implement network monitoring for AI traffic</li><li>Create firewall rules for AI zone isolation</li></ul> | **High** |
| **Monitoring** | <ul><li>Setup AI service health monitoring</li><li>Create audit log analysis for AI interactions</li><li>Implement GPU temperature and resource monitoring</li><li>Create alerting for AI service failures</li></ul> | **High** |
| **Documentation** | <ul><li>Create AI integration security guidelines</li><li>Update development workflows with AI security requirements</li><li>Create AI compliance documentation</li><li>Update API documentation with AI security requirements</li></ul> | **Medium** |
| **Testing** | <ul><li>Create AI security penetration tests</li><li>Implement AI boundary validation tests</li><li>Create AI authentication and authorization tests</li><li>Setup AI compliance verification tests</li></ul> | **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)
@@ -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** | <ul><li>ADD UUID column to 14 core tables (SQL First)</li><li>CREATE UNIQUE INDEX on each UUID column</li><li>Update data dictionary with new fields</li></ul> | **Critical** |
| **Backend** | <ul><li>Create BaseUuidEntity with publicId property</li><li>Update 14+ entities to extend BaseUuidEntity</li><li>Modify controllers to accept UUID parameters</li><li>Update services to resolve UUID → INT for queries</li><li>Modify DTOs to expose publicId, exclude INT id</li></ul> | **Critical** |
| **API Layer** | <ul><li>Update route patterns to use :uuid parameters</li><li>Add ParseUUIDPipe for validation</li><li>Implement FindByIdOrUuid methods during transition</li><li>Update API responses to return publicId</li></ul> | **Critical** |
| **Frontend** | <ul><li>Update all TypeScript interfaces to use publicId</li><li>Remove fallback uuid/id fields from types</li><li>Update URL construction to use publicId</li><li>Modify API calls to pass UUID strings</li></ul> | **High** |
| **Security** | <ul><li>Update CASL policies to work with UUID identifiers</li><li>Enhance API authentication for UUID-based routes</li><li>Update audit logging to use UUID references</li></ul> | **High** |
| **Caching** | <ul><li>Update Redis cache key strategy to use UUID</li><li>Implement cache invalidation for UUID-based keys</li><li>Migrate existing cache entries during transition</li></ul> | **Medium** |
| **Testing** | <ul><li>Update unit tests with UUID fixtures</li><li>Modify integration tests for UUID routes</li><li>Add performance tests for UUID vs INT lookups</li></ul> | **Medium** |
| **Documentation** | <ul><li>Update API documentation with UUID examples</li><li>Create migration guide for developers</li><li>Update frontend development guidelines</li></ul> | **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`_
@@ -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** | <ul><li>Create `migration_logs` table (SQL First)</li><li>Create `ai_audit_logs` table</li><li>Update data dictionary</li></ul> | **Critical** |
| **Backend** | <ul><li>Implement AiModule with n8n integration</li><li>Create MigrationService with business logic</li><li>Add AI endpoints with CASL guards</li><li>Update validation layer for AI responses</li></ul> | **Critical** |
| **Frontend** | <ul><li>Build DocumentReviewForm reusable component</li><li>Create Admin Migration Dashboard</li><li>Integrate AI suggestions in RFA form</li><li>Add confidence score indicators</li></ul> | **High** |
| **Infrastructure** | <ul><li>Setup n8n on Admin Desktop (Desk-5439)</li><li>Deploy Ollama with Gemma 4</li><li>Configure PaddleOCR service</li><li>Setup Docker containers</li></ul> | **Critical** |
| **Security** | <ul><li>Implement ADR-018 AI boundaries</li><li>Add AI-specific authentication scopes</li><li>Create audit logging for AI interactions</li><li>Setup rate limiting for AI endpoints</li></ul> | **Critical** |
| **Testing** | <ul><li>AI accuracy validation tests</li><li>End-to-end pipeline tests</li><li>Security boundary verification</li><li>Performance benchmarking</li></ul> | **High** |
| **Documentation** | <ul><li>Admin workflow procedures</li><li>User AI assistance guide</li><li>Troubleshooting procedures</li><li>API documentation updates</li></ul> | **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)
@@ -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
@@ -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]
+77 -71
View File
@@ -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 (สร้างในอนาคต)
+7 -25
View File
@@ -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:**
+274
View File
@@ -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<T>`, `PaginatedResponse<T>`, `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<T extends BaseEntity> {
constructor(
protected readonly service: BaseService<T>,
protected readonly entityName: string
) {}
@Get()
@ApiResponse({ status: 200, description: `List ${entityName}` })
async findAll(@Query() query: PaginationDto): Promise<PaginatedResponse<T>> {
return this.service.findAll(query);
}
@Get(':uuid')
@ApiResponse({ status: 200, description: `Get ${entityName} by UUID` })
async findOne(@Param('uuid') uuid: string): Promise<ApiResponse<T>> {
return this.service.findOne(uuid);
}
@Post()
@ApiResponse({ status: 201, description: `Create ${entityName}` })
async create(@Body() dto: CreateDto): Promise<ApiResponse<T>> {
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<Correspondence> {
@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<ActionResponse> {
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<ActionResponse> {
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<PaginatedCorrespondences> {
return this.client.get('', { params: query });
}
async findOne(uuid: string): Promise<Correspondence> {
return this.client.get(`/${uuid}`);
}
async create(dto: CreateCorrespondenceDto): Promise<Correspondence> {
return this.client.post('', dto);
}
// Action operations
async submit(uuid: string, dto: SubmitCorrespondenceDto): Promise<ActionResponse> {
return this.client.post(`/${uuid}/submit`, dto);
}
async approve(uuid: string, dto: ApproveCorrespondenceDto): Promise<ActionResponse> {
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
+406
View File
@@ -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<AuditLog>
) {}
async logCreate(entity: BaseEntity, userId: number): Promise<void> {
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<void> {
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<Observable<any>> {
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
+466
View File
@@ -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<Correspondence> {
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 (
<div className="rounded-lg border border-red-200 bg-red-50 p-4">
<div className="flex items-center">
<div className="flex-shrink-0">
<ExclamationTriangleIcon className="h-5 w-5 text-red-400" />
</div>
<div className="ml-3">
<h3 className={`text-sm font-medium ${getSeverityColor(error.error.severity)}`}>
{error.error.message}
</h3>
{error.error.recoveryActions && (
<div className="mt-2 text-sm text-gray-600">
<p className="font-medium">วิธีแก้ไข:</p>
<ul className="list-disc list-inside space-y-1">
{error.error.recoveryActions.map((action, index) => (
<li key={index}>{action}</li>
))}
</ul>
</div>
)}
<div className="mt-3 flex space-x-3">
{onRetry && (
<button
onClick={onRetry}
className="rounded bg-blue-600 px-3 py-1 text-sm text-white hover:bg-blue-700"
>
ลองใหม่
</button>
)}
<button className="rounded bg-gray-600 px-3 py-1 text-sm text-white hover:bg-gray-700">
ติดต่อผู้ดูแลระบบ
</button>
</div>
</div>
</div>
</div>
);
}
```
### 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