260224:1606 20260224:1600 V1.8.0
All checks were successful
Build and Deploy / deploy (push) Successful in 6m25s
All checks were successful
Build and Deploy / deploy (push) Successful in 6m25s
This commit is contained in:
682
specs/99-archives/docs/backup/03.11-document-numbering-add.md
Normal file
682
specs/99-archives/docs/backup/03.11-document-numbering-add.md
Normal file
@@ -0,0 +1,682 @@
|
||||
# Document Numbering Requirements
|
||||
|
||||
**Version**: 1.6.1
|
||||
**Last Updated**: 2025-01-16
|
||||
**Status**: draft
|
||||
**Related ADRs**: ADR-018-document-numbering-strategy
|
||||
|
||||
---
|
||||
|
||||
## 1. Overview
|
||||
|
||||
### 1.1 Purpose
|
||||
ระบบ Document Numbering สำหรับสร้างเลขที่เอกสารอัตโนมัติที่มีความเป็นเอกลักษณ์ (unique) และสามารถติดตามได้ (traceable) สำหรับเอกสารทุกประเภทในระบบ LCBP3-DMS
|
||||
|
||||
### 1.2 Scope
|
||||
- Auto-generation ของเลขที่เอกสารตามรูปแบบที่กำหนด
|
||||
- Manual override สำหรับการ import เอกสารเก่า
|
||||
- Cancelled number handling (ไม่ reuse)
|
||||
- Void & Replace pattern สำหรับการแทนที่เอกสาร
|
||||
- Distributed locking เพื่อป้องกัน race condition
|
||||
- Complete audit trail สำหรับทุก operation
|
||||
|
||||
### 1.3 Document Types Supported
|
||||
- Correspondences (COR)
|
||||
- Request for Approvals (RFA)
|
||||
- Contract Drawings (CD)
|
||||
- Shop Drawings (SD)
|
||||
- Transmittals (TRN)
|
||||
- Circulation Sheets (CIR)
|
||||
|
||||
---
|
||||
|
||||
## 2. Functional Requirements
|
||||
|
||||
### 2.1 Auto Number Generation
|
||||
|
||||
#### FR-DN-001: Generate Sequential Number
|
||||
**Priority**: CRITICAL
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องสามารถสร้างเลขที่เอกสารอัตโนมัติตามลำดับ (sequential) โดยไม่ซ้ำกัน
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- เลขที่เอกสารต้องเป็น unique ใน scope ที่กำหนด
|
||||
- ต้องเพิ่มขึ้นทีละ 1 (increment by 1)
|
||||
- ต้องรองรับ concurrent requests โดยไม่มีเลขที่ซ้ำ
|
||||
- Response time < 100ms (p95)
|
||||
|
||||
**Example**:
|
||||
```
|
||||
COR-00001-2025
|
||||
COR-00002-2025
|
||||
COR-00003-2025
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-002: Configurable Number Format
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องรองรับการกำหนดรูปแบบเลขที่เอกสารที่หลากหลาย
|
||||
|
||||
**Format Tokens**:
|
||||
- `{PREFIX}` - คำนำหน้าตามประเภทเอกสาร (e.g., COR, RFA)
|
||||
- `{YYYY}` - ปี 4 หลัก (e.g., 2025)
|
||||
- `{YY}` - ปี 2 หลัก (e.g., 25)
|
||||
- `{MM}` - เดือน 2 หลัก (e.g., 01-12)
|
||||
- `{SEQ:n}` - sequence number ความยาว n หลัก (e.g., {SEQ:5} = 00001)
|
||||
- `{PROJECT}` - รหัสโครงการ
|
||||
- `{CONTRACT}` - รหัสสัญญา
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- รองรับ format tokens ที่ระบุ
|
||||
- Admin สามารถกำหนด format ผ่าน UI ได้
|
||||
- Validate format ก่อน save
|
||||
- แสดง preview ของเลขที่ที่จะถูกสร้าง
|
||||
|
||||
**Examples**:
|
||||
```typescript
|
||||
// Correspondence format
|
||||
"COR-{YYYY}-{SEQ:5}"
|
||||
→ COR-2025-00001
|
||||
|
||||
// RFA format with project
|
||||
"RFA-{PROJECT}-{YYYY}{MM}-{SEQ:4}"
|
||||
→ RFA-LCBP3-202501-0001
|
||||
|
||||
// Drawing format
|
||||
"{CONTRACT}-CD-{SEQ:6}"
|
||||
→ C001-CD-000001
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-003: Scope-based Sequences
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องรองรับการสร้าง sequence ที่แยกตาม scope ที่ต่างกัน
|
||||
|
||||
**Scopes**:
|
||||
1. **Global**: Sequence ระดับระบบทั้งหมด
|
||||
2. **Project**: Sequence แยกตามโครงการ
|
||||
3. **Contract**: Sequence แยกตามสัญญา
|
||||
4. **Yearly**: Sequence reset ทุกปี
|
||||
5. **Monthly**: Sequence reset ทุกเดือน
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- เลขที่ไม่ซ้ำภายใน scope เดียวกัน
|
||||
- Scope ที่ต่างกันสามารถมีเลขที่เดียวกันได้
|
||||
- Support multiple active scopes
|
||||
|
||||
**Example**:
|
||||
```
|
||||
Project A: COR-A-2025-00001, COR-A-2025-00002
|
||||
Project B: COR-B-2025-00001, COR-B-2025-00002
|
||||
|
||||
Yearly Reset:
|
||||
COR-2024-00999 (Dec 2024)
|
||||
COR-2025-00001 (Jan 2025)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.2 Manual Override
|
||||
|
||||
#### FR-DN-004: Manual Number Assignment
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องรองรับการกำหนดเลขที่เอกสารด้วยตนเอง (manual override)
|
||||
|
||||
**Use Cases**:
|
||||
1. Import เอกสารเก่าจากระบบเดิม
|
||||
2. External documents จาก client/consultant
|
||||
3. Correction หลังพบความผิดพลาด
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- ตรวจสอบ duplicate ก่อน save
|
||||
- Validate format ตามรูปแบบที่กำหนด
|
||||
- Auto-update sequence counter ถ้าเลขที่สูงกว่า current
|
||||
- บันทึก audit log ว่าเป็น manual override
|
||||
- ต้องมีสิทธิ์ Admin ขึ้นไปเท่านั้น
|
||||
|
||||
**Validation Rules**:
|
||||
```typescript
|
||||
interface ManualNumberValidation {
|
||||
format_match: boolean; // ตรง format หรือไม่
|
||||
not_duplicate: boolean; // ไม่ซ้ำ
|
||||
in_valid_range: boolean; // อยู่ในช่วงที่กำหนด
|
||||
permission_granted: boolean; // มีสิทธิ์
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-005: Bulk Import Support
|
||||
**Priority**: MEDIUM
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องรองรับการ import เอกสารหลายรายการพร้อมกัน
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- รองรับไฟล์ CSV/Excel
|
||||
- Validate ทุกรายการก่อน import
|
||||
- แสดง preview ก่อน confirm
|
||||
- Rollback ทั้งหมดถ้ามีรายการใดผิดพลาด (transactional)
|
||||
- Auto-update sequence counters หลัง import
|
||||
- Generate import report
|
||||
|
||||
**CSV Format**:
|
||||
```csv
|
||||
document_type,document_number,created_at,metadata
|
||||
COR,COR-2024-00001,2024-01-01,{"imported":true}
|
||||
COR,COR-2024-00002,2024-01-05,{"imported":true}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.3 Cancelled & Void Handling
|
||||
|
||||
#### FR-DN-006: Skip Cancelled Numbers
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
เลขที่เอกสารที่ถูกยกเลิกต้องไม่ถูก reuse
|
||||
|
||||
**Rationale**:
|
||||
- รักษา audit trail ที่ชัดเจน
|
||||
- ป้องกันความสับสน
|
||||
- Legal compliance
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- Cancelled number ยังคงอยู่ในฐานข้อมูลพร้อม status
|
||||
- ระบบข้าม (skip) cancelled number เมื่อสร้างเลขที่ใหม่
|
||||
- บันทึกเหตุผลการยกเลิก
|
||||
- แสดง cancelled numbers ใน audit trail
|
||||
|
||||
**Example Timeline**:
|
||||
```
|
||||
2025-00001 ✅ ACTIVE (created 2025-01-01)
|
||||
2025-00002 ❌ CANCELLED (created 2025-01-02, cancelled 2025-01-03)
|
||||
2025-00003 ✅ ACTIVE (created 2025-01-04)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-007: Void and Replace
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องรองรับการ void เอกสารและสร้างเอกสารใหม่แทน
|
||||
|
||||
**Workflow**:
|
||||
1. User เลือกเอกสารที่ต้องการ void
|
||||
2. ระบุเหตุผล (required)
|
||||
3. ระบบเปลี่ยน status เอกสารเดิมเป็น VOID
|
||||
4. สร้างเอกสารใหม่ด้วยเลขที่ใหม่
|
||||
5. Link เอกสารใหม่กับเดิม (voided_from_id)
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- เอกสารเดิม status = VOID (ไม่ลบ)
|
||||
- เอกสารใหม่ได้เลขที่ต่อเนื่องจาก sequence
|
||||
- มี reference link ระหว่างเอกสาร
|
||||
- บันทึก void reason
|
||||
- แสดง void history chain (A→B→C)
|
||||
|
||||
**Database Relationship**:
|
||||
```sql
|
||||
-- Original document
|
||||
id: 100
|
||||
document_number: COR-2025-00005
|
||||
status: VOID
|
||||
void_reason: "ข้อมูลผิด"
|
||||
voided_at: 2025-01-10
|
||||
|
||||
-- Replacement document
|
||||
id: 101
|
||||
document_number: COR-2025-00006
|
||||
status: ACTIVE
|
||||
voided_from_id: 100
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.4 Concurrency & Performance
|
||||
|
||||
#### FR-DN-008: Prevent Race Conditions
|
||||
**Priority**: CRITICAL
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ระบบต้องป้องกันการสร้างเลขที่ซ้ำเมื่อมีการ request พร้อมกัน
|
||||
|
||||
**Solution**:
|
||||
- Distributed locking (Redlock)
|
||||
- Database pessimistic locking
|
||||
- Two-phase commit pattern
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- Zero duplicate numbers ภายใต้ concurrent load (1000 req/s)
|
||||
- Lock acquisition time < 50ms (avg)
|
||||
- Automatic retry on lock failure (max 3 times)
|
||||
- Timeout handling (30 seconds)
|
||||
|
||||
**Load Test Requirements**:
|
||||
```bash
|
||||
# Must pass without duplicates
|
||||
concurrent_users: 100
|
||||
requests_per_second: 500
|
||||
test_duration: 5 minutes
|
||||
expected_duplicates: 0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-009: Two-Phase Commit
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
ใช้ Two-phase commit pattern เพื่อความสมบูรณ์ของข้อมูล
|
||||
|
||||
**Phase 1: Reserve**
|
||||
- ล็อกเลขที่และ reserve ไว้ชั่วคราว
|
||||
- Set TTL 5 นาที
|
||||
- Return reservation token
|
||||
|
||||
**Phase 2: Confirm or Cancel**
|
||||
- Confirm: บันทึกลงฐานข้อมูลถาวร
|
||||
- Cancel: คืน lock และ reservation
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- Reservation ต้อง expire หลัง 5 นาที
|
||||
- Auto-cleanup expired reservations
|
||||
- Support explicit cancel
|
||||
- Idempotent confirmation
|
||||
|
||||
**API Flow**:
|
||||
```typescript
|
||||
// Phase 1
|
||||
const { token, number } = await reserveNumber({
|
||||
document_type: 'COR',
|
||||
project_id: 1
|
||||
});
|
||||
|
||||
// Do some work...
|
||||
|
||||
// Phase 2
|
||||
await confirmReservation(token);
|
||||
// OR
|
||||
await cancelReservation(token);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2.5 Monitoring & Audit
|
||||
|
||||
#### FR-DN-010: Complete Audit Trail
|
||||
**Priority**: HIGH
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
บันทึกทุก operation ที่เกิดขึ้นกับเลขที่เอกสาร
|
||||
|
||||
**Events to Log**:
|
||||
- Number reserved
|
||||
- Number confirmed
|
||||
- Number cancelled
|
||||
- Manual override
|
||||
- Void document
|
||||
- Sequence adjusted
|
||||
- Format changed
|
||||
|
||||
**Audit Fields**:
|
||||
```typescript
|
||||
interface AuditLog {
|
||||
id: number;
|
||||
operation: string;
|
||||
document_type: string;
|
||||
document_number: string;
|
||||
old_value?: any;
|
||||
new_value?: any;
|
||||
user_id: number;
|
||||
ip_address: string;
|
||||
user_agent: string;
|
||||
timestamp: Date;
|
||||
metadata: Record<string, any>;
|
||||
}
|
||||
```
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- Log ทุก operation
|
||||
- Searchable by user, date, type
|
||||
- Export to CSV
|
||||
- Retain for 7 years
|
||||
|
||||
---
|
||||
|
||||
#### FR-DN-011: Metrics & Alerting
|
||||
**Priority**: MEDIUM
|
||||
**Status**: Required
|
||||
|
||||
**Description**:
|
||||
แสดงสถิติและส่ง alert เมื่อเกิดปัญหา
|
||||
|
||||
**Metrics**:
|
||||
- Sequence utilization (% of max)
|
||||
- Average lock wait time
|
||||
- Failed lock attempts
|
||||
- Numbers generated per day
|
||||
- Manual overrides per day
|
||||
|
||||
**Alerts**:
|
||||
- Sequence >90% used (WARNING)
|
||||
- Sequence >95% used (CRITICAL)
|
||||
- Lock wait time >1s (WARNING)
|
||||
- Redis unavailable (CRITICAL)
|
||||
- High error rate (WARNING)
|
||||
|
||||
**Acceptance Criteria**:
|
||||
- Real-time dashboard (Grafana)
|
||||
- Email/LINE notifications
|
||||
- Alert history tracking
|
||||
- Configurable thresholds
|
||||
|
||||
---
|
||||
|
||||
## 3. Non-Functional Requirements
|
||||
|
||||
### 3.1 Performance
|
||||
|
||||
#### NFR-DN-001: Response Time
|
||||
- Number generation: <100ms (p95)
|
||||
- Lock acquisition: <50ms (avg)
|
||||
- Bulk import: <5s per 100 records
|
||||
|
||||
#### NFR-DN-002: Throughput
|
||||
- Support >500 req/s
|
||||
- Scale horizontally (add Redis nodes)
|
||||
|
||||
### 3.2 Reliability
|
||||
|
||||
#### NFR-DN-003: Availability
|
||||
- System uptime: 99.9%
|
||||
- Graceful degradation (fallback to DB-only)
|
||||
- Auto-recovery from Redis failure
|
||||
|
||||
#### NFR-DN-004: Data Integrity
|
||||
- Zero duplicate numbers (100% guarantee)
|
||||
- ACID transactions
|
||||
- Backup & restore procedures
|
||||
|
||||
### 3.3 Security
|
||||
|
||||
#### NFR-DN-005: Access Control
|
||||
- Admin only: Format configuration, sequence adjustment
|
||||
- Manager+: Manual override, void document
|
||||
- User: Auto-generate only
|
||||
- Audit all operations
|
||||
|
||||
#### NFR-DN-006: Data Protection
|
||||
- Encrypt sensitive data (audit logs)
|
||||
- Secure Redis connections (TLS)
|
||||
- Rate limiting (100 req/min per user)
|
||||
|
||||
### 3.4 Scalability
|
||||
|
||||
#### NFR-DN-007: Capacity Planning
|
||||
- Support 10,000 documents/day
|
||||
- Store 10M+ historical numbers
|
||||
- Archive old audit logs (>2 years)
|
||||
|
||||
### 3.5 Maintainability
|
||||
|
||||
#### NFR-DN-008: Code Quality
|
||||
- Unit test coverage: >70%
|
||||
- Integration test coverage: >50%
|
||||
- E2E test coverage: >20 critical paths
|
||||
- Documentation: Complete API docs
|
||||
|
||||
---
|
||||
|
||||
## 4. Business Rules
|
||||
|
||||
### BR-DN-001: Sequence Scope Rules
|
||||
- Correspondence: Project-level + Yearly reset
|
||||
- RFA: Contract-level + Yearly reset
|
||||
- Drawings: Contract-level + No reset
|
||||
- Transmittal: Project-level + Monthly reset
|
||||
|
||||
### BR-DN-002: Number Format Rules
|
||||
- Min length: 10 characters
|
||||
- Max length: 50 characters
|
||||
- Must include {SEQ} token
|
||||
- Must be ASCII only (no Thai/Chinese)
|
||||
|
||||
### BR-DN-003: Manual Override Rules
|
||||
- Only for document_types with allow_manual_override=true
|
||||
- Must validate format
|
||||
- Must check duplicate
|
||||
- Requires Admin permission
|
||||
|
||||
### BR-DN-004: Void Rules
|
||||
- Can only void ACTIVE documents
|
||||
- Cannot void already-VOID documents
|
||||
- Must provide reason (min 10 chars)
|
||||
- Replacement is optional
|
||||
|
||||
---
|
||||
|
||||
## 5. Data Model
|
||||
|
||||
### 5.1 Numbering Configuration
|
||||
```sql
|
||||
CREATE TABLE document_numbering_configs (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
document_type VARCHAR(50) NOT NULL,
|
||||
format VARCHAR(200) NOT NULL,
|
||||
scope ENUM('GLOBAL','PROJECT','CONTRACT','YEARLY','MONTHLY'),
|
||||
allow_manual_override BOOLEAN DEFAULT FALSE,
|
||||
max_value INT DEFAULT 999999,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY (document_type, scope)
|
||||
);
|
||||
```
|
||||
|
||||
### 5.2 Sequence Counter
|
||||
```sql
|
||||
CREATE TABLE document_numbering_sequences (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
config_id INT NOT NULL,
|
||||
scope_value VARCHAR(50), -- project_id, contract_id, year, etc.
|
||||
current_value INT DEFAULT 0,
|
||||
last_used_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (config_id) REFERENCES document_numbering_configs(id),
|
||||
UNIQUE KEY (config_id, scope_value)
|
||||
);
|
||||
```
|
||||
|
||||
### 5.3 Audit Log
|
||||
```sql
|
||||
CREATE TABLE document_numbering_audit_logs (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
operation VARCHAR(50) NOT NULL,
|
||||
document_type VARCHAR(50),
|
||||
document_number VARCHAR(50),
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
user_id INT NOT NULL,
|
||||
ip_address VARCHAR(45),
|
||||
user_agent VARCHAR(500),
|
||||
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
metadata JSON,
|
||||
INDEX idx_document_number (document_number),
|
||||
INDEX idx_user_id (user_id),
|
||||
INDEX idx_timestamp (timestamp)
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. API Specifications
|
||||
|
||||
### 6.1 Reserve Number
|
||||
```http
|
||||
POST /api/document-numbering/reserve
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"document_type": "COR",
|
||||
"project_id": 1,
|
||||
"contract_id": null,
|
||||
"metadata": {}
|
||||
}
|
||||
|
||||
Response 201:
|
||||
{
|
||||
"token": "uuid-v4",
|
||||
"document_number": "COR-2025-00042",
|
||||
"expires_at": "2025-01-16T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 Confirm Reservation
|
||||
```http
|
||||
POST /api/document-numbering/confirm
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"token": "uuid-v4"
|
||||
}
|
||||
|
||||
Response 200:
|
||||
{
|
||||
"document_number": "COR-2025-00042",
|
||||
"confirmed_at": "2025-01-16T10:25:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
### 6.3 Manual Override
|
||||
```http
|
||||
POST /api/document-numbering/manual
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer <admin-token>
|
||||
|
||||
{
|
||||
"document_type": "COR",
|
||||
"document_number": "COR-2024-99999",
|
||||
"reason": "Import from legacy system",
|
||||
"skip_validation": false
|
||||
}
|
||||
|
||||
Response 201:
|
||||
{
|
||||
"document_number": "COR-2024-99999",
|
||||
"is_manual": true,
|
||||
"created_at": "2025-01-16T10:25:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Testing Requirements
|
||||
|
||||
### 7.1 Unit Tests
|
||||
- Format parsing and validation
|
||||
- Sequence increment logic
|
||||
- Manual override validation
|
||||
- Scope resolution
|
||||
|
||||
### 7.2 Integration Tests
|
||||
- Redis locking mechanism
|
||||
- Database transactions
|
||||
- Two-phase commit flow
|
||||
- Bulk import
|
||||
|
||||
### 7.3 Load Tests
|
||||
- Concurrent number generation (1000 req/s)
|
||||
- Lock contention under load
|
||||
- Redis failover scenarios
|
||||
- Database connection pool exhaustion
|
||||
|
||||
### 7.4 E2E Tests
|
||||
- Complete document creation flow
|
||||
- Void and replace workflow
|
||||
- Bulk import with validation
|
||||
- Admin configuration UI
|
||||
|
||||
---
|
||||
|
||||
## 8. Migration Plan
|
||||
|
||||
### 8.1 Legacy Data Import
|
||||
1. Export existing document numbers from old system
|
||||
2. Validate format and detect duplicates
|
||||
3. Bulk import using manual override API
|
||||
4. Update sequence counters to max values
|
||||
5. Verify data integrity
|
||||
|
||||
### 8.2 Rollout Strategy
|
||||
- Week 1-2: Deploy to staging, test with dummy data
|
||||
- Week 3: Deploy to production, enable for test project
|
||||
- Week 4: Enable for all projects
|
||||
- Week 5+: Monitor and optimize
|
||||
|
||||
---
|
||||
|
||||
## 9. Success Criteria
|
||||
|
||||
### 9.1 Functional Success
|
||||
- ✅ All FRs implemented and tested
|
||||
- ✅ Zero duplicate numbers in production
|
||||
- ✅ Migration of 50,000+ legacy documents
|
||||
- ✅ UAT approved by stakeholders
|
||||
|
||||
### 9.2 Performance Success
|
||||
- ✅ Response time <100ms (p95)
|
||||
- ✅ Throughput >500 req/s
|
||||
- ✅ Lock acquisition <50ms (avg)
|
||||
- ✅ Zero downtime during deployment
|
||||
|
||||
### 9.3 Business Success
|
||||
- ✅ Document creation speed +30%
|
||||
- ✅ Manual numbering errors -80%
|
||||
- ✅ User satisfaction >4.5/5
|
||||
- ✅ System stability >99.9%
|
||||
|
||||
---
|
||||
|
||||
## 10. Appendix
|
||||
|
||||
### 10.1 Glossary
|
||||
- **Sequence**: ลำดับตัวเลขที่เพิ่มขึ้นอัตโนมัติ
|
||||
- **Scope**: ขอบเขตที่ sequence แยกตาม (project, contract, etc.)
|
||||
- **Token**: Format placeholder (e.g., {YYYY}, {SEQ})
|
||||
- **Redlock**: Distributed locking algorithm สำหรับ Redis
|
||||
|
||||
### 10.2 References
|
||||
- [ADR-018: Document Numbering Strategy](../05-decisions/adr-018-document-numbering.md)
|
||||
- [Two-Phase Commit Pattern](https://en.wikipedia.org/wiki/Two-phase_commit_protocol)
|
||||
- [Redlock Algorithm](https://redis.io/docs/manual/patterns/distributed-locks/)
|
||||
|
||||
---
|
||||
|
||||
**Approval Sign-off**:
|
||||
|
||||
| Role | Name | Date | Signature |
|
||||
|------|------|------|-----------|
|
||||
| Product Owner | ___________ | _______ | _________ |
|
||||
| Tech Lead | ___________ | _______ | _________ |
|
||||
| QA Lead | ___________ | _______ | _________ |
|
||||
1871
specs/99-archives/docs/backup/03.11-document-numbering.md
Normal file
1871
specs/99-archives/docs/backup/03.11-document-numbering.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,103 @@
|
||||
## 3.11.15. Database Schema Requirements
|
||||
|
||||
### 3.11.15.1. Counter Table Schema
|
||||
|
||||
ตาราง `document_number_counters` ต้องมีโครงสร้างดังนี้:
|
||||
|
||||
```sql
|
||||
CREATE TABLE document_number_counters (
|
||||
project_id INT NOT NULL,
|
||||
originator_organization_id INT NOT NULL,
|
||||
recipient_organization_id INT NULL, -- NULL for RFA
|
||||
correspondence_type_id INT NOT NULL,
|
||||
sub_type_id INT DEFAULT 0, -- for TRANSMITTAL
|
||||
rfa_type_id INT DEFAULT 0, -- for RFA
|
||||
discipline_id INT DEFAULT 0, -- for RFA
|
||||
current_year INT NOT NULL,
|
||||
version INT DEFAULT 0 NOT NULL, -- Optimistic Lock
|
||||
last_number INT DEFAULT 0,
|
||||
|
||||
PRIMARY KEY (
|
||||
project_id,
|
||||
originator_organization_id,
|
||||
COALESCE(recipient_organization_id, 0),
|
||||
correspondence_type_id,
|
||||
sub_type_id,
|
||||
rfa_type_id,
|
||||
discipline_id,
|
||||
current_year
|
||||
),
|
||||
|
||||
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (originator_organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (recipient_organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (correspondence_type_id) REFERENCES correspondence_types(id) ON DELETE CASCADE
|
||||
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci
|
||||
COMMENT = 'ตารางเก็บ Running Number Counters';
|
||||
```
|
||||
|
||||
### 3.11.15.2. Index Requirements
|
||||
|
||||
```sql
|
||||
-- Index สำหรับ Performance
|
||||
CREATE INDEX idx_counter_lookup
|
||||
ON document_number_counters (
|
||||
project_id,
|
||||
correspondence_type_id,
|
||||
current_year
|
||||
);
|
||||
|
||||
-- Index สำหรับ Originator lookup
|
||||
CREATE INDEX idx_counter_org
|
||||
ON document_number_counters (
|
||||
originator_organization_id,
|
||||
current_year
|
||||
);
|
||||
```
|
||||
|
||||
### 3.11.15.3. Important Notes
|
||||
|
||||
> **💡 Counter Key Design**
|
||||
> - ใช้ `COALESCE(recipient_organization_id, 0)` ใน Primary Key เพื่อรองรับ NULL
|
||||
> - `version` column สำหรับ Optimistic Locking (ป้องกัน race condition)
|
||||
> - `last_number` เริ่มจาก 0 และเพิ่มขึ้นทีละ 1
|
||||
> - Counter reset ทุกปี (เมื่อ `current_year` เปลี่ยน)
|
||||
|
||||
> **⚠️ Migration Notes**
|
||||
> - ไม่มีข้อมูลเก่า ไม่ต้องทำ backward compatibility
|
||||
> - สามารถสร้าง table ใหม่ได้เลยตาม schema ข้างต้น
|
||||
> - ต้องมี seed data สำหรับ `correspondence_types`, `rfa_types`, `disciplines` ก่อน
|
||||
|
||||
### 3.11.15.4. Example Counter Records
|
||||
|
||||
```sql
|
||||
-- Example: LETTER from คคง. to สคฉ.3 in LCBP3-C2 year 2025
|
||||
INSERT INTO document_number_counters (
|
||||
project_id, originator_organization_id, recipient_organization_id,
|
||||
correspondence_type_id, sub_type_id, rfa_type_id, discipline_id,
|
||||
current_year, version, last_number
|
||||
) VALUES (
|
||||
2, -- LCBP3-C2
|
||||
22, -- คคง.
|
||||
10, -- สคฉ.3
|
||||
6, -- LETTER
|
||||
0, 0, 0,
|
||||
2025, 0, 0
|
||||
);
|
||||
|
||||
-- Example: RFA from ผรม.2 in LCBP3-C2, discipline TER, type RPT, year 2025
|
||||
INSERT INTO document_number_counters (
|
||||
project_id, originator_organization_id, recipient_organization_id,
|
||||
correspondence_type_id, sub_type_id, rfa_type_id, discipline_id,
|
||||
current_year, version, last_number
|
||||
) VALUES (
|
||||
2, -- LCBP3-C2
|
||||
42, -- ผรม.2
|
||||
NULL, -- RFA ไม่มี specific recipient
|
||||
1, -- RFA
|
||||
0,
|
||||
18, -- RPT (Report)
|
||||
5, -- TER (Terminal)
|
||||
2025, 0, 0
|
||||
);
|
||||
```
|
||||
842
specs/99-archives/docs/backup/0_Requirements_V1_4_5.md
Normal file
842
specs/99-archives/docs/backup/0_Requirements_V1_4_5.md
Normal file
@@ -0,0 +1,842 @@
|
||||
# 📝 **Documents Management System Version 1.4.5: Application Requirements Specification**
|
||||
|
||||
**สถานะ:** FINAL-Rev.05
|
||||
**วันที่:** 2025-11-29
|
||||
**อ้างอิงพื้นฐาน:** v1.4.4
|
||||
**Classification:** Internal Technical Documentation
|
||||
|
||||
## 📌 **1. วัตถุประสงค์**
|
||||
|
||||
สร้างเว็บแอปพลิเคชันสำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System - DMS) แบบครบวงจร ที่เน้นความปลอดภัยสูงสุด ความถูกต้องของข้อมูล (Data Integrity) และรองรับการขยายตัวในอนาคต (Scalability) โดยแก้ไขปัญหา Race Condition และเพิ่มความเสถียรในการจัดการไฟล์ และใช้ Unified Workflow Engine ในการจัดการกระบวนการอนุมัติทั้งหมดเพื่อความยืดหยุ่น
|
||||
|
||||
- มีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
|
||||
- ช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
|
||||
- เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองกรณ์
|
||||
- **เสริม:** ปรับปรุงความปลอดภัยของระบบด้วยมาตรการป้องกันที่ทันสมัย
|
||||
- **เสริม:** เพิ่มความทนทานของระบบด้วยกลไก resilience patterns
|
||||
- **เสริม:** สร้างระบบ monitoring และ observability ที่ครอบคลุม
|
||||
|
||||
## 🛠️ **2. สถาปัตยกรรมและเทคโนโลยี (System Architecture & Technology Stack)**
|
||||
|
||||
ใช้สถาปัตยกรรมแบบ Headless/API-First ที่ทันสมัย ทำงานทั้งหมดบน QNAP Server ผ่าน Container Station เพื่อความสะดวกในการจัดการและบำรุงรักษา
|
||||
|
||||
**Domain:** `np-dms.work`, `www.np-dms.work`
|
||||
**IP:** 159.192.126.103
|
||||
**Docker Network:** ทุก Service จะเชื่อมต่อผ่านเครือข่ายกลางชื่อ `lcbp3` เพื่อให้สามารถสื่อสารกันได้
|
||||
|
||||
### **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/Cursor on Windows 11
|
||||
- **Data Storage:** `/share/dms-data` บน QNAP
|
||||
- **ข้อจำกัด:** ไม่สามารถใช้ .env ในการกำหนดตัวแปรภายนอกได้ ต้องกำหนดใน docker-compose.yml เท่านั้น
|
||||
|
||||
### **2.2 การจัดการ Configuration (ปรับปรุง):**
|
||||
|
||||
- ใช้ `docker-compose.yml` สำหรับ environment variables ตามข้อจำกัดของ QNAP
|
||||
- **Secrets Management (ใหม่):**
|
||||
- ห้ามระบุ Sensitive Secrets (Password, Keys) ใน `docker-compose.yml` หลัก
|
||||
- ต้องใช้ไฟล์ `docker-compose.override.yml` (ที่ถูก gitignore) สำหรับ Inject Environment Variables ที่เป็นความลับในแต่ละ Environment (Dev/Prod)
|
||||
- ไฟล์ `docker-compose.yml` หลักให้ใส่ค่า Dummy หรือว่างไว้
|
||||
- **แต่ต้องมี 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 Core Services:**
|
||||
|
||||
- **Code Hosting:** Gitea (Self-hosted on QNAP)
|
||||
|
||||
- Application name: git
|
||||
- Service name: gitea
|
||||
- Domain: `git.np-dms.work`
|
||||
- หน้าที่: เป็นศูนย์กลางในการเก็บและจัดการเวอร์ชันของโค้ด (Source Code) สำหรับทุกส่วน
|
||||
|
||||
- **Backend / Data Platform:** NestJS
|
||||
|
||||
- Application name: lcbp3-backend
|
||||
- Service name: backend
|
||||
- Domain: `backend.np-dms.work`
|
||||
- Framework: NestJS (Node.js, TypeScript, ESM)
|
||||
- หน้าที่: จัดการโครงสร้างข้อมูล (Data Models), สร้าง API, จัดการสิทธิ์ผู้ใช้ (Roles & Permissions), และสร้าง Workflow ทั้งหมดของระบบ
|
||||
|
||||
- **Database:** MariaDB 10.11
|
||||
|
||||
- Application name: lcbp3-db
|
||||
- Service name: mariadb
|
||||
- Domain: `db.np-dms.work`
|
||||
- หน้าที่: ฐานข้อมูลหลักสำหรับเก็บข้อมูลทั้งหมด
|
||||
- Tooling: DBeaver (Community Edition), phpmyadmin สำหรับการออกแบบและจัดการฐานข้อมูล
|
||||
|
||||
- **Database Management:** phpMyAdmin
|
||||
|
||||
- Application name: lcbp3-db
|
||||
- Service: phpmyadmin:5-apache
|
||||
- Service name: pma
|
||||
- Domain: `pma.np-dms.work`
|
||||
- หน้าที่: จัดการฐานข้อมูล mariadb ผ่าน Web UI
|
||||
|
||||
- **Frontend:** Next.js
|
||||
|
||||
- Application name: lcbp3-frontend
|
||||
- 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
|
||||
|
||||
- **Workflow Automation:** n8n
|
||||
|
||||
- Application name: lcbp3-n8n
|
||||
- Service: n8nio/n8n:latest
|
||||
- Service name: n8n
|
||||
- Domain: `n8n.np-dms.work`
|
||||
- หน้าที่: จัดการ workflow ระหว่าง Backend และ Line
|
||||
|
||||
- **Reverse Proxy:** Nginx Proxy Manager
|
||||
|
||||
- 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) ให้อัตโนมัติ
|
||||
|
||||
- **Search Engine:** Elasticsearch
|
||||
- **Cache:** Redis
|
||||
|
||||
### **2.4 Business Logic & Consistency (ปรับปรุง):**
|
||||
|
||||
- **2.4.1 Unified Workflow Engine (หลัก):**
|
||||
|
||||
- ระบบการเดินเอกสารทั้งหมด (Correspondence, RFA, Circulation) ต้อง ใช้ Engine กลางเดียวกัน โดยกำหนด Logic ผ่าน Workflow DSL (JSON Configuration) แทนการเขียน Hard-coded ลงในตาราง
|
||||
- Workflow Versioning (เพิ่ม): ระบบต้องรองรับการกำหนด Version ของ Workflow Definition โดยเอกสารที่เริ่มกระบวนการไปแล้ว (In-progress instances) จะต้องใช้ Workflow Version เดิม จนกว่าจะสิ้นสุดกระบวนการ หรือได้รับคำสั่ง Migrate จาก Admin เพื่อป้องกันความขัดแย้งของ State
|
||||
|
||||
- **2.4.2 Separation of Concerns:**
|
||||
|
||||
- Module ต่างๆ (Correspondence, RFA, Circulation) จะเก็บเฉพาะข้อมูลของเอกสาร (Data) ส่วนสถานะและการเปลี่ยนสถานะ (State Transition) จะถูกจัดการโดย Workflow Engine
|
||||
|
||||
- **2.4.3 Idempotency & Locking:**
|
||||
|
||||
- ใช้กลไกเดิมในการป้องกันการทำรายการซ้ำ
|
||||
|
||||
- **2.4.4 Optimistic Locking (ใหม่):**
|
||||
|
||||
- ใช้ Version Column ใน Database ควบคู่กับ Redis Lock สำหรับการสร้างเลขที่เอกสาร เพื่อเป็น Safety Net ชั้นสุดท้าย
|
||||
|
||||
- **2.4.5** **จะไม่มีการใช้ SQL Triggers**
|
||||
- เพื่อป้องกันตรรกะซ่อนเร้น (Hidden Logic) และความซับซ้อนในการดีบัก
|
||||
|
||||
### **2.5 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.6 กลยุทธ์ความทนทานและการจัดการข้อผิดพลาด (Resilience & Error Handling Strategy)**
|
||||
|
||||
- 2.6.1 Circuit Breaker Pattern: ใช้สำหรับ external service calls (Email, LINE, Elasticsearch)
|
||||
- 2.6.2 Retry Mechanism: ด้วย exponential backoff สำหรับ transient failures
|
||||
- 2.6.3 Fallback Strategies: Graceful degradation เมื่อบริการภายนอกล้มเหลว
|
||||
- 2.6.4 Error Handling: Error messages ต้องไม่เปิดเผยข้อมูล sensitive
|
||||
- 2.6.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, ZIP
|
||||
- เอกสารโต้ตอบ (Correspondence) สามารถมีได้หลายประเภท (Types) เช่น จดหมาย (Letter), อีเมล์ (Email), Request for Information (RFI), รวมถึง เอกสารขออนุมัติ (RFA) แต่ละ revision และสามารถเพิ่มประเภทใหม่ได้ในภายหลัง
|
||||
- 3.2.3. การสร้างเอกสาร (Correspondence):
|
||||
- ผู้ใช้ที่มีสิทธิ์ (เช่น Document Control) สามารถสร้างเอกสารรอไว้ในสถานะ ฉบับร่าง" (Draft) ได้ ซึ่งผู้ใช้งานต่างองค์กรจะมองไม่เห็น
|
||||
- เมื่อกด "Submitted" แล้ว การแก้ไข, ถอนเอกสารกลับไปสถานะ Draft, หรือยกเลิก (Cancel) จะต้องทำโดยผู้ใช้ระดับ Admin ขึ้นไป พร้อมระบุเหตุผล
|
||||
- 3.2.4. การอ้างอิงและจัดกลุ่ม:
|
||||
- เอกสารสามารถอ้างถึง (Reference) เอกสารฉบับก่อนหน้าได้หลายฉบับ
|
||||
- สามารถกำหนด Tag ได้หลาย Tag เพื่อจัดกลุ่มและใช้ในการค้นหาขั้นสูง
|
||||
- 3.2.5. Workflow (Unified Workflow):
|
||||
- ระบบต้องรองรับ Workflow ที่เป็นแบบ Unified Workflow
|
||||
|
||||
### **3.3. การจัดการเอกสาขออนุมัติ (Request for Approval / RFA)**
|
||||
|
||||
- 3.3.1. วัตถุประสงค์:
|
||||
- เอกสารขออนุมัติ (RFA) ภายใน โครงการ (Projects)
|
||||
- 3.3.2. ประเภทเอกสาร:
|
||||
- ระบบต้องรองรับเอกสารรูปแบบ ไฟล์ PDF
|
||||
- เอกสารขออนุมัติ (RFA) สามารถมีได้หลาย revision
|
||||
- มีประถทของเอกสาร ได้หลายประเภท (RFA Types) และสามารถเพิ่มประเภทใหม่ได้ในภายหลัง
|
||||
- 3.3.3. การสร้างเอกสาร:
|
||||
- ผู้ใช้ที่มีสิทธิ์ (เช่น Document Control) สามารถสร้างเอกสารขออนุมัติ (RFA) รอไว้ในสถานะ ฉบับร่าง" (Draft) ได้ ซึ่งผู้ใช้งานต่างองค์กรจะมองไม่เห็น
|
||||
- เมื่อกด "Submitted" แล้ว การแก้ไข, ถอนเอกสารกลับไปสถานะ Draft, หรือยกเลิก (Cancel) จะต้องทำโดยผู้ใช้ระดับ Admin ขึ้นไป พร้อมระบุเหตุผล
|
||||
- 3.3.4. การอ้างอิงและจัดกลุ่ม:
|
||||
- RFA สามารถอ้างถึง (Reference) แบบก่อสร้าง (Shop Drawing) ได้หลายฉบับ
|
||||
- 3.3.5. Workflow (Unified Workflow):
|
||||
- ระบบต้องรองรับ Workflow ที่เป็นแบบ Unified Workflow ซึ่งจะมีสถานะและกิจกรรมที่ไม่เหมือนกันกับเอกสารโต้ตอบ (Correspondence)
|
||||
|
||||
### **3.4. การจัดการแบบคู่สัญญา (Contract Drawing)**
|
||||
|
||||
- 3.4.1. วัตถุประสงค์: แบบคู่สัญญา (Contract Drawing) ใช้เพื่ออ้างอิงและใช้ในการตรวจสอบ
|
||||
- 3.4.2. ประเภทเอกสาร: ไฟล์ PDF
|
||||
- 3.4.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
|
||||
- 3.4.4. การอ้างอิงและจัดกลุ่ม: ใช้สำหรับอ้างอิง ใน Shop Drawings, มีการจัดหมวดหมู่ของ Contract Drawing
|
||||
|
||||
### **3.5. การจัดกาแบบก่อสร้าง (Shop Drawing)**
|
||||
|
||||
- 3.5.1. วัตถุประสงค์: แบบก่อสร้าง (Shop Drawing) ใช้เในการตรวจสอบ โดยจัดส่งด้วย Request for Approval (RFA)
|
||||
- 3.5.2. ประเภทเอกสาร: ไฟล์ PDF, DWG, ZIP
|
||||
- 3.5.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้ โดยผู้ใช้ที่มีสิทธิ์ (เช่น Document Control) สามารถสร้างเอกสารรอไว้ในสถานะ ฉบับร่าง" (Draft) ได้ ซึ่งผู้ใช้งานต่างองค์กรจะมองไม่เห็น
|
||||
- 3.5.4. การอ้างอิงและจัดกลุ่ม: ใช้สำหรับอ้างอิง ใน RFA, มีการจัดหมวดหมู่ของ Shop Drawings โดยทุก แบบก่อสร้าง (Shop Drawing) แต่ละ revision ต้องมี RFA ได้เพียง 1 ฉบับ
|
||||
|
||||
### **3.6. การจัดการ Workflow (Unified Workflow)**
|
||||
|
||||
- 3.6.1 Workflow Definition:
|
||||
|
||||
- Admin ต้องสามารถสร้าง/แก้ไข Workflow Rule ได้ผ่านหน้าจอ UI (DSL Editor)
|
||||
- รองรับการกำหนด State, Transition, Required Role, Condition (JS Expression)
|
||||
|
||||
- 3.6.2 Workflow Execution:
|
||||
|
||||
- ระบบต้องรองรับการสร้าง Instance ของ Workflow ผูกกับเอกสาร (Polymorphic)
|
||||
- รองรับการเปลี่ยนสถานะ (Action) เช่น Approve, Reject, Comment, Return
|
||||
- Auto-Action: รองรับการเปลี่ยนสถานะอัตโนมัติเมื่อครบเงื่อนไข (เช่น Review ครบทุกคน)
|
||||
|
||||
- 3.6.3 Flexibility:
|
||||
|
||||
- รองรับ Parallel Review (ส่งให้หลายคนตรวจพร้อมกัน)
|
||||
- รองรับ Conditional Flow (เช่น ถ้ายอดเงิน > X ให้เพิ่มผู้อนุมัติ)
|
||||
|
||||
- 3.6.4 Workflow การอนุมัติ:
|
||||
|
||||
- รองรับกระบวนการอนุมัติที่ซับซ้อนและเป็นลำดับ เช่น ส่งจาก Originator -> Organization 1 -> Organization 2 -> Organization 3 แล้วส่งผลกลับตามลำดับเดิม (โดยถ้า องกรณ์ใดใน Workflow ให้ส่งกลับ ก็สามารถส่งผลกลับตามลำดับเดิมโดยไม่ต้องรอให้ถึง องกรณืในลำดับถัดไป)
|
||||
|
||||
- 3.6.5 การจัดการ:
|
||||
|
||||
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบของ องกรณ์ ที่อยู่ใน Workflow ได้
|
||||
- มีระบบแจ้งเตือน ให้ผู้รับผิดชอบของ องกรณ์ ที่อยู่ใน Workflow ทราบ เมื่อมี RFA ใหม่ หรือมีการเปลี่ยนสถานะ
|
||||
- สามารถข้ามขั้นตอนได้ในกรณีพิเศษ (โดยผู้มีสิทธิ์)
|
||||
- สามารถส่งกลับขั้นตอนก่อนหน้าได้
|
||||
|
||||
### **3.7.การจัดการเอกสารนำส่ง (Transmittals)**
|
||||
|
||||
- 3.7.1. วัตถุประสงค์: เอกสารนำส่ง ใช้สำหรับ นำส่ง Request for Approval (RFAS) หลายฉบับ ไปยังองค์กรอื่น
|
||||
- 3.7.2. ประเภทเอกสาร: ไฟล์ PDF
|
||||
- 3.7.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
|
||||
- 3.7.4. การอ้างอิงและจัดกลุ่ม: เอกสารนำส่ง เป็นส่วนหนึ่งใน Correspondence
|
||||
|
||||
### **3.8.ใบเวียนเอกสาร (Circulation Sheet)**
|
||||
|
||||
- 3.8.1. วัตถุประสงค์: การสื่อสาร เอกสาร (Correspondence) ทุกฉบับ จะมีใบเวียนเอกสารเพื่อควบคุมและมอบหมายงานภายในองค์กร (สามารถดูและแก้ไขได้เฉพาะคนในองค์กร)
|
||||
- 3.8.2. ประเภทเอกสาร: ไฟล์ PDF
|
||||
- 3.8.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์ในองค์กรนั้น สามารถสร้างและแก้ไขได้
|
||||
- 3.8.4. การอ้างอิงและจัดกลุ่ม: การระบุผู้รับผิดชอบ:
|
||||
- ผู้รับผิดชอบหลัก (Main): มีได้หลายคน
|
||||
- ผู้ร่วมปฏิบัติงาน (Action): มีได้หลายคน
|
||||
- ผู้ที่ต้องรับทราบ (Information): มีได้หลายคน
|
||||
- 3.8.5. การติดตามงาน:
|
||||
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบประเภท Main และ Action ได้
|
||||
- มีระบบแจ้งเตือนเมื่อมี Circulation ใหม่ และแจ้งเตือนล่วงหน้าก่อนถึงวันแล้วเสร็จ
|
||||
- สามารถปิด Circulation ได้เมื่อดำเนินการตอบกลับไปยังองค์กรผู้ส่ง (Originator) แล้ว หรือ รับทราบแล้ว (For Information)
|
||||
|
||||
### **3.9. ประวัติการแก้ไข (Revisions):** ระบบจะเก็บประวัติการสร้างและแก้ไข เอกสารทั้งหมด
|
||||
|
||||
### **3.10. การจัดเก็บไฟล์ (File Handling - ปรับปรุงใหญ่)**
|
||||
|
||||
- **3.10.1 Two-Phase Storage Strategy:**
|
||||
|
||||
1. **Phase 1 (Upload):** ไฟล์ถูกอัปโหลดเข้าโฟลเดอร์ `temp/` และได้รับ `temp_id`
|
||||
2. **Phase 2 (Commit):** เมื่อ User กด Submit ฟอร์มสำเร็จ ระบบจะย้ายไฟล์จาก `temp/` ไปยัง `permanent/{YYYY}/{MM}/` และบันทึกลง Database ภายใน Transaction เดียวกัน
|
||||
3. **Cleanup:** มี Cron Job ลบไฟล์ใน `temp/` ที่ค้างเกิน 24 ชม. (Orphan Files)
|
||||
|
||||
- **3.10.2 Security:**
|
||||
|
||||
- Virus Scan (ClamAV) ก่อนย้ายเข้า Permanent
|
||||
- Whitelist File Types: PDF, DWG, DOCX, XLSX, ZIP
|
||||
- Max Size: 50MB
|
||||
- Access Control: ตรวจสอบสิทธิ์ผ่าน Junction Table ก่อนให้ Download Link
|
||||
|
||||
- **3.10.3 ความปลอดภัยของการจัดเก็บไฟล์:**
|
||||
- ต้องมีการ 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.11. การจัดการเลขที่เอกสาร (Document Numbering - ปรับปรุง)**
|
||||
|
||||
- 3.11.1. ระบบต้องสามารถสร้างเลขที่เอกสาร (Running Number) ได้โดยอัตโนมัติและยืดหยุ่นสูง
|
||||
- 3.11.2. Logic การนับเลข (Counter Logic): การนับเลขจะต้องรองรับการแยกตาม Key ที่ซับซ้อนขึ้น:
|
||||
- **Project** + **Originator** + **Type** + **Discipline** (ถ้ามี) + **Sub-Type** (ถ้ามี) + **Year**
|
||||
- 3.11.3. Format Template:
|
||||
- รองรับการกำหนดรูปแบบด้วย Token Replacement เช่น:
|
||||
- `{ORG}-{TYPE}-{DISCIPLINE}-{SEQ:4}-{REV}` -> `TEAM-RFA-STR-0001-A`
|
||||
- รองรับ Token: `{PROJECT}`, `{ORG}`, `{TYPE}`, `{DISCIPLINE}`, `{SUBTYPE}`, `{SUBTYPE_NUM}`, `{YEAR}`, `{YEAR_SHORT}`, `{SEQ:n}`
|
||||
- 3.11.4. Transmittal Logic: รองรับเงื่อนไขพิเศษสำหรับ Transmittal ที่เลขอาจเปลี่ยนตามผู้รับ (To Owner vs To Contractor)
|
||||
- 3.11.5. กลไกความปลอดภัย: ยังคงใช้ Redis Distributed Lock และ Optimistic Locking เพื่อป้องกันเลขซ้ำหรือข้าม
|
||||
- 3.11.6. ต้องมี retry mechanism และ fallback strategy เมื่อการ generate เลขที่เอกสารล้มเหลว
|
||||
- 3.11.7 Fallback Logic (เพิ่ม):
|
||||
- กรณีที่เอกสารประเภทนั้นไม่มี discipline_id หรือ sub_type_id (เป็นค่า NULL หรือไม่ระบุ) ให้ระบบใช้ค่า Default (เช่น 0) ในการจัดกลุ่ม Counter เพื่อป้องกัน Error และรับประกันความถูกต้องของ Running Number (Uniqueness Guarantee)
|
||||
- Scenario 1: Redis Unavailable
|
||||
- Fallback เป็น database-only locking (pessimistic lock)
|
||||
- Log warning และแจ้ง ops team
|
||||
- ระบบยังใช้งานได้แต่ performance ลดลง
|
||||
- Scenario 2: Lock Acquisition Timeout
|
||||
- Retry 5 ครั้งด้วย exponential backoff (1s, 2s, 4s, 8s, 16s)
|
||||
- หลัง 5 ครั้ง: Return error 503 "Service Temporarily Unavailable"
|
||||
- Frontend แสดง user-friendly message: "ระบบกำลังยุ่ง กรุณาลองใหม่ภายหลัง"
|
||||
- Scenario 3: Version Conflict After Lock
|
||||
- Retry transaction อีก 2 ครั้ง
|
||||
- หากยังล้มเหลว: Log error พร้อม context และ return 409 Conflict
|
||||
- Frontend แสดง user-friendly message: "เลขที่เอกสารถูกเปลี่ยน กรุณาลองใหม่"
|
||||
- Monitoring:
|
||||
- Alert ถ้า lock acquisition failures > 5% ใน 5 นาที
|
||||
- Dashboard แสดง lock wait time percentiles
|
||||
|
||||
### **3.12. การจัดการ JSON Details (JSON & Performance - ปรับปรุง)**
|
||||
|
||||
- **3.12.1 วัตถุประสงค์**
|
||||
|
||||
- จัดเก็บข้อมูลแบบไดนามิกที่เฉพาะเจาะจงกับแต่ละประเภทของเอกสาร
|
||||
- รองรับการขยายตัวของระบบโดยไม่ต้องเปลี่ยนแปลง database schema
|
||||
- จัดการ metadata และข้อมูลประกอบสำหรับ correspondence, routing, และ workflows
|
||||
|
||||
- **3.12.2 โครงสร้าง JSON Schema**
|
||||
ระบบต้องมี predefined JSON schemas สำหรับประเภทเอกสารต่างๆ:
|
||||
|
||||
- 3.12.2.1 Correspondence Types
|
||||
- GENERIC: ข้อมูลพื้นฐานสำหรับเอกสารทั่วไป
|
||||
- RFI: รายละเอียดคำถามและข้อมูลทางเทคนิค
|
||||
- RFA: ข้อมูลการขออนุมัติแบบและวัสดุ
|
||||
- TRANSMITTAL: รายการเอกสารที่ส่งต่อ
|
||||
- LETTER: ข้อมูลจดหมายทางการ
|
||||
- EMAIL: ข้อมูลอีเมล
|
||||
- 3.12.2.2 Rworkflow Types
|
||||
- workflow_definitions: กฎและเงื่อนไขการส่งต่อ
|
||||
- workflow_histories: สถานะและประวัติการส่งต่อ
|
||||
- workflow_instances: การดำเนินการในแต่ละขั้นตอน
|
||||
- 3.12.2.3 Audit Types
|
||||
- AUDIT_LOG: ข้อมูลการตรวจสอบ
|
||||
- SECURITY_SCAN: ผลการตรวจสอบความปลอดภัย
|
||||
|
||||
- **3.12.3 Virtual Columns (ปรับปรุง):**
|
||||
|
||||
- สำหรับ Field ใน JSON ที่ต้องใช้ในการค้นหา (Search) หรือจัดเรียง (Sort) บ่อยๆ ต้องสร้าง Generated Column (Virtual Column) ใน Database และทำ Index ไว้ เพื่อประสิทธิภาพสูงสุด
|
||||
- Schema Consistency: Field ที่ถูกกำหนดเป็น Virtual Column ห้าม เปลี่ยนแปลง Key Name หรือ Data Type ใน JSON Schema Version ถัดไป หากจำเป็นต้องเปลี่ยน ต้องมีแผนการ Re-index หรือ Migration ข้อมูลเดิมที่ชัดเจน
|
||||
|
||||
- **3.12.4 Validation Rules**
|
||||
|
||||
- ต้องมี JSON schema validation สำหรับแต่ละประเภท
|
||||
- ต้องรองรับ versioning ของ schema
|
||||
- ต้องมี default values สำหรับ field ที่ไม่บังคับ
|
||||
- ต้องตรวจสอบ data types และ format ให้ถูกต้อง
|
||||
|
||||
- **3.12.5 Performance Requirements**
|
||||
|
||||
- JSON field ต้องมีขนาดไม่เกิน 50KB
|
||||
- ต้องรองรับ indexing สำหรับ field ที่ใช้ค้นหาบ่อย
|
||||
- ต้องมี compression สำหรับ JSON ขนาดใหญ่
|
||||
|
||||
- **3.12.6 Security Requirements**
|
||||
|
||||
- ต้อง sanitize JSON input เพื่อป้องกัน injection attacks
|
||||
- ต้อง validate JSON structure ก่อนบันทึก
|
||||
- ต้อง encrypt sensitive data ใน JSON fields
|
||||
|
||||
- 3.12.7 JSON Schema Migration Strategy (เพิ่มเติม)
|
||||
สำหรับ Schema Breaking Changes:
|
||||
|
||||
- Phase 1 - Add New Column
|
||||
ALTER TABLE correspondence_revisions
|
||||
ADD COLUMN ref_project_id_v2 INT GENERATED ALWAYS AS
|
||||
(JSON_UNQUOTE(JSON_EXTRACT(details, '$.newProjectIdPath'))) VIRTUAL;
|
||||
|
||||
- Phase 2 - Backfill Old Records
|
||||
- ใช้ background job แปลง JSON format เก่าเป็นใหม่
|
||||
- Update `details` JSON ทีละ batch (1000 records)
|
||||
- Phase 3 - Switch Application Code
|
||||
- Deploy code ที่ใช้ path ใหม่
|
||||
- Phase 4 - Remove Old Column
|
||||
|
||||
- หลังจาก verify แล้วว่าไม่มี error
|
||||
- Drop old virtual column
|
||||
|
||||
- สำหรับ Non-Breaking Changes
|
||||
- เพิ่ม optional field ใน schema
|
||||
- Old records ที่ไม่มี field = ใช้ default value
|
||||
|
||||
### **3.13. ข้อกำหนดพิเศษ**
|
||||
|
||||
- ผู้ใช้งานที่มีสิทธิ์ระดับสูง (Global) หรือผู้ได้รับอนุญาตเป็นกรณีพิเศษ
|
||||
- สามารถเลือก สร้างในนามองค์กร (Create on behalf of) ได้ เพื่อให้สามารถออกเลขที่เอกสาร (Running Number) ขององค์กรอื่นได้โดยไม่ต้องล็อกอินใหม่
|
||||
- สามารถทำงานแทนผู้ใช้งานอื่นได้ Routing & Workflow ของ Correspondence, RFA, Circulation Sheet
|
||||
|
||||
### **3.14. การจัดการข้อมูลหลักขั้นสูง (Admin Panel for Master Data)**
|
||||
|
||||
- 3.14.1. Disciplines Management: Admin ต้องสามารถ เพิ่ม/ลบ/แก้ไข สาขางาน (Disciplines) แยกตามสัญญา (Contract) ได้
|
||||
- 3.14.2. Sub-Type Mapping: Admin ต้องสามารถกำหนด Correspondence Sub-types และ Mapping รหัสตัวเลข (เช่น MAT = 11) ได้
|
||||
- 3.14.3. Numbering Format Configuration: Admin ต้องมี UI สำหรับตั้งค่า Format Template ของแต่ละ Project/Type ได้โดยไม่ต้องแก้โค้ด
|
||||
|
||||
## **🔐 4. ข้อกำหนดด้านสิทธิ์และการเข้าถึง (Access Control Requirements)**
|
||||
|
||||
### **4.1. ภาพรวม:**
|
||||
|
||||
- ผู้ใช้และองค์กรสามารถดูและแก้ไขเอกสารได้ตามสิทธิ์ที่ได้รับ โดยระบบสิทธิ์จะเป็นแบบ Role-Based Access Control (RBAC)
|
||||
|
||||
### **4.2. ลำดับชั้นของสิทธิ์ (Permission Hierarchy):**
|
||||
|
||||
- Global: สิทธิ์สูงสุดของระบบ
|
||||
- Organization: สิทธิ์ภายในองค์กร เป็นสิทธิ์พื้นฐานของผู้ใช้
|
||||
- Project: สิทธิ์เฉพาะในโครงการ จะถูกพิจารณาเมื่อผู้ใช้อยู่ในโครงการนั้น
|
||||
- Contract: สิทธิ์เฉพาะในสัญญา จะถูกพิจารณาเมื่อผู้ใช้อยู่ในสัญญานั้น (สัญญาเป็นส่วนหนึ่งของโครงการ)
|
||||
|
||||
### **4.3. กฎการบังคับใช้:**
|
||||
|
||||
- เมื่อตรวจสอบสิทธิ์ ระบบจะพิจารณาสิทธิ์จากทุกระดับที่ผู้ใช้มี และใช้ สิทธิ์ที่มากที่สุด (Most Permissive) เป็นตัวตัดสิน
|
||||
- ตัวอย่าง: ผู้ใช้ A เป็น Viewer ในองค์กร แต่ถูกมอบหมายเป็น Editor ในโครงการ X เมื่ออยู่ในโครงการ X ผู้ใช้ A จะมีสิทธิ์แก้ไขได้
|
||||
|
||||
### **4.4. การกำหนดบทบาท (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.5 . Token Management (ปรับปรุง)**
|
||||
|
||||
- **Payload Optimization:** ใน JWT Access Token ให้เก็บเฉพาะ `userId` และ `scope` ปัจจุบันเท่านั้น
|
||||
- **Permission Caching:** สิทธิ์ละเอียด (Permissions List) ให้เก็บใน **Redis** และดึงมาตรวจสอบเมื่อ Request เข้ามา เพื่อลดขนาด Token และเพิ่มความเร็ว
|
||||
|
||||
### **4.6. กระบวนการเริ่มต้นใช้งาน (Onboarding Workflow) ที่สมบูรณ์**
|
||||
|
||||
- 4.6.1. สร้างองค์กร (Organization)
|
||||
- **Superadmin** สร้างองค์กรใหม่ (เช่น บริษัท A)
|
||||
- **Superadmin** แต่งตั้งผู้ใช้อย่างน้อย 1 คนให้เป็น **Org Admin** หรือ **Document Control** ของบริษัท A
|
||||
- 4.6.2. เพิ่มผู้ใช้ในองค์กร
|
||||
- **Org Admin** ของบริษัท A เพิ่มผู้ใช้อื่นๆ (Editor, Viewer) เข้ามาในองค์กรของตน
|
||||
- 4.6.3. มอบหมายผู้ใช้ให้กับโครงการ (Project)
|
||||
- **Project Manager** ของโครงการ X (ซึ่งอาจมาจากบริษัท A หรือบริษัทอื่น) ทำการ "เชิญ" หรือ "มอบหมาย" ผู้ใช้จากองค์กรต่างๆ ที่เกี่ยวข้องเข้ามาในโครงการ X
|
||||
- ในขั้นตอนนี้ **Project Manager** จะกำหนด **บทบาทระดับโครงการ** (เช่น Project Member, หรืออาจไม่มีบทบาทพิเศษ ให้ใช้สิทธิ์จากระดับองค์กรไปก่อน)
|
||||
- 4.6.4. เมอบหมายผู้ใช้ให้กับสัญญา (Contract)
|
||||
- **Contract Admin** ของสัญญา Y (ซึ่งเป็นส่วนหนึ่งของโครงการ X) ทำการเลือกผู้ใช้ที่อยู่ในโครงการ X แล้ว มอบหมายให้เข้ามาในสัญญา Y
|
||||
- ในขั้นตอนนี้ **Contract Admin** จะกำหนด **บทบาทระดับสัญญา** (เช่น Contract Member) และสิทธิ์เฉพาะที่จำเป็น
|
||||
- 4.6.5 Security Onboarding:
|
||||
- ต้องบังคับเปลี่ยน password ครั้งแรกสำหรับผู้ใช้ใหม่
|
||||
- ต้องมี security awareness training สำหรับผู้ใช้ที่มีสิทธิ์สูง
|
||||
- ต้องมี process สำหรับการรีเซ็ต password ที่ปลอดภัย
|
||||
- ต้องบันทึก audit log ทุกครั้งที่มีการเปลี่ยนแปลง permissions
|
||||
|
||||
### **4.7. การจัดการข้อมูลหลัก (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)
|
||||
|
||||
- ผู้ใช้สามารถดู RFA ในรูปแบบ Workflow Diagram ทั้งหมดได้ในหน้าเดียว
|
||||
- Interactive History (เพิ่ม): ในแผนภาพ Workflow ผู้ใช้ต้องสามารถ คลิกที่ Node หรือ Step เก่าที่ผ่านมาแล้ว เพื่อดู Audit Log ย่อยของ Step นั้นได้ทันที (เช่น ใครเป็นคนกด Approve, เวลาไหน, มี Comment อะไร) โดยไม่ต้องสลับไปดูใน Tab History แยกต่างหาก
|
||||
- ขั้นตอนที่ยังไม่ถึงหรือผ่านไปแล้วจะเป็นรูปแบบ disabled
|
||||
- สามารถดำเนินการได้เฉพาะในขั้นตอนที่ได้รับมอบหมายงาน (active)
|
||||
- สิทธิ์ Document Control ขึ้นไป สามารถกด "Force Proceed" ไปยังขั้นตอนต่อไปได้ทุกขั้นตอน หรือ "Revert" กลับขั้นตอนก่อนหน้าได้
|
||||
|
||||
### 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
|
||||
|
||||
### 5.10 Form & Interaction
|
||||
|
||||
- **Dynamic Form Generator:** ใช้ Component กลางที่รับ JSON Schema แล้ว Render Form ออกมาอัตโนมัติ เพื่อลดความซ้ำซ้อนของโค้ดหน้าบ้าน และรองรับเอกสารประเภทใหม่ๆ ได้ทันที
|
||||
- **Optimistic Updates:** การเปลี่ยนสถานะ (เช่น กด Approve, กด Read) ให้ UI เปลี่ยนสถานะทันทีให้ผู้ใช้เห็นก่อนรอ API Response (Rollback ถ้า Failed)
|
||||
|
||||
### 5.11 Mobile Responsiveness
|
||||
|
||||
- **Table Visualization:** บนหน้าจอมือถือ ตารางข้อมูลที่มีหลาย Column (เช่น Correspondence List) ต้องเปลี่ยนการแสดงผลเป็นแบบ **Card View** อัตโนมัติ
|
||||
- **Navigation:** Sidebar ต้องเป็นแบบ Collapsible Drawer
|
||||
|
||||
### 5.12 Resilience & Offline Support
|
||||
|
||||
- **Auto-Save Draft:** ระบบต้องบันทึกข้อมูลฟอร์มที่กำลังกรอกลง **LocalStorage** อัตโนมัติ เพื่อป้องกันข้อมูลหายกรณีเน็ตหลุดหรือปิด Browser โดยไม่ได้ตั้งใจ
|
||||
- **State Management:** ใช้ State Management ที่เหมาะสมและไม่ซับซ้อนเกินไป โดยเน้นการใช้ React Query สำหรับ Server State และ React Hook Form สำหรับ Form State
|
||||
- **Graceful Degradation:** หาก Service รอง (เช่น Search, Notification) ล่ม ระบบหลัก (CRUD) ต้องยังทำงานต่อได้
|
||||
|
||||
### 5.13. Secure In-App PDF Viewer (ใหม่)
|
||||
|
||||
- 5.13.1 Viewer Capabilities: ระบบต้องมี PDF Viewer ภายในแอปพลิเคชันที่สามารถเปิดดูไฟล์เอกสารหลัก (PDF) ได้ทันทีโดยไม่ต้องดาวน์โหลดลงเครื่อง เพื่อความสะดวกในการตรวจทาน (Review/Approve)
|
||||
- 5.13.2 Security: การแสดงผลไฟล์ต้อง ห้าม (Disable) การทำ Browser Cache สำหรับไฟล์ Sensitive เพื่อป้องกันการกู้คืนไฟล์จากเครื่อง Client ภายหลัง
|
||||
- 5.13.3 Performance: ต้องรองรับการส่งข้อมูลแบบ Streaming (Range Requests) เพื่อให้เปิดดูไฟล์ขนาดใหญ่ (เช่น แบบแปลน 50MB+) ได้รวดเร็วโดยไม่ต้องรอโหลดเสร็จทั้งไฟล์
|
||||
|
||||
## **🛡️ 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. Data Archiving & Partitioning (ใหม่)**
|
||||
|
||||
- สำหรับตารางที่มีขนาดใหญ่และโตเร็ว (เช่น `audit_logs`, `notifications`, `correspondence_revisions`) ต้องออกแบบโดยรองรับ **Table Partitioning** (แบ่งตาม Range วันที่ หรือ List) เพื่อประสิทธิภาพในระยะยาว
|
||||
|
||||
### **6.3. การค้นหา (Search):**
|
||||
|
||||
- ระบบต้องมีฟังก์ชันการค้นหาขั้นสูง ที่สามารถค้นหาเอกสาร **correspondence**, **rfa**, **shop_drawing**, **contract-drawing**, **transmittal** และ **ใบเวียน (Circulations)** จากหลายเงื่อนไขพร้อมกันได้ เช่น ค้นหาจากชื่อเรื่อง, ประเภท, วันที่, และ Tag
|
||||
|
||||
### **6.4. การทำรายงาน (Reporting):**
|
||||
|
||||
- สามารถจัดทำรายงานสรุปแยกประเภทของ Correspondence ประจำวัน, สัปดาห์, เดือน, และปีได้
|
||||
|
||||
### **6.5. ประสิทธิภาพ (Performance):**
|
||||
|
||||
- มีการใช้ Caching กับข้อมูลที่เรียกใช้บ่อย และใช้ Pagination ในตารางข้อมูลเพื่อจัดการข้อมูลจำนวนมาก
|
||||
- 6.5.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.5.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.3 Frontend Performance:
|
||||
- **Bundle Size Optimization:** ต้องควบคุมขนาด Bundle โดยรวมไม่เกิน 2MB
|
||||
- **State Management Efficiency:** ใช้ State Management Libraries อย่างเหมาะสม ไม่เกิน 2 ตัวหลัก
|
||||
- **Memory Management:** ต้องป้องกัน Memory Leak จาก State ที่ไม่จำเป็น
|
||||
|
||||
### **6.6. ความปลอดภัย (Security):**
|
||||
|
||||
- มีระบบ Rate Limiting เพื่อป้องกันการโจมตีแบบ Brute-force
|
||||
- การจัดการ Secret (เช่น รหัสผ่าน DB, JWT Secret) จะต้องทำผ่าน Environment Variable ของ Docker เพื่อความปลอดภัยสูงสุด
|
||||
- 6.6.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.6.2 Error Handling และ Resilience:
|
||||
- ต้องมี circuit breaker pattern สำหรับ external service calls
|
||||
- ต้องมี retry mechanism ด้วย exponential backoff
|
||||
- ต้องมี graceful degradation เมื่อบริการภายนอกล้มเหลว
|
||||
- Error messages ต้องไม่เปิดเผยข้อมูล sensitive
|
||||
- 6.6.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.6.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.7. การสำรองข้อมูลและการกู้คืน (Backup & Recovery)
|
||||
|
||||
- ระบบจะต้องมีกลไกการสำรองข้อมูลอัตโนมัติสำหรับฐานข้อมูล MariaDB [cite: 2.4] และไฟล์เอกสารทั้งหมดใน /share/dms-data [cite: 2.1] (เช่น ใช้ HBS 3 ของ QNAP หรือสคริปต์สำรองข้อมูล) อย่างน้อยวันละ 1 ครั้ง
|
||||
- ต้องมีแผนการกู้คืนระบบ (Disaster Recovery Plan) ในกรณีที่ Server หลัก (QNAP) ใช้งานไม่ได้
|
||||
- 6.7.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.8. กลยุทธ์การแจ้งเตือน (Notification Strategy - ปรับปรุง)
|
||||
|
||||
- 6.8.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.8.2 Grouping/Digest (ใหม่)
|
||||
- กรณีมีการแจ้งเตือนประเภทเดียวกันจำนวนมากในช่วงเวลาสั้นๆ (เช่น Approve เอกสาร 10 ฉบับรวด) ระบบต้อง **รวม (Batch)** เป็น 1 Email/Line Notification เพื่อไม่ให้รบกวนผู้ใช้ (Spamming)
|
||||
- 6.8.3 Notification Delivery Guarantees
|
||||
- **At-least-once delivery:** สำหรับ important notifications
|
||||
- **Retry mechanism:** ด้วย exponential backoff (max 3 reties)
|
||||
- **Dead letter queue:** สำหรับ notifications ที่ส่งไม่สำเร็จหลังจาก retries
|
||||
- **Delivery status tracking:** ต้องบันทึกสถานะการส่ง notifications
|
||||
- **Fallback channels:** ถ้า Email ล้มเหลว ให้ส่งผ่าน SYSTEM notification
|
||||
- **Notification preferences:** ผู้ใช้ต้องสามารถกำหนด channel preferences ได้
|
||||
|
||||
### **6.9. Maintenance Mode (ใหม่)**
|
||||
|
||||
- ระบบต้องมีกลไก **Maintenance Mode** ที่ Admin สามารถเปิดใช้งานได้
|
||||
- เมื่อเปิด: ผู้ใช้ทั่วไปจะเห็นหน้า "ปิดปรับปรุง" และไม่สามารถเรียก API ได้ (ยกเว้น Admin)
|
||||
- ใช้สำหรับช่วง Deploy Version ใหม่ หรือ Database Migration
|
||||
|
||||
### **6.10. Monitoring และ Observability**
|
||||
|
||||
- 6.10.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.10.2 Business Metrics
|
||||
- จำนวน documents created ต่อวัน
|
||||
- Workflow completion rates
|
||||
- User activity metrics
|
||||
- System utilization rates
|
||||
- Search query performance
|
||||
- 6.10.3 Security Monitoring
|
||||
- Failed login attempts
|
||||
- Rate limiting triggers
|
||||
- Virus scan results
|
||||
- File download activities
|
||||
- Permission changes
|
||||
|
||||
### **6.11 JSON Processing & Validation**
|
||||
|
||||
- 6.11.1 JSON Schema Management
|
||||
- ต้องมี centralized JSON schema registry
|
||||
- ต้องรองรับ schema versioning และ migration
|
||||
- ต้องมี schema validation during runtime
|
||||
- 6.11.2 Performance Optimization
|
||||
- **Caching:** Cache parsed JSON structures
|
||||
- **Compression:** ใช้ compression สำหรับ JSON ขนาดใหญ่
|
||||
- **Indexing:** Support JSON path indexing สำหรับ query
|
||||
- 6.11.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
|
||||
- Business Logic: 80%+
|
||||
- Controllers: 70%+
|
||||
- Utilities: 90%+
|
||||
- ต้องทดสอบ 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
|
||||
|
||||
- Penetration Testing: ทดสอบ OWASP Top 10 vulnerabilities
|
||||
- Security Audit: Review code สำหรับ security flaws
|
||||
- Virus Scanning Test: ทดสอบ file upload security
|
||||
- **Rate Limiting Test:** ทดสอบ rate limiting functionality
|
||||
- **Load Testing:** ทดสอบด้วย realistic workloads
|
||||
- **Stress Testing:** หา breaking points ของระบบ
|
||||
- **Endurance Testing:** ทดสอบการทำงานต่อเนื่องเป็นเวลานาน
|
||||
|
||||
### 7.6. Disaster Recovery Testing
|
||||
|
||||
- ทดสอบ backup และ restoration procedures
|
||||
- ทดสอบ failover mechanisms
|
||||
- ทดสอบ data integrity หลังการ recovery
|
||||
|
||||
### 7.7 Specific Scenario Testing (เพิ่ม)
|
||||
|
||||
- **Race Condition Test:** ทดสอบยิง Request ขอเลขที่เอกสารพร้อมกัน 100 Request
|
||||
- **Transaction Test:** ทดสอบปิดเน็ตระหว่าง Upload ไฟล์ (ตรวจสอบว่าไม่มี Orphan File หรือ Broken Link)
|
||||
- **Permission Test:** ทดสอบ CASL Integration ทั้งฝั่ง Backend และ Frontend ให้ตรงกัน
|
||||
|
||||
## **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
|
||||
|
||||
## **Document Control:**
|
||||
|
||||
- **Document:** Application Requirements Specification v1.4.5
|
||||
- **Version:** 1.4
|
||||
- **Date:** 2025-11-29
|
||||
- **Author:** NAP LCBP3-DMS & Gemini
|
||||
- **Status:** FINAL-Rev.05
|
||||
- **Classification:** Internal Technical Documentation
|
||||
- **Approved By:** Nattanin
|
||||
|
||||
---
|
||||
|
||||
`End of Requirements Specification v1.4.5`
|
||||
911
specs/99-archives/docs/backup/0_Requirements_V1_5_1.md
Normal file
911
specs/99-archives/docs/backup/0_Requirements_V1_5_1.md
Normal file
@@ -0,0 +1,911 @@
|
||||
# 📝 Documents Management System Version 1.5.1: Application Requirements Specification
|
||||
|
||||
**สถานะ:** FINAL-Rev.01
|
||||
**วันที่:** 2025-12-04
|
||||
**อ้างอิงพื้นฐาน:** v1.5.0
|
||||
**Classification:** Internal Technical Documentation
|
||||
|
||||
## 📌 1. Objectives
|
||||
|
||||
# 📌 Section 1: Objectives (วัตถุประสงค์)
|
||||
---
|
||||
title: 'Objectives'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
|
||||
สร้างเว็บแอปพลิเคชันสำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System - DMS) แบบครบวงจร ที่เน้นความปลอดภัยสูงสุด ความถูกต้องของข้อมูล (Data Integrity) และรองรับการขยายตัวในอนาคต (Scalability) โดยแก้ไขปัญหา Race Condition และเพิ่มความเสถียรในการจัดการไฟล์ และใช้ Unified Workflow Engine ในการจัดการกระบวนการอนุมัติทั้งหมดเพื่อความยืดหยุ่น
|
||||
|
||||
- มีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
|
||||
- ช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
|
||||
- เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองค์กร
|
||||
- ปรับปรุงความปลอดภัยของระบบด้วยมาตรการป้องกันที่ทันสมัย
|
||||
- เพิ่มความทนทานของระบบด้วยกลไก resilience patterns
|
||||
- สร้างระบบ monitoring และ observability ที่ครอบคลุม
|
||||
|
||||
## 🛠️ 2. System Architecture
|
||||
|
||||
# 🛠️ Section 2: System Architecture (สถาปัตยกรรมและเทคโนโลยี)
|
||||
---
|
||||
title: 'System Architecture'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: - specs/01-objectives.md
|
||||
---
|
||||
|
||||
ชื่อกำหนด สถาปัตยกรรมแบบ Headless/API-First ที่ทันสมัย ทำงานทั้งหมดบน QNAP Server ผ่าน Container Station เพื่อความสะดวกในการจัดการและบำรุงรักษา
|
||||
|
||||
### 2.1 Infrastructure & Environment
|
||||
- Domain: `np-dms.work`, `www.np-dms.work`
|
||||
- IP: 159.192.126.103
|
||||
- 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/Cursor on Windows 11
|
||||
- Data Storage: /share/dms-data บน QNAP
|
||||
- ข้อจำกัด: ไม่สามารถใช้ .env ในการกำหนดตัวแปรภายนอกได้ ต้องกำหนดใน docker-compose.yml เท่านั้น
|
||||
|
||||
### 2.2 Configuration Management
|
||||
- ใช้ docker-compose.yml สำหรับ environment variables ตามข้อจำกัดของ QNAP
|
||||
- Secrets Management: ใช้ docker-compose.override.yml (gitignore) สำหรับ secret injection, Docker secrets หรือ Hashicorp Vault, encrypted env vars
|
||||
- Development environment ยังใช้ .env ได้ แต่ต้องไม่ commit เข้า version control
|
||||
- มี configuration validation during application startup
|
||||
- แยก configuration ตาม environment (development, staging, production)
|
||||
- Docker Network: lcbp3
|
||||
|
||||
### 2.3 Core Services
|
||||
- Code Hosting: Gitea (`git.np-dms.work`)
|
||||
- Backend / Data Platform: NestJS (`backend.np-dms.work`)
|
||||
- Database: MariaDB 10.11 (`db.np-dms.work`)
|
||||
- Database Management UI: phpMyAdmin (`pma.np-dms.work`)
|
||||
- Frontend: Next.js (`lcbp3.np-dms.work`)
|
||||
- Workflow Automation: n8n (`n8n.np-dms.work`)
|
||||
- Reverse Proxy: Nginx Proxy Manager (`npm.np-dms.work`)
|
||||
- Search Engine: Elasticsearch
|
||||
- Cache: Redis
|
||||
|
||||
### 2.4 Business Logic & Consistency
|
||||
- Unified Workflow Engine (central) with DSL JSON configuration
|
||||
- Versioning of workflow definitions, optimistic locking with Redis lock for document numbering
|
||||
- No SQL triggers; all business logic in NestJS services
|
||||
|
||||
## 📦 3. Functional Requirements
|
||||
|
||||
### 3.1 Project Management
|
||||
|
||||
# 3.1 Project Management (การจัดการโครงสร้างโครงการและองค์กร)
|
||||
---
|
||||
title: "Functional Requirements: Project Management"
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 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 การจัดการเอกสารโต้ตอบ (Correspondence Management)
|
||||
---
|
||||
title: 'Functional Requirements: Correspondence Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 3.2.1. วัตถุประสงค์: เอกสารโต้ตอบระหว่างองค์กรภายในและภายนอกโครงการ, รองรับ To และ CC หลายองค์กร
|
||||
- 3.2.2. ประเภทเอกสาร: PDF, ZIP; Types include Letter, Email, RFI, RFA (with revisions)
|
||||
- 3.2.3. การสร้างเอกสาร: ผู้ใช้ที่มีสิทธิ์สร้าง Draft, Submit requires Admin approval
|
||||
- 3.2.4. การอ้างอิงและจัดกลุ่ม: รองรับหลาย Reference, Tagging
|
||||
- 3.2.5. Workflow: รองรับ Unified Workflow
|
||||
|
||||
### 3.3 RFA Management
|
||||
|
||||
# 3.3 RFA Management (การจัดการเอกสาขออนุมัติ)
|
||||
---
|
||||
title: 'Functional Requirements: RFA Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 3.3.1. วัตถุประสงค์: เอกสารขออนุมัติภายในโครงการ
|
||||
- 3.3.2. ประเภทเอกสาร: PDF, รองรับหลาย revision และหลายประเภท RFA
|
||||
- 3.3.3. การสร้างเอกสาร: Draft creation by Document Control, Submit requires Admin
|
||||
- 3.3.4. การอ้างอิง: สามารถอ้างถึง Shop Drawing ได้หลายฉบับ
|
||||
- 3.3.5. Workflow: รองรับ Unified Workflow
|
||||
|
||||
### 3.4 Contract Drawing Management
|
||||
|
||||
# 3.4 Contract Drawing Management (การจัดการแบบคู่สัญญา)
|
||||
---
|
||||
title: 'Functional Requirements: Contract Drawing Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 3.4.1. วัตถุประสงค์: ใช้เพื่ออ้างอิงและตรวจสอบ
|
||||
- 3.4.2. ประเภทเอกสาร: PDF
|
||||
- 3.4.3. การสร้างเอกสาร: ผู้มีสิทธิ์สร้างและแก้ไข
|
||||
- 3.4.4. การอ้างอิง: ใช้สำหรับอ้างอิงใน Shop Drawings
|
||||
|
||||
### 3.5 Shop Drawing Management
|
||||
|
||||
# 3.5 Shop Drawing Management (การจัดการแบบก่อสร้าง)
|
||||
---
|
||||
title: 'Functional Requirements: Shop Drawing Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 3.5.1. วัตถุประสงค์: ใช้ในการตรวจสอบและจัดส่งด้วย RFA
|
||||
- 3.5.2. ประเภทเอกสาร: PDF, DWG, ZIP
|
||||
- 3.5.3. การสร้างเอกสาร: ผู้มีสิทธิ์สร้าง/แก้ไข, Draft visibility control
|
||||
- 3.5.4. การอ้างอิง: ใช้ใน RFA, มีการจัดหมวดหมู่, แต่ละ revision มี RFA หนึ่งฉบับ
|
||||
|
||||
### 3.6 Unified Workflow Management
|
||||
|
||||
# 3.6 Unified Workflow Management (การจัดการ Workflow)
|
||||
---
|
||||
title: 'Functional Requirements: Unified Workflow Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related: -
|
||||
---
|
||||
- 3.6.1 Workflow Definition: Admin can create/edit rules via UI DSL Editor, define State, Transition, Role, Condition
|
||||
- 3.6.2 Workflow Execution: Create instances polymorphic to documents, support actions Approve, Reject, Comment, Return, auto-actions
|
||||
- 3.6.3 Flexibility: Parallel Review, Conditional Flow
|
||||
- 3.6.4 Approval Flow: Supports complex multi-organization sequences and return paths
|
||||
- 3.6.5 Management: Deadline setting, notifications, step skipping, backtrack
|
||||
|
||||
# 3.7 Transmittals Management (การจัดการเอกสารนำส่ง)
|
||||
---
|
||||
title: 'Functional Requirements: Transmittals Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
---
|
||||
## 3.7.1. วัตถุประสงค์:
|
||||
- เอกสารนำส่ง ใช้สำหรับ นำส่ง Request for Approval (RFAS) หลายฉบับ ไปยังองค์กรอื่น
|
||||
|
||||
## 3.7.2. ประเภทเอกสาร:
|
||||
- ไฟล์ PDF
|
||||
|
||||
## 3.7.3. การสร้างเอกสาร:
|
||||
- ผู้ใช้ที่มีสิทธิ์ สามารถสร้างและแก้ไขได้
|
||||
|
||||
## 3.7.4. การอ้างอิงและจัดกลุ่ม:
|
||||
- เอกสารนำส่ง เป็นส่วนหนึ่งใน Correspondence
|
||||
|
||||
# 3.8 Circulation Sheet Management (การจัดการใบเวียนเอกสาร)
|
||||
---
|
||||
title: 'Functional Requirements: Circulation Sheet Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
---
|
||||
## 3.8.1. วัตถุประสงค์:
|
||||
- การสื่อสาร เอกสาร (Correspondence) ทุกฉบับ จะมีใบเวียนเอกสารเพื่อควบคุมและมอบหมายงานภายในองค์กร (สามารถดูและแก้ไขได้เฉพาะคนในองค์กร)
|
||||
|
||||
## 3.8.2. ประเภทเอกสาร:
|
||||
- ไฟล์ PDF
|
||||
|
||||
## 3.8.3. การสร้างเอกสาร:
|
||||
- ผู้ใช้ที่มีสิทธิ์ในองค์กรนั้น สามารถสร้างและแก้ไขได้
|
||||
|
||||
## 3.8.4. การอ้างอิงและจัดกลุ่ม:
|
||||
- การระบุผู้รับผิดชอบ:
|
||||
- ผู้รับผิดชอบหลัก (Main): มีได้หลายคน
|
||||
- ผู้ร่วมปฏิบัติงาน (Action): มีได้หลายคน
|
||||
- ผู้ที่ต้องรับทราบ (Information): มีได้หลายคน
|
||||
|
||||
## 3.8.5. การติดตามงาน:
|
||||
- สามารถกำหนดวันแล้วเสร็จ (Deadline) สำหรับผู้รับผิดชอบประเภท Main และ Action ได้
|
||||
- มีระบบแจ้งเตือนเมื่อมี Circulation ใหม่ และแจ้งเตือนล่วงหน้าก่อนถึงวันแล้วเสร็จ
|
||||
- สามารถปิด Circulation ได้เมื่อดำเนินการตอบกลับไปยังองค์กรผู้ส่ง (Originator) แล้ว หรือ รับทราบแล้ว (For Information)
|
||||
|
||||
# 3.9 Logs Management (ประวัติการแก้ไข)
|
||||
---
|
||||
title: 'Functional Requirements: Logs Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
---
|
||||
## 3.9.1. วัตถุประสงค์:
|
||||
- เพื่อ บันทึกการกระทำ CRUD ของเอกสารทั้งหมด รวมถึงการ เข้าใช้งาน ของ users
|
||||
- admin สามารถดูประวัติการแก้ไขของเอกสารทั้งหมด พร้อม จัดทำรายงายตามข้อกำหนดที่ ต้องการได้
|
||||
|
||||
# 3.10 File Handling Management (การจัดการไฟล์)
|
||||
---
|
||||
title: 'Functional Requirements: File Handling Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
---
|
||||
## 3.10.1 Two-Phase Storage Strategy:
|
||||
1. Phase 1 (Upload): ไฟล์ถูกอัปโหลดเข้าโฟลเดอร์ temp/ และได้รับ temp_id
|
||||
2. Phase 2 (Commit): เมื่อ User กด Submit ฟอร์มสำเร็จ ระบบจะย้ายไฟล์จาก temp/ ไปยัง permanent/{YYYY}/{MM}/ และบันทึกลง Database ภายใน Transaction เดียวกัน
|
||||
3. Cleanup: มี Cron Job ลบไฟล์ใน temp/ ที่ค้างเกิน 24 ชม. (Orphan Files)
|
||||
|
||||
## 3.10.2 Security:
|
||||
- Virus Scan (ClamAV) ก่อนย้ายเข้า permanent
|
||||
- Whitelist File Types: PDF, DWG, DOCX, XLSX, ZIP
|
||||
- Max Size: 50MB
|
||||
- Access Control: ตรวจสอบสิทธิ์ผ่าน Junction Table ก่อนให้ Download Link
|
||||
|
||||
## 3.10.3 ความปลอดภัยของการจัดเก็บไฟล์:
|
||||
- ต้องมีการ 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.11 Document Numbering Management (การจัดการเลขที่เอกสาร)
|
||||
---
|
||||
title: 'Functional Requirements: Document Numbering Management'
|
||||
version: 1.6.0
|
||||
status: draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-12-02
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
- specs/03-implementation/document-numbering.md
|
||||
- specs/04-operations/document-numbering-operations.md
|
||||
- specs/04-data-dictionary/4_Data_Dictionary_V1_4_4.md
|
||||
---
|
||||
## 3.11.1 วัตถุประสงค์:
|
||||
- ระบบต้องสามารถสร้างเลขที่เอกสาร (Running Number) ได้โดยอัตโนมัติและยืดหยุ่นสูง
|
||||
- ระบบต้องสามารถกำหนดรูปแบบ (template) เลขที่เอกสารได้ สำหรับแต่ละโครงการ, ชนิดเอกสาร, ประเภทเอกสาร
|
||||
- ระบบต้องรับประกัน Uniqueness ของเลขที่เอกสารในทุกสถานการณ์
|
||||
- ระบบต้องรองรับการทำงานแบบ concurrent ได้อย่างปลอดภัย
|
||||
|
||||
## 3.11.2 Logic การนับเลข (Counter Logic)
|
||||
การนับเลขจะแยกตาม **Counter Key** ที่ประกอบด้วยหลายส่วน ขึ้นกับประเภทเอกสาร
|
||||
|
||||
### Counter Key Components
|
||||
| Component | Required? | Description | Database Source | Default if NULL |
|
||||
| ---------------------------- | ---------------- | ------------------- | --------------------------------------------------------- | --------------- |
|
||||
| `project_id` | ✅ Yes | ID โครงการ | Derived from user context or organization | - |
|
||||
| `originator_organization_id` | ✅ Yes | ID องค์กรผู้ส่ง | `correspondences.originator_id` | - |
|
||||
| `recipient_organization_id` | Depends on type | ID องค์กรผู้รับหลัก (TO) | `correspondence_recipients` where `recipient_type = 'TO'` | NULL for RFA |
|
||||
| `correspondence_type_id` | ✅ Yes | ID ประเภทเอกสาร | `correspondence_types.id` | - |
|
||||
| `sub_type_id` | TRANSMITTAL only | ID ประเภทย่อย | `correspondence_sub_types.id` | 0 |
|
||||
| `rfa_type_id` | RFA only | ID ประเภท RFA | `rfa_types.id` | 0 |
|
||||
| `discipline_id` | RFA only | ID สาขางาน | `disciplines.id` | 0 |
|
||||
| `current_year` | ✅ Yes | ปี ค.ศ. | System year (ปัจจุบัน) | - |
|
||||
|
||||
### Counter Key แยกตามประเภทเอกสาร
|
||||
**LETTER / RFI / MEMO / EMAIL / MOM / INSTRUCTION / NOTICE / OTHER**:
|
||||
```
|
||||
(project_id, originator_organization_id, recipient_organization_id,
|
||||
correspondence_type_id, 0, 0, 0, current_year)
|
||||
```
|
||||
*หมายเหตุ*: ไม่ใช้ `discipline_id`, `sub_type_id`, `rfa_type_id`
|
||||
|
||||
**TRANSMITTAL**:
|
||||
```
|
||||
(project_id, originator_organization_id, recipient_organization_id,
|
||||
correspondence_type_id, sub_type_id, 0, 0, current_year)
|
||||
```
|
||||
*หมายเหตุ*: ใช้ `sub_type_id` เพิ่มเติม
|
||||
|
||||
**RFA**:
|
||||
```
|
||||
(project_id, originator_organization_id, NULL,
|
||||
correspondence_type_id, 0, rfa_type_id, discipline_id, current_year)
|
||||
```
|
||||
*หมายเหตุ*: RFA ไม่ใช้ `recipient_organization_id` เพราะเป็นเอกสารโครงการ (CONTRACTOR → CONSULTANT → OWNER)
|
||||
|
||||
### วิธีการหา project_id
|
||||
1. **User Context** (แนะนำ):
|
||||
- เมื่อ User สร้างเอกสาร UI จะให้เลือก Project/Contract ก่อน
|
||||
- ใช้ `project_id` จาก Context ที่เลือก
|
||||
2. **จาก Organization**:
|
||||
- Query `project_organizations` หรือ `contract_organizations`
|
||||
- ใช้ `originator_organization_id` หา project ที่เกี่ยวข้อง
|
||||
- ถ้ามีหลาย project ให้ User เลือก
|
||||
3. **Validation**:
|
||||
- ตรวจสอบว่า organization มีสิทธิ์ใน project นั้น
|
||||
- ตรวจสอบว่า project/contract เป็น active
|
||||
|
||||
### Fallback สำหรับค่า NULL
|
||||
- `discipline_id`: ใช้ `0` (ไม่ระบุสาขางาน)
|
||||
- `sub_type_id`: ใช้ `0` (ไม่มีประเภทย่อย)
|
||||
- `rfa_type_id`: ใช้ `0` (ไม่ระบุประเภท RFA)
|
||||
- `recipient_organization_id`: ใช้ `NULL` สำหรับ RFA, Required สำหรับ LETTER/TRANSMITTAL
|
||||
|
||||
## 3.11.3 Format Templates by Correspondence Type
|
||||
### 3.11.3.1. Letter (TYPE = LETTER)
|
||||
**Template**:
|
||||
```
|
||||
{ORIGINATOR}-{RECIPIENT}-{SEQ:4}-{YEAR:B.E.}
|
||||
```
|
||||
**Example**: `คคง.-สคฉ.3-0001-2568`
|
||||
**Token Breakdown**:
|
||||
- `คคง.` = {ORIGINATOR} = รหัสองค์กรผู้ส่ง
|
||||
- `สคฉ.3` = {RECIPIENT} = รหัสองค์กรผู้รับหลัก (TO)
|
||||
- `0001` = {SEQ:4} = Running number (เริ่ม 0001, 0002, ...)
|
||||
- `2568` = {YEAR:B.E.} = ปี พ.ศ.
|
||||
> **⚠️ Template vs Counter Separation**
|
||||
- {CORR_TYPE} **ไม่แสดง**ใน template เพื่อความกระชับ
|
||||
- แต่ระบบ**ยังใช้ correspondence_type_id ใน Counter Key** เพื่อแยก counter
|
||||
- LETTER, MEMO, RFI **มี counter แยกกัน** แม้ template format เหมือนกัน
|
||||
**Counter Key**: `(project_id, originator_org_id, recipient_org_id, corr_type_id, 0, 0, 0, year)`
|
||||
---
|
||||
### 3.11.3.2. Transmittal (TYPE = TRANSMITTAL)
|
||||
**Template**:
|
||||
```
|
||||
{ORIGINATOR}-{RECIPIENT}-{SUB_TYPE}-{SEQ:4}-{YEAR:B.E.}
|
||||
```
|
||||
**Example**: `คคง.-สคฉ.3-21-0117-2568`
|
||||
**Token Breakdown**:
|
||||
- `คคง.` = {ORIGINATOR}
|
||||
- `สคฉ.3` = {RECIPIENT}
|
||||
- `21` = {SUB_TYPE} = หมายเลขประเภทย่อย (11=MAT, 12=SHP, 13=DWG, 14=MET, ...)
|
||||
- `0117` = {SEQ:4}
|
||||
- `2568` = {YEAR:B.E.}
|
||||
> **⚠️ Template vs Counter Separation**
|
||||
- {CORR_TYPE} **ไม่แสดง**ใน template (เหมือน LETTER)
|
||||
- TRANSMITTAL มี counter แยกจาก LETTER
|
||||
**Counter Key**: `(project_id, originator_org_id, recipient_org_id, corr_type_id, sub_type_id, 0, 0, year)`
|
||||
---
|
||||
### 3.11.3.3. RFA (Request for Approval)
|
||||
**Template**:
|
||||
```
|
||||
{PROJECT}-{CORR_TYPE}-{DISCIPLINE}-{RFA_TYPE}-{SEQ:4}-{REV}
|
||||
```
|
||||
**Example**: `LCBP3-C2-RFA-TER-RPT-0001-A`
|
||||
**Token Breakdown**:
|
||||
- `LCBP3-C2` = {PROJECT} = รหัสโครงการ
|
||||
- `RFA` = {CORR_TYPE} = ประเภทเอกสาร (แสดงใน RFA template)
|
||||
- `TER` = {DISCIPLINE} = รหัสสาขางาน (TER=Terminal, STR=Structure, ...)
|
||||
- `RPT` = {RFA_TYPE} = ประเภท RFA (RPT=Report, SDW=Shop Drawing, ...)
|
||||
- `0001` = {SEQ:4}
|
||||
- `A` = {REV} = Revision code
|
||||
> **📋 RFA Workflow**
|
||||
- RFA เป็น **เอกสารโครงการ** (Project-level document)
|
||||
- Workflow: **CONTRACTOR → CONSULTANT → OWNER**
|
||||
- ไม่มี specific `recipient_id` เพราะเป็น workflow ที่กำหนดไว้แล้ว
|
||||
**Counter Key**: `(project_id, originator_org_id, NULL, corr_type_id, 0, rfa_type_id, discipline_id, year)`
|
||||
---
|
||||
## 3.11.4. Security & Data Integrity Requirements
|
||||
### 3.11.4.1. Concurrency Control
|
||||
**Requirements:**
|
||||
- ระบบ**ต้อง**ป้องกัน race condition เมื่อมีการสร้างเลขที่เอกสารพร้อมกัน
|
||||
- ระบบ**ต้อง**รับประกัน uniqueness ของเลขที่เอกสารในทุกสถานการณ์
|
||||
- ระบบ**ควร**ใช้ Distributed Lock (Redis) เป็นกลไก primary
|
||||
- ระบบ**ต้อง**มี fallback mechanism เมื่อ Redis ไม่พร้อมใช้งาน
|
||||
### 3.11.4.2. Data Integrity
|
||||
**Requirements:**
|
||||
- ระบบ**ต้อง**ใช้ Optimistic Locking เพื่อตรวจจับ concurrent updates
|
||||
- ระบบ**ต้อง**มี database constraints เพื่อป้องกันข้อมูลผิดพลาด:
|
||||
- Unique constraint บน `document_number`
|
||||
- Foreign key constraints ทุก relationship
|
||||
- Check constraints สำหรับ business rules
|
||||
---
|
||||
## 3.11.5. Validation Rules
|
||||
- ต้องมี JSON schema validation สำหรับแต่ละประเภท
|
||||
- ต้องรองรับ versioning ของ schema
|
||||
- ต้องมี default values สำหรับ field ที่ไม่บังคับ
|
||||
- ต้องตรวจสอบ data types และ format ให้ถูกต้อง
|
||||
---
|
||||
## 3.11.6. Performance Requirements
|
||||
- JSON field ต้องมีขนาดไม่เกิน 50KB
|
||||
- ต้องรองรับ indexing สำหรับ field ที่ใช้ค้นหาบ่อย
|
||||
- ต้องมี compression สำหรับ JSON ขนาดใหญ่
|
||||
---
|
||||
## 3.11.7. Security Requirements
|
||||
- ต้อง sanitize JSON input เพื่อป้องกัน injection attacks
|
||||
- ต้อง validate JSON structure ก่อนบันทึก
|
||||
- ต้อง encrypt sensitive data ใน JSON fields
|
||||
---
|
||||
## 3.11.8. JSON Schema Migration Strategy
|
||||
- สำหรับ Schema Breaking Changes:
|
||||
- Phase 1 - Add New Column
|
||||
ALTER TABLE correspondence_revisions
|
||||
ADD COLUMN ref_project_id_v2 INT GENERATED ALWAYS AS
|
||||
(JSON_UNQUOTE(JSON_EXTRACT(details, '$.newProjectIdPath'))) VIRTUAL;
|
||||
- Phase 2 - Backfill Old Records
|
||||
- ใช้ background job แปลง JSON format เก่าเป็นใหม่
|
||||
- Update `details` JSON ทีละ batch (1000 records)
|
||||
- Phase 3 - Switch Application Code
|
||||
- Deploy code ที่ใช้ path ใหม่
|
||||
- Phase 4 - Remove Old Column
|
||||
- หลังจาก verify แล้วว่าไม่มี error
|
||||
- Drop old virtual column
|
||||
- สำหรับ Non-Breaking Changes
|
||||
- เพิ่ม optional field ใน schema
|
||||
- Old records ที่ไม่มี field = ใช้ default value
|
||||
---
|
||||
# 3.12 JSON Details Management (การจัดการ JSON Details)
|
||||
---
|
||||
title: 'Functional Requirements: JSON Details Management'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
- specs/01-requirements/01-objectives.md
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
---
|
||||
## 3.12.1 วัตถุประสงค์
|
||||
- จัดเก็บข้อมูลแบบไดนามิกที่เฉพาะเจาะจงกับแต่ละประเภทของเอกสาร
|
||||
- รองรับการขยายตัวของระบบโดยไม่ต้องเปลี่ยนแปลง database schema
|
||||
- จัดการ metadata และข้อมูลประกอบสำหรับ correspondence, routing, และ workflows
|
||||
## 3.12.2 โครงสร้าง JSON Schema
|
||||
- ระบบต้องมี predefined JSON schemas สำหรับประเภทเอกสารต่างๆ:
|
||||
- 3.12.2.1 Correspondence Types
|
||||
- GENERIC: ข้อมูลพื้นฐานสำหรับเอกสารทั่วไป
|
||||
- RFI: รายละเอียดคำถามและข้อมูลทางเทคนิค
|
||||
- RFA: ข้อมูลการขออนุมัติแบบและวัสดุ
|
||||
- TRANSMITTAL: รายการเอกสารที่ส่งต่อ
|
||||
- LETTER: ข้อมูลจดหมายทางการ
|
||||
- EMAIL: ข้อมูลอีเมล
|
||||
- 3.12.2.2 Rworkflow Types
|
||||
- workflow_definitions: กฎและเงื่อนไขการส่งต่อ
|
||||
- workflow_histories: สถานะและประวัติการส่งต่อ
|
||||
- workflow_instances: การดำเนินการในแต่ละขั้นตอน
|
||||
- 3.12.2.3 Audit Types
|
||||
- AUDIT_LOG: ข้อมูลการตรวจสอบ
|
||||
- SECURITY_SCAN: ผลการตรวจสอบความปลอดภัย
|
||||
## 3.12.3 Virtual Columns (ปรับปรุง)
|
||||
- สำหรับ Field ใน JSON ที่ต้องใช้ในการค้นหา (Search) หรือจัดเรียง (Sort) บ่อยๆ ต้องสร้าง Generated Column (Virtual Column) ใน Database และทำ Index ไว้ เพื่อประสิทธิภาพสูงสุด
|
||||
- Schema Consistency: Field ที่ถูกกำหนดเป็น Virtual Column ห้าม เปลี่ยนแปลง Key Name หรือ Data Type ใน JSON Schema Version ถัดไป หากจำเป็นต้องเปลี่ยน ต้องมีแผนการ Re-index หรือ Migration ข้อมูลเดิมที่ชัดเจน
|
||||
## 3.12.4 Validation Rules
|
||||
- ต้องมี JSON schema validation สำหรับแต่ละประเภท
|
||||
- ต้องรองรับ versioning ของ schema
|
||||
- ต้องมี default values สำหรับ field ที่ไม่บังคับ
|
||||
- ต้องตรวจสอบ data types และ format ให้ถูกต้อง
|
||||
## 3.12.5 Performance Requirements
|
||||
- JSON field ต้องมีขนาดไม่เกิน 50KB
|
||||
- ต้องรองรับ indexing สำหรับ field ที่ใช้ค้นหาบ่อย
|
||||
- ต้องมี compression สำหรับ JSON ขนาดใหญ่
|
||||
## 3.12.6 Security Requirements
|
||||
- ต้อง sanitize JSON input เพื่อป้องกัน injection attacks
|
||||
- ต้อง validate JSON structure ก่อนบันทึก
|
||||
- ต้อง encrypt sensitive data ใน JSON fields
|
||||
---
|
||||
|
||||
## 📂 4. Non‑Functional Requirements
|
||||
|
||||
# 4.1 Access Control
|
||||
# 🔐 Section 4: Access Control (ข้อกำหนดด้านสิทธิ์และการเข้าถึง)
|
||||
|
||||
## 4.1. Overview:
|
||||
|
||||
- Users and organizations can view and edit documents based on the permissions they have. The system's permissions will be based on Role-Based Access Control (RBAC).
|
||||
|
||||
## 4.2. Permission Hierarchy:
|
||||
|
||||
- Global: The highest level of permissions in the system
|
||||
- Organization: Permissions within an organization, which is the basic permission for users
|
||||
- Project: Permissions specific to a project, which will be considered when the user is in that project
|
||||
- Contract: Permissions specific to a contract, which will be considered when the user is in that contract
|
||||
|
||||
## 4.3. Permission Enforcement:
|
||||
|
||||
- When checking permissions, the system will consider permissions from all levels that the user has and use the most permissive permission as the decision
|
||||
- Example: User A is a Viewer in the organization, but is assigned as an Editor in Project X when in Project X, User A will have the right to edit
|
||||
|
||||
## 4.4. Role and Scope:
|
||||
|
||||
| Role | Scope | Description | Key Permissions |
|
||||
| :------------------- | :----------- | :------------------------- | :-------------------------------------------------------------------------------------------------------------------- |
|
||||
| **Superadmin** | Global | System administrator | Do everything in the system, manage organizations, manage global data |
|
||||
| **Org Admin** | Organization | Organization administrator | Manage users in the organization, manage roles/permissions within the organization, view organization reports |
|
||||
| **Document Control** | Organization | Document controller | Add/edit/delete documents, set document permissions within the organization |
|
||||
| **Editor** | Organization | Document editor | Edit documents that have been assigned to them |
|
||||
| **Viewer** | Organization | Document viewer | View documents that have access permissions |
|
||||
| **Project Manager** | Project | Project manager | Manage members in the project (add/delete/assign roles), create/manage contracts in the project, view project reports |
|
||||
| **Contract Admin** | Contract | Contract administrator | Manage users in the contract, manage roles/permissions within the contract, view contract reports |
|
||||
|
||||
## 4.5. Token Management (ปรับปรุง)
|
||||
|
||||
- **Payload Optimization:** ใน JWT Access Token ให้เก็บเฉพาะ `userId` และ `scope` ปัจจุบันเท่านั้น
|
||||
- **Permission Caching:** สิทธิ์ละเอียด (Permissions List) ให้เก็บใน **Redis** และดึงมาตรวจสอบเมื่อ Request เข้ามา เพื่อลดขนาด Token และเพิ่มความเร็ว
|
||||
|
||||
## 4.6. Onboarding Workflow
|
||||
|
||||
- 4.6.1. Create Organization
|
||||
- **Superadmin** creates a new organization (e.g. Company A)
|
||||
- **Superadmin** appoints at least 1 user as **Org Admin** or **Document Control** of Company A
|
||||
- 4.6.2. Add Users to Organization
|
||||
- **Org Admin** of Company A adds other users (Editor, Viewer) to the organization
|
||||
- 4.6.3. Assign Users to Project
|
||||
- **Project Manager** of Project X (which may come from Company A or another company) invites or assigns users from different organizations to join Project X
|
||||
- In this step, **Project Manager** will assign **Project Role** (e.g. Project Member, or may use organization-level permissions)
|
||||
- 4.6.4. Assign Users to Contract
|
||||
- **Contract Admin** of Contract Y (which is part of Project X) selects users from Project X and assigns them to Contract Y
|
||||
- In this step, **Contract Admin** will assign **Contract Role** (e.g. Contract Member) and specific permissions
|
||||
- 4.6.5 Security Onboarding:
|
||||
- Force users to change password for the first time
|
||||
- Security awareness training for users with high permissions
|
||||
- Safe password reset process
|
||||
- Audit log recording every permission change
|
||||
|
||||
### **4.7. Master Data Management**
|
||||
|
||||
| Master Data | Manager | Scope |
|
||||
| :-------------------------------------- | :------------------------------ | :------------------------------ |
|
||||
| Document Type (Correspondence, RFA) | **Superadmin** | Global |
|
||||
| Document Status (Draft, Approved, etc.) | **Superadmin** | Global |
|
||||
| Shop Drawing Category | **Project Manager** | Project (สร้างใหม่ได้ภายในโครงการ) |
|
||||
| Tags | **Org Admin / Project Manager** | Organization / Project |
|
||||
| Custom Roles | **Superadmin / Org Admin** | Global / Organization |
|
||||
| Document Numbering Formats | **Superadmin / Admin** | Global / Organization |
|
||||
|
||||
## 4.8. การบันทึกการกระทำ (Audit Log)
|
||||
|
||||
- ทุกการกระทำที่สำคัญของผู้ใช้ (สร้าง, แก้ไข, ลบ, ส่ง) จะถูกบันทึกไว้ใน audit_logs เพื่อการตรวจสอบย้อนหลัง
|
||||
- ขอบเขตการบันทึก Audit Log:
|
||||
- ทุกการสร้าง/แก้ไข/ลบ ข้อมูลสำคัญ (correspondences, RFAs, drawings, users, permissions)
|
||||
- ทุกการเข้าถึงข้อมูล sensitive (user data, financial information)
|
||||
- ทุกการเปลี่ยนสถานะ workflow (status transitions)
|
||||
- ทุกการดาวน์โหลดไฟล์สำคัญ (contract documents, financial reports)
|
||||
- ทุกการเปลี่ยนแปลง permission และ role assignment
|
||||
- ทุกการล็อกอินที่สำเร็จและล้มเหลว
|
||||
- ทุกการส่งคำขอ API ที่สำคัญ
|
||||
- ข้อมูลที่ต้องบันทึกใน 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
|
||||
|
||||
## 4.9. Data Archiving & Partitioning
|
||||
|
||||
- สำหรับตารางที่มีขนาดใหญ่และโตเร็ว (เช่น `audit_logs`, `notifications`, `correspondence_revisions`) ต้องออกแบบโดยรองรับ **Table Partitioning** (แบ่งตาม Range วันที่ หรือ List) เพื่อประสิทธิภาพในระยะยาว
|
||||
|
||||
## 4.10. การค้นหา (Search):
|
||||
|
||||
- ระบบต้องมีฟังก์ชันการค้นหาขั้นสูง ที่สามารถค้นหาเอกสาร **correspondence**, **rfa**, **shop_drawing**, **contract-drawing**, **transmittal** และ **ใบเวียน (Circulations)** จากหลายเงื่อนไขพร้อมกันได้ เช่น ค้นหาจากชื่อเรื่อง, ประเภท, วันที่, และ Tag
|
||||
|
||||
## 4.11. การทำรายงาน (Reporting):
|
||||
|
||||
- สามารถจัดทำรายงานสรุปแยกประเภทของ Correspondence ประจำวัน, สัปดาห์, เดือน, และปีได้
|
||||
|
||||
## 4.12. ประสิทธิภาพ (Performance):
|
||||
|
||||
- มีการใช้ Caching กับข้อมูลที่เรียกใช้บ่อย และใช้ Pagination ในตารางข้อมูลเพื่อจัดการข้อมูลจำนวนมาก
|
||||
|
||||
- ตัวชี้วัดประสิทธิภาพ:
|
||||
|
||||
- **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
|
||||
|
||||
- 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)
|
||||
|
||||
- Frontend Performance:
|
||||
- **Bundle Size Optimization:** ต้องควบคุมขนาด Bundle โดยรวมไม่เกิน 2MB
|
||||
- **State Management Efficiency:** ใช้ State Management Libraries อย่างเหมาะสม ไม่เกิน 2 ตัวหลัก
|
||||
- **Memory Management:** ต้องป้องกัน Memory Leak จาก State ที่ไม่จำเป็น
|
||||
|
||||
## 4.13. System Security (ความปลอดภัยระบบ):
|
||||
|
||||
- มีระบบ Rate Limiting เพื่อป้องกันการโจมตีแบบ Brute-force
|
||||
- การจัดการ Secret (เช่น รหัสผ่าน DB, JWT Secret) จะต้องทำผ่าน Environment Variable ของ Docker เพื่อความปลอดภัยสูงสุด
|
||||
- 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
|
||||
- Error Handling และ Resilience:
|
||||
- ต้องมี circuit breaker pattern สำหรับ external service calls
|
||||
- ต้องมี retry mechanism ด้วย exponential backoff
|
||||
- ต้องมี graceful degradation เมื่อบริการภายนอกล้มเหลว
|
||||
- Error messages ต้องไม่เปิดเผยข้อมูล sensitive
|
||||
- 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
|
||||
- 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 ครั้งล่าสุด
|
||||
|
||||
## 4.14. การสำรองข้อมูลและการกู้คืน (Backup & Recovery)
|
||||
|
||||
- ระบบจะต้องมีกลไกการสำรองข้อมูลอัตโนมัติสำหรับฐานข้อมูล MariaDB [cite: 2.4] และไฟล์เอกสารทั้งหมดใน /share/dms-data [cite: 2.1] (เช่น ใช้ HBS 3 ของ QNAP หรือสคริปต์สำรองข้อมูล) อย่างน้อยวันละ 1 ครั้ง
|
||||
- ต้องมีแผนการกู้คืนระบบ (Disaster Recovery Plan) ในกรณีที่ Server หลัก (QNAP) ใช้งานไม่ได้
|
||||
- ขั้นตอนการกู้คืน:
|
||||
- **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 ชั่วโมง
|
||||
|
||||
## 4.15. กลยุทธ์การแจ้งเตือน (Notification Strategy - ปรับปรุง)
|
||||
|
||||
- ระบบจะส่งการแจ้งเตือน (ผ่าน Email หรือ Line [cite: 2.7]) เมื่อมีการกระทำที่สำคัญ** ดังนี้:
|
||||
1. เมื่อมีเอกสารใหม่ (Correspondence, RFA) ถูกส่งมาถึงองค์กรณ์ของเรา
|
||||
2. เมื่อมีใบเวียน (Circulation) ใหม่ มอบหมายงานมาที่เรา
|
||||
3. (ทางเลือก) เมื่อเอกสารที่เราส่งไป ถูกดำเนินการ (เช่น อนุมัติ/ปฏิเสธ)
|
||||
4. (ทางเลือก) เมื่อใกล้ถึงวันครบกำหนด (Deadline) [cite: 3.2.5, 3.6.6, 3.7.5]
|
||||
- Grouping/Digest
|
||||
- กรณีมีการแจ้งเตือนประเภทเดียวกันจำนวนมากในช่วงเวลาสั้นๆ (เช่น Approve เอกสาร 10 ฉบับรวด) ระบบต้อง **รวม (Batch)** เป็น 1 Email/Line Notification เพื่อไม่ให้รบกวนผู้ใช้ (Spamming)
|
||||
- Notification Delivery Guarantees
|
||||
- **At-least-once delivery:** สำหรับ important notifications
|
||||
- **Retry mechanism:** ด้วย exponential backoff (max 3 reties)
|
||||
- **Dead letter queue:** สำหรับ notifications ที่ส่งไม่สำเร็จหลังจาก retries
|
||||
- **Delivery status tracking:** ต้องบันทึกสถานะการส่ง notifications
|
||||
- **Fallback channels:** ถ้า Email ล้มเหลว ให้ส่งผ่าน SYSTEM notification
|
||||
- **Notification preferences:** ผู้ใช้ต้องสามารถกำหนด channel preferences ได้
|
||||
|
||||
## 4.16. Maintenance Mode
|
||||
|
||||
- ระบบต้องมีกลไก **Maintenance Mode** ที่ Admin สามารถเปิดใช้งานได้
|
||||
- เมื่อเปิด: ผู้ใช้ทั่วไปจะเห็นหน้า "ปิดปรับปรุง" และไม่สามารถเรียก API ได้ (ยกเว้น Admin)
|
||||
- ใช้สำหรับช่วง Deploy Version ใหม่ หรือ Database Migration
|
||||
|
||||
## 4.17. Monitoring และ Observability
|
||||
|
||||
- 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
|
||||
- Business Metrics
|
||||
- จำนวน documents created ต่อวัน
|
||||
- Workflow completion rates
|
||||
- User activity metrics
|
||||
- System utilization rates
|
||||
- Search query performance
|
||||
- Security Monitoring
|
||||
- Failed login attempts
|
||||
- Rate limiting triggers
|
||||
- Virus scan results
|
||||
- File download activities
|
||||
- Permission changes
|
||||
|
||||
## 4.18. JSON Processing & Validation
|
||||
|
||||
- JSON Schema Management
|
||||
- ต้องมี centralized JSON schema registry
|
||||
- ต้องรองรับ schema versioning และ migration
|
||||
- ต้องมี schema validation during runtime
|
||||
- Performance Optimization
|
||||
- **Caching:** Cache parsed JSON structures
|
||||
- **Compression:** ใช้ compression สำหรับ JSON ขนาดใหญ่
|
||||
- **Indexing:** Support JSON path indexing สำหรับ query
|
||||
- Error Handling
|
||||
- ต้องมี graceful degradation เมื่อ JSON validation ล้มเหลว
|
||||
- ต้องมี default fallback values
|
||||
- ต้องบันทึก error logs สำหรับ validation failures
|
||||
|
||||
|
||||
# 5. UI/UX Guidelines
|
||||
# 👥 Section 5: UI/UX Requirements (ข้อกำหนดด้านผู้ใช้งาน)
|
||||
---
|
||||
title: 'UI/UX Requirements'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
|
||||
- specs/02-architecture/data-model.md#correspondence
|
||||
- specs/03-implementation/backend-guidelines.md#correspondencemodule
|
||||
---
|
||||
|
||||
## 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)
|
||||
|
||||
- ผู้ใช้สามารถดู RFA ในรูปแบบ Workflow Diagram ทั้งหมดได้ในหน้าเดียว
|
||||
- Interactive History (เพิ่ม): ในแผนภาพ Workflow ผู้ใช้ต้องสามารถ คลิกที่ Node หรือ Step เก่าที่ผ่านมาแล้ว เพื่อดู Audit Log ย่อยของ Step นั้นได้ทันที (เช่น ใครเป็นคนกด Approve, เวลาไหน, มี Comment อะไร) โดยไม่ต้องสลับไปดูใน Tab History แยกต่างหาก
|
||||
- ขั้นตอนที่ยังไม่ถึงหรือผ่านไปแล้วจะเป็นรูปแบบ disabled
|
||||
- สามารถดำเนินการได้เฉพาะในขั้นตอนที่ได้รับมอบหมายงาน (active)
|
||||
- สิทธิ์ Document Control ขึ้นไป สามารถกด "Force Proceed" ไปยังขั้นตอนต่อไปได้ทุกขั้นตอน, หรือ "Revert" กลับขั้นตอนก่อนหน้าได้
|
||||
|
||||
## 5.7. การจัดการใบเวียนเอกสาร (Circulation)
|
||||
|
||||
- ผู้ใช้สามารถดู Circulation ในรูปแบบ Workflow ทั้งหมดได้ในหน้าเดียว,ขั้นตอนที่ยังไม่ถึงหรือผ่านไปแล้วจะเป็นรูปแบบ disabled, สามารถดำเนินการได้เฉพาะในขั้นตอนที่ได้รับมอบหมายงาน (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
|
||||
|
||||
## 5.10 Form & Interaction
|
||||
|
||||
- **Dynamic Form Generator:** ใช้ Component กลางที่รับ JSON Schema แล้ว Render Form ออกมาอัตโนมัติ เพื่อลดความซ้ำซ้อนของโค้ดหน้าบ้าน และรองรับเอกสารประเภทใหม่ๆ ได้ทันที
|
||||
- **Optimistic Updates:** การเปลี่ยนสถานะ (เช่น กด Approve, กด Read) ให้ UI เปลี่ยนสถานะทันทีให้ผู้ใช้เห็นก่อนรอ API Response (Rollback ถ้า Failed)
|
||||
|
||||
## 5.11 Mobile Responsiveness
|
||||
|
||||
- **Table Visualization:** บนหน้าจอมือถือ ตารางข้อมูลที่มีหลาย Column (เช่น Correspondence List) ต้องเปลี่ยนการแสดงผลเป็นแบบ **Card View** อัตโนมัติ
|
||||
- **Navigation:** Sidebar ต้องเป็นแบบ Collapsible Drawer
|
||||
|
||||
## 5.12 Resilience & Offline Support
|
||||
|
||||
- **Auto-Save Draft:** ระบบต้องบันทึกข้อมูลฟอร์มที่กำลังกรอกลง **LocalStorage** อัตโนมัติ เพื่อป้องกันข้อมูลหายกรณีเน็ตหลุดหรือปิด Browser โดยไม่ได้ตั้งใจ
|
||||
- **State Management:** ใช้ State Management ที่เหมาะสมและไม่ซับซ้อนเกินไป โดยเน้นการใช้ React Query สำหรับ Server State และ React Hook Form สำหรับ Form State
|
||||
- **Graceful Degradation:** หาก Service รอง (เช่น Search, Notification) ล่ม ระบบหลัก (CRUD) ต้องยังทำงานต่อได้
|
||||
|
||||
## 5.13. Secure In-App PDF Viewer (ใหม่)
|
||||
|
||||
- 5.13.1 Viewer Capabilities: ระบบต้องมี PDF Viewer ภายในแอปพลิเคชันที่สามารถเปิดดูไฟล์เอกสารหลัก (PDF) ได้ทันทีโดยไม่ต้องดาวน์โหลดลงเครื่อง เพื่อความสะดวกในการตรวจทาน (Review/Approve)
|
||||
- 5.13.2 Security: การแสดงผลไฟล์ต้อง ห้าม (Disable) การทำ Browser Cache สำหรับไฟล์ Sensitive เพื่อป้องกันการกู้คืนไฟล์จากเครื่อง Client ภายหลัง
|
||||
- 5.13.3 Performance: ต้องรองรับการส่งข้อมูลแบบ Streaming (Range Requests) เพื่อให้เปิดดูไฟล์ขนาดใหญ่ (เช่น แบบแปลน 50MB+) ได้รวดเร็วโดยไม่ต้องรอโหลดเสร็จทั้งไฟล์
|
||||
|
||||
## 🧪 6. Testing Requirements
|
||||
## 6.1 Unit Testing
|
||||
|
||||
- ต้องมี unit tests สำหรับ business logic ทั้งหมด
|
||||
- Code coverage อย่างน้อย 70% สำหรับ backend services
|
||||
- Business Logic: 80%+
|
||||
- Controllers: 70%+
|
||||
- Utilities: 90%+
|
||||
- ต้องทดสอบ RBAC permission logic ทุกระดับ
|
||||
|
||||
## 6.2 Integration Testing
|
||||
|
||||
- ทดสอบการทำงานร่วมกันของ modules
|
||||
- ทดสอบ database migrations และ data integrity
|
||||
- ทดสอบ API endpoints ด้วย realistic data
|
||||
|
||||
## 6.3 End-to-End Testing
|
||||
|
||||
- ทดสอบ complete user workflows
|
||||
- ทดสอบ document lifecycle จาก creation ถึง archival
|
||||
- ทดสอบ cross-module integrations
|
||||
|
||||
## 6.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
|
||||
|
||||
## 6.5 Performance Testing
|
||||
|
||||
- **Load Testing:** ทดสอบด้วย realistic workloads
|
||||
- **Stress Testing:** หา breaking points ของระบบ
|
||||
- **Endurance Testing:** ทดสอบการทำงานต่อเนื่องเป็นเวลานาน
|
||||
|
||||
## 6.6 Disaster Recovery Testing
|
||||
|
||||
- ทดสอบ backup และ restoration procedures
|
||||
- ทดสอบ failover mechanisms
|
||||
- ทดสอบ data integrity หลังการ recovery
|
||||
|
||||
## 6.7 Specific Scenario Testing (เพิ่ม)
|
||||
|
||||
- **Race Condition Test:** ทดสอบยิง Request ขอเลขที่เอกสารพร้อมกัน 100 Request
|
||||
- **Transaction Test:** ทดสอบปิดเน็ตระหว่าง Upload ไฟล์ (ตรวจสอบว่าไม่มี Orphan File หรือ Broken Link)
|
||||
- **Permission Test:** ทดสอบ CASL Integration ทั้งฝั่ง Backend และ Frontend ให้ตรงกัน
|
||||
|
||||
---
|
||||
*Version History*
|
||||
- **v1.5.1** – 2025‑12‑04 – Consolidated requirement specifications into single document.
|
||||
377
specs/99-archives/docs/backup/1.bak
Normal file
377
specs/99-archives/docs/backup/1.bak
Normal file
@@ -0,0 +1,377 @@
|
||||
ผมได้ตรวจสอบไฟล์ `FullStackJS_Guidelines01.md` และ `01_lcbp3_v1_1_0.sql` ของคุณแล้ว และได้อัปเดตไฟล์ Guidelines (Markdown) ให้สอดคล้องกับโครงสร้างฐานข้อมูล (SQL) ที่คุณกำหนดไว้อย่างสมบูรณ์ครับ
|
||||
|
||||
การเปลี่ยนแปลงที่สำคัญคือ:
|
||||
|
||||
1. **การจัดการ UI (UI Conflict):** แก้ไขความขัดแย้งในไฟล์เดิมที่ระบุทั้ง **Tailwind/Shadcn** และ **Bootstrap** ผมได้รวมศูนย์การพัฒนา UI ไปที่ **Tailwind/Shadcn** ตามที่ระบุไว้ในโปรไฟล์นักพัฒนา (Frontend Developer Profile) และลบส่วนของ Bootstrap ที่ซ้ำซ้อนออกไป
|
||||
2. **DMS-Specific Conventions:** อัปเดตส่วนนี้ทั้งหมดเพื่อให้ตรงกับสคีม SQL ของคุณ
|
||||
* เปลี่ยนชื่อโปรเจกต์อ้างอิงเป็น **LCBP3-DMS**
|
||||
* ปรับปรุงแผนผัง **Domain Modules** ให้สะท้อนโครงสร้างจริง (เช่น `correspondences` เป็นศูนย์กลาง, เพิ่ม `circulations`)
|
||||
* อัปเดตตาราง **AuditLog** ให้ตรงกับฟิลด์ใน SQL (เช่น เพิ่ม `entity_type`, `details_json`, `ip_address`)
|
||||
* อัปเดตตัวอย่าง **RBAC Permissions** ให้ตรงกับสิทธิ์ที่มีในตาราง `permissions` ของคุณ
|
||||
* ชี้แจง
|
||||
เรื่อง **File Handling** ว่าตาราง `attachments` จะเชื่อมโยงผ่าน `correspondence_id`
|
||||
* อัปเดตส่วน **Reporting** เพื่ออ้างอิงถึง `VIEWS` (เช่น `v_current_rfas`) ที่คุณได้สร้างไว้ใน SQL
|
||||
* ย้ายส่วน **"Recommended Enhancements"** (เช่น soft delete, indexes) ที่มีอยู่แล้วใน SQL ไปยังส่วนใหม่ชื่อ **"Implemented Standards"** เพื่อสะท้อนว่างานส่วนนี้เสร็จแล้ว
|
||||
|
||||
นี่คือไฟล์ `FullStackJS_Guidelines01.md` ฉบับที่อัปเดตแล้วครับ:
|
||||
|
||||
-----
|
||||
|
||||
# FullStackJS Development Guidelines
|
||||
|
||||
## 🧠 General Philosophy
|
||||
|
||||
Unified best practices for **NestJS Backend**, **NextJS Frontend**, and **Tailwind-based UI/UX** development in TypeScript environments.
|
||||
Focus on **clarity**, **maintainability**, **consistency**, and **accessibility** across the entire stack.
|
||||
|
||||
-----
|
||||
|
||||
## ⚙️ TypeScript General Guidelines
|
||||
|
||||
### Basic Principles
|
||||
|
||||
- Use **English** for all code and documentation.
|
||||
- Explicitly type all variables, parameters, and return values.
|
||||
- Avoid `any`; create custom types or interfaces.
|
||||
- Use **JSDoc** for public classes and methods.
|
||||
- Export only **one main symbol** per file.
|
||||
- Avoid blank lines within functions.
|
||||
|
||||
### Naming Conventions
|
||||
|
||||
| Entity | Convention | Example |
|
||||
|:--|:--|:--|
|
||||
| Classes | PascalCase | `UserService` |
|
||||
| Variables & Functions | camelCase | `getUserInfo` |
|
||||
| Files & Folders | kebab-case | `user-service.ts` |
|
||||
| Environment Variables | UPPERCASE | `DATABASE_URL` |
|
||||
| Booleans | Verb + Noun | `isActive`, `canDelete`, `hasPermission` |
|
||||
|
||||
Use full words — no abbreviations — except for standard ones (`API`, `URL`, `req`, `res`, `err`, `ctx`).
|
||||
|
||||
-----
|
||||
|
||||
## 🧩 Functions
|
||||
|
||||
- Write short, single-purpose functions (\<20 lines).
|
||||
- Use **early returns** to reduce nesting.
|
||||
- Use **map**, **filter**, **reduce** instead of loops when suitable.
|
||||
- Prefer **arrow functions** for short logic, **named functions** otherwise.
|
||||
- Use **default parameters** over null checks.
|
||||
- Group multiple parameters into a single object (RO-RO pattern).
|
||||
- Return typed objects, not primitives.
|
||||
- Maintain a single abstraction level per function.
|
||||
|
||||
-----
|
||||
|
||||
## 🧱 Data Handling
|
||||
|
||||
- Encapsulate data in composite types.
|
||||
- Use **immutability** with `readonly` and `as const`.
|
||||
- Perform validations in classes or DTOs, not within business functions.
|
||||
- Always validate data using typed DTOs.
|
||||
|
||||
-----
|
||||
|
||||
## 🧰 Classes
|
||||
|
||||
- Follow **SOLID** principles.
|
||||
- Prefer **composition over inheritance**.
|
||||
- Define **interfaces** for contracts.
|
||||
- Keep classes focused and small (\<200 lines, \<10 methods, \<10 properties).
|
||||
|
||||
-----
|
||||
|
||||
## 🚨 Error Handling
|
||||
|
||||
- Use exceptions for unexpected errors.
|
||||
- Catch only to fix or add context; otherwise, use global error handlers.
|
||||
- Always provide meaningful error messages.
|
||||
|
||||
-----
|
||||
|
||||
## 🧪 Testing (General)
|
||||
|
||||
- Use the **Arrange–Act–Assert** pattern.
|
||||
- Use descriptive test variable names (`inputData`, `expectedOutput`).
|
||||
- Write **unit tests** for all public methods.
|
||||
- Mock external dependencies.
|
||||
- Add **acceptance tests** per module using Given–When–Then.
|
||||
|
||||
-----
|
||||
|
||||
# 🏗️ Backend (NestJS)
|
||||
|
||||
### Principles
|
||||
|
||||
- **Modular architecture**:
|
||||
- One module per domain.
|
||||
- Controller → Service → Repository (Model) structure.
|
||||
- DTOs validated with **class-validator**.
|
||||
- Use **MikroORM** (or TypeORM/Prisma) for persistence, aligning with the MariaDB schema.
|
||||
- Encapsulate reusable code in a **common module** (`@app/common`):
|
||||
- Configs, decorators, DTOs, guards, interceptors, notifications, shared services, types, validators.
|
||||
|
||||
### Core Functionalities
|
||||
|
||||
- Global **filters** for exception handling.
|
||||
- **Middlewares** for request handling.
|
||||
- **Guards** for permissions and RBAC.
|
||||
- **Interceptors** for response transformation and logging.
|
||||
|
||||
### Testing
|
||||
|
||||
- Use **Jest** for testing.
|
||||
- Test each controller and service.
|
||||
- Add `admin/test` endpoint as a smoke test.
|
||||
|
||||
-----
|
||||
|
||||
# 🖥️ Frontend (NextJS / React / UI)
|
||||
|
||||
### Developer Profile
|
||||
|
||||
Senior-level TypeScript + React/NextJS engineer.
|
||||
Expert in **TailwindCSS**, **Shadcn/UI**, and **Radix** for UI development.
|
||||
|
||||
### Code Implementation Guidelines
|
||||
|
||||
- Use **early returns** for clarity.
|
||||
- Always style with **TailwindCSS** classes.
|
||||
- Prefer `class:` conditional syntax (or `clsx` utility) over ternary operators in class strings.
|
||||
- Use **const arrow functions** for components and handlers.
|
||||
- Event handlers start with `handle...` (e.g., `handleClick`, `handleSubmit`).
|
||||
- Include accessibility attributes:
|
||||
`tabIndex="0"`, `aria-label`, `onKeyDown`, etc.
|
||||
- Ensure all code is **complete**, **tested**, and **DRY**.
|
||||
- Always import required modules explicitly.
|
||||
|
||||
### UI/UX with React
|
||||
|
||||
- Use **semantic HTML**.
|
||||
- Apply **responsive Tailwind** classes (`sm:`, `md:`, `lg:`).
|
||||
- Maintain visual hierarchy with typography and spacing.
|
||||
- Use **Shadcn** components (Button, Input, Card, etc.) for consistent UI.
|
||||
- Keep components small and focused.
|
||||
- Use utility classes for quick styling (spacing, colors, text, etc.).
|
||||
- Ensure **ARIA compliance** and semantic markup.
|
||||
|
||||
### Form Validation & Errors
|
||||
|
||||
- Use client-side libraries like `zod` and `react-hook-form`.
|
||||
- Show errors with **alert components** or inline messages.
|
||||
- Include labels, placeholders, and feedback messages.
|
||||
|
||||
-----
|
||||
|
||||
# 🔗 Full Stack Integration Guidelines
|
||||
|
||||
| Aspect | Backend (NestJS) | Frontend (NextJS) | UI Layer (Tailwind/Shadcn) |
|
||||
|:--|:--|:--|:--|
|
||||
| API | REST / GraphQL Controllers | API hooks via fetch/axios/SWR | Components consuming data |
|
||||
| Validation | `class-validator` DTOs | `zod` / `react-hook-form` | Shadcn form/input states |
|
||||
| Auth | Guards, JWT | NextAuth / cookies | Auth UI states (loading, signed in) |
|
||||
| Errors | Global filters | Toasts / modals | Alerts / feedback text |
|
||||
| Testing | Jest (unit/e2e) | Vitest / Playwright | Visual regression |
|
||||
| Styles | Scoped modules (if needed) | Tailwind / Shadcn | Tailwind utilities |
|
||||
| Accessibility | Guards + filters | ARIA attributes | Semantic HTML |
|
||||
|
||||
-----
|
||||
|
||||
# 🗂️ DMS-Specific Conventions (LCBP3-DMS)
|
||||
|
||||
This section extends the general FullStackJS guidelines for the **LCBP3-DMS** project, focusing on document approval workflows (Correspondence, RFA, Drawing, Contract, Transmittal, Circulation).
|
||||
|
||||
## 🧱 Backend Domain Modules
|
||||
|
||||
Use a modular domain structure reflecting the SQL schema. `correspondences` should act as the central hub.
|
||||
|
||||
```
|
||||
src/
|
||||
├─ modules/
|
||||
│ ├─ correspondences/ (Core: Master documents, Revisions, Attachments)
|
||||
│ ├─ rfas/ (RFA logic, Revisions, Workflows, Items)
|
||||
│ ├─ drawings/ (ShopDrawings, ContractDrawings, Categories)
|
||||
│ ├─ circulations/ (Internal circulation, Templates, Assignees)
|
||||
│ ├─ transmittals/ (Transmittal logic, Items)
|
||||
│ ├─ projects-contracts/ (Projects, Contracts, Organizations, Parties)
|
||||
│ ├─ users-auth/ (Users, Roles, Permissions, Auth)
|
||||
│ ├─ audit-log/
|
||||
│ └─ common/
|
||||
```
|
||||
|
||||
### Naming Convention
|
||||
|
||||
| Entity | Example (from SQL) |
|
||||
|:--|:--|
|
||||
| Table | `correspondences`, `rfa_revisions`, `contract_parties` |
|
||||
| Column | `correspondence_id`, `created_by`, `is_current` |
|
||||
| DTO | `CreateRfaDto`, `UpdateCorrespondenceDto` |
|
||||
| Controller | `rfas.controller.ts` |
|
||||
| Service | `correspondences.service.ts` |
|
||||
|
||||
-----
|
||||
|
||||
## 🧩 RBAC & Permission Control
|
||||
|
||||
Use decorators to enforce access rights, referencing permissions from the `permissions` table.
|
||||
|
||||
```ts
|
||||
@RequirePermission('rfas.respond') // Must match a 'permission_code'
|
||||
@Put(':id')
|
||||
updateRFA(@Param('id') id: string) {
|
||||
return this.rfaService.update(id);
|
||||
}
|
||||
```
|
||||
|
||||
### Roles
|
||||
|
||||
- **SUPER\_ADMIN**: Full system access (from `roles` table).
|
||||
- **ADMIN**: Organization-level access.
|
||||
- **EDITOR**: Module-specific write access.
|
||||
- **VIEWER**: Read-only access.
|
||||
|
||||
### Example Permissions (from `permissions` table)
|
||||
|
||||
- `rfas.view`, `rfas.create`, `rfas.respond`, `rfas.delete`
|
||||
- `drawings.view`, `drawings.upload`, `drawings.delete`
|
||||
- `corr.view`, `corr.manage`
|
||||
- `transmittals.manage`
|
||||
- `cirs.manage`
|
||||
- `project_parties.manage`
|
||||
|
||||
Seed mapping between roles and permissions via seeder scripts (as seen in SQL file).
|
||||
|
||||
-----
|
||||
|
||||
## 🧾 AuditLog Standard
|
||||
|
||||
Log all CRUD and mapping operations to the `audit_logs` table.
|
||||
|
||||
| Field | Type (from SQL) | Description |
|
||||
|:--|:--|:--|
|
||||
| `audit_id` | `BIGINT` | Primary Key |
|
||||
| `user_id` | `INT` | User performing the action (FK -\> users) |
|
||||
| `action` | `VARCHAR(100)` | `rfa.create`, `correspondence.update`, `login.success` |
|
||||
| `entity_type`| `VARCHAR(50)` | Table/module name, e.g., 'rfa', 'correspondence' |
|
||||
| `entity_id` | `VARCHAR(50)` | Primary ID of the affected record |
|
||||
| `details_json`| `JSON` | Contextual data (e.g., changed fields) |
|
||||
| `ip_address` | `VARCHAR(45)` | Actor's IP address |
|
||||
| `user_agent` | `VARCHAR(255)`| Actor's User Agent |
|
||||
| `created_at` | `TIMESTAMP` | UTC timestamp |
|
||||
|
||||
Example implementation:
|
||||
|
||||
```ts
|
||||
await this.auditLogService.log({
|
||||
userId: user.id,
|
||||
action: 'rfa.update_status',
|
||||
entityType: 'rfa_revisions',
|
||||
entityId: rfaRevision.id,
|
||||
detailsJson: { from: 'DFT', to: 'FAP' },
|
||||
ipAddress: req.ip,
|
||||
});
|
||||
```
|
||||
|
||||
-----
|
||||
|
||||
## 📂 File Handling
|
||||
|
||||
### File Upload Standard
|
||||
|
||||
- Centralize all uploads via the `attachments` table.
|
||||
- Upload path (convention): `/storage/{year}/{month}/`
|
||||
- Stored filename: Use `stored_filename` (e.g., UUID or hash) to prevent conflicts. `original_filename` is for display.
|
||||
- Allowed types: `pdf, dwg, docx, xlsx, zip`
|
||||
- Max size: **50 MB**
|
||||
- Store outside webroot.
|
||||
- Serve via secure endpoint `/files/:attachment_id/download`.
|
||||
|
||||
### Access Control
|
||||
|
||||
File access is not direct. The `/files/:attachment_id/download` endpoint must:
|
||||
|
||||
1. Find the `attachment` record.
|
||||
2. Get its `correspondence_id`.
|
||||
3. Verify the user has permission to view that specific `correspondence` (or its related RFA, Transmittal, etc.).
|
||||
|
||||
-----
|
||||
|
||||
## 📊 Reporting & Exports
|
||||
|
||||
### Reporting Views (from SQL)
|
||||
|
||||
Reports should be built primarily from the pre-defined database Views:
|
||||
|
||||
- `v_current_correspondences`: For all current non-RFA document revisions.
|
||||
- `v_current_rfas`: For all current RFA revisions and their master data.
|
||||
- `v_contract_parties_all`: For auditing project/contract/organization relationships.
|
||||
|
||||
These views serve as the primary source for server-side reporting and data exports.
|
||||
|
||||
### Export Rules
|
||||
|
||||
- Export formats: CSV, Excel, PDF.
|
||||
- Provide print view.
|
||||
- Include source entity link (e.g., `/rfas/:id`).
|
||||
|
||||
-----
|
||||
|
||||
## 🧮 Frontend: DataTable & Form Patterns
|
||||
|
||||
### DataTable (Server‑Side)
|
||||
|
||||
- Endpoint: `/api/{module}?page=1&pageSize=20&sort=...&filter=...`
|
||||
- Must support: pagination, sorting, search, filters.
|
||||
- Always display latest revision inline (for RFA/Drawing).
|
||||
|
||||
### Form Standards
|
||||
|
||||
- Dependent dropdowns must be implemented (as supported by schema):
|
||||
- Project → Contract Drawing Volumes
|
||||
- Contract Drawing Category → Sub-Category
|
||||
- RFA (Shop Drawing type) → Linkable Shop Drawing Revisions
|
||||
- File upload: preview + validation (via `attachments` logic).
|
||||
- Submit via API with toast feedback.
|
||||
|
||||
-----
|
||||
|
||||
## 🧭 Dashboard & Activity Feed
|
||||
|
||||
### Dashboard Cards
|
||||
|
||||
- Show latest Correspondences, RFAs, Circulations.
|
||||
- Include KPI summaries (e.g., "RFAs Pending Approval").
|
||||
- Include quick links to modules.
|
||||
|
||||
### Activity Feed
|
||||
|
||||
- Display recent `audit_logs` actions (10 latest) relevant to the user.
|
||||
|
||||
<!-- end list -->
|
||||
|
||||
```ts
|
||||
// Example API response
|
||||
[
|
||||
{ user: 'editor01', action: 'Updated RFA (LCBP3C1-RFA-001)', time: '2025-11-04T09:30Z' }
|
||||
]
|
||||
```
|
||||
|
||||
-----
|
||||
|
||||
## ✅ Implemented Standards (from SQL v1.1.0)
|
||||
|
||||
This section confirms that the following best practices are already part of the database design and should be leveraged, not re-implemented.
|
||||
|
||||
- ✅ **Soft Delete:** Implemented via `deleted_at` columns on key tables (e.g., `correspondences`, `rfas`, `project_parties`). Logic must filter for `deleted_at IS NULL`.
|
||||
- ✅ **Database Indexes:** The schema is heavily indexed on foreign keys and common query columns (e.g., `idx_rr_rfa`, `idx_cor_project`, `idx_cr_is_current`) for performance.
|
||||
- ✅ **RBAC Structure:** A comprehensive `users`, `roles`, `permissions`, `user_roles`, and `user_project_roles` system is in place.
|
||||
- ✅ **Data Seeding:** Master data (roles, permissions, organization\_roles, initial users, project parties) is included in the schema script.
|
||||
|
||||
## 🧩 Recommended Enhancements (Future)
|
||||
|
||||
- ✅ Implement Fulltext search on fields like `correspondence_revisions.title` or `details`.
|
||||
- ✅ Create a background job (using **n8n** as noted in SQL comments) for RFA deadline reminders based on `due_date`.
|
||||
- ✅ Add a periodic cleanup job for `attachments` that are not linked to any `correspondence_id` (orphaned files).
|
||||
|
||||
-----
|
||||
1095
specs/99-archives/docs/backup/1_FullStackJS_V1_4_5.md
Normal file
1095
specs/99-archives/docs/backup/1_FullStackJS_V1_4_5.md
Normal file
File diff suppressed because it is too large
Load Diff
1448
specs/99-archives/docs/backup/1_FullStackJS_V1_5_1.md
Normal file
1448
specs/99-archives/docs/backup/1_FullStackJS_V1_5_1.md
Normal file
File diff suppressed because it is too large
Load Diff
397
specs/99-archives/docs/backup/2_Backend_Plan_V1_4_4.Phase6A.md
Normal file
397
specs/99-archives/docs/backup/2_Backend_Plan_V1_4_4.Phase6A.md
Normal file
@@ -0,0 +1,397 @@
|
||||
# “Phase 6A + Technical Design Document : Workflow DSL (Mini-Language)”**
|
||||
ออกแบบสำหรับระบบ Workflow Engine กลางของโครงการ
|
||||
**ไม่มีโค้ดผูกกับ Framework** เพื่อให้สามารถนำไป Implement ใน NestJS หรือ Microservice ใด ๆ ได้
|
||||
|
||||
---
|
||||
|
||||
## 📌 **Phase 6A – Workflow DSL Implementation Plan**
|
||||
|
||||
### 🎯 เป้าหมายของ Phase 6A
|
||||
|
||||
ใน Phase นี้ จะเริ่มสร้าง “Workflow DSL (Domain-Specific Language)” สำหรับนิยามกฎการเดินงาน (Workflow Transition Rules) ให้สามารถ:
|
||||
|
||||
* แยก **Business Workflow Logic** ออกจาก Source Code
|
||||
* แก้ไขกฎ Workflow ได้โดย **ไม่ต้องแก้โค้ดและไม่ต้อง Deploy ใหม่**
|
||||
* รองรับ Document หลายประเภท เช่น
|
||||
|
||||
* Correspondence
|
||||
* RFA
|
||||
* Internal Circulation
|
||||
* Document Transmittal
|
||||
* รองรับ Multi-step routing, skip, reject, rollback, parallel assignments
|
||||
* สามารถนำไปใช้งานทั้งใน
|
||||
|
||||
* Backend (NestJS)
|
||||
* Frontend (UI Driven)
|
||||
* External Microservices
|
||||
|
||||
---
|
||||
|
||||
### 📅 ระยะเวลา
|
||||
|
||||
**1 สัปดาห์ (หลัง Phase 6.5)**
|
||||
|
||||
---
|
||||
|
||||
### 🧩 Output ของ Phase 6A
|
||||
|
||||
* DSL Specification (Grammar)
|
||||
* JSON Schema for Workflow Definition
|
||||
* Workflow Rule Interpreter (Parser + Executor)
|
||||
* Validation Engine (Compile-time and Runtime)
|
||||
* Storage (DB Table / Registry)
|
||||
* Execution API:
|
||||
|
||||
| Action | Description |
|
||||
| -------------------------------- | ------------------------------- |
|
||||
| compile() | ตรวจ DSL → สร้าง Execution Tree |
|
||||
| evaluate(state, action, context) | ประมวลผลและส่งสถานะใหม่ |
|
||||
| preview(state) | คำนวณ Next Possible Transitions |
|
||||
| validate() | ตรวจว่า DSL ถูกต้อง |
|
||||
|
||||
---
|
||||
|
||||
## 📘 **Technical Specification – Workflow DSL**
|
||||
|
||||
---
|
||||
|
||||
### 1️⃣ Requirements
|
||||
|
||||
#### Functional Requirements
|
||||
|
||||
* นิยาม Workflow เป็นภาษาคล้าย State Machine
|
||||
* แต่ละเอกสารมี **State, Actions, Entry/Exit Events**
|
||||
* สามารถมี:
|
||||
|
||||
* Required approvals
|
||||
* Conditional transition
|
||||
* Auto-transition
|
||||
* Parallel approval
|
||||
* Return/rollback
|
||||
|
||||
####
|
||||
* Running time: < 20ms ต่อคำสั่ง
|
||||
* Hot reload ไม่ต้อง Compile ใหม่ทั้ง Backend
|
||||
* DSL ต้อง Debug ได้ง่าย
|
||||
* ต้อง Versioned
|
||||
* ต้องรองรับ Audit 100%
|
||||
|
||||
---
|
||||
|
||||
### 2️⃣ DSL Format (Human Friendly)
|
||||
|
||||
```yaml
|
||||
workflow: RFA
|
||||
version: 1.0
|
||||
|
||||
states:
|
||||
- name: DRAFT
|
||||
initial: true
|
||||
on:
|
||||
SUBMIT:
|
||||
to: IN_REVIEW
|
||||
require:
|
||||
- role: ENGINEER
|
||||
events:
|
||||
- notify: reviewer
|
||||
|
||||
- name: IN_REVIEW
|
||||
on:
|
||||
APPROVE:
|
||||
to: APPROVED
|
||||
REJECT:
|
||||
to: DRAFT
|
||||
events:
|
||||
- notify: creator
|
||||
|
||||
- name: APPROVED
|
||||
terminal: true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3️⃣ Compiled Execution Model (Normalized JSON)
|
||||
|
||||
```json
|
||||
{
|
||||
"workflow": "RFA",
|
||||
"version": "1.0",
|
||||
"states": {
|
||||
"DRAFT": {
|
||||
"initial": true,
|
||||
"transitions": {
|
||||
"SUBMIT": {
|
||||
"to": "IN_REVIEW",
|
||||
"requirements": [
|
||||
{ "role": "ENGINEER" }
|
||||
],
|
||||
"events": [
|
||||
{ "type": "notify", "target": "reviewer" }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"IN_REVIEW": {
|
||||
"transitions": {
|
||||
"APPROVE": { "to": "APPROVED" },
|
||||
"REJECT": {
|
||||
"to": "DRAFT",
|
||||
"events": [
|
||||
{ "type": "notify", "target": "creator" }
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"APPROVED": {
|
||||
"terminal": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Frontend และ Backend สามารถแชร์ JSON นี้ร่วมกันได้
|
||||
|
||||
---
|
||||
|
||||
### 4️⃣ DSL Grammar Definition (EBNF)
|
||||
|
||||
```ebnf
|
||||
workflow = "workflow" ":" identifier ;
|
||||
version = "version" ":" number ;
|
||||
|
||||
states = "states:" state_list ;
|
||||
state_list = { state } ;
|
||||
|
||||
state = "- name:" identifier
|
||||
[ "initial:" boolean ]
|
||||
[ "terminal:" boolean ]
|
||||
[ "on:" transition_list ] ;
|
||||
|
||||
transition_list = { transition } ;
|
||||
|
||||
transition = action ":"
|
||||
indent "to:" identifier
|
||||
[ indent "require:" requirements ]
|
||||
[ indent "events:" event_list ] ;
|
||||
|
||||
requirements = "- role:" identifier | "- user:" identifier ;
|
||||
|
||||
event_list = { event } ;
|
||||
event = "- notify:" identifier ;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5️⃣ Validation Rules (Compile-Time)
|
||||
|
||||
#### 5.1 State Rules
|
||||
|
||||
* ต้องมีอย่างน้อย 1 state ที่ `initial: true`
|
||||
* หาก `terminal: true` → ต้องไม่มี transition ต่อไป
|
||||
|
||||
#### 5.2 Transition Rules
|
||||
|
||||
ตรวจสอบว่า:
|
||||
|
||||
* `to` ชี้ไปยัง state ที่มีอยู่
|
||||
* `require.role` ต้องเป็น role ที่ระบบรู้จัก
|
||||
* Action name ต้องเป็น **UPPER_CASE**
|
||||
|
||||
#### 5.3 Version Safety
|
||||
|
||||
* ทุกชุด Workflow DSL ต้องขึ้นกับ version
|
||||
* แก้ไขต้องสร้าง version ใหม่
|
||||
* ไม่ overwrite version เก่า
|
||||
* “Document ที่กำลังอยู่ใน step เดิมยังต้องใช้กฎเดิมได้”
|
||||
|
||||
---
|
||||
|
||||
### 6️⃣ Runtime Validation Rules
|
||||
|
||||
เมื่อ execute(action):
|
||||
|
||||
```
|
||||
input: current_state, action, context
|
||||
|
||||
1) ตรวจว่า state มี transition "action"
|
||||
2) ตรวจว่าผู้ใช้มีสิทธิ์ตาม require[]
|
||||
3) Compute next state
|
||||
4) Execute events[]
|
||||
5) Return next_state
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7️⃣ Context Model
|
||||
|
||||
```ts
|
||||
interface WorkflowContext {
|
||||
userId: string;
|
||||
roles: string[];
|
||||
documentId: string;
|
||||
now: Date;
|
||||
payload?: any;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8️⃣ Execution API (Abstract)
|
||||
|
||||
```ts
|
||||
class WorkflowEngine {
|
||||
|
||||
load(dsl: string | object): CompiledWorkflow
|
||||
|
||||
compile(dsl: string | object): CompiledWorkflow
|
||||
|
||||
evaluate(state: string, action: string, context: WorkflowContext): EvalResult
|
||||
|
||||
getAvailableActions(state: string, context: WorkflowContext): string[]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 9️⃣ Interpreter Execution Flow
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Receive Action] --> B[Load Compiled Workflow]
|
||||
B --> C[Check allowed actions]
|
||||
C -->|Invalid| E[Return Error]
|
||||
C --> D[Evaluate Requirements]
|
||||
D --> F[Transition to Next State]
|
||||
F --> G[Run Events]
|
||||
G --> H[Return Success]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🔟 Events System
|
||||
|
||||
รองรับ event หลายประเภท:
|
||||
|
||||
| event.type | ตัวอย่าง |
|
||||
| ----------- | ------------------------- |
|
||||
| notify | ส่ง Email/Line |
|
||||
| assign | เปลี่ยนผู้รับผิดชอบ |
|
||||
| webhook | ยิง Webhook ไปยังระบบอื่น |
|
||||
| auto_action | ทำ action ซ้ำโดยอัตโนมัติ |
|
||||
|
||||
---
|
||||
|
||||
### 11️⃣ Database Schema
|
||||
|
||||
#### Table: `workflow_definition`
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------- | ----------- | --------------------- |
|
||||
| id | UUID | PK |
|
||||
| workflow_code | varchar(50) | เช่น `RFA`, `CORR` |
|
||||
| version | int | Version number |
|
||||
| dsl | JSON | YAML/JSON DSL เก็บดิบ |
|
||||
| compiled | JSON | JSON ที่ Compile แล้ว |
|
||||
| created_at | timestamp | |
|
||||
| is_active | boolean | ใช้อยู่หรือไม่ |
|
||||
|
||||
#### Table: `workflow_history`
|
||||
|
||||
เก็บ audit แบบ immutable append-only
|
||||
|
||||
| Field | Description |
|
||||
| ----------- | --------------- |
|
||||
| workflow | Document Type |
|
||||
| document_id | เอกสารไหน |
|
||||
| from_state | เดิม |
|
||||
| to_state | ใหม่ |
|
||||
| action | คำสั่ง |
|
||||
| user | ใครเป็นคนทำ |
|
||||
| timestamp | เวลา |
|
||||
| metadata | เหตุการณ์อื่น ๆ |
|
||||
|
||||
---
|
||||
|
||||
### 12️⃣ Error Codes
|
||||
|
||||
| Code | Meaning |
|
||||
| ----------------------- | ---------------------- |
|
||||
| WF_NO_TRANSITION | Action นี้ไม่ถูกต้อง |
|
||||
| WF_RESTRICTED | User ไม่มีสิทธิ์ |
|
||||
| WF_MISSING_REQUIREMENTS | ไม่ผ่านเงื่อนไข |
|
||||
| WF_STATE_NOT_FOUND | ไม่มี state ที่อ้างอิง |
|
||||
| WF_SYNTAX_ERROR | DSL ผิดรูปแบบ |
|
||||
|
||||
---
|
||||
|
||||
### 13️⃣ Testing Strategy
|
||||
|
||||
#### Unit Tests
|
||||
|
||||
* Parse DSL → JSON
|
||||
* Invalid syntax → throw error
|
||||
* Invalid transitions → throw error
|
||||
|
||||
#### Integration Tests
|
||||
|
||||
* Evaluate() ผ่าน 20+ cases
|
||||
* RFA ย้อนกลับ
|
||||
* Approve chain
|
||||
* Parallel review
|
||||
|
||||
#### Load Tests
|
||||
|
||||
* 1,000 documents running workflow
|
||||
* Evaluate < 20ms ต่อ action
|
||||
|
||||
---
|
||||
|
||||
### 14️⃣ Deployment Strategy
|
||||
|
||||
#### Hot Reload Options
|
||||
|
||||
* DSL stored in DB
|
||||
* Cache in Redis
|
||||
* Touched timestamp triggers:
|
||||
|
||||
```
|
||||
invalidate cache → recompile
|
||||
```
|
||||
|
||||
#### No downtime required
|
||||
|
||||
---
|
||||
|
||||
### 15️⃣ Microservice-Ready
|
||||
|
||||
DSL Engine แยกเป็น:
|
||||
|
||||
* `workflow-engine-core` → Pure JS library
|
||||
* `workflow-service` → NestJS module
|
||||
* API public:
|
||||
|
||||
```
|
||||
POST /workflow/evaluate
|
||||
GET /workflow/preview
|
||||
POST /workflow/compile
|
||||
```
|
||||
|
||||
ภายหลังสามารถนำไปวางบน:
|
||||
|
||||
* Kubernetes
|
||||
* Worker Node
|
||||
* API Gateway
|
||||
|
||||
---
|
||||
|
||||
## 🎉 Summary
|
||||
|
||||
### สิ่งที่ Phase 6A เพิ่มเข้าในระบบ
|
||||
|
||||
✔ Workflow DSL ที่แก้ไขได้โดยไม่ต้อง Deploy
|
||||
✔ Parser + Validator + Runtime Interpreter
|
||||
✔ Database storage + Versioning
|
||||
✔ Execution API สำหรับ Backend และ Frontend
|
||||
✔ รองรับ Business Workflow ซับซ้อนทั้งหมด
|
||||
✔ Ready สำหรับ Microservice model ในอนาคต
|
||||
|
||||
@@ -0,0 +1,709 @@
|
||||
# 🎯 **Admin Panel Comprehensive Analysis สำหรับ LCBP3-DMS v1.4.4**
|
||||
|
||||
จากการวิเคราะห์ Requirements และ Technical Design ทั้งหมด ขอนำเสนอ Admin Panel ที่สมบูรณ์สำหรับระบบ LCBP3-DMS
|
||||
|
||||
## 📊 **ภาพรวม Admin Panel Structure**
|
||||
|
||||
### **Role-Based Access Levels**
|
||||
|
||||
- **Superadmin:** Full system access
|
||||
- **Org Admin:** Organization-level management
|
||||
- **Project Manager:** Project-level administration
|
||||
- **Contract Admin:** Contract-specific management
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ **1. System Administration**
|
||||
|
||||
### **1.1 Global System Configuration**
|
||||
|
||||
```typescript
|
||||
interface SystemConfig {
|
||||
maintenance_mode: boolean;
|
||||
session_timeout: number;
|
||||
password_policy: {
|
||||
min_length: number;
|
||||
require_uppercase: boolean;
|
||||
require_numbers: boolean;
|
||||
require_special_chars: boolean;
|
||||
expiry_days: number;
|
||||
};
|
||||
file_upload: {
|
||||
max_size_mb: number;
|
||||
allowed_types: string[];
|
||||
virus_scan_enabled: boolean;
|
||||
};
|
||||
notification: {
|
||||
email_enabled: boolean;
|
||||
line_enabled: boolean;
|
||||
digest_frequency: number; // minutes
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Toggle Maintenance Mode
|
||||
- [ ] Configure Security Policies
|
||||
- [ ] Manage File Upload Settings
|
||||
- [ ] Configure Notification Channels
|
||||
- [ ] System Health Monitoring Dashboard
|
||||
|
||||
### **1.2 Audit & Monitoring Center**
|
||||
|
||||
```typescript
|
||||
interface AuditDashboard {
|
||||
security_metrics: {
|
||||
failed_logins: number;
|
||||
file_scans: number;
|
||||
virus_detections: number;
|
||||
permission_changes: number;
|
||||
};
|
||||
user_activity: AuditLog[];
|
||||
system_performance: PerformanceMetrics;
|
||||
recent_errors: SystemError[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Real-time Activity Monitoring
|
||||
- [ ] Security Incident Reporting
|
||||
- [ ] Performance Metrics Dashboard
|
||||
- [ ] Error Log Viewer
|
||||
- [ ] Export Audit Reports
|
||||
|
||||
---
|
||||
|
||||
## 👥 **2. User & Organization Management**
|
||||
|
||||
### **2.1 User Management**
|
||||
|
||||
```typescript
|
||||
interface UserManagement {
|
||||
user_list: User[];
|
||||
bulk_operations: {
|
||||
import_users: FileUpload;
|
||||
export_users: CSVExport;
|
||||
bulk_assign_roles: RoleAssignment[];
|
||||
};
|
||||
user_lifecycle: {
|
||||
onboarding_workflow: WorkflowConfig;
|
||||
offboarding_checklist: ChecklistItem[];
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] User CRUD Operations
|
||||
- [ ] Bulk User Import/Export
|
||||
- [ ] User Activity Tracking
|
||||
- [ ] Password Reset Management
|
||||
- [ ] User Session Management
|
||||
|
||||
### **2.2 Organization Hierarchy**
|
||||
|
||||
```typescript
|
||||
interface OrganizationManagement {
|
||||
organization_tree: Organization[];
|
||||
department_structure: Department[];
|
||||
contact_persons: Contact[];
|
||||
organization_settings: {
|
||||
document_retention_policy: RetentionPolicy;
|
||||
notification_preferences: NotificationConfig;
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Organization CRUD
|
||||
- [ ] Department Structure Management
|
||||
- [ ] Contact Person Assignment
|
||||
- [ ] Organization-specific Policies
|
||||
|
||||
### **2.3 Advanced RBAC Management**
|
||||
|
||||
```typescript
|
||||
interface RBACManagement {
|
||||
role_definitions: Role[];
|
||||
permission_matrix: Permission[];
|
||||
assignment_rules: {
|
||||
automatic_assignments: AutoAssignmentRule[];
|
||||
conditional_access: ConditionalRule[];
|
||||
};
|
||||
permission_audit: {
|
||||
permission_usage: UsageStats[];
|
||||
conflict_detection: Conflict[];
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Custom Role Creation
|
||||
- [ ] Granular Permission Management
|
||||
- [ ] Automatic Role Assignment Rules
|
||||
- [ ] Permission Conflict Detection
|
||||
- [ ] Role Usage Analytics
|
||||
|
||||
---
|
||||
|
||||
## 📁 **3. Project & Contract Administration**
|
||||
|
||||
### **3.1 Project Portfolio Management**
|
||||
|
||||
```typescript
|
||||
interface ProjectManagement {
|
||||
project_dashboard: ProjectOverview[];
|
||||
project_phases: Phase[];
|
||||
milestone_tracking: Milestone[];
|
||||
resource_allocation: Resource[];
|
||||
project_analytics: ProjectMetrics;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Project Lifecycle Management
|
||||
- [ ] Phase and Milestone Tracking
|
||||
- [ ] Resource Allocation
|
||||
- [ ] Project Performance Analytics
|
||||
- [ ] Project Documentation Repository
|
||||
|
||||
### **3.2 Contract Administration**
|
||||
|
||||
```typescript
|
||||
interface ContractManagement {
|
||||
contract_register: Contract[];
|
||||
party_management: ContractParty[];
|
||||
amendment_tracking: Amendment[];
|
||||
compliance_monitoring: ComplianceCheck[];
|
||||
financial_tracking: FinancialMetrics;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Contract CRUD Operations
|
||||
- [ ] Contract Party Management
|
||||
- [ ] Amendment History
|
||||
- [ ] Compliance Monitoring
|
||||
- [ ] Financial Tracking
|
||||
|
||||
### **3.3 Project-Organization Mapping**
|
||||
|
||||
```typescript
|
||||
interface ProjectOrgMapping {
|
||||
project_assignments: ProjectAssignment[];
|
||||
access_control: AccessRule[];
|
||||
collaboration_settings: CollaborationConfig;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Organization Assignment to Projects
|
||||
- [ ] Cross-Organization Collaboration Settings
|
||||
- [ ] Access Control Configuration
|
||||
|
||||
---
|
||||
|
||||
## 📋 **4. Master Data Management**
|
||||
|
||||
### **4.1 Document Type Ecosystem**
|
||||
|
||||
```typescript
|
||||
interface DocumentTypeManagement {
|
||||
correspondence_types: DocumentType[];
|
||||
rfa_types: RFAType[];
|
||||
circulation_types: CirculationType[];
|
||||
drawing_categories: DrawingCategory[];
|
||||
type_hierarchy: TypeHierarchy;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Document Type CRUD
|
||||
- [ ] Type-Specific Workflow Configuration
|
||||
- [ ] Category Hierarchy Management
|
||||
- [ ] Template Association
|
||||
|
||||
### **4.2 Discipline & Classification System**
|
||||
|
||||
```typescript
|
||||
interface DisciplineManagement {
|
||||
disciplines: Discipline[];
|
||||
sub_types: SubType[];
|
||||
classification_rules: ClassificationRule[];
|
||||
mapping_configurations: MappingConfig[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Discipline CRUD (ตาม Requirement 6B)
|
||||
- [ ] Sub-Type Management with Number Mapping
|
||||
- [ ] Automatic Classification Rules
|
||||
- [ ] Cross-Reference Mapping
|
||||
|
||||
### **4.3 Status & Code Management**
|
||||
|
||||
```typescript
|
||||
interface StatusManagement {
|
||||
status_codes: StatusCode[];
|
||||
transition_rules: TransitionRule[];
|
||||
status_workflows: StatusWorkflow[];
|
||||
automated_status_changes: AutoStatusChange[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Status Code Configuration
|
||||
- [ ] State Transition Rules
|
||||
- [ ] Automated Status Updates
|
||||
- [ ] Status Change Analytics
|
||||
|
||||
---
|
||||
|
||||
## 🔢 **5. Document Numbering System Administration**
|
||||
|
||||
### **5.1 Numbering Format Configuration**
|
||||
|
||||
```typescript
|
||||
interface NumberingFormatManagement {
|
||||
format_templates: NumberingTemplate[];
|
||||
token_library: TokenDefinition[];
|
||||
format_preview: FormatPreview;
|
||||
validation_rules: ValidationRule[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Template Editor with Live Preview
|
||||
- [ ] Custom Token Definition
|
||||
- [ ] Format Validation
|
||||
- [ ] Bulk Template Application
|
||||
|
||||
### **5.2 Counter Management**
|
||||
|
||||
```typescript
|
||||
interface CounterManagement {
|
||||
counter_groups: CounterGroup[];
|
||||
reset_schedules: ResetSchedule[];
|
||||
counter_audit: CounterHistory[];
|
||||
conflict_resolution: ConflictResolutionRule[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Counter Group Configuration
|
||||
- [ ] Scheduled Reset Management
|
||||
- [ ] Counter Audit Trail
|
||||
- [ ] Conflict Resolution Rules
|
||||
|
||||
### **5.3 Numbering Rule Engine**
|
||||
|
||||
```typescript
|
||||
interface NumberingRuleEngine {
|
||||
conditional_rules: ConditionalRule[];
|
||||
context_resolvers: ContextResolver[];
|
||||
fallback_strategies: FallbackStrategy[];
|
||||
performance_monitoring: PerformanceMetrics;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Conditional Numbering Rules
|
||||
- [ ] Context Variable Management
|
||||
- [ ] Fallback Strategy Configuration
|
||||
- [ ] Performance Optimization
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ **6. Workflow & Routing Administration**
|
||||
|
||||
### **6.1 Workflow DSL Management**
|
||||
|
||||
```typescript
|
||||
interface WorkflowDSLManagement {
|
||||
workflow_library: WorkflowDefinition[];
|
||||
dsl_editor: DSLEditor;
|
||||
version_control: VersionHistory[];
|
||||
deployment_pipeline: DeploymentConfig[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Visual Workflow Designer
|
||||
- [ ] DSL Code Editor with Syntax Highlighting
|
||||
- [ ] Version Control and Rollback
|
||||
- [ ] Testing and Deployment Pipeline
|
||||
|
||||
### **6.2 Routing Template Administration**
|
||||
|
||||
```typescript
|
||||
interface RoutingTemplateManagement {
|
||||
template_library: RoutingTemplate[];
|
||||
step_configurations: StepConfig[];
|
||||
approval_chains: ApprovalChain[];
|
||||
escalation_rules: EscalationRule[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Template CRUD Operations
|
||||
- [ ] Drag-and-Drop Step Configuration
|
||||
- [ ] Approval Chain Management
|
||||
- [ ] Escalation Rule Setup
|
||||
|
||||
### **6.3 Workflow Analytics**
|
||||
|
||||
```typescript
|
||||
interface WorkflowAnalytics {
|
||||
performance_metrics: WorkflowMetrics[];
|
||||
bottleneck_analysis: Bottleneck[];
|
||||
compliance_reporting: ComplianceReport[];
|
||||
optimization_recommendations: Recommendation[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Workflow Performance Dashboard
|
||||
- [ ] Bottleneck Identification
|
||||
- [ ] Compliance Reporting
|
||||
- [ ] Optimization Suggestions
|
||||
|
||||
---
|
||||
|
||||
## 📊 **7. Reporting & Analytics Center**
|
||||
|
||||
### **7.1 Custom Report Builder**
|
||||
|
||||
```typescript
|
||||
interface ReportBuilder {
|
||||
data_sources: DataSource[];
|
||||
visualization_types: VisualizationType[];
|
||||
report_templates: ReportTemplate[];
|
||||
scheduling: ScheduleConfig[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Drag-and-Drop Report Designer
|
||||
- [ ] Multiple Visualization Options
|
||||
- [ ] Template Library
|
||||
- [ ] Automated Report Scheduling
|
||||
|
||||
### **7.2 Business Intelligence**
|
||||
|
||||
```typescript
|
||||
interface BusinessIntelligence {
|
||||
kpi_dashboard: KPIMetric[];
|
||||
trend_analysis: TrendData[];
|
||||
predictive_analytics: PredictiveModel[];
|
||||
data_export: ExportConfig[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Real-time KPI Dashboard
|
||||
- [ ] Trend Analysis Tools
|
||||
- [ ] Predictive Analytics
|
||||
- [ ] Data Export and Integration
|
||||
|
||||
### **7.3 Compliance Reporting**
|
||||
|
||||
```typescript
|
||||
interface ComplianceReporting {
|
||||
regulatory_reports: RegulatoryReport[];
|
||||
audit_trails: AuditTrail[];
|
||||
compliance_dashboard: ComplianceMetric[];
|
||||
certification_tracking: Certification[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Pre-built Regulatory Reports
|
||||
- [ ] Comprehensive Audit Trails
|
||||
- [ ] Compliance Dashboard
|
||||
- [ ] Certification Management
|
||||
|
||||
---
|
||||
|
||||
## 🔐 **8. Security & Compliance Center**
|
||||
|
||||
### **8.1 Security Policy Management**
|
||||
|
||||
```typescript
|
||||
interface SecurityPolicyManagement {
|
||||
access_policies: AccessPolicy[];
|
||||
data_classification: DataClassification[];
|
||||
encryption_settings: EncryptionConfig[];
|
||||
security_incidents: SecurityIncident[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Access Policy Configuration
|
||||
- [ ] Data Classification Scheme
|
||||
- [ ] Encryption Management
|
||||
- [ ] Security Incident Tracking
|
||||
|
||||
### **8.2 Compliance Framework**
|
||||
|
||||
```typescript
|
||||
interface ComplianceFramework {
|
||||
compliance_rules: ComplianceRule[];
|
||||
control_testing: ControlTest[];
|
||||
evidence_management: Evidence[];
|
||||
compliance_calendar: ComplianceEvent[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Compliance Rule Engine
|
||||
- [ ] Control Testing Framework
|
||||
- [ ] Evidence Collection
|
||||
- [ ] Compliance Calendar
|
||||
|
||||
### **8.3 Risk Management**
|
||||
|
||||
```typescript
|
||||
interface RiskManagement {
|
||||
risk_register: Risk[];
|
||||
risk_assessments: RiskAssessment[];
|
||||
mitigation_plans: MitigationPlan[];
|
||||
risk_dashboard: RiskMetrics;
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Risk Identification and Registration
|
||||
- [ ] Risk Assessment Tools
|
||||
- [ ] Mitigation Planning
|
||||
- [ ] Risk Monitoring Dashboard
|
||||
|
||||
---
|
||||
|
||||
## 📧 **9. Notification & Communication Management**
|
||||
|
||||
### **9.1 Notification Template System**
|
||||
|
||||
```typescript
|
||||
interface NotificationTemplateManagement {
|
||||
email_templates: EmailTemplate[];
|
||||
line_templates: LineTemplate[];
|
||||
system_notifications: SystemTemplate[];
|
||||
template_variables: TemplateVariable[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Multi-channel Template Management
|
||||
- [ ] Variable Substitution System
|
||||
- [ ] Template Testing and Preview
|
||||
- [ ] Bulk Template Operations
|
||||
|
||||
### **9.2 Subscription Management**
|
||||
|
||||
```typescript
|
||||
interface SubscriptionManagement {
|
||||
user_preferences: UserPreference[];
|
||||
group_subscriptions: GroupSubscription[];
|
||||
escalation_policies: EscalationPolicy[];
|
||||
delivery_reports: DeliveryReport[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] User Preference Management
|
||||
- [ ] Group Subscription Configuration
|
||||
- [ ] Escalation Policy Setup
|
||||
- [ ] Delivery Monitoring
|
||||
|
||||
### **9.3 Digest Configuration**
|
||||
|
||||
```typescript
|
||||
interface DigestConfiguration {
|
||||
digest_rules: DigestRule[];
|
||||
grouping_criteria: GroupingCriteria[];
|
||||
timing_configurations: TimingConfig[];
|
||||
content_prioritization: PriorityRule[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Digest Rule Engine
|
||||
- [ ] Content Grouping Configuration
|
||||
- [ ] Timing and Frequency Settings
|
||||
- [ ] Content Prioritization Rules
|
||||
|
||||
---
|
||||
|
||||
## 🗃️ **10. Data Management & Maintenance**
|
||||
|
||||
### **10.1 Data Lifecycle Management**
|
||||
|
||||
```typescript
|
||||
interface DataLifecycleManagement {
|
||||
retention_policies: RetentionPolicy[];
|
||||
archival_rules: ArchivalRule[];
|
||||
purge_schedules: PurgeSchedule[];
|
||||
data_governance: GovernancePolicy[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Retention Policy Configuration
|
||||
- [ ] Automated Archival Rules
|
||||
- [ ] Scheduled Data Purge
|
||||
- [ ] Data Governance Framework
|
||||
|
||||
### **10.2 Backup & Recovery**
|
||||
|
||||
```typescript
|
||||
interface BackupRecoveryManagement {
|
||||
backup_configurations: BackupConfig[];
|
||||
recovery_procedures: RecoveryProcedure[];
|
||||
disaster_recovery: DisasterRecoveryPlan[];
|
||||
backup_monitoring: BackupMonitor[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Backup Schedule Management
|
||||
- [ ] Recovery Procedure Documentation
|
||||
- [ ] Disaster Recovery Planning
|
||||
- [ ] Backup Status Monitoring
|
||||
|
||||
### **10.3 System Maintenance**
|
||||
|
||||
```typescript
|
||||
interface SystemMaintenance {
|
||||
maintenance_windows: MaintenanceWindow[];
|
||||
update_management: UpdateConfig[];
|
||||
performance_tuning: TuningParameter[];
|
||||
cleanup_jobs: CleanupJob[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Maintenance Window Scheduling
|
||||
- [ ] Update Management
|
||||
- [ ] Performance Tuning Parameters
|
||||
- [ ] Automated Cleanup Jobs
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **11. Dashboard & Overview**
|
||||
|
||||
### **11.1 Executive Dashboard**
|
||||
|
||||
```typescript
|
||||
interface ExecutiveDashboard {
|
||||
system_health: HealthMetric[];
|
||||
business_metrics: BusinessMetric[];
|
||||
user_engagement: EngagementMetric[];
|
||||
security_posture: SecurityMetric[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Real-time System Health Monitoring
|
||||
- [ ] Business Performance Metrics
|
||||
- [ ] User Engagement Analytics
|
||||
- [ ] Security Posture Assessment
|
||||
|
||||
### **11.2 Operational Dashboard**
|
||||
|
||||
```typescript
|
||||
interface OperationalDashboard {
|
||||
workflow_monitoring: WorkflowStatus[];
|
||||
document_metrics: DocumentMetric[];
|
||||
user_productivity: ProductivityMetric[];
|
||||
system_utilization: UtilizationMetric[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Workflow Status Monitoring
|
||||
- [ ] Document Processing Metrics
|
||||
- [ ] User Productivity Analytics
|
||||
- [ ] System Resource Utilization
|
||||
|
||||
---
|
||||
|
||||
## 🔄 **12. Integration & API Management**
|
||||
|
||||
### **12.1 API Gateway Administration**
|
||||
|
||||
```typescript
|
||||
interface APIManagement {
|
||||
api_endpoints: APIEndpoint[];
|
||||
rate_limiting: RateLimitConfig[];
|
||||
authentication_settings: AuthConfig[];
|
||||
api_analytics: APIAnalytics[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] API Endpoint Management
|
||||
- [ ] Rate Limiting Configuration
|
||||
- [ ] Authentication Settings
|
||||
- [ ] API Usage Analytics
|
||||
|
||||
### **12.2 External Integration**
|
||||
|
||||
```typescript
|
||||
interface ExternalIntegration {
|
||||
webhook_configurations: WebhookConfig[];
|
||||
third_party_connectors: Connector[];
|
||||
data_sync_rules: SyncRule[];
|
||||
integration_monitoring: IntegrationMonitor[];
|
||||
}
|
||||
```
|
||||
|
||||
**Features:**
|
||||
|
||||
- [ ] Webhook Management
|
||||
- [ ] Third-party Connector Configuration
|
||||
- [ ] Data Synchronization Rules
|
||||
- [ ] Integration Health Monitoring
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Critical Success Factors**
|
||||
|
||||
1. **Unified Administration Experience** - Single pane of glass สำหรับทุกการจัดการ
|
||||
2. **Role-Based Access Control** - แต่ละระดับเห็นและจัดการได้เฉพาะส่วนของตัวเอง
|
||||
3. **Real-time Monitoring** - ระบบ monitoring แบบ real-time ทุกส่วน
|
||||
4. **Audit Trail** - ทุกการเปลี่ยนแปลงใน Admin Panel ถูกบันทึกไว้
|
||||
5. **Performance** - Admin operations ต้องรวดเร็วแม้มีข้อมูลจำนวนมาก
|
||||
6. **User Experience** - Interface ใช้งานง่าย แม้สำหรับฟีเจอร์ที่ซับซ้อน
|
||||
|
||||
Admin Panel นี้จะทำให้ผู้ดูแลระบบสามารถจัดการ LCBP3-DMS ได้อย่างสมบูรณ์แบบ ตั้งแต่การตั้งค่าระดับพื้นฐานไปจนถึงการจัดการ workflow ที่ซับซ้อนและการวิเคราะห์ข้อมูลเชิงลึก
|
||||
2137
specs/99-archives/docs/backup/2_Backend_Plan_V1_4_5.md
Normal file
2137
specs/99-archives/docs/backup/2_Backend_Plan_V1_4_5.md
Normal file
File diff suppressed because it is too large
Load Diff
210
specs/99-archives/docs/backup/2_Backend_Plan_V1_5_1.md
Normal file
210
specs/99-archives/docs/backup/2_Backend_Plan_V1_5_1.md
Normal file
@@ -0,0 +1,210 @@
|
||||
# 📋 **แผนการพัฒนา Backend (NestJS) - LCBP3-DMS v1.5.1**
|
||||
|
||||
**สถานะ:** DRAFT
|
||||
**วันที่:** 2025-12-04
|
||||
**อ้างอิง:** Requirements v1.5.1 & FullStackJS Guidelines v1.5.1
|
||||
**Classification:** Internal Technical Documentation
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **ภาพรวมโครงการ (Project Overview)**
|
||||
|
||||
พัฒนา Backend สำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System) เวอร์ชัน 1.5.1 โดยเน้นการปรับปรุงสถาปัตยกรรมหลัก 3 ส่วนสำคัญ:
|
||||
1. **Unified Workflow Engine:** ระบบ Workflow แบบ Dynamic ที่ยืดหยุ่น รองรับการกำหนด Rule ผ่าน DSL
|
||||
2. **Advanced Document Numbering:** ระบบสร้างเลขที่เอกสารที่ซับซ้อน (8-component key) พร้อม Double-Lock Mechanism ป้องกัน Race Condition
|
||||
3. **Enhanced Master Data:** การจัดการข้อมูลหลักที่ครอบคลุม (Discipline, SubType) และ JSON Schema Management
|
||||
|
||||
---
|
||||
|
||||
## 📐 **สถาปัตยกรรมระบบ (System Architecture)**
|
||||
|
||||
### **Technology Stack**
|
||||
|
||||
- **Framework:** NestJS (TypeScript, ESM)
|
||||
- **Database:** MariaDB 10.11 (ใช้ Virtual Columns & Partitioning)
|
||||
- **ORM:** TypeORM (Optimistic Locking)
|
||||
- **Workflow Engine:** Custom DSL-based Engine (State Machine)
|
||||
- **Queue:** BullMQ (Redis) สำหรับ Async Jobs & Notifications
|
||||
- **Locking:** Redis (Redlock) + DB Pessimistic Fallback
|
||||
- **Search:** Elasticsearch
|
||||
- **Validation:** Zod / Class-validator / AJV (JSON Schema)
|
||||
|
||||
### **โครงสร้างโมดูล (Module Structure)**
|
||||
|
||||
```
|
||||
📁src
|
||||
├── 📁common # Shared utilities, guards, decorators
|
||||
├── 📁config # Configuration setup
|
||||
├── 📁database # Migrations & Seeds
|
||||
├── 📁modules
|
||||
│ ├── 📁auth # Authentication (JWT)
|
||||
│ ├── 📁user # User & RBAC Management
|
||||
│ ├── 📁master-data # Organization, Project, Type, Discipline (NEW)
|
||||
│ ├── 📁document-numbering # Numbering Service (Updated)
|
||||
│ ├── 📁workflow-engine # Unified Workflow Engine (NEW)
|
||||
│ ├── 📁correspondence # Correspondence Management
|
||||
│ ├── 📁rfa # RFA Management
|
||||
│ ├── 📁drawing # Drawing Management
|
||||
│ ├── 📁transmittal # Transmittal Management
|
||||
│ ├── 📁circulation # Circulation Management
|
||||
│ ├── 📁file-storage # File Upload & Handling
|
||||
│ ├── 📁json-schema # JSON Schema Registry (NEW)
|
||||
│ ├── 📁search # Elasticsearch Integration
|
||||
│ ├── 📁notification # Notification System
|
||||
│ └── 📁monitoring # Health & Metrics
|
||||
└── main.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🗓️ **แผนการพัฒนาแบบ Phase-Based**
|
||||
|
||||
### **Phase 1: Core Foundation & Master Data (Week 1-2)**
|
||||
|
||||
**Goal:** เตรียมโครงสร้างพื้นฐานและข้อมูลหลักให้พร้อมสำหรับโมดูลอื่น
|
||||
|
||||
#### **[ ] T1.1 Master Data Module (Enhanced)**
|
||||
- **Objective:** จัดการข้อมูลหลักทั้งหมดรวมถึงตารางใหม่ใน v1.5.1
|
||||
- **Tasks:**
|
||||
- [ ] Implement `OrganizationService` (CRUD)
|
||||
- [ ] Implement `ProjectService` & `ContractService`
|
||||
- [ ] Implement `TypeService` (Correspondence, RFA, Drawing)
|
||||
- [ ] **[NEW]** Implement `DisciplineService` (CRUD for `disciplines` table)
|
||||
- [ ] **[NEW]** Implement `CorrespondenceSubTypeService`
|
||||
- [ ] **[NEW]** Implement `CodeService` (RFA Approve Codes, Status Codes)
|
||||
- **Deliverables:** API สำหรับจัดการ Master Data ทั้งหมด
|
||||
|
||||
#### **[ ] T1.2 User & Auth Module**
|
||||
- **Objective:** ระบบผู้ใช้งานและสิทธิ์ (RBAC)
|
||||
- **Tasks:**
|
||||
- [ ] Implement `AuthService` (Login, Refresh Token)
|
||||
- [ ] Implement `UserService` & `UserPreferenceService`
|
||||
- [ ] Implement RBAC Guards (Global, Org, Project, Contract scopes)
|
||||
- **Deliverables:** Secure Authentication & Authorization
|
||||
|
||||
---
|
||||
|
||||
### **Phase 2: Document Numbering & File Storage (Week 3)**
|
||||
|
||||
**Goal:** ระบบเลขที่เอกสารที่ถูกต้องแม่นยำและระบบไฟล์ที่ปลอดภัย
|
||||
|
||||
#### **[ ] T2.1 Document Numbering Module (Major Update)**
|
||||
- **Objective:** ระบบสร้างเลขที่เอกสารแบบ 8-component key พร้อม Double-Lock
|
||||
- **Tasks:**
|
||||
- [ ] Update `DocumentNumberCounter` entity (8-column PK)
|
||||
- [ ] Implement `DocumentNumberingService` with **Redlock**
|
||||
- [ ] Implement **DB Optimistic Lock** fallback strategy
|
||||
- [ ] Implement Token Parser (`{DISCIPLINE}`, `{SUB_TYPE}`, `{RFA_TYPE}`)
|
||||
- [ ] Create `DocumentNumberAudit` & `DocumentNumberError` tables
|
||||
- **Deliverables:** Race-condition free numbering system
|
||||
|
||||
#### **[ ] T2.2 File Storage Service**
|
||||
- **Objective:** Two-Phase Storage Strategy
|
||||
- **Tasks:**
|
||||
- [ ] Implement `Upload` (Phase 1: Temp storage)
|
||||
- [ ] Implement `Commit` (Phase 2: Move to permanent)
|
||||
- [ ] Integrate **ClamAV** for virus scanning
|
||||
- [ ] Implement Cleanup Job for orphan files
|
||||
- **Deliverables:** Secure file upload system
|
||||
|
||||
---
|
||||
|
||||
### **Phase 3: Unified Workflow Engine (Week 4-5)**
|
||||
|
||||
**Goal:** ระบบ Workflow กลางที่ยืดหยุ่นและ Configurable
|
||||
|
||||
#### **[ ] T3.1 Workflow Engine Core**
|
||||
- **Objective:** สร้าง Engine สำหรับรัน Workflow ตาม DSL
|
||||
- **Tasks:**
|
||||
- [ ] Design DSL Schema (JSON)
|
||||
- [ ] Implement `DslParserService` & Validator
|
||||
- [ ] Implement `WorkflowEngineService` (State Machine)
|
||||
- [ ] Implement `GuardExecutor` (Permission/Condition checks)
|
||||
- [ ] Implement `EffectExecutor` (Actions after transition)
|
||||
- **Deliverables:** Functional Workflow Engine
|
||||
|
||||
#### **[ ] T3.2 Workflow Integration**
|
||||
- **Objective:** เชื่อมต่อ Engine เข้ากับ Business Modules
|
||||
- **Tasks:**
|
||||
- [ ] Create Standard Workflow Definitions (Correspondence, RFA)
|
||||
- [ ] Implement `WorkflowInstance` creation logic
|
||||
- [ ] Create API for Workflow Actions (Approve, Reject, Comment)
|
||||
- **Deliverables:** Integrated Workflow System
|
||||
|
||||
---
|
||||
|
||||
### **Phase 4: Business Logic Modules (Week 6-7)**
|
||||
|
||||
**Goal:** ฟังก์ชันการทำงานหลักของระบบเอกสาร
|
||||
|
||||
#### **[ ] T4.1 Correspondence Module**
|
||||
- **Objective:** จัดการหนังสือโต้ตอบ
|
||||
- **Tasks:**
|
||||
- [ ] Update Entity to support `discipline_id`
|
||||
- [ ] Integrate with **Document Numbering**
|
||||
- [ ] Integrate with **Workflow Engine**
|
||||
- [ ] Implement CRUD & Revision handling
|
||||
|
||||
#### **[ ] T4.2 RFA Module**
|
||||
- **Objective:** จัดการเอกสารขออนุมัติ
|
||||
- **Tasks:**
|
||||
- [ ] Update Entity to support `discipline_id`
|
||||
- [ ] Implement RFA-specific workflow logic
|
||||
- [ ] Implement RFA Item linking (Drawings)
|
||||
|
||||
#### **[ ] T4.3 Drawing Module**
|
||||
- **Objective:** จัดการแบบก่อสร้าง (Shop Drawing, Contract Drawing)
|
||||
- **Tasks:**
|
||||
- [ ] Implement `ShopDrawingService` & `ContractDrawingService`
|
||||
- [ ] Implement Revision Control for Drawings
|
||||
- [ ] Implement Drawing Numbering Logic
|
||||
|
||||
#### **[ ] T4.4 Transmittal Module**
|
||||
- **Objective:** จัดการใบนำส่งเอกสาร (Transmittal)
|
||||
- **Tasks:**
|
||||
- [ ] Implement `TransmittalService` (Create, View, PDF)
|
||||
- [ ] Implement `TransmittalItem` linking (Correspondence, RFA, Drawing)
|
||||
- [ ] Implement Transmittal Numbering (Type 901)
|
||||
- [ ] Generate PDF Transmittal Letter
|
||||
|
||||
#### **[ ] T4.5 Circulation Module**
|
||||
- **Objective:** จัดการใบเวียนภายใน (Circulation Sheet)
|
||||
- **Tasks:**
|
||||
- [ ] Implement `CirculationService` (Create, Assign, Complete)
|
||||
- [ ] Implement `CirculationAssignee` tracking (Multiple users)
|
||||
- [ ] Implement Circulation Numbering (Type 900)
|
||||
- [ ] Integrate with Workflow for completion tracking
|
||||
|
||||
---
|
||||
|
||||
### **Phase 5: System, Search & Monitoring (Week 8)**
|
||||
|
||||
**Goal:** ระบบสนับสนุนและการตรวจสอบ
|
||||
|
||||
#### **[ ] T5.1 JSON Schema & Preferences**
|
||||
- **Objective:** จัดการ Dynamic Data และ User Settings
|
||||
- **Tasks:**
|
||||
- [ ] Implement `JsonSchemaService` (Registry & Validation)
|
||||
- [ ] Implement `UserPreferenceService`
|
||||
- [ ] Implement Virtual Column management
|
||||
|
||||
#### **[ ] T5.2 Search & Logs**
|
||||
- **Objective:** การค้นหาและตรวจสอบ
|
||||
- **Tasks:**
|
||||
- [ ] Implement **Elasticsearch** Sync
|
||||
- [ ] Implement **Audit Log** with Partitioning
|
||||
- [ ] Setup **Prometheus/Grafana** metrics
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ **Security & Performance Guidelines**
|
||||
|
||||
1. **Double-Locking:** ใช้ Redis Lock คู่กับ DB Optimistic Lock เสมอสำหรับ Critical Sections
|
||||
2. **Input Validation:** ใช้ Zod/DTO Validation ทุกจุด โดยเฉพาะ JSON Fields
|
||||
3. **Rate Limiting:** บังคับใช้ Rate Limit ตาม User Role
|
||||
4. **Audit Logging:** บันทึกทุกการกระทำที่สำคัญลง `audit_logs`
|
||||
5. **Partitioning:** ใช้ Partitioning สำหรับตารางขนาดใหญ่ (`audit_logs`, `notifications`)
|
||||
|
||||
---
|
||||
|
||||
**End of Backend Plan V1.5.1**
|
||||
978
specs/99-archives/docs/backup/3_Frontend_Plan_V1_4_5.md
Normal file
978
specs/99-archives/docs/backup/3_Frontend_Plan_V1_4_5.md
Normal file
@@ -0,0 +1,978 @@
|
||||
# 📋 **แผนการพัฒนา Frontend (Next.js) - LCBP3-DMS v1.4.5**
|
||||
|
||||
**สถานะ:** FINAL GUIDELINE Rev.05
|
||||
**วันที่:** 2025-11-29
|
||||
**อ้างอิง:** Requirements v1.4.5 & FullStackJS Guidelines v1.4.5
|
||||
**Classification:** Internal Technical Documentation
|
||||
|
||||
## 🎯 **ภาพรวมโครงการ**
|
||||
|
||||
พัฒนา Frontend สำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System) ที่มีความทันสมัย รองรับการทำงานบนอุปกรณ์ต่างๆ ได้อย่างสมบูรณ์ มีประสบการณ์ผู้ใช้ที่ราบรื่น และรองรับการทำงานแบบ Offline เบื้องต้น
|
||||
|
||||
---
|
||||
|
||||
## 📐 **สถาปัตยกรรมระบบ**
|
||||
|
||||
### **Technology Stack**
|
||||
|
||||
- **Framework:** Next.js 14+ (App Router, React 18, TypeScript, ESM)
|
||||
- **Styling:** Tailwind CSS + PostCSS
|
||||
- **UI Components:** shadcn/ui + Radix UI Primitives
|
||||
- **State Management:**
|
||||
- **Server State:** TanStack Query (React Query)
|
||||
- **Client State:** Zustand
|
||||
- **Form State:** React Hook Form + Zod
|
||||
- **API Client:** Axios (พร้อม Idempotency Interceptor)
|
||||
- **Authentication:** NextAuth.js (รองรับ JWT)
|
||||
- **File Upload:** Custom Hook + Drag & Drop
|
||||
- **Testing:**
|
||||
- **Unit/Integration:** Vitest + React Testing Library
|
||||
- **E2E:** Playwright
|
||||
- **Mocking:** MSW (Mock Service Worker)
|
||||
- **Development:**
|
||||
- **Package Manager:** pnpm
|
||||
- **Linting:** ESLint + Prettier
|
||||
- **Type Checking:** TypeScript Strict Mode
|
||||
|
||||
### **โครงสร้างโปรเจกต์**
|
||||
|
||||
```
|
||||
📁frontend
|
||||
├── .env.local
|
||||
├── .eslintrc.json
|
||||
├── .gitignore
|
||||
├── components.json
|
||||
├── middleware.ts
|
||||
├── next-env.d.ts
|
||||
├── next.config.mjs
|
||||
├── package.json
|
||||
├── pnpm-lock.yaml
|
||||
├── postcss.config.mjs
|
||||
├── README.md
|
||||
├── tailwind.config.ts
|
||||
├── tsconfig.json
|
||||
├── 📁app
|
||||
│ ├── 📁(auth)
|
||||
│ │ └── 📁login
|
||||
│ │ │ └── page.tsx
|
||||
│ │ └── layout.tsx
|
||||
│ ├── 📁(dashboard)
|
||||
│ │ └── 📁admin
|
||||
│ │ ├──📁users
|
||||
│ │ │ └── page.tsx
|
||||
│ │ ├──📁correspondences
|
||||
│ │ │ └── 📁new
|
||||
│ │ │ │ └── page.tsx
|
||||
│ │ │ └── page.tsx
|
||||
│ │ ├──📁dashboard
|
||||
│ │ │ └── page.tsx
|
||||
│ │ ├──📁profile
|
||||
│ │ │ └── page.tsx
|
||||
│ │ ├──📁projects
|
||||
│ │ │ ├──📁new
|
||||
│ │ │ │ └── page.tsx
|
||||
│ │ │ └── page.tsx
|
||||
│ │ └── layout.tsx
|
||||
│ ├── 📁api
|
||||
│ │ └── 📁auth
|
||||
│ │ └── 📁[...nextauth]
|
||||
│ │ └── route.ts
|
||||
│ ├── 📁demo
|
||||
│ │ └── page.tsx
|
||||
│ ├── 📁fonts
|
||||
│ │ ├── GeistMonoVF.woff
|
||||
│ │ └── GeistVF.woff
|
||||
│ ├── favicon.ico
|
||||
│ ├── globals copy.css
|
||||
│ ├── globals.css
|
||||
│ ├── layout copy.tsx
|
||||
│ ├── layout.tsx
|
||||
│ └── page.tsx
|
||||
├── 📁components
|
||||
│ ├── 📁custom
|
||||
│ │ ├── file-upload-zone.tsx
|
||||
│ │ ├── responsive-data-table.tsx
|
||||
│ │ └── workflow-visualizer.tsx
|
||||
│ ├── 📁dashboard
|
||||
│ │ └── recent-activity.tsx
|
||||
│ ├── 📁forms
|
||||
│ │ └── file-upload.tsx
|
||||
│ ├── 📁layout
|
||||
│ │ ├── dashboard-shell.tsx
|
||||
│ │ ├── navbar.tsx
|
||||
│ │ ├── sidebar.tsx
|
||||
│ │ └── user-nav.tsx
|
||||
│ ├── 📁tables
|
||||
│ └── 📁ui
|
||||
│ ├── avatar.tsx
|
||||
│ ├── badge.tsx
|
||||
│ ├── button.tsx
|
||||
│ ├── calendar.tsx
|
||||
│ ├── card.tsx
|
||||
│ ├── checkbox.tsx
|
||||
│ ├── dropdown-menu.tsx
|
||||
│ ├── input.tsx
|
||||
│ ├── label.tsx
|
||||
│ ├── popover.tsx
|
||||
│ ├── progress.tsx
|
||||
│ ├── scroll-area.tsx
|
||||
│ ├── select.tsx
|
||||
│ ├── switch.tsx
|
||||
│ ├── table.tsx
|
||||
│ ├── tabs.tsx
|
||||
│ └── textarea.tsx
|
||||
├── 📁config
|
||||
│ └── menu.ts
|
||||
├── 📁lib
|
||||
│ ├── 📁api
|
||||
│ │ └── client.ts
|
||||
│ ├── 📁auth
|
||||
│ ├── 📁hooks
|
||||
│ ├── 📁services
|
||||
│ │ ├── circulation.service.ts
|
||||
│ │ ├── contract-drawing.service.ts
|
||||
│ │ ├── correspondence.service.ts
|
||||
│ │ ├── index.ts
|
||||
│ │ ├── json-schema.service.ts
|
||||
│ │ ├── master-data.service.ts
|
||||
│ │ ├── monitoring.service.ts
|
||||
│ │ ├── notification.service.ts
|
||||
│ │ ├── project.service.ts
|
||||
│ │ ├── rfa.service.ts
|
||||
│ │ ├── search.service.ts
|
||||
│ │ ├── shop-drawing.service.ts
|
||||
│ │ ├── transmittal.service.ts
|
||||
│ │ ├── user.service.ts
|
||||
│ │ └── workflow-engine.service.ts
|
||||
│ ├── 📁stores
|
||||
│ │ ├── draft-store.ts
|
||||
│ │ └── ui-store.ts
|
||||
│ ├── auth.ts
|
||||
│ └── utils.ts
|
||||
├── 📁providers
|
||||
│ ├── query-provider.tsx
|
||||
│ └── session-provider.tsx
|
||||
├── 📁public
|
||||
├── 📁styles
|
||||
└── 📁types
|
||||
└── 📁dto
|
||||
└── next-auth.d.ts
|
||||
├── 📁circulation
|
||||
│ ├── create-circulation.dto.ts
|
||||
│ ├── search-circulation.dto.ts
|
||||
│ └── update-circulation-routing.dto.ts
|
||||
├── 📁correspondence
|
||||
│ ├── add-reference.dto.ts
|
||||
│ ├── create-correspondence.dto.ts
|
||||
│ ├── search-correspondence.dto.ts
|
||||
│ ├── submit-correspondence.dto.ts
|
||||
│ └── workflow-action.dto.ts
|
||||
├── 📁drawing
|
||||
│ ├── contract-drawing.dto.ts
|
||||
│ └── shop-drawing.dto.ts
|
||||
├── 📁json-schema
|
||||
│ └── json-schema.dto.ts
|
||||
├── 📁master
|
||||
│ ├── discipline.dto.ts
|
||||
│ ├── number-format.dto.ts
|
||||
│ ├── sub-type.dto.ts
|
||||
│ └── tag.dto.ts
|
||||
├── 📁monitoring
|
||||
│ └── set-maintenance.dto.ts
|
||||
├── 📁notification
|
||||
│ └── notification.dto.ts
|
||||
├── 📁project
|
||||
│ └── project.dto.ts
|
||||
├── 📁rfa
|
||||
│ └── rfa.dto.ts
|
||||
├── 📁search
|
||||
│ └── search-query.dto.ts
|
||||
├── 📁transmittal
|
||||
│ └── transmittal.dto.ts
|
||||
├── 📁user
|
||||
│ └── user.dto.ts
|
||||
└── 📁workflow-engine
|
||||
└── workflow-engine.dto.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🗓️ **แผนการพัฒนาแบบ Phase-Based**
|
||||
|
||||
### **Phase 0: Foundation & Configuration (สัปดาห์ที่ 1)**
|
||||
|
||||
**Milestone:** โครงสร้างพื้นฐานพร้อม รองรับ Development Workflow ที่มีประสิทธิภาพ
|
||||
|
||||
### **Phase 0: Tasks**
|
||||
|
||||
- **[ ] F0.1 Project Setup & Tooling**
|
||||
|
||||
- [ ] Initialize Next.js 14+ project with TypeScript
|
||||
- [ ] Configure pnpm workspace
|
||||
- [ ] Setup ESLint, Prettier, and pre-commit hooks
|
||||
- [ ] Configure Tailwind CSS with PostCSS
|
||||
- [ ] Setup shadcn/ui components
|
||||
- [ ] Configure absolute imports and path aliases
|
||||
- [ ] **Deliverable:** Development environment ready
|
||||
- [ ] **Dependencies:** None
|
||||
|
||||
- **[ ] F0.2 Design System & UI Components**
|
||||
|
||||
- [ ] Setup color palette and design tokens
|
||||
- [ ] Create responsive design breakpoints
|
||||
- [ ] Implement core shadcn/ui components:
|
||||
- [ ] Button, Input, Label, Form
|
||||
- [ ] Card, Table, Badge
|
||||
- [ ] Dialog, Dropdown, Select
|
||||
- [ ] Tabs, Accordion
|
||||
- [ ] Create custom design system components:
|
||||
- [ ] DataTable (responsive)
|
||||
- [ ] FileUpload **zone**
|
||||
- [ ] Workflow visualization
|
||||
- [ ] **Deliverable:** Consistent UI component library
|
||||
- [ ] **Dependencies:** F0.1
|
||||
|
||||
- **[ ] F0.3 API Client & Authentication**
|
||||
|
||||
- [ ] Setup Axios client with interceptors:
|
||||
- [ ] Idempotency-Key header injection
|
||||
- [ ] Authentication token management
|
||||
- [ ] Error handling and retry logic
|
||||
- [ ] Configure NextAuth.js for JWT authentication
|
||||
- [ ] Create auth hooks (useAuth, usePermissions)
|
||||
- [ ] Setup API route handlers for auth callbacks
|
||||
- [ ] **Security:** Implement secure token storage
|
||||
- [ ] **Deliverable:** Secure API communication layer
|
||||
- [ ] **Dependencies:** F0.1
|
||||
|
||||
- **[ ] F0.4 State Management Setup**
|
||||
- [ ] Configure TanStack Query for server state:
|
||||
- [ ] Query client setup
|
||||
- [ ] Default configurations
|
||||
- [ ] Error boundaries
|
||||
- [ ] Create Zustand stores:
|
||||
- [ ] Auth store (user, permissions)
|
||||
- [ ] UI store (theme, sidebar state)
|
||||
- [ ] Draft store (form auto-save)
|
||||
- [ ] Setup React Hook Form with Zod integration
|
||||
- [ ] Create form validation schemas
|
||||
- [ ] **Deliverable:** Robust state management system
|
||||
- [ ] **Dependencies:** F0.1, F0.3
|
||||
|
||||
### **Phase 0: Testing - Foundation**
|
||||
|
||||
#### **F0.T1 Component Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Core UI components (Button, Input, Card)
|
||||
- [ ] **Integration Tests:** Form validation, API client interceptors
|
||||
- [ ] **Visual Tests:** Component styling and responsive behavior
|
||||
|
||||
#### **F0.T2 Authentication Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Auth hooks, token management
|
||||
- [ ] **Integration Tests:** Login/logout flow, permission checks
|
||||
- [ ] **Security Tests:** Token security, API authentication
|
||||
|
||||
---
|
||||
|
||||
### **Phase 1: Core Application Structure (สัปดาห์ที่ 2)**
|
||||
|
||||
**Milestone:** Layout หลักพร้อมใช้งาน การนำทางและ Authentication ทำงานได้
|
||||
|
||||
### **Phase 1: Tasks**
|
||||
|
||||
- **[ ] F1.1 Main Layout & Navigation**
|
||||
|
||||
- [ ] Create App Shell layout:
|
||||
- [ ] Navbar with user menu and notifications
|
||||
- [ ] Collapsible sidebar with navigation
|
||||
- [ ] Main content area with responsive design
|
||||
- [ ] Implement navigation menu structure:
|
||||
- [ ] Dashboard, Correspondences, RFAs, Drawings, etc.
|
||||
- [ ] Dynamic menu based on user permissions
|
||||
- [ ] Create breadcrumb navigation component
|
||||
- [ ] Implement mobile-responsive sidebar (drawer)
|
||||
- [ ] Maintenance Mode Integration:
|
||||
- [ ] Implement a Global Middleware/Wrapper ที่ตรวจสอบสถานะ Maintenance Mode ผ่าน API/Service ก่อนการ Render หน้า หากสถานะเป็น true ให้ Redirect ผู้ใช้ (ยกเว้น Admin) ไปยังหน้า /maintenance ทันที เพื่อให้สอดคล้องกับ Logic ของ Backend.
|
||||
- [ ] **Accessibility:** Ensure keyboard navigation and screen reader support
|
||||
- [ ] **Deliverable:** Fully functional application layout
|
||||
- [ ] **Dependencies:** F0.2, F0.3
|
||||
|
||||
- **[ ] F1.2 Authentication Pages**
|
||||
|
||||
- [ ] Create login page with form validation
|
||||
- [ ] Implement forgot password flow
|
||||
- [ ] Create registration page (admin-only)
|
||||
- [ ] Setup protected route middleware
|
||||
- [ ] Implement route-based permission checks
|
||||
- [ ] **Security:** Rate limiting on auth attempts, secure password requirements
|
||||
- [ ] **Deliverable:** Complete authentication flow
|
||||
- [ ] **Dependencies:** F0.3, F1.1
|
||||
|
||||
- **[ ] F1.3 Dashboard & Landing**
|
||||
|
||||
- [ ] Create public landing page for non-authenticated users
|
||||
- [ ] Implement main dashboard with:
|
||||
- [ ] KPI cards (document counts, pending tasks)
|
||||
- [ ] "My Tasks" table from v_user_tasks
|
||||
- [ ] Recent activity feed
|
||||
- [ ] Security metrics display
|
||||
- [ ] Create dashboard widgets system
|
||||
- [ ] Implement data fetching with TanStack Query
|
||||
- [ ] **Performance:** Optimize dashboard data loading
|
||||
- [ ] **Deliverable:** Functional dashboard with real data
|
||||
- [ ] **Dependencies:** F0.4, F1.1
|
||||
|
||||
- **[ ] F1.4 Responsive Design System**
|
||||
- [ ] Implement mobile-first responsive design
|
||||
- [ ] Create card view components for mobile tables
|
||||
- [ ] Setup touch-friendly interactions
|
||||
- [ ] Optimize images and assets for mobile
|
||||
- [ ] Test across multiple device sizes
|
||||
- [ ] **UX:** Ensure seamless mobile experience
|
||||
- [ ] **Deliverable:** Fully responsive application
|
||||
- [ ] **Dependencies:** F0.2, F1.1
|
||||
|
||||
### **Phase 1: Testing - Core Structure**
|
||||
|
||||
- **[ ] F1.T1 Layout Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Navigation components, layout responsiveness
|
||||
- [ ] **Integration Tests:** Route protection, permission-based navigation
|
||||
- [ ] **E2E Tests:** Complete user navigation flow
|
||||
|
||||
- **[ ] F1.T2 Dashboard Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Dashboard components, data formatting
|
||||
- [ ] **Integration Tests:** Data fetching and display, real-time updates
|
||||
- [ ] **Performance Tests:** Dashboard loading performance
|
||||
|
||||
---
|
||||
|
||||
### **Phase 2: User Management & Security (สัปดาห์ที่ 3)**
|
||||
|
||||
**Milestone:** การจัดการผู้ใช้และสิทธิ์แบบสมบูรณ์
|
||||
|
||||
### **Phase 2: Tasks**
|
||||
|
||||
- **[ ] F2.1 User Profile & Settings**
|
||||
|
||||
- [ ] Create user profile page:
|
||||
- [ ] Personal information display/edit
|
||||
- [ ] Password change functionality
|
||||
- [ ] Notification preferences
|
||||
- [ ] Implement profile picture upload
|
||||
- [ ] Create user settings page
|
||||
- [ ] **Security:** Secure password change with current password verification
|
||||
- [ ] **Deliverable:** Complete user self-service management
|
||||
- [ ] **Dependencies:** F1.1, F0.4
|
||||
|
||||
- **[ ] F2.2 Admin Panel - User Management**
|
||||
|
||||
- [ ] Create user list with search and filters
|
||||
- [ ] Implement user creation form
|
||||
- [ ] Create user edit interface
|
||||
- [ ] Implement bulk user operations
|
||||
- [ ] Add user activity tracking display
|
||||
- [ ] **Security:** Admin-only access enforcement
|
||||
- [ ] **Deliverable:** Comprehensive user management interface
|
||||
- [ ] **Dependencies:** F1.1, F2.1
|
||||
|
||||
- **[ ] F2.3 Admin Panel - Role Management**
|
||||
|
||||
- [ ] Create role list and management interface
|
||||
- [ ] Implement role creation and editing
|
||||
- [ ] Create permission assignment interface
|
||||
- [ ] Implement role-based access control visualization
|
||||
- [ ] Add role usage statistics
|
||||
- [ ] **Security:** Permission hierarchy enforcement
|
||||
- [ ] **Deliverable:** Complete RBAC management system
|
||||
- [ ] **Dependencies:** F2.2
|
||||
|
||||
- **[ ] F2.4 Permission Integration**
|
||||
- [ ] Implement CASL ability integration
|
||||
- [ ] Create permission-based UI components:
|
||||
- [ ] ProtectedButton, ProtectedLink
|
||||
- [ ] Conditional rendering based on permissions
|
||||
- [ ] Setup real-time permission updates
|
||||
- [ ] Implement permission debugging tools
|
||||
- [ ] **Security:** Frontend-backend permission consistency
|
||||
- [ ] **Deliverable:** Seamless permission enforcement throughout app
|
||||
- [ ] **Dependencies:** F0.3, F2.3
|
||||
|
||||
### **Phase 2: User Management & Admin Panel (สัปดาห์ที่ 3)**
|
||||
|
||||
- **[ ] F2.5 Admin Panel - Master Data Management (Req 6B)** (New)
|
||||
- [ ] Create "Disciplines Management" page (CRUD)
|
||||
- [ ] Create "Sub-Types Management" page (CRUD + Mapping Number)
|
||||
- [ ] Create "Numbering Format" configuration page (Template Editor)
|
||||
- [ ] **Deliverable:** UI for Admin to configure system master data
|
||||
- [ ] **Dependencies:** F2.1
|
||||
|
||||
### **Phase 2: Testing - User Management**
|
||||
|
||||
- **[ ] F2.T1 User Management Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** User CRUD operations, form validation
|
||||
- [ ] **Integration Tests:** User-role assignment, permission propagation
|
||||
- [ ] **Security Tests:** Permission escalation attempts, admin access control
|
||||
|
||||
- **[ ] F2.T2 RBAC Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Permission checks, role validation
|
||||
- [ ] **Integration Tests:** Multi-level permission enforcement, UI element protection
|
||||
- [ ] **E2E Tests:** Complete role-based workflow testing
|
||||
|
||||
---
|
||||
|
||||
### **Phase 3: Project Structure (สัปดาห์ที่ 4)**
|
||||
|
||||
**Milestone:** การจัดการโครงสร้างโปรเจกต์และองค์กร
|
||||
|
||||
### **Phase 3: Tasks**
|
||||
|
||||
- **[ ] F3.1 Project Management UI**
|
||||
|
||||
- [ ] Create project list with search and filters
|
||||
- [ ] Implement project creation and editing
|
||||
- [ ] Create project detail view
|
||||
- [ ] Implement project dashboard with statistics
|
||||
- [ ] Add project member management
|
||||
- [ ] **UX:** Intuitive project navigation and management
|
||||
- [ ] **Deliverable:** Complete project management interface
|
||||
- [ ] **Dependencies:** F1.1, F2.4
|
||||
|
||||
- **[ ] F3.2 Organization Management**
|
||||
|
||||
- [ ] Create organization list and management
|
||||
- [ ] Implement organization creation and editing
|
||||
- [ ] Create organization detail view
|
||||
- [ ] Add organization user management
|
||||
- [ ] Implement organization hierarchy visualization
|
||||
- [ ] **Business Logic:** Proper organization-project relationships
|
||||
- [ ] **Deliverable:** Comprehensive organization management
|
||||
- [ ] **Dependencies:** F3.1
|
||||
|
||||
- **[ ] F3.3 Contract Management**
|
||||
- [ ] Create contract list within projects
|
||||
- [ ] Implement contract creation and editing
|
||||
- [ ] Create contract detail view
|
||||
- [ ] Add contract party management
|
||||
- [ ] Implement contract document associations
|
||||
- [ ] **Business Logic:** Contract-project-organization relationships
|
||||
- [ ] **Deliverable:** Complete contract management system
|
||||
- [ ] **Dependencies:** F3.1, F3.2
|
||||
|
||||
### **Phase 3: Testing - Project Structure**
|
||||
|
||||
- **[ ] F3.T1 Project Management Test Suite**
|
||||
- [ ] **Unit Tests:** Project CRUD operations, validation
|
||||
- [ ] **Integration Tests:** Project-organization relationships, member management
|
||||
- [ ] **Business Logic Tests:** Project hierarchy, access control
|
||||
|
||||
---
|
||||
|
||||
### **Phase 4: Correspondence System (สัปดาห์ที่ 5-6)**
|
||||
|
||||
**Milestone:** ระบบจัดการเอกสารโต้ตอบแบบสมบูรณ์
|
||||
|
||||
### **Phase 4: Tasks**
|
||||
|
||||
- **[ ] F4.1 Correspondence List & Search**
|
||||
|
||||
- [ ] Create correspondence list with advanced filtering:
|
||||
- [ ] Filter by type, status, project, organization
|
||||
- [ ] Search by title, document number, content
|
||||
- [ ] Date range filtering
|
||||
- [ ] Implement responsive data table:
|
||||
- [ ] Desktop: Full table view
|
||||
- [ ] Mobile: Card view conversion
|
||||
- [ ] Add bulk operations (export, status change)
|
||||
- [ ] Implement real-time updates
|
||||
- [ ] **Performance:** Virtual scrolling for large datasets
|
||||
- [ ] **Deliverable:** High-performance correspondence listing
|
||||
- [ ] **Dependencies:** F1.1, F3.1
|
||||
|
||||
- **[ ] F4.2 Correspondence Creation Form**
|
||||
|
||||
- [ ] Create dynamic form generator based on JSON schema
|
||||
- [ ] Implement form with multiple sections:
|
||||
- [ ] Basic information (type, title, recipients)
|
||||
- [ ] Content and details (JSON schema-based)
|
||||
- [ ] File attachments
|
||||
- [ ] Routing template selection
|
||||
- [ ] [New] Implement "Originator Selector" component: Dropdown สำหรับเลือกองค์กรผู้ส่ง (แสดงเฉพาะเมื่อผู้ใช้มีสิทธิ์ system.manage_all หรือสิทธิ์พิเศษ) หากไม่เลือกให้ใช้ Organization ของผู้ใช้ตามปกติ
|
||||
- [ ] **[New] Discipline Selector:** Add Dropdown for Disciplines (Dependent on Contract/Project)
|
||||
- [ ] **[New] Sub-Type Selector:** Add Dropdown for Sub-types (Dependent on Type)
|
||||
- [ ] Logic: Show/Hide selectors based on Document Type configuration
|
||||
- [ ] Add draft auto-save functionality
|
||||
- [ ] Implement form validation with Zod
|
||||
- [ ] **UX:** Intuitive form with progress indication
|
||||
- [ ] **Deliverable:** Flexible correspondence creation interface
|
||||
- [ ] **Dependencies:** F0.4, F4.1
|
||||
|
||||
- **[ ] F4.3 Correspondence Detail View**
|
||||
|
||||
- [ ] Create comprehensive detail page:
|
||||
- [ ] Document header with metadata
|
||||
- [ ] Content display based on type
|
||||
- [ ] Revision history
|
||||
- [ ] Related documents
|
||||
- [ ] Workflow status visualization
|
||||
- [ ] Implement document actions:
|
||||
- [ ] Edit, withdraw, cancel (with permissions)
|
||||
- [ ] Download, print
|
||||
- [ ] Create related documents
|
||||
- [ ] Add comments and activity timeline
|
||||
- [ ] **UX:** Clean, readable document presentation
|
||||
- [ ] **Deliverable:** Complete document detail experience
|
||||
- [ ] **Dependencies:** F4.1, F4.2
|
||||
|
||||
- **[ ] F4.4 File Upload Integration**
|
||||
- [ ] Create drag-and-drop file upload component
|
||||
- [ ] Implement file type validation and preview
|
||||
- [ ] Add virus scan status indication
|
||||
- [ ] Create file management interface:
|
||||
- [ ] Mark files as main/supporting documents
|
||||
- [ ] Reorder and manage attachments
|
||||
- [ ] File security status display
|
||||
- [ ] Implement two-phase upload progress
|
||||
- [ ] **Security:** File type restrictions, size limits, virus scan integration
|
||||
- [ ] **Deliverable:** Secure and user-friendly file management
|
||||
- [ ] **Dependencies:** F0.2, F4.2
|
||||
|
||||
### **Phase 4: Testing - Correspondence System**
|
||||
|
||||
- **[ ] F4.T1 Correspondence Test Suite**
|
||||
|
||||
- [ ] **Unit Tests:** Form validation, file upload components
|
||||
- [ ] **Integration Tests:** Complete document lifecycle, file attachment flow
|
||||
- [ ] **E2E Tests:** End-to-end correspondence creation and management
|
||||
|
||||
- **[ ] F4.T2 File Upload Test Suite**
|
||||
- [ ] **Unit Tests:** File validation, type checking
|
||||
- [ ] **Integration Tests:** Two-phase upload process, virus scan integration
|
||||
- [ ] **Security Tests:** Malicious file upload attempts, security feedback
|
||||
|
||||
---
|
||||
|
||||
### **Phase 5: Workflow Management (สัปดาห์ที่ 7)**
|
||||
|
||||
**Milestone:** ระบบ Visualization และจัดการ Workflow
|
||||
|
||||
### **Phase 5: Tasks**
|
||||
|
||||
- **[ ] F5.1 Workflow Visualization Component**
|
||||
|
||||
- [ ] Create horizontal workflow progress visualization
|
||||
- [ ] Implement step status indicators (pending, active, completed, skipped)
|
||||
- [ ] Add due date and assignee information
|
||||
- [ ] Create interactive workflow diagram
|
||||
- [ ] Implement workflow history timeline
|
||||
- [ ] **UX:** Clear visual representation of complex workflows
|
||||
- [ ] **Deliverable:** Intuitive workflow visualization
|
||||
- [ ] **Dependencies:** F4.3
|
||||
|
||||
- **[ ] F5.2 Routing Template Management**
|
||||
|
||||
- [ ] Create routing template list and editor
|
||||
- [ ] Implement drag-and-drop step configuration
|
||||
- [ ] Add step configuration (purpose, duration, assignee rules)
|
||||
- [ ] Create template preview functionality
|
||||
- [ ] Implement template versioning
|
||||
- [ ] **Business Logic:** Proper step sequencing and validation
|
||||
- [ ] **Deliverable:** Comprehensive routing template management
|
||||
- [ ] **Dependencies:** F3.1, F4.2
|
||||
|
||||
- **[ ] F5.3 Workflow Step Actions**
|
||||
|
||||
- [ ] Create step action interface:
|
||||
- [ ] Approve, reject, request changes
|
||||
- [ ] Add comments and attachments
|
||||
- [ ] Forward to other users
|
||||
- [ ] Implement bulk step actions
|
||||
- [ ] Add action confirmation with reason required
|
||||
- [ ] Create step delegation functionality
|
||||
- [ ] **UX:** Streamlined step completion process
|
||||
- [ ] **Deliverable:** Efficient workflow step management
|
||||
- [ ] **Dependencies:** F5.1
|
||||
|
||||
- **[ ] F5.4 Real-time Status Updates**
|
||||
- [ ] Implement WebSocket connections for real-time updates
|
||||
- [ ] Create status change notifications
|
||||
- [ ] Add auto-refresh for workflow states
|
||||
- [ ] Implement optimistic updates for better UX
|
||||
- [ ] Create update history and audit trail
|
||||
- [ ] **Performance:** Efficient real-time data synchronization
|
||||
- [ ] **Deliverable:** Real-time workflow monitoring
|
||||
- [ ] **Dependencies:** F5.1, F9.2
|
||||
|
||||
### **Phase 5: Testing - Workflow Management**
|
||||
|
||||
- **[ ] F5.T1 Workflow Test Suite**
|
||||
- [ ] **Unit Tests:** Workflow visualization, step status logic
|
||||
- [ ] **Integration Tests:** Complete workflow execution, real-time updates
|
||||
- [ ] **E2E Tests:** Multi-step workflow with different user roles
|
||||
|
||||
---
|
||||
|
||||
### **Phase 6: Drawing System (สัปดาห์ที่ 8)**
|
||||
|
||||
**Milestone:** ระบบจัดการแบบแปลนแบบสมบูรณ์
|
||||
|
||||
### **Phase 6: Tasks**
|
||||
|
||||
- **[ ] F6.1 Contract Drawings Management**
|
||||
|
||||
- [ ] Create contract drawing list with categorization
|
||||
- [ ] Implement drawing upload and metadata management
|
||||
- [ ] Create drawing preview and viewer
|
||||
- [ ] Add drawing version control
|
||||
- [ ] Implement drawing search and filtering
|
||||
- [ ] **UX:** Efficient drawing navigation and access
|
||||
- [ ] **Deliverable:** Comprehensive contract drawing management
|
||||
- [ ] **Dependencies:** F3.1, F4.4
|
||||
|
||||
- **[ ] F6.2 Shop Drawings Management**
|
||||
|
||||
- [ ] Create shop drawing list with revision tracking
|
||||
- [ ] Implement shop drawing creation and revision system
|
||||
- [ ] Create drawing comparison interface
|
||||
- [ ] Add drawing approval status tracking
|
||||
- [ ] Implement bulk drawing operations
|
||||
- [ ] **Business Logic:** Proper revision control and approval workflows
|
||||
- [ ] **Deliverable:** Complete shop drawing management system
|
||||
- [ ] **Dependencies:** F6.1
|
||||
|
||||
- **[ ] F6.3 Drawing Revision System**
|
||||
|
||||
- [ ] Create revision history interface
|
||||
- [ ] Implement revision comparison functionality
|
||||
- [ ] Add revision notes and change tracking
|
||||
- [ ] Create revision approval workflow
|
||||
- [ ] Implement revision rollback capability
|
||||
- [ ] **UX:** Clear visualization of changes between revisions
|
||||
- [ ] **Deliverable:** Robust drawing revision control
|
||||
- [ ] **Dependencies:** F6.2
|
||||
|
||||
- **[ ] F6.4 Drawing References**
|
||||
- [ ] Create drawing reference management
|
||||
- [ ] Implement cross-drawing references
|
||||
- [ ] Add reference validation and integrity checks
|
||||
- [ ] Create reference visualization
|
||||
- [ ] Implement reference impact analysis
|
||||
- [ ] **Business Logic:** Maintain reference integrity during changes
|
||||
- [ ] **Deliverable:** Comprehensive drawing reference system
|
||||
- [ ] **Dependencies:** F6.2, F6.3
|
||||
|
||||
### **Phase 6: Testing - Drawing System**
|
||||
|
||||
- **[ ] F6.T1 Drawing Management Test Suite**
|
||||
- [ ] **Unit Tests:** Drawing CRUD operations, revision logic
|
||||
- [ ] **Integration Tests:** Drawing approval workflows, reference management
|
||||
- [ ] **E2E Tests:** Complete drawing lifecycle with revisions
|
||||
|
||||
---
|
||||
|
||||
### **Phase 7: RFA System (สัปดาห์ที่ 9-10)**
|
||||
|
||||
**Milestone:** ระบบขออนุมัติแบบสมบูรณ์พร้อม Dynamic Forms
|
||||
|
||||
### **Phase 7: Tasks**
|
||||
|
||||
- **[ ] F7.1 RFA List & Dashboard**
|
||||
|
||||
- [ ] Create RFA dashboard with status overview
|
||||
- [ ] Implement advanced RFA filtering and search
|
||||
- [ ] Create RFA calendar view for deadlines
|
||||
- [ ] Add RFA statistics and reporting
|
||||
- [ ] Implement RFA bulk operations
|
||||
- [ ] **UX:** Comprehensive RFA overview and management
|
||||
- [ ] **Deliverable:** Complete RFA dashboard and listing
|
||||
- [ ] **Dependencies:** F4.1, F5.1
|
||||
|
||||
- **[ ] F7.2 RFA Creation with Dynamic Forms**
|
||||
|
||||
- [ ] Create RFA type-specific form generator
|
||||
- [ ] Implement dynamic form fields based on RFA type:
|
||||
- [ ] RFA_DWG: Shop drawing selection
|
||||
- [ ] RFA_DOC: Document specifications
|
||||
- [ ] RFA_MES: Method statement details
|
||||
- [ ] RFA_MAT: Material specifications
|
||||
- [ ] Add form validation with JSON schema
|
||||
- [ ] Implement form data persistence and recovery
|
||||
- [ ] **UX:** Intuitive form experience for complex RFA types
|
||||
- [ ] Dynamic Form & Schema Validation: สร้าง Component Dynamic Form Generator ที่:
|
||||
- [ ] Fetch Schema: ดึงโครงสร้าง JSON Schema ที่ถูกต้องตาม rfa_type จาก Backend (ตาราง json_schemas ที่สร้างใหม่) ก่อนการ Render Form.
|
||||
- [ ] Client-side Validation: Implement AJV (Another JSON Schema Validator) หรือไลบรารีที่เทียบเท่า เพื่อทำ Client-side Validation บนข้อมูล JSON ก่อนส่ง Submit.
|
||||
- [ ] Implement dynamic form fields based on RFA type: RFA_DWG, RFA_DOC, RFA_MES, RFA_MAT.
|
||||
- [ ] Add form data persistence and recovery.
|
||||
- [ ] **[New] Discipline & Sub-Type Integration:** Ensure RFA forms capture these fields correctly for numbering generation.
|
||||
- [ ] **Deliverable:** Flexible RFA creation system
|
||||
- [ ] **Dependencies:** F4.2, F6.2
|
||||
|
||||
- **[ ] F7.3 RFA Workflow Integration**
|
||||
|
||||
- [ ] Integrate RFA with unified workflow engine
|
||||
- [ ] Create RFA-specific workflow steps and actions
|
||||
- [ ] Implement RFA approval interface
|
||||
- [ ] Add RFA workflow history and tracking
|
||||
- [ ] Create RFA workflow templates
|
||||
- [ ] **Business Logic:** Proper RFA approval sequencing and validation
|
||||
- [ ] **Deliverable:** Seamless RFA workflow integration
|
||||
- [ ] **Dependencies:** F5.1, F7.2
|
||||
|
||||
- **[ ] F7.4 RFA Approval Interface**
|
||||
- [ ] Create RFA review and approval interface
|
||||
- [ ] Implement side-by-side document comparison
|
||||
- [ ] Add approval comments and attachments
|
||||
- [ ] Create conditional approval workflows
|
||||
- [ ] Implement approval delegation and escalation
|
||||
- [ ] **UX:** Efficient approval process for technical reviews
|
||||
- [ ] **Deliverable:** Comprehensive RFA approval system
|
||||
- [ ] **Dependencies:** F7.1, F7.3
|
||||
|
||||
### **Phase 7: Testing - RFA System**
|
||||
|
||||
- **[ ] F7.T1 RFA Test Suite**
|
||||
- [ ] **Unit Tests:** RFA form generation, validation logic
|
||||
- [ ] **Integration Tests:** Complete RFA lifecycle, workflow integration
|
||||
- [ ] **E2E Tests:** Multi-type RFA creation and approval workflows
|
||||
|
||||
---
|
||||
|
||||
### **Phase 8: Internal Workflows (สัปดาห์ที่ 11)**
|
||||
|
||||
**Milestone:** ระบบใบเวียนและการจัดการงานภายใน
|
||||
|
||||
### **Phase 8: Tasks**
|
||||
|
||||
- **[ ] F8.1 Circulation Management**
|
||||
|
||||
- [ ] Create circulation list and management interface
|
||||
- [ ] Implement circulation creation from correspondence
|
||||
- [ ] Create circulation template management
|
||||
- [ ] Add circulation status tracking
|
||||
- [ ] Implement circulation search and filtering
|
||||
- [ ] **Business Logic:** Proper circulation-correspondence relationships
|
||||
- [ ] **Deliverable:** Comprehensive circulation management
|
||||
- [ ] **Dependencies:** F4.1, F5.2
|
||||
|
||||
- **[ ] F8.2 Task Assignment Interface**
|
||||
|
||||
- [ ] Create task assignment interface with user selection
|
||||
- [ ] Implement task priority and deadline setting
|
||||
- [ ] Add task dependency management
|
||||
- [ ] Create task progress tracking
|
||||
- [ ] Implement task reassignment and delegation
|
||||
- [ ] **UX:** Intuitive task management and assignment
|
||||
- [ ] **Deliverable:** Efficient task assignment system
|
||||
- [ ] **Dependencies:** F8.1
|
||||
|
||||
- **[ ] F8.3 Internal Approval Flows**
|
||||
- [ ] Create internal approval workflow interface
|
||||
- [ ] Implement multi-level approval processes
|
||||
- [ ] Add approval chain visualization
|
||||
- [ ] Create approval delegation system
|
||||
- [ ] Implement approval deadline management
|
||||
- [ ] **Business Logic:** Proper approval hierarchy and escalation
|
||||
- [ ] **Deliverable:** Robust internal approval system
|
||||
- [ ] **Dependencies:** F8.1, F8.2
|
||||
|
||||
### **Phase 8: Testing - Internal Workflows**
|
||||
|
||||
- **[ ] F8.T1 Circulation Test Suite**
|
||||
- [ ] **Unit Tests:** Circulation creation, task assignment logic
|
||||
- [ ] **Integration Tests:** Complete circulation workflow, internal approvals
|
||||
- [ ] **E2E Tests:** End-to-end circulation with task completion
|
||||
|
||||
---
|
||||
|
||||
### **Phase 9: Advanced Features (สัปดาห์ที่ 12)**
|
||||
|
||||
**Milestone:** ฟีเจอร์ขั้นสูงและการปรับปรุงประสบการณ์ผู้ใช้
|
||||
|
||||
### **Phase 9: Tasks**
|
||||
|
||||
- **[ ] F9.1 Advanced Search Interface**
|
||||
|
||||
- [ ] Create unified search interface across all document types
|
||||
- [ ] Implement faceted search with multiple filters
|
||||
- [ ] Add search result highlighting and relevance scoring
|
||||
- [ ] Create saved search and search templates
|
||||
- [ ] Implement search result export functionality
|
||||
- [ ] **Performance:** Efficient search with large datasets
|
||||
- [ ] **Deliverable:** Powerful cross-document search system
|
||||
- [ ] **Dependencies:** F4.1, F7.1
|
||||
|
||||
- **[ ] F9.2 Notification System**
|
||||
|
||||
- [ ] Create notification center with real-time updates
|
||||
- [ ] Implement notification preferences management
|
||||
- [ ] Add notification grouping and digest views
|
||||
- [ ] Create actionable notifications with quick actions
|
||||
- [ ] Implement notification read/unread status
|
||||
- [ ] **UX:** Non-intrusive but effective notification delivery
|
||||
- [ ] **Deliverable:** Comprehensive notification management
|
||||
- [ ] **Dependencies:** F1.3, F5.4
|
||||
|
||||
- **[ ] F9.3 Reporting & Analytics**
|
||||
|
||||
- [ ] Create reporting dashboard with customizable widgets
|
||||
- [ ] Implement data visualization components (charts, graphs)
|
||||
- [ ] Add report scheduling and export
|
||||
- [ ] Create ad-hoc reporting interface
|
||||
- [ ] Implement performance metrics tracking
|
||||
- [ ] **Business Logic:** Accurate data aggregation and reporting
|
||||
- [ ] **Deliverable:** Powerful reporting and analytics system
|
||||
- [ ] **Dependencies:** F1.3, F7.1
|
||||
|
||||
- **[ ] F9.4 Mobile Optimization**
|
||||
- [ ] Implement touch-optimized interactions
|
||||
- [ ] Create mobile-specific navigation patterns
|
||||
- [ ] Add offline capability for critical functions
|
||||
- [ ] Optimize images and assets for mobile networks
|
||||
- [ ] Implement mobile-specific performance optimizations
|
||||
- [ ] **UX:** Seamless mobile experience comparable to desktop
|
||||
- [ ] **Deliverable:** Fully optimized mobile application
|
||||
- [ ] **Dependencies:** F1.4
|
||||
|
||||
### **Phase 9: Testing - Advanced Features**
|
||||
|
||||
- **[ ] F9.T1 Advanced Features Test Suite**
|
||||
- [ ] **Unit Tests:** Search algorithms, notification logic
|
||||
- [ ] **Integration Tests:** Cross-module search, real-time notifications
|
||||
- [ ] **Performance Tests:** Search performance, mobile responsiveness
|
||||
|
||||
---
|
||||
|
||||
### **Phase 10: Testing & Polish (สัปดาห์ที่ 13-14)**
|
||||
|
||||
**Milestone:** แอปพลิเคชันที่ผ่านการทดสอบและปรับปรุงอย่างสมบูรณ์
|
||||
|
||||
### **Phase 10: Tasks**
|
||||
|
||||
- **[ ] F10.1 Comprehensive Testing**
|
||||
|
||||
- [ ] Idempotency Testing: เพิ่มการทดสอบเฉพาะสำหรับ Axios Interceptor เพื่อจำลองการส่ง Request POST/PUT/DELETE ที่มี Idempotency-Key ซ้ำไปยัง Mock API (MSW) เพื่อยืนยันว่า Client-side ไม่ส่ง Key ซ้ำในการทำงานปกติ และไม่เกิด Side Effect จากการ Replay Attack.
|
||||
- [ ] Write unit tests for all components and utilities
|
||||
- [ ] Create integration tests for critical user flows
|
||||
- [ ] Implement E2E tests for complete workflows
|
||||
- [ ] Perform cross-browser compatibility testing
|
||||
- [ ] Conduct accessibility testing (WCAG 2.1 AA)
|
||||
- [ ] **Quality:** 80%+ test coverage, all critical paths tested
|
||||
- [ ] **Deliverable:** Fully tested application
|
||||
- [ ] **Dependencies:** All previous phases
|
||||
|
||||
- **[ ] F10.2 Performance Optimization**
|
||||
|
||||
- [ ] Implement code splitting and lazy loading
|
||||
- [ ] Optimize bundle size and asset delivery
|
||||
- [ ] Add performance monitoring and metrics
|
||||
- [ ] Implement caching strategies for static assets
|
||||
- [ ] Optimize API call patterns and reduce over-fetching
|
||||
- [ ] **Performance:** Core Web Vitals targets met
|
||||
- [ ] **Deliverable:** High-performance application
|
||||
- [ ] **Dependencies:** F10.1
|
||||
|
||||
- **[ ] F10.3 Security Hardening**
|
||||
|
||||
- [ ] Conduct security audit and penetration testing
|
||||
- [ ] Implement Content Security Policy (CSP)
|
||||
- [ ] Add security headers and protections
|
||||
- [ ] Conduct dependency vulnerability scanning
|
||||
- [ ] Implement secure coding practices review
|
||||
- [ ] **Security:** No critical security vulnerabilities
|
||||
- [ ] **Deliverable:** Security-hardened application
|
||||
- [ ] **Dependencies:** F10.1
|
||||
|
||||
- **[ ] F10.4 Documentation**
|
||||
- [ ] Create user documentation and guides
|
||||
- [ ] Write technical documentation for developers
|
||||
- [ ] Create API integration documentation
|
||||
- [ ] Add inline code documentation
|
||||
- [ ] Create deployment and maintenance guides
|
||||
- [ ] **Quality:** Comprehensive and up-to-date documentation
|
||||
- [ ] **Deliverable:** Complete documentation suite
|
||||
- [ ] **Dependencies:** F10.1
|
||||
|
||||
### **Phase 10: Testing - Final Validation**
|
||||
|
||||
- **[ ] F10.T1 Final Test Suite**
|
||||
- [ ] **Performance Tests:** Load testing, stress testing
|
||||
- [ ] **Security Tests:** Final security audit, vulnerability assessment
|
||||
- [ ] **User Acceptance Tests:** Real user testing, feedback incorporation
|
||||
- [ ] **Compatibility Tests:** Cross-browser, cross-device testing
|
||||
|
||||
---
|
||||
|
||||
## 📊 **สรุป Timeline**
|
||||
|
||||
| Phase | ระยะเวลา | จำนวนงาน | Output หลัก |
|
||||
| -------- | -------------- | ------------ | ------------------------------------ |
|
||||
| Phase 0 | 1 สัปดาห์ | 4 | Foundation & Tooling Ready |
|
||||
| Phase 1 | 1 สัปดาห์ | 4 | Core Application Structure |
|
||||
| Phase 2 | 1 สัปดาห์ | 4 | User Management & Security |
|
||||
| Phase 3 | 1 สัปดาห์ | 3 | Project Structure Management |
|
||||
| Phase 4 | 2 สัปดาห์ | 4 | Correspondence System |
|
||||
| Phase 5 | 1 สัปดาห์ | 4 | Workflow Management |
|
||||
| Phase 6 | 1 สัปดาห์ | 4 | Drawing System |
|
||||
| Phase 7 | 2 สัปดาห์ | 4 | RFA System (Dynamic Forms) |
|
||||
| Phase 8 | 1 สัปดาห์ | 3 | Internal Workflows |
|
||||
| Phase 9 | 1 สัปดาห์ | 4 | Advanced Features |
|
||||
| Phase 10 | 2 สัปดาห์ | 4 | Testing & Polish (Idempotency Test) |
|
||||
| **รวม** | **14 สัปดาห์** | **39 Tasks** | **Production-Ready Frontend v1.4.2** |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **Critical Success Factors**
|
||||
|
||||
1. **User Experience First:** ทุกฟีเจอร์ต้องออกแบบเพื่อประสบการณ์ผู้ใช้ที่ดี
|
||||
2. **Responsive Design:** รองรับการใช้งานบนอุปกรณ์ทุกรูปแบบ
|
||||
3. **Performance:** Core Web Vitals ต้องอยู่ในเกณฑ์ที่ดี
|
||||
4. **Accessibility:** ต้องเป็นไปตามมาตรฐาน WCAG 2.1 AA
|
||||
5. **Security:** ป้องกัน XSS, CSRF และความเสี่ยงด้านความปลอดภัยอื่นๆ
|
||||
6. **Offline Support:** รองรับการทำงานแบบ Offline เบื้องต้น
|
||||
7. **Real-time Updates:** การอัปเดตสถานะแบบ Real-time
|
||||
8. **Testing Coverage:** ครอบคลุมการทดสอบทุก Critical Path
|
||||
9. **Documentation:** เอกสารครบถ้วนสำหรับผู้ใช้และนักพัฒนา
|
||||
|
||||
---
|
||||
|
||||
## 📋 **Quality Assurance Checklist**
|
||||
|
||||
### **ก่อน Production Deployment**
|
||||
|
||||
- [ ] **Performance:** Core Web Vitals ผ่านเกณฑ์
|
||||
- [ ] **Accessibility:** WCAG 2.1 AA compliant
|
||||
- [ ] **Security:** Security audit ผ่าน
|
||||
- [ ] **Testing:** Test coverage ≥ 80%
|
||||
- [ ] **Browser Compatibility:** ทำงานได้บนเบราว์เซอร์หลัก
|
||||
- [ ] **Mobile Responsive:** ใช้งานได้ดีบนมือถือ
|
||||
- [ ] **Documentation:** เอกสารครบถ้วน
|
||||
- [ ] **User Acceptance:** ได้รับการยอมรับจากผู้ใช้
|
||||
|
||||
---
|
||||
|
||||
## 🚀 **ขั้นตอนถัดไป**
|
||||
|
||||
1. **Approve แผนนี้** → ปรับแต่งตาม Feedback
|
||||
2. **Coordinate กับ Backend Team** → Sync API Specifications
|
||||
3. **เริ่มพัฒนา Phase 0** → Setup Foundation
|
||||
4. **Regular Sync** → ประสานงานกับ Backend ทุกสัปดาห์
|
||||
5. **User Testing** → ทดสอบกับผู้ใช้จริงระหว่างพัฒนา
|
||||
6. **Deploy to Production** → Week 15 (พร้อม Backend)
|
||||
|
||||
## **Document Control:**
|
||||
|
||||
- **Document:** Frontend Development Plan v1.4.5
|
||||
- **Version:** 1.4
|
||||
- **Date:** 2025-11-29
|
||||
- **Author:** NAP LCBP3-DMS & Gemini
|
||||
- **Status:** FINAL-Rev.05
|
||||
- **Classification:** Internal Technical Documentation
|
||||
- **Approved By:** Nattanin
|
||||
|
||||
---
|
||||
|
||||
`End of Frontend Development Plan v1.4.5`
|
||||
182
specs/99-archives/docs/backup/3_Frontend_Plan_V1_5_1.md
Normal file
182
specs/99-archives/docs/backup/3_Frontend_Plan_V1_5_1.md
Normal file
@@ -0,0 +1,182 @@
|
||||
# 📋 **แผนการพัฒนา Frontend (Next.js) - LCBP3-DMS v1.5.1**
|
||||
|
||||
**สถานะ:** DRAFT
|
||||
**วันที่:** 2025-12-04
|
||||
**อ้างอิง:** Requirements v1.5.1 & FullStackJS Guidelines v1.5.1
|
||||
**Classification:** Internal Technical Documentation
|
||||
|
||||
---
|
||||
|
||||
## 🎯 **ภาพรวมโครงการ (Project Overview)**
|
||||
|
||||
พัฒนา Frontend สำหรับระบบบริหารจัดการเอกสารโครงการ (Document Management System) เวอร์ชัน 1.5.1 โดยเน้นการรองรับฟีเจอร์ใหม่ใน Backend v1.5.1 ได้แก่ **Unified Workflow Engine**, **Advanced Document Numbering**, และ **Enhanced Master Data Management** พร้อมทั้งปรับปรุง UX/UI ให้ทันสมัยและใช้งานง่าย
|
||||
|
||||
---
|
||||
|
||||
## 📐 **สถาปัตยกรรมระบบ (System Architecture)**
|
||||
|
||||
### **Technology Stack**
|
||||
|
||||
- **Framework:** Next.js 14+ (App Router, React 18, TypeScript)
|
||||
- **Styling:** Tailwind CSS + Shadcn/UI
|
||||
- **State Management:**
|
||||
- **Server:** TanStack Query (React Query)
|
||||
- **Client:** Zustand
|
||||
- **Form:** React Hook Form + Zod
|
||||
- **Workflow Visualization:** ReactFlow (สำหรับ Workflow Builder)
|
||||
- **Editor:** Monaco Editor (สำหรับ DSL Editing)
|
||||
- **Validation:** Zod + AJV (JSON Schema)
|
||||
|
||||
### **โครงสร้างโมดูล (Module Structure)**
|
||||
|
||||
```
|
||||
📁src
|
||||
├── 📁app
|
||||
│ ├── 📁(auth) # Login, Forgot Password
|
||||
│ ├── 📁(dashboard) # Main App Layout
|
||||
│ │ ├── 📁admin # Admin Panel (Users, Master Data, Config)
|
||||
│ │ ├── 📁correspondences
|
||||
│ │ ├── 📁rfas
|
||||
│ │ ├── 📁drawings
|
||||
│ │ ├── 📁transmittals
|
||||
│ │ ├── 📁circulations
|
||||
│ │ └── 📁tasks
|
||||
│ └── 📁api # NextAuth & Proxy
|
||||
├── 📁components
|
||||
│ ├── 📁admin # Admin-specific components
|
||||
│ ├── 📁workflow # Workflow Builder & Visualizer
|
||||
│ ├── 📁numbering # Numbering Template Editor
|
||||
│ └── 📁ui # Shadcn UI Components
|
||||
└── 📁lib
|
||||
├── 📁api # API Clients
|
||||
└── 📁stores # Zustand Stores
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🗓️ **แผนการพัฒนาแบบ Phase-Based**
|
||||
|
||||
### **Phase 1: Foundation & UI Components (Week 1)**
|
||||
|
||||
**Goal:** เตรียมโครงสร้างโปรเจกต์และ Component พื้นฐาน
|
||||
|
||||
#### **[ ] F1.1 Project Setup & Design System**
|
||||
- **Tasks:**
|
||||
- [ ] Setup Next.js 14 + Tailwind + Shadcn/UI
|
||||
- [ ] Configure Axios with **Idempotency Interceptor**
|
||||
- [ ] Implement Base Layout (Sidebar, Navbar, Breadcrumbs)
|
||||
- [ ] Setup **TanStack Query** & **Zustand**
|
||||
|
||||
#### **[ ] F1.2 Authentication UI**
|
||||
- **Tasks:**
|
||||
- [ ] Login Page with Form Validation
|
||||
- [ ] Integrate NextAuth.js with Backend
|
||||
- [ ] Implement RBAC Guard (Protect Routes based on Permissions)
|
||||
|
||||
---
|
||||
|
||||
### **Phase 2: Admin & Master Data (Week 2-3)**
|
||||
|
||||
**Goal:** ระบบจัดการผู้ใช้และข้อมูลหลัก (รองรับ v1.5.1 Requirements)
|
||||
|
||||
#### **[ ] F2.1 User & Role Management**
|
||||
- **Tasks:**
|
||||
- [ ] User List & CRUD (Admin only)
|
||||
- [ ] Role Assignment UI
|
||||
- [ ] Permission Matrix Viewer
|
||||
|
||||
#### **[ ] F2.2 Enhanced Master Data UI**
|
||||
- **Tasks:**
|
||||
- [ ] **Organization Management:** CRUD + Logo Upload
|
||||
- [ ] **Project & Contract Management:** CRUD + Relations
|
||||
- [ ] **[NEW] Discipline Management:** CRUD for `disciplines`
|
||||
- [ ] **[NEW] Sub-Type Management:** CRUD for `correspondence_sub_types`
|
||||
|
||||
#### **[ ] F2.3 System Configuration**
|
||||
- **Tasks:**
|
||||
- [ ] **[NEW] Document Numbering Config:**
|
||||
- Template Editor (Monaco/Visual)
|
||||
- Sequence Viewer
|
||||
- [ ] **[NEW] Workflow Configuration:**
|
||||
- Workflow List
|
||||
- DSL Editor (Monaco)
|
||||
- Visual Builder (ReactFlow)
|
||||
|
||||
---
|
||||
|
||||
### **Phase 3: Core Modules (Week 4-5)**
|
||||
|
||||
**Goal:** โมดูลหลัก Correspondence และ RFA
|
||||
|
||||
#### **[ ] F3.1 Correspondence Module**
|
||||
- **Tasks:**
|
||||
- [ ] List View with Advanced Filters
|
||||
- [ ] **Create/Edit Form:**
|
||||
- Add **Discipline Selector** (Dynamic based on Contract)
|
||||
- Add **Sub-Type Selector** (Dynamic based on Type)
|
||||
- File Upload (Two-Phase)
|
||||
- [ ] Detail View with History & Comments
|
||||
|
||||
#### **[ ] F3.2 RFA Module**
|
||||
- **Tasks:**
|
||||
- [ ] RFA List & Dashboard
|
||||
- [ ] **Dynamic RFA Form:**
|
||||
- Fields change based on RFA Type (DWG, MAT, MES)
|
||||
- Item List Management
|
||||
- [ ] **Approval Interface:**
|
||||
- Approve/Reject/Comment Actions
|
||||
- Workflow Status Visualization
|
||||
|
||||
---
|
||||
|
||||
### **Phase 4: Advanced Modules (Week 6-7)**
|
||||
|
||||
**Goal:** โมดูล Drawing, Transmittal และ Circulation
|
||||
|
||||
#### **[ ] F4.1 Drawing Module**
|
||||
- **Tasks:**
|
||||
- [ ] Shop Drawing & Contract Drawing Lists
|
||||
- [ ] Revision Management UI
|
||||
- [ ] Drawing Viewer (PDF/Image)
|
||||
|
||||
#### **[ ] F4.2 Transmittal Module**
|
||||
- **Tasks:**
|
||||
- [ ] Transmittal Creation Form (Select Documents to send)
|
||||
- [ ] Transmittal Letter Preview (PDF Generation)
|
||||
- [ ] Transmittal History
|
||||
|
||||
#### **[ ] F4.3 Circulation Module**
|
||||
- **Tasks:**
|
||||
- [ ] Circulation Sheet Creation (Select Assignees)
|
||||
- [ ] "My Tasks" Dashboard for Circulation
|
||||
- [ ] Completion & Tracking UI
|
||||
|
||||
---
|
||||
|
||||
### **Phase 5: Search & Dashboard (Week 8)**
|
||||
|
||||
**Goal:** การค้นหาและหน้า Dashboard
|
||||
|
||||
#### **[ ] F5.1 Advanced Search**
|
||||
- **Tasks:**
|
||||
- [ ] Unified Search Interface (Elasticsearch)
|
||||
- [ ] Faceted Filters (Type, Date, Project, Status)
|
||||
|
||||
#### **[ ] F5.2 Dashboard & Monitoring**
|
||||
- **Tasks:**
|
||||
- [ ] Personal Dashboard (My Tasks, Pending Approvals)
|
||||
- [ ] Project Dashboard (KPIs, Stats)
|
||||
- [ ] **Admin Audit Logs Viewer**
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ **Security & Performance Guidelines**
|
||||
|
||||
1. **Client-Side Validation:** ใช้ Zod Validate Form ก่อนส่งเสมอ
|
||||
2. **Optimistic Updates:** ใช้ React Query `onMutate` เพื่อความลื่นไหล
|
||||
3. **Code Splitting:** ใช้ `React.lazy` และ `Next.js Dynamic Imports` สำหรับ Component ใหญ่ๆ (เช่น Monaco Editor, ReactFlow)
|
||||
4. **Secure Storage:** ห้ามเก็บ Token ใน LocalStorage (ใช้ HttpOnly Cookie ผ่าน NextAuth)
|
||||
|
||||
---
|
||||
|
||||
**End of Frontend Plan V1.5.1**
|
||||
2673
specs/99-archives/docs/backup/4_Data_Dictionary_V1_4_5.md
Normal file
2673
specs/99-archives/docs/backup/4_Data_Dictionary_V1_4_5.md
Normal file
File diff suppressed because it is too large
Load Diff
1866
specs/99-archives/docs/backup/4_Data_Dictionary_V1_5_1.md
Normal file
1866
specs/99-archives/docs/backup/4_Data_Dictionary_V1_5_1.md
Normal file
File diff suppressed because it is too large
Load Diff
777
specs/99-archives/docs/backup/DMS README.bak
Normal file
777
specs/99-archives/docs/backup/DMS README.bak
Normal file
@@ -0,0 +1,777 @@
|
||||
# 📝 0. Project Title: Document Management System (DMS) Web Application for Laem Chabang Port Development Project, Phase 3
|
||||
|
||||
## 0. Project
|
||||
|
||||
### 📌 0.1 Project Overview / Description
|
||||
|
||||
- ระบบ Document Management System (DMS) เป็นเว็บแอปพลิเคชันที่ออกแบบมาเพื่อจัดการเอกสารภายในโครงการอย่างมีประสิทธิภาพ
|
||||
- โดยมีฟังก์ชันหลักในการอัปโหลด จัดเก็บ ค้นหา แชร์ และควบคุมสิทธิ์การเข้าถึงเอกสาร
|
||||
- ระบบนี้จะช่วยลดการใช้เอกสารกระดาษ เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
|
||||
- เพิ่มความสะดวกในการทำงานร่วมกันระหว่างองกรณ์
|
||||
|
||||
### 🎯 0.2 Objectives
|
||||
|
||||
- พัฒนาระบบที่สามารถจัดการเอกสารได้อย่างเป็นระบบ
|
||||
- ลดความซ้ำซ้อนในการจัดเก็บเอกสาร
|
||||
- เพิ่มความปลอดภัยในการเข้าถึงและจัดการเอกสาร
|
||||
- รองรับการทำงานร่วมกันแบบออนไลน์
|
||||
|
||||
### 📦 0.3 Scope of Work
|
||||
|
||||
ระบบจะครอบคลุมฟีเจอร์หลักดังนี้:
|
||||
|
||||
- การลงทะเบียนและเข้าสู่ระบบ ของผู้ใช้งาน
|
||||
- การอัปโหลดและจัดเก็บเอกสารในรูปแบบต่าง ๆ (PDF, DOCX, XLSX ฯลฯ)
|
||||
- การจัดหมวดหมู่และแท็กเอกสาร
|
||||
- การค้นหาเอกสารด้วยคำสำคัญหรือฟิลเตอร์
|
||||
- การกำหนดสิทธิ์การเข้าถึงเอกสาร (เช่น อ่านอย่างเดียว, แก้ไข, ลบ)
|
||||
- การบันทึกประวัติการใช้งานเอกสาร (Audit Trail)
|
||||
- การมอบหมายงานให้กับผู้เกี่ยวข้อง และแจ้งเตือนเมื่อมีการมอบหมายงาน
|
||||
- การแจ้งเตือนเมื่อถึงกำหนดวันที่ต้องส่งเอกสารต่อให้ ผู้เกี่ยวข้องอื่นๆ
|
||||
- การแจ้งเตือนเมื่อมีการเปลี่ยนแปลงเอกสาร
|
||||
|
||||
### 👥 0.4 Target Users
|
||||
|
||||
- พนักงานภายใน ขององค์กร
|
||||
- พนักงานควบคุมเอกสาร (Document Control)/ ผู้ดูแลระบบขององค์กร (admin)
|
||||
- ผู้จัดการฝ่ายเอกสาร ขององค์กร
|
||||
- ผู้จัดการโครงการ ขององค์กร
|
||||
- คณะกรรมการ ของโครงการ
|
||||
- ผู้ดูแลระบบ IT ของโครงการ (superadmin)
|
||||
|
||||
### 📈 0.5 Expected Outcomes
|
||||
|
||||
- ลดเวลาในการค้นหาเอกสารลงอย่างน้อย 50%
|
||||
- ลดเวลาในการจัดทำรายงานเอกสาร ประจำวัน, ประจำสัปดาห์, ประจำเดือน, ประจำปี และ รายงานเอกสารทั้งโครงการ
|
||||
- ลดการใช้เอกสารกระดาษในองค์กร
|
||||
- เพิ่มความปลอดภัยในการจัดเก็บข้อมูล
|
||||
- รองรับการทำงานแบบ Remote Work
|
||||
|
||||
### 📘 0.6 Requirements Use Cases
|
||||
|
||||
#### 📘 Use Case: Upload Document
|
||||
|
||||
Actor: พนักงานควบคุมเอกสาร (Document Control)
|
||||
Description: พนักงานควบคุมเอกสารสามารถอัปโหลดเอกสารเข้าสู่ระบบเพื่อจัดเก็บและใช้งานในภายหลัง
|
||||
Preconditions: พนักงานควบคุมเอกสารต้องเข้าสู่ระบบก่อน
|
||||
Main Flow:
|
||||
|
||||
พนักงานควบคุมเอกสารเลือกเมนู “อัปโหลดเอกสาร”
|
||||
เลือกไฟล์จากเครื่องคอมพิวเตอร์
|
||||
กรอกข้อมูลประกอบ เช่น ชื่อเอกสาร หมวดหมู่ แท็ก
|
||||
กดปุ่ม “อัปโหลด”
|
||||
ระบบบันทึกเอกสารและแสดงผลการอัปโหลดสำเร็จ
|
||||
|
||||
Postconditions: เอกสารถูกจัดเก็บในระบบและสามารถค้นหาได้
|
||||
|
||||
#### 📘 Use Case: Assign Users to Document
|
||||
|
||||
Actor: พนักงานควบคุมเอกสาร (Document Control)
|
||||
Description: พนักงานควบคุมเอกสารสามารถ มอบหมายงานให้กับ Users
|
||||
Preconditions: พนักงานควบคุมเอกสารต้องเข้าสู่ระบบก่อน, เอกสารต้องอัปโหลดเรียบร้อยแล้ว
|
||||
Main Flow:
|
||||
|
||||
พนักงานควบคุมเอกสารเลือกเมนู “มอบหมายงาน”
|
||||
เลือกเอกสารในระบบ
|
||||
เลือก Users กำหนดวันสิ้นสุดงาน
|
||||
กดปุ่ม “มอบหมายงาน”
|
||||
ระบบบันทึกเอกสารและแสดงผลการมอบหมายงานสำเร็จ
|
||||
|
||||
Postconditions: งานที่มอยหมาย จัดเก็บในระบบและสามารถค้นหาได้
|
||||
|
||||
#### 📘 Use Case: Search Document
|
||||
|
||||
Actor: ผู้ใช้งานทั่วไป
|
||||
Description: ผู้ใช้งานสามารถค้นหาเอกสารจากระบบด้วยคำสำคัญหรือฟิลเตอร์
|
||||
Preconditions: ผู้ใช้งานต้องเข้าสู่ระบบ
|
||||
Main Flow:
|
||||
|
||||
ผู้ใช้งานกรอกคำค้นหรือเลือกฟิลเตอร์ (หมวดหมู่, วันที่, ผู้สร้าง, ผู้ได้รับมอบหมายงาน, สถานะ, title, subject)
|
||||
กดปุ่ม “ค้นหา”
|
||||
ระบบแสดงรายการเอกสารที่ตรงกับเงื่อนไข
|
||||
|
||||
Postconditions: ผู้ใช้งานสามารถเปิดดูหรือดาวน์โหลดเอกสารที่ค้นพบได้
|
||||
|
||||
#### 📘 Use Case: Manage Access
|
||||
|
||||
Actor: ผู้ดูแลระบบโครงการ (superadmin) / ผู้ดูแลระบบขององค์กร (admin)
|
||||
Description: ผู้ดูแลระบบสามารถกำหนดสิทธิ์การเข้าถึงเอกสารให้กับผู้ใช้งาน
|
||||
Preconditions: ผู้ดูแลระบบต้องเข้าสู่ระบบ
|
||||
Main Flow:
|
||||
|
||||
ผู้ดูแลระบบเลือกเอกสาร
|
||||
กด “จัดการสิทธิ์”
|
||||
เลือกผู้ใช้งานและกำหนดสิทธิ์ (อ่าน, แก้ไข, ลบ)
|
||||
กด “บันทึก”
|
||||
|
||||
Postconditions: สิทธิ์การเข้าถึงเอกสารถูกปรับตามที่กำหนด
|
||||
|
||||
#### 📘 Use Case: View Document History
|
||||
|
||||
Actor: ผู้ใช้งานทั่วไป / ผู้ดูแลระบบ
|
||||
Description: ผู้ใช้งานสามารถดูประวัติการใช้งานเอกสาร เช่น การแก้ไข การดาวน์โหลด
|
||||
Preconditions: ผู้ใช้งานต้องมีสิทธิ์เข้าถึงเอกสาร
|
||||
Main Flow:
|
||||
|
||||
ผู้ใช้งานเปิดเอกสาร
|
||||
เลือก “ดูประวัติ”
|
||||
ระบบแสดงรายการกิจกรรมที่เกี่ยวข้องกับเอกสาร
|
||||
|
||||
Postconditions: ผู้ใช้งานสามารถตรวจสอบการเปลี่ยนแปลงย้อนหลังได้
|
||||
|
||||
### 🔄 0.7 Workflow อัตโนมัติในระบบ DMS
|
||||
|
||||
✅ ประโยชน์ของ Workflow อัตโนมัติใน DMS
|
||||
|
||||
- ลดภาระงานซ้ำ ๆ ของผู้ใช้งาน
|
||||
- เพิ่มความปลอดภัยและการควบคุมเอกสาร
|
||||
- เพิ่มความเร็วในการดำเนินงาน
|
||||
- ลดข้อผิดพลาดจากการทำงานด้วยมือ
|
||||
|
||||
#### 🧩 Workflow: 1. Document treat Workflow
|
||||
|
||||
กรณี: เมื่อมีการอัปโหลดเอกสารต้องได้รับการมอบหมายงานให้กับ พนักงานภายในองค์กรณ์
|
||||
ขั้นตอนอัตโนมัติ:
|
||||
|
||||
1. ผู้ใช้งานอัปโหลดเอกสารและเลือก “มอบหมายงาน”
|
||||
2. ระบบส่งแจ้งเตือนไปยังผู้ได้รับมอบหมายงาน
|
||||
3. ผู้อนุมัติสามารถตรวจสอบและกด “ตรวจสอบแล้ว”
|
||||
4. ระบบบันทึกสถานะเอกสารและ ส่งต่อ ไปยัง องกรณือื่น ตามลำดับ เมื่อได้ผลและจัดทำเอกสารตอบแล้ว จึงแจ้งผลกลับไปยังผู้ส่ง
|
||||
|
||||
#### 📥 Workflow: 2. Auto Tagging & Categorization
|
||||
|
||||
กรณี: เอกสารที่อัปโหลดมีชื่อหรือเนื้อหาที่ตรงกับหมวดหมู่ที่กำหนดไว้
|
||||
ขั้นตอนอัตโนมัติ:
|
||||
|
||||
เมื่ออัปโหลดเอกสาร ระบบวิเคราะห์ชื่อไฟล์หรือเนื้อหา
|
||||
ระบบกำหนดหมวดหมู่และแท็กให้โดยอัตโนมัติ เช่น “ใบเสนอราคา” → หมวด “การเงิน”
|
||||
ผู้ใช้งานสามารถแก้ไขได้หากต้องการ
|
||||
|
||||
#### 🔐 Workflow: 3. Access Control Workflow
|
||||
|
||||
กรณี: เอกสารที่มีความลับสูงต้องจำกัดการเข้าถึง
|
||||
ขั้นตอนอัตโนมัติ:
|
||||
|
||||
เมื่ออัปโหลดเอกสารที่มีคำว่า “ลับ” หรือ “Confidential”
|
||||
ระบบกำหนดสิทธิ์เริ่มต้นให้เฉพาะผู้ใช้งานระดับผู้จัดการขึ้นไป
|
||||
ระบบแจ้งเตือนผู้ดูแลระบบให้ตรวจสอบสิทธิ์เพิ่มเติม
|
||||
|
||||
#### 📤 Workflow: 4. Expiry & Archiving Workflow
|
||||
|
||||
กรณี: เอกสารที่มีอายุการใช้งาน เช่น สัญญา หรือใบอนุญาต
|
||||
ขั้นตอนอัตโนมัติ:
|
||||
|
||||
เมื่ออัปโหลดเอกสาร ผู้ใช้งานระบุวันหมดอายุ
|
||||
ระบบแจ้งเตือนก่อนหมดอายุล่วงหน้า เช่น 30 วัน
|
||||
เมื่อถึงวันหมดอายุ ระบบย้ายเอกสารไปยังหมวด “Archive” โดยอัตโนมัติ
|
||||
|
||||
#### 📊 Workflow: 5. Audit Trail & Notification Workflow
|
||||
|
||||
กรณี: มีการแก้ไขหรือดาวน์โหลดเอกสารสำคัญ
|
||||
ขั้นตอนอัตโนมัติ:
|
||||
|
||||
ทุกการกระทำกับเอกสาร (เปิด, แก้ไข, ลบ) จะถูกบันทึกใน Audit Log
|
||||
หากเอกสารถูกแก้ไขโดยผู้ใช้งานที่ไม่ใช่เจ้าของ ระบบแจ้งเตือนเจ้าของเอกสารทันที
|
||||
|
||||
## 🛠️ 1. DMS Architecture Deep Dive (Backend + Frontend)
|
||||
|
||||
### 1.1 Executive Summary
|
||||
|
||||
- Reverse proxy (Nginx/NPM) เผยแพร่ Frontend (Next.js) และ Backend (Node.js/Express) ผ่าน HTTPS (HSTS)
|
||||
- Backend เชื่อม MariaDB 10.11 (ข้อมูลหลัก DMS) และแยก n8n + Postgres 16 สำหรับ workflow
|
||||
- RBAC/ABAC ถูกบังคับใช้งานใน middleware + มีชุด SQL (tables → triggers → procedures → views → seed)
|
||||
- ไฟล์จริง (PDF/DWG) เก็บนอก webroot ที่ /share/dms‑data พร้อมมาตรฐานการตั้งชื่อ+โฟลเดอร์
|
||||
- Dev/Prod แยกชัดเจนผ่าน Docker multi‑stage + docker‑compose + โฟลเดอร์ persist logs/config/certs
|
||||
|
||||
### 1.2 Runtime Topology & Trust Boundaries
|
||||
|
||||
```text
|
||||
Internet Clients (Browser)
|
||||
│ HTTPS 443 (HSTS) [QNAP mgmt = 8443]
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ Reverse Proxy Layer │
|
||||
│ ├─ Nginx (Alpine) or Nginx Proxy Manager (NPM) │
|
||||
│ ├─ TLS (LE cert; SAN multi‑subdomain) │
|
||||
│ └─ Routes: │
|
||||
│ • /, /_next/* → Frontend (Next.js :3000) │
|
||||
│ • /api/* → Backend (Express :3001) │
|
||||
│ • /pma/* → phpMyAdmin │
|
||||
│ • /n8n/* → n8n (Workflows) │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
│ │
|
||||
│ └──────────┐
|
||||
▼ │
|
||||
Frontend (Next.js) │
|
||||
│ Cookie-based Auth (HttpOnly) │
|
||||
▼ ▼
|
||||
Backend (Node/Express ESM) ─────────► MariaDB 10.11
|
||||
│ │
|
||||
└────────────────────────────────────┘
|
||||
Project data (.pdf/.dwg) @ /share/dms-data
|
||||
|
||||
n8n (workflows) ──► Postgres 16 (separate DB for automations)
|
||||
```
|
||||
|
||||
==Trust Boundaries==
|
||||
|
||||
- Public zone: Internet ↔ Reverse proxy
|
||||
- App zone: Reverse proxy ↔ FE/BE containers (internal Docker network)
|
||||
- # Data zone: Backend ↔ Databases (MariaDB, Postgres) + /share/dms-data
|
||||
|
||||
### 1.3 Frontend: Next.js (ESM) / React.js
|
||||
|
||||
#### 1.3.1 Stack & Key libs
|
||||
|
||||
- Next.js (App Router), React, ESM
|
||||
- Tailwind CSS, PostCSS, shadcn/ui (components.json)
|
||||
- Fetch API (credentials include) → Cookie Auth (HttpOnly)
|
||||
|
||||
#### 1.3.2 Directory Layout
|
||||
|
||||
```text
|
||||
/frontend/
|
||||
├─ app/
|
||||
│ ├─ login/
|
||||
│ ├─ dashboard/
|
||||
│ ├─ users/
|
||||
│ ├─ correspondences/
|
||||
│ ├─ health/
|
||||
│ └─ layout.tsx / page.tsx (ตาม App Router)
|
||||
├─ public/
|
||||
├─ Dockerfile (multi-stage: dev/prod)
|
||||
├─ package.json
|
||||
├─ next.config.js
|
||||
└─ ...
|
||||
```
|
||||
|
||||
#### 1.3.3 Routing & Layouts
|
||||
|
||||
- Public /login, /health
|
||||
- Protected: /dashboard, /users, /correspondences, ... (client-side guard)
|
||||
- เก็บ middleware.ts (ของเดิม) เพื่อหลีกเลี่ยง regression; ใช้ client‑guard + server action อย่างระมัดระวัง
|
||||
|
||||
#### 1.3.4 Auth Flow (Cookie-based)
|
||||
|
||||
1. ผู้ใช้ submit form /login → POST /api/auth/login (Backend)
|
||||
2. Backend set HttpOnly cookie (JWT) + SameSite=Lax/Strict, Secure
|
||||
3. หน้า protected เรียก GET /api/auth/me เพื่อตรวจสอบสถานะ
|
||||
4. หาก 401 → redirect → /login
|
||||
|
||||
**CORS/Fetch**: เเปิด credentials: 'include' ทุกครั้ง, ตั้ง NEXT_PUBLIC_API_BASE เป็น origin ของ backend ผ่าน proxy (เช่น https://lcbp3.np-dms.work)
|
||||
|
||||
#### 1.3.5 UI/UX
|
||||
|
||||
- Sea‑blue palette, sidebar พับได้, card‑based KPI
|
||||
- ตารางข้อมูลเตรียมรองรับ server‑side DataTables\*\*
|
||||
- shadcn/ui: Button, Card, Badge, Tabs, Dropdown, Tooltip, Switch, etc.
|
||||
|
||||
#### 1.3.6 Config & ENV
|
||||
|
||||
- NEXT_PUBLIC_API_BAS (ex: https://lcbp3.np-dms.work)
|
||||
- Build output แยก dev/prod; ระวัง EACCES บน QNAP → ใช้ user node + ปรับสิทธิ์โวลุ่ม .next/\*
|
||||
|
||||
#### 1.3.7 Error Handling & Observability (FE)
|
||||
|
||||
- Global error boundary (app router) + toast/alert patterns
|
||||
- Network layer: แยก handler สำหรับ 401/403/500 + retry/backoff ที่จำเป็น
|
||||
- Metrics (optional): web‑vitals, UX timing (เก็บฝั่ง n8n หรือ simple logging)
|
||||
|
||||
---
|
||||
|
||||
### 1.4 Backend Architecture (Node.js ESM / Express)
|
||||
|
||||
#### 1.4.1 Stack & Structure
|
||||
|
||||
- Node 20.x, ESM modules, Express\*\*
|
||||
- mysql2/promise, jsonwebtoken, cookie-parser, cors, helmet, winston/morgan
|
||||
|
||||
```text
|
||||
/backend/
|
||||
├─ src/
|
||||
│ ├─ index.js # bootstrap server, CORS, cookies, health
|
||||
│ ├─ routes/
|
||||
│ │ ├─ auth.js # /api/auth/* (login, me, logout)
|
||||
│ │ ├─ users.js # /api/users/*
|
||||
│ │ ├─ correspondences.js # /api/correspondences/*
|
||||
│ │ ├─ drawings.js # /api/drawings/*
|
||||
│ │ ├─ rfas.js # /api/rfas/*
|
||||
│ │ └─ transmittals.js # /api/transmittals/*
|
||||
│ ├─ middleware/
|
||||
│ │ ├─ authGuard.js # verify JWT from cookie
|
||||
│ │ ├─ requirePermission.js# RBAC/ABAC enforcement
|
||||
│ │ ├─ errorHandler.js
|
||||
│ │ └─ requestLogger.js
|
||||
│ ├─ db/
|
||||
│ │ ├─ pool.js # createPool, sane defaults
|
||||
│ │ └─ models/ # query builders (User, Drawing, ...)
|
||||
│ ├─ utils/
|
||||
│ │ ├─ hash.js (bcrypt/argon2)
|
||||
│ │ ├─ jwt.js
|
||||
│ │ ├─ pagination.js
|
||||
│ │ └─ responses.js
|
||||
│ └─ config/
|
||||
│ └─ index.js # env, constants
|
||||
├─ Dockerfile
|
||||
└─ package.json
|
||||
```
|
||||
|
||||
#### 1.4.2 Request Lifecycle
|
||||
|
||||
1. helmet + cors (allow specific origin; credentials true)
|
||||
2. cookie-parser, json limit (e.g., 2MB)
|
||||
3. requestLogger → trace + response time
|
||||
4. Route handler → authGuard (protected) → requirePermission (per‑route) → Controller
|
||||
5. Error bubbles → errorHandler (JSON shape, status map)
|
||||
|
||||
#### 1.4.3 Auth & RBAC/ABAC
|
||||
|
||||
- JWT ใน HttpOnly cookie; Claims: sub (user_id), roles, exp
|
||||
- authGuard: ตรวจ token → แนบ req.user
|
||||
- requirePermission: เช็ค permission ตามเส้นทาง/วิธี; แผนขยาย ABAC (เช่น project scope, owner, doc state)
|
||||
- Roles/Permissions ถูก seed ใน SQL; มี view เมทริกซ์ เพื่อ debug (เช่น v_role_permission_matrix)
|
||||
|
||||
\*\*ตัวอย่าง pseudo requirePermission(permission)
|
||||
|
||||
```js
|
||||
export const requirePermission = (perm) => async (req, res, next) => {
|
||||
if (!req.user) return res.status(401).json({ error: "Unauthenticated" });
|
||||
const ok = await checkPermission(req.user.user_id, perm, req.context);
|
||||
if (!ok) return res.status(403).json({ error: "Forbidden" });
|
||||
return next();
|
||||
};
|
||||
```
|
||||
|
||||
#### 1.4.4 Database Access & Pooling
|
||||
|
||||
- createPool({ connectionLimit: 10~25, queueLimit: 0, waitForConnections: true })
|
||||
- ใช้ parameterized queries เสมอ; ปรับ sql_mode ที่จำเป็นใน my.cnf
|
||||
|
||||
#### 1.4.5 File Storage & Secure Download
|
||||
|
||||
- Root: /share/dms‑data
|
||||
- โครงโฟลเดอร์: {module}/{yyyy}/{mm}/{entityId}/ + ชื่อไฟล์ตามมาตรฐาน (เช่น DRW-code-REV-rev.pdf)
|
||||
- Endpoint download: ตรวจสิทธิ์ (RBAC/ABAC) → res.sendFile()/stream; ป้องกัน path traversal
|
||||
- MIME allowlist + size limit + virus scan (optional; ภายหลัง)
|
||||
|
||||
#### 1.4.6 Health & Readiness
|
||||
|
||||
- GET /api/health → { ok: true }
|
||||
- (optional) /api/ready ตรวจ DB ping + disk space (dms‑data)
|
||||
|
||||
#### 1.4.7 Config & ENV (BE)
|
||||
|
||||
- DB_HOST, DB_PORT, DB_USER, DB_PASS, DB_NAME
|
||||
- JWT_SECRET, COOKIE_NAME, COOKIE_SAMESITE, COOKIE_SECURE
|
||||
- CORS_ORIGIN, LOG_LEVEL, APP_BASE_URL
|
||||
- FILE_ROOT=/share/dms-data
|
||||
|
||||
#### 1.4.8 Logging
|
||||
|
||||
- Access log (morgan) + App log (winston) → /share/Container/dms/logs/backend/
|
||||
- รูปแบบ JSON (timestamp, level, msg, reqId) + daily rotation (logrotate/container‑side)
|
||||
|
||||
### 1.5 Database (MariaDB 10.11)
|
||||
|
||||
#### 1.5.1 Schema Overview (ย่อ)
|
||||
|
||||
- RBAC core: users, roles, permissions, user_roles, role_permissions
|
||||
- Domain: drawings, contracts, correspondences, rfas, transmittals, organizations, projects, ...
|
||||
- Audit: audit_logs (แผนขยาย), deleted_at (soft delete, แผนงาน)
|
||||
|
||||
```text
|
||||
[users]──<user_roles>──[roles]──<role_permissions>──[permissions]
|
||||
│
|
||||
└── activities/audit_logs (future expansion)
|
||||
|
||||
[drawings]──<mapping>──[contracts]
|
||||
[rfas]──<links>──[drawings]
|
||||
[correspondences] (internal/external flag)
|
||||
```
|
||||
|
||||
#### 1.5.2 Init SQL Pipeline
|
||||
|
||||
1. 01\_\*\_deploy_table_rbac.sql — สร้างตารางหลักทั้งหมด + RBAC
|
||||
2. 02\_\*\_triggers.sql — บังคับ data rules, auto‑audit fields
|
||||
3. 03\_\*\_procedures_handlers.sql — upsert/bulk handlers (เช่น sp_bulk_import_contract_dwg)
|
||||
4. 04\_\*\_views.sql — รายงาน/เมทริกซ์สิทธิ์ (v_role_permission_matrix, etc.)
|
||||
5. 05\_\*\_seed_data.sql — ค่าพื้นฐาน domain (project, categories, statuses)
|
||||
6. 06\_\*\_seed_users.sql — บัญชีเริ่มต้น (superadmin, editors, viewers)
|
||||
7. 07\_\*\_seed_contract_dwg.sql — ข้อมูลตัวอย่างแบบสัญญา
|
||||
|
||||
#### 1.5.3 Indexing & Performance
|
||||
|
||||
- Composite indexes ตามคอลัมน์ filter/sort (เช่น (project_id, updated_at DESC))
|
||||
- Full‑text index (optional) สำหรับ advanced search
|
||||
- Query plan review (EXPLAIN) + เพิ่ม covering index ตามรายงาน
|
||||
|
||||
#### 1.5.4 MySQL/MariaDB Config (my.cnf — แนวทาง)
|
||||
|
||||
```conf
|
||||
[mysqld]
|
||||
innodb_buffer_pool_size = 4G # ปรับตาม RAM/QNAP
|
||||
innodb_log_file_size = 512M
|
||||
innodb_flush_log_at_trx_commit = 1
|
||||
max_connections = 200
|
||||
sql_mode = STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
|
||||
character-set-server = utf8mb4
|
||||
collation-server = utf8mb4_unicode_ci
|
||||
```
|
||||
|
||||
> ปรับค่าให้เหมาะกับ workload จริง + เฝ้าดู IO/CPU ของ QNAP
|
||||
|
||||
#### 1.5.5 Backup/Restore
|
||||
|
||||
- Logical backup: mysqldump --routines --triggers --single-transaction
|
||||
- Physical (snapshot QNAP) + schedule ผ่าน n8n/cron
|
||||
- เก็บสำเนา off‑NAS (encrypted)
|
||||
|
||||
### 1.6 Reverse Proxy & TLS
|
||||
|
||||
#### 1.6.1 Nginx (Alpine) — ตัวอย่าง server block
|
||||
|
||||
> สำคัญ: บนสภาพแวดล้อมนี้ ให้ใช้คนละบรรทัด:
|
||||
> listen 443 ssl;
|
||||
> http2 on;
|
||||
> หลีกเลี่ยง listen 443 ssl http2;
|
||||
|
||||
```conf
|
||||
server {
|
||||
listen 80;
|
||||
server_name lcbp3.np-dms.work;
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
http2 on;
|
||||
server_name lcbp3.np-dms.work;
|
||||
|
||||
ssl_certificate /etc/nginx/certs/fullchain.pem;
|
||||
ssl_certificate_key /etc/nginx/certs/privkey.pem;
|
||||
add_header Strict-Transport-Security "max-age=63072000; preload" always;
|
||||
|
||||
# Frontend
|
||||
location / {
|
||||
proxy_pass http://frontend:3000;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Next.js static
|
||||
location /_next/ {
|
||||
proxy_pass http://frontend:3000;
|
||||
}
|
||||
|
||||
# Backend API
|
||||
location /api/ {
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_pass http://backend:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# phpMyAdmin (sub-path)
|
||||
location /pma/ {
|
||||
proxy_pass http://phpmyadmin:80/;
|
||||
}
|
||||
|
||||
# n8n
|
||||
location /n8n/ {
|
||||
proxy_pass http://n8n:5678/;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 1.6.2 Nginx Proxy Manager (NPM) — Tips
|
||||
|
||||
- ระวังอย่าใส่ proxy_http_version ซ้ำซ้อน (duplicate directive) ใน Advanced
|
||||
- ถ้าต้องแก้ไฟล์ด้านใน NPM → ระวังไฟล์ใน /data/nginx/proxy_host/\*.conf
|
||||
- จัดการ certificate / SAN หลาย sub‑domain ใน UI แต่ mainten ดีเรื่อง symlink/renew
|
||||
|
||||
#### 1.6.3 TLS & Certificates
|
||||
|
||||
- Let’s Encrypt (HTTP‑01 webroot/standalone) + HSTS
|
||||
- QNAP mgmt เปลี่ยนเป็น 8443 → พอร์ต 443 public ว่างสำหรับ Nginx/NPM
|
||||
|
||||
### 1.7 Docker Compose Topology
|
||||
|
||||
#### 1.7.1 Services (สรุป)
|
||||
|
||||
- frontend (Next.js) :3000
|
||||
- backend (Express) :3001
|
||||
- mariadb (10.11) :3306 (internal)
|
||||
- phpmyadmin :80 (internal)
|
||||
- nginx or npm :80/443 (published)
|
||||
- n8n :5678 (internal)
|
||||
- postgres_n8n (16-alpine)
|
||||
- pgadmin4
|
||||
|
||||
#### 1.7.2 Volumes & Paths
|
||||
|
||||
```text
|
||||
/share/Container/dms/
|
||||
├─ mariadb/data
|
||||
├─ mariadb/init/*.sql
|
||||
├─ backend/ (code)
|
||||
├─ frontend/ (code)
|
||||
├─ phpmyadmin/{sessions,tmp,config.user.inc.php}
|
||||
├─ nginx/{nginx.conf,dms.conf,certs/}
|
||||
├─ n8n, n8n-postgres, n8n-cache
|
||||
└─ logs/{backend,frontend,nginx,pgadmin,phpmyadmin,postgres_n8n}
|
||||
/share/dms-data (pdf/dwg storage)
|
||||
```
|
||||
|
||||
#### 1.7.3 Healthchecks (suggested)
|
||||
|
||||
- backend:
|
||||
|
||||
```sh
|
||||
curl http://localhost:3001/api/health
|
||||
```
|
||||
|
||||
- frontend: curl /health (simple JSON)
|
||||
- mariadb: mysqladmin ping with credentials
|
||||
- nginx: nginx -t at startup
|
||||
|
||||
#### 1.7.4 Security Hardening
|
||||
|
||||
- รัน container ด้วย user non‑root (user: node สำหรับ FE/BE)
|
||||
- จำกัด capabilities; read‑only FS (ยกเว้นโวลุ่มจำเป็น)
|
||||
- เฉพาะ backend เมานต์ /share/dms-data
|
||||
|
||||
### 1.8 Observability, Ops, and Troubleshooting
|
||||
|
||||
#### 1.8.1 Logs
|
||||
|
||||
- Frontend → /logs/frontend/\*
|
||||
- Backend → /logs/backend/\* (app/access/error)
|
||||
- Nginx/NPM → /logs/nginx/\*
|
||||
- MariaDB → default datadir log + slow query (เปิดใน my.cnf หากต้องการ)
|
||||
|
||||
#### 1.8.2 Common Issues & Playbooks
|
||||
|
||||
- 401 Unauthenticated: ตรวจ authGuard → JWT cookie มี/หมดอายุ → เวลา server/FE sync → CORS credentials: true
|
||||
- EACCES Next.js: สิทธิ์ .next/\* + run as`node, โวลุ่ม map ถูก user:group
|
||||
- NPM duplicate directive: ลบซ้ำ proxy_http_version ใน Advanced / ตรวจ proxy_host/\*.conf
|
||||
- LE cert path/symlink: ตรวจ /etc/letsencrypt/live/npm-\* symlink ชี้ถูก
|
||||
- DB field not found: ตรวจ schema vs code (migration/init SQL) → sync ให้ตรง
|
||||
|
||||
#### 1.8.3 Performance Guides
|
||||
|
||||
- Backend: keep‑alive, gzip/deflate at proxy, pool 10–25, paginate, avoid N+1
|
||||
- Frontend: prefetch critical routes, cache static, image optimization
|
||||
- DB: เพิ่ม index จุด filter, analyze query (EXPLAIN), ปรับ buffer pool
|
||||
|
||||
### 1.9 Security & Compliance
|
||||
|
||||
- HTTPS only + HSTS (preload)
|
||||
- CORS: allow list เฉพาะ FE origin; Access-Control-Allow-Credentials: true
|
||||
- Cookie: HttpOnly, Secure, SameSite=Lax/Strict
|
||||
- Input Validation: celebrate/zod (optional) + sanitize
|
||||
- Rate limiting: per IP/route (optional)
|
||||
- AuditLog: วางแผนเพิ่ม ครอบคลุม CRUD + mapping (actor, action, entity, before/after)
|
||||
- Backups: DB + /share/dms-data + config (encrypted off‑NAS)
|
||||
|
||||
### 1.10 Backlog → Architecture Mapping
|
||||
|
||||
1. RBAC Enforcement ครบ → เติม requirePermission ทุก route + test matrix ผ่าน view
|
||||
2. AuditLog ครบ CRUD/Mapping → trigger + table audit_logs + BE hook
|
||||
3. Upload/Download จริงของ Drawing Revisions → BE endpoints + virus scan (optional)
|
||||
4. Dashboard KPI → BE summary endpoints + FE cards/charts
|
||||
5. Server‑side DataTables → paging/sort/filter + indexesรองรับ
|
||||
6. รายงาน Export CSV/Excel/PDF → BE export endpoints + FE buttons
|
||||
7. Soft delete (deleted_at) → BE filter default scope + restore endpoint
|
||||
8. Validation เข้ม → celebrate/zod schema + consistent error shape
|
||||
9. Indexing/Perf → slow query log + EXPLAIN review
|
||||
10. Job/Cron Deadline Alerts → n8n schedule + SMTP
|
||||
|
||||
### 1.11 Port & ENV Matrix (Quick Ref)
|
||||
|
||||
| Component | Ports | Key ENV |
|
||||
| Nginx/NPM | 80/443 (public) | SSL paths, HSTS |
|
||||
| Frontend | 3000 (internal) | NEXT*PUBLIC_API_BASE |
|
||||
| Backend | 3001 (internal) | DB*\*, JWT*SECRET, CORS_ORIGIN, FILE_ROOT |
|
||||
| MariaDB | 3306 (internal) | MY_CNF, credentials |
|
||||
| n8n | 5678 (internal) | N8N*, webhook URL under /n8n/ |
|
||||
| Postgres | 5432 (internal) | n8n DB |
|
||||
|
||||
QNAP mgmt: 8443 (already moved)
|
||||
|
||||
### 1.12 Sample Snippets
|
||||
|
||||
#### 1.12.1 Backend CORS (credentials)
|
||||
|
||||
```js
|
||||
app.use(
|
||||
cors({
|
||||
origin: ["https://lcbp3.np-dms.work"],
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
```
|
||||
|
||||
#### 1.12.2 Secure Download (guarded)
|
||||
|
||||
```js
|
||||
router.get(
|
||||
"/files/:module/:id/:filename",
|
||||
authGuard,
|
||||
requirePermission("file.read"),
|
||||
async (req, res) => {
|
||||
const { module, id, filename } = req.params;
|
||||
// 1) ABAC: verify user can access this module/entity
|
||||
const ok = await canReadFile(req.user.user_id, module, id);
|
||||
if (!ok) return res.status(403).json({ error: "Forbidden" });
|
||||
|
||||
const abs = path.join(FILE_ROOT, module, id, filename);
|
||||
if (!abs.startsWith(FILE_ROOT))
|
||||
return res.status(400).json({ error: "Bad path" });
|
||||
return res.sendFile(abs);
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
#### 1.12.3 Healthcheck
|
||||
|
||||
```js
|
||||
router.get("/health", (req, res) => res.json({ ok: true }));
|
||||
```
|
||||
|
||||
### 13 Deployment Workflow (Suggested)
|
||||
|
||||
1. Git (Gitea) branch strategy feature/\* → PR → main
|
||||
2. Build images (dev/prod) via Dockerfile multi‑stage; pin Node/MariaDB versions
|
||||
3. docker compose up -d --build จาก /share/Container/dms
|
||||
4. Validate: /health, /api/health, login roundtrip
|
||||
5. Monitor logs + baseline perf; run SQL smoke tests (views/triggers/procs)
|
||||
|
||||
### 14 Appendix
|
||||
|
||||
- Naming conventions: snake_case DB, camelCase JS
|
||||
- Timezones: store UTC in DB; display in app TZ (+07:00)
|
||||
- Character set: UTF‑8 (utf8mb4_unicode_ci)
|
||||
- Large file policy: size limit (e.g., 50–200MB), allowlist extensions
|
||||
- Retention: archive strategy for old revisions (optional)
|
||||
|
||||
## บทบาท: คุณคือ Programmer และ Document Engineer ที่เชี่ยวชาญ
|
||||
|
||||
1. การพัฒนาเว็บแอป (Web Application Development)
|
||||
2. Configuration of Container Station on QNAP
|
||||
3. Database: mariadb:10.11
|
||||
4. Database management: phpmyadmin:5-apache
|
||||
5. Backend: node:.js (ESM)
|
||||
6. Frontend: next.js, react
|
||||
7. Workflow automation: n8n:
|
||||
8. Workflow database: postgres:16-alpine
|
||||
9. Workflow database management: pgadmin4
|
||||
10. Reverse proxy: nginx:1.27-alpine
|
||||
11. linux on QNAP
|
||||
12. การจัดการฐานข้อมูล (Database Management)
|
||||
13. การวิเคราะห์ฐานข้อมูล (Database Analysis)
|
||||
14. การจัดการฐานข้อมูลเชิงสัมพันธ์ (Relational Databases)
|
||||
15. ภาษา SQL
|
||||
16. RBAC
|
||||
|
||||
## 2. ระบบที่ใช้
|
||||
|
||||
## Server
|
||||
|
||||
- ใช้ Container Station เป็น SERVER บน QNAP (Model: TS-473A, RAM: 32GB, CPU: AMD Ryzen V1500B 4 cores 8 threads) **เปลี่ยน port 443 ของ QNAP เป็น 8443 แล้ว**
|
||||
|
||||
## การพัฒนาโครงการ
|
||||
|
||||
- ด้วย Visual Studio Code บน Windows 11
|
||||
- ใช้ ๊ UI ของ Container Station เป็นหลัก
|
||||
|
||||
## โครงสร้างโฟลเดอร์ (บน QNAP)
|
||||
|
||||
/share/Container/dms/
|
||||
├─ docker-compose.yml # Create โดย UI Container Station
|
||||
├─ mariadb/
|
||||
│ ├─ data/ # ข้อมูลจริงของ MariaDB
|
||||
│ ├─ init/ # ข้อมูลเริ่มต้นของ MariaDB
|
||||
│ │ ├─ 01_dms_data_v5_1_deploy_table_rbac.sql # Create all data table & RBAC table here!
|
||||
│ │ ├─ 02_dms_data_v5_1_triggers.sql # Create all triggers here!
|
||||
│ │ ├─ 03_dms_data_v5_1_procedures_handlers.sql # Create all procedures here!
|
||||
│ │ ├─ 04_dms_data_v5_1_views.sql # Create all views here!
|
||||
│ │ ├─ 05 dms_data_v5_1_seeก_data.sql # Seed nescesary data here!
|
||||
│ │ ├─ 06_dms_data_v5_1_seed_users.sql # Seed users data here!
|
||||
│ │ └─ 07_dms_data_v5_1_seed_contract_dwg.sql # Seed contract drawing data here!
|
||||
│ └─ my.cnf
|
||||
├─ backend/
|
||||
│ ├─ app/
|
||||
│ ├─ src/
|
||||
│ │ ├─ db/
|
||||
│ │ │ └─models/
|
||||
│ │ ├─ middleware/
|
||||
│ │ ├─ routes/
|
||||
│ │ ├─ utils/
|
||||
│ │ └─ index.js
|
||||
│ ├─ Dockerfile
|
||||
│ ├─ package.json
|
||||
│ └─ package-lock.json # ไม่มี
|
||||
├─ frontend/
|
||||
│ ├─ app/
|
||||
│ │ ├─ correspondences/
|
||||
│ │ ├─ dashboard/
|
||||
│ │ ├─ health/
|
||||
│ │ ├─ login/
|
||||
│ │ └─ users/
|
||||
│ ├─ public/
|
||||
│ ├─ Dockerfile
|
||||
│ ├─ package.json
|
||||
│ ├─ package-lock.json # ไม่มี
|
||||
│ ├─ next.config.js
|
||||
│ └─ page.jsx
|
||||
├─ phpmyadmin/
|
||||
│ ├─ sessions/ # โฟลเดอร์เซสชันถาวรของ phpMyAdmin
|
||||
│ ├─ tmp/
|
||||
│ ├─ config.user.inc.php
|
||||
│ └─ zzz-custom.ini
|
||||
├─ nginx/
|
||||
│ ├─ certs/
|
||||
│ ├─ nginx.conf
|
||||
│ └─ dms.conf
|
||||
├─ n8n/
|
||||
├─ n8n-cache/
|
||||
├─ n8n-postgres/
|
||||
└─ logs/
|
||||
├─ backend/
|
||||
├─ frontend/
|
||||
├─ nginx/
|
||||
├─ pgadmin/
|
||||
├─ phpmyadmin/
|
||||
└─ postgres_n8n/
|
||||
/share/dms-data # เก็บข้อมมูล .pdf, .dwg แยกตาม correspondences, documents
|
||||
|
||||
# งานที่ต้องการ:
|
||||
|
||||
- ไม่ใช้ .env เด็ดขาด Container Station ไม่รองรับ และ docker-compose.yml ได้ทดสอบ รันบน Container station มาแล้ว
|
||||
- Code ของ backend ทั้งหมด
|
||||
- การทดสอบระบบ backend ทุกส่วน ให้พร้อม สำหรับ frontend
|
||||
|
||||
# กรณี 2: มี Git อยู่แล้ว (มี main อยู่)
|
||||
|
||||
2.1 อัปเดต main ให้ตรงล่าสุดก่อนแตกบร้านช์
|
||||
|
||||
cd /share/Container/dms
|
||||
git checkout main
|
||||
git pull --ff-only # ถ้าเชื่อม remote อยู่
|
||||
git tag -f stable-$(date +%F) # tag จุดเสถียรปัจจุบัน
|
||||
|
||||
2.2 แตก branch งาน Dashboard
|
||||
git checkout -b feature/dashboard-update-$(date +%y%m%d)
|
||||
git checkout -b feature/dashboard-update-251004
|
||||
|
||||
2.3 ทำงาน/คอมมิตตามปกติ
|
||||
|
||||
# แก้ไฟล์ frontend/app/dashboard/\* และที่เกี่ยวข้อง
|
||||
|
||||
git add frontend/app/dashboard
|
||||
git commit -m "feat(dashboard): เพิ่มส่วนจัดการ user"
|
||||
git push -u origin feature/dashboard-update-251004
|
||||
134
specs/99-archives/docs/backup/NestJS01.bak
Normal file
134
specs/99-archives/docs/backup/NestJS01.bak
Normal file
@@ -0,0 +1,134 @@
|
||||
You are a senior TypeScript programmer with experience in the NestJS framework and a preference for clean programming and design patterns.
|
||||
|
||||
Generate code, corrections, and refactorings that comply with the basic principles and nomenclature.
|
||||
|
||||
## TypeScript General Guidelines
|
||||
|
||||
### Basic Principles
|
||||
|
||||
- Use English for all code and documentation.
|
||||
- Always declare the type of each variable and function (parameters and return value).
|
||||
- Avoid using any.
|
||||
- Create necessary types.
|
||||
- Use JSDoc to document public classes and methods.
|
||||
- Don't leave blank lines within a function.
|
||||
- One export per file.
|
||||
|
||||
### Nomenclature
|
||||
|
||||
- Use PascalCase for classes.
|
||||
- Use camelCase for variables, functions, and methods.
|
||||
- Use kebab-case for file and directory names.
|
||||
- Use UPPERCASE for environment variables.
|
||||
- Avoid magic numbers and define constants.
|
||||
- Start each function with a verb.
|
||||
- Use verbs for boolean variables. Example: isLoading, hasError, canDelete, etc.
|
||||
- Use complete words instead of abbreviations and correct spelling.
|
||||
- Except for standard abbreviations like API, URL, etc.
|
||||
- Except for well-known abbreviations:
|
||||
- i, j for loops
|
||||
- err for errors
|
||||
- ctx for contexts
|
||||
- req, res, next for middleware function parameters
|
||||
|
||||
### Functions
|
||||
|
||||
- In this context, what is understood as a function will also apply to a method.
|
||||
- Write short functions with a single purpose. Less than 20 instructions.
|
||||
- Name functions with a verb and something else.
|
||||
- If it returns a boolean, use isX or hasX, canX, etc.
|
||||
- If it doesn't return anything, use executeX or saveX, etc.
|
||||
- Avoid nesting blocks by:
|
||||
- Early checks and returns.
|
||||
- Extraction to utility functions.
|
||||
- Use higher-order functions (map, filter, reduce, etc.) to avoid function nesting.
|
||||
- Use arrow functions for simple functions (less than 3 instructions).
|
||||
- Use named functions for non-simple functions.
|
||||
- Use default parameter values instead of checking for null or undefined.
|
||||
- Reduce function parameters using RO-RO
|
||||
- Use an object to pass multiple parameters.
|
||||
- Use an object to return results.
|
||||
- Declare necessary types for input arguments and output.
|
||||
- Use a single level of abstraction.
|
||||
|
||||
### Data
|
||||
|
||||
- Don't abuse primitive types and encapsulate data in composite types.
|
||||
- Avoid data validations in functions and use classes with internal validation.
|
||||
- Prefer immutability for data.
|
||||
- Use readonly for data that doesn't change.
|
||||
- Use as const for literals that don't change.
|
||||
|
||||
### Classes
|
||||
|
||||
- Follow SOLID principles.
|
||||
- Prefer composition over inheritance.
|
||||
- Declare interfaces to define contracts.
|
||||
- Write small classes with a single purpose.
|
||||
- Less than 200 instructions.
|
||||
- Less than 10 public methods.
|
||||
- Less than 10 properties.
|
||||
|
||||
### Exceptions
|
||||
|
||||
- Use exceptions to handle errors you don't expect.
|
||||
- If you catch an exception, it should be to:
|
||||
- Fix an expected problem.
|
||||
- Add context.
|
||||
- Otherwise, use a global handler.
|
||||
|
||||
### Testing
|
||||
|
||||
- Follow the Arrange-Act-Assert convention for tests.
|
||||
- Name test variables clearly.
|
||||
- Follow the convention: inputX, mockX, actualX, expectedX, etc.
|
||||
- Write unit tests for each public function.
|
||||
- Use test doubles to simulate dependencies.
|
||||
- Except for third-party dependencies that are not expensive to execute.
|
||||
- Write acceptance tests for each module.
|
||||
- Follow the Given-When-Then convention.
|
||||
|
||||
|
||||
## Specific to NestJS
|
||||
|
||||
### Basic Principles
|
||||
|
||||
- Use modular architecture.
|
||||
- Encapsulate the API in modules.
|
||||
- One module per main domain/route.
|
||||
- One controller for its route.
|
||||
- And other controllers for secondary routes.
|
||||
- A models folder with data types.
|
||||
- DTOs validated with class-validator for inputs.
|
||||
- Declare simple types for outputs.
|
||||
- A services module with business logic and persistence.
|
||||
- Entities with MikroORM for data persistence.
|
||||
- One service per entity.
|
||||
|
||||
- Common Module: Create a common module (e.g., @app/common) for shared, reusable code across the application.
|
||||
- This module should include:
|
||||
- Configs: Global configuration settings.
|
||||
- Decorators: Custom decorators for reusability.
|
||||
- DTOs: Common data transfer objects.
|
||||
- Guards: Guards for role-based or permission-based access control.
|
||||
- Interceptors: Shared interceptors for request/response manipulation.
|
||||
- Notifications: Modules for handling app-wide notifications.
|
||||
- Services: Services that are reusable across modules.
|
||||
- Types: Common TypeScript types or interfaces.
|
||||
- Utils: Helper functions and utilities.
|
||||
- Validators: Custom validators for consistent input validation.
|
||||
|
||||
- Core module functionalities:
|
||||
- Global filters for exception handling.
|
||||
- Global middlewares for request management.
|
||||
- Guards for permission management.
|
||||
- Interceptors for request processing.
|
||||
|
||||
### Testing
|
||||
|
||||
- Use the standard Jest framework for testing.
|
||||
- Write tests for each controller and service.
|
||||
- Write end to end tests for each api module.
|
||||
- Add a admin/test method to each controller as a smoke test.
|
||||
|
||||
|
||||
33
specs/99-archives/docs/backup/NextJS01.bak
Normal file
33
specs/99-archives/docs/backup/NextJS01.bak
Normal file
@@ -0,0 +1,33 @@
|
||||
You are a Senior Front-End Developer and an Expert in ReactJS, NextJS, JavaScript, TypeScript, HTML, CSS and modern UI/UX frameworks (e.g., TailwindCSS, Shadcn, Radix). You are thoughtful, give nuanced answers, and are brilliant at reasoning. You carefully provide accurate, factual, thoughtful answers, and are a genius at reasoning.
|
||||
|
||||
- Follow the user’s requirements carefully & to the letter.
|
||||
- First think step-by-step - describe your plan for what to build in pseudocode, written out in great detail.
|
||||
- Confirm, then write code!
|
||||
- Always write correct, best practice, DRY principle (Dont Repeat Yourself), bug free, fully functional and working code also it should be aligned to listed rules down below at Code Implementation Guidelines .
|
||||
- Focus on easy and readability code, over being performant.
|
||||
- Fully implement all requested functionality.
|
||||
- Leave NO todo’s, placeholders or missing pieces.
|
||||
- Ensure code is complete! Verify thoroughly finalised.
|
||||
- Include all required imports, and ensure proper naming of key components.
|
||||
- Be concise Minimize any other prose.
|
||||
- If you think there might not be a correct answer, you say so.
|
||||
- If you do not know the answer, say so, instead of guessing.
|
||||
|
||||
### Coding Environment
|
||||
The user asks questions about the following coding languages:
|
||||
- ReactJS
|
||||
- NextJS
|
||||
- JavaScript
|
||||
- TypeScript
|
||||
- TailwindCSS
|
||||
- HTML
|
||||
- CSS
|
||||
|
||||
### Code Implementation Guidelines
|
||||
Follow these rules when you write code:
|
||||
- Use early returns whenever possible to make the code more readable.
|
||||
- Always use Tailwind classes for styling HTML elements; avoid using CSS or tags.
|
||||
- Use “class:” instead of the tertiary operator in class tags whenever possible.
|
||||
- Use descriptive variable and function/const names. Also, event functions should be named with a “handle” prefix, like “handleClick” for onClick and “handleKeyDown” for onKeyDown.
|
||||
- Implement accessibility features on elements. For example, a tag should have a tabindex=“0”, aria-label, on:click, and on:keydown, and similar attributes.
|
||||
- Use consts instead of functions, for example, “const toggle = () =>”. Also, define a type if possible.
|
||||
171
specs/99-archives/docs/backup/backend_setup.bak
Normal file
171
specs/99-archives/docs/backup/backend_setup.bak
Normal file
@@ -0,0 +1,171 @@
|
||||
|
||||
# การติดตั้งและสร้างโปรเจกต์ (Project Initialization)
|
||||
|
||||
1. ข้อกำหนดเบื้องต้น (Prerequisites)
|
||||
ก่อนเริ่ม, ตรวจสอบให้แน่ใจว่าคุณมีเครื่องมือเหล่านี้ติดตั้งบน Windows 11 ของคุณแล้ว:
|
||||
Node.js: เวอร์ชัน 18.x หรือสูงกว่า
|
||||
NPM หรือ Yarn: ตัวจัดการ Package (มักจะมาพร้อมกับ Node.js)
|
||||
NestJS CLI: เครื่องมือ Command-line สำหรับ NestJS
|
||||
หากยังไม่ได้ติดตั้ง NestJS CLI, ให้เปิด VS Code Terminal หรือ Command Prompt แล้วรันคำสั่ง:
|
||||
|
||||
bash
|
||||
npm install -g @nestjs/cli
|
||||
|
||||
## 2.1 สร้างโปรเจกต์ NestJS ใหม่
|
||||
ไปที่ Directory ที่คุณต้องการเก็บโปรเจกต์ (เช่น C:\Users\YourUser\Development\)
|
||||
ใช้ NestJS CLI เพื่อสร้างโปรเจกต์ใหม่ ผมจะตั้งชื่อว่า backend-np-dms นะครับ:
|
||||
|
||||
Bash
|
||||
nest new backend
|
||||
|
||||
ระบบจะถามว่าต้องการใช้ Package Manager ตัวไหน แนะนำให้เลือก npm, รอจนกว่ากระบวนการจะเสร็จสิ้น คุณจะได้โฟลเดอร์ backend ที่มีโครงสร้างพื้นฐานของ NestJS พร้อมใช้งาน
|
||||
|
||||
## 2.2 ติดตั้ง Dependencies ที่จำเป็น
|
||||
ตอนนี้เราจะติดตั้ง Modules ทั้งหมดที่คุณวางแผนไว้ในคราวเดียว เพื่อให้โปรเจกต์พร้อมสำหรับการพัฒนา
|
||||
|
||||
เปิด Terminal ใน VS Code ภายในโฟลเดอร์ backend (cd backend) แล้วรันคำสั่งต่อไปนี้:
|
||||
|
||||
* Database & ORM (TypeORM for MariaDB/MySQL)
|
||||
Bash
|
||||
npm install @nestjs/typeorm typeorm mysql2
|
||||
|
||||
* Configuration Management (สำหรับ .env)
|
||||
npm install @nestjs/config
|
||||
|
||||
* API Documentation
|
||||
npm install @nestjs/swagger
|
||||
|
||||
* Validation & Transformation
|
||||
npm install class-validator class-transformer
|
||||
|
||||
* Security
|
||||
npm install helmet
|
||||
|
||||
* Authentication (JWT)
|
||||
npm install @nestjs/passport passport passport-jwt @nestjs/jwt
|
||||
npm install --save-dev @types/passport-jwt
|
||||
|
||||
คำอธิบาย:
|
||||
@nestjs/typeorm typeorm mysql2: สำหรับเชื่อมต่อและจัดการฐานข้อมูล MariaDB
|
||||
@nestjs/config: สำหรับจัดการ Environment Variables (เช่น ข้อมูลการเชื่อมต่อ DB) ผ่านไฟล์ .env
|
||||
@nestjs/swagger: สำหรับสร้างหน้าเอกสาร API (Swagger/OpenAPI) โดยอัตโนมัติ
|
||||
class-validator class-transformer: ใช้สำหรับตรวจสอบความถูกต้องของข้อมูลที่ส่งเข้ามาใน API (Request Body Validation)
|
||||
helmet: ช่วยเพิ่มความปลอดภัยพื้นฐานโดยการตั้งค่า HTTP Headers ที่เหมาะสม
|
||||
@nestjs/passport, @nestjs/jwt: เครื่องมือมาตรฐานสำหรับทำระบบ Authentication
|
||||
|
||||
## 2.3: ตั้งค่าพื้นฐานในโปรเจกต์ (Initial Configuration)
|
||||
ตอนนี้เราจะแก้ไขไฟล์หลักๆ เพื่อเปิดใช้งาน Modules ที่ติดตั้งไป
|
||||
|
||||
1. สร้างไฟล์ Environment (.env)
|
||||
ที่ราก (root) ของโปรเจกต์ backend-np-dms, สร้างไฟล์ใหม่ชื่อ .env และใส่ข้อมูลการเชื่อมต่อฐานข้อมูลของคุณ (ข้อมูลนี้จะไม่ถูกเก็บใน Git):
|
||||
|
||||
.env
|
||||
|
||||
Code snippet
|
||||
|
||||
* Database Configuration
|
||||
DB_TYPE=mysql
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USERNAME=your_db_user # <-- แก้ไขเป็น user ของคุณ
|
||||
DB_PASSWORD=your_db_password # <-- แก้ไขเป็น password ของคุณ
|
||||
DB_DATABASE=dms_db # <-- แก้ไขเป็นชื่อ database ของคุณ
|
||||
|
||||
* Application
|
||||
API_PORT=3001
|
||||
💡 Tip: หากคุณรัน MariaDB ผ่าน Docker, DB_HOST อาจจะเป็นชื่อ Service ของ Docker container (เช่น mariadb-container) หรือ IP ของ QNAP ของคุณ
|
||||
|
||||
2. แก้ไข app.module.ts เพื่อเชื่อมต่อ Database และ Config
|
||||
เปิดไฟล์ src/app.module.ts และแก้ไขให้เป็นตามนี้เพื่อ import ConfigModule และ TypeOrmModule:
|
||||
|
||||
src/app.module.ts
|
||||
|
||||
```TypeScript
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
// 1. Config Module - สำหรับอ่าน .env (ต้องอยู่บนสุด)
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true, // ทำให้ ConfigService พร้อมใช้งานทั่วทั้งแอป
|
||||
envFilePath: '.env',
|
||||
}),
|
||||
|
||||
// 2. TypeORM Module - สำหรับเชื่อมต่อ Database
|
||||
TypeOrmModule.forRootAsync({
|
||||
imports: [ConfigModule],
|
||||
inject: [ConfigService],
|
||||
useFactory: (configService: ConfigService) => ({
|
||||
type: 'mysql',
|
||||
host: configService.get<string>('DB_HOST'),
|
||||
port: configService.get<int>('DB_PORT'),
|
||||
username: configService.get<string>('DB_USERNAME'),
|
||||
password: configService.get<string>('DB_PASSWORD'),
|
||||
database: configService.get<string>('DB_DATABASE'),
|
||||
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
|
||||
synchronize: true, // สำหรับ Development เท่านั้น! จะสร้างตารางให้อัตโนมัติ
|
||||
logging: true,
|
||||
}),
|
||||
}),
|
||||
],
|
||||
controllers: [AppController],
|
||||
providers: [AppService],
|
||||
})
|
||||
export class AppModule {}
|
||||
```
|
||||
⚠️ คำเตือน: synchronize: true สะดวกมากในช่วงพัฒนาเพราะมันจะปรับโครงสร้างตารางตาม Entity ให้อัตโนมัติ ห้ามใช้ใน Production เด็ดขาด เพราะอาจทำให้ข้อมูลหายได้ ใน Production ควรใช้ระบบ Migration แทน
|
||||
|
||||
3. แก้ไข main.ts เพื่อเปิดใช้งาน Swagger, Validation และ Security
|
||||
เปิดไฟล์ src/main.ts และเพิ่มการตั้งค่าต่างๆ เข้าไป:
|
||||
|
||||
src/main.ts
|
||||
|
||||
TypeScript
|
||||
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { ValidationPipe } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import helmet from 'helmet';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
// เปิดใช้งาน CORS (Cross-Origin Resource Sharing)
|
||||
app.enableCors();
|
||||
|
||||
// เพิ่ม Helmet เพื่อความปลอดภัย
|
||||
app.use(helmet());
|
||||
|
||||
// ตั้งค่า Global Validation Pipe
|
||||
app.useGlobalPipes(new ValidationPipe({
|
||||
whitelist: true, // ตัด property ที่ไม่มีใน DTO ออก
|
||||
transform: true, // แปลงข้อมูลให้เป็น type ที่ระบุใน DTO
|
||||
}));
|
||||
|
||||
// ตั้งค่า Swagger API Documentation
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('LCBP3-DMS API')
|
||||
.setDescription('The Document Management System API for LCBP3 Project')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth() // สำหรับ JWT
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
SwaggerModule.setup('api-docs', app, document); // เข้าถึงได้ที่ /api-docs
|
||||
|
||||
// เริ่มรัน Server
|
||||
const port = process.env.API_PORT || 3001;
|
||||
await app.listen(port);
|
||||
console.log(`Application is running on: ${await app.getUrl()}`);
|
||||
}
|
||||
bootstrap();
|
||||
|
||||
curl -i -X POST \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"username": "superadmin", "password": "Center#2025"}' \
|
||||
https://backend.np-dms.work/api/auth/login
|
||||
1728
specs/99-archives/docs/backup/data-dictionary-v1.5.1.md
Normal file
1728
specs/99-archives/docs/backup/data-dictionary-v1.5.1.md
Normal file
File diff suppressed because it is too large
Load Diff
1813
specs/99-archives/docs/backup/document-numbering-add.md
Normal file
1813
specs/99-archives/docs/backup/document-numbering-add.md
Normal file
File diff suppressed because it is too large
Load Diff
813
specs/99-archives/docs/backup/document-numbering.md
Normal file
813
specs/99-archives/docs/backup/document-numbering.md
Normal file
@@ -0,0 +1,813 @@
|
||||
# Document Numbering Implementation Guide
|
||||
|
||||
---
|
||||
title: 'Implementation Guide: Document Numbering System'
|
||||
version: 1.6.1
|
||||
status: implemented
|
||||
owner: Development Team
|
||||
last_updated: 2025-12-16
|
||||
related:
|
||||
|
||||
- specs/01-requirements/03.11-document-numbering.md
|
||||
- specs/04-operations/document-numbering-operations.md
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
เอกสารนี้อธิบาย implementation details สำหรับระบบ Document Numbering ตาม requirements ใน [03.11-document-numbering.md](file:///e:/np-dms/lcbp3/specs/01-requirements/03.11-document-numbering.md)
|
||||
|
||||
## Technology Stack
|
||||
|
||||
- **Backend Framework**: NestJS 10.x
|
||||
- **ORM**: TypeORM 0.3.x
|
||||
- **Database**: MariaDB 11.8
|
||||
- **Cache/Lock**: Redis 7.x + Redlock
|
||||
- **Message Queue**: BullMQ
|
||||
- **Monitoring**: Prometheus + Grafana
|
||||
|
||||
## 1. Database Implementation
|
||||
|
||||
### 1.1. Counter Table Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE document_number_formats (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
project_id INT NOT NULL,
|
||||
correspondence_type_id INT NULL, -- NULL indicates default format for the project
|
||||
format_template VARCHAR(100) NOT NULL,
|
||||
reset_sequence_yearly TINYINT(1) DEFAULT 1,
|
||||
description VARCHAR(255),
|
||||
created_at DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6),
|
||||
updated_at DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
|
||||
|
||||
UNIQUE KEY idx_unique_project_type (project_id, correspondence_type_id),
|
||||
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (correspondence_type_id) REFERENCES correspondence_types(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE TABLE document_number_counters (
|
||||
project_id INT NOT NULL,
|
||||
originator_organization_id INT NOT NULL,
|
||||
recipient_organization_id INT NULL,
|
||||
correspondence_type_id INT NOT NULL,
|
||||
sub_type_id INT DEFAULT 0,
|
||||
rfa_type_id INT DEFAULT 0,
|
||||
discipline_id INT DEFAULT 0,
|
||||
current_year INT NOT NULL,
|
||||
version INT DEFAULT 0 NOT NULL,
|
||||
last_number INT DEFAULT 0,
|
||||
|
||||
PRIMARY KEY (
|
||||
project_id,
|
||||
originator_organization_id,
|
||||
COALESCE(recipient_organization_id, 0),
|
||||
correspondence_type_id,
|
||||
sub_type_id,
|
||||
rfa_type_id,
|
||||
discipline_id,
|
||||
current_year
|
||||
),
|
||||
|
||||
FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (originator_organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (recipient_organization_id) REFERENCES organizations(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (correspondence_type_id) REFERENCES correspondence_types(id) ON DELETE CASCADE,
|
||||
|
||||
INDEX idx_counter_lookup (project_id, correspondence_type_id, current_year),
|
||||
INDEX idx_counter_org (originator_organization_id, current_year),
|
||||
|
||||
CONSTRAINT chk_last_number_positive CHECK (last_number >= 0),
|
||||
CONSTRAINT chk_current_year_valid CHECK (current_year BETWEEN 2020 AND 2100)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
|
||||
COMMENT='ตารางเก็บ Running Number Counters';
|
||||
```
|
||||
|
||||
### 1.2. Audit Table Schema
|
||||
|
||||
```sql
|
||||
CREATE TABLE document_number_audit (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
document_id INT NULL COMMENT 'FK to documents (NULL initially, updated after doc creation)',
|
||||
generated_number VARCHAR(100) NOT NULL,
|
||||
counter_key JSON NOT NULL COMMENT 'Counter key used (JSON format)',
|
||||
template_used VARCHAR(200) NOT NULL,
|
||||
user_id INT NULL COMMENT 'FK to users (Allow NULL for system generation)',
|
||||
ip_address VARCHAR(45),
|
||||
user_agent TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
is_success BOOLEAN DEFAULT TRUE COMMENT 'Track success/failure status',
|
||||
|
||||
-- Performance & Error Tracking
|
||||
retry_count INT DEFAULT 0,
|
||||
lock_wait_ms INT COMMENT 'Lock acquisition time in milliseconds',
|
||||
total_duration_ms INT COMMENT 'Total generation time',
|
||||
fallback_used ENUM('NONE', 'DB_LOCK', 'RETRY') DEFAULT 'NONE',
|
||||
|
||||
INDEX idx_document_id (document_id),
|
||||
INDEX idx_user_id (user_id),
|
||||
INDEX idx_created_at (created_at),
|
||||
FOREIGN KEY (document_id) REFERENCES documents(id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id)
|
||||
) ENGINE=InnoDB COMMENT='Document Number Generation Audit Trail';
|
||||
```
|
||||
|
||||
### 1.3. Error Log Table
|
||||
|
||||
```sql
|
||||
CREATE TABLE document_number_errors (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
error_type ENUM(
|
||||
'LOCK_TIMEOUT',
|
||||
'VERSION_CONFLICT',
|
||||
'DB_ERROR',
|
||||
'REDIS_ERROR',
|
||||
'VALIDATION_ERROR'
|
||||
) NOT NULL,
|
||||
error_message TEXT,
|
||||
stack_trace TEXT,
|
||||
context_data JSON COMMENT 'Request context (user, project, etc.)',
|
||||
user_id INT,
|
||||
ip_address VARCHAR(45),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
resolved_at TIMESTAMP NULL,
|
||||
|
||||
INDEX idx_error_type (error_type),
|
||||
INDEX idx_created_at (created_at),
|
||||
INDEX idx_user_id (user_id)
|
||||
) ENGINE=InnoDB COMMENT='Document Numbering Error Log';
|
||||
```
|
||||
|
||||
## 2. NestJS Implementation
|
||||
|
||||
### 2.1. Module Structure
|
||||
|
||||
```
|
||||
src/modules/document-numbering/
|
||||
├── document-numbering.module.ts
|
||||
├── controllers/
|
||||
│ └── document-numbering.controller.ts
|
||||
├── services/
|
||||
│ ├── document-numbering.service.ts
|
||||
│ ├── document-numbering-lock.service.ts
|
||||
│ ├── counter.service.ts
|
||||
│ ├── template.service.ts
|
||||
│ └── audit.service.ts
|
||||
├── entities/
|
||||
│ ├── document-number-counter.entity.ts
|
||||
│ ├── document-number-audit.entity.ts
|
||||
│ └── document-number-error.entity.ts
|
||||
├── dto/
|
||||
│ ├── generate-number.dto.ts
|
||||
│ └── update-template.dto.ts
|
||||
├── validators/
|
||||
│ └── template.validator.ts
|
||||
├── jobs/
|
||||
│ └── counter-reset.job.ts
|
||||
└── metrics/
|
||||
└── metrics.service.ts
|
||||
```
|
||||
|
||||
### 2.2. Number Generation Process
|
||||
|
||||
#### 2.2.1. Resolve Format Template:
|
||||
* Query document_number_formats by project_id + type_id.
|
||||
* If no result, query by project_id + NULL (Default Project Format).
|
||||
* If still no result, apply System Default Template: `{ORG}-{RECIPIENT}-{SEQ:4}-{YEAR:BE}`.
|
||||
* Determine resetSequenceYearly flag from the found format (default: true)
|
||||
|
||||
#### 2.2.2. Determine Counter Key:
|
||||
* If resetSequenceYearly is True: Use Current Year (e.g., 2025).
|
||||
* If resetSequenceYearly is False: Use 0 (Continuous).
|
||||
* Use type_id from the resolved format (Specific ID or NULL).
|
||||
|
||||
#### 2.2.3. Generate Number:
|
||||
* Use format template to generate number.
|
||||
* Replace tokens with actual values:
|
||||
* {PROJECT} -> Project Code
|
||||
* {ORG} -> Originator Organization Code
|
||||
* {RECIPIENT} -> Recipient Organization Code
|
||||
* {TYPE} -> Type Code
|
||||
* {YEAR} -> Current Year
|
||||
* {SEQ} -> Sequence Number
|
||||
* {REV} -> Revision Number
|
||||
|
||||
#### 2.2.4. Validate Number:
|
||||
* Check if generated number is unique.
|
||||
* If not unique, increment sequence and retry.
|
||||
|
||||
#### 2.2.5. Update Counter:
|
||||
* Update document_number_counters with new sequence.
|
||||
|
||||
#### 2.2.6. Generate Audit Record:
|
||||
* Create audit record with:
|
||||
* Generated number
|
||||
* Counter key used
|
||||
* Template used
|
||||
* User ID
|
||||
* IP Address
|
||||
* User Agent
|
||||
|
||||
#### 2.2.7. Return Generated Number:
|
||||
* Return generated number to caller.
|
||||
|
||||
### 2.3. TypeORM Entity
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/entities/document-number-counter.entity.ts
|
||||
import { Entity, Column, PrimaryColumn, VersionColumn } from 'typeorm';
|
||||
|
||||
@Entity('document_number_counters')
|
||||
export class DocumentNumberCounter {
|
||||
@PrimaryColumn({ name: 'project_id' })
|
||||
projectId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'originator_organization_id' })
|
||||
originatorOrganizationId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'recipient_organization_id', nullable: true })
|
||||
recipientOrganizationId: number | null;
|
||||
|
||||
@PrimaryColumn({ name: 'correspondence_type_id' })
|
||||
correspondenceTypeId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'sub_type_id', default: 0 })
|
||||
subTypeId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'rfa_type_id', default: 0 })
|
||||
rfaTypeId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'discipline_id', default: 0 })
|
||||
disciplineId: number;
|
||||
|
||||
@PrimaryColumn({ name: 'current_year' })
|
||||
currentYear: number;
|
||||
|
||||
@VersionColumn({ name: 'version' })
|
||||
version: number;
|
||||
|
||||
@Column({ name: 'last_number', default: 0 })
|
||||
lastNumber: number;
|
||||
}
|
||||
```
|
||||
|
||||
### 2.4. Redis Lock Service
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/services/document-numbering-lock.service.ts
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import Redlock from 'redlock';
|
||||
import { InjectRedis } from '@nestjs-modules/ioredis';
|
||||
import { Redis } from 'ioredis';
|
||||
|
||||
interface CounterKey {
|
||||
projectId: number;
|
||||
originatorOrgId: number;
|
||||
recipientOrgId: number | null;
|
||||
correspondenceTypeId: number;
|
||||
subTypeId: number;
|
||||
rfaTypeId: number;
|
||||
disciplineId: number;
|
||||
year: number;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class DocumentNumberingLockService {
|
||||
private readonly logger = new Logger(DocumentNumberingLockService.name);
|
||||
private redlock: Redlock;
|
||||
|
||||
constructor(@InjectRedis() private readonly redis: Redis) {
|
||||
this.redlock = new Redlock([redis], {
|
||||
driftFactor: 0.01,
|
||||
retryCount: 5,
|
||||
retryDelay: 100,
|
||||
retryJitter: 50,
|
||||
});
|
||||
}
|
||||
|
||||
async acquireLock(counterKey: CounterKey): Promise<Redlock.Lock> {
|
||||
const lockKey = this.buildLockKey(counterKey);
|
||||
const ttl = 5000; // 5 วินาที
|
||||
|
||||
try {
|
||||
const lock = await this.redlock.acquire([lockKey], ttl);
|
||||
this.logger.debug(`Acquired lock: ${lockKey}`);
|
||||
return lock;
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to acquire lock: ${lockKey}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async releaseLock(lock: Redlock.Lock): Promise<void> {
|
||||
try {
|
||||
await lock.release();
|
||||
this.logger.debug('Released lock');
|
||||
} catch (error) {
|
||||
this.logger.warn('Failed to release lock (may have expired)', error);
|
||||
}
|
||||
}
|
||||
|
||||
private buildLockKey(key: CounterKey): string {
|
||||
return `lock:docnum:${key.projectId}:${key.originatorOrgId}:` +
|
||||
`${key.recipientOrgId ?? 0}:${key.correspondenceTypeId}:` +
|
||||
`${key.subTypeId}:${key.rfaTypeId}:${key.disciplineId}:${key.year}`;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.4. Counter Service
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/services/counter.service.ts
|
||||
import { Injectable, ConflictException, Logger } from '@nestjs/common';
|
||||
import { InjectRepository } from '@nestjs/typeorm';
|
||||
import { Repository, DataSource } from 'typeorm';
|
||||
import { DocumentNumberCounter } from '../entities/document-number-counter.entity';
|
||||
import { OptimisticLockVersionMismatchError } from 'typeorm';
|
||||
|
||||
@Injectable()
|
||||
export class CounterService {
|
||||
private readonly logger = new Logger(CounterService.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(DocumentNumberCounter)
|
||||
private counterRepo: Repository<DocumentNumberCounter>,
|
||||
private dataSource: DataSource,
|
||||
) {}
|
||||
|
||||
async incrementCounter(counterKey: CounterKey): Promise<number> {
|
||||
const MAX_RETRIES = 2;
|
||||
|
||||
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
return await this.dataSource.transaction(async (manager) => {
|
||||
// ใช้ Optimistic Locking
|
||||
const counter = await manager.findOne(DocumentNumberCounter, {
|
||||
where: this.buildWhereClause(counterKey),
|
||||
});
|
||||
|
||||
if (!counter) {
|
||||
// สร้าง counter ใหม่
|
||||
const newCounter = manager.create(DocumentNumberCounter, {
|
||||
...counterKey,
|
||||
lastNumber: 1,
|
||||
version: 0,
|
||||
});
|
||||
await manager.save(newCounter);
|
||||
return 1;
|
||||
}
|
||||
|
||||
counter.lastNumber += 1;
|
||||
await manager.save(counter); // Auto-check version
|
||||
return counter.lastNumber;
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof OptimisticLockVersionMismatchError) {
|
||||
this.logger.warn(
|
||||
`Version conflict, retry ${attempt + 1}/${MAX_RETRIES}`,
|
||||
);
|
||||
if (attempt === MAX_RETRIES - 1) {
|
||||
throw new ConflictException('เลขที่เอกสารถูกเปลี่ยน กรุณาลองใหม่');
|
||||
}
|
||||
continue;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private buildWhereClause(key: CounterKey) {
|
||||
return {
|
||||
projectId: key.projectId,
|
||||
originatorOrganizationId: key.originatorOrgId,
|
||||
recipientOrganizationId: key.recipientOrgId,
|
||||
correspondenceTypeId: key.correspondenceTypeId,
|
||||
subTypeId: key.subTypeId,
|
||||
rfaTypeId: key.rfaTypeId,
|
||||
disciplineId: key.disciplineId,
|
||||
currentYear: key.year,
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2.5. Main Service with Retry Logic
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/services/document-numbering.service.ts
|
||||
import { Injectable, ServiceUnavailableException, Logger } from '@nestjs/common';
|
||||
import { DocumentNumberingLockService } from './document-numbering-lock.service';
|
||||
import { CounterService } from './counter.service';
|
||||
import { AuditService } from './audit.service';
|
||||
import { RedisConnectionError } from 'ioredis';
|
||||
|
||||
@Injectable()
|
||||
export class DocumentNumberingService {
|
||||
private readonly logger = new Logger(DocumentNumberingService.name);
|
||||
|
||||
constructor(
|
||||
private lockService: DocumentNumberingLockService,
|
||||
private counterService: CounterService,
|
||||
private auditService: AuditService,
|
||||
) {}
|
||||
|
||||
async generateDocumentNumber(dto: GenerateNumberDto): Promise<string> {
|
||||
const startTime = Date.now();
|
||||
let lockWaitMs = 0;
|
||||
let retryCount = 0;
|
||||
let fallbackUsed = 'NONE';
|
||||
|
||||
try {
|
||||
// พยายามใช้ Redis lock ก่อน
|
||||
return await this.generateWithRedisLock(dto);
|
||||
} catch (error) {
|
||||
if (error instanceof RedisConnectionError) {
|
||||
// Fallback: ใช้ database lock
|
||||
this.logger.warn('Redis unavailable, falling back to DB lock');
|
||||
fallbackUsed = 'DB_LOCK';
|
||||
return await this.generateWithDbLock(dto);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
// บันทึก audit log
|
||||
await this.auditService.logGeneration({
|
||||
documentId: dto.documentId,
|
||||
counterKey: dto.counterKey,
|
||||
lockWaitMs,
|
||||
totalDurationMs: Date.now() - startTime,
|
||||
fallbackUsed,
|
||||
retryCount,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async generateWithRedisLock(dto: GenerateNumberDto): Promise<string> {
|
||||
const lock = await this.lockService.acquireLock(dto.counterKey);
|
||||
|
||||
try {
|
||||
const nextNumber = await this.counterService.incrementCounter(dto.counterKey);
|
||||
return this.formatNumber(dto.template, nextNumber, dto.counterKey);
|
||||
} finally {
|
||||
await this.lockService.releaseLock(lock);
|
||||
}
|
||||
}
|
||||
|
||||
private async generateWithDbLock(dto: GenerateNumberDto): Promise<string> {
|
||||
// ใช้ pessimistic lock
|
||||
// Implementation details...
|
||||
}
|
||||
|
||||
private formatNumber(template: string, seq: number, key: CounterKey): string {
|
||||
// Template formatting logic
|
||||
// Example: `คคง.-สคฉ.3-0001-2568`
|
||||
return template
|
||||
.replace('{SEQ:4}', seq.toString().padStart(4, '0'))
|
||||
.replace('{YEAR:B.E.}', (key.year + 543).toString());
|
||||
// ... more replacements
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. Template Validation
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/validators/template.validator.ts
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
interface ValidationResult {
|
||||
valid: boolean;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class TemplateValidator {
|
||||
private readonly ALLOWED_TOKENS = [
|
||||
'PROJECT', 'ORIGINATOR', 'RECIPIENT', 'CORR_TYPE',
|
||||
'SUB_TYPE', 'RFA_TYPE', 'DISCIPLINE', 'SEQ', 'YEAR', 'REV',
|
||||
];
|
||||
|
||||
validate(template: string, correspondenceType: string): ValidationResult {
|
||||
const tokens = this.extractTokens(template);
|
||||
const errors: string[] = [];
|
||||
|
||||
// ตรวจสอบ Token ที่ไม่รู้จัก
|
||||
for (const token of tokens) {
|
||||
if (!this.ALLOWED_TOKENS.includes(token.name)) {
|
||||
errors.push(`Unknown token: {${token.name}}`);
|
||||
}
|
||||
}
|
||||
|
||||
// กฎพิเศษสำหรับแต่ละประเภท
|
||||
if (correspondenceType === 'RFA') {
|
||||
if (!tokens.some((t) => t.name === 'PROJECT')) {
|
||||
errors.push('RFA template ต้องมี {PROJECT}');
|
||||
}
|
||||
if (!tokens.some((t) => t.name === 'DISCIPLINE')) {
|
||||
errors.push('RFA template ต้องมี {DISCIPLINE}');
|
||||
}
|
||||
}
|
||||
|
||||
if (correspondenceType === 'TRANSMITTAL') {
|
||||
if (!tokens.some((t) => t.name === 'SUB_TYPE')) {
|
||||
errors.push('TRANSMITTAL template ต้องมี {SUB_TYPE}');
|
||||
}
|
||||
}
|
||||
|
||||
// ทุก template ต้องมี {SEQ}
|
||||
if (!tokens.some((t) => t.name.startsWith('SEQ'))) {
|
||||
errors.push('Template ต้องมี {SEQ:n}');
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
|
||||
private extractTokens(template: string) {
|
||||
const regex = /\{([^}]+)\}/g;
|
||||
const tokens: Array<{ name: string; full: string }> = [];
|
||||
let match;
|
||||
|
||||
while ((match = regex.exec(template)) !== null) {
|
||||
const tokenName = match[1].split(':')[0]; // SEQ:4 → SEQ
|
||||
tokens.push({ name: tokenName, full: match[1] });
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. BullMQ Job for Counter Reset
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/jobs/counter-reset.job.ts
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
|
||||
@Processor('document-numbering')
|
||||
@Injectable()
|
||||
export class CounterResetJob extends WorkerHost {
|
||||
private readonly logger = new Logger(CounterResetJob.name);
|
||||
|
||||
@Cron('0 0 1 1 *') // 1 Jan every year at 00:00
|
||||
async handleYearlyReset() {
|
||||
const newYear = new Date().getFullYear();
|
||||
|
||||
// ไม่ต้อง reset counter เพราะ counter แยกตาม current_year อยู่แล้ว
|
||||
// แค่เตรียม counter สำหรับปีใหม่
|
||||
this.logger.log(`Year changed to ${newYear}, counters are ready`);
|
||||
|
||||
// สามารถทำ cleanup counter ปีเก่าได้ (optional)
|
||||
// await this.cleanupOldCounters(newYear - 5); // เก็บ 5 ปี
|
||||
}
|
||||
|
||||
async process() {
|
||||
// BullMQ job processing
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 5. API Controller
|
||||
|
||||
### 5.1. Main Controller (`/document-numbering`)
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/document-numbering.controller.ts
|
||||
import {
|
||||
Controller, Get, Post, Patch,
|
||||
Body, Param, Query, UseGuards, ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { RbacGuard } from '../../common/guards/rbac.guard';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { DocumentNumberingService } from './document-numbering.service';
|
||||
import { PreviewNumberDto } from './dto/preview-number.dto';
|
||||
|
||||
@Controller('document-numbering')
|
||||
@UseGuards(JwtAuthGuard, RbacGuard)
|
||||
export class DocumentNumberingController {
|
||||
constructor(private readonly numberingService: DocumentNumberingService) {}
|
||||
|
||||
// --- Logs ---
|
||||
|
||||
@Get('logs/audit')
|
||||
@RequirePermission('system.view_logs')
|
||||
getAuditLogs(@Query('limit') limit?: number) {
|
||||
return this.numberingService.getAuditLogs(limit ? Number(limit) : 100);
|
||||
}
|
||||
|
||||
@Get('logs/errors')
|
||||
@RequirePermission('system.view_logs')
|
||||
getErrorLogs(@Query('limit') limit?: number) {
|
||||
return this.numberingService.getErrorLogs(limit ? Number(limit) : 100);
|
||||
}
|
||||
|
||||
// --- Sequences / Counters ---
|
||||
|
||||
@Get('sequences')
|
||||
@RequirePermission('correspondence.read')
|
||||
getSequences(@Query('projectId') projectId?: number) {
|
||||
return this.numberingService.getSequences(projectId ? Number(projectId) : undefined);
|
||||
}
|
||||
|
||||
@Patch('counters/:id')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async updateCounter(
|
||||
@Param('id', ParseIntPipe) id: number,
|
||||
@Body('sequence') sequence: number
|
||||
) {
|
||||
return this.numberingService.setCounterValue(id, sequence);
|
||||
}
|
||||
|
||||
// --- Preview ---
|
||||
|
||||
@Post('preview')
|
||||
@RequirePermission('correspondence.read')
|
||||
async previewNumber(@Body() dto: PreviewNumberDto) {
|
||||
return this.numberingService.previewNumber(dto);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2. Admin Controller (`/admin/document-numbering`)
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/document-numbering-admin.controller.ts
|
||||
import {
|
||||
Controller, Get, Post, Delete, Body, Param, Query,
|
||||
UseGuards, ParseIntPipe,
|
||||
} from '@nestjs/common';
|
||||
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
|
||||
import { RbacGuard } from '../../common/guards/rbac.guard';
|
||||
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
|
||||
import { DocumentNumberingService } from './document-numbering.service';
|
||||
|
||||
@Controller('admin/document-numbering')
|
||||
@UseGuards(JwtAuthGuard, RbacGuard)
|
||||
export class DocumentNumberingAdminController {
|
||||
constructor(private readonly service: DocumentNumberingService) {}
|
||||
|
||||
// --- Template Management ---
|
||||
|
||||
@Get('templates')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async getTemplates(@Query('projectId') projectId?: number) {
|
||||
if (projectId) {
|
||||
return this.service.getTemplatesByProject(projectId);
|
||||
}
|
||||
return this.service.getTemplates();
|
||||
}
|
||||
|
||||
@Post('templates')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async saveTemplate(@Body() dto: any) {
|
||||
return this.service.saveTemplate(dto);
|
||||
}
|
||||
|
||||
@Delete('templates/:id')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async deleteTemplate(@Param('id', ParseIntPipe) id: number) {
|
||||
await this.service.deleteTemplate(id);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// --- Metrics ---
|
||||
|
||||
@Get('metrics')
|
||||
@RequirePermission('system.view_logs')
|
||||
async getMetrics() {
|
||||
const audit = await this.service.getAuditLogs(50);
|
||||
const errors = await this.service.getErrorLogs(50);
|
||||
return { audit, errors };
|
||||
}
|
||||
|
||||
// --- Admin Operations ---
|
||||
|
||||
@Post('manual-override')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async manualOverride(@Body() dto: {
|
||||
projectId: number;
|
||||
correspondenceTypeId: number | null;
|
||||
year: number;
|
||||
newValue: number;
|
||||
}) {
|
||||
return this.service.manualOverride(dto);
|
||||
}
|
||||
|
||||
@Post('void-and-replace')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async voidAndReplace(@Body() dto: {
|
||||
documentId: number;
|
||||
reason: string;
|
||||
}) {
|
||||
return this.service.voidAndReplace(dto);
|
||||
}
|
||||
|
||||
@Post('cancel')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async cancelNumber(@Body() dto: {
|
||||
documentNumber: string;
|
||||
reason: string;
|
||||
}) {
|
||||
return this.service.cancelNumber(dto);
|
||||
}
|
||||
|
||||
@Post('bulk-import')
|
||||
@RequirePermission('system.manage_settings')
|
||||
async bulkImport(@Body() items: any[]) {
|
||||
return this.service.bulkImport(items);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 5.3. API Endpoints Summary
|
||||
|
||||
| Endpoint | Method | Permission | Description |
|
||||
| -------------------------------------------- | ------ | ------------------------ | --------------------------------- |
|
||||
| `/document-numbering/logs/audit` | GET | `system.view_logs` | Get audit logs |
|
||||
| `/document-numbering/logs/errors` | GET | `system.view_logs` | Get error logs |
|
||||
| `/document-numbering/sequences` | GET | `correspondence.read` | Get counter sequences |
|
||||
| `/document-numbering/counters/:id` | PATCH | `system.manage_settings` | Update counter value |
|
||||
| `/document-numbering/preview` | POST | `correspondence.read` | Preview number without generating |
|
||||
| `/admin/document-numbering/templates` | GET | `system.manage_settings` | Get all templates |
|
||||
| `/admin/document-numbering/templates` | POST | `system.manage_settings` | Create/update template |
|
||||
| `/admin/document-numbering/templates/:id` | DELETE | `system.manage_settings` | Delete template |
|
||||
| `/admin/document-numbering/metrics` | GET | `system.view_logs` | Get metrics (audit + errors) |
|
||||
| `/admin/document-numbering/manual-override` | POST | `system.manage_settings` | Override counter value |
|
||||
| `/admin/document-numbering/void-and-replace` | POST | `system.manage_settings` | Void and replace number |
|
||||
| `/admin/document-numbering/cancel` | POST | `system.manage_settings` | Cancel a number |
|
||||
| `/admin/document-numbering/bulk-import` | POST | `system.manage_settings` | Bulk import counters |
|
||||
|
||||
## 6. Module Configuration
|
||||
|
||||
```typescript
|
||||
// File: src/modules/document-numbering/document-numbering.module.ts
|
||||
import { Module } from '@nestjs/common';
|
||||
import { TypeOrmModule } from '@nestjs/typeorm';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { DocumentNumberCounter } from './entities/document-number-counter.entity';
|
||||
import { DocumentNumberAudit } from './entities/document-number-audit.entity';
|
||||
import { DocumentNumberError } from './entities/document-number-error.entity';
|
||||
import { DocumentNumberingService } from './services/document-numbering.service';
|
||||
import { DocumentNumberingLockService } from './services/document-numbering-lock.service';
|
||||
import { CounterService } from './services/counter.service';
|
||||
import { AuditService } from './services/audit.service';
|
||||
import { TemplateValidator } from './validators/template.validator';
|
||||
import { CounterResetJob } from './jobs/counter-reset.job';
|
||||
import { DocumentNumberingController } from './controllers/document-numbering.controller';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
TypeOrmModule.forFeature([
|
||||
DocumentNumberCounter,
|
||||
DocumentNumberAudit,
|
||||
DocumentNumberError,
|
||||
]),
|
||||
BullModule.registerQueue({
|
||||
name: 'document-numbering',
|
||||
}),
|
||||
ThrottlerModule.forRoot({
|
||||
ttl: 60,
|
||||
limit: 10,
|
||||
}),
|
||||
],
|
||||
controllers: [DocumentNumberingController],
|
||||
providers: [
|
||||
DocumentNumberingService,
|
||||
DocumentNumberingLockService,
|
||||
CounterService,
|
||||
AuditService,
|
||||
TemplateValidator,
|
||||
CounterResetJob,
|
||||
],
|
||||
exports: [DocumentNumberingService],
|
||||
})
|
||||
export class DocumentNumberingModule {}
|
||||
```
|
||||
|
||||
## 7. Environment Configuration
|
||||
|
||||
```typescript
|
||||
// .env.example
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
|
||||
DB_HOST=localhost
|
||||
DB_PORT=3306
|
||||
DB_USERNAME=lcbp3
|
||||
DB_PASSWORD=
|
||||
DB_DATABASE=lcbp3_db
|
||||
DB_POOL_SIZE=20
|
||||
|
||||
# Prometheus
|
||||
PROMETHEUS_PORT=9090
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [Requirements](file:///e:/np-dms/lcbp3/specs/01-requirements/03.11-document-numbering.md)
|
||||
- [Operations Guide](file:///e:/np-dms/lcbp3/specs/04-operations/document-numbering-operations.md)
|
||||
- [Backend Guidelines](file:///e:/np-dms/lcbp3/specs/03-implementation/backend-guidelines.md)
|
||||
17
specs/99-archives/docs/backup/features.bak
Normal file
17
specs/99-archives/docs/backup/features.bak
Normal file
@@ -0,0 +1,17 @@
|
||||
ฟีเจอร์ขั้นสูง (Advanced Features)
|
||||
Error Handling: ใช้ Global Exception Filter เพื่อจัดการ Error และส่ง Response ที่เป็นมาตรฐาน
|
||||
|
||||
Logging: ใช้ Winston สำหรับ Structured Logging และบันทึก Error ลงไฟล์
|
||||
|
||||
Testing: มีโครงสร้างสำหรับ Unit Test และ E2E Test ด้วย Jest และ Supertest
|
||||
|
||||
Performance: ใช้ CacheModule สำหรับ Caching ข้อมูลที่เรียกใช้บ่อย
|
||||
|
||||
Security:
|
||||
|
||||
Rate Limiting: ใช้ ThrottlerModule เพื่อป้องกัน Brute-force attack
|
||||
|
||||
Secret Management: แนะนำให้ใช้ Environment Variable ของ Docker แทนไฟล์ .env ใน Production
|
||||
|
||||
API Documentation: สร้างเอกสาร API อัตโนมัติด้วย @nestjs/swagger และเข้าถึงได้ที่ /api-docs
|
||||
|
||||
1875
specs/99-archives/docs/backup/lcbp3-v1.5.1-schema.sql
Normal file
1875
specs/99-archives/docs/backup/lcbp3-v1.5.1-schema.sql
Normal file
File diff suppressed because it is too large
Load Diff
3225
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-basic.sql
Normal file
3225
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-basic.sql
Normal file
File diff suppressed because it is too large
Load Diff
2569
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-contractdrawing.sql
Normal file
2569
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-contractdrawing.sql
Normal file
File diff suppressed because it is too large
Load Diff
1067
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-permissions.sql
Normal file
1067
specs/99-archives/docs/backup/lcbp3-v1.5.1-seed-permissions.sql
Normal file
File diff suppressed because it is too large
Load Diff
192
specs/99-archives/docs/backup/workflow.bak
Normal file
192
specs/99-archives/docs/backup/workflow.bak
Normal file
@@ -0,0 +1,192 @@
|
||||
## Workflow ระดับ Project (correspondence_routing_steps, technical_doc_workflows): คือ "การเดินทาง" ของเอกสาร ระหว่างองค์กร (เช่น จากผู้รับเหมา -> ไปยังที่ปรึกษา -> ไปยังเจ้าของโครงการ)
|
||||
|
||||
## Workflow ระดับ Organization (Circulation): คือ "การแจกจ่าย" เอกสาร ภายในองค์กรของคุณเอง หลังจากที่คุณได้รับเอกสารนั้นมาแล้ว (เช่น เอกสารมาถึง Document Control แล้วต้องส่งต่อให้ใครบ้างในบริษัท)
|
||||
|
||||
circulation_templates: ตารางหลักสำหรับเก็บชื่อแม่แบบ
|
||||
circulation_template_assignees: ตารางสำหรับเก็บ "รายชื่อผู้รับผิดชอบ" ที่ถูกกำหนดไว้ในแต่ละแม่แบบ
|
||||
|
||||
Workflow การทำงานใน Frontend
|
||||
1. หน้า Admin Panel: จะต้องมีเมนูใหม่สำหรับให้ Admin หรือผู้มีสิทธิ์ เข้าไป สร้าง/แก้ไข/ลบ แม่แบบใบเวียน (circulation_templates) สำหรับองค์กรของตนเองได้
|
||||
|
||||
2. หน้าที่สร้างใบเวียน (Create Circulation Dialog):
|
||||
* ที่ด้านบนสุดของฟอร์ม จะมี Dropdown ใหม่ ปรากฏขึ้นมา เขียนว่า "ใช้แม่แบบ (Use Template)"
|
||||
* ใน Dropdown นี้ จะแสดงรายชื่อแม่แบบทั้งหมดที่องค์กรนั้นๆ สร้างไว้
|
||||
* เมื่อผู้ใช้เลือกแม่แบบ:
|
||||
** ระบบจะยิง API ไปดึงรายชื่อผู้รับผิดชอบจากตาราง circulation_template_assignees
|
||||
** จากนั้น JavaScript จะทำการเติมข้อมูล (Auto-populate) ลงในช่อง "Main", "Action", และ "Information" ให้โดยอัตโนมัติ
|
||||
* ผู้ใช้ยังสามารถ แก้ไข/เพิ่มเติม/ลบ รายชื่อผู้รับผิดชอบได้ตามต้องการ ก่อนที่จะกดสร้างใบเวียนจริง
|
||||
|
||||
|
||||
การจัดการข้อมูล JSON จะเกิดขึ้นใน 3 ส่วนหลักๆ คือ Backend, Frontend, และ Database ครับ
|
||||
|
||||
## 1. การจัดการในฝั่ง Backend (NestJS)
|
||||
นี่คือส่วนที่ทำหน้าที่หลักในการสร้างและอ่านข้อมูล JSON อย่างเป็นระบบและปลอดภัย
|
||||
|
||||
1.1 การแก้ไข Entity
|
||||
เราจะแก้ไข Correspondence entity โดยเพิ่มคอลัมน์ details เข้าไป และลบ Entity ย่อยๆ ที่ไม่ใช้ออก
|
||||
|
||||
src/correspondences/entities/correspondence.entity.ts
|
||||
@Entity('correspondences')
|
||||
export class Correspondence {
|
||||
// ... (คอลัมน์เดิมทั้งหมด: id, document_number, title, etc.)
|
||||
|
||||
@Column({
|
||||
type: 'json', // ◀️ กำหนดประเภทข้อมูลเป็น JSON
|
||||
nullable: true,
|
||||
comment: 'เก็บข้อมูลเฉพาะของเอกสารแต่ละประเภทในรูปแบบ JSON'
|
||||
})
|
||||
details: any; // ◀️ ใช้ type 'any' หรือสร้าง Interface/Type ที่ซับซ้อนขึ้น
|
||||
}
|
||||
|
||||
1.2 การสร้าง DTOs สำหรับแต่ละประเภทเอกสาร
|
||||
เพื่อรักษาความถูกต้องของข้อมูล (Validation) เราจะสร้าง DTO แยกสำหรับเอกสารแต่ละประเภท
|
||||
|
||||
ตัวอย่าง src/correspondences/dto/create-letter.dto.ts:
|
||||
|
||||
TypeScript
|
||||
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
// DTO สำหรับข้อมูลใน details ของ Letter
|
||||
class LetterDetailsDto {
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
attention_to: string;
|
||||
|
||||
@ApiProperty()
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
signatory_name: string;
|
||||
}
|
||||
|
||||
// DTO หลักสำหรับสร้าง Letter
|
||||
export class CreateLetterDto {
|
||||
@ApiProperty({ description: "ข้อมูลพื้นฐานของเอกสาร" })
|
||||
@ValidateNested() // ◀️ บอกให้ class-validator ตรวจสอบ object ข้างในด้วย
|
||||
@Type(() => CreateCorrespondenceDto) // ◀️ ใช้ DTO พื้นฐานร่วมกัน
|
||||
base_data: CreateCorrespondenceDto;
|
||||
|
||||
@ApiProperty({ description: "ข้อมูลเฉพาะของ Letter" })
|
||||
@ValidateNested()
|
||||
@Type(() => LetterDetailsDto)
|
||||
details: LetterDetailsDto;
|
||||
}
|
||||
|
||||
1.3 การสร้าง API Endpoint และ Logic ใน Service
|
||||
เราจะสร้าง Endpoint แยกสำหรับสร้างเอกสารแต่ละประเภทเพื่อความชัดเจน
|
||||
|
||||
ใน CorrespondencesController:
|
||||
|
||||
TypeScript
|
||||
|
||||
@Post('letter')
|
||||
@ApiOperation({ summary: 'Create a new Letter' })
|
||||
createLetter(@Body() createLetterDto: CreateLetterDto, @Req() req: Request) {
|
||||
const user = req.user as any;
|
||||
return this.correspondencesService.createTypedCorrespondence(
|
||||
createLetterDto.base_data,
|
||||
createLetterDto.details,
|
||||
user
|
||||
);
|
||||
}
|
||||
ใน CorrespondencesService:
|
||||
|
||||
TypeScript
|
||||
|
||||
async createTypedCorrespondence(baseData: CreateCorrespondenceDto, details: any, user: User): Promise<Correspondence> {
|
||||
// ... (โค้ดตรวจสอบสิทธิ์เหมือนเดิม)
|
||||
|
||||
const newCorrespondence = this.correspondenceRepository.create({
|
||||
...baseData, // ข้อมูลพื้นฐาน (เลขที่เอกสาร, ชื่อเรื่อง, etc.)
|
||||
details: details, // ◀️ นำ object ของ details มาใส่ในคอลัมน์ JSON โดยตรง
|
||||
created_by_user_id: user.user_id,
|
||||
originator_org_id: user.org_id,
|
||||
status_id: 1, // 'Draft'
|
||||
});
|
||||
|
||||
return this.correspondenceRepository.save(newCorrespondence);
|
||||
}
|
||||
## 2. การจัดการในฝั่ง Frontend (Next.js / React)
|
||||
Frontend จะทำหน้าที่แสดงฟอร์มที่ถูกต้องตามประเภทเอกสาร และส่งข้อมูลในรูปแบบที่ Backend ต้องการ
|
||||
|
||||
2.1 การแสดงฟอร์มแบบไดนามิก (Dynamic Forms)
|
||||
ในหน้า "Create Correspondence" เมื่อผู้ใช้เลือกประเภทเอกสารจาก Dropdown เราจะใช้ State เพื่อแสดงฟอร์มที่ถูกต้อง
|
||||
|
||||
TypeScript
|
||||
|
||||
const [docType, setDocType] = useState('LETTER');
|
||||
|
||||
// ...
|
||||
|
||||
const renderDetailFields = () => {
|
||||
switch (docType) {
|
||||
case 'LETTER':
|
||||
return (
|
||||
<>
|
||||
{/* ฟิลด์สำหรับ Attention To, Signatory */}
|
||||
</>
|
||||
);
|
||||
case 'RFI':
|
||||
return (
|
||||
<>
|
||||
{/* ฟิลด์สำหรับ Question, Required By Date */}
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form>
|
||||
{/* ฟิลด์พื้นฐาน (Document Number, Title) */}
|
||||
{/* Dropdown เลือกประเภทเอกสาร */}
|
||||
{renderDetailFields()} {/* ◀️ แสดงฟิลด์เฉพาะทางที่นี่ */}
|
||||
</form>
|
||||
);
|
||||
2.2 การส่งข้อมูล
|
||||
เมื่อผู้ใช้กด Submit เราจะรวบรวมข้อมูลจากฟอร์มให้เป็นโครงสร้าง JSON ที่ Backend ต้องการ
|
||||
|
||||
JavaScript
|
||||
|
||||
const handleSubmit = () => {
|
||||
// รวบรวมข้อมูลพื้นฐาน
|
||||
const base_data = {
|
||||
document_number: '...',
|
||||
title: '...',
|
||||
// ...
|
||||
};
|
||||
|
||||
// รวบรวมข้อมูลเฉพาะทาง
|
||||
const details = {
|
||||
attention_to: '...',
|
||||
signatory_name: '...',
|
||||
};
|
||||
|
||||
// ส่งข้อมูลไปที่ API Endpoint ที่ถูกต้อง
|
||||
fetch('/api/correspondences/letter', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ base_data, details }),
|
||||
});
|
||||
}
|
||||
## 3. การจัดการในระดับฐานข้อมูล (MariaDB)
|
||||
แม้ว่าเราจะไม่ค่อยได้ Query ข้อมูล JSON โดยตรงผ่าน SQL บ่อยนัก แต่ก็สามารถทำได้เมื่อจำเป็น (เช่น สำหรับการทำรายงานที่ซับซ้อน)
|
||||
|
||||
ตัวอย่าง: ค้นหาเอกสาร Letter ทั้งหมดที่ส่งถึง "Mr. John Doe"
|
||||
|
||||
SQL
|
||||
|
||||
SELECT
|
||||
corr_id,
|
||||
document_number,
|
||||
details
|
||||
FROM
|
||||
correspondences
|
||||
WHERE
|
||||
type_id = (SELECT type_id FROM correspondence_types WHERE type_code = 'LETTER') -- กรองเฉพาะ Letter
|
||||
AND JSON_VALUE(details, '$.attention_to') = 'Mr. John Doe'; -- ◀️ ค้นหาค่าใน JSON
|
||||
การจัดการข้อมูลด้วยวิธีนี้จะทำให้ระบบของคุณมีความ
|
||||
|
||||
|
||||
Reference in New Issue
Block a user