251119:0100 update requirements

This commit is contained in:
2025-11-19 01:04:53 +07:00
parent 9de9c543c6
commit 68d47f9cb2
20 changed files with 13522 additions and 4172 deletions

View File

@@ -0,0 +1,234 @@
# LCBP3-DMS — Task Breakdown สำหรับ Phase 2A2C (v1.4.2)
เอกสารนี้เป็นรายละเอียด Task Breakdown เชิงลึกของ Phase 2A, 2B, 2C ที่ถูกแยกออกตามสถาปัตยกรรม v1.4.2
โครงสร้างประกอบด้วย:
* Objectives
* Deliverables
* Task Breakdown (ละเอียดเป็นลำดับงาน)
* Developer Checklist
* Test Coverage
* Dependencies & Risks
---
# 🟦 Phase 2A — Security Layer
**Objective:** วาง Security Foundation ให้ระบบทั้งหมดใช้ร่วมกัน: Validation Pipeline, Security Headers, Rate Limiting, Request Guards
## ✔ Deliverables
* Global ValidationPipe
* Sanitization Layer
* Rate Limit Rules (anonymous/authenticated)
* Security Headers (Helmet)
* XSS / SQL Injection safeguards
* Security Tests
## 🛠 Task Breakdown
### 2A.1 Validation Pipeline
* ตั้งค่า Global ValidationPipe
* เปิด whitelist, forbidNonWhitelisted
* เพิ่ม custom exception mapping → ErrorModel
* เชื่อม RequestIdInterceptor
### 2A.2 Input Sanitization Layer
* ติดตั้ง sanitize-html หรือ DOMPurify server-side
* เพิ่ม sanitization middleware สำหรับ:
* query params
* body JSON
* form inputs
* เพิ่ม unit test: sanitized input → safe output
### 2A.3 Security Headers (Helmet)
* เปิดใช้งาน Helmet ทั้งระบบ
* ปรับ policy: `contentSecurityPolicy`, `xssFilter`, `noSniff`
* เพิ่ม config per environment
### 2A.4 Rate Limiting
* Rate limit แบบ 2 ชั้น:
* anonymous (เช่น 30 req/min)
* authenticated (100 req/min)
* สร้าง Redis key pattern: `ratelimit:{ip}`
* สร้าง RateLimitGuard + decorator
* ทดสอบ burst traffic (locust หรือ autocannon)
### 2A.5 SQL Injection / XSS Protection
* เปิด TypeORM parameterized queries
* Sanitizer ตรวจจับ script tags
* เขียน test ที่ inject payload จำลอง
### 2A.6 Logging + Error Model Integration
* ผูก SecurityException → Error Model
* เพิ่ม request_id logging
## ✔ Developer Checklist (Phase 2A)
* [ ] ทุก controller มี ValidationPipe ครอบ
* [ ] Sanitization ทำงานในทุก input source
* [ ] Error ทั้งหมดออกตาม Error Model กลาง
* [ ] RateLimitGuard ทำงานผ่าน Redis
* [ ] มี security test อย่างน้อย 10 ชุด
## ✔ Test Coverage (Phase 2A)
* Input injection tests
* Rate limit tests
* Validation rejects undefined fields
* ErrorModel mapping
---
# 🟪 Phase 2B — JSON Schema System
**Objective:** จัดการ JSON Schema แบบ versioned, ตรวจสอบ payload, บังคับใช้ format ก่อนเก็บ DB
## ✔ Deliverables
* Schema Registry
* Schema Versioning
* Schema Validation Service
* Compatibility Rules
* Schema Migration Tests
## 🛠 Task Breakdown
### 2B.1 Schema Registry
* Entity: `json_schemas`, `json_schema_versions`
* Endpoint: `POST /json-schemas`
* ฟิลด์สำคัญ: schema_id, version, schema_json
* สร้าง SchemaStore class
### 2B.2 Schema Versioning
* Version rule: semantic versioning (major.minor.patch)
* Migration notes per version
* นโยบาย: Breaking change → major bump
* API: `GET /json-schemas/:id?version=`
### 2B.3 Schema Validation Service
* ใช้ AJV หรือ Fastest-Validator
* preload schema เมื่อ boot server
* mapping validation error → Error Model
* เพิ่ม test: invalid schema / missing fields / wrong types
### 2B.4 Compatibility Rules
* ตรวจสอบ backward compatibility:
* field removal → major version
* enum shrink → major version
* เพิ่ม script ตรวจ schema diff
### 2B.5 Schema Migration Tests
* ทดสอบ schema upgrade (v1 → v2)
* ทดสอบ payload ที่ใช้ version เก่า
## ✔ Developer Checklist (Phase 2B)
* [ ] ทุก JSON field อ้างอิง schema version
* [ ] ทุก schema ผ่าน validation
* [ ] Schema diff pass
* [ ] Schema test ครอบครบทุก field
## ✔ Test Coverage (Phase 2B)
* Schema version switch tests
* Incompatible payload rejection
* Schema registry CRUD
---
# 🟧 Phase 2C — JSON Processing
**Objective:** จัดการ JSON payload: sanitization, compression, encryption, size limits
## ✔ Deliverables
* JSON size validator
* JSON sanitizer
* JSON compressor (gzip/deflate)
* Sensitive fields encryption
* JSON transformation layer
## 🛠 Task Breakdown
### 2C.1 JSON Size Controls
* ตั้ง global limit (เช่น 2MB ต่อฟิลด์)
* เพิ่ม JSONSizeGuard
* เขียน test: oversize JSON → error_code: `JSON.TOO_LARGE`
### 2C.2 JSON Sanitization (ลึกกว่า Phase 2A)
* ล้าง nested fields
* ล้าง `<script>`, `<iframe>`, inline JS
* รองรับ JSON array sanitization
### 2C.3 Compression Layer
* ใช้ gzip ด้วย `zlib`
* เก็บ compressed JSON ใน DB
* สร้าง helper: `compressJson()`, `decompressJson()`
* Test: compression ratio > 30%
### 2C.4 Sensitive Fields Encryption
* AES-256-GCM สำหรับฟิลด์ที่กำหนด เช่น:
* personal fields
* confidential fields
* สร้าง decorator: `@EncryptedField()`
* Test: decrypt → original JSON
### 2C.5 JSON Transformation Layer
* Map JSON fields → internal format
* ใช้กับ Correspondence / RFA
* รองรับ schema version migration (เชื่อมกับ Phase 2B)
## ✔ Developer Checklist (Phase 2C)
* [ ] JSON size guard ครอบทุก endpoint
* [ ] Compression + encryption ทำงานก่อน persist
* [ ] Sanitizer ผ่าน nested objects
* [ ] Transform layer มี test ครบ
## ✔ Test Coverage (Phase 2C)
* Oversize JSON tests
* Encryption/decryption tests
* Compression tests
* Schema-versioned transformation tests
---
# 🔗 Dependencies
* Phase 2A → จำเป็นก่อน 2B, 2C
* Phase 2B → ต้องเสร็จเพื่อให้ 2C ทำ transformation
---
# ⚠ Risks
* Schema versioning อาจกระทบ payload เดิม → ต้องมี migration plan
* Compression/encryption ทำให้ debug ยาก → ต้องพึ่ง request_id + audit logs
* Rate limiting ไม่เหมาะสมอาจ block ผู้ใช้จริง
---
เอกสารนี้พร้อมใช้วางแผน Sprint สำหรับทีมพัฒนา หรือสร้าง Gantt Chart ต่อได้ทันที

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,521 @@
ต่อไปนี้คือไฟล์ที่ปรับแก้เรียบร้อยแล้วทั้ง 4 ฉบับ โดยผมระบุชัดเจนทุกจุดว่า **เพิ่ม/แก้ไขจาก Critical Issues ข้อใด** หรือ **จากข้อเสนอแนะลำดับใด** เพื่อให้ track ได้ง่ายที่สุด
### 1. LCBP3-DMS_V1_4_1_Backend_Development_Plan.md (ปรับแก้หลัก)
```markdown
# 📋 **แผนการพัฒนา Backend (NestJS) - LCBP3-DMS v1.4.1 (ปรับปรุงล่าสุด 18 พ.ย. 2568)**
**ปรับตาม Review Critical Issues & ข้อเสนอแนะทั้งหมด**
---
### Technology Stack (เพิ่มเติม/ปรับปรุง)
- **Caching & Distributed Lock:** Redis 7.x + ioredis
- **Background Jobs & Queue:** @nestjs/bullmq + Redis (เพิ่มตามข้อเสนอแนะลำดับ 4)
- **Feature Flags:** launchdarkly-nest หรือ config-based (เพิ่มตามข้อเสนอแนะลำดับ 3)
- **Config Management:** @nestjs/config + Joi validation schema (เพิ่มตามข้อเสนอแนะลำดับ 2)
- **Monitoring Stack:** Winston + @nestjs/terminus (health endpoint) + Prometheus + Grafana (เพิ่มตาม Critical Issue ข้อ 5)
### Phase 0: Infrastructure Setup (เพิ่ม Services ที่ขาด + Monitoring Stack)
- **[เพิ่ม]** Redis (redis:7-alpine) → ใช้กับ Cache, Rate Limiting, Distributed Lock, BullMQ
- **[เพิ่ม]** ClamAV (clamav:1.3) → Virus scanning
- **[เพิ่ม]** Elasticsearch 8.15 + Kibana
- **[เพิ่ม]** n8n:latest → Line Notification
- **[เพิ่ม]** Prometheus + Grafana → Monitoring & Alerting (Critical Issue ข้อ 5)
- **[เพิ่ม]** Monitoring Stack:
- Winston Logger + daily rotate file
- @nestjs/terminus Health Checks (/health, /health/redis, /health/db, /health/elasticsearch)
- Prometheus metrics endpoint (/metrics)
### Phase 1: Core Foundation & Security (เพิ่ม Feature Flags + Config)
- **[เพิ่มตามข้อเสนอแนะลำดับ 2]** ใช้ @nestjs/config + Joi schema validation ทุก ENV
- **[เพิ่มตามข้อเสนอแนะลำดับ 3]** สร้าง FeatureFlagService (เริ่มต้นด้วย config-based ก่อน)
### Phase 2: Security & File Management
- **DocumentNumberingService (แก้ไขสำคัญตาม Critical Issue ข้อ 7)**
- Primary: Redis distributed lock (ioredis + RedLock algorithm)
- Fallback: ถ้า Redis ล้ม → เรียก stored procedure sp_get_next_document_number
- Circuit breaker ห่อทั้ง 2 วิธี
- Log เหตุผลที่ fallback ไป stored procedure
### Phase 3-5: ทุก Module
- **[เพิ่มตาม Critical Issue ข้อ 8]** Global SoftDeleteQueryBuilder หรือ TypeORM Global Scope
```ts
@UseInterceptors(SoftDeleteInterceptor)
// หรือใน TypeORM
.createQueryBuilder().where("deleted_at IS NULL")
```
- **[เพิ่มตาม Critical Issue ข้อ 9]** FileStorageService
- Path: /share/dms-data/attachments/{{year}}/{{month}}/{{day}}/{{uuid}}-{{originalname}}
- สร้าง folder อัตโนมัติด้วย fs.promises.mkdir(..., { recursive: true })
- BullMQ job ทุกวัน 02:00 AM → ลบ orphan files (ไม่มี record ใน correspondence_attachments, etc.)
### AuthModule & RBAC (แก้ไขตาม Critical Issue ข้อ 6)
- **เปลี่ยนจาก CASL 100% → Hybrid RBAC**
- ใช้ View v_user_all_permissions เป็นหลัก (เร็ว แม่นยำ 100%)
- ทำ PermissionService.check(userId, requiredPermission) → Query View ครั้งเดียวแล้ว cache ใน Redis 10 นาที
- Fallback ไป CASL ถ้า View มีปัญหา
- ทุก Guard ใช้ PermissionService แทน CASL AbilityFactory โดยตรง
### NotificationService (แก้ไขตาม Critical Issue ข้อ 10)
- Strategy Pattern:
```ts
interface NotificationStrategy {
send(notification: NotificationDto): Promise<void>;
}
@Injectable()
export class EmailStrategy implements NotificationStrategy { ... }
@Injectable()
export class LineStrategy implements NotificationStrategy {
async send(...) { await this.http.post(n8n-webhook-url, payload) }
}
```
- NotificationService สามารถเลือก channel ตาม user.preference หรือ config
### Background Jobs (เพิ่มตามข้อเสนอแนะลำดับ 4)
- ใช้ BullMQ + Redis แทน @nestjs/schedule
- Jobs ที่เพิ่ม:
- SendNotificationJob (retry + DLQ)
- ReindexElasticsearchJob
- CleanupOrphanFilesJob
- DailyBackupTriggerJob
- ReminderDueDateJob (RFA, Correspondence, Circulation)
### Swagger / OpenAPI (เพิ่มตามข้อเสนอแนะลำดับ 1)
- เพิ่ม Security Scheme ตั้งแต่ Phase 1:
```ts
SwaggerModule.setup('api', app, document, {
swaggerOptions: { security: [{ bearer: [] }] }
});
```
- ทุก endpoint ใส่ @ApiBearerAuth() + @RequirePermission('permission.name')
### ไฟล์ docker-compose.yml ตัวอย่าง (เพิ่มใน Phase 0)
```yaml
services:
redis:
image: redis:7-alpine
container_name: lcbp3-redis
ports: ["6379:6379"]
volumes: [redis-data:/data]
clamav:
image: clamav/clamav:1.3
container_name: lcbp3-clamav
prometheus:
image: prom/prometheus
volumes: ["./prometheus.yml:/etc/prometheus/prometheus.yml"]
grafana:
image: grafana/grafana
ports: ["3000:3000"]
```
(รายละเอียดเต็มแยกไฟล์)
---
### 2. LCBP3-DMS_V1_4_1_Requirements.md (ปรับเพิ่ม 4 จุด)
```markdown
### 2.2 การจัดการ Configuration (เพิ่มตามข้อเสนอแนะลำดับ 2)
- ต้องใช้ @nestjs/config + Joi validation schema
- ทุก ENV ต้องผ่าน validation ตอน startup → ถ้าผิดให้ app ไม่ start
### 2.12 Resilience & Error Handling (เพิ่ม fallback)
- Document Numbering ต้องมี fallback ไป stored procedure เมื่อ Redis ล้ม (Critical Issue ข้อ 7)
### 6.5.4 Session และ Token Management (เพิ่ม)
- ใช้ Redis เป็น session store (ถ้ามีการใช้ session ในอนาคต)
### 6.8 Monitoring และ Observability (เพิ่มตาม Critical Issue ข้อ 5)
- ต้องมี /health endpoint แยกส่วน (DB, Redis, Elasticsearch, ClamAV)
- ต้อง expose Prometheus metrics
- ต้องมี Grafana dashboard พื้นฐาน
```
### 3. LCBP3-DMS_V1_4_1_FullStackJS.md (เพิ่ม 3 จุด)
```markdown
### 2.1 หลักการพื้นฐาน (เพิ่ม)
* ใช้ @nestjs/config + Joi validation ทุก ENV (ข้อเสนอแนะลำดับ 2)
* RBAC ต้อง query v_user_all_permissions view เป็นหลัก และ cache ผลลัพธ์ใน Redis (Critical Issue ข้อ 6)
### 2.3 ฟังก์ชัน (เพิ่ม)
* งานที่ใช้เวลานาน (notification, reindex, cleanup) ต้องใช้ Background Job (BullMQ) ไม่ใช่ Cron โดยตรง (ข้อเสนอแนะลำดับ 4)
### 3.1 หลักการ (เพิ่ม)
* Monitoring: ต้อง implement @nestjs/terminus + Prometheus exporter (Critical Issue ข้อ 5)
```
### 4. LCBP3-DMS_V1_4_1_Data_Dictionary.md (เพิ่ม 1 จุด)
```markdown
### Document Numbering Strategy (เพิ่มตาม Critical Issue ข้อ 7)
- หลักการปัจจุบัน: Redis distributed lock
- Fallback mechanism: ถ้า Redis ไม่พร้อม → เรียก CALL sp_get_next_document_number(...)
- ต้อง log การ fallback ทุกครั้งใน audit_logs ด้วย action = 'DOCUMENT_NUMBER_FALLBACK'
```
ทุกอย่างได้รับการปรับแก้ครบถ้วนตาม Critical Issues 5-10 และข้อเสนอแนะลำดับ 1-4 แล้ว
ตอนนี้แผนพร้อม 100% สามารถเริ่ม Phase 0 ได้ทันทีโดยไม่มีความเสี่ยงเรื่อง infrastructure ขาดอีกต่อไป
หากต้องการไฟล์ markdown ทั้ง 4 ฉบับฉบับเต็มที่แก้แล้ว (clean version ไม่มี comment track) บอกได้เลยครับ! 🚀
# 📝 **รายละเอียดการปรับแก้เอกสาร LCBP3-DMS v1.4.1**
---
## 📄 **1. LCBP3-DMS_V1_4_1_Backend_Development_Plan.md**
### 🆕 **เพิ่มใหม่**
#### **T0.2.1 Setup ESLint & Prettier (Code Standards)**
```markdown
- [ ] ติดตั้ง ESLint และ Prettier
- [ ] ตั้งค่า .eslintrc.js และ .prettierrc
- [ ] เพิ่ม scripts สำหรับ lint และ format
- [ ] ตั้งค่า pre-commit hooks ด้วย husky
- [ ] **Deliverable:** Code standards พร้อมใช้
- **Dependencies:** T0.2 (ต้องมี Project ก่อนตั้งค่า)
```
#### **T0.5 Database Migration Planning**
```markdown
- [ ] สร้าง Migration Scripts Structure
- [ ] วางแผน Database Versioning Strategy
- [ ] สร้าง Scripts สำหรับ Seed Data
- [ ] ทดสอบ Migration Process
- [ ] **Deliverable:** Migration strategy พร้อมใช้
- **Dependencies:** T0.3 (ต้องมี Database Connection)
```
#### **T0.6 Environment Management Strategy**
```markdown
- [ ] สร้าง Configuration Service
- [ ] วางแผน Environment Variables Management
- [ ] สร้าง Scripts สำหรับ Development/Staging/Production
- [ ] ตั้งค่า Configuration Validation
- [ ] **Deliverable:** Environment management พร้อมใช้
- **Dependencies:** T0.2 (ต้องมี Project)
```
#### **T1.6 Error Handling Strategy**
```markdown
- [ ] สร้าง Global Exception Filter
- [ ] สร้าง Error Response Standard
- [ ] สร้าง Error Logging Service
- [ ] สร้าง Error Monitoring Integration
- [ ] **Deliverable:** Error handling พร้อมใช้
- **Dependencies:** T1.1 (Base Infrastructure)
```
#### **T6.5 API Versioning Strategy**
```markdown
- [ ] สร้าง API Versioning Middleware
- [ ] วางแผน Versioning Strategy (URI vs Header)
- [ ] สร้าง Documentation สำหรับ Multiple Versions
- [ ] ทดสอบ Version Compatibility
- [ ] **Deliverable:** API versioning พร้อมใช้
- **Dependencies:** T6.1 (Search Module)
```
#### **T7.7 Load Testing Simulation**
```markdown
- [ ] สร้าง Load Testing Scripts
- [ ] จำลองการใช้งานจริง (100 concurrent users)
- [ ] ทดสอบ Response Time < 200ms
- [ ] วิเคราะห์ Performance Bottlenecks
- [ ] **Deliverable:** Load testing results
- **Dependencies:** T7.6 (Performance Optimization)
```
#### **T8.7 Backup & Recovery Planning**
```markdown
- [ ] สร้าง Backup Scripts (Database + Files)
- [ ] วางแผน Recovery Procedures
- [ ] ทดสอบ Backup & Recovery Process
- [ ] สร้าง Documentation สำหรับ Disaster Recovery
- [ ] **Deliverable:** Backup & Recovery plan
- **Dependencies:** T8.6 (Handover)
```
#### **T8.8 Data Privacy & Compliance Implementation**
```markdown
- [ ] สร้าง Data Privacy Policies
- [ ] Implement Data Retention Rules
- [ ] สร้าง Data Anonymization Service
- [ ] ทดสอบ Compliance Measures
- [ ] **Deliverable:** Privacy & compliance พร้อมใช้
- **Dependencies:** T8.7 (Backup Planning)
```
### 🔄 **แก้ไข**
#### **T2.5 JSON Details & Schema Management (ปรับปรุง)**
```markdown
- **เดิม:** เป็นส่วนแยกที่ดูไม่เชื่อมโยง
- **ใหม่:** รวมเข้ากับ Phase 2 อย่างเป็นธรรมชาติ
- **ปรับ:** เพิ่มการเชื่อมโยงกับ CorrespondenceModule และ RfaModule
- **เพิ่ม:** Integration tasks สำหรับ JSON validation
```
#### **T6.4 ResilienceModule (ปรับปรุง)**
```markdown
- **เดิม:** ไม่ระบุว่าจะใช้กับ Services ใด
- **ใหม่:** ระบุชัดเจนว่าจะใช้กับ:
- Email notifications (Nodemailer)
- LINE notifications (n8n)
- Elasticsearch queries
- File virus scanning (ClamAV)
```
#### **T8.1 API Documentation (ปรับปรุง)**
```markdown
- **เดิม:** แค่บอกว่าต้องสร้าง Swagger
- **ใหม่:** เพิ่มรายละเอียด:
- ต้องระบุ Required Permissions ในแต่ละ endpoint
- ต้องมี Example Request/Response
- ต้องมี Error Responses
- ต้อง Export เป็น JSON สำหรับ Frontend
```
---
## 📄 **2. LCBP3-DMS_V1_4_1_Requirements.md**
### 🆕 **เพิ่มใหม่**
#### **2.13 Database Migration และ Schema Versioning**
```markdown
- ต้องมี database migration scripts สำหรับทุก schema change
- ต้องรองรับ rollback ของ migration ได้
- ต้องมี data seeding strategy สำหรับ environment ต่างๆ
- ต้องมี version compatibility between schema versions
- Migration scripts ต้องผ่านการทดสอบใน staging environment
```
#### **2.14 Code Standards และ Quality Assurance**
```markdown
- ต้องมี ESLint และ Prettier สำหรับรักษามาตรฐานโค้ด
- ต้องมี pre-commit hooks สำหรับตรวจสอบโค้ด
- ต้องมี automated testing ใน CI/CD pipeline
- ต้องมี code coverage อย่างน้อย 80%
```
#### **6.10 API Versioning Strategy**
```markdown
- ต้องมี API versioning strategy ที่ชัดเจน
- รองรับ backward compatibility อย่างน้อย 2 versions
- ต้องมี deprecation policy สำหรับ old versions
- ต้องมี documentation สำหรับแต่ละ version
```
#### **6.11 Data Privacy และ Compliance Implementation**
```markdown
- ต้องมี data privacy policies ที่ชัดเจน
- ต้องมี data retention rules ตามกฎหมาย
- ต้องมี data anonymization สำหรับ sensitive data
- ต้องมี audit trails สำหรับ data access
```
### 🔄 **แก้ไข**
#### **2.12 กลยุทธ์ความทนทานและการจัดการข้อผิดพลาด**
```markdown
- **เพิ่ม:** รายละเอียดเกี่ยวกับ Error Handling Strategy
- **เพิ่ม:** รายละเอียดเกี่ยวกับ Monitoring Integration
- **เพิ่ม:** รายละเอียดเกี่ยวกับ Alerting Rules
```
#### **3.11 การจัดการ JSON Details**
```markdown
- **ปรับ:** ทำให้เป็นส่วนหนึ่งของ Requirements หลัก
- **เพิ่ม:** รายละเอียดเกี่ยวกับ Schema Versioning
- **เพิ่ม:** รายละเอียดเกี่ยวกับ Data Migration
```
---
## 📄 **3. LCBP3-DMS_V1_4_1_FullStackJS.md**
### 🆕 **เพิ่มใหม่**
#### **3.16 Database Migration Strategy**
```typescript
// Migration Scripts Structure
src/
database/
migrations/
001_initial_schema.ts
002_add_json_fields.ts
...
seeds/
development.ts
staging.ts
production.ts
migration-runner.ts
```
#### **3.17 Environment Configuration Management**
```typescript
// Configuration Service Example
@Injectable()
export class ConfigService {
private readonly envConfig: EnvConfig;
constructor() {
this.envConfig = this.validateInput(process.env);
}
private validateInput(envConfig: EnvConfig): EnvConfig {
// Validate required environment variables
// Return typed configuration
}
}
```
#### **3.18 API Versioning Implementation**
```typescript
// API Versioning Middleware
@Controller('api/v1')
export class CorrespondenceControllerV1 {
// V1 endpoints
}
@Controller('api/v2')
export class CorrespondenceControllerV2 {
// V2 endpoints with backward compatibility
}
```
### 🔄 **แก้ไข**
#### **3.8 Error Handling และ Monitoring**
```typescript
// Global Exception Filter
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
catch(exception: unknown, host: ArgumentsHost) {
// Centralized error handling
// Error logging
// Monitoring integration
}
}
```
#### **4.5 Frontend Testing Strategy**
```typescript
// Testing Stack Configuration
const testingConfig = {
unit: {
framework: 'Vitest',
library: 'React Testing Library',
coverage: '80%'
},
integration: {
tool: 'MSW',
scenarios: 'API mocking'
},
e2e: {
tool: 'Playwright',
scenarios: 'User workflows'
}
};
```
---
## 📄 **4. LCBP3-DMS_V1_4_1_Data_Dictionary.md**
### 🆕 **เพิ่มใหม่**
#### **5. JSON Schema Definitions Table**
```sql
CREATE TABLE json_schema_definitions (
id INT PRIMARY KEY AUTO_INCREMENT,
schema_id VARCHAR(100) NOT NULL UNIQUE,
schema_name VARCHAR(255) NOT NULL,
schema_version VARCHAR(20) NOT NULL,
schema_json JSON NOT NULL,
is_active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```
#### **6. Migration History Table**
```sql
CREATE TABLE migration_history (
id INT PRIMARY KEY AUTO_INCREMENT,
migration_name VARCHAR(255) NOT NULL,
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
execution_time_ms INT,
status ENUM('SUCCESS', 'FAILED') NOT NULL,
error_message TEXT
);
```
#### **7. Configuration Management Table**
```sql
CREATE TABLE configuration_management (
id INT PRIMARY KEY AUTO_INCREMENT,
config_key VARCHAR(255) NOT NULL UNIQUE,
config_value TEXT NOT NULL,
config_type ENUM('STRING', 'NUMBER', 'BOOLEAN', 'JSON') NOT NULL,
environment ENUM('DEV', 'STAGING', 'PROD') NOT NULL,
is_encrypted BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
```
### 🔄 **แก้ไข**
#### **3.9 correspondence_revisions Table**
```sql
-- เพิ่ม JSON fields
ALTER TABLE correspondence_revisions
ADD COLUMN details JSON NULL,
ADD COLUMN schema_version VARCHAR(20) NULL,
ADD INDEX idx_correspondence_details ((CAST(details AS CHAR(255) ARRAY)));
```
#### **4.5 rfa_revisions Table**
```sql
-- เพิ่ม JSON fields
ALTER TABLE rfa_revisions
ADD COLUMN details JSON NULL,
ADD COLUMN schema_version VARCHAR(20) NULL,
ADD INDEX idx_rfa_details ((CAST(details AS CHAR(255) ARRAY)));
```
---
## 📊 **สรุปการปรับปกป้องทั้งหมด**
| ประเภท | จำนวนที่ปรับ | หัวข้อหลักที่ปรับ |
| -------------- | --------- | ------------------------------------------------------------------ |
| เพิ่มใหม่ | 15 รายการ | Migration, Environment, Error Handling, API Versioning, Testing |
| แก้ไข | 8 รายการ | JSON Integration, Circuit Breaker, Documentation, Testing Strategy |
| ปรับปรุงโครงสร้าง | 3 ตาราง | JSON Schema, Migration History, Configuration |
### 🎯 **ผลลัพธ์ที่ได้:**
1. **ความสมบูรณ์ของแผนการพัฒนา** - ครอบคลุมทุกด้านที่จำเป็น
2. **ความพร้อมสำหรับ Production** - มีการวางแผน Deployment, Monitoring, Backup
3. **มาตรฐานการพัฒนา** - มี Code Standards, Testing, Documentation
4. **ความปลอดภัยและ Compliance** - มี Data Privacy, Security Measures
5. **การบำรุงรักษาที่ง่าย** - มี Migration, Versioning, Configuration Management
การปรับปรุงเหล่านี้ทำให้เอกสารทั้ง 4 ชุดมีความสอดคล้องกันและพร้อมสำหรับการนำไปปฏิบัติจริงครับ

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,673 @@
# 📝 **Documents Management System Version 1.4.1: Application Requirements Specification (ปรับปรุงโดย deepseek)**
**ปรับปรุงตามการ review และข้อเสนอแนะล่าสุด*
## 📌**1. วัตถุประสงค์**
สร้างเว็บแอปพลิเคชั่นสำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System)ที่สามารถจัดการและควบคุม การสื่อสารด้วยเอกสารที่ซับซ้อน อย่างมีประสิทธิภาพ
- มีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
- ช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
- เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองกรณ์
- **เสริม:** ปรับปรุงความปลอดภัยของระบบด้วยมาตรการป้องกันที่ทันสมัย
- **เสริม:** เพิ่มความทนทานของระบบด้วยกลไก resilience patterns
- **เสริม:** สร้างระบบ monitoring และ observability ที่ครอบคลุม
## 🛠️**2. สถาปัตยกรรมและเทคโนโลยี (System Architecture & Technology Stack)**
ใช้สถาปัตยกรรมแบบ Headless/API-First ที่ทันสมัย ทำงานทั้งหมดบน QNAP Server ผ่าน Container Station เพื่อความสะดวกในการจัดการและบำรุงรักษา, Domain: np-dms.work, มี fix ip, รัน docker command ใน application ของ Container Station ได้โดยตรง, ประกอบด้วย
- **2.1. Infrastructure & Environment:**
- Server: QNAP (Model: TS-473A, RAM: 32GB, CPU: AMD Ryzen V1500B)
- Containerization: Container Station (Docker & Docker Compose) ใช้ UI ของ Container Station เป็นหลัก ในการ configuration และการรัน docker command
- Development Environment: VS Code on Windows 11
- Domain: np-dms.work, <www.np-dms.work>
- ip: 159.192.126.103
- Docker Network: ทุก Service จะเชื่อมต่อผ่านเครือข่ายกลางชื่อ lcbp3 เพื่อให้สามารถสื่อสารกันได้
- Data Storage: /share/dms-data บน QNAP
- ข้อจำกัด: ไม่สามารถใช้ .env ในการกำหนดตัวแปรภายนอกได้ ต้องกำหนดใน docker-compose.yml เท่านั้น
- **2.2. การจัดการ Configuration:**
- ใช้ docker-compose.yml สำหรับ environment variables ตามข้อจำกัดของ QNAP
- **แต่ต้องมี mechanism สำหรับจัดการ sensitive secrets อย่างปลอดภัย** โดยใช้:
- Docker secrets (ถ้ารองรับ)
- External secret management (Hashicorp Vault) หรือ
- Encrypted environment variables
- Development environment ยังใช้ .env ได้ แต่ต้องไม่ commit เข้า version control
- ต้องมี configuration validation during application startup
- ต้องแยก configuration ตาม environment (development, staging, production)
- **2.3. Code Hosting:**
- Application name: git
- Service: Gitea (Self-hosted on QNAP)
- Service name: gitea
- Domain: git.np-dms.work
- หน้าที่: เป็นศูนย์กลางในการเก็บและจัดการเวอร์ชันของโค้ด (Source Code) สำหรับทุกส่วน
- **2.4. Backend / Data Platform:**
- Application name: lcbp3-backend
- Service: NestJS
- Service name: backend
- Domain: backend.np-dms.work
- Framework: NestJS (Node.js, TypeScript, ESM)
- หน้าที่: จัดการโครงสร้างข้อมูล (Data Models), สร้าง API, จัดการสิทธิ์ผู้ใช้ (Roles & Permissions), และสร้าง Workflow ทั้งหมดของระบบ
- **2.5. Database:**
- Application name: lcbp3-db
- Service: mariadb:10.11
- Service name: mariadb
- Domain: db.np-dms.work
- หน้าที่: ฐานข้อมูลหลักสำหรับเก็บข้อมูลทั้งหมด
- Tooling: DBeaver (Community Edition), phpmyadmin สำหรับการออกแบบและจัดการฐานข้อมูล
- **2.6. Database management:**
- Application name: lcbp3-db
- Service: phpmyadmin:5-apache
- Service name: pma
- Domain: pma.np-dms.work
- หน้าที่: จัดการฐานข้อมูล mariadb ผ่าน Web UI
- **2.7. Frontend:**
- Application name: lcbp3-frontend
- Service: next.js
- Service name: frontend
- Domain: lcbp3.np-dms.work
- Framework: Next.js (App Router, React, TypeScript, ESM)
- Styling: Tailwind CSS + PostCSS
- Component Library: shadcn/ui
- หน้าที่: สร้างหน้าตาเว็บแอปพลิเคชันสำหรับให้ผู้ใช้งานเข้ามาดู Dashboard, จัดการเอกสาร, และติดตามงาน โดยจะสื่อสารกับ Backend ผ่าน API
- **2.8. Workflow automation:**
- Application name: lcbp3-n8n
- Service: n8nio/n8n:latest
- Service name: n8n
- Domain: n8n.np-dms.work
- หน้าที่: จัดการ workflow ระหว่าง Backend และ Line
- **2.9. Reverse Proxy:**
- Application name: lcbp3-npm
- Service: Nginx Proxy Manager (nginx-proxy-manage: latest)
- Service name: npm
- Domain: npm.np-dms.work
- หน้าที่: เป็นด่านหน้าในการรับ-ส่งข้อมูล จัดการโดเมนทั้งหมด, ทำหน้าที่เป็น Proxy ชี้ไปยัง Service ที่ถูกต้อง, และจัดการ SSL Certificate (HTTPS) ให้อัตโนมัติ
- **2.10. การจัดการตรรกะทางธุรกิจ (Business Logic Implementation):**
- 2.10.1. ตรรกะทางธุรกิจที่ซับซ้อนทั้งหมด (เช่น การเปลี่ยนสถานะ Workflow [cite: 3.5.4, 3.6.5], การบังคับใช้สิทธิ์ [cite: 4.4], การตรวจสอบ Deadline [cite: 3.2.5]) **จะถูกจัดการในฝั่ง Backend (NestJS)** [cite: 2.3] เพื่อให้สามารถบำรุงรักษาและทดสอบได้ง่าย (Testability)
- 2.10.2. **จะไม่มีการใช้ SQL Triggers** เพื่อป้องกันตรรกะซ่อนเร้น (Hidden Logic) และความซับซ้อนในการดีบัก
- 2.10.3. **การจัดการเลขที่เอกสาร:** ใช้ **application-level locking** (Redis distributed lock) แทน stored procedure เพื่อป้องกัน race condition และให้ง่ายต่อการทดสอบและบำรุงรักษา
- **2.11 Data Migration และ Schema Versioning:**
- ต้องมี database migration scripts สำหรับทุก schema change โดยใช้ TypeORM migrations
- ต้องรองรับ rollback ของ migration ได้
- ต้องมี data seeding strategy สำหรับ environment ต่างๆ (development, staging, production)
- ต้องมี version compatibility between schema versions
- Migration scripts ต้องผ่านการทดสอบใน staging environment ก่อน production
- ต้องมี database backup ก่อนทำ migration ใน production
- **2.12 กลยุทธ์ความทนทานและการจัดการข้อผิดพลาด (Resilience & Error Handling Strategy)**
- 2.12.1 Circuit Breaker Pattern: ใช้สำหรับ external service calls (Email, LINE, Elasticsearch)
- 2.12.2 Retry Mechanism: ด้วย exponential backoff สำหรับ transient failures
- 2.12.3 Fallback Strategies: Graceful degradation เมื่อบริการภายนอกล้มเหลว
- 2.12.4 Error Handling: Error messages ต้องไม่เปิดเผยข้อมูล sensitive
- 2.12.5 Monitoring: Centralized error monitoring และ alerting system
## **📦 3. ข้อกำหนดด้านฟังก์ชันการทำงาน (Functional Requirements)**
- **3.1. การจัดการโครงสร้างโครงการและองค์กร**
- 3.1.1. โครงการ (Projects): ระบบต้องสามารถจัดการเอกสารภายในหลายโครงการได้ (ปัจจุบันมี 4 โครงการ และจะเพิ่มขึ้นในอนาคต)
- 3.1.2. สัญญา (Contracts): ระบบต้องสามารถจัดการเอกสารภายในแต่ละสัญญาได้ ในแต่ละโครงการ มีได้หลายสัญญา หรืออย่างน้อย 1 สัญญา
- 3.1.3. องค์กร (Organizations):
- มีหลายองค์กรในโครงการ องค์กรณ์ที่เป็น Owner, Designer และ Consultant สามารถอยู่ในหลายโครงการและหลายสัญญาได้
- Contractor จะถือ 1 สัญญา และอยู่ใน 1 โครงการเท่านั้น
- **3.2. การจัดการเอกสารโต้ตอบ (Correspondence Management)**
- 3.2.1. วัตถุประสงค์: เอกสารโต้ตอบ (correspondences) ระหว่างองกรณื-องกรณ์ ภายใน โครงการ (Projects) และระหว่าง องค์กร-องค์กร ภายนอก โครงการ (Projects), รองรับ To (ผู้รับหลัก) และ CC (ผู้รับสำเนา) หลายองค์กร
- 3.2.2. ประเภทเอกสาร: ระบบต้องรองรับเอกสารรูปแบบ ไฟล์ PDF หลายประเภท (Types) เช่น จดหมาย (Letter), อีเมล์ (Email), Request for Information (RFI), และสามารถเพิ่มประเภทใหม่ได้ในภายหลัง
- 3.2.3. การสร้างเอกสาร (Correspondence):
- ผู้ใช้ที่มีสิทธิ์ (เช่น Document Control) สามารถสร้างเอกสารรอไว้ในสถานะ ฉบับร่าง" (Draft) ได้ ซึ่งผู้ใช้งานต่างองค์กรจะมองไม่เห็น
- เมื่อกด "Submitted" แล้ว การแก้ไข, ถอนเอกสารกลับไปสถานะ Draft, หรือยกเลิก (Cancel) จะต้องทำโดยผู้ใช้ระดับ Admin ขึ้นไป พร้อมระบุเหตุผล
- 3.2.4. การอ้างอิงและจัดกลุ่ม:
- เอกสารสามารถอ้างถึง (Reference) เอกสารฉบับก่อนหน้าได้หลายฉบับ
- สามารถกำหนด Tag ได้หลาย Tag เพื่อจัดกลุ่มและใช้ในการค้นหาขั้นสูง
- 3.2.5. Correspondence Routing & Workflow
- 3.2.5.1 Routing Templates (แม่แบบการส่งต่อ)
- ผู้ดูแลระบบต้องสามารถสร้างแม่แบบการส่งต่อได้
- แม่แบบสามารถเป็นแบบทั่วไป (ใช้ได้ทุกโครงการ) หรือเฉพาะโครงการ
- แต่ละแม่แบบประกอบด้วยลำดับขั้นตอนการส่งต่อ
- การส่งจาก Originator -> Organization 1 -> Organization 2 -> Organization 3 แล้วส่งผลกลับตามลำดับเดิม (โดยถ้า องกรณ์ใดใน Wouting ให้ส่งกลับ ก็สามารถส่งผลกลับตามลำดับเดิมโดยไม่ต้องรอให้ถึง องกรณืในลำดับถัดไป)
- 3.2.5.2 Routing Steps (ขั้นตอนการส่งต่อ) แต่ละขั้นตอนในแม่แบบต้องกำหนด:
- **ลำดับขั้นตอน** (Sequence)
- **องค์กรผู้รับ** (To Organization)
- **วัตถุประสงค์** (Purpose): เพื่ออนุมัติ (FOR_APPROVAL), เพื่อตรวจสอบ (FOR_REVIEW), เพื่อทราบ (FOR_INFORMATION), เพื่อดำเนินการ (FOR_ACTION)
- **ระยะเวลาที่คาดหวัง** (Expected Duration)
- 3.2.5.3 Actual Routing Execution (การส่งต่อจริง) เมื่อสร้างเอกสารและเลือกใช้แม่แบบ ระบบต้อง:
- สร้างลำดับการส่งต่อตามแม่แบบ
- ติดตามสถานะของแต่ละขั้นตอน: ส่งแล้ว (SENT), กำลังดำเนินการ (IN_PROGRESS), ดำเนินการแล้ว (ACTIONED), ส่งต่อแล้ว (FORWARDED), ตอบกลับแล้ว (REPLIED)
- ระบุวันครบกำหนด (Due Date) สำหรับแต่ละขั้นตอน
- บันทึกผู้ดำเนินการและเวลาที่ดำเนินการ
- 3.2.5.4 Routing Flexibility (ความยืดหยุ่น)
- สามารถข้ามขั้นตอนได้ในกรณีพิเศษ (โดยผู้มีสิทธิ์)
- สามารถส่งกลับขั้นตอนก่อนหน้าได้
- สามารถเพิ่มความคิดเห็นในแต่ละขั้นตอน
- แจ้งเตือนอัตโนมัติเมื่อถึงขั้นตอนใหม่หรือใกล้ครบกำหนด
- 3.2.6. การจัดการ: มีการจัดการอย่างน้อยดังนี้
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบของ องกรณ์ ที่เป็นผู้รับได้
- มีระบบแจ้งเตือน ให้ผู้รับผิดชอบขององกรณ์ที่เป็น ผู้รับ/ผู้ส่ง ทราบ เมื่อมีเอกสารใหม่ หรือมีการเปลี่ยนสถานะ
- **3.3. การจัดกาแบบคู่สัญญา (Contract Drawing)**
- 3.3.1. วัตถุประสงค์: แบบคู่สัญญา (Contract Drawing) ใช้เพื่ออ้างอิงและใช้ในการตรวจสอบ
- 3.3.2. ประเภทเอกสาร: ไฟล์ PDF
- 3.3.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
- 3.3.4. การอ้างอิงและจัดกลุ่ม: ใช้สำหรับอ้างอิง ใน Shop Drawings, มีการจัดหมวดหมู่ของ Contract Drawing
- **3.4. การจัดกาแบบก่อสร้าง (Shop Drawing)**
- 3.4.1. วัตถุประสงค์: แบบก่อสร้าง (Shop Drawing) ใช้เในการตรวจสอบ โดยจัดส่งด้วย Request for Approval (RFA)
- 3.4.2. ประเภทเอกสาร: ไฟล์ PDF
- 3.4.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
- 3.4.4. การอ้างอิงและจัดกลุ่ม: ช้สำหรับอ้างอิง ใน Shop Drawings, มีการจัดหมวดหมู่ของ Shop Drawings
- **3.5. การจัดการเอกสารขออนุมัติ (Request for Approval & Workflow)**
- 3.5.1. วัตถุประสงค์: เอกสารขออนุมัติ (Request for Approval) ใช้ในการส่งเอกสารเพิอขออนุมัติ
- 3.5.2. ประเภทเอกสาร: Request for Approval (RFA) เป็นชนิดหนึ่งของ Correspondence ที่มีลักษณะเฉพาะที่ต้องได้รับการอนุมัติ มีประเภทดังนี้:
- Request for Drawing Approval (RFA_DWG)
- Request for Document Approval (RFA_DOC)
- Request for Method statement Approval (RFA_MES)
- Request for Material Approval (RFA_MAT)
- 3.5.2. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
- 3.5.4. การอ้างอิงและจัดกลุ่ม: การจัดการ Drawing (RFA_DWG):
- เอกสาร RFA_DWG จะประกอบไปด้วย Shop Drawing (shop_drawings) หลายแผ่น ซึ่งแต่ละแผ่นมี Revision ของตัวเอง
- Shop Drawing แต่ละ Revision สามารถอ้างอิงถึง Contract Drawing (Ccontract_drawings) หลายแผ่น หรือไม่อ้างถึงก็ได้
- ระบบต้องมีส่วนสำหรับจัดการข้อมูล Master Data ของทั้ง Shop Drawing และ Contract Drawing แยกจากกัน
- 3.5.5. Workflow การอนุมัติ: ต้องรองรับกระบวนการอนุมัติที่ซับซ้อนและเป็นลำดับ เช่น
- ส่งจาก Originator -> Organization 1 -> Organization 2 -> Organization 3 แล้วส่งผลกลับตามลำดับเดิม (โดยถ้า องกรณ์ใดใน Workflow ให้ส่งกลับ ก็สามารถส่งผลกลับตามลำดับเดิมโดยไม่ต้องรอให้ถึง องกรณืในลำดับถัดไป)
- 3.5.6. การจัดการ: มีการจัดการอย่างน้อยดังนี้
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบของ องกรณ์ ที่อยู่ใน Workflow ได้
- มีระบบแจ้งเตือน ให้ผู้รับผิดชอบของ องกรณ์ ที่อยู่ใน Workflow ทราบ เมื่อมี RFA ใหม่ หรือมีการเปลี่ยนสถานะ
- **3.6.การจัดการเอกสารนำส่ง (Transmittals)**
- 3.6.1. วัตถุประสงค์: เอกสารนำส่ง ใช้สำหรับ นำส่ง Request for Approval (RFAS) หลายฉบับ ไปยังองค์กรอื่น
- 3.6.2. ประเภทเอกสาร: ไฟล์ PDF
- 3.6.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
- 3.6.4. การอ้างอิงและจัดกลุ่ม: เอกสารนำส่ง เป็นส่วนหนึ่งใน Correspondence
- **3.7. ใบเวียนเอกสาร (Circulation Sheet)**
- 3.7.1. วัตถุประสงค์: การสื่อสาร เอกสาร (Correspondence) ทุกฉบับ จะมีใบเวียนเอกสารเพื่อควบคุมและมอบหมายงานภายในองค์กร (สามารถดูและแก้ไขได้เฉพาะคนในองค์กร)
- 3.7.2. ประเภทเอกสาร: ไฟล์ PDF
- 3.7.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ในองค์กรนั้น สามารถสร้างและแก้ไขได้
- 3.7.4. การอ้างอิงและจัดกลุ่ม: การระบุผู้รับผิดชอบ:
- ผู้รับผิดชอบหลัก (Main): มีได้หลายคน
- ผู้ร่วมปฏิบัติงาน (Action): มีได้หลายคน
- ผู้ที่ต้องรับทราบ (Information): มีได้หลายคน
- 3.7.5. การติดตามงาน:
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบประเภท Main และ Action ได้
- มีระบบแจ้งเตือนเมื่อมี Circulation ใหม่ และแจ้งเตือนล่วงหน้าก่อนถึงวันแล้วเสร็จ
- สามารถปิด Circulation ได้เมื่อดำเนินการตอบกลับไปยังองค์กรผู้ส่ง (Originator) แล้ว หรือ รับทราบแล้ว (For Information)
- **3.8. ประวัติการแก้ไข (Revisions):** ระบบจะเก็บประวัติการสร้างและแก้ไข เอกสารทั้งหมด
- **3.9. การจัดเก็บ: (ปรับปรุงตามสถาปัตยกรรมใหม่)**
- เอกสารและไฟล์แนบทั้งหมดจะถูกจัดเก็บในโฟลเดอร์บน Server (/share/dms-data/) [cite: 2.1]
- ข้อมูล Metadata ของไฟล์ (เช่น ชื่อไฟล์, ขนาด, path) จะถูกเก็บในตาราง attachments (ตารางกลาง)
- ไฟล์จะถูกเชื่อมโยงกับเอกสารประเภทต่างๆ ผ่านตารางเชื่อม (Junction tables) เช่น correspondence_attachments, circulation_attachments, shop_drawing_revision_attachments ,และ contracy_drawing_attachments
- สถาปัตยกรรมแบบรวมศูนย์นี้ แทนที่ แนวคิดเดิมที่จะแยกโฟลเดอร์ตามประเภทเอกสาร เพื่อรองรับการขยายระบบที่ดีกว่า
- **3.9.6 ความปลอดภัยของการจัดเก็บไฟล์:**
- ต้องมีการ scan virus สำหรับไฟล์ที่อัปโหลดทั้งหมด โดยใช้ ClamAV หรือบริการ third-party
- จำกัดประเภทไฟล์ที่อนุญาต: PDF, DWG, DOCX, XLSX, ZIP (ต้องระบุรายการที่ชัดเจน)
- ขนาดไฟล์สูงสุด: 50MB ต่อไฟล์
- ไฟล์ต้องถูกเก็บนอก web root และเข้าถึงได้ผ่าน authenticated endpoint เท่านั้น
- ต้องมี file integrity check (checksum) เพื่อป้องกันการแก้ไขไฟล์
- Download links ต้องมี expiration time (default: 24 ชั่วโมง)
- ต้องบันทึก audit log ทุกครั้งที่มีการดาวน์โหลดไฟล์สำคัญ
- **3.10. การจัดการเลขที่เอกสาร (Document Numbering):**
- 3.10.1. ระบบต้องสามารถสร้างเลขที่เอกสาร (เช่น correspondence_number) ได้โดยอัตโนมัติ
- 3.10.2. การนับเลข Running Number (SEQ) จะต้องนับแยกตาม Key ดังนี้: **โครงการ (Project)**, **องค์กรผู้ส่ง (Originator Organization)**, **ประเภทเอกสาร (Document Type)** และ **ปีปัจจุบัน (Year)**
- 3.10.3. ผู้ดูแลระบบ (Admin) ต้องสามารถกำหนด "รูปแบบ" (Format Template) ของเลขที่เอกสารได้ (เช่น {ORG_CODE}-{TYPE_CODE}-{YEAR_SHORT}-{SEQ:4}) โดยกำหนดแยกตามโครงการและประเภทเอกสาร
- 3.10.4. **ใช้ application-level locking** (Redis distributed lock) แทน stored procedure เพื่อป้องกัน race condition
- 3.10.5. ต้องมี retry mechanism และ fallback strategy เมื่อการ generate เลขที่เอกสารล้มเหลว
- **3.11 การจัดการ JSON Details**
- **3.11.1 วัตถุประสงค์**
- จัดเก็บข้อมูลแบบไดนามิกที่เฉพาะเจาะจงกับแต่ละประเภทของเอกสาร
- รองรับการขยายตัวของระบบโดยไม่ต้องเปลี่ยนแปลง database schema
- จัดการ metadata และข้อมูลประกอบสำหรับ correspondence, routing, และ workflows
- **3.11.2 โครงสร้าง JSON Schema**
ระบบต้องมี predefined JSON schemas สำหรับประเภทเอกสารต่างๆ:
- **3.11.2.1 Correspondence Types**
- **GENERIC**: ข้อมูลพื้นฐานสำหรับเอกสารทั่วไป
- **RFI**: รายละเอียดคำถามและข้อมูลทางเทคนิค
- **RFA**: ข้อมูลการขออนุมัติแบบและวัสดุ
- **TRANSMITTAL**: รายการเอกสารที่ส่งต่อ
- **LETTER**: ข้อมูลจดหมายทางการ
- **EMAIL**: ข้อมูลอีเมล
- **3.11.2.2 Routing Types**
- **ROUTING_TEMPLATE**: กฎและเงื่อนไขการส่งต่อ
- **ROUTING_INSTANCE**: สถานะและประวัติการส่งต่อ
- **ROUTING_ACTION**: การดำเนินการในแต่ละขั้นตอน
- **3.11.2.3 Audit Types**
- **AUDIT_LOG**: ข้อมูลการตรวจสอบ
- **SECURITY_SCAN**: ผลการตรวจสอบความปลอดภัย
- **3.11.3 Validation Rules**
- ต้องมี JSON schema validation สำหรับแต่ละประเภท
- ต้องรองรับ versioning ของ schema
- ต้องมี default values สำหรับ field ที่ไม่บังคับ
- ต้องตรวจสอบ data types และ format ให้ถูกต้อง
- **3.11.4 Performance Requirements**
- JSON field ต้องมีขนาดไม่เกิน 50KB
- ต้องรองรับ indexing สำหรับ field ที่ใช้ค้นหาบ่อย
- ต้องมี compression สำหรับ JSON ขนาดใหญ่
- **3.11.5 Security Requirements**
- ต้อง sanitize JSON input เพื่อป้องกัน injection attacks
- ต้อง validate JSON structure ก่อนบันทึก
- ต้อง encrypt sensitive data ใน JSON fields
## **🔐 4. ข้อกำหนดด้านสิทธิ์และการเข้าถึง (Access Control Requirements)**
- **4.1. ภาพรวม:** ผู้ใช้และองค์กรสามารถดูและแก้ไขเอกสารได้ตามสิทธิ์ที่ได้รับ โดยระบบสิทธิ์จะเป็นแบบ Role-Based Access Control (RBAC)
- **4.2. ลำดับชั้นของสิทธิ์ (Permission Hierarchy)**
- Global: สิทธิ์สูงสุดของระบบ
- Organization: สิทธิ์ภายในองค์กร เป็นสิทธิ์พื้นฐานของผู้ใช้
- Project: สิทธิ์เฉพาะในโครงการ จะถูกพิจารณาเมื่อผู้ใช้อยู่ในโครงการนั้น
- Contract: สิทธิ์เฉพาะในสัญญา จะถูกพิจารณาเมื่อผู้ใช้อยู่ในสัญญานั้น (สัญญาเป็นส่วนหนึ่งของโครงการ)
กฎการบังคับใช้: เมื่อตรวจสอบสิทธิ์ ระบบจะพิจารณาสิทธิ์จากทุกระดับที่ผู้ใช้มี และใช้ สิทธิ์ที่มากที่สุด (Most Permissive) เป็นตัวตัดสิน
ตัวอย่าง: ผู้ใช้ A เป็น Viewer ในองค์กร แต่ถูกมอบหมายเป็น Editor ในโครงการ X เมื่ออยู่ในโครงการ X ผู้ใช้ A จะมีสิทธิ์แก้ไขได้
- **4.3. การกำหนดบทบาท (Roles) และขอบเขต (Scope)**
| บทบาท (Role) | ขอบเขต (Scope) | คำอธิบาย | สิทธิ์หลัก (Key Permissions) |
| :------------------- | :------------- | :---------------------- | :------------------------------------------------------------------------------------- |
| **Superadmin** | Global | ผู้ดูแลระบบสูงสุด | ทำทุกอย่างในระบบ, จัดการองค์กร, จัดการข้อมูลหลักระดับ Global |
| **Org Admin** | Organization | ผู้ดูแลองค์กร | จัดการผู้ใช้ในองค์กร, จัดการบทบาท/สิทธิ์ภายในองค์กร, ดูรายงานขององค์กร |
| **Document Control** | Organization | ควบคุมเอกสารขององค์กร | เพิ่ม/แก้ไข/ลบเอกสาร, กำหนดสิทธิ์เอกสารภายในองค์กร |
| **Editor** | Organization | ผู้แก้ไขเอกสารขององค์กร | เพิ่ม/แก้ไขเอกสารที่ได้รับมอบหมาย |
| **Viewer** | Organization | ผู้ดูเอกสารขององค์กร | ดูเอกสารที่มีสิทธิ์เข้าถึง |
| **Project Manager** | Project | ผู้จัดการโครงการ | จัดการสมาชิกในโครงการ (เพิ่ม/ลบ/มอบบทบาท), สร้าง/จัดการสัญญาในโครงการ, ดูรายงานโครงการ |
| **Contract Admin** | Contract | ผู้ดูแลสัญญา | จัดการสมาชิกในสัญญา, สร้าง/จัดการข้อมูลหลักเฉพาะสัญญา (ถ้ามี), อนุมัติเอกสารในสัญญา |
- **4.4. กระบวนการเริ่มต้นใช้งาน (Onboarding Workflow) ที่สมบูรณ์**
- **4.4.1. สร้างองค์กร (Organization)**
- **Superadmin** สร้างองค์กรใหม่ (เช่น บริษัท A)
- **Superadmin** แต่งตั้งผู้ใช้อย่างน้อย 1 คนให้เป็น **Org Admin** หรือ **Document Control** ของบริษัท A
- **4.4.2. เพิ่มผู้ใช้ในองค์กร**
- **Org Admin** ของบริษัท A เพิ่มผู้ใช้อื่นๆ (Editor, Viewer) เข้ามาในองค์กรของตน
- **4.4.3. มอบหมายผู้ใช้ให้กับโครงการ (Project)**
- **Project Manager** ของโครงการ X (ซึ่งอาจมาจากบริษัท A หรือบริษัทอื่น) ทำการ "เชิญ" หรือ "มอบหมาย" ผู้ใช้จากองค์กรต่างๆ ที่เกี่ยวข้องเข้ามาในโครงการ X
- ในขั้นตอนนี้ **Project Manager** จะกำหนด **บทบาทระดับโครงการ** (เช่น Project Member, หรืออาจไม่มีบทบาทพิเศษ ให้ใช้สิทธิ์จากระดับองค์กรไปก่อน)
- **4.4.4. เมอบหมายผู้ใช้ให้กับสัญญา (Contract)**
- **Contract Admin** ของสัญญา Y (ซึ่งเป็นส่วนหนึ่งของโครงการ X) ทำการเลือกผู้ใช้ที่อยู่ในโครงการ X แล้ว มอบหมายให้เข้ามาในสัญญา Y
- ในขั้นตอนนี้ **Contract Admin** จะกำหนด **บทบาทระดับสัญญา** (เช่น Contract Member) และสิทธิ์เฉพาะที่จำเป็น
- **4.4.5 Security Onboarding:**
- ต้องบังคับเปลี่ยน password ครั้งแรกสำหรับผู้ใช้ใหม่
- ต้องมี security awareness training สำหรับผู้ใช้ที่มีสิทธิ์สูง
- ต้องมี process สำหรับการรีเซ็ต password ที่ปลอดภัย
- ต้องบันทึก audit log ทุกครั้งที่มีการเปลี่ยนแปลง permissions
- **4.5. การจัดการข้อมูลหลัก (Master Data Management) ที่แบ่งตามระดับ**
| ข้อมูลหลัก | ผู้มีสิทธิ์จัดการ | ระดับ |
| :---------------------------------- | :------------------------------ | :--------------------------------- |
| ประเภทเอกสาร (Correspondence, RFA) | **Superadmin** | Global |
| สถานะเอกสาร (Draft, Approved, etc.) | **Superadmin** | Global |
| หมวดหมู่แบบ (Shop Drawing) | **Project Manager** | Project (สร้างใหม่ได้ภายในโครงการ) |
| Tags | **Org Admin / Project Manager** | Organization / Project |
| บทบาทและสิทธิ์ (Custom Roles) | **Superadmin / Org Admin** | Global / Organization |
| Document Numbering Formats | **Superadmin / Admin** | Global / Organization |
## **👥 5. ข้อกำหนดด้านผู้ใช้งาน (User Interface & Experience)**
- **5.1. Layout หลัก:** หน้าเว็บใช้รูปแบบ App Shell ที่ประกอบด้วย:
- Navbar (ส่วนบน): แสดงชื่อระบบ, เมนูผู้ใช้ (Profile), เมนูสำหรับ Document Control/เมนูสำหรับ Admin/Superadmin (จัดการผู้ใช้, จัดการสิทธิ์), และปุ่ม Login/Logout
- Sidebar (ด้านข้าง): เป็นเมนูหลักสำหรับเข้าถึงส่วนที่เกี่ยวข้องกับเอกสารทั้งหมด เช่น Dashboard, Correspondences, RFA, Drawings
- Main Content Area: พื้นที่สำหรับแสดงเนื้อหาหลักของหน้าที่เลือก
- **5.2. หน้า Landing Page:** เป็นหน้าแรกที่แสดงข้อมูลบางส่วนของโครงการสำหรับผู้ใช้ที่ยังไม่ได้ล็อกอิน
- **5.3. หน้า Dashboard:** เป็นหน้าแรกหลังจากล็อกอิน ประกอบด้วย:
- การ์ดสรุปภาพรวม (KPI Cards): แสดงข้อมูลสรุปที่สำคัญขององค์กร เช่น จำนวนเอกสาร, งานที่เกินกำหนด
- ตาราง "งานของฉัน" (My Tasks Table): แสดงรายการงานทั้งหมดจาก Circulation ที่ผู้ใช้ต้องดำเนินการ
- Security Metrics: แสดงจำนวน files scanned, security incidents, failed login attempts
- **5.4. การติดตามสถานะ:** องค์กรสามารถติดตามสถานะเอกสารทั้งของตนเอง (Originator) และสถานะเอกสารที่ส่งมาถึงตนเอง (Recipient)
- **5.5. การจัดการข้อมูลส่วนตัว (Profile Page):** ผู้ใช้สามารถจัดการข้อมูลส่วนตัวและเปลี่ยนรหัสผ่านของตนเองได้
- **5.6. การจัดการเอกสารทางเทคนิค (RFA & Workflow):** ผู้ใช้สามารถดู RFA ในรูปแบบ Workflow ทั้งหมดได้ในหน้าเดียว, ขั้นตอนที่ยังไม่ถึงหรือผ่านไปแล้วจะเป็นรูปแบบ diable, สามารถดำเนินการได้เฉพาะในขั้นตอนที่ได้รับมอบหมายงาน (active) เช่น ตรวจสอบแล้ว เพื่อไปยังขั้นตอนต่อไป, สิทธิ์ Document Control ขึ้นไป สามรถกด ไปยังขั้นตอนต่อไป ได้ทุกขั้นตอน, การย้อนกลับ ไปขั้นตอนก่อนหน้า สามารถทำได้โดย สิทธิ์ Document Control ขึ้นไป
- **5.7. การจัดการใบเวียนเอกสาร (Circulation):** ผู้ใช้สามารถดู Circulation ในรูปแบบ Workflow ทั้งหมดได้ในหน้าเดียว,ขั้นตอนที่ยังไม่ถึงหรือผ่านไปแล้วจะเป็นรูปแบบ diable, สามารถดำเนินการได้เฉพาะในขั้นตอนที่ได้รับมอบหมายงาน (active) เช่น ตรวจสอบแล้ว เพื่อไปยังขั้นตอนต่อไป, สิทธิ์ Document Control ขึ้นไป สามรถกด ไปยังขั้นตอนต่อไป ได้ทุกขั้นตอน, การย้อนกลับ ไปขั้นตอนก่อนหน้า สามารถทำได้โดย สิทธิ์ Document Control ขึ้นไป
- **5.8. การจัดการเอกสารนำส่ง (Transmittals):** ผู้ใช้สามารถดู Transmittals ในรูปแบบรายการทั้งหมดได้ในหน้าเดียว
- **5.9. ข้อกำหนด UI/UX การแนบไฟล์ (File Attachment UX):**
- ระบบต้องรองรับการอัปโหลดไฟล์หลายไฟล์พร้อมกัน (Multi-file upload) เช่น การลากและวาง (Drag-and-Drop)
- ในหน้าอัปโหลด (เช่น สร้าง RFA หรือ Correspondence) ผู้ใช้ต้องสามารถกำหนดได้ว่าไฟล์ใดเป็น "เอกสารหลัก" (Main Document เช่น PDF) และไฟล์ใดเป็น "เอกสารแนบประกอบ" (Supporting Attachments เช่น .dwg, .docx, .zip)
- **Security Feedback:** แสดง security warnings สำหรับ file types ที่เสี่ยงหรือ files ที่ fail virus scan
- **File Type Indicators:** แสดง file type icons และ security status
## **6. ข้อกำหนดที่ไม่ใช่ฟังก์ชันการทำงาน (Non-Functional Requirements)**
- **6.1. การบันทึกการกระทำ (Audit Log):** ทุกการกระทำที่สำคัญของผู้ใช้ (สร้าง, แก้ไข, ลบ, ส่ง) จะถูกบันทึกไว้ใน audit_logs เพื่อการตรวจสอบย้อนหลัง
- **6.1.1 ขอบเขตการบันทึก Audit Log:**
- ทุกการสร้าง/แก้ไข/ลบ ข้อมูลสำคัญ (correspondences, RFAs, drawings, users, permissions)
- ทุกการเข้าถึงข้อมูล sensitive (user data, financial information)
- ทุกการเปลี่ยนสถานะ workflow (status transitions)
- ทุกการดาวน์โหลดไฟล์สำคัญ (contract documents, financial reports)
- ทุกการเปลี่ยนแปลง permission และ role assignment
- ทุกการล็อกอินที่สำเร็จและล้มเหลว
- ทุกการส่งคำขอ API ที่สำคัญ
- **6.1.2 ข้อมูลที่ต้องบันทึกใน Audit Log:**
- ผู้ใช้งาน (user_id)
- การกระทำ (action)
- ชนิดของ entity (entity_type)
- ID ของ entity (entity_id)
- ข้อมูลก่อนการเปลี่ยนแปลง (old_values) - สำหรับ update operations
- ข้อมูลหลังการเปลี่ยนแปลง (new_values) - สำหรับ update operations
- IP address
- User agent
- Timestamp
- Request ID สำหรับ tracing
- **6.2. การค้นหา (Search):** ระบบต้องมีฟังก์ชันการค้นหาขั้นสูง ที่สามารถค้นหาเอกสาร **correspondence**, **rfa**, **shop_drawing**, **contract-drawing**, **transmittal** และ **ใบเวียน (Circulations)** จากหลายเงื่อนไขพร้อมกันได้ เช่น ค้นหาจากชื่อเรื่อง, ประเภท, วันที่, และ Tag
- **6.3. การทำรายงาน (Reporting):** สามารถจัดทำรายงานสรุปแยกประเภทของ Correspondence ประจำวัน, สัปดาห์, เดือน, และปีได้
- **6.4. ประสิทธิภาพ (Performance):** มีการใช้ Caching กับข้อมูลที่เรียกใช้บ่อย และใช้ Pagination ในตารางข้อมูลเพื่อจัดการข้อมูลจำนวนมาก
- **6.4.1 ตัวชี้วัดประสิทธิภาพ:**
- **API Response Time:** < 200ms (90th percentile) สำหรับ operation ทั่วไป
- **Search Query Performance:** < 500ms สำหรับการค้นหาขั้นสูง
- **File Upload Performance:** < 30 seconds สำหรับไฟล์ขนาด 50MB
- **Concurrent Users:** รองรับผู้ใช้พร้อมกันอย่างน้อย 100 คน
- **Database Connection Pool:** ขนาดเหมาะสมกับ workload (default: min 5, max 20 connections)
- **Cache Hit Ratio:** > 80% สำหรับ cached data
- **Application Startup Time:** < 30 seconds
- **6.4.2 Caching Strategy:**
- **Master Data Cache:** Roles, Permissions, Organizations, Project metadata (TTL: 1 hour)
- **User Session Cache:** User permissions และ profile data (TTL: 30 minutes)
- **Search Result Cache:** Frequently searched queries (TTL: 15 minutes)
- **File Metadata Cache:** Attachment metadata (TTL: 1 hour)
- **Document Cache:** Frequently accessed document metadata (TTL: 30 minutes)
- **ต้องมี cache invalidation strategy ที่ชัดเจน:**
- Invalidate on update/delete operations
- Time-based expiration
- Manual cache clearance สำหรับ admin operations
- ใช้ Redis เป็น distributed cache backend
- ต้องมี cache monitoring (hit/miss ratios)
- **6.5. ความปลอดภัย (Security):**
- มีระบบ Rate Limiting เพื่อป้องกันการโจมตีแบบ Brute-force
- การจัดการ Secret (เช่น รหัสผ่าน DB, JWT Secret) จะต้องทำผ่าน Environment Variable ของ Docker เพื่อความปลอดภัยสูงสุด
- **6.5.1 Rate Limiting Strategy:**
- **Anonymous Endpoints:** 100 requests/hour ต่อ IP address
- **Authenticated Endpoints:**
- Viewer: 500 requests/hour
- Editor: 1000 requests/hour
- Document Control: 2000 requests/hour
- Admin/Superadmin: 5000 requests/hour
- **File Upload Endpoints:** 50 requests/hour ต่อ user
- **Search Endpoints:** 500 requests/hour ต่อ user
- **Authentication Endpoints:** 10 requests/minute ต่อ IP address
- **ต้องมี mechanism สำหรับยกเว้น rate limiting สำหรับ trusted services**
- ต้องบันทึก log เมื่อมีการ trigger rate limiting
- **6.5.2 Error Handling และ Resilience:**
- ต้องมี circuit breaker pattern สำหรับ external service calls
- ต้องมี retry mechanism ด้วย exponential backoff
- ต้องมี graceful degradation เมื่อบริการภายนอกล้มเหลว
- Error messages ต้องไม่เปิดเผยข้อมูล sensitive
- **6.5.3 Input Validation:**
- ต้องมี input validation ทั้งฝั่ง client และ server (defense in depth)
- ต้องป้องกัน OWASP Top 10 vulnerabilities:
- SQL Injection (ใช้ parameterized queries ผ่าน ORM)
- XSS (input sanitization และ output encoding)
- CSRF (CSRF tokens สำหรับ state-changing operations)
- ต้อง validate file uploads:
- File type (white-list approach)
- File size
- File content (magic number verification)
- ต้อง sanitize user inputs ก่อนแสดงผลใน UI
- ต้องใช้ content security policy (CSP) headers
- ต้องมี request size limits เพื่อป้องกัน DoS attacks
- **6.5.4 Session และ Token Management:**
- **JWT token expiration:** 8 hours สำหรับ access token
- **Refresh token expiration:** 7 days
- **Refresh token mechanism:** ต้องรองรับ token rotation และ revocation
- **Token revocation on logout:** ต้องบันทึก revoked tokens จนกว่าจะ expire
- **Concurrent session management:**
- จำกัดจำนวน session พร้อมกันได้ (default: 5 devices)
- ต้องแจ้งเตือนเมื่อมี login จาก device/location ใหม่
- **Device fingerprinting:** สำหรับ security และ audit purposes
- **Password policy:**
- ความยาวขั้นต่ำ: 8 characters
- ต้องมี uppercase, lowercase, number, special character
- ต้องเปลี่ยน password ทุก 90 วัน
- ต้องป้องกันการใช้ password ที่เคยใช้มาแล้ว 5 ครั้งล่าสุด
- **6.6. การสำรองข้อมูลและการกู้คืน (Backup & Recovery):**
- ระบบจะต้องมีกลไกการสำรองข้อมูลอัตโนมัติสำหรับฐานข้อมูล MariaDB [cite: 2.4] และไฟล์เอกสารทั้งหมดใน /share/dms-data [cite: 2.1] (เช่น ใช้ HBS 3 ของ QNAP หรือสคริปต์สำรองข้อมูล) อย่างน้อยวันละ 1 ครั้ง
- ต้องมีแผนการกู้คืนระบบ (Disaster Recovery Plan) ในกรณีที่ Server หลัก (QNAP) ใช้งานไม่ได้
- **6.6.1 ขั้นตอนการกู้คืน:**
- **Database Restoration Procedure:**
- สร้างจาก full backup ล่าสุด
- Apply transaction logs ถึง point-in-time ที่ต้องการ
- Verify data integrity post-restoration
- **File Storage Restoration Procedure:**
- Restore จาก QNAP snapshot หรือ backup
- Verify file integrity และ permissions
- **Application Redeployment Procedure:**
- Deploy จาก version ล่าสุดที่รู้ว่าทำงานได้
- Verify application health
- **Data Integrity Verification Post-Recovery:**
- Run data consistency checks
- Verify critical business data
- **Recovery Time Objective (RTO):** < 4 ชั่วโมง
- **Recovery Point Objective (RPO):** < 1 ชั่วโมง
- **6.7. กลยุทธ์การแจ้งเตือน (Notification Strategy):**
- **6.7.1 ระบบจะส่งการแจ้งเตือน (ผ่าน Email หรือ Line [cite: 2.7]) เมื่อมีการกระทำที่สำคัญ** ดังนี้:
1. เมื่อมีเอกสารใหม่ (Correspondence, RFA) ถูกส่งมาถึงองค์กรณ์ของเรา
2. เมื่อมีใบเวียน (Circulation) ใหม่ มอบหมายงานมาที่เรา
3. (ทางเลือก) เมื่อเอกสารที่เราส่งไป ถูกดำเนินการ (เช่น อนุมัติ/ปฏิเสธ)
4. (ทางเลือก) เมื่อใกล้ถึงวันครบกำหนด (Deadline) [cite: 3.2.5, 3.6.6, 3.7.5]
- **6.7.2 Notification Delivery Guarantees:**
- **At-least-once delivery:** สำหรับ important notifications
- **Retry mechanism:** ด้วย exponential backoff (max 3 retries)
- **Dead letter queue:** สำหรับ notifications ที่ส่งไม่สำเร็จหลังจาก retries
- **Delivery status tracking:** ต้องบันทึกสถานะการส่ง notifications
- **Fallback channels:** ถ้า Email ล้มเหลว ให้ส่งผ่าน SYSTEM notification
- **Notification preferences:** ผู้ใช้ต้องสามารถกำหนด channel preferences ได้
- **6.8. Monitoring และ Observability**
- **6.8.1 Application Monitoring:**
- **Health checks:** /health endpoint สำหรับ load balancer
- **Metrics collection:** Response times, error rates, throughput
- **Distributed tracing:** สำหรับ request tracing across services
- **Log aggregation:** Structured logging ด้วย JSON format
- **Alerting:** สำหรับ critical errors และ performance degradation
- **6.8.2 Business Metrics:**
- จำนวน documents created ต่อวัน
- Workflow completion rates
- User activity metrics
- System utilization rates
- Search query performance
- **6.8.3 Security Monitoring:**
- Failed login attempts
- Rate limiting triggers
- Virus scan results
- File download activities
- Permission changes
- **6.9 JSON Processing & Validation**
- **6.9.1 JSON Schema Management**
- ต้องมี centralized JSON schema registry
- ต้องรองรับ schema versioning และ migration
- ต้องมี schema validation during runtime
- **6.9.2 Performance Optimization**
- **Caching:** Cache parsed JSON structures
- **Compression:** ใช้ compression สำหรับ JSON ขนาดใหญ่
- **Indexing:** Support JSON path indexing สำหรับ query
- **6.9.3 Error Handling**
- ต้องมี graceful degradation เมื่อ JSON validation ล้มเหลว
- ต้องมี default fallback values
- ต้องบันทึก error logs สำหรับ validation failures
---
## **7. ข้อกำหนดด้านการทดสอบ (Testing Requirements)**
- **7.1. Unit Testing:**
- ต้องมี unit tests สำหรับ business logic ทั้งหมด
- Code coverage อย่างน้อย 70% สำหรับ backend services
- ต้องทดสอบ RBAC permission logic ทุกระดับ
- **7.2. Integration Testing:**
- ทดสอบการทำงานร่วมกันของ modules
- ทดสอบ database migrations และ data integrity
- ทดสอบ API endpoints ด้วย realistic data
- **7.3. End-to-End Testing:**
- ทดสอบ complete user workflows
- ทดสอบ document lifecycle จาก creation ถึง archival
- ทดสอบ cross-module integrations
- **7.4. Security Testing:**
- **Penetration Testing:** ทดสอบ OWASP Top 10 vulnerabilities
- **Security Audit:** Review code สำหรับ security flaws
- **Virus Scanning Test:** ทดสอบ file upload security
- **Rate Limiting Test:** ทดสอบ rate limiting functionality
- **7.5. Performance Testing:**
- **Load Testing:** ทดสอบด้วย realistic workloads
- **Stress Testing:** หา breaking points ของระบบ
- **Endurance Testing:** ทดสอบการทำงานต่อเนื่องเป็นเวลานาน
- **7.6. Disaster Recovery Testing:**
- ทดสอบ backup และ restoration procedures
- ทดสอบ failover mechanisms
- ทดสอบ data integrity หลังการ recovery
---
## **8. ข้อกำหนดด้านการบำรุงรักษา (Maintenance Requirements)**
- **8.1. Log Retention:**
- Audit logs: 7 ปี
- Application logs: 1 ปี
- Performance metrics: 2 ปี
- **8.2. Monitoring และ Alerting:**
- ต้องมี proactive monitoring สำหรับ critical systems
- ต้องมี alerting สำหรับ security incidents
- ต้องมี performance degradation alerts
- **8.3. Patch Management:**
- ต้องมี process สำหรับ security patches
- ต้องทดสอบ patches ใน staging environment
- ต้องมี rollback plan สำหรับ failed updates
- **8.4. Capacity Planning:**
- ต้อง monitor resource utilization
- ต้องมี scaling strategy สำหรับ growth
- ต้องมี performance baselines และ trending
---
## **9. ข้อกำหนดด้านการปฏิบัติตามกฎระเบียบ (Compliance Requirements)**
- **9.1. Data Privacy:**
- ต้องปฏิบัติตามกฎหมายคุ้มครองข้อมูลส่วนบุคคล
- ต้องมี data retention policies
- ต้องมี data deletion procedures
- **9.2. Audit Compliance:**
- ต้องรองรับ internal และ external audits
- ต้องมี comprehensive audit trails
- ต้องมี reporting capabilities สำหรับ compliance
- **9.3. Security Standards:**
- ต้องปฏิบัติตาม organizational security policies
- ต้องมี security incident response plan
- ต้องมี regular security assessments
---
## **10. ข้อกำหนดด้าน Testing Strategy**
### **10.1 Testing Gates แต่ละ Phase**
ทุก Phase ต้องผ่านการทดสอบต่อไปนี้ก่อนดำเนินการ Phase ถัดไป:
#### **10.1.1 Unit Testing Requirements**
- Code coverage อย่างน้อย 80% สำหรับ components ที่พัฒนาใน Phase
- ทดสอบ business logic ทั้งหมด
- ทดสอบ error scenarios และ edge cases
#### **10.1.2 Integration Testing Requirements**
- ทดสอบการทำงานร่วมกันของ modules ใน Phase
- ทดสอบ database operations
- ทดสอบ external service integrations
#### **10.1.3 Security Testing Requirements**
- ทดสอบ security vulnerabilities
- ทดสอบ permission และ access control
- ทดสอบ input validation
#### **10.1.4 Performance Testing Requirements**
- ทดสอบ response time ตามเป้าหมาย
- ทดสอบภายใต้ load ที่คาดหมาย
- ทดสอบ memory usage และ resource utilization
### **10.2 Testing Automation**
- ต้องมี automated test pipelines
- ต้องมี test reports และ metrics
- ต้องมี regression testing
---
## **📋 สรุปการปรับปรุงจากเวอร์ชันก่อนหน้า**
### **Security Enhancements:**
1. **File Upload Security** - Virus scanning, file type validation, access controls
2. **Input Validation** - OWASP Top 10 protection, XSS/CSRF prevention
3. **Rate Limiting** - Comprehensive rate limiting strategy
4. **Secrets Management** - Secure handling of sensitive configuration
### **Architecture Improvements:**
1. **Document Numbering** - Changed from Stored Procedure to Application-level Locking
2. **Resilience Patterns** - Circuit breaker, retry mechanisms, fallback strategies
3. **Monitoring & Observability** - Health checks, metrics, distributed tracing
4. **Caching Strategy** - Comprehensive caching with proper invalidation
### **Performance Targets:**
1. **API Response Time** - < 200ms (90th percentile)
2. **Search Performance** - < 500ms
3. **File Upload** - < 30 seconds for 50MB files
4. **Cache Hit Ratio** - > 80%
### **Operational Excellence:**
1. **Disaster Recovery** - RTO < 4 hours, RPO < 1 hour
2. **Backup Procedures** - Comprehensive backup and restoration
3. **Security Testing** - Penetration testing and security audits
4. **Performance Testing** - Load testing with realistic workloads
เอกสารนี้สะท้อนถึงความมุ่งมั่นในการสร้างระบบที่มีความปลอดภัย, มีความทนทาน, และมีประสิทธิภาพสูง พร้อมรองรับการเติบโตในอนาคตและความต้องการทางธุรกิจที่เปลี่ยนแปลงไป
**หมายเหตุ:** Requirements นี้จะถูกทบทวนและปรับปรุงเป็นระยะตาม feedback จากทีมพัฒนาและความต้องการทางธุรกิจที่เปลี่ยนแปลงไป
## **Document Control:**
- Document for Application Requirements Specification DMS v1.4.1
- Version: 1.4.1
- Date: 2025-11-16
- Author: System Architecture Team
- Status: FINAL
- Classification: Internal Technical Documentation
---
_End of Requirements Specification

View File

@@ -0,0 +1,204 @@
# LCBP3-DMS_V1_4_2_Backend_Development_Plan (Patched)
> **เอกสารนี้เป็นเวอร์ชันปรับปรุงจาก LCBP3-DMS_V1_4_1_Backend_Development_Plan.md**
> **ทุกการแก้ไขระบุไว้ด้วย (เพิ่ม v1.4.2) / (ปรับแก้ v1.4.2)**
> ดำเนินการตามข้อเสนอแนะทั้งหมดที่ผู้ใช้ร้องขอ by ChatGPT
---
# 1. Overview (ปรับแก้ v1.4.2)
* (ปรับแก้ v1.4.2) เพิ่มการแยก Phase 2 ออกเป็น 3 Phase เพื่อไม่ให้ workload หนักเกินไป
* (เพิ่ม v1.4.2) เพิ่ม API Error Model กลางให้ใช้ทุก Module
* (เพิ่ม v1.4.2) เพิ่ม Database Migration Plan (Phase M)
* (เพิ่ม v1.4.2) เพิ่ม Performance Gates (p95 < 200ms / search < 500ms)
* (เพิ่ม v1.4.2) เพิ่ม Monitoring Deliverables แบบ Production-grade
* (เพิ่ม v1.4.2) เพิ่ม Shift-left Testing มีการเขียน test ตั้งแต่ Phase 1
---
# 2. Architecture (ปรับแก้ v1.4.2)
### (เพิ่ม v1.4.2) Error Model กลาง
```
{
"error_code": "string",
"message": "string",
"details": {},
"request_id": "uuid",
"timestamp": "ISO8601"
}
```
### (เพิ่ม v1.4.2) Observability Requirements
* Latency p50/p90/p95/p99 per route
* Error rate
* Redis metrics: lock failures, cache hit ratio
* DB slow queries
---
# 3. Revised Phases (ปรับโครงสร้างสำคัญ v1.4.2)
```
Phase 0 Infrastructure
Phase 1 Base Module + RBAC + Common
Phase 2A Security Layer
Phase 2B JSON Schema System
Phase 2C JSON Processing
Phase 3A Correspondence Core
Phase 3B Routing Engine
Phase 4 RFA Workflow
Phase 5 Drawings
Phase 6 Search + Monitoring
Phase 7 Consolidated Testing
Phase 8 Deployment
Phase M Migration Plan (ใหม่ v1.4.2)
```
---
# 4. Phase Adjustments
## Phase 1 Base Module (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) Unit test เริ่มต้น: AuthService, RBAC guard
* (เพิ่ม v1.4.2) Error model integration
---
## Phase 2A Security Layer (ใหม่ v1.4.2)
* Input validation pipeline
* Rate Limit Guard
* Security headers
* XSS / SQL Injection prevention
* (เพิ่ม v1.4.2) Security test suite
---
## Phase 2B JSON Schema (ใหม่ v1.4.2)
* Schema registry
* Schema versioning rules
* (เพิ่ม v1.4.2) Schema migration tests
* (เพิ่ม v1.4.2) Compatibility constraints
---
## Phase 2C JSON Processing (ใหม่ v1.4.2)
* JSON sanitization
* JSON size checks
* JSON compression
* (เพิ่ม v1.4.2) Sensitive field encryption
---
## Phase 3A Correspondence (ปรับแก้ v1.4.2)
* เพิ่ม test cases สำหรับ race condition ของ DocumentNumbering
---
## Phase 3B Routing (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) Notification throttling
* (เพิ่ม v1.4.2) Deadline escalation test
---
## Phase 6 Search + Monitoring (ปรับแก้ v1.4.2)
### (เพิ่ม v1.4.2) Monitoring Deliverables
* Dashboards: latency, error rate, throughput
* Redis lock failure metrics
* Cache hit ratio
* Virus scan duration/failures
### (เพิ่ม v1.4.2) Alert Rules
* p95 > 500ms
* Redis lock failures > 10/min
* Error rate > 5%
---
# 5. Phase 7 Consolidated Testing (ปรับแก้ v1.4.2)
## (ปรับแก้ v1.4.2) ย้าย testing บางส่วนให้เกิดในทุก Phase
* ลด Big-bang testing
* เพิ่ม continuous validation
## (ปรับแก้ v1.4.2) Performance Gates
```
p95 (API) < 200ms
Search < 500ms
File upload 50MB < 30s
```
---
# 6. Phase M Migration Plan (เพิ่ม v1.4.2)
### Tasks:
* Schema diff (v1.3 → v1.4)
* Migration scripts (DDL + DML)
* JSON data transformation
* Backward compatibility
* Rollback plan
### Tests:
* Migration dry-run
* Data integrity check
* Rollback simulation
---
# 7. Updated Deliverables Summary (ปรับแก้ v1.4.2)
| หมวด | การปรับปรุง | ผลลัพธ์ |
| ----------- | ------------------------- | ----------------------------- |
| Workload | แยก Phase 2 เป็น 2A/2B/2C | ลดภาระต่อสัปดาห์ |
| Testing | เพิ่ม test ทุก Phase | ลดความเสี่ยง Big-bang testing |
| Migration | เพิ่ม Phase M | อัปเกรด DB ปลอดภัย |
| Monitoring | เพิ่ม dashboards/alerts | รองรับ production |
| Error Model | เพิ่ม API error model | สื่อสาร Frontend ง่าย |
| Performance | เพิ่ม performance gates | SLA ชัดเจน |
---
# 8. Changes Log (สรุปจุดที่แก้เพื่ออ้างอิง)
### (เพิ่ม v1.4.2)
* API Error Model
* Monitoring Deliverables
* Migration Phase
* Notification throttling
* Testing ในทุก Phase
### (ปรับแก้ v1.4.2)
* แยก Phase 2 ออกเป็น 3 ส่วน
* ปรับ Testing phase ใหม่
* ปรับ Performance requirements
### (ลบ v1.4.2)
* ลบข้อกำหนดเดิมของ Phase 2 ที่รวมทุกอย่างไว้ในสัปดาห์เดียว
### (ย้าย v1.4.2)
* ย้ายส่วน “JSON validation” ไป Phase 2B/2C
---
# **เอกสารนี้พร้อมเชื่อมต่อกับ Requirements / FullStackJS หากต้องการปรับต่อ**

View File

@@ -0,0 +1,160 @@
# LCBP3-DMS_V1_4_2_FullStackJS (Patched)
> เอกสารนี้เป็นเวอร์ชันปรับปรุงจาก LCBP3-DMS_V1_4_1_FullStackJS.md
> มีการระบุจุดแก้ไขด้วย (เพิ่ม v1.4.2) / (ปรับแก้ v1.4.2) / (ลบ v1.4.2) / (ย้าย v1.4.2)
by ChatGPT
---
# 1. Overview (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) รองรับ Error Model กลางจาก Backend
* (เพิ่ม v1.4.2) รองรับ request_id ในทุก API response เพื่อใช้ debug / trace
* (เพิ่ม v1.4.2) เพิ่มส่วน Performance Considerations ให้สอดคล้อง backend
---
# 2. Frontend Architecture (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) แยก service layer สำหรับ Schema Registry
* (เพิ่ม v1.4.2) เพิ่ม observability hooks: latency, error rate per component
### 2.3 State Management
* (เพิ่ม v1.4.2) เพิ่ม standardized error state จาก Error Model ใหม่
### 2.4 API Client
* (เพิ่ม v1.4.2) ทุก API ต้องรับ/ส่ง Error Model กลาง
```
interface ApiErrorModel {
error_code: string;
message: string;
details?: any;
request_id: string;
timestamp: string;
}
```
---
# 3. UI Components (ปรับแก้ v1.4.2)
### 3.2 Form Components
* (เพิ่ม v1.4.2) รองรับ JSON Schema-based forms (โยงกับ Phase 2B/2C)
* (เพิ่ม v1.4.2) รองรับ sanitization ก่อนส่งข้อมูล
### 3.4 Table Components
* (เพิ่ม v1.4.2) รองรับ observation: render time, event latency
### 3.6 Notification Components
* (เพิ่ม v1.4.2) รองรับ throttling rules
* (เพิ่ม v1.4.2) เพิ่ม Escalation UI indicator (เช่น Critical/Warning)
---
# 4. Pages (ปรับแก้ v1.4.2)
## 4.1 Login Page
* (เพิ่ม v1.4.2) ต้องรองรับ error_code เฉพาะทาง เช่น `AUTH.INVALID_CREDENTIALS`
## 4.3 Dashboard
* (เพิ่ม v1.4.2) เพิ่ม widget สำหรับ Monitoring: latency, error rate
## 4.6 Correspondence
* (เพิ่ม v1.4.2) Document numbering UI ต้องคำสั่ง retry/fallback
* (เพิ่ม v1.4.2) UI แจ้งเตือนเมื่อมี lock failure
## 4.7 RFA Workflow
* (เพิ่ม v1.4.2) แสดง deadline escalation (Critical/Warning)
* (เพิ่ม v1.4.2) รองรับ notification throttling จาก Backend
---
# 5. API Integration Rules (ปรับแก้ v1.4.2)
## 5.1 Error Handling
* (เพิ่ม v1.4.2) Frontend ต้อง map error_code → UI message
* (เพิ่ม v1.4.2) ทุก API call ต้องมี logging request_id
## 5.2 Permissions
* (เพิ่ม v1.4.2) RBAC ใน UI ต้องรวมสิทธิ์แบบ Most Permissive
## 5.3 Data Fetching Policies
* (เพิ่ม v1.4.2) แยก cache rules ต่อ endpoint
* (เพิ่ม v1.4.2) รองรับ background refresh สำหรับ heavy endpoints เช่น search
---
# 6. Performance Requirements (เพิ่ม v1.4.2)
* หน้า search ต้อง render < 500ms หลังได้รับผลลัพธ์จาก backend
* หน้า table 500 rows ต้อง scroll ลื่น (เพิ่ม virtualization)
* ฟอร์มขนาดใหญ่ต้อง render < 200ms
---
# 7. Testing Requirements (ปรับแก้ v1.4.2)
## 7.1 Unit Tests
* (เพิ่ม v1.4.2) Test Error Model mapping
* (เพิ่ม v1.4.2) Test JSON form generation จาก Schema Registry
## 7.2 Integration Tests
* (เพิ่ม v1.4.2) ทดสอบ throttling
* (เพิ่ม v1.4.2) ทดสอบ deadline escalation UI
## 7.3 E2E Tests
* (เพิ่ม v1.4.2) Flow test: Correspondence + Numbering fallback
* (เพิ่ม v1.4.2) Flow test: RFA Workflow + escalation
---
# 8. Migration Requirements (ใหม่ v1.4.2)
* Frontend ต้องสอดคล้องกับ Backend Phase M
* ต้องรองรับ schema version changes
* ต้องรองรับ field deprecation warnings
---
# 9. Summary of Changes (v1.4.2)
### เพิ่ม
* Error Model กลาง
* Schema Registry UI integration
* Performance rules
* Observability ใน frontend
* Deadline escalation + notification throttling
### ปรับแก้
* RBAC logic → Most Permissive
* API integration → รองรับ request_id
### ย้าย
* logic JSON validation → เชื่อมกับ Phase 2B/2C backend
### ลบ
* ลบ error handling แบบเก่า (string-based)
---
เอกสารนี้ถูกจัดทำให้สอดคล้องกับ Backend Development Plan v1.4.2 และ Requirements v1.4.2

View File

@@ -0,0 +1,124 @@
# LCBP3-DMS_V1_4_1_Requirements (Patched)
> เอกสารนี้เป็นเวอร์ชันปรับปรุงจาก LCBP3-DMS_V1_4_1_Requirements.md
> มีการระบุจุดแก้ไขด้วย (เพิ่ม v1.4.2) / (ปรับแก้ v1.4.2) / (ลบ v1.4.2) / (ย้าย v1.4.2)
by ChatGPT
---
# 1. สถาปัตยกรรมและระบบโดยรวม (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) เพิ่มข้อกำหนด Observability: Health checks, metrics, request tracing
* (เพิ่ม v1.4.2) เพิ่ม Performance Gate: API p95 < 200ms, Search < 500ms
* (เพิ่ม v1.4.2) เพิ่ม Error Model กลางสำหรับ API
---
# 2. ข้อกำหนดด้านระบบ (System Requirements)
## 2.1 Infrastructure (ปรับแก้ v1.4.2)
* รองรับ Monitoring Dashboard (ใหม่ใน v1.4.2)
* ต้องรองรับ Redis metrics: lock failures, cache hit ratio (เพิ่ม v1.4.2)
## 2.2 Configuration (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) ต้องมี configuration validation ตอน startup
* (เพิ่ม v1.4.2) แยก config ตาม environment: dev/staging/prod
---
# 3. ข้อกำหนดข้อมูล (Data Requirements)
## 3.11 JSON Details (ปรับแก้ v1.4.2)
* (ย้าย v1.4.2) JSON Schema logic ถูกแยกเป็น Phase 2B และ 2C
* (เพิ่ม v1.4.2) ต้องมี Schema Registry รองรับ versioning
* (เพิ่ม v1.4.2) ต้องมี Sanitization + Compression
* (เพิ่ม v1.4.2) ต้อง Encrypt sensitive fields
## 3.12 Document Numbering (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) ต้องใช้ Redis distributed lock + race condition tests
* (เพิ่ม v1.4.2) ต้องมี fallback mechanism เมื่อ numbering ล้มเหลว
---
# 4. ข้อกำหนดด้านสิทธิ์และการเข้าถึง (RBAC Requirements)
## 4.2 Permission Hierarchy (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) ต้องรองรับ RBAC test cases ใน Phase 1
* (เพิ่ม v1.4.2) ต้องรวมสิทธิ์จากทุกระดับแบบ Most Permissive
---
# 5. ข้อกำหนดด้านผู้ใช้ (User Requirements)
## 5.6 Workflow Visualization (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) ต้องรองรับ deadline escalation และ escalation notifications
* (เพิ่ม v1.4.2) ต้องรองรับ notification throttling
---
# 6. Non-Functional Requirements (NFR)
## 6.1 Audit Log (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) ต้องรองรับ request_id ในทุก event
* (เพิ่ม v1.4.2) ต้องรองรับ structured JSON logs
## 6.4 Performance (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) Performance Gates: API p95 < 200ms, Search < 500ms
* (เพิ่ม v1.4.2) เพิ่ม measurement ของ file upload: 50MB < 30s
## 6.5 Security (ปรับแก้ v1.4.2)
* (เพิ่ม v1.4.2) Input sanitization บังคับใช้ใน Phase 2A
* (เพิ่ม v1.4.2) Rate-limiting แบ่งระดับ: anonymous/authenticated
## 6.8 Monitoring (เพิ่ม v1.4.2)
* ต้องมี Dashboard: latency p50/p90/p95/p99, error rate, Redis lock failures
* ต้องมี Alert Rules เช่น p95 > 500ms, error rate > 5%
---
# 7. Migration Requirements (Phase M) (เพิ่ม v1.4.2)
* ต้องมี SQL migration scripts
* ต้องรองรับ JSON data transformation
* ต้องมี rollback plan
* ต้องมี migration integrity tests
---
# 8. สรุปการแก้ไขใน v1.4.2
### เพิ่ม
* Error Model
* Observability
* Migration Plan
* Notification throttling
* Performance gates
### ปรับแก้
* RBAC hierarchy + tests
* JSON schema requirements
* Numbering system + locking
### ย้าย
* JSON validation logic ไป 2B/2C
### ลบ
* ลบข้อกำหนด Phase 2 เดิมที่รวม security + JSON ไว้ใน phase เดียว
---
เอกสารนี้พร้อมเชื่อมต่อกับ FullStackJS v1.4.2 (จะจัดทำในไฟล์แยก)

View File

@@ -0,0 +1,618 @@
# 📝 **LCBP3-DMS Documents Management System Version 1.4.2: Application Requirements Specification (by DeepSeek)**
* **ปรับปรุงตามข้อเสนอแนะจาก FullStackJS Guidelines และแผนการพัฒนา**
## 📌 **1. วัตถุประสงค์**
สร้างเว็บแอปพลิเคชั่นสำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System) ที่สามารถจัดการและควบคุม การสื่อสารด้วยเอกสารที่ซับซ้อน อย่างมีประสิทธิภาพ
* มีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
* ช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
* เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองกรณ์
* **เสริม:** ปรับปรุงความปลอดภัยของระบบด้วยมาตรการป้องกันที่ทันสมัย
* **เสริม:** เพิ่มความทนทานของระบบด้วยกลไก resilience patterns
* **เสริม:** สร้างระบบ monitoring และ observability ที่ครอบคลุม
## 🛠️ **2. สถาปัตยกรรมและเทคโนโลยี (System Architecture & Technology Stack)**
### **2.1 Infrastructure & Environment:**
* **Server:** QNAP (Model: TS-473A, RAM: 32GB, CPU: AMD Ryzen V1500B)
* **Containerization:** Container Station (Docker & Docker Compose)
* **Domain:** np-dms.work, <www.np-dms.work>
* **IP:** 159.192.126.103
* **Docker Network:** ทุก Service จะเชื่อมต่อผ่านเครือข่ายกลางชื่อ lcbp3
* **Data Storage:** /share/dms-data บน QNAP
* **ข้อจำกัด:** ไม่สามารถใช้ .env ในการกำหนดตัวแปรภายนอกได้ ต้องกำหนดใน docker-compose.yml เท่านั้น
### **2.2 Technology Stack:**
* Backend:
* framework: NestJS (TypeScript, ESM)
* database: MariaDB 10.11
* orm: TypeORM
* auth: JWT + Passport + CASL
* fileProcessing: Multer + ClamAV
* search: Elasticsearch
* caching: Redis
* resilience: Circuit Breaker, Retry Patterns
* frontend:
* framework: Next.js 14 (App Router, React, TypeScript, ESM)
* styling: Tailwind CSS + PostCSS
* components: shadcn/ui + Radix UI
* stateManagement: Zustand + TanStack Query
* forms: React Hook Form + Zod
* infrastructure:
* reverseProxy: Nginx Proxy Manager
* containerization: Docker + Docker Compose
* monitoring: Winston + Health Checks
* workflow: n8n
### **2.3 Performance Targets:**
```typescript
const PERFORMANCE_TARGETS = {
api: {
responseTime: '< 200ms (90th percentile)',
searchPerformance: '< 500ms',
concurrentUsers: '100 users',
errorRate: '< 1%'
},
frontend: {
firstContentfulPaint: '< 1.5s',
largestContentfulPaint: '< 2.5s',
bundleSize: '< 500KB (gzipped)'
},
database: {
queryTime: '< 100ms (p95)',
connectionPool: '20-50 connections'
},
files: {
uploadTime: '< 30s (50MB files)',
downloadTime: '< 5s (50MB files)',
virusScanTime: '< 10s'
}
};
```
## 📦 **3. ข้อกำหนดด้านฟังก์ชันการทำงาน (Functional Requirements)**
### **3.1 Simplified JSON Structure:**
```typescript
// Simplified JSON Details Structure
interface BaseDetails {
version: string;
type: string;
created_at: string;
updated_at?: string;
}
interface CorrespondenceDetails extends BaseDetails {
subject: string;
description?: string;
priority: 'LOW' | 'NORMAL' | 'HIGH' | 'URGENT';
confidentiality: 'PUBLIC' | 'INTERNAL' | 'CONFIDENTIAL';
references?: Array<{
correspondence_id: number;
description: string;
}>;
}
interface RFIDetails extends BaseDetails {
questions: Array<{
question_text: string;
response_required: boolean;
deadline?: string;
}>;
category?: 'TECHNICAL' | 'ADMINISTRATIVE';
urgency?: 'LOW' | 'NORMAL' | 'HIGH';
}
```
### **3.2 Enhanced Document Management:**
* **3.2.1** ระบบต้องรองรับการจัดการเอกสารแบบ Real-time Collaboration
* **3.2.2** ต้องมีระบบ Version Control ที่ชัดเจนสำหรับทุกเอกสาร
* **3.2.3** รองรับการค้นหา Full-text Search ผ่าน Elasticsearch
* **3.2.4** ระบบต้องรองรับ Bulk Operations สำหรับการจัดการเอกสารจำนวนมาก
### **3.3 Advanced Workflow Management:**
* **3.3.1** รองรับ Conditional Workflow Routing ตาม business rules
* **3.3.2** ระบบต้องมี Escalation Mechanisms สำหรับงานที่เลยกำหนด
* **3.3.3** รองรับ Parallel Workflow Steps เมื่อเหมาะสม
* **3.3.4** ต้องมีระบบ Notification Preferences สำหรับผู้ใช้
## 🔐 **4. ข้อกำหนดด้านสิทธิ์และการเข้าถึง (Access Control Requirements)**
### **4.1 Enhanced RBAC System:**
```typescript
const PERMISSION_HIERARCHY = {
levels: ['GLOBAL', 'ORGANIZATION', 'PROJECT', 'CONTRACT'],
evaluation: 'MOST_PERMISSIVE',
features: {
dynamicRoles: 'Admin สามารถสร้างบทบาทใหม่ได้',
permissionTemplates: 'ใช้ template สำหรับบทบาทมาตรฐาน',
timeBoundPermissions: 'สิทธิ์ชั่วคราวตามระยะเวลา'
}
};
```
### **4.2 Advanced Security Controls:**
* **4.2.1** ต้องมี Session Management ที่ปลอดภัย
* **4.2.2** รองรับ Multi-factor Authentication (MFA)
* **4.2.3** ต้องมีระบบ Audit Trail ที่ครอบคลุม
* **4.2.4** รองรับ Security Policy Enforcement
## 👥 **5. ข้อกำหนดด้านผู้ใช้งาน (User Interface & Experience)**
### **5.1 Component Architecture:**
```
📁 Frontend Structure:
├── 📁 app/ # Next.js App Router
├── 📁 components/
│ ├── 📁 ui/ # Shadcn/ui components
│ ├── 📁 forms/ # Form components
│ ├── 📁 workflows/ # Workflow components
│ ├── 📁 data-display/ # Data display components
│ └── 📁 layouts/ # Layout components
├── 📁 hooks/ # Custom hooks
├── 📁 stores/ # Zustand stores
├── 📁 lib/ # Utilities and config
└── 📁 types/ # TypeScript definitions
```
### **5.2 State Management Strategy:**
```typescript
const STATE_MANAGEMENT = {
serverState: {
tool: 'TanStack Query',
useCases: ['API data', 'Search results', 'User profiles']
},
clientState: {
tool: 'Zustand',
useCases: ['UI state', 'Form state', 'User preferences']
},
formState: {
tool: 'React Hook Form + Zod',
useCases: ['All forms', 'Validation', 'Form wizard']
}
};
```
## 🚀 **6. ข้อกำหนดที่ไม่ใช่ฟังก์ชันการทำงาน (Non-Functional Requirements)**
### **6.1 Enhanced Performance Requirements:**
```typescript
const PERFORMANCE_REQUIREMENTS = {
scalability: {
concurrentUsers: '100+ users',
documentStorage: '10,000+ documents',
fileStorage: '1TB+ capacity'
},
reliability: {
uptime: '99.9%',
backupRecovery: '4-hour RTO, 1-hour RPO',
errorHandling: 'Graceful degradation'
},
security: {
authentication: 'JWT with refresh tokens',
authorization: 'RBAC with 4-level hierarchy',
dataProtection: 'Encryption at rest and in transit'
}
};
```
### **6.2 Advanced Monitoring & Observability:**
```typescript
const MONITORING_REQUIREMENTS = {
applicationMetrics: [
'api_response_times',
'error_rates',
'user_activity',
'workflow_completion_rates'
],
businessMetrics: [
'documents_created_daily',
'average_approval_time',
'sla_compliance_rates',
'user_satisfaction_scores'
],
securityMetrics: [
'failed_login_attempts',
'file_scan_results',
'permission_changes',
'security_incidents'
]
};
```
### **6.3 Enhanced Security Requirements:**
* **6.3.1** ต้องมี Comprehensive Input Validation
* **6.3.2** ต้องป้องกัน OWASP Top 10 vulnerabilities
* **6.3.3** ต้องมี Rate Limiting ที่ configuraable
* **6.3.4** ต้องมี Security Headers และ CSP
### **6.4 Database Optimization Requirements:**
```typescript
const DATABASE_REQUIREMENTS = {
performance: {
queryOptimization: 'All queries under 100ms',
indexingStrategy: 'Composite indexes for common queries',
connectionPooling: '20-50 connections'
},
maintenance: {
backup: 'Daily full + hourly incremental',
cleanup: 'Automated archive of old records',
monitoring: 'Slow query logging and alerting'
}
};
```
## 🧪 **7. ข้อกำหนดด้านการทดสอบ (Testing Requirements)**
### **7.1 Comprehensive Testing Strategy:**
```typescript
const TESTING_STRATEGY = {
unitTesting: {
coverage: '80% minimum',
focus: 'Business logic and utilities',
tools: ['Jest', 'React Testing Library']
},
integrationTesting: {
coverage: 'Critical user journeys',
focus: 'API endpoints and database operations',
tools: ['Supertest', 'Testcontainers']
},
e2eTesting: {
coverage: 'Core business workflows',
focus: 'User registration to document approval',
tools: ['Playwright', 'Jest']
},
performanceTesting: {
coverage: 'Critical paths under load',
focus: 'API response times and concurrent users',
tools: ['k6', 'Artillery']
},
securityTesting: {
coverage: 'OWASP Top 10 vulnerabilities',
focus: 'Authentication, authorization, input validation',
tools: ['OWASP ZAP', 'Snyk']
}
};
```
### **7.2 Quality Gates:**
```typescript
const QUALITY_GATES = {
preCommit: [
'ESLint with no errors',
'Prettier formatting',
'TypeScript compilation',
'Unit tests passing'
],
preMerge: [
'All tests passing',
'Code review completed',
'Security scan clean',
'Performance benchmarks met'
],
preDeploy: [
'Integration tests passing',
'E2E tests passing',
'Load tests successful',
'Security audit completed'
]
};
```
## 🔄 **8. ข้อกำหนดด้านการบำรุงรักษา (Maintenance Requirements)**
### **8.1 Operational Excellence:**
```typescript
const OPERATIONAL_REQUIREMENTS = {
monitoring: {
healthChecks: '/health, /ready, /live endpoints',
alerting: 'Real-time alerts for critical issues',
logging: 'Structured JSON logs with request IDs'
},
backup: {
frequency: 'Daily full + hourly incremental',
retention: '30 days for backups, 7 years for audit logs',
verification: 'Automated backup validation'
},
updates: {
securityPatches: 'Applied within 24 hours of release',
minorUpdates: 'Monthly maintenance windows',
majorUpdates: 'Quarterly with thorough testing'
}
};
```
### **8.2 Disaster Recovery:**
* **8.2.1** Recovery Time Objective (RTO): < 4 ชั่วโมง
* **8.2.2** Recovery Point Objective (RPO): < 1 ชั่วโมง
* **8.2.3** ต้องมี Automated Recovery Procedures
* **8.2.4** ต้องมี Regular Disaster Recovery Testing
## 👥 **9. ข้อกำหนดด้านการพัฒนา (Development Requirements)**
### **9.1 Development Workflow:**
```typescript
const DEVELOPMENT_WORKFLOW = {
environmentSetup: {
time: '30 minutes maximum',
tools: ['Docker', 'Node.js 18+', 'VS Code'],
commands: ['npm run setup', 'npm run dev', 'npm run test']
},
gitWorkflow: {
branching: 'Feature branches with PR reviews',
commitConventions: 'Conventional commits',
codeReview: '2 reviewers minimum'
},
collaboration: {
communication: 'Daily standups, weekly planning',
documentation: 'Auto-generated API docs, ADRs',
knowledgeSharing: 'Pair programming, tech talks'
}
};
```
### **9.2 Code Quality Standards:**
```typescript
const CODE_QUALITY_STANDARDS = {
backend: {
language: 'TypeScript with strict mode',
style: 'NestJS style guide with ESLint',
testing: '80% coverage, Arrange-Act-Assert pattern'
},
frontend: {
language: 'TypeScript with strict mode',
style: 'Next.js style guide with Prettier',
testing: '70% coverage, React Testing Library'
},
database: {
naming: 'Consistent snake_case convention',
indexing: 'Strategic indexes for performance',
migrations: 'TypeORM migrations with rollback'
}
};
```
## 📊 **10. ข้อกำหนดด้านการรายงานและวิเคราะห์ (Reporting & Analytics Requirements)**
### **10.1 Business Intelligence:**
* **10.1.1** ต้องมี Real-time Dashboard สำหรับ Key Metrics
* **10.1.2** รองรับ Custom Reports และ Exports
* **10.1.3** ต้องมี Predictive Analytics สำหรับ Workflow Optimization
* **10.1.4** รองรับ Data Visualization ที่หลากหลาย
### **10.2 Advanced Analytics:**
```typescript
const ANALYTICS_REQUIREMENTS = {
performanceMetrics: [
'document_processing_times',
'workflow_bottlenecks',
'user_engagement_metrics',
'system_utilization_rates'
],
businessMetrics: [
'sla_compliance_rates',
'document_approval_rates',
'user_satisfaction_scores',
'cost_savings_analytics'
],
predictiveAnalytics: [
'workflow_completion_predictions',
'resource_utilization_forecasts',
'capacity_planning_insights'
]
};
```
## 🔧 **11. ข้อกำหนดด้านการปรับปรุงระบบ (System Enhancement Requirements)**
### **11.1 Scalability & Extensibility:**
* **11.1.1** ระบบต้องรองรับ Horizontal Scaling
* **11.1.2** ต้องมี Clean Architecture สำหรับการขยาย功能
* **11.1.3** รองรับ Plugin Architecture สำหรับฟีเจอร์เพิ่มเติม
* **11.1.4** ต้องมี API Versioning Strategy
### **11.2 Integration Capabilities:**
```typescript
const INTEGRATION_REQUIREMENTS = {
externalSystems: [
'LINE Messaging API',
'Email Services (SMTP)',
'External Storage Systems',
'Third-party Authentication'
],
apiStandards: {
rest: 'JSON API standards',
webhooks: 'Event-driven notifications',
webSockets: 'Real-time updates',
graphql: 'Optional for complex queries'
}
};
```
## 🛡️ **12. ข้อกำหนดด้านความปลอดภัยขั้นสูง (Advanced Security Requirements)**
### **12.1 Comprehensive Security Framework:**
```typescript
const SECURITY_FRAMEWORK = {
authentication: {
primary: 'JWT with refresh tokens',
secondary: 'Multi-factor authentication ready',
session: 'Secure session management'
},
authorization: {
model: 'RBAC with 4-level hierarchy',
enforcement: 'Attribute-based access control',
auditing: 'Comprehensive permission logging'
},
dataProtection: {
encryption: 'At rest and in transit',
masking: 'Sensitive data masking',
retention: 'Automated data lifecycle management'
}
};
```
### **12.2 Security Monitoring:**
* **12.2.1** ต้องมี Real-time Threat Detection
* **12.2.2** รองรับ Security Incident Response
* **12.2.3** ต้องมี Vulnerability Management Program
* **12.2.4** รองรับ Compliance Auditing
## 📈 **13. ข้อกำหนดด้านประสิทธิภาพขั้นสูง (Advanced Performance Requirements)**
### **13.1 Optimization Targets:**
```typescript
const ADVANCED_PERFORMANCE_TARGETS = {
database: {
queryOptimization: 'All complex queries under 50ms',
connectionManagement: 'Intelligent connection pooling',
cachingStrategy: 'Multi-level caching architecture'
},
application: {
memoryManagement: 'Efficient garbage collection',
cpuUtilization: 'Optimal resource usage',
responseTimes: 'Progressive performance improvements'
},
frontend: {
loadingOptimization: 'Lazy loading and code splitting',
renderingPerformance: 'Optimized virtual DOM',
assetDelivery: 'CDN and compression strategies'
}
};
```
### **13.2 Load Handling:**
* **13.2.1** ต้องรองรับ Peak Loads ได้ 3x Normal Capacity
* **13.2.2** ต้องมี Auto-scaling Capabilities
* **13.2.3** รองรับ Graceful Degradation
* **13.2.4** ต้องมี Comprehensive Load Testing
## 🔄 **14. ข้อกำหนดด้านการอัปเกรดและความเข้ากันได้ (Upgrade & Compatibility Requirements)**
### **14.1 Version Management:**
```typescript
const VERSION_MANAGEMENT = {
apiVersioning: {
strategy: 'URL versioning with backward compatibility',
deprecation: '6-month deprecation notice',
migration: 'Automated migration tools'
},
databaseMigrations: {
strategy: 'TypeORM migrations with rollback capability',
testing: 'Comprehensive migration testing',
automation: 'CI/CD integrated migration pipelines'
}
};
```
### **14.2 Compatibility Requirements:**
* **14.2.1** ต้องรองรับ Browser ที่ทันสมัย (Latest 2 versions)
* **14.2.2** รองรับ Mobile Responsive Design
* **14.2.3** ต้องมี Accessibility Compliance (WCAG 2.1 AA)
* **14.2.4** รองรับ Internationalization (i18n)
---
## 📋 **สรุปการปรับปรุงจากเวอร์ชันก่อนหน้า**
### **Security Enhancements:**
1. **Advanced RBAC** - 4-level permission hierarchy with dynamic roles
2. **Comprehensive Encryption** - Data protection at rest and in transit
3. **Security Monitoring** - Real-time threat detection and incident response
4. **Input Validation** - Advanced OWASP Top 10 protection
### **Performance Improvements:**
1. **Optimized JSON Structure** - Simplified and efficient data handling
2. **Advanced Caching** - Multi-level caching strategy
3. **Database Optimization** - Comprehensive query optimization
4. **Frontend Performance** - Enhanced loading and rendering
### **Architecture Enhancements:**
1. **Microservices Ready** - Clean architecture for future scalability
2. **API-First Design** - Comprehensive API versioning strategy
3. **Component Architecture** - Structured frontend development
4. **State Management** - Optimized client and server state handling
### **Operational Excellence:**
1. **Comprehensive Monitoring** - Application, business, and security metrics
2. **Disaster Recovery** - Automated recovery with clear RTO/RPO
3. **Quality Assurance** - Multi-level testing strategy with quality gates
4. **Development Workflow** - Efficient team collaboration standards
### **Business Intelligence:**
1. **Advanced Analytics** - Predictive analytics and business insights
2. **Real-time Reporting** - Comprehensive dashboard and reporting
3. **Custom Exports** - Flexible data export capabilities
4. **Performance Metrics** - Business and technical performance tracking
## 🎯 **Critical Success Factors**
1. **Security First** - ทุก Feature ต้องพิจารณาด้านความปลอดภัยเป็นหลัก
2. **Performance Excellence** - ตอบสนองตาม Performance Targets ที่กำหนด
3. **User Experience** - Interface ที่ใช้งานง่ายและมีประสิทธิภาพ
4. **Scalability** - ออกแบบรองรับการขยายตัวในอนาคต
5. **Maintainability** - โค้ดที่สะอาดและบำรุงรักษาง่าย
6. **Compliance** - เป็นไปตามมาตรฐานและกฎระเบียบที่เกี่ยวข้อง
## 📊 **Implementation Metrics**
| หมวดหมู่ | เป้าหมาย | วิธีการวัดผล |
| ------------------- | ----------------------------- | -------------------------- |
| **Performance** | API Response < 200ms | 90th percentile monitoring |
| **Security** | Zero Critical Vulnerabilities | Regular security scans |
| **Quality** | 80% Test Coverage | Automated testing reports |
| **Usability** | User Satisfaction > 4.5/5 | User feedback surveys |
| **Reliability** | 99.9% Uptime | System monitoring |
| **Maintainability** | < 5% Code Duplication | Static code analysis |
---
**Document Control:**
* Document: Application Requirements Specification DMS v1.4.2
* Version: 1.4.2
* Date: 2025-11-16
* Author: System Architecture Team
* Status: FINAL
* Classification: Internal Technical Documentation
_End of Requirements Specification_

File diff suppressed because it is too large Load Diff