Main: revise specs to 1.5.0 (completed)
This commit is contained in:
@@ -1,58 +1,487 @@
|
||||
# 📋 Architecture Specification v1.5.0
|
||||
|
||||
## Status: first-draft
|
||||
|
||||
**Date:** 2025-11-30
|
||||
> **สถาปัตยกรรมระบบ LCBP3-DMS**
|
||||
>
|
||||
> เอกสารชุดนี้อธิบายสถาปัตยกรรมทางเทคนิคของระบบ Document Management System สำหรับโครงการท่าเรือแหลมฉบังระยะที่ 3
|
||||
|
||||
---
|
||||
|
||||
## 📑 Table of Contents
|
||||
## 📊 Document Status
|
||||
|
||||
1. [General Philosophy](./01-general-philosophy.md)
|
||||
2. [TypeScript](./02-typescript.md)
|
||||
3. [Functional Requirements](./03-functional-requirements.md)
|
||||
- [3.1 Project & Organization Management](./03.1-project-management.md)
|
||||
- [3.2 Correspondence Management](./03.2-correspondence.md)
|
||||
- [3.3 RFA Management](./03.3-rfa.md)
|
||||
- [3.4 Contract Drawing Management](./03.4-contract-drawing.md)
|
||||
- [3.5 Shop Drawing Management](./03.5-shop-drawing.md)
|
||||
- [3.6 Unified Workflow](./03.6-unified-workflow.md)
|
||||
- [3.7 Transmittals Management](./03.7-transmittals.md)
|
||||
- [3.8 Circulation Sheet Management](./03.8-circulation-sheet.md)
|
||||
- [3.9 Revisions Management](./03.9-revisions.md)
|
||||
- [3.10 File Handling](./03.10-file-handling.md)
|
||||
- [3.11 Document Numbering](./03.11-document-numbering.md)
|
||||
- [3.12 JSON Details](./03.12-json-details.md)
|
||||
4. [Access Control & RBAC](./04-access-control.md)
|
||||
5. [UI/UX Requirements](./05-ui-ux.md)
|
||||
6. [Non-Functional Requirements](./06-non-functional.md)
|
||||
7. [Testing Requirements](./07-testing.md)
|
||||
| Attribute | Value |
|
||||
| ------------------ | -------------------------------- |
|
||||
| **Version** | 1.5.0 |
|
||||
| **Status** | First Draft |
|
||||
| **Last Updated** | 2025-11-30 |
|
||||
| **Owner** | Nattanin Peancharoen |
|
||||
| **Classification** | Internal Technical Documentation |
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Recent Changes
|
||||
## 📚 Table of Contents
|
||||
|
||||
See [CHANGELOG.md](../../CHANGELOG.md) for detailed version history.
|
||||
|
||||
### v1.4.5 (2025-11-30)
|
||||
|
||||
- ✅ Added comprehensive security requirements
|
||||
- ✅ Enhanced resilience patterns
|
||||
- ✅ Added performance targets
|
||||
- ⚠️ **Breaking:** Changed document numbering from stored procedure to app-level locking
|
||||
- [ภาพรวม](#-ภาพรวม-overview)
|
||||
- [เอกสารสถาปัตยกรรม](#-เอกสารสถาปัตยกรรม)
|
||||
- [หลักการออกแบบ](#-หลักการออกแบบ-architecture-principles)
|
||||
- [Technology Stack](#-technology-stack)
|
||||
- [Key Architectural Decisions](#-key-architectural-decisions)
|
||||
- [Related Documents](#-related-documents)
|
||||
|
||||
---
|
||||
|
||||
## 📊 Compliance Matrix
|
||||
## 🎯 ภาพรวม (Overview)
|
||||
|
||||
| Requirement | Status | Owner | Target Release |
|
||||
| ----------------------------- | ----------- | ------------ | -------------- |
|
||||
| FR-001: Correspondence CRUD | ✅ Done | Backend Team | v1.0 |
|
||||
| FR-002: RFA Workflow | In Progress | Backend Team | v1.1 |
|
||||
| NFR-001: API Response < 200ms | Planned | DevOps | v1.2 |
|
||||
ระบบ LCBP3-DMS ใช้สถาปัตยกรรมแบบ **Headless/API-First** ที่แยก Frontend และ Backend เป็นอิสระ โดยเน้นที่:
|
||||
|
||||
### Core Principles
|
||||
|
||||
1. **Data Integrity First** - ความถูกต้องของข้อมูลเป็นสิ่งสำคัญที่สุด
|
||||
2. **Security by Design** - ความปลอดภัยที่ทุกชั้น (Defense in Depth)
|
||||
3. **Scalability** - รองรับการเติบโตในอนาคต
|
||||
4. **Resilience** - ทนทานต่อความล้มเหลวและกู้คืนได้รวดเร็ว
|
||||
5. **Observability** - ติดตามและวิเคราะห์สถานะระบบได้ง่าย
|
||||
|
||||
### Architecture Style
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ Headless/API-First Architecture │
|
||||
├─────────────────────────────────────────┤
|
||||
│ │
|
||||
│ ┌──────────┐ ┌──────────┐ │
|
||||
│ │ Next.js │ ◄─────► │ NestJS │ │
|
||||
│ │ Frontend │ API │ Backend │ │
|
||||
│ └──────────┘ └────┬─────┘ │
|
||||
│ │ │
|
||||
│ ┌────▼─────┐ │
|
||||
│ │ MariaDB │ │
|
||||
│ │ + Redis │ │
|
||||
│ └──────────┘ │
|
||||
└─────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📬 Feedback
|
||||
## 📖 เอกสารสถาปัตยกรรม
|
||||
|
||||
Found issues? [Open an issue](https://github.com/your-org/lcbp3-dms/issues/new?template=spec-issue.md)
|
||||
### 1. [System Architecture](./system-architecture.md)
|
||||
|
||||
**สถาปัตยกรรมระบบโดยรวม**
|
||||
|
||||
- Infrastructure & Deployment (QNAP Server)
|
||||
- Network Architecture
|
||||
- Core Services (Frontend, Backend, Database, Cache, Search)
|
||||
- Backend Module Architecture (13 modules)
|
||||
- Data Flow Architecture
|
||||
- Security Architecture (6 layers)
|
||||
- Performance & Scalability
|
||||
- Resilience & Error Handling
|
||||
- Monitoring & Observability
|
||||
|
||||
**Key Topics:**
|
||||
|
||||
- ✅ Modular Design (Domain-Driven)
|
||||
- ✅ Two-Phase File Storage
|
||||
- ✅ Document Numbering (Double-Lock Mechanism)
|
||||
- ✅ Unified Workflow Engine
|
||||
- ✅ 4-Level RBAC
|
||||
- ✅ Caching Strategy
|
||||
- ✅ Rate Limiting
|
||||
|
||||
### 2. [API Design](./api-design.md)
|
||||
|
||||
**การออกแบบ API แบบ RESTful**
|
||||
|
||||
- API Design Principles (API-First Approach)
|
||||
- Authentication & Authorization (JWT + RBAC)
|
||||
- API Conventions (HTTP Methods, Status Codes)
|
||||
- Idempotency Implementation
|
||||
- Pagination, Filtering & Sorting
|
||||
- Security Features (Rate Limiting, Input Validation)
|
||||
- Core Module APIs (Correspondence, RFA, Drawing, etc.)
|
||||
- Performance Optimization
|
||||
- API Versioning Strategy
|
||||
|
||||
**Key Topics:**
|
||||
|
||||
- ✅ RESTful Best Practices
|
||||
- ✅ Idempotency-Key Header
|
||||
- ✅ Consistent Response Format
|
||||
- ✅ Comprehensive Error Handling
|
||||
- ✅ Rate Limiting per Role
|
||||
- ✅ File Upload Security
|
||||
|
||||
### 3. [Data Model](./data-model.md)
|
||||
|
||||
**โครงสร้างฐานข้อมูลและ Entity Relationships**
|
||||
|
||||
> [!NOTE]
|
||||
> เอกสารนี้อยู่ระหว่างการพัฒนา กรุณาอ้างอิง [Data Dictionary](../../docs/4_Data_Dictionary_V1_4_5.md) สำหรับข้อมูลละเอียด
|
||||
|
||||
**Expected Content:**
|
||||
|
||||
- Entity Relationship Diagrams (ERD)
|
||||
- Database Schema Design
|
||||
- Table Relationships
|
||||
- Indexing Strategy
|
||||
- JSON Schema Management
|
||||
- Virtual Columns for Performance
|
||||
- Partitioning Strategy
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ หลักการออกแบบ (Architecture Principles)
|
||||
|
||||
### 1. Separation of Concerns
|
||||
|
||||
```
|
||||
Frontend (Next.js) Backend (NestJS) Database (MariaDB)
|
||||
│ │ │
|
||||
├─ UI/UX ├─ Business Logic ├─ Data Storage
|
||||
├─ Client State ├─ API Endpoints ├─ Transactions
|
||||
├─ Validation ├─ Authorization ├─ Constraints
|
||||
└─ User Interaction └─ Data Processing └─ Relationships
|
||||
```
|
||||
|
||||
### 2. Modular Architecture
|
||||
|
||||
**Backend Modules (Domain-Driven):**
|
||||
|
||||
```
|
||||
Core Modules:
|
||||
├── CommonModule (Shared Services)
|
||||
├── AuthModule (JWT & Guards)
|
||||
└── UserModule (User Management)
|
||||
|
||||
Business Modules:
|
||||
├── ProjectModule (Projects & Contracts)
|
||||
├── CorrespondenceModule (Correspondences)
|
||||
├── RfaModule (RFA Management)
|
||||
├── DrawingModule (Shop & Contract Drawings)
|
||||
├── CirculationModule (Circulation Sheets)
|
||||
└── TransmittalModule (Transmittals)
|
||||
|
||||
Supporting Modules:
|
||||
├── WorkflowEngineModule (Unified Workflow)
|
||||
├── DocumentNumberingModule (Auto Numbering)
|
||||
├── SearchModule (Elasticsearch)
|
||||
├── MasterModule (Master Data)
|
||||
└── JsonSchemaModule (JSON Validation)
|
||||
```
|
||||
|
||||
### 3. Security Layers
|
||||
|
||||
```
|
||||
Layer 1: Network Security (SSL/TLS, Firewall)
|
||||
Layer 2: Application Security (Rate Limiting, CSRF, XSS)
|
||||
Layer 3: Authentication (JWT Tokens)
|
||||
Layer 4: Authorization (4-Level RBAC)
|
||||
Layer 5: Data Security (Encryption, Audit Logs)
|
||||
Layer 6: File Security (Virus Scanning, Access Control)
|
||||
```
|
||||
|
||||
### 4. Data Integrity Mechanisms
|
||||
|
||||
- **Two-Phase File Storage** - ป้องกัน Orphan Files
|
||||
- **Double-Lock Document Numbering** - ป้องกัน Race Condition
|
||||
- **Optimistic Locking** - Version Column สำหรับ Concurrent Updates
|
||||
- **Transaction Management** - ACID Compliance
|
||||
- **Idempotency** - ป้องกันการทำรายการซ้ำ
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Technology Stack
|
||||
|
||||
### Frontend Stack
|
||||
|
||||
| Component | Technology | Purpose |
|
||||
| -------------------- | -------------------------------- | ---------------------------- |
|
||||
| **Framework** | Next.js 14+ (App Router) | React Framework with SSR |
|
||||
| **Language** | TypeScript (ESM) | Type-safe JavaScript |
|
||||
| **Styling** | Tailwind CSS + PostCSS | Utility-first CSS |
|
||||
| **Components** | shadcn/ui | Accessible Component Library |
|
||||
| **State Management** | TanStack Query + React Hook Form | Server State + Form State |
|
||||
| **Validation** | Zod | Schema Validation |
|
||||
| **Testing** | Vitest + Playwright | Unit + E2E Testing |
|
||||
|
||||
### Backend Stack
|
||||
|
||||
| Component | Technology | Purpose |
|
||||
| ------------------ | ---------------- | ---------------------------- |
|
||||
| **Framework** | NestJS (Node.js) | Enterprise Node.js Framework |
|
||||
| **Language** | TypeScript (ESM) | Type-safe JavaScript |
|
||||
| **ORM** | TypeORM | Object-Relational Mapping |
|
||||
| **Authentication** | JWT + Passport | Token-based Auth |
|
||||
| **Authorization** | CASL | Permission Management |
|
||||
| **Validation** | class-validator | DTO Validation |
|
||||
| **Queue** | BullMQ (Redis) | Background Jobs |
|
||||
| **Documentation** | Swagger/OpenAPI | API Documentation |
|
||||
| **Testing** | Jest + Supertest | Unit + Integration Testing |
|
||||
|
||||
### Infrastructure Stack
|
||||
|
||||
| Component | Technology | Purpose |
|
||||
| -------------------- | ----------------------- | ----------------------- |
|
||||
| **Server** | QNAP TS-473A | Physical Server |
|
||||
| **Containerization** | Docker + Docker Compose | Container Orchestration |
|
||||
| **Reverse Proxy** | Nginx Proxy Manager | SSL/TLS + Routing |
|
||||
| **Database** | MariaDB 10.11 | Relational Database |
|
||||
| **Cache** | Redis 7.x | Caching + Locking |
|
||||
| **Search** | Elasticsearch | Full-text Search |
|
||||
| **Version Control** | Gitea | Self-hosted Git |
|
||||
| **Workflow** | n8n | Workflow Automation |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 Key Architectural Decisions
|
||||
|
||||
### ADR-001: Unified Workflow Engine
|
||||
|
||||
**Decision:** ใช้ Workflow Engine กลางเดียวสำหรับทุกประเภทเอกสาร
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- ลดความซ้ำซ้อนของ Code
|
||||
- ง่ายต่อการบำรุงรักษา
|
||||
- รองรับการเปลี่ยนแปลง Workflow ได้ยืดหยุ่น
|
||||
|
||||
**Implementation:**
|
||||
|
||||
- DSL-Based Configuration (JSON)
|
||||
- Workflow Versioning
|
||||
- Polymorphic Entity Relationships
|
||||
|
||||
**Related:** [specs/05-decisions/001-workflow-engine.md](../05-decisions/001-workflow-engine.md)
|
||||
|
||||
### ADR-002: Two-Phase File Storage
|
||||
|
||||
**Decision:** แยกการอัปโหลดไฟล์เป็น 2 ขั้นตอน (Upload → Commit)
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- ป้องกัน Orphan Files
|
||||
- รักษา Data Integrity
|
||||
- รองรับ Transaction Rollback
|
||||
|
||||
**Implementation:**
|
||||
|
||||
1. Phase 1: Upload to `temp/` → Return `temp_id`
|
||||
2. Phase 2: Commit to `permanent/` when operation succeeds
|
||||
3. Cleanup: Cron Job ลบไฟล์ค้างใน `temp/` > 24h
|
||||
|
||||
**Related:** [specs/05-decisions/002-file-storage.md](../05-decisions/002-file-storage.md)
|
||||
|
||||
### ADR-003: Document Numbering Strategy
|
||||
|
||||
**Decision:** ใช้ Application-Level Locking แทน Database Stored Procedure
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- ยืดหยุ่นกว่า (Token-Based Generator)
|
||||
- ง่ายต่อการ Debug
|
||||
- รองรับ Complex Numbering Rules
|
||||
|
||||
**Implementation:**
|
||||
|
||||
- Layer 1: Redis Distributed Lock
|
||||
- Layer 2: Optimistic Database Lock (`@VersionColumn()`)
|
||||
- Retry with Exponential Backoff
|
||||
|
||||
### ADR-004: 4-Level RBAC
|
||||
|
||||
**Decision:** ใช้ Permission Hierarchy 4 ระดับ (Global, Organization, Project, Contract)
|
||||
|
||||
**Rationale:**
|
||||
|
||||
- รองรับโครงสร้างองค์กรที่ซับซ้อน
|
||||
- ยืดหยุ่นในการกำหนดสิทธิ์
|
||||
- Most Permissive Rule (ใช้สิทธิ์สูงสุดที่มี)
|
||||
|
||||
**Implementation:**
|
||||
|
||||
- CASL for Permission Rules
|
||||
- Redis Cache for Performance
|
||||
- Permission Checking at Guard Level
|
||||
|
||||
---
|
||||
|
||||
## 📊 Architecture Diagrams
|
||||
|
||||
### High-Level System Architecture
|
||||
|
||||
```mermaid
|
||||
graph TB
|
||||
subgraph "Client Layer"
|
||||
Browser[Web Browser]
|
||||
Mobile[Mobile Browser]
|
||||
end
|
||||
|
||||
subgraph "Presentation Layer"
|
||||
NPM[Nginx Proxy Manager<br/>SSL/TLS Termination]
|
||||
end
|
||||
|
||||
subgraph "Application Layer"
|
||||
Frontend[Next.js Frontend<br/>lcbp3.np-dms.work]
|
||||
Backend[NestJS Backend<br/>backend.np-dms.work]
|
||||
end
|
||||
|
||||
subgraph "Data Layer"
|
||||
MariaDB[(MariaDB 10.11<br/>Primary Database)]
|
||||
Redis[(Redis<br/>Cache + Queue)]
|
||||
Elastic[Elasticsearch<br/>Search Engine]
|
||||
Storage[File Storage<br/>/share/dms-data]
|
||||
end
|
||||
|
||||
subgraph "Integration Layer"
|
||||
N8N[n8n Workflow]
|
||||
Email[Email Service]
|
||||
Line[LINE Notify]
|
||||
end
|
||||
|
||||
Browser --> NPM
|
||||
Mobile --> NPM
|
||||
NPM --> Frontend
|
||||
NPM --> Backend
|
||||
|
||||
Frontend --> Backend
|
||||
Backend --> MariaDB
|
||||
Backend --> Redis
|
||||
Backend --> Elastic
|
||||
Backend --> Storage
|
||||
Backend --> N8N
|
||||
|
||||
N8N --> Email
|
||||
N8N --> Line
|
||||
```
|
||||
|
||||
### Request Flow (Simplified)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Client
|
||||
participant N as Nginx
|
||||
participant B as Backend
|
||||
participant R as Redis
|
||||
participant D as Database
|
||||
|
||||
C->>N: HTTPS Request + JWT
|
||||
N->>B: Forward Request
|
||||
|
||||
B->>B: Rate Limit Check
|
||||
B->>B: Input Validation
|
||||
B->>B: JWT Verification
|
||||
B->>R: Get Permissions
|
||||
R-->>B: Permission Data
|
||||
B->>B: RBAC Check
|
||||
|
||||
B->>D: Query/Update
|
||||
D-->>B: Result
|
||||
|
||||
B->>D: Audit Log
|
||||
B-->>C: JSON Response
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Related Documents
|
||||
|
||||
### Requirements
|
||||
|
||||
- [Application Requirements](../../docs/0_Requirements_V1_4_5.md)
|
||||
- [Full Stack Guidelines](../../docs/1_FullStackJS_V1_4_5.md)
|
||||
|
||||
### Implementation Plans
|
||||
|
||||
- [Backend Development Plan](../../docs/2_Backend_Plan_V1_4_5.md)
|
||||
- [Frontend Development Plan](../../docs/3_Frontend_Plan_V1_4_5.md)
|
||||
|
||||
### Data Specifications
|
||||
|
||||
- [Data Dictionary](../../docs/4_Data_Dictionary_V1_4_5.md)
|
||||
- [Database Schema SQL](../../docs/8_lcbp3_v1_4_5.sql)
|
||||
|
||||
### Other Specifications
|
||||
|
||||
- [Requirements Specs](../01-requirements/README.md)
|
||||
- [Implementation Specs](../03-implementation/README.md)
|
||||
- [Operations Specs](../04-operations/README.md)
|
||||
- [Architecture Decisions](../05-decisions/README.md)
|
||||
|
||||
---
|
||||
|
||||
## 📈 Performance Targets
|
||||
|
||||
| Metric | Target | Measurement |
|
||||
| ---------------------- | ------- | ----------------------------- |
|
||||
| **API Response Time** | < 200ms | 90th percentile (Simple CRUD) |
|
||||
| **Search Performance** | < 500ms | Complex Search Queries |
|
||||
| **File Upload** | < 30s | 50MB file processing |
|
||||
| **Concurrent Users** | 100+ | Simultaneous active users |
|
||||
| **Cache Hit Ratio** | > 80% | Master Data caching |
|
||||
| **Uptime** | 99.5% | Monthly availability |
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Security Standards
|
||||
|
||||
### OWASP Top 10 Protection
|
||||
|
||||
| Vulnerability | Protection Measure |
|
||||
| ------------------------- | ------------------------------------ |
|
||||
| SQL Injection | Parameterized Queries (TypeORM) |
|
||||
| XSS | Input Sanitization + Output Encoding |
|
||||
| CSRF | CSRF Tokens for State-Changing Ops |
|
||||
| Broken Authentication | JWT + Secure Token Management |
|
||||
| Security Misconfiguration | Security Headers (Helmet.js) |
|
||||
| Sensitive Data Exposure | Encryption + Secure Storage |
|
||||
| Insufficient Logging | Comprehensive Audit Logs |
|
||||
|
||||
### Rate Limiting
|
||||
|
||||
| User Role | Limit | Scope |
|
||||
| ---------------- | ------------- | ---------- |
|
||||
| Anonymous | 100 req/hour | IP Address |
|
||||
| Viewer | 500 req/hour | User ID |
|
||||
| Editor | 1000 req/hour | User ID |
|
||||
| Document Control | 2000 req/hour | User ID |
|
||||
| Admin/Superadmin | 5000 req/hour | User ID |
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Change History
|
||||
|
||||
| Version | Date | Author | Changes |
|
||||
| ------- | ---------- | ----------- | ---------------------------------- |
|
||||
| 1.5.0 | 2025-11-30 | Nattanin P. | Initial architecture specification |
|
||||
| 1.4.5 | 2025-11-29 | - | Added security requirements |
|
||||
| 1.4.4 | 2025-11-28 | - | Enhanced resilience patterns |
|
||||
|
||||
---
|
||||
|
||||
## 📞 Questions & Feedback
|
||||
|
||||
### Architecture Review
|
||||
|
||||
- **Tech Lead:** [ระบุชื่อ]
|
||||
- **Senior Architect:** [ระบุชื่อ]
|
||||
|
||||
### Contributing
|
||||
|
||||
กรุณาอ่าน [CONTRIBUTING.md](../../CONTRIBUTING.md) สำหรับแนวทางการมีส่วนร่วมในการพัฒนา Specifications
|
||||
|
||||
### Issues & Discussions
|
||||
|
||||
- [Gitea Issues](https://git.np-dms.work/lcbp3/lcbp3-dms/issues)
|
||||
- [Architecture Discussions](https://git.np-dms.work/lcbp3/lcbp3-dms/discussions)
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**LCBP3-DMS Architecture Specification v1.5.0**
|
||||
|
||||
[System Architecture](./system-architecture.md) • [API Design](./api-design.md) • [Data Model](./data-model.md)
|
||||
|
||||
[Main README](../../README.md) • [Requirements](../01-requirements/README.md) • [Implementation](../03-implementation/README.md)
|
||||
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,628 @@
|
||||
# Data Model Architecture
|
||||
|
||||
---
|
||||
|
||||
title: 'Data Model Architecture'
|
||||
version: 1.5.0
|
||||
status: first-draft
|
||||
owner: Nattanin Peancharoen
|
||||
last_updated: 2025-11-30
|
||||
related:
|
||||
|
||||
- specs/01-requirements/02-architecture.md
|
||||
- specs/01-requirements/03-functional-requirements.md
|
||||
- docs/4_Data_Dictionary_V1_4_5.md
|
||||
- docs/8_lcbp3_v1_4_5.sql
|
||||
|
||||
---
|
||||
|
||||
## 📋 Overview
|
||||
|
||||
เอกสารนี้อธิบายสถาปัตยกรรมของ Data Model สำหรับระบบ LCBP3-DMS โดยครอบคลุมโครงสร้างฐานข้อมูล, ความสัมพันธ์ระหว่างตาราง, และหลักการออกแบบที่สำคัญ
|
||||
|
||||
## 🎯 Design Principles
|
||||
|
||||
### 1. Separation of Concerns
|
||||
|
||||
- **Master-Revision Pattern**: แยกข้อมูลที่ไม่เปลี่ยนแปลง (Master) จากข้อมูลที่มีการแก้ไข (Revisions)
|
||||
- `correspondences` (Master) ↔ `correspondence_revisions` (Revisions)
|
||||
- `rfas` (Master) ↔ `rfa_revisions` (Revisions)
|
||||
- `shop_drawings` (Master) ↔ `shop_drawing_revisions` (Revisions)
|
||||
|
||||
### 2. Data Integrity
|
||||
|
||||
- **Foreign Key Constraints**: ใช้ FK ทุกความสัมพันธ์เพื่อรักษาความสมบูรณ์ของข้อมูล
|
||||
- **Soft Delete**: ใช้ `deleted_at` แทนการลบข้อมูลจริง เพื่อรักษาประวัติ
|
||||
- **Optimistic Locking**: ใช้ `version` column ใน `document_number_counters` ป้องกัน Race Condition
|
||||
|
||||
### 3. Flexibility & Extensibility
|
||||
|
||||
- **JSON Details Field**: เก็บข้อมูลเฉพาะประเภทใน `correspondence_revisions.details`
|
||||
- **Virtual Columns**: สร้าง Index จาก JSON fields สำหรับ Performance
|
||||
- **Master Data Tables**: แยกข้อมูล Master (Types, Status, Codes) เพื่อความยืดหยุ่น
|
||||
|
||||
### 4. Security & Audit
|
||||
|
||||
- **RBAC (Role-Based Access Control)**: ระบบสิทธิ์แบบ Hierarchical Scope
|
||||
- **Audit Trail**: บันทึกผู้สร้าง/แก้ไข และเวลาในทุกตาราง
|
||||
- **Two-Phase File Upload**: ป้องกันไฟล์ขยะด้วย Temporary Storage
|
||||
|
||||
## 🗂️ Database Schema Overview
|
||||
|
||||
### Entity Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
%% Core Entities
|
||||
organizations ||--o{ users : "employs"
|
||||
projects ||--o{ contracts : "contains"
|
||||
projects ||--o{ correspondences : "manages"
|
||||
|
||||
%% RBAC
|
||||
users ||--o{ user_assignments : "has"
|
||||
roles ||--o{ user_assignments : "assigned_to"
|
||||
roles ||--o{ role_permissions : "has"
|
||||
permissions ||--o{ role_permissions : "granted_by"
|
||||
|
||||
%% Correspondences
|
||||
correspondences ||--o{ correspondence_revisions : "has_revisions"
|
||||
correspondence_types ||--o{ correspondences : "categorizes"
|
||||
correspondence_status ||--o{ correspondence_revisions : "defines_state"
|
||||
disciplines ||--o{ correspondences : "classifies"
|
||||
|
||||
%% RFAs
|
||||
rfas ||--o{ rfa_revisions : "has_revisions"
|
||||
rfa_types ||--o{ rfas : "categorizes"
|
||||
rfa_status_codes ||--o{ rfa_revisions : "defines_state"
|
||||
rfa_approve_codes ||--o{ rfa_revisions : "defines_result"
|
||||
disciplines ||--o{ rfas : "classifies"
|
||||
|
||||
%% Drawings
|
||||
shop_drawings ||--o{ shop_drawing_revisions : "has_revisions"
|
||||
shop_drawing_main_categories ||--o{ shop_drawings : "categorizes"
|
||||
shop_drawing_sub_categories ||--o{ shop_drawings : "sub_categorizes"
|
||||
|
||||
%% Attachments
|
||||
attachments ||--o{ correspondence_attachments : "attached_to"
|
||||
correspondences ||--o{ correspondence_attachments : "has"
|
||||
```
|
||||
|
||||
## 📊 Data Model Categories
|
||||
|
||||
### 1. 🏢 Core & Master Data
|
||||
|
||||
#### 1.1 Organizations & Projects
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `organization_roles` - บทบาทขององค์กร (OWNER, DESIGNER, CONSULTANT, CONTRACTOR)
|
||||
- `organizations` - องค์กรทั้งหมดในระบบ
|
||||
- `projects` - โครงการ
|
||||
- `contracts` - สัญญาภายใต้โครงการ
|
||||
- `project_organizations` - M:N ระหว่าง Projects และ Organizations
|
||||
- `contract_organizations` - M:N ระหว่าง Contracts และ Organizations พร้อม Role
|
||||
|
||||
**Key Relationships:**
|
||||
|
||||
```
|
||||
projects (1) ──→ (N) contracts
|
||||
projects (N) ←→ (N) organizations [via project_organizations]
|
||||
contracts (N) ←→ (N) organizations [via contract_organizations]
|
||||
```
|
||||
|
||||
**Business Rules:**
|
||||
|
||||
- Organization code ต้องไม่ซ้ำกันในระบบ
|
||||
- Contract ต้องผูกกับ Project เสมอ (ON DELETE CASCADE)
|
||||
- Soft delete ใช้ `is_active` flag
|
||||
|
||||
---
|
||||
|
||||
### 2. 👥 Users & RBAC
|
||||
|
||||
#### 2.1 User Management
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `users` - ผู้ใช้งานระบบ
|
||||
- `roles` - บทบาทพร้อม Scope (Global, Organization, Project, Contract)
|
||||
- `permissions` - สิทธิ์การใช้งาน (49 permissions)
|
||||
- `role_permissions` - M:N mapping
|
||||
- `user_assignments` - การมอบหมายบทบาทพร้อม Scope Context
|
||||
|
||||
**Scope Hierarchy:**
|
||||
|
||||
```
|
||||
Global (ทั้งระบบ)
|
||||
↓
|
||||
Organization (ระดับองค์กร)
|
||||
↓
|
||||
Project (ระดับโครงการ)
|
||||
↓
|
||||
Contract (ระดับสัญญา)
|
||||
```
|
||||
|
||||
**Key Features:**
|
||||
|
||||
- **Hierarchical Scope**: User สามารถมีหลาย Role ในหลาย Scope
|
||||
- **Scope Inheritance**: สิทธิ์ระดับบนครอบคลุมระดับล่าง
|
||||
- **Account Security**: Failed login tracking, Account locking, Password hashing (bcrypt)
|
||||
|
||||
**Example User Assignment:**
|
||||
|
||||
```sql
|
||||
-- User A เป็น Editor ในองค์กร TEAM
|
||||
INSERT INTO user_assignments (user_id, role_id, organization_id)
|
||||
VALUES (1, 4, 3);
|
||||
|
||||
-- User B เป็น Project Manager ในโครงการ LCBP3
|
||||
INSERT INTO user_assignments (user_id, role_id, project_id)
|
||||
VALUES (2, 6, 1);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. ✉️ Correspondences (เอกสารโต้ตอบ)
|
||||
|
||||
#### 3.1 Master-Revision Pattern
|
||||
|
||||
**Master Table: `correspondences`**
|
||||
|
||||
เก็บข้อมูลที่ไม่เปลี่ยนแปลง:
|
||||
|
||||
- `correspondence_number` - เลขที่เอกสาร (Unique per Project)
|
||||
- `correspondence_type_id` - ประเภทเอกสาร (RFA, RFI, TRANSMITTAL, etc.)
|
||||
- `discipline_id` - สาขางาน (GEN, STR, ARC, etc.) [NEW v1.4.5]
|
||||
- `project_id`, `originator_id` - โครงการและองค์กรผู้ส่ง
|
||||
|
||||
**Revision Table: `correspondence_revisions`**
|
||||
|
||||
เก็บข้อมูลที่เปลี่ยนแปลงได้:
|
||||
|
||||
- `revision_number` - หมายเลข Revision (0, 1, 2...)
|
||||
- `is_current` - Flag สำหรับ Revision ปัจจุบัน (UNIQUE constraint)
|
||||
- `title`, `description` - เนื้อหาเอกสาร
|
||||
- `correspondence_status_id` - สถานะ (DRAFT, SUBOWN, REPCSC, etc.)
|
||||
- `details` - JSON field สำหรับข้อมูลเฉพาะประเภท
|
||||
- Virtual Columns: `v_ref_project_id`, `v_ref_type`, `v_doc_subtype` (Indexed)
|
||||
|
||||
**Supporting Tables:**
|
||||
|
||||
- `correspondence_types` - Master ประเภทเอกสาร (10 types)
|
||||
- `correspondence_status` - Master สถานะ (23 status codes)
|
||||
- `correspondence_sub_types` - ประเภทย่อยสำหรับ Document Numbering [NEW v1.4.5]
|
||||
- `disciplines` - สาขางาน (GEN, STR, ARC, etc.) [NEW v1.4.5]
|
||||
- `correspondence_recipients` - M:N ผู้รับ (TO/CC)
|
||||
- `correspondence_tags` - M:N Tags
|
||||
- `correspondence_references` - M:N Cross-references
|
||||
|
||||
**Example Query - Get Current Revision:**
|
||||
|
||||
```sql
|
||||
SELECT c.correspondence_number, cr.title, cr.revision_label, cs.status_name
|
||||
FROM correspondences c
|
||||
JOIN correspondence_revisions cr ON c.id = cr.correspondence_id
|
||||
JOIN correspondence_status cs ON cr.correspondence_status_id = cs.id
|
||||
WHERE cr.is_current = TRUE
|
||||
AND c.deleted_at IS NULL;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. 📐 RFAs (Request for Approval)
|
||||
|
||||
#### 4.1 RFA Structure
|
||||
|
||||
**Master Table: `rfas`**
|
||||
|
||||
- `rfa_type_id` - ประเภท RFA (DWG, DOC, MAT, SPC, etc.)
|
||||
- `discipline_id` - สาขางาน [NEW v1.4.5]
|
||||
|
||||
**Revision Table: `rfa_revisions`**
|
||||
|
||||
- `correspondence_id` - Link กับ Correspondence (RFA เป็น Correspondence ประเภทหนึ่ง)
|
||||
- `rfa_status_code_id` - สถานะ (DFT, FAP, FRE, FCO, ASB, OBS, CC)
|
||||
- `rfa_approve_code_id` - ผลการอนุมัติ (1A, 1C, 1N, 1R, 3C, 3R, 4X, 5N)
|
||||
- `approved_date` - วันที่อนุมัติ
|
||||
|
||||
**Supporting Tables:**
|
||||
|
||||
- `rfa_types` - 11 ประเภท (Shop Drawing, Document, Material, etc.)
|
||||
- `rfa_status_codes` - 7 สถานะ
|
||||
- `rfa_approve_codes` - 8 รหัสผลการอนุมัติ
|
||||
- `rfa_items` - M:N เชื่อม RFA (ประเภท DWG) กับ Shop Drawing Revisions
|
||||
|
||||
**RFA Workflow States:**
|
||||
|
||||
```
|
||||
DFT (Draft)
|
||||
↓
|
||||
FAP (For Approve) / FRE (For Review)
|
||||
↓
|
||||
[Approval Process]
|
||||
↓
|
||||
FCO (For Construction) / ASB (As-Built) / 3R (Revise) / 4X (Reject)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. 📐 Drawings (แบบก่อสร้าง)
|
||||
|
||||
#### 5.1 Contract Drawings (แบบคู่สัญญา)
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `contract_drawing_volumes` - เล่มแบบ
|
||||
- `contract_drawing_cats` - หมวดหมู่หลัก
|
||||
- `contract_drawing_sub_cats` - หมวดหมู่ย่อย
|
||||
- `contract_drawing_subcat_cat_maps` - M:N Mapping
|
||||
- `contract_drawings` - แบบคู่สัญญา
|
||||
|
||||
**Hierarchy:**
|
||||
|
||||
```
|
||||
Volume (เล่ม)
|
||||
└─ Category (หมวดหมู่หลัก)
|
||||
└─ Sub-Category (หมวดหมู่ย่อย)
|
||||
└─ Drawing (แบบ)
|
||||
```
|
||||
|
||||
#### 5.2 Shop Drawings (แบบก่อสร้าง)
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `shop_drawing_main_categories` - หมวดหมู่หลัก (ARCH, STR, MEP, etc.)
|
||||
- `shop_drawing_sub_categories` - หมวดหมู่ย่อย
|
||||
- `shop_drawings` - Master แบบก่อสร้าง
|
||||
- `shop_drawing_revisions` - Revisions
|
||||
- `shop_drawing_revision_contract_refs` - M:N อ้างอิงแบบคู่สัญญา
|
||||
|
||||
**Revision Tracking:**
|
||||
|
||||
```sql
|
||||
-- Get latest revision of a shop drawing
|
||||
SELECT sd.drawing_number, sdr.revision_label, sdr.revision_date
|
||||
FROM shop_drawings sd
|
||||
JOIN shop_drawing_revisions sdr ON sd.id = sdr.shop_drawing_id
|
||||
WHERE sd.drawing_number = 'SD-STR-001'
|
||||
ORDER BY sdr.revision_number DESC
|
||||
LIMIT 1;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. 🔄 Circulations & Transmittals
|
||||
|
||||
#### 6.1 Circulations (ใบเวียนภายใน)
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `circulation_status_codes` - สถานะ (OPEN, IN_REVIEW, COMPLETED, CANCELLED)
|
||||
- `circulations` - ใบเวียน (1:1 กับ Correspondence)
|
||||
|
||||
**Workflow:**
|
||||
|
||||
```
|
||||
OPEN → IN_REVIEW → COMPLETED
|
||||
↓
|
||||
CANCELLED
|
||||
```
|
||||
|
||||
#### 6.2 Transmittals (เอกสารนำส่ง)
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `transmittals` - ข้อมูล Transmittal (1:1 กับ Correspondence)
|
||||
- `transmittal_items` - M:N รายการเอกสารที่นำส่ง
|
||||
|
||||
**Purpose Types:**
|
||||
|
||||
- FOR_APPROVAL
|
||||
- FOR_INFORMATION
|
||||
- FOR_REVIEW
|
||||
- OTHER
|
||||
|
||||
---
|
||||
|
||||
### 7. 📎 File Management
|
||||
|
||||
#### 7.1 Two-Phase Storage Pattern
|
||||
|
||||
**Table: `attachments`**
|
||||
|
||||
**Phase 1: Temporary Upload**
|
||||
|
||||
```sql
|
||||
INSERT INTO attachments (
|
||||
original_filename, stored_filename, file_path,
|
||||
mime_type, file_size, is_temporary, temp_id,
|
||||
uploaded_by_user_id, expires_at, checksum
|
||||
)
|
||||
VALUES (
|
||||
'document.pdf', 'uuid-document.pdf', '/temp/uuid-document.pdf',
|
||||
'application/pdf', 1024000, TRUE, 'temp-uuid-123',
|
||||
1, NOW() + INTERVAL 1 HOUR, 'sha256-hash'
|
||||
);
|
||||
```
|
||||
|
||||
**Phase 2: Commit to Permanent**
|
||||
|
||||
```sql
|
||||
-- Update attachment to permanent
|
||||
UPDATE attachments
|
||||
SET is_temporary = FALSE, expires_at = NULL
|
||||
WHERE temp_id = 'temp-uuid-123';
|
||||
|
||||
-- Link to correspondence
|
||||
INSERT INTO correspondence_attachments (correspondence_id, attachment_id, is_main_document)
|
||||
VALUES (1, 123, TRUE);
|
||||
```
|
||||
|
||||
**Junction Tables:**
|
||||
|
||||
- `correspondence_attachments` - M:N
|
||||
- `circulation_attachments` - M:N
|
||||
- `shop_drawing_revision_attachments` - M:N (with file_type)
|
||||
- `contract_drawing_attachments` - M:N (with file_type)
|
||||
|
||||
**Security Features:**
|
||||
|
||||
- Checksum validation (SHA-256)
|
||||
- Automatic cleanup of expired temporary files
|
||||
- File type validation via `mime_type`
|
||||
|
||||
---
|
||||
|
||||
### 8. 🔢 Document Numbering
|
||||
|
||||
#### 8.1 Format & Counter System
|
||||
|
||||
**Tables:**
|
||||
|
||||
- `document_number_formats` - Template รูปแบบเลขที่เอกสาร
|
||||
- `document_number_counters` - Running Number Counter with Optimistic Locking
|
||||
|
||||
**Format Template Example:**
|
||||
|
||||
```
|
||||
{ORG_CODE}-{TYPE_CODE}-{DISCIPLINE_CODE}-{YEAR}-{SEQ:4}
|
||||
→ TEAM-RFA-STR-2025-0001
|
||||
```
|
||||
|
||||
**Counter Table Structure:**
|
||||
|
||||
```sql
|
||||
CREATE TABLE document_number_counters (
|
||||
project_id INT,
|
||||
originator_organization_id INT,
|
||||
correspondence_type_id INT,
|
||||
discipline_id INT DEFAULT 0, -- NEW v1.4.5
|
||||
current_year INT,
|
||||
version INT DEFAULT 0, -- Optimistic Lock
|
||||
last_number INT DEFAULT 0,
|
||||
PRIMARY KEY (project_id, originator_organization_id, correspondence_type_id, discipline_id, current_year)
|
||||
);
|
||||
```
|
||||
|
||||
**Optimistic Locking Pattern:**
|
||||
|
||||
```sql
|
||||
-- Get next number with version check
|
||||
UPDATE document_number_counters
|
||||
SET last_number = last_number + 1,
|
||||
version = version + 1
|
||||
WHERE project_id = 1
|
||||
AND originator_organization_id = 3
|
||||
AND correspondence_type_id = 1
|
||||
AND discipline_id = 2
|
||||
AND current_year = 2025
|
||||
AND version = @current_version; -- Optimistic lock check
|
||||
|
||||
-- If affected rows = 0, retry (conflict detected)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Security & Audit
|
||||
|
||||
### 1. Audit Logging
|
||||
|
||||
**Table: `audit_logs`**
|
||||
|
||||
บันทึกการเปลี่ยนแปลงสำคัญ:
|
||||
|
||||
- User actions (CREATE, UPDATE, DELETE)
|
||||
- Entity type และ Entity ID
|
||||
- Old/New values (JSON)
|
||||
- IP Address, User Agent
|
||||
|
||||
### 2. User Preferences
|
||||
|
||||
**Table: `user_preferences`**
|
||||
|
||||
เก็บการตั้งค่าส่วนตัว:
|
||||
|
||||
- Language preference
|
||||
- Notification settings
|
||||
- UI preferences (JSON)
|
||||
|
||||
### 3. JSON Schema Validation
|
||||
|
||||
**Table: `json_schemas`**
|
||||
|
||||
เก็บ Schema สำหรับ Validate JSON fields:
|
||||
|
||||
- `correspondence_revisions.details`
|
||||
- `user_preferences.preferences`
|
||||
|
||||
---
|
||||
|
||||
## 📈 Performance Optimization
|
||||
|
||||
### 1. Indexing Strategy
|
||||
|
||||
**Primary Indexes:**
|
||||
|
||||
- Primary Keys (AUTO_INCREMENT)
|
||||
- Foreign Keys (automatic in InnoDB)
|
||||
- Unique Constraints (business keys)
|
||||
|
||||
**Secondary Indexes:**
|
||||
|
||||
```sql
|
||||
-- Correspondence search
|
||||
CREATE INDEX idx_corr_type_status ON correspondence_revisions(correspondence_type_id, correspondence_status_id);
|
||||
CREATE INDEX idx_corr_date ON correspondence_revisions(document_date);
|
||||
|
||||
-- Virtual columns for JSON
|
||||
CREATE INDEX idx_v_ref_project ON correspondence_revisions(v_ref_project_id);
|
||||
CREATE INDEX idx_v_doc_subtype ON correspondence_revisions(v_doc_subtype);
|
||||
|
||||
-- User lookup
|
||||
CREATE INDEX idx_user_email ON users(email);
|
||||
CREATE INDEX idx_user_org ON users(primary_organization_id, is_active);
|
||||
```
|
||||
|
||||
### 2. Virtual Columns
|
||||
|
||||
ใช้ Virtual Columns สำหรับ Index JSON fields:
|
||||
|
||||
```sql
|
||||
ALTER TABLE correspondence_revisions
|
||||
ADD COLUMN v_ref_project_id INT GENERATED ALWAYS AS (JSON_UNQUOTE(JSON_EXTRACT(details, '$.ref_project_id'))) VIRTUAL,
|
||||
ADD INDEX idx_v_ref_project(v_ref_project_id);
|
||||
```
|
||||
|
||||
### 3. Partitioning (Future)
|
||||
|
||||
พิจารณา Partition ตาราง `audit_logs` ตามปี:
|
||||
|
||||
```sql
|
||||
ALTER TABLE audit_logs
|
||||
PARTITION BY RANGE (YEAR(created_at)) (
|
||||
PARTITION p2024 VALUES LESS THAN (2025),
|
||||
PARTITION p2025 VALUES LESS THAN (2026),
|
||||
PARTITION p_future VALUES LESS THAN MAXVALUE
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔄 Migration Strategy
|
||||
|
||||
### 1. TypeORM Migrations
|
||||
|
||||
ใช้ TypeORM Migration สำหรับ Schema Changes:
|
||||
|
||||
```typescript
|
||||
// File: backend/src/migrations/1234567890-AddDisciplineToCorrespondences.ts
|
||||
import { MigrationInterface, QueryRunner } from 'typeorm';
|
||||
|
||||
export class AddDisciplineToCorrespondences1234567890
|
||||
implements MigrationInterface
|
||||
{
|
||||
public async up(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE correspondences
|
||||
ADD COLUMN discipline_id INT NULL COMMENT 'สาขางาน (ถ้ามี)'
|
||||
AFTER correspondence_type_id
|
||||
`);
|
||||
|
||||
await queryRunner.query(`
|
||||
ALTER TABLE correspondences
|
||||
ADD CONSTRAINT fk_corr_discipline
|
||||
FOREIGN KEY (discipline_id) REFERENCES disciplines(id)
|
||||
ON DELETE SET NULL
|
||||
`);
|
||||
}
|
||||
|
||||
public async down(queryRunner: QueryRunner): Promise<void> {
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE correspondences DROP FOREIGN KEY fk_corr_discipline`
|
||||
);
|
||||
await queryRunner.query(
|
||||
`ALTER TABLE correspondences DROP COLUMN discipline_id`
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Data Seeding
|
||||
|
||||
ใช้ Seed Scripts สำหรับ Master Data:
|
||||
|
||||
```typescript
|
||||
// File: backend/src/seeds/1-organizations.seed.ts
|
||||
export class OrganizationSeeder implements Seeder {
|
||||
public async run(dataSource: DataSource): Promise<void> {
|
||||
const repository = dataSource.getRepository(Organization);
|
||||
await repository.save([
|
||||
{
|
||||
organization_code: 'กทท.',
|
||||
organization_name: 'Port Authority of Thailand',
|
||||
},
|
||||
{
|
||||
organization_code: 'TEAM',
|
||||
organization_name: 'TEAM Consulting Engineering',
|
||||
},
|
||||
// ...
|
||||
]);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 Best Practices
|
||||
|
||||
### 1. Naming Conventions
|
||||
|
||||
- **Tables**: `snake_case`, plural (e.g., `correspondences`, `users`)
|
||||
- **Columns**: `snake_case` (e.g., `correspondence_number`, `created_at`)
|
||||
- **Foreign Keys**: `{referenced_table_singular}_id` (e.g., `project_id`, `user_id`)
|
||||
- **Junction Tables**: `{table1}_{table2}` (e.g., `correspondence_tags`)
|
||||
|
||||
### 2. Timestamp Columns
|
||||
|
||||
ทุกตารางควรมี:
|
||||
|
||||
- `created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP`
|
||||
- `updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`
|
||||
|
||||
### 3. Soft Delete
|
||||
|
||||
ใช้ `deleted_at DATETIME NULL` แทนการลบจริง:
|
||||
|
||||
```sql
|
||||
-- Soft delete
|
||||
UPDATE correspondences SET deleted_at = NOW() WHERE id = 1;
|
||||
|
||||
-- Query active records
|
||||
SELECT * FROM correspondences WHERE deleted_at IS NULL;
|
||||
```
|
||||
|
||||
### 4. JSON Field Guidelines
|
||||
|
||||
- ใช้สำหรับข้อมูลที่ไม่ต้อง Query บ่อย
|
||||
- สร้าง Virtual Columns สำหรับ fields ที่ต้อง Index
|
||||
- Validate ด้วย JSON Schema
|
||||
- Document structure ใน Data Dictionary
|
||||
|
||||
---
|
||||
|
||||
## 🔗 Related Documentation
|
||||
|
||||
- [System Architecture](./02-architecture.md) - สถาปัตยกรรมระบบโดยรวม
|
||||
- [API Design](./api-design.md) - การออกแบบ API
|
||||
- [Data Dictionary v1.4.5](../../docs/4_Data_Dictionary_V1_4_5.md) - รายละเอียดตารางทั้งหมด
|
||||
- [SQL Schema v1.4.5](../../docs/8_lcbp3_v1_4_5.sql) - SQL Script สำหรับสร้างฐานข้อมูล
|
||||
- [Functional Requirements](../01-requirements/03-functional-requirements.md) - ความต้องการด้านฟังก์ชัน
|
||||
|
||||
---
|
||||
|
||||
## 📝 Version History
|
||||
|
||||
| Version | Date | Author | Changes |
|
||||
| ------- | ---------- | -------------------- | ---------------------------------------------- |
|
||||
| 1.5.0 | 2025-11-30 | Nattanin Peancharoen | Initial data model documentation |
|
||||
| 1.4.5 | 2025-11-29 | System | Added disciplines and correspondence_sub_types |
|
||||
|
||||
Reference in New Issue
Block a user