From 71c091055ae30b15ce7f204226ae781c9a304e4b Mon Sep 17 00:00:00 2001 From: admin Date: Mon, 1 Dec 2025 01:28:32 +0700 Subject: [PATCH] Main: revise specs to 1.5.0 (completed) --- .github/workflows/link-checker.yml | 1 + .github/workflows/spec-validation.yml | 64 +- .vscode/extensions.json | 3 +- CONTRIBUTING.md | 667 ++++++++- README.md | 510 ++++++- docs/temp.md | 714 ++++++++++ nap-dms.lcbp3.code-workspace | 29 +- specs/00-overview/README.md | 403 +++++- specs/00-overview/glossary.md | 497 ++++++- specs/00-overview/quick-start.md | 389 +++++ specs/02-architecture/README.md | 509 ++++++- specs/02-architecture/data-model.md | 628 +++++++++ specs/03-implementation/backend-guidelines.md | 6 +- .../03-implementation/frontend-guidelines.md | 6 +- .../03-implementation/fullftack-js-v1.5.0.md | 18 +- specs/03-implementation/testing-strategy.md | 1253 +++++++++++++++++ specs/04-operations/README.md | 190 +++ specs/04-operations/backup-recovery.md | 374 +++++ specs/04-operations/deployment.md | 0 specs/04-operations/disaster-recovery.md | 0 specs/04-operations/environment-setup.md | 463 ++++++ specs/04-operations/incident-response.md | 483 +++++++ specs/04-operations/maintenance-procedures.md | 501 +++++++ specs/04-operations/monitoring-alerting.md | 443 ++++++ specs/04-operations/monitoring.md | 0 specs/04-operations/security-operations.md | 444 ++++++ .../ADR-001-unified-workflow-engine.md | 353 +++++ .../ADR-002-document-numbering-strategy.md | 432 ++++++ .../ADR-003-file-storage-approach.md | 505 +++++++ .../ADR-004-rbac-implementation.md | 423 ++++++ .../05-decisions/ADR-005-technology-stack.md | 291 ++++ .../ADR-006-redis-caching-strategy.md | 438 ++++++ .../ADR-007-api-design-error-handling.md | 352 +++++ .../ADR-008-email-notification-strategy.md | 388 +++++ .../ADR-009-database-migration-strategy.md | 383 +++++ .../ADR-010-logging-monitoring-strategy.md | 464 ++++++ .../05-decisions/ADR-011-nextjs-app-router.md | 399 ++++++ .../ADR-012-ui-component-library.md | 428 ++++++ .../ADR-013-form-handling-validation.md | 497 +++++++ .../05-decisions/ADR-014-state-management.md | 400 ++++++ .../ADR-015-deployment-infrastructure.md | 457 ++++++ .../ADR-016-security-authentication.md | 451 ++++++ specs/05-decisions/README.md | 356 +++++ specs/06-tasks/README.md | 623 ++++++++ .../TASK-BE-001-database-migrations.md | 263 ++++ specs/06-tasks/TASK-BE-002-auth-rbac.md | 427 ++++++ specs/06-tasks/TASK-BE-003-file-storage.md | 470 +++++++ .../TASK-BE-004-document-numbering.md | 476 +++++++ .../TASK-BE-005-correspondence-module.md | 521 +++++++ specs/06-tasks/TASK-BE-006-workflow-engine.md | 540 +++++++ specs/06-tasks/TASK-BE-007-rfa-module.md | 587 ++++++++ specs/06-tasks/TASK-BE-008-drawing-module.md | 584 ++++++++ .../TASK-BE-009-circulation-transmittal.md | 578 ++++++++ .../TASK-BE-010-search-elasticsearch.md | 493 +++++++ .../TASK-BE-011-notification-audit.md | 524 +++++++ .../TASK-BE-012-master-data-management.md | 641 +++++++++ specs/06-tasks/TASK-BE-013-user-management.md | 738 ++++++++++ specs/06-tasks/TASK-FE-001-frontend-setup.md | 381 +++++ specs/06-tasks/TASK-FE-002-auth-ui.md | 438 ++++++ .../06-tasks/TASK-FE-003-layout-navigation.md | 346 +++++ .../06-tasks/TASK-FE-004-correspondence-ui.md | 406 ++++++ .../06-tasks/TASK-FE-005-common-components.md | 454 ++++++ specs/06-tasks/TASK-FE-006-rfa-ui.md | 408 ++++++ specs/06-tasks/TASK-FE-007-drawing-ui.md | 388 +++++ specs/06-tasks/TASK-FE-008-search-ui.md | 382 +++++ .../TASK-FE-009-dashboard-notifications.md | 344 +++++ specs/06-tasks/TASK-FE-010-admin-panel.md | 680 +++++++++ .../TASK-FE-011-workflow-config-ui.md | 505 +++++++ .../TASK-FE-012-numbering-config-ui.md | 517 +++++++ 69 files changed, 28252 insertions(+), 74 deletions(-) create mode 100644 .github/workflows/link-checker.yml create mode 100644 docs/temp.md create mode 100644 specs/00-overview/quick-start.md create mode 100644 specs/04-operations/README.md create mode 100644 specs/04-operations/backup-recovery.md create mode 100644 specs/04-operations/deployment.md create mode 100644 specs/04-operations/disaster-recovery.md create mode 100644 specs/04-operations/environment-setup.md create mode 100644 specs/04-operations/incident-response.md create mode 100644 specs/04-operations/maintenance-procedures.md create mode 100644 specs/04-operations/monitoring-alerting.md create mode 100644 specs/04-operations/monitoring.md create mode 100644 specs/04-operations/security-operations.md create mode 100644 specs/05-decisions/ADR-001-unified-workflow-engine.md create mode 100644 specs/05-decisions/ADR-002-document-numbering-strategy.md create mode 100644 specs/05-decisions/ADR-003-file-storage-approach.md create mode 100644 specs/05-decisions/ADR-004-rbac-implementation.md create mode 100644 specs/05-decisions/ADR-005-technology-stack.md create mode 100644 specs/05-decisions/ADR-006-redis-caching-strategy.md create mode 100644 specs/05-decisions/ADR-007-api-design-error-handling.md create mode 100644 specs/05-decisions/ADR-008-email-notification-strategy.md create mode 100644 specs/05-decisions/ADR-009-database-migration-strategy.md create mode 100644 specs/05-decisions/ADR-010-logging-monitoring-strategy.md create mode 100644 specs/05-decisions/ADR-011-nextjs-app-router.md create mode 100644 specs/05-decisions/ADR-012-ui-component-library.md create mode 100644 specs/05-decisions/ADR-013-form-handling-validation.md create mode 100644 specs/05-decisions/ADR-014-state-management.md create mode 100644 specs/05-decisions/ADR-015-deployment-infrastructure.md create mode 100644 specs/05-decisions/ADR-016-security-authentication.md create mode 100644 specs/05-decisions/README.md create mode 100644 specs/06-tasks/README.md create mode 100644 specs/06-tasks/TASK-BE-001-database-migrations.md create mode 100644 specs/06-tasks/TASK-BE-002-auth-rbac.md create mode 100644 specs/06-tasks/TASK-BE-003-file-storage.md create mode 100644 specs/06-tasks/TASK-BE-004-document-numbering.md create mode 100644 specs/06-tasks/TASK-BE-005-correspondence-module.md create mode 100644 specs/06-tasks/TASK-BE-006-workflow-engine.md create mode 100644 specs/06-tasks/TASK-BE-007-rfa-module.md create mode 100644 specs/06-tasks/TASK-BE-008-drawing-module.md create mode 100644 specs/06-tasks/TASK-BE-009-circulation-transmittal.md create mode 100644 specs/06-tasks/TASK-BE-010-search-elasticsearch.md create mode 100644 specs/06-tasks/TASK-BE-011-notification-audit.md create mode 100644 specs/06-tasks/TASK-BE-012-master-data-management.md create mode 100644 specs/06-tasks/TASK-BE-013-user-management.md create mode 100644 specs/06-tasks/TASK-FE-001-frontend-setup.md create mode 100644 specs/06-tasks/TASK-FE-002-auth-ui.md create mode 100644 specs/06-tasks/TASK-FE-003-layout-navigation.md create mode 100644 specs/06-tasks/TASK-FE-004-correspondence-ui.md create mode 100644 specs/06-tasks/TASK-FE-005-common-components.md create mode 100644 specs/06-tasks/TASK-FE-006-rfa-ui.md create mode 100644 specs/06-tasks/TASK-FE-007-drawing-ui.md create mode 100644 specs/06-tasks/TASK-FE-008-search-ui.md create mode 100644 specs/06-tasks/TASK-FE-009-dashboard-notifications.md create mode 100644 specs/06-tasks/TASK-FE-010-admin-panel.md create mode 100644 specs/06-tasks/TASK-FE-011-workflow-config-ui.md create mode 100644 specs/06-tasks/TASK-FE-012-numbering-config-ui.md diff --git a/.github/workflows/link-checker.yml b/.github/workflows/link-checker.yml new file mode 100644 index 0000000..dcf7292 --- /dev/null +++ b/.github/workflows/link-checker.yml @@ -0,0 +1 @@ +# ตรวจสอบ broken links diff --git a/.github/workflows/spec-validation.yml b/.github/workflows/spec-validation.yml index ef142f6..0d14154 100644 --- a/.github/workflows/spec-validation.yml +++ b/.github/workflows/spec-validation.yml @@ -1 +1,63 @@ -# ตรวจสอบ specs +name: Spec Validation + +on: + pull_request: + paths: + - 'specs/**' + - 'diagrams/**' + push: + branches: [main] + +jobs: + validate-markdown: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + # 1. ตรวจสอบ Markdown syntax + - name: Lint Markdown + uses: avto-dev/markdown-lint@v1 + with: + config: '.markdownlint.json' + args: 'specs/**/*.md' + + # 2. ตรวจสอบ internal links + - name: Check Links + uses: gaurav-nelson/github-action-markdown-link-check@v1 + with: + use-quiet-mode: 'yes' + folder-path: 'specs' + + # 3. ตรวจสอบ required metadata + - name: Validate Metadata + run: | + python scripts/validate-spec-metadata.py + + # 4. ตรวจสอบ version consistency + - name: Check Version Numbers + run: | + python scripts/check-versions.py + + validate-diagrams: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + # ตรวจสอบว่า Mermaid diagrams render ได้ + - name: Validate Mermaid + uses: neenjaw/compile-mermaid-markdown-action@v1 + with: + files: 'diagrams/**/*.mmd' + + check-todos: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + # แจ้งเตือนถ้ามี TODO/FIXME + - name: Check for TODOs + run: | + if grep -r "TODO\|FIXME" specs/; then + echo "⚠️ Found TODO/FIXME in specs!" + exit 1 + fi diff --git a/.vscode/extensions.json b/.vscode/extensions.json index 2d72e84..c461831 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -49,7 +49,8 @@ "wallabyjs.console-ninja", // Icons & Theme - "pkief.material-icon-theme" + "pkief.material-icon-theme", + "bierner.markdown-mermaid" // AI Assistance (Optional - เลือก 1 อัน) // "github.copilot", diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6da7b91..1d36d09 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1 +1,666 @@ -# How to contribute to specs +# 📝 Contributing to LCBP3-DMS Specifications + +> แนวทางการมีส่วนร่วมในการพัฒนาเอกสาร Specifications ของโครงการ LCBP3-DMS + +ยินดีต้อนรับสู่คู่มือการมีส่วนร่วมในการพัฒนาเอกสาร Specifications! เอกสารนี้จะช่วยให้คุณเข้าใจวิธีการสร้าง แก้ไข และปรับปรุงเอกสารข้อกำหนดของโครงการได้อย่างมีประสิทธิภาพ + +--- + +## 📚 Table of Contents + +- [ภาพรวม Specification Structure](#-specification-structure) +- [หลักการเขียน Specifications](#-writing-principles) +- [Workflow การแก้ไข Specs](#-contribution-workflow) +- [Template และ Guidelines](#-templates--guidelines) +- [Review Process](#-review-process) +- [Best Practices](#-best-practices) +- [Tools และ Resources](#-tools--resources) + +--- + +## 🗂️ Specification Structure + +โครงสร้างเอกสาร Specifications ของโครงการแบ่งออกเป็น 6 หมวดหลัก: + +``` +specs/ +├── 00-overview/ # ภาพรวมโครงการ +│ ├── README.md # Project overview +│ └── glossary.md # คำศัพท์เทคนิค +│ +├── 01-requirements/ # ข้อกำหนดระบบ +│ ├── README.md # Requirements overview +│ ├── 01-objectives.md # วัตถุประสงค์ +│ ├── 02-architecture.md # สถาปัตยกรรม +│ ├── 03-functional-requirements.md +│ ├── 03.1-project-management.md +│ ├── 03.2-correspondence.md +│ ├── 03.3-rfa.md +│ ├── 03.4-contract-drawing.md +│ ├── 03.5-shop-drawing.md +│ ├── 03.6-unified-workflow.md +│ ├── 03.7-transmittals.md +│ ├── 03.8-circulation-sheet.md +│ ├── 03.9-logs.md +│ ├── 03.10-file-handling.md +│ ├── 03.11-document-numbering.md +│ ├── 03.12-json-details.md +│ ├── 04-access-control.md +│ ├── 05-ui-ux.md +│ ├── 06-non-functional.md +│ └── 07-testing.md +│ +├── 02-architecture/ # สถาปัตยกรรมระบบ +│ ├── README.md +│ ├── system-architecture.md +│ ├── api-design.md +│ └── data-model.md +│ +├── 03-implementation/ # แผนการพัฒนา +│ ├── README.md +│ ├── backend-plan.md +│ ├── frontend-plan.md +│ └── integration-plan.md +│ +├── 04-operations/ # การดำเนินงาน +│ ├── README.md +│ ├── deployment.md +│ └── monitoring.md +│ +└── 05-decisions/ # Architecture Decision Records + ├── README.md + ├── 001-workflow-engine.md + └── 002-file-storage.md +``` + +### 📋 หมวดหมู่เอกสาร + +| หมวด | วัตถุประสงค์ | ผู้ดูแล | +| --------------------- | ----------------------------- | ----------------------------- | +| **00-overview** | ภาพรวมโครงการและคำศัพท์ | Project Manager | +| **01-requirements** | ข้อกำหนดฟังก์ชันและระบบ | Business Analyst + Tech Lead | +| **02-architecture** | สถาปัตยกรรมและการออกแบบ | Tech Lead + Architects | +| **03-implementation** | แผนการพัฒนาและ Implementation | Development Team Leads | +| **04-operations** | Deployment และ Operations | DevOps Team | +| **05-decisions** | Architecture Decision Records | Tech Lead + Senior Developers | + +--- + +## ✍️ Writing Principles + +### 1. ภาษาที่ใช้ + +- **ชื่อเรื่อง (Headings)**: ภาษาไทยหรืออังกฤษ (ตามบริบท) +- **เนื้อหาหลัก**: ภาษาไทย +- **Code Examples**: ภาษาอังกฤษ +- **Technical Terms**: ภาษาอังกฤษ (พร้อมคำอธิบายภาษาไทย) + +### 2. รูปแบบการเขียน + +#### ✅ ถูกต้อง + +````markdown +## 3.2 การจัดการเอกสารโต้ตอบ (Correspondence Management) + +ระบบต้องรองรับการจัดการเอกสารโต้ตอบ (Correspondence) ระหว่างองค์กร โดยมีฟีเจอร์ดังนี้: + +- **สร้างเอกสาร**: ผู้ใช้สามารถสร้างเอกสารใหม่ได้ +- **แก้ไขเอกสาร**: รองรับการแก้ไข Draft +- **ส่งเอกสาร**: ส่งผ่าน Workflow Engine + +### ตัวอย่าง API Endpoint + +```typescript +POST /api/correspondences +{ + "subject": "Request for Information", + "type_id": 1, + "to_org_id": 2 +} +``` +```` + +```` + +#### ❌ ผิด + +```markdown +## correspondence management + +ระบบต้องรองรับ correspondence ระหว่างองค์กร + +- สร้างได้ +- แก้ไขได้ +- ส่งได้ +```` + +### 3. โครงสร้างเอกสาร + +ทุกเอกสารควรมีโครงสร้างดังนี้: + +```markdown +# [ชื่อเอกสาร] + +> คำอธิบายสั้นๆ เกี่ยวกับเอกสาร + +## Table of Contents (ถ้าเอกสารยาว) + +- [Section 1](#section-1) +- [Section 2](#section-2) + +## Overview + +[ภาพรวมของหัวข้อ] + +## [Main Sections] + +[เนื้อหาหลัก] + +## Related Documents + +- [Link to related spec 1] +- [Link to related spec 2] + +--- + +**Last Updated**: 2025-11-30 +**Version**: 1.4.5 +**Status**: Draft | Review | Approved +``` + +--- + +## 🔄 Contribution Workflow + +### ขั้นตอนการแก้ไข Specifications + +#### 1. สร้าง Issue (ถ้าจำเป็น) + +```bash +# ใน Gitea Issues +Title: [SPEC] Update Correspondence Requirements +Description: +- เพิ่มข้อกำหนดการ CC หลายองค์กร +- อัพเดท Workflow diagram +- เพิ่ม validation rules +``` + +#### 2. สร้าง Branch + +```bash +# Naming convention +git checkout -b spec/[category]/[description] + +# ตัวอย่าง +git checkout -b spec/requirements/update-correspondence +git checkout -b spec/architecture/add-workflow-diagram +git checkout -b spec/adr/file-storage-strategy +``` + +#### 3. แก้ไขเอกสาร + +```bash +# แก้ไขไฟล์ที่เกี่ยวข้อง +vim specs/01-requirements/03.2-correspondence.md + +# ตรวจสอบ markdown syntax +pnpm run lint:markdown + +# Preview (ถ้ามี) +pnpm run preview:specs +``` + +#### 4. Commit Changes + +```bash +# Commit message format +git commit -m "spec(requirements): update correspondence CC requirements + +- Add support for multiple CC organizations +- Update workflow diagram +- Add validation rules for CC list +- Link to ADR-003 + +Refs: #123" + +# Commit types: +# spec(category): สำหรับการแก้ไข specs +# docs(category): สำหรับเอกสารทั่วไป +# adr(number): สำหรับ Architecture Decision Records +``` + +#### 5. Push และสร้าง Pull Request + +```bash +git push origin spec/requirements/update-correspondence +``` + +**Pull Request Template:** + +```markdown +## 📝 Specification Changes + +### Category + +- [ ] Requirements +- [ ] Architecture +- [ ] Implementation +- [ ] Operations +- [ ] ADR + +### Type of Change + +- [ ] New specification +- [ ] Update existing spec +- [ ] Fix typo/formatting +- [ ] Add diagram/example + +### Description + +[อธิบายการเปลี่ยนแปลง] + +### Impact Analysis + +- **Affected Modules**: [ระบุ modules ที่ได้รับผลกระทบ] +- **Breaking Changes**: Yes/No +- **Migration Required**: Yes/No + +### Related Documents + +- Related Specs: [links] +- Related Issues: #123 +- Related ADRs: ADR-001 + +### Checklist + +- [ ] เขียนเป็นภาษาไทย (เนื้อหาหลัก) +- [ ] ใช้ Technical terms ภาษาอังกฤษ +- [ ] มี Code examples (ถ้าเกี่ยวข้อง) +- [ ] อัพเดท Table of Contents +- [ ] อัพเดท Last Updated date +- [ ] ตรวจสอบ markdown syntax +- [ ] ตรวจสอบ internal links +- [ ] เพิ่ม Related Documents +``` + +--- + +## 📋 Templates & Guidelines + +### Template: Functional Requirement + +````markdown +## [Feature ID]. [Feature Name] + +### วัตถุประสงค์ (Purpose) + +[อธิบายว่าฟีเจอร์นี้ทำอะไร และทำไมต้องมี] + +### ข้อกำหนดหลัก (Requirements) + +#### [REQ-001] [Requirement Title] + +**Priority**: High | Medium | Low +**Status**: Proposed | Approved | Implemented + +**Description**: +[คำอธิบายข้อกำหนด] + +**Acceptance Criteria**: + +- [ ] Criterion 1 +- [ ] Criterion 2 +- [ ] Criterion 3 + +**Technical Notes**: + +```typescript +// ตัวอย่าง code หรือ API +``` +```` + +**Related**: + +- Dependencies: [REQ-002], [REQ-003] +- Conflicts: None +- ADRs: [ADR-001] + +### User Stories + +```gherkin +Given [context] +When [action] +Then [expected result] +``` + +### UI/UX Requirements + +[Screenshots, Wireframes, หรือ Mockups] + +### Non-Functional Requirements + +- **Performance**: [เช่น Response time < 200ms] +- **Security**: [เช่น RBAC required] +- **Scalability**: [เช่น Support 100 concurrent users] + +### Test Scenarios + +1. **Happy Path**: [อธิบาย] +2. **Edge Cases**: [อธิบาย] +3. **Error Handling**: [อธิบาย] + +```` + +### Template: Architecture Decision Record (ADR) + +```markdown +# ADR-[NUMBER]: [Title] + +**Status**: Proposed | Accepted | Deprecated | Superseded +**Date**: YYYY-MM-DD +**Deciders**: [ชื่อผู้ตัดสินใจ] +**Technical Story**: [Issue/Epic link] + +## Context and Problem Statement + +[อธิบายปัญหาและบริบท] + +## Decision Drivers + +- [Driver 1] +- [Driver 2] +- [Driver 3] + +## Considered Options + +### Option 1: [Title] + +**Pros**: +- [Pro 1] +- [Pro 2] + +**Cons**: +- [Con 1] +- [Con 2] + +### Option 2: [Title] + +[เหมือนข้างบน] + +## Decision Outcome + +**Chosen option**: "[Option X]" + +**Justification**: +[อธิบายเหตุผล] + +**Consequences**: +- **Positive**: [ผลดี] +- **Negative**: [ผลเสีย] +- **Neutral**: [ผลกระทบอื่นๆ] + +## Implementation + +```typescript +// ตัวอย่าง implementation +```` + +## Validation + +[วิธีการตรวจสอบว่า decision นี้ถูกต้อง] + +## Related Decisions + +- Supersedes: [ADR-XXX] +- Related to: [ADR-YYY] +- Conflicts with: None + +## References + +- [Link 1] +- [Link 2] + +```` + +--- + +## 👀 Review Process + +### Reviewer Checklist + +#### ✅ Content Quality + +- [ ] **Clarity**: เนื้อหาชัดเจน เข้าใจง่าย +- [ ] **Completeness**: ครบถ้วนตามโครงสร้าง +- [ ] **Accuracy**: ข้อมูลถูกต้อง ตรงตามความเป็นจริง +- [ ] **Consistency**: สอดคล้องกับ specs อื่นๆ +- [ ] **Traceability**: มี links ไปยังเอกสารที่เกี่ยวข้อง + +#### ✅ Technical Quality + +- [ ] **Feasibility**: สามารถ implement ได้จริง +- [ ] **Performance**: คำนึงถึง performance implications +- [ ] **Security**: ระบุ security requirements +- [ ] **Scalability**: รองรับการขยายตัว +- [ ] **Maintainability**: ง่ายต่อการบำรุงรักษา + +#### ✅ Format & Style + +- [ ] **Markdown Syntax**: ไม่มี syntax errors +- [ ] **Language**: ใช้ภาษาไทยสำหรับเนื้อหาหลัก +- [ ] **Code Examples**: มี syntax highlighting +- [ ] **Diagrams**: ชัดเจน อ่านง่าย +- [ ] **Links**: ทุก link ใช้งานได้ + +### Review Levels + +| Level | Reviewer | Scope | +|-------|----------|-------| +| **L1: Peer Review** | Team Member | Format, Clarity, Completeness | +| **L2: Technical Review** | Tech Lead | Technical Accuracy, Feasibility | +| **L3: Approval** | Project Manager | Business Alignment, Impact | + +### Review Timeline + +- **L1 Review**: 1-2 วันทำการ +- **L2 Review**: 2-3 วันทำการ +- **L3 Approval**: 1-2 วันทำการ + +--- + +## 💡 Best Practices + +### 1. เขียนให้ชัดเจนและเฉพาะเจาะจง + +#### ✅ ถูกต้อง +```markdown +ระบบต้องรองรับการอัปโหลดไฟล์ประเภท PDF, DWG, DOCX, XLSX, ZIP +โดยมีขนาดไม่เกิน 50MB ต่อไฟล์ และต้องผ่านการ scan virus ด้วย ClamAV +```` + +#### ❌ ผิด + +```markdown +ระบบต้องรองรับการอัปโหลดไฟล์หลายประเภท +``` + +### 2. ใช้ Diagrams และ Examples + +````markdown +### Workflow Diagram + +```mermaid +graph LR + A[Draft] --> B[Submitted] + B --> C{Review} + C -->|Approve| D[Approved] + C -->|Reject| E[Rejected] +``` +```` + +```` + +### 3. อ้างอิงเอกสารที่เกี่ยวข้อง + +```markdown +## Related Documents + +- Requirements: [03.2-correspondence.md](./03.2-correspondence.md) +- Architecture: [system-architecture.md](../02-architecture/system-architecture.md) +- ADR: [ADR-001: Workflow Engine](../05-decisions/001-workflow-engine.md) +- Implementation: [Backend Plan](../../docs/2_Backend_Plan_V1_4_5.md) +```` + +### 4. Version Control + +```markdown +--- + +**Document History**: + +| Version | Date | Author | Changes | +| ------- | ---------- | ---------- | --------------- | +| 1.0.0 | 2025-01-15 | John Doe | Initial version | +| 1.1.0 | 2025-02-20 | Jane Smith | Add CC support | +| 1.2.0 | 2025-03-10 | John Doe | Update workflow | + +**Current Version**: 1.2.0 +**Status**: Approved +**Last Updated**: 2025-03-10 +``` + +### 5. ใช้ Consistent Terminology + +อ้างอิงจาก [glossary.md](./specs/00-overview/glossary.md) เสมอ + +```markdown +- ✅ ใช้: "Correspondence" (เอกสารโต้ตอบ) +- ❌ ไม่ใช้: "Letter", "Document", "Communication" + +- ✅ ใช้: "RFA" (Request for Approval) +- ❌ ไม่ใช้: "Approval Request", "Submit for Approval" +``` + +--- + +## 🛠️ Tools & Resources + +### Markdown Tools + +```bash +# Lint markdown files +pnpm run lint:markdown + +# Fix markdown issues +pnpm run lint:markdown:fix + +# Preview specs (if available) +pnpm run preview:specs +``` + +### Recommended VS Code Extensions + +```json +{ + "recommendations": [ + "yzhang.markdown-all-in-one", + "DavidAnson.vscode-markdownlint", + "bierner.markdown-mermaid", + "shd101wyy.markdown-preview-enhanced", + "streetsidesoftware.code-spell-checker" + ] +} +``` + +### Markdown Linting Rules + +Create `.markdownlint.json`: + +```json +{ + "default": true, + "MD013": false, + "MD033": false, + "MD041": false +} +``` + +### Diagram Tools + +- **Mermaid**: สำหรับ flowcharts, sequence diagrams +- **PlantUML**: สำหรับ UML diagrams +- **Draw.io**: สำหรับ architecture diagrams + +### Reference Documents + +- [Markdown Guide](https://www.markdownguide.org/) +- [Mermaid Documentation](https://mermaid-js.github.io/) +- [ADR Template](https://github.com/joelparkerhenderson/architecture-decision-record) + +--- + +## 📞 Getting Help + +### คำถามเกี่ยวกับ Specs + +1. **ตรวจสอบเอกสารที่มีอยู่**: [specs/](./specs/) +2. **ดู Glossary**: [specs/00-overview/glossary.md](./specs/00-overview/glossary.md) +3. **ค้นหา Issues**: [Gitea Issues](https://git.np-dms.work/lcbp3/lcbp3-dms/issues) +4. **ถาม Team**: [ช่องทางการติดต่อ] + +### การรายงานปัญหา + +```markdown +**Title**: [SPEC] [Category] [Brief description] + +**Description**: + +- **Current State**: [อธิบายปัญหาปัจจุบัน] +- **Expected State**: [อธิบายสิ่งที่ควรจะเป็น] +- **Affected Documents**: [ระบุเอกสารที่เกี่ยวข้อง] +- **Proposed Solution**: [เสนอแนะวิธีแก้ไข] + +**Labels**: spec, [category] +``` + +--- + +## 🎯 Quality Standards + +### Definition of Done (DoD) สำหรับ Spec Changes + +- [x] เนื้อหาครบถ้วนตามโครงสร้าง +- [x] ใช้ภาษาไทยสำหรับเนื้อหาหลัก +- [x] มี code examples (ถ้าเกี่ยวข้อง) +- [x] มี diagrams (ถ้าจำเป็น) +- [x] อัพเดท Table of Contents +- [x] อัพเดท Last Updated date +- [x] ผ่าน markdown linting +- [x] ตรวจสอบ internal links +- [x] เพิ่ม Related Documents +- [x] ผ่าน L1 Peer Review +- [x] ผ่าน L2 Technical Review +- [x] ได้รับ L3 Approval + +--- + +## 📜 License & Copyright + +เอกสาร Specifications ทั้งหมดเป็นทรัพย์สินของโครงการ LCBP3-DMS +**Internal Use Only** - ห้ามเผยแพร่ภายนอก + +--- + +## 🙏 Acknowledgments + +ขอบคุณทุกท่านที่มีส่วนร่วมในการพัฒนาเอกสาร Specifications ของโครงการ! + +--- + +
+ +**Questions?** Contact the Tech Lead or Project Manager + +[Specs Directory](./specs) • [Main README](./README.md) • [Documentation](./docs) + +
diff --git a/README.md b/README.md index 965a175..4480997 100644 --- a/README.md +++ b/README.md @@ -1 +1,509 @@ -# Project documentation hub +# 📋 LCBP3-DMS - Document Management System + +> **Laem Chabang Port Phase 3 - Document Management System** +> +> ระบบบริหารจัดการเอกสารโครงการแบบครบวงจร สำหรับโครงการก่อสร้างท่าเรือแหลมฉบังระยะที่ 3 + +[![Version](https://img.shields.io/badge/version-1.4.5-blue.svg)](./CHANGELOG.md) +[![License](https://img.shields.io/badge/license-Internal-red.svg)]() +[![Status](https://img.shields.io/badge/status-In%20Development-yellow.svg)]() + +--- + +## 🎯 ภาพรวมโครงการ + +LCBP3-DMS เป็นระบบบริหารจัดการเอกสารโครงการที่ออกแบบมาเพื่อรองรับการทำงานของโครงการก่อสร้างขนาดใหญ่ โดยเน้นที่: + +- **ความปลอดภัยสูงสุด** - Security-first approach ด้วย RBAC 4 ระดับ +- **ความถูกต้องของข้อมูล** - Data Integrity ผ่าน Transaction และ Locking Mechanisms +- **ความยืดหยุ่น** - Unified Workflow Engine รองรับ Workflow ที่ซับซ้อน +- **ความทนทาน** - Resilience Patterns และ Error Handling ที่ครอบคลุม + +### ✨ ฟีเจอร์หลัก + +- 📝 **Correspondence Management** - จัดการเอกสารโต้ตอบระหว่างองค์กร +- 🔧 **RFA Management** - ระบบขออนุมัติเอกสารทางเทคนิค +- 📐 **Drawing Management** - จัดการแบบก่อสร้างและแบบคู่สัญญา +- 🔄 **Workflow Engine** - DSL-based workflow สำหรับกระบวนการอนุมัติ +- 📊 **Advanced Search** - ค้นหาเอกสารด้วย Elasticsearch +- 🔐 **RBAC 4-Level** - ควบคุมสิทธิ์แบบละเอียด (Global, Organization, Project, Contract) +- 📁 **Two-Phase File Storage** - จัดการไฟล์แบบ Transactional พร้อม Virus Scanning +- 🔢 **Document Numbering** - สร้างเลขที่เอกสารอัตโนมัติ ป้องกัน Race Condition + +--- + +## 🏗️ สถาปัตยกรรมระบบ + +### Technology Stack + +#### Backend (NestJS) + +```typescript +{ + "framework": "NestJS (TypeScript, ESM)", + "database": "MariaDB 10.11", + "orm": "TypeORM", + "authentication": "JWT + Passport", + "authorization": "CASL (RBAC)", + "search": "Elasticsearch", + "cache": "Redis", + "queue": "BullMQ", + "fileUpload": "Multer + ClamAV", + "notification": "Nodemailer + n8n (LINE)", + "documentation": "Swagger" +} +``` + +#### Frontend (Next.js) + +```typescript +{ + "framework": "Next.js 14+ (App Router)", + "language": "TypeScript", + "styling": "Tailwind CSS", + "components": "shadcn/ui", + "stateManagement": { + "server": "TanStack Query (React Query)", + "forms": "React Hook Form + Zod", + "ui": "useState/useReducer" + }, + "testing": "Vitest + Playwright" +} +``` + +#### Infrastructure + +- **Server**: QNAP TS-473A (AMD Ryzen V1500B, 32GB RAM) +- **Containerization**: Docker + Docker Compose (Container Station) +- **Reverse Proxy**: Nginx Proxy Manager +- **Version Control**: Gitea (Self-hosted) +- **Domain**: `np-dms.work` + +### โครงสร้างระบบ + +``` +┌─────────────────┐ +│ Nginx Proxy │ ← SSL/TLS Termination +│ Manager │ +└────────┬────────┘ + │ + ┌────┴────┬────────────┬──────────┐ + │ │ │ │ +┌───▼───┐ ┌──▼──┐ ┌─────▼────┐ ┌──▼──┐ +│Next.js│ │NestJS│ │Elasticsearch│ │ n8n │ +│Frontend│ │Backend│ │ Search │ │Workflow│ +└───────┘ └──┬──┘ └──────────┘ └─────┘ + │ + ┌────────┼────────┐ + │ │ │ +┌───▼───┐ ┌─▼──┐ ┌──▼────┐ +│MariaDB│ │Redis│ │ClamAV │ +│ DB │ │Cache│ │ Scan │ +└───────┘ └────┘ └───────┘ +``` + +--- + +## 🚀 เริ่มต้นใช้งาน + +### ข้อกำหนดระบบ + +- **Node.js**: v20.x หรือสูงกว่า +- **pnpm**: v8.x หรือสูงกว่า +- **Docker**: v24.x หรือสูงกว่า +- **MariaDB**: 10.11 +- **Redis**: 7.x + +### การติดตั้ง + +#### 1. Clone Repository + +```bash +git clone https://git.np-dms.work/lcbp3/lcbp3-dms.git +cd lcbp3-dms +``` + +#### 2. ติดตั้ง Dependencies + +```bash +# ติดตั้ง dependencies ทั้งหมด (backend + frontend) +pnpm install +``` + +#### 3. ตั้งค่า Environment Variables + +**Backend:** + +```bash +cd backend +cp .env.example .env +# แก้ไข .env ตามความเหมาะสม +``` + +**Frontend:** + +```bash +cd frontend +cp .env.local.example .env.local +# แก้ไข .env.local ตามความเหมาะสม +``` + +#### 4. ตั้งค่า Database + +```bash +# Import schema +mysql -u root -p lcbp3_dev < docs/8_lcbp3_v1_4_5.sql + +# Import seed data +mysql -u root -p lcbp3_dev < docs/8_lcbp3_v1_4_5_seed.sql +``` + +#### 5. รัน Development Server + +**Backend:** + +```bash +cd backend +pnpm run start:dev +``` + +**Frontend:** + +```bash +cd frontend +pnpm run dev +``` + +### การเข้าถึงระบบ + +- **Frontend**: `http://localhost:3000` +- **Backend API**: `http://localhost:3001` +- **API Documentation**: `http://localhost:3001/api` + +### ข้อมูลเข้าสู่ระบบเริ่มต้น + +``` +Superadmin: + Username: admin@np-dms.work + Password: (ดูใน seed data) +``` + +--- + +## 📁 โครงสร้างโปรเจกต์ + +``` +lcbp3-dms/ +├── backend/ # NestJS Backend +│ ├── src/ +│ │ ├── common/ # Shared modules +│ │ ├── modules/ # Feature modules +│ │ │ ├── auth/ +│ │ │ ├── user/ +│ │ │ ├── project/ +│ │ │ ├── correspondence/ +│ │ │ ├── rfa/ +│ │ │ ├── drawing/ +│ │ │ ├── workflow-engine/ +│ │ │ └── ... +│ │ └── main.ts +│ ├── test/ +│ └── package.json +│ +├── frontend/ # Next.js Frontend +│ ├── app/ # App Router +│ ├── components/ # React Components +│ ├── lib/ # Utilities +│ └── package.json +│ +├── docs/ # 📚 เอกสารโครงการ +│ ├── 0_Requirements_V1_4_5.md +│ ├── 1_FullStackJS_V1_4_5.md +│ ├── 2_Backend_Plan_V1_4_5.md +│ ├── 3_Frontend_Plan_V1_4_5.md +│ ├── 4_Data_Dictionary_V1_4_5.md +│ ├── 8_lcbp3_v1_4_5.sql +│ └── 8_lcbp3_v1_4_5_seed.sql +│ +├── infrastructure/ # Docker & Deployment +│ └── Markdown/ # Legacy docs +│ +└── pnpm-workspace.yaml +``` + +--- + +## 📚 เอกสารประกอบ + +### เอกสารหลัก + +| เอกสาร | คำอธิบาย | ไฟล์ | +| ------------------------- | ------------------------------------------ | ----------------------------------------------------------------- | +| **Requirements** | ข้อกำหนดระบบและฟังก์ชันการทำงาน | [0_Requirements_V1_4_5.md](./docs/0_Requirements_V1_4_5.md) | +| **Full Stack Guidelines** | แนวทางการพัฒนา TypeScript/NestJS/Next.js | [1_FullStackJS_V1_4_5.md](./docs/1_FullStackJS_V1_4_5.md) | +| **Backend Plan** | แผนการพัฒนา Backend แบบ Phase-Based | [2_Backend_Plan_V1_4_5.md](./docs/2_Backend_Plan_V1_4_5.md) | +| **Frontend Plan** | แผนการพัฒนา Frontend | [3_Frontend_Plan_V1_4_5.md](./docs/3_Frontend_Plan_V1_4_5.md) | +| **Data Dictionary** | โครงสร้างฐานข้อมูลและ Entity Relationships | [4_Data_Dictionary_V1_4_5.md](./docs/4_Data_Dictionary_V1_4_5.md) | + +### เอกสารเพิ่มเติม + +- **Database Schema**: [8_lcbp3_v1_4_5.sql](./docs/8_lcbp3_v1_4_5.sql) +- **Seed Data**: [8_lcbp3_v1_4_5_seed.sql](./docs/8_lcbp3_v1_4_5_seed.sql) +- **Changelog**: [CHANGELOG.md](./CHANGELOG.md) +- **Contributing**: [CONTRIBUTING.md](./CONTRIBUTING.md) + +--- + +## 🔧 Development Guidelines + +### Coding Standards + +#### ภาษาที่ใช้ + +- **Code**: ภาษาอังกฤษ (English) +- **Comments & Documentation**: ภาษาไทย (Thai) + +#### TypeScript Rules + +```typescript +// ✅ ถูกต้อง +interface User { + user_id: number; // Property: snake_case + firstName: string; // Variable: camelCase + isActive: boolean; // Boolean: Verb + Noun +} + +// ❌ ผิด +interface User { + userId: number; // ไม่ใช้ camelCase สำหรับ property + first_name: string; // ไม่ใช้ snake_case สำหรับ variable + active: boolean; // ไม่ใช้ Verb + Noun +} +``` + +#### File Naming + +``` +user-service.ts ✅ kebab-case +UserService.ts ❌ PascalCase +user_service.ts ❌ snake_case +``` + +### Git Workflow + +```bash +# สร้าง feature branch +git checkout -b feature/correspondence-module + +# Commit message format +git commit -m "feat(correspondence): add create correspondence endpoint" + +# Types: feat, fix, docs, style, refactor, test, chore +``` + +### Testing + +```bash +# Backend +cd backend +pnpm test # Unit tests +pnpm test:e2e # E2E tests +pnpm test:cov # Coverage + +# Frontend +cd frontend +pnpm test # Unit tests +pnpm test:e2e # Playwright E2E +``` + +--- + +## 🔐 Security + +### Security Features + +- ✅ **JWT Authentication** - Access & Refresh Tokens +- ✅ **RBAC 4-Level** - Global, Organization, Project, Contract +- ✅ **Rate Limiting** - ป้องกัน Brute-force +- ✅ **Virus Scanning** - ClamAV สำหรับไฟล์ที่อัปโหลด +- ✅ **Input Validation** - ป้องกัน SQL Injection, XSS, CSRF +- ✅ **Idempotency** - ป้องกันการทำรายการซ้ำ +- ✅ **Audit Logging** - บันทึกการกระทำทั้งหมด + +### Security Best Practices + +1. **ห้ามเก็บ Secrets ใน Git** + + - ใช้ `.env` สำหรับ Development + - ใช้ `docker-compose.override.yml` (gitignored) + +2. **Password Policy** + + - ความยาวขั้นต่ำ: 8 ตัวอักษร + - ต้องมี uppercase, lowercase, number, special character + - เปลี่ยน password ทุก 90 วัน + +3. **File Upload** + - White-list file types: PDF, DWG, DOCX, XLSX, ZIP + - Max size: 50MB + - Virus scan ทุกไฟล์ + +--- + +## 🧪 Testing Strategy + +### Test Pyramid + +``` + /\ + / \ E2E Tests (10%) + /____\ + / \ Integration Tests (20%) + /________\ + / \ Unit Tests (70%) + /____________\ +``` + +### Coverage Goals + +- **Backend**: 70%+ overall + - Business Logic: 80%+ + - Controllers: 70%+ + - Utilities: 90%+ +- **Frontend**: 60%+ overall + +--- + +## 📊 Monitoring & Observability + +### Health Checks + +```bash +# Backend health +curl http://localhost:3001/health + +# Database health +curl http://localhost:3001/health/db + +# Redis health +curl http://localhost:3001/health/redis +``` + +### Metrics + +- API Response Time +- Error Rates +- Cache Hit Ratio +- Database Connection Pool +- File Upload Performance + +--- + +## 🚢 Deployment + +### Production Deployment + +```bash +# Build backend +cd backend +pnpm run build + +# Build frontend +cd frontend +pnpm run build + +# Deploy with Docker Compose +docker-compose -f docker-compose.yml up -d +``` + +### Environment-specific Configs + +- **Development**: `.env`, `docker-compose.override.yml` +- **Staging**: Environment variables ใน Container Station +- **Production**: Docker secrets หรือ Vault + +--- + +## 🤝 Contributing + +กรุณาอ่าน [CONTRIBUTING.md](./CONTRIBUTING.md) สำหรับรายละเอียดเกี่ยวกับ: + +- Code of Conduct +- Development Process +- Pull Request Process +- Coding Standards + +--- + +## 📝 License + +This project is **Internal Use Only** - ลิขสิทธิ์เป็นของโครงการ LCBP3 + +--- + +## 👥 Team + +- **Project Manager**: [ระบุชื่อ] +- **Tech Lead**: [ระบุชื่อ] +- **Backend Team**: [ระบุชื่อ] +- **Frontend Team**: [ระบุชื่อ] + +--- + +## 📞 Support + +สำหรับคำถามหรือปัญหา กรุณาติดต่อ: + +- **Email**: support@np-dms.work +- **Internal Chat**: [ระบุช่องทาง] +- **Issue Tracker**: [Gitea Issues](https://git.np-dms.work/lcbp3/lcbp3-dms/issues) + +--- + +## 🗺️ Roadmap + +### Version 1.4.5 (Current) + +- ✅ Core Infrastructure +- ✅ Authentication & Authorization +- 🔄 Correspondence Module +- 🔄 RFA Module +- 🔄 Workflow Engine + +### Version 1.5.0 (Planned) + +- 📋 Advanced Reporting +- 📊 Dashboard Analytics +- 🔔 Enhanced Notifications +- 📱 Mobile App + +--- + +## 📖 Additional Resources + +### API Documentation + +- Swagger UI: `http://localhost:3001/api` +- Postman Collection: [ดาวน์โหลด](./docs/postman/) + +### Architecture Diagrams + +- [System Architecture](./diagrams/system-architecture.md) +- [Database ERD](./diagrams/database-erd.md) +- [Workflow Engine](./diagrams/workflow-engine.md) + +### Learning Resources + +- [NestJS Documentation](https://docs.nestjs.com/) +- [Next.js Documentation](https://nextjs.org/docs) +- [TypeORM Documentation](https://typeorm.io/) + +--- + +
+ +**Built with ❤️ for LCBP3 Project** + +[Documentation](./docs) • [Issues](https://git.np-dms.work/lcbp3/lcbp3-dms/issues) • [Changelog](./CHANGELOG.md) + +
diff --git a/docs/temp.md b/docs/temp.md new file mode 100644 index 0000000..86c80a6 --- /dev/null +++ b/docs/temp.md @@ -0,0 +1,714 @@ +# 🚀 GitHub Spec Kit: การใช้งานร่วมกับ Requirements & FullStackJS v1.4.5 + +## ðŸ"‹ ภาพรวม + +GitHub Spec Kit เป็นเครื่องมือที่ช่วยให้คุณสร้าง **Issue Specifications** ที่มีโครงสร้างชัดเจนและครบถ้วนสำหรับโปรเจค LCBP3-DMS โดยอ้างอิง Requirements v1.4.5 และ FullStackJS v1.4.5 + +--- + +## 🎯 วัตถุประสงค์หลัก + +1. **แปลง Requirements เป็น Actionable Tasks** - แบ่งความต้องการขนาดใหญ่เป็น issues ขนาดเล็กที่ทำได้จริง +2. **รักษา Standards** - ทุก issue ต้องสอดคล้องกับ FullStackJS Guidelines +3. **Traceability** - อ้างอิงกลับไปยัง Requirements ได้ทุกครั้ง +4. **Consistency** - ใช้ template และรูปแบบเดียวกันทั้งโปรเจค + +--- + +## ðŸ"š โครงสร้าง Spec Kit + +### 1. **Issue Title Format** + +``` +[] : +``` + +**ตัวอย่าง:** + +- `[RFA] Feature: Implement RFA Creation Workflow` +- `[Auth] Security: Add Rate Limiting to Login Endpoint` +- `[File] Refactor: Implement Two-Phase Storage Strategy` + +### 2. **Issue Labels** + +- **Type:** `feature`, `bug`, `refactor`, `security`, `performance` +- **Priority:** `critical`, `high`, `medium`, `low` +- **Module:** `backend`, `frontend`, `database`, `infrastructure` +- **Status:** `blocked`, `in-progress`, `review-needed` + +### 3. **Issue Template Structure** + +```markdown +## 📋 Overview + +[Brief description of what needs to be done] + +## 🎯 Requirements Reference + +- **Section:** [Requirements v1.4.5 - Section X.X] +- **Related:** [Link to specific requirement] + +## ðŸ'» Technical Specifications + +### Backend (NestJS) + +- Module: `` +- Files to modify: + - [ ] `src/modules//.ts` +- Dependencies: `` + +### Frontend (Next.js) + +- Pages/Components: + - [ ] `app//page.tsx` +- Dependencies: `` + +### Database + +- Tables affected: `` +- Migrations needed: [ ] Yes / [ ] No + +## ✅ Acceptance Criteria + +- [ ] Criterion 1 +- [ ] Criterion 2 +- [ ] Security checks passed +- [ ] Tests written and passing +- [ ] Documentation updated + +## 🧪 Testing Requirements + +- [ ] Unit tests (70% coverage minimum) +- [ ] Integration tests +- [ ] E2E tests (if applicable) + +## 🔒 Security Checklist + +- [ ] Input validation implemented +- [ ] RBAC permissions checked +- [ ] Audit logging added +- [ ] No sensitive data in logs + +## ðŸ"— Related Issues + +- Blocks: # +- Depends on: # +- Related to: # + +## ðŸ"Œ Notes + +[Any additional context, decisions, or constraints] +``` + +--- + +## ðŸ› ï¸ วิธีการใช้งาน + +### **Step 1: ระบุ Feature จาก Requirements** + +อ้างอิง: `0_Requirements_V1_4_5.md` + +**ตัวอย่าง:** + +``` +Section 3.3: การจัดการเอกสารขออนุมัติ (RFA) +``` + +### **Step 2: สร้าง Issue Specification** + +**Title:** + +``` +[RFA] Feature: Implement RFA Creation with Workflow Engine +``` + +**Overview:** + +```markdown +## 📋 Overview + +Implement the RFA (Request for Approval) creation workflow that allows +Document Control users to create RFAs with multiple revisions and trigger +the unified workflow engine. + +## 🎯 Requirements Reference + +- **Section:** Requirements v1.4.5 - Section 3.3 +- **Page Reference:** Lines 250-275 +- **Key Requirements:** + - Support PDF file uploads only [3.3.2] + - Multiple revisions support [3.3.2] + - Draft/Submitted state management [3.3.3] + - Integration with Unified Workflow Engine [3.3.5] +``` + +### **Step 3: กำหนด Technical Specs ตาม FullStackJS** + +อ้างอิง: `1_FullStackJS_V1_4_5.md` + +````markdown +## ðŸ'» Technical Specifications + +### Backend (NestJS) + +- **Module:** `RfaModule` [Section 3.9.7] +- **Files to modify:** + + - [ ] `src/modules/rfa/rfa.controller.ts` + - [ ] `src/modules/rfa/rfa.service.ts` + - [ ] `src/modules/rfa/dto/create-rfa.dto.ts` + - [ ] `src/modules/workflow/workflow-engine.service.ts` + +- **Dependencies:** + ```json + { + "@nestjs/typeorm": "^10.0.0", + "class-validator": "^0.14.0", + "class-transformer": "^0.5.1" + } + ``` +```` + +- **Implementation Guidelines:** + - Use Two-Phase Storage for file uploads [Section 3.3] + - Apply Optimistic Locking for race conditions [Section 3.2.1] + - Integrate with DocumentNumberingService [Section 3.9.12] + - Follow RBAC permissions [Section 5.4] + +### Frontend (Next.js) + +- **Pages/Components:** + + - [ ] `app/rfas/new/page.tsx` + - [ ] `components/rfa/rfa-form.tsx` + - [ ] `components/rfa/revision-manager.tsx` + +- **Dependencies:** + + ```json + { + "react-hook-form": "^7.50.0", + "zod": "^3.22.0", + "@tanstack/react-query": "^5.20.0" + } + ``` + +- **State Management:** [Section 4.10] + - Use React Query for server state + - Use React Hook Form for form state + - Implement auto-save drafts to localStorage [Section 4.1.1] + +### Database + +- **Tables affected:** + + - `rfas` - main table + - `rfa_revisions` - revision history + - `rfa_items` - related items + - `workflow_instances` - workflow state + +- **Migrations needed:** [ ✓ ] Yes + - Create migration for virtual columns if using JSON [Section 3.2.2] + +```` + +### **Step 4: กำหนด Acceptance Criteria** + +```markdown +## ✅ Acceptance Criteria + +### Functional Requirements +- [ ] Document Control users can create new RFAs +- [ ] Support PDF file upload (max 50MB) [Section 3.10.1] +- [ ] RFA can have multiple revisions [Section 3.3.2] +- [ ] RFA number auto-generated using format template [Section 3.11] +- [ ] Draft state allows editing, Submitted state is read-only [Section 3.3.3] +- [ ] Triggers workflow engine on submission [Section 3.3.5] + +### Non-Functional Requirements +- [ ] API response time < 200ms (excluding file processing) [Section 6.4] +- [ ] Virus scanning implemented for all uploads [Section 3.10.2] +- [ ] File integrity checks (checksum) performed [Section 3.10.3] +- [ ] Audit log entry created for all actions [Section 6.1] +- [ ] RBAC permissions enforced (rfas.create) [Section 5.4.2] + +### Security Requirements +- [ ] Input validation using class-validator [Section 2.1] +- [ ] Rate limiting applied (1000 req/hour for Editor) [Section 6.5.1] +- [ ] No sensitive data in error messages [Section 6.5.4] +- [ ] Download links expire after 24 hours [Section 3.10.2] +```` + +### **Step 5: กำหนด Testing Requirements** + +```markdown +## 🧪 Testing Requirements + +### Unit Tests (Jest) [Section 3.14] + +- [ ] RfaService.create() - success case +- [ ] RfaService.create() - validation failures +- [ ] RfaService.create() - file upload failures +- [ ] RfaService.create() - race condition handling +- [ ] DocumentNumberingService integration +- **Target Coverage:** 70% minimum [Section 7.1] + +### Integration Tests (Supertest) [Section 7.2] + +- [ ] POST /api/rfas - with valid file upload +- [ ] POST /api/rfas - with invalid file type +- [ ] POST /api/rfas - with virus-infected file +- [ ] POST /api/rfas - without required permissions +- [ ] Workflow engine integration test + +### E2E Tests (Playwright) [Section 7.3] + +- [ ] Complete RFA creation flow +- [ ] File upload with drag-and-drop +- [ ] Form auto-save and recovery +- [ ] Error handling and user feedback + +### Security Tests [Section 7.4] + +- [ ] SQL injection attempts blocked +- [ ] XSS attacks prevented +- [ ] File upload security bypass attempts +- [ ] Rate limiting enforcement +``` + +### **Step 6: Security Checklist** + +```markdown +## 🔒 Security Checklist [Section 6.5] + +### Input Validation + +- [ ] All DTOs use class-validator [Section 3.1] +- [ ] File type white-list enforced (PDF only) [Section 3.10.1] +- [ ] File size limit checked (50MB max) [Section 3.10.1] +- [ ] JSON schema validation for details field [Section 3.12] + +### Authentication & Authorization + +- [ ] JWT token validation [Section 5.1] +- [ ] RBAC permission check (rfas.create) [Section 5.4] +- [ ] Organization scope validation [Section 4.2] +- [ ] Session tracking implemented [Section 6.5.4] + +### Data Protection + +- [ ] Audit log entry created [Section 8.1] +- [ ] Sensitive data not logged [Section 6.5.4] +- [ ] File integrity checksum stored [Section 3.10.3] +- [ ] Virus scanning completed [Section 3.10.2] + +### Rate Limiting [Section 6.5.1] + +- [ ] Editor: 1000 req/hour +- [ ] File Upload: 50 req/hour +- [ ] Fallback for rate limiter failures +``` + +--- + +## ðŸ"Š ตัวอย่าง Issue ที่สมบูรณ์ + +### Issue #1: [RFA] Feature: Implement RFA Creation with Workflow Engine + +````markdown +## 📋 Overview + +Implement the RFA (Request for Approval) creation workflow that allows +Document Control users to create RFAs with multiple revisions and trigger +the unified workflow engine. + +## 🎯 Requirements Reference + +- **Section:** Requirements v1.4.5 - Section 3.3 +- **Lines:** 250-275 +- **Key Requirements:** + - วัตถุประสงค์: เอกสารขออนุมัติ (RFA) ภายใน โครงการ [3.3.1] + - ประเภทเอกสาร: รองรับเอกสารรูปแบบ ไฟล์ PDF [3.3.2] + - รองรับ Multiple Revisions [3.3.2] + - Draft/Submitted State Management [3.3.3] + - Unified Workflow Integration [3.3.5] + +## ðŸ'» Technical Specifications + +### Backend (NestJS) + +**Module:** `RfaModule` [FullStackJS Section 3.9.7] + +**Files to create/modify:** + +- [ ] `src/modules/rfa/rfa.controller.ts` +- [ ] `src/modules/rfa/rfa.service.ts` +- [ ] `src/modules/rfa/dto/create-rfa.dto.ts` +- [ ] `src/modules/rfa/entities/rfa.entity.ts` +- [ ] `src/modules/rfa/entities/rfa-revision.entity.ts` +- [ ] `src/modules/workflow/workflow-engine.service.ts` + +**Dependencies:** + +```json +{ + "@nestjs/typeorm": "^10.0.0", + "class-validator": "^0.14.0", + "class-transformer": "^0.5.1", + "uuid": "^9.0.0" +} +``` +```` + +**Implementation Guidelines:** + +1. **File Storage:** Use Two-Phase Storage Strategy [FullStackJS 3.3] + + - Phase 1: Upload to `temp/` with virus scan + - Phase 2: Move to `permanent/{YYYY}/{MM}/` on commit + +2. **Concurrency:** Apply Optimistic Locking [FullStackJS 3.2.1] + + ```typescript + @VersionColumn() + version: number; + ``` + +3. **Document Numbering:** [FullStackJS 3.9.12] + + - Inject `DocumentNumberingService` + - Use Redis distributed lock for counter + - Format: `{ORG}-RFA-{DISCIPLINE}-{SEQ:4}-{REV}` + +4. **Workflow Integration:** [FullStackJS 3.9.14] + - Call `WorkflowEngineService.createInstance()` + - Set initial state to 'DRAFT' + - Transition to workflow on submission + +### Frontend (Next.js) + +**Pages/Components:** + +- [ ] `app/rfas/new/page.tsx` - Main creation page +- [ ] `components/rfa/rfa-form.tsx` - Form component +- [ ] `components/rfa/revision-manager.tsx` - Revision UI +- [ ] `components/file-upload/multi-file-upload.tsx` - File upload + +**Dependencies:** + +```json +{ + "react-hook-form": "^7.50.0", + "zod": "^3.22.0", + "@tanstack/react-query": "^5.20.0", + "react-dropzone": "^14.2.3" +} +``` + +**State Management:** [FullStackJS 4.10] + +- **Server State:** React Query for RFA data +- **Form State:** React Hook Form + Zod validation +- **Auto-save:** LocalStorage for drafts [FullStackJS 4.1.1] + +**File Upload UX:** [FullStackJS 5.7] + +```typescript +// Multi-file drag-and-drop +// Distinguish between "Main Document" and "Supporting Attachments" +// Show virus scan progress +// Display file type icons and security warnings +``` + +### Database + +**Tables affected:** + +- `rfas` - Main RFA table +- `rfa_revisions` - Revision history +- `rfa_items` - Related items +- `workflow_instances` - Workflow state +- `attachments` - File metadata +- `rfa_attachments` - Junction table + +**Migrations needed:** [ ✓ ] Yes + +```sql +-- Example migration structure +CREATE TABLE rfas ( + rfa_id INT PRIMARY KEY AUTO_INCREMENT, + project_id INT NOT NULL, + rfa_number VARCHAR(100) UNIQUE NOT NULL, + current_state VARCHAR(50), + version INT DEFAULT 1, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + deleted_at TIMESTAMP NULL, + FOREIGN KEY (project_id) REFERENCES projects(project_id) +); +``` + +## ✅ Acceptance Criteria + +### Functional Requirements + +- [ ] Document Control users can create new RFAs +- [ ] Support PDF file upload (max 50MB) [Req 3.10.1] +- [ ] RFA can have multiple revisions [Req 3.3.2] +- [ ] RFA number auto-generated: `{ORG}-RFA-{DISCIPLINE}-{SEQ:4}-{REV}` [Req 3.11] +- [ ] Draft state allows editing, Submitted state is read-only [Req 3.3.3] +- [ ] Admin can cancel/revert submitted RFAs [Req 3.3.3] +- [ ] Triggers unified workflow engine on submission [Req 3.3.5] +- [ ] Can reference Shop Drawings in RFA [Req 3.3.4] + +### Non-Functional Requirements + +- [ ] API response time < 200ms (excluding file processing) [Req 6.4] +- [ ] File upload completes < 30 seconds for 50MB [Req 6.4] +- [ ] Virus scanning implemented (ClamAV) [Req 3.10.2] +- [ ] File integrity checks (checksum) performed [Req 3.10.3] +- [ ] Audit log entry created for all actions [Req 6.1] +- [ ] RBAC permissions enforced (rfas.create, rfas.respond) [Req 5.4.2] + +### UI/UX Requirements [FullStackJS 5.7] + +- [ ] Form uses React Hook Form + Zod validation +- [ ] Multi-file drag-and-drop interface +- [ ] Clear distinction between main document and attachments +- [ ] Real-time virus scan feedback +- [ ] File type indicators and security warnings +- [ ] Auto-save draft to localStorage every 30 seconds +- [ ] Mobile-responsive (Card View on small screens) + +### Security Requirements [Req 6.5] + +- [ ] Input validation using class-validator +- [ ] Rate limiting: Editor 1000 req/hour, File Upload 50 req/hour +- [ ] No sensitive data in error messages +- [ ] Download links expire after 24 hours +- [ ] Files stored outside web root +- [ ] Access control checks before file download + +## 🧪 Testing Requirements + +### Unit Tests (Jest) [FullStackJS 3.14] + +```typescript +describe('RfaService', () => { + describe('create', () => { + it('should create RFA with valid data'); + it('should reject invalid file types'); + it('should handle race conditions with optimistic locking'); + it('should generate correct RFA number'); + it('should trigger workflow on submission'); + }); +}); +``` + +- **Target Coverage:** 70% minimum [Req 7.1] + +### Integration Tests (Supertest) [FullStackJS 3.14] + +```typescript +describe('POST /api/rfas', () => { + it('should create RFA with file upload'); + it('should reject virus-infected files'); + it('should enforce RBAC permissions'); + it('should create workflow instance'); +}); +``` + +### E2E Tests (Playwright) [FullStackJS 4.9] + +```typescript +test('Complete RFA creation flow', async ({ page }) => { + // Login as Document Control user + // Navigate to RFA creation page + // Fill form with test data + // Upload main document (PDF) + // Upload supporting attachment + // Verify auto-save works + // Submit RFA + // Verify workflow starts +}); +``` + +### Security Tests [Req 7.4] + +- [ ] SQL injection attempts blocked +- [ ] XSS attacks prevented +- [ ] File upload security bypass attempts +- [ ] Rate limiting enforcement +- [ ] Unauthorized access attempts blocked + +## 🔒 Security Checklist [Req 6.5] + +### Input Validation + +- [ ] All DTOs use class-validator decorators +- [ ] File type white-list enforced (PDF only) +- [ ] File size limit checked (50MB max) +- [ ] JSON schema validation for details field +- [ ] Sanitize all user inputs + +### Authentication & Authorization + +- [ ] JWT token validation on all endpoints +- [ ] RBAC permission check (rfas.create, rfas.respond) +- [ ] Organization scope validation +- [ ] Project membership validation +- [ ] Session tracking and concurrent session limits + +### Data Protection + +- [ ] Audit log entry for: create, update, submit, cancel +- [ ] Sensitive data not logged (file contents, user emails) +- [ ] File integrity checksum stored in database +- [ ] Virus scanning before file is accessible +- [ ] Encrypted storage for sensitive metadata + +### Rate Limiting [Req 6.5.1] + +- [ ] Document Control: 2000 req/hour +- [ ] File Upload: 50 req/hour per user +- [ ] Graceful degradation if Redis unavailable +- [ ] Alert on rate limit violations + +## ðŸ"— Related Issues + +- **Depends on:** + + - # FileStorageService implementation + - # WorkflowEngine implementation + - # DocumentNumberingService implementation + +- **Blocks:** + + - # RFA Response/Approval workflow + - # RFA Reports and Analytics + +- **Related to:** + - # Shop Drawing reference system + - # Unified Workflow Engine + +## ðŸ"Œ Notes + +### Design Decisions + +1. **Why Two-Phase Storage?** + + - Prevents orphan files if transaction fails + - Allows virus scanning before commitment + - Reference: FullStackJS Section 3.3 + +2. **Why Application-level Locking?** + + - More portable than database stored procedures + - Better observability with Redis + - Reference: FullStackJS Section 3.9.12 + +3. **Why Optimistic Locking?** + - Better performance than pessimistic locks + - Handles concurrent updates gracefully + - Reference: FullStackJS Section 3.2.1 + +### Implementation Order + +1. Backend: Entity, DTO, Service (with tests) +2. Backend: Controller, Guards, Interceptors +3. Database: Migration scripts +4. Frontend: Form component (with validation) +5. Frontend: File upload component +6. Frontend: Integration with API +7. E2E: Complete user flow test + +### Risk Mitigation + +- **File Upload Failures:** Implement retry with exponential backoff +- **Virus Scan Downtime:** Queue files for later scanning, block download +- **Database Contention:** Redis lock + Optimistic lock dual protection +- **Large Files:** Stream uploads, show progress indicator + +--- + +## ðŸ"Œ Labels + +`feature` `backend` `frontend` `database` `high-priority` `requires-testing` + +## 👤 Assignment + +- **Backend:** @backend-team +- **Frontend:** @frontend-team +- **QA:** @qa-team + +## ⏱ï¸ Estimated Effort + +- **Backend:** 5 days +- **Frontend:** 3 days +- **Testing:** 2 days +- **Total:** 10 days + +```` + +--- + +## ðŸ"§ Best Practices + +### 1. **ความละเอียดที่เหมาะสม** +- ✅ **DO:** แบ่ง issue ให้ทำเสร็จภายใน 1-2 สัปดาห์ +- ❌ **DON'T:** สร้าง issue ขนาดใหญ่ที่ใช้เวลาเป็นเดือน + +### 2. **การอ้างอิง** +- ✅ **DO:** อ้างอิง section และ line numbers จาก Requirements +- ✅ **DO:** อ้างอิง section จาก FullStackJS Guidelines +- ❌ **DON'T:** Copy-paste ข้อความยาวๆ ทั้งหมด + +### 3. **Acceptance Criteria** +- ✅ **DO:** เขียนเป็นข้อๆ ที่ตรวจสอบได้ (testable) +- ✅ **DO:** แยก functional และ non-functional requirements +- ❌ **DON'T:** เขียนคลุมเครือ เช่น "ระบบต้องเร็ว" + +### 4. **Testing** +- ✅ **DO:** ระบุ test cases ที่ต้องเขียนชัดเจน +- ✅ **DO:** ระบุ coverage target (70% minimum) +- ❌ **DON'T:** ปล่อยให้ "เขียน test ภายหลัง" + +### 5. **Security** +- ✅ **DO:** มี Security Checklist ทุก issue ที่เกี่ยวกับ user input +- ✅ **DO:** ระบุ permission ที่ต้องใช้ชัดเจน +- ❌ **DON'T:** คิดว่า "จะเพิ่ม security ทีหลัง" + +--- + +## ðŸ"Š Issue Workflow + +```mermaid +graph LR + A[Create Issue from Req] --> B[Add Technical Specs] + B --> C[Define Acceptance Criteria] + C --> D[Add Testing Requirements] + D --> E[Security Checklist] + E --> F[Link Related Issues] + F --> G[Assign & Estimate] + G --> H[Ready for Development] +```` + +--- + +## ✅ สรุป: ขั้นตอนการสร้าง Issue ที่สมบูรณ์ + +1. **ระบุ Requirement** - เลือก section จาก Requirements v1.4.5 +2. **สร้าง Title** - ใช้รูปแบบ `[Module] Type: Description` +3. **เขียน Overview** - สรุปสั้นๆ ว่าต้องทำอะไร +4. **อ้างอิง Requirements** - ระบุ section และ line numbers +5. **กำหนด Technical Specs** - แยกเป็น Backend, Frontend, Database +6. **ใช้ FullStackJS Guidelines** - อ้างอิง section ที่เกี่ยวข้อง +7. **เขียน Acceptance Criteria** - แยก functional/non-functional +8. **ระบุ Testing Requirements** - Unit, Integration, E2E +9. **Security Checklist** - ครอบคลุม OWASP Top 10 +10. **Link Related Issues** - ระบุ dependencies และ blockers +11. **เพิ่ม Labels & Assignment** - ใส่ label และมอบหมายงาน +12. **Estimate Effort** - ประมาณการเวลาที่ใช้ + +--- + +**เอกสารนี้เป็น Living Document และจะถูกปรับปรุงตามความต้องการของทีมพัฒนา** diff --git a/nap-dms.lcbp3.code-workspace b/nap-dms.lcbp3.code-workspace index ee91a74..406f539 100644 --- a/nap-dms.lcbp3.code-workspace +++ b/nap-dms.lcbp3.code-workspace @@ -1,21 +1,24 @@ { "folders": [+ { - "name": "🗓️ Documents", - "path": "./Documnets" - }, - - { - "name": "🔧 Backend", - "path": "./backend" - }, - { - "name": "🎨 Frontend", - "path": "./frontend" - }, - { "name": "🎯 Root", "path": "./" + }, + { + "name": "🗓️ docs", + "path": "./docs" + }, + { + "name": "🔗 specs", + "path": "./specs" + }, + { + "name": "🔧 Backend", + "path": "./backend" + }, + { + "name": "🎨 Frontend", + "path": "./frontend" } ], "settings": { diff --git a/specs/00-overview/README.md b/specs/00-overview/README.md index 308b0b1..22889d8 100644 --- a/specs/00-overview/README.md +++ b/specs/00-overview/README.md @@ -1 +1,402 @@ -# Project overview +# LCBP3-DMS - Project Overview + +**Project Name:** Laem Chabang Port Phase 3 - Document Management System (LCBP3-DMS) +**Version:** 1.5.0 +**Status:** Planning & Specification Phase +**Last Updated:** 2025-12-01 + +--- + +## 📋 Table of Contents + +- [Project Introduction](#-project-introduction) +- [Key Features](#-key-features) +- [Technology Stack](#-technology-stack) +- [Project Structure](#-project-structure) +- [Quick Links](#-quick-links) +- [Getting Started](#-getting-started) +- [Team & Stakeholders](#-team--stakeholders) + +--- + +## 🎯 Project Introduction + +LCBP3-DMS is a comprehensive Document Management System (DMS) designed specifically for the Laem Chabang Port Phase 3 construction project. The system manages construction documents, workflows, approvals, and communications between multiple organizations including port authority, consultants, contractors, and third parties. + +### Project Objectives + +1. **Centralize Document Management** - Single source of truth for all project documents +2. **Streamline Workflows** - Automated routing and approval processes +3. **Improve Collaboration** - Real-time access for all stakeholders +4. **Ensure Compliance** - Audit trails and document version control +5. **Enhance Efficiency** - Reduce paper-based processes and manual routing + +### Project Scope + +**In Scope:** + +- Correspondence Management (Letters & Communications) +- RFA (Request for Approval) Management +- Drawing Management (Contract & Shop Drawings) +- Workflow Engine (Approvals & Routing) +- Document Numbering System +- File Storage & Management +- Search & Reporting +- User & Access Management +- Audit Logs & Notifications + +**Out of Scope:** + +- Financial Management & Billing +- Procurement & Material Management +- Project Scheduling (Gantt Charts) +- HR & Payroll Systems +- Mobile App (Phase 1 only) + +--- + +## ✨ Key Features + +### 📨 Correspondence Management + +- Create, review, and track official letters +- Master-Revision pattern for version control +- Multi-level approval workflows +- Attachment management +- Automatic document numbering + +### 📋 RFA Management + +- Submit requests for approval +- Item-based RFA structure +- Response tracking (Approved/Approved with Comments/Rejected) +- Revision management +- Integration with workflow engine + +### 📐 Drawing Management + +- Contract Drawings (แบบคู่สัญญา) +- Shop Drawings (แบบก่อสร้าง) with revisions +- Version control & comparison +- Drawing linking and references + +### ⚙️ Workflow Engine + +- DSL-based workflow configuration +- Dynamic routing based on rules +- Parallel & sequential approvals +- Escalation & timeout handling +- Workflow history & audit trail + +### 🗄️ Document Numbering + +- Automatic number generation +- Template-based formatting +- Discipline-specific numbering +- Concurrent request handling (Double-lock mechanism) +- Annual reset support + +### 🔍 Search & Discovery + +- Full-text search (Elasticsearch) +- Advanced filtering +- Document metadata search +- Quick access to recent documents + +### 🔐 Security & Access Control + +- 4-Level Hierarchical RBAC (Global/Organization/Project/Contract) +- JWT-based authentication +- Permission-based access control +- Audit logging +- Session management + +### 📧 Notifications + +- Multi-channel (Email, LINE Notify, In-app) +- Workflow event notifications +- Customizable user preferences +- Async delivery (Queue-based) + +--- + +## 🛠️ Technology Stack + +### Backend + +- **Framework:** NestJS (TypeScript) +- **Database:** MariaDB 10.11 +- **Cache & Queue:** Redis 7.2 +- **Search:** Elasticsearch 8.11 +- **ORM:** TypeORM +- **Authentication:** JWT (JSON Web Tokens) +- **Authorization:** CASL (4-Level RBAC) +- **File Processing:** ClamAV (Virus Scanning) +- **Queue:** BullMQ + +### Frontend + +- **Framework:** Next.js 14+ (App Router) +- **Language:** TypeScript +- **Styling:** Tailwind CSS +- **UI Components:** Shadcn/UI +- **State Management:** React Context / Zustand +- **Forms:** React Hook Form + Zod +- **API Client:** Axios + +### Infrastructure + +- **Deployment:** Docker & Docker Compose +- **Platform:** QNAP Container Station +- **Reverse Proxy:** NGINX +- **Logging:** Winston +- **Monitoring:** Health Checks + Log Aggregation + +--- + +## 📁 Project Structure + +``` +lcbp3/ +├── backend/ # NestJS Backend Application +│ ├── src/ +│ │ ├── modules/ # Feature modules +│ │ ├── common/ # Shared utilities +│ │ ├── config/ # Configuration +│ │ └── migrations/ # Database migrations +│ ├── test/ # Tests +│ └── package.json +│ +├── frontend/ # Next.js Frontend Application +│ ├── app/ # App router pages +│ ├── components/ # React components +│ ├── lib/ # Utilities +│ └── package.json +│ +├── docs/ # Source documentation +│ ├── 0_Requirements_V1_4_5.md +│ ├── 1_FullStackJS_V1_4_5.md +│ ├── 2_Backend_Plan_V1_4_4.md +│ ├── 3_Frontend_Plan_V1_4_4.md +│ └── 4_Data_Dictionary_V1_4_5.md +│ +├── specs/ # Technical Specifications +│ ├── 00-overview/ # Project overview & glossary +│ ├── 01-requirements/ # Functional requirements +│ ├── 02-architecture/ # System architecture +│ ├── 03-implementation/ # Implementation guidelines +│ ├── 04-operations/ # Deployment & operations +│ ├── 05-decisions/ # Architecture Decision Records (ADRs) +│ └── 06-tasks/ # Development tasks +│ +├── docker-compose.yml # Docker services configuration +└── README.md # Project README +``` + +--- + +## 🔗 Quick Links + +### Documentation + +| Category | Document | Description | +| ------------------ | --------------------------------------------------------------------------- | ------------------------------------- | +| **Overview** | [Glossary](./glossary.md) | Technical terminology & abbreviations | +| **Overview** | [Quick Start](./quick-start.md) | 5-minute getting started guide | +| **Requirements** | [Functional Requirements](../01-requirements/03-functional-requirements.md) | Feature specifications | +| **Architecture** | [System Architecture](../02-architecture/system-architecture.md) | Overall system design | +| **Architecture** | [Data Model](../02-architecture/data-model.md) | Database schema | +| **Architecture** | [API Design](../02-architecture/api-design.md) | REST API specifications | +| **Implementation** | [Backend Guidelines](../03-implementation/backend-guidelines.md) | Backend coding standards | +| **Implementation** | [Frontend Guidelines](../03-implementation/frontend-guidelines.md) | Frontend coding standards | +| **Implementation** | [Testing Strategy](../03-implementation/testing-strategy.md) | Testing approach | +| **Operations** | [Deployment Guide](../04-operations/deployment-guide.md) | How to deploy | +| **Operations** | [Monitoring](../04-operations/monitoring-alerting.md) | Monitoring & alerts | +| **Decisions** | [ADR Index](../05-decisions/README.md) | Architecture decisions | +| **Tasks** | [Backend Tasks](../06-tasks/README.md) | Development tasks | + +### Key ADRs + +1. [ADR-001: Unified Workflow Engine](../05-decisions/ADR-001-unified-workflow-engine.md) +2. [ADR-002: Document Numbering Strategy](../05-decisions/ADR-002-document-numbering-strategy.md) +3. [ADR-003: Two-Phase File Storage](../05-decisions/ADR-003-file-storage-approach.md) +4. [ADR-004: RBAC Implementation](../05-decisions/ADR-004-rbac-implementation.md) +5. [ADR-005: Technology Stack](../05-decisions/ADR-005-technology-stack.md) + +--- + +## 🚀 Getting Started + +### For Developers + +1. **Read Documentation** + + - Start with [Quick Start Guide](./quick-start.md) + - Review [System Architecture](../02-architecture/system-architecture.md) + - Study [Backend](../03-implementation/backend-guidelines.md) / [Frontend](../03-implementation/frontend-guidelines.md) guidelines + +2. **Setup Development Environment** + + - Clone repository + - Install Docker & Docker Compose + - Run `docker-compose up` + - Access backend: `http://localhost:3000` + - Access frontend: `http://localhost:3001` + +3. **Start Coding** + - Pick a task from [Backend Tasks](../06-tasks/README.md) + - Follow coding guidelines + - Write tests + - Submit PR for review + +### For Operations Team + +1. **Infrastructure Setup** + + - Review [Environment Setup](../04-operations/environment-setup.md) + - Configure QNAP Container Station + - Setup Docker Compose + +2. **Deployment** + + - Follow [Deployment Guide](../04-operations/deployment-guide.md) + - Configure [Backup & Recovery](../04-operations/backup-recovery.md) + - Setup [Monitoring](../04-operations/monitoring-alerting.md) + +3. **Maintenance** + - Review [Maintenance Procedures](../04-operations/maintenance-procedures.md) + - Setup [Incident Response](../04-operations/incident-response.md) + - Configure [Security Operations](../04-operations/security-operations.md) + +--- + +## 👥 Team & Stakeholders + +### Project Team + +- **System Architect:** Nattanin Peancharoen +- **Backend Team Lead:** [Name] +- **Frontend Team Lead:** [Name] +- **DevOps Engineer:** [Name] +- **QA Lead:** [Name] +- **Database Administrator:** [Name] + +### Stakeholders + +- **Port Authority of Thailand (กทท.)** - Owner +- **Project Supervisors (สค©.)** - Consultants +- **Design Consultants (TEAM)** - Designers +- **Construction Supervisors (คคง.)** - Supervision +- **Contractors (ผรม.1-4)** - Construction + +--- + +## 📊 Project Timeline + +### Phase 1: Foundation (Weeks 1-4) + +- Database setup & migrations +- Authentication & RBAC +- **Milestone:** User can login + +### Phase 2: Core Infrastructure (Weeks 5-10) + +- User Management & Master Data +- File Storage & Document Numbering +- Workflow Engine +- **Milestone:** Core services ready + +### Phase 3: Business Modules (Weeks 11-17) + +- Correspondence Management +- RFA Management +- **Milestone:** Core documents manageable + +### Phase 4: Supporting Modules (Weeks 18-21) + +- Drawing Management +- Circulation & Transmittal +- Search & Elasticsearch +- **Milestone:** Document ecosystem complete + +### Phase 5: Services (Week 22) + +- Notifications & Audit Logs +- **Milestone:** MVP ready for UAT + +### Phase 6: Testing & Deployment (Weeks 23-24) + +- User Acceptance Testing (UAT) +- Production deployment +- **Milestone:** Go-Live + +--- + +## 📈 Success Metrics + +### Technical Metrics + +- **Uptime:** > 99.5% +- **API Response Time (P95):** < 500ms +- **Error Rate:** < 1% +- **Database Query Time (P95):** < 100ms + +### Business Metrics + +- **User Adoption:** > 90% of stakeholders using system +- **Document Processing Time:** 50% reduction vs manual +- **Search Success Rate:** > 95% +- **User Satisfaction:** > 4.0/5.0 + +--- + +## 🔐 Security & Compliance + +- **Data Encryption:** At rest & in transit +- **Access Control:** 4-level RBAC +- **Audit Logging:** All user actions logged +- **Backup:** Daily automated backups +- **Disaster Recovery:** RTO 4h, RPO 24h +- **Security Scanning:** Automated vulnerability scans + +--- + +## 📞 Support & Contact + +### Development Support + +- **Repository:** [Internal Git Repository] +- **Issue Tracker:** [Internal Issue Tracker] +- **Documentation:** This repository `/specs` + +### Operations Support + +- **Email:** ops-team@example.com +- **Phone:** [Phone Number] +- **On-Call:** [On-Call Schedule] + +--- + +## 📝 Document Control + +- **Version:** 1.5.0 +- **Status:** Active +- **Last Updated:** 2025-12-01 +- **Next Review:** 2026-01-01 +- **Owner:** System Architect +- **Classification:** Internal Use Only + +--- + +## 🔄 Version History + +| Version | Date | Description | +| ------- | ---------- | ------------------------------------------ | +| 1.5.0 | 2025-12-01 | Complete specification with ADRs and tasks | +| 1.4.5 | 2025-11-30 | Updated architecture documents | +| 1.4.4 | 2025-11-29 | Initial backend/frontend plans | +| 1.0.0 | 2025-11-01 | Initial requirements | + +--- + +**Welcome to LCBP3-DMS Project! 🚀** diff --git a/specs/00-overview/glossary.md b/specs/00-overview/glossary.md index aeafbba..1f5d858 100644 --- a/specs/00-overview/glossary.md +++ b/specs/00-overview/glossary.md @@ -1 +1,496 @@ -# คำศัพท์เทคนิค +# Glossary - คำศัพท์และคำย่อทางเทคนิค + +**Project:** LCBP3-DMS +**Version:** 1.5.0 +**Last Updated:** 2025-12-01 + +--- + +## 📋 General Terms (คำศัพท์ทั่วไป) + +### A + +**ADR (Architecture Decision Record)** +เอกสารบันทึกการตัดสินใจทางสถาปัตยกรรมที่สำคัญ พร้อมบริบท ทางเลือก และเหตุผล + +**API (Application Programming Interface)** +ชุดคำสั่งและโปรโตคอลที่ใช้สำหรับการสื่อสารระหว่างระบบ + +**APM (Application Performance Monitoring)** +การติดตามประสิทธิภาพของแอปพลิเคชัน + +**Async (Asynchronous)** +การทำงานแบบไม่ต้องรอให้งานก่อนหน้าเสร็จก่อน + +**Attachment** +ไฟล์แนบที่อยู่กับเอกสาร เช่น PDF, Word, Drawing files + +**Audit Log** +บันทึกการกระทำของผู้ใช้ในระบบเพื่อการตรวจสอบ + +**Authentication** +การยืนยันตัวตนผู้ใช้ (Login) + +**Authorization** +การกำหนดสิทธิ์การเข้าถึง + +--- + +### B + +**Backend** +ส่วนของระบบที่ทำงานฝั่งเซิร์ฟเวอร์ จัดการข้อมูลและ Business Logic + +**Backup** +การสำรองข้อมูล + +**Blue-Green Deployment** +กลยุทธ์การ Deploy โดยมี 2 สภาพแวดล้อม (Blue และ Green) สลับกันใช้งาน + +**BullMQ** +Message Queue library สำหรับ Node.js ที่ใช้ Redis + +--- + +### C + +**Cache** +ที่เก็บข้อมูลชั่วคราวเพื่อเพิ่มความเร็วในการเข้าถึง + +**CASL (Component Ability Serialization Language)** +Library สำหรับจัดการ Authorization และ Permissions + +**CI/CD (Continuous Integration / Continuous Deployment)** +กระบวนการอัตโนมัติในการ Build, Test และ Deploy code + +**ClamAV** +Antivirus software แบบ Open-source สำหรับสแกนไวรัส + +**Container** +หน่วยของ Software ที่รวม Application และ Dependencies ทั้งหมด + +**CORS (Cross-Origin Resource Sharing)** +กลไกที่อนุญาตให้เว็บคุยข้ามโดเมน + +**CRUD (Create, Read, Update, Delete)** +การดำเนินการพื้นฐานกับข้อมูล + +--- + +### D + +**Database Migration** +การเปลี่ยนแปลง Schema ของฐานข้อมูลอย่างเป็นระบบ + +**DBA (Database Administrator)** +ผู้ดูแลระบบฐานข้อมูล + +**DevOps** +แนวทางที่รวม Development และ Operations เข้าด้วยกัน + +**Discipline** +สาขาวิชาชีพ เช่น GEN (General), STR (Structure), ARC (Architecture) + +**DMS (Document Management System)** +ระบบจัดการเอกสาร + +**Docker** +Platform สำหรับพัฒนาและรัน Application ใน Container + +**DTO (Data Transfer Object)** +Object ที่ใช้สำหรับส่งข้อมูลระหว่าง Layer ต่างๆ + +**DSL (Domain-Specific Language)** +ภาษาที่ออกแบบมาสำหรับโดเมนเฉพาะ + +--- + +### E + +**Elasticsearch** +Search Engine แบบ Distributed สำหรับ Full-text Search + +**Entity** +Object ที่แทนตารางในฐานข้อมูล (TypeORM) + +**ENV (Environment)** +สภาพแวดล้อมการทำงาน เช่น Development, Staging, Production + +**Escalation** +การส่งต่อเรื่องไปยังผู้มีอำนาจสูงขึ้น + +--- + +### F + +**Foreign Key (FK)** +คีย์ที่เชื่อมโยงระหว่างตาราง + +**Frontend** +ส่วนของระบบที่ผู้ใช้โต้ตอบได้ (User Interface) + +--- + +### G + +**Guard** +Middleware ใน NestJS ที่ใช้ตรวจสอบ Authorization + +**GUI (Graphical User Interface)** +ส่วนติดต่อผู้ใช้แบบกราฟิก + +--- + +### H + +**Health Check** +การตรวจสอบสถานะของ Service ว่าทำงานปกติหรือไม่ + +**Hot Reload** +การ Reload code โดยไม่ต้อง Restart server + +--- + +### I + +**Idempotency** +การดำเนินการที่ให้ผลลัพธ์เดียวกันไม่ว่าจะทำกี่ครั้ง + +**Incident** +เหตุการณ์ที่ทำให้ระบบไม่สามารถทำงานได้ตามปกติ + +**Index** +โครงสร้างข้อมูลที่ช่วยเพิ่มความเร็วในการค้นหา (Database) + +**Interceptor** +Middleware ใน NestJS ที่ดัก Request/Response + +--- + +### J + +**JWT (JSON Web Token)** +มาตรฐานสำหรับ Token-based Authentication + +--- + +### K + +**Key-Value Store** +ฐานข้อมูลที่เก็บข้อมูลในรูปแบบ Key และ Value (เช่น Redis) + +--- + +### L + +**LCBP3 (Laem Chabang Port Phase 3)** +โครงการท่าเรือแหลมฉบังระยะที่ 3 + +**Load Balancer** +ตัวกระจายโหลดไปยัง Server หลายตัว + +**Lock** +กลไกป้องกันการเข้าถึงข้อมูลพร้อมกัน + +**Log** +บันทึกเหตุการณ์ที่เกิดขึ้นในระบบ + +--- + +### M + +**MariaDB** +ฐานข้อมูล Relational แบบ Open-source + +**Master Data** +ข้อมูลหลักของระบบ เช่น Organizations, Projects + +**Master-Revision Pattern** +รูปแบบการจัดเก็บข้อมูลที่มี Master record และ Revision records + +**Microservices** +สถาปัตยกรรมที่แบ่งระบบเป็น Service เล็กๆ หลายตัว + +**Migration** +การย้ายหรือเปลี่ยนแปลง Schema ของฐานข้อมูล + +**Modular Monolith** +Monolithic application ที่แบ่งโมดูลชัดเจน + +**MTBF (Mean Time Between Failures)** +เวลาเฉลี่ยระหว่างความล้มเหลว + +**MTTR (Mean Time To Resolution/Repair)** +เวลาเฉลี่ยในการแก้ไขปัญหา + +**MVP (Minimum Viable Product)** +ผลิตภัณฑ์ขั้นต่ำที่ใช้งานได้ + +--- + +### N + +**NestJS** +Framework สำหรับสร้าง Backend Node.js application + +**Next.js** +Framework สำหรับสร้าง React application + +**NGINX** +Web Server และ Reverse Proxy + +--- + +### O + +**ORM (Object-Relational Mapping)** +เทคนิคแปลง Object เป็น Relational Database + +**Optimistic Locking** +กลไกป้องกัน Concurrent update โดยใช้ Version + +--- + +### P + +**Pessimistic Locking** +กลไกป้องกัน Concurrent access โดย Lock ทันที + +**PIR (Post-Incident Review)** +การทบทวนหลังเกิดปัญหา + +**Primary Key (PK)** +คีย์หลักของตาราง + +**Production** +สภาพแวดล้อมที่ผู้ใช้จริงใช้งาน + +--- + +### Q + +**QNAP** +ยี่ห้อ NAS (Network Attached Storage) + +**Queue** +แถวลำดับงานที่รอการประมวลผล + +--- + +### R + +**Race Condition** +สถานการณ์ที่ผลลัพธ์ขึ้นกับลำดับเวลาการทำงาน + +**RBAC (Role-Based Access Control)** +การควบคุมการเข้าถึงตามบทบาท + +**Redis** +In-memory Key-Value store สำหรับ Cache และ Queue + +**Repository Pattern** +รูปแบบการออกแบบสำหรับการเข้าถึงข้อมูล + +**REST (Representational State Transfer)** +สถาปัตยกรรม API ที่ใช้ HTTP + +**Rollback** +การย้อนกลับไปสถานะก่อนหน้า + +**RPO (Recovery Point Objective)** +จุดเวลาที่ยอมรับได้สำหรับการกู้คืนข้อมูล + +**RTO (Recovery Time Objective)** +เวลาที่ยอมรับได้สำหรับการกู้คืนระบบ + +--- + +### S + +**Seed Data** +ข้อมูลเริ่มต้นที่ใส่ในฐานข้อมูล + +**Session** +ช่วงเวลาที่ผู้ใช้ Login อยู่ + +**Soft Delete** +การลบข้อมูลโดยทำ Mark แทนการลบจริง + +**SQL (Structured Query Language)** +ภาษาสำหรับจัดการฐานข้อมูล + +**SSL/TLS (Secure Sockets Layer / Transport Layer Security)** +โปรโตคอลสำหรับการเข้ารหัสข้อมูล + +**Staging** +สภาพแวดล้อมสำหรับทดสอบก่อน Production + +**State Machine** +โมเดลที่มีหลาย State และ Transition + +--- + +### T + +**Temp (Temporary)** +ชั่วคราว + +**Transaction** +ชุดการดำเนินการที่ต้องสำเร็จทั้งหมดหรือไม่ทำเลย + +**Two-Phase Storage** +การจัดเก็บไฟล์แบบ 2 ขั้นตอน (Temp → Permanent) + +**TypeORM** +ORM สำหรับ TypeScript/JavaScript + +**TypeScript** +ภาษาโปรแกรมที่เป็น Superset ของ JavaScript พร้อม Static Typing + +--- + +### U + +**UAT (User Acceptance Testing)** +การทดสอบโดยผู้ใช้จริง + +**UUID (Universally Unique Identifier)** +รหัสไม่ซ้ำกัน 128-bit + +--- + +### V + +**Validation** +การตรวจสอบความถูกต้องของข้อมูล + +**Version Control** +การควบคุมเวอร์ชันของ Code (เช่น Git) + +**Volume** +พื้นที่เก็บข้อมูลถาวรใน Docker + +--- + +### W + +**Webhook** +HTTP Callback ที่เรียกเมื่อเกิด Event + +**Winston** +Logging library สำหรับ Node.js + +**Workflow** +ลำดับขั้นตอนการทำงาน + +--- + +## 🏗️ Project-Specific Terms (คำศัพท์เฉพาะโครงการ) + +### Organizations (องค์กร) + +**กทท. (Port Authority of Thailand)** +การท่าเรือแห่งประเทศไทย - เจ้าของโครงการ + +**สค©. (Supervision Consultant)** +ที่ปรึกษาควบคุมงาน + +**TEAM (Design Consultant)** +ที่ปรึกษาออกแบบ + +**คคง. (Construction Supervision)** +ผู้ควบคุมงานก่อสร้าง + +**ผรม. (Contractor)** +ผู้รับเหมาก่อสร้าง + +--- + +### Document Types + +**Correspondence** +เอกสารโต้ตอบ / หนังสือราชการ + +**RFA (Request for Approval)** +เอกสารขออนุมัติ + +**Contract Drawing** +แบบคู่สัญญา + +**Shop Drawing** +แบบก่อสร้าง / แบบการผลิต + +**Transmittal** +เอกสารนำส่ง + +**Circulation Sheet** +ใบเวียนเอกสารภายใน + +--- + +### Workflow States + +**Draft** +ร่างเอกสาร + +**Pending** +รอดำเนินการ + +**In Review** +อยู่ระหว่างตรวจสอบ + +**Approved** +อนุมัติ + +**Rejected** +ไม่อนุมัติ + +**Closed** +ปิดเรื่อง + +--- + +### Disciplines (สาขาวิชาชีพ) + +**GEN - General** +ทั่วไป + +**STR - Structure** +โครงสร้าง + +**ARC - Architecture** +สถาปัตยกรรม + +**MEP - Mechanical, Electrical & Plumbing** +ระบบเครื่องกล ไฟฟ้า และสุขาภิบาล + +**CIV - Civil** +โยธา + +--- + +## 📚 Acronyms Reference (อ้างอิงตัวย่อ) + +| Acronym | Full Form | Thai | +| ------- | --------------------------------- | ------------------------------- | +| ADR | Architecture Decision Record | บันทึกการตัดสินใจทางสถาปัตยกรรม | +| API | Application Programming Interface | ส่วนต่อประสานโปรแกรม | +| CRUD | Create, Read, Update, Delete | สร้าง อ่าน แก้ไข ลบ | +| DMS | Document Management System | ระบบจัดการเอกสาร | +| DTO | Data Transfer Object | วัตถุถ่ายโอนข้อมูล | +| JWT | JSON Web Token | โทเคนเว็บ JSON | +| LCBP3 | Laem Chabang Port Phase 3 | ท่าเรือแหลมฉบังระยะที่ 3 | +| MVP | Minimum Viable Product | ผลิตภัณฑ์ขั้นต่ำที่ใช้งานได้ | +| ORM | Object-Relational Mapping | การแมปวัตถุกับฐานข้อมูล | +| RBAC | Role-Based Access Control | การควบคุมการเข้าถึงตามบทบาท | +| REST | Representational State Transfer | การถ่ายโอนสถานะแบบนำเสนอ | +| RFA | Request for Approval | เอกสารขออนุมัติ | +| RTO | Recovery Time Objective | เวลาเป้าหมายในการกู้คืน | +| RPO | Recovery Point Objective | จุดเป้าหมายในการกู้คืน | +| UAT | User Acceptance Testing | การทดสอบการยอมรับของผู้ใช้ | + +--- + +**Version:** 1.5.0 +**Last Updated:** 2025-12-01 +**Next Review:** 2026-03-01 diff --git a/specs/00-overview/quick-start.md b/specs/00-overview/quick-start.md new file mode 100644 index 0000000..4bac079 --- /dev/null +++ b/specs/00-overview/quick-start.md @@ -0,0 +1,389 @@ +# Quick Start Guide + +**Project:** LCBP3-DMS +**Version:** 1.5.0 +**Last Updated:** 2025-12-01 + +--- + +## ⚡ 5-Minute Quick Start + +This guide will get you up and running with LCBP3-DMS in 5 minutes. + +--- + +## 👨‍💻 For Developers + +### Prerequisites + +```bash +# Required +- Docker 20.10+ +- Docker Compose 2.0+ +- Git +- Node.js 18+ (for local development) + +# Recommended +- VS Code +- Postman or similar API testing tool +``` + +### Step 1: Clone Repository + +```bash +git clone +cd lcbp3 +``` + +### Step 2: Setup Environment + +```bash +# Backend +cp backend/.env.example backend/.env +# Edit backend/.env and set required values + +# Frontend +cp frontend/.env.example frontend/.env.local +# Edit frontend/.env.local +``` + +### Step 3: Start Services + +```bash +# Start all services with Docker Compose +docker-compose up -d + +# Check status +docker-compose ps +``` + +### Step 4: Initialize Database + +```bash +# Run migrations +docker exec lcbp3-backend npm run migration:run + +# (Optional) Seed sample data +docker exec lcbp3-backend npm run seed +``` + +### Step 5: Access Application + +```bash +# Backend API +http://localhost:3000 + +# Health check +curl http://localhost:3000/health + +# Frontend +http://localhost:3001 + +# API Documentation (Swagger) +http://localhost:3000/api/docs +``` + +### Step 6: Login + +**Default Admin Account:** + +- Username: `admin` +- Password: `Admin@123` (Change immediately!) + +--- + +## 🧪 For QA/Testers + +### Running Tests + +```bash +# Backend unit tests +docker exec lcbp3-backend npm test + +# Backend e2e tests +docker exec lcbp3-backend npm run test:e2e + +# Frontend tests +docker exec lcbp3-frontend npm test +``` + +### Test Data + +```bash +# Reset database to clean state +docker exec lcbp3-backend npm run migration:revert +docker exec lcbp3-backend npm run migration:run + +# Load test data +docker exec lcbp3-backend npm run seed +``` + +--- + +## 🚀 For DevOps + +### Deploy to Staging + +```bash +# Build images +docker-compose build + +# Push to registry +docker-compose push + +# Deploy to staging server +ssh staging-server +cd /app/lcbp3 +git pull +docker-compose pull +docker-compose up -d + +# Run migrations +docker exec lcbp3-backend npm run migration:run +``` + +### Deploy to Production + +```bash +# Backup database first! +./scripts/backup-database.sh + +# Deploy with zero-downtime +./scripts/zero-downtime-deploy.sh + +# Verify deployment +curl -f https://lcbp3-dms.example.com/health +``` + +--- + +## 📊 For Project Managers + +### View Project Status + +**Documentation:** + +- Requirements: [specs/01-requirements](../01-requirements/) +- Architecture: [specs/02-architecture](../02-architecture/) +- Tasks: [specs/06-tasks](../06-tasks/) + +**Metrics:** + +- Check [Monitoring Dashboard](http://localhost:9200) (if setup) +- Review [Task Board](../06-tasks/README.md) + +--- + +## 🔍 Common Tasks + +### Create New Module + +```bash +# Backend +cd backend +nest g module modules/my-module +nest g controller modules/my-module +nest g service modules/my-module + +# Follow backend guidelines +# See: specs/03-implementation/backend-guidelines.md +``` + +### Create New Migration + +```bash +# Generate migration from entity changes +docker exec lcbp3-backend npm run migration:generate -- -n MigrationName + +# Create empty migration +docker exec lcbp3-backend npm run migration:create -- -n MigrationName + +# Run migrations +docker exec lcbp3-backend npm run migration:run + +# Revert last migration +docker exec lcbp3-backend npm run migration:revert +``` + +### View Logs + +```bash +# All services +docker-compose logs -f + +# Specific service +docker logs lcbp3-backend -f --tail=100 + +# Search logs +docker logs lcbp3-backend 2>&1 | grep "ERROR" +``` + +### Database Access + +```bash +# MySQL CLI +docker exec -it lcbp3-mariadb mysql -u root -p + +# Run SQL file +docker exec -i lcbp3-mariadb mysql -u root -p lcbp3_dms < script.sql +``` + +### Redis Access + +```bash +# Redis CLI +docker exec -it lcbp3-redis redis-cli -a + +# Check keys +docker exec lcbp3-redis redis-cli -a KEYS "*" + +# Clear cache +docker exec lcbp3-redis redis-cli -a FLUSHDB +``` + +--- + +## 🐛 Troubleshooting + +### Backend not starting + +```bash +# Check logs +docker logs lcbp3-backend + +# Common issues: +# 1. Database connection - check DB_HOST in .env +# 2. Redis connection - check REDIS_HOST in .env +# 3. Port conflict - check if port 3000 is free +``` + +### Database connection failed + +```bash +# Check if MariaDB is running +docker ps | grep mariadb + +# Test connection +docker exec lcbp3-mariadb mysqladmin ping -h localhost + +# Check credentials +docker exec lcbp3-backend env | grep DB_ +``` + +### Frontend build failed + +```bash +# Clear cache and rebuild +docker exec lcbp3-frontend rm -rf .next node_modules +docker exec lcbp3-frontend npm install +docker exec lcbp3-frontend npm run build +``` + +### Port already in use + +```bash +# Find process using port +lsof -i :3000 + +# Kill process +kill -9 + +# Or change port in docker-compose.yml +``` + +--- + +## 📚 Next Steps + +### Learn More + +1. **Architecture** - [System Architecture](../02-architecture/system-architecture.md) +2. **Development** - [Backend Guidelines](../03-implementation/backend-guidelines.md) +3. **Deployment** - [Deployment Guide](../04-operations/deployment-guide.md) +4. **Decisions** - [ADR Index](../05-decisions/README.md) + +### Join the Team + +1. Read [Contributing Guidelines](../../CONTRIBUTING.md) +2. Pick a task from [Backend Tasks](../06-tasks/README.md) +3. Create a branch: `git checkout -b feature/my-feature` +4. Make changes and write tests +5. Submit Pull Request + +--- + +## 💡 Tips & Best Practices + +### Development + +- ✅ Always write tests for new features +- ✅ Follow coding guidelines +- ✅ Use TypeScript strict mode +- ✅ Add JSDoc for public APIs +- ✅ Keep Pull Requests small + +### Git Workflow + +```bash +# Update main branch +git checkout main +git pull + +# Create feature branch +git checkout -b feature/my-feature + +# Make commits +git add . +git commit -m "feat: add new feature" + +# Push and create PR +git push origin feature/my-feature +``` + +### Code Review + +- Review [Backend Guidelines](../03-implementation/backend-guidelines.md) +- Check test coverage +- Verify documentation updated +- Run linter: `npm run lint` +- Run tests: `npm test` + +--- + +## 🆘 Getting Help + +### Resources + +- **Documentation:** `/specs` directory +- **API Docs:** http://localhost:3000/api/docs +- **Issue Tracker:** [Link to issue tracker] + +### Contact + +- **Tech Lead:** [Email] +- **DevOps:** [Email] +- **Slack:** #lcbp3-dms + +--- + +## ✅ Checklist for First Day + +- [ ] Clone repository +- [ ] Install prerequisites +- [ ] Setup environment variables +- [ ] Start Docker services +- [ ] Run migrations +- [ ] Access backend (http://localhost:3000/health) +- [ ] Access frontend (http://localhost:3001) +- [ ] Login with default credentials +- [ ] Run tests +- [ ] Read [System Architecture](../02-architecture/system-architecture.md) +- [ ] Read [Backend Guidelines](../03-implementation/backend-guidelines.md) +- [ ] Pick first task from [Tasks](../06-tasks/README.md) + +--- + +**Welcome aboard! 🎉** + +**Version:** 1.5.0 +**Last Updated:** 2025-12-01 diff --git a/specs/02-architecture/README.md b/specs/02-architecture/README.md index 9374c98..4bf0980 100644 --- a/specs/02-architecture/README.md +++ b/specs/02-architecture/README.md @@ -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
SSL/TLS Termination] + end + + subgraph "Application Layer" + Frontend[Next.js Frontend
lcbp3.np-dms.work] + Backend[NestJS Backend
backend.np-dms.work] + end + + subgraph "Data Layer" + MariaDB[(MariaDB 10.11
Primary Database)] + Redis[(Redis
Cache + Queue)] + Elastic[Elasticsearch
Search Engine] + Storage[File Storage
/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) + +--- + +
+ +**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) + +
diff --git a/specs/02-architecture/data-model.md b/specs/02-architecture/data-model.md index e69de29..c8e82ea 100644 --- a/specs/02-architecture/data-model.md +++ b/specs/02-architecture/data-model.md @@ -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 { + 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 { + 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 { + 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 | diff --git a/specs/03-implementation/backend-guidelines.md b/specs/03-implementation/backend-guidelines.md index 6090422..f62ef86 100644 --- a/specs/03-implementation/backend-guidelines.md +++ b/specs/03-implementation/backend-guidelines.md @@ -1,8 +1,8 @@ # Backend Development Guidelines **สำหรับ:** NAP-DMS LCBP3 Backend (NestJS + TypeScript) -**เวอร์ชัน:** 1.4.5 -**อัปเดต:** 2025-11-30 +**เวอร์ชัน:** 1.5.0 +**อัปเดต:** 2025-12-01 --- @@ -453,4 +453,4 @@ async approve(@Param('id') id: string, @CurrentUser() user: User) { | Version | Date | Changes | | ------- | ---------- | ---------------------------------- | -| 1.0.0 | 2025-11-30 | Initial backend guidelines created | +| 1.5.0 | 2025-12-01 | Initial backend guidelines created | diff --git a/specs/03-implementation/frontend-guidelines.md b/specs/03-implementation/frontend-guidelines.md index d30a7e7..ea921b3 100644 --- a/specs/03-implementation/frontend-guidelines.md +++ b/specs/03-implementation/frontend-guidelines.md @@ -1,8 +1,8 @@ # Frontend Development Guidelines **สำหรับ:** NAP-DMS LCBP3 Frontend (Next.js + TypeScript) -**เวอร์ชัน:** 1.4.5 -**อัปเดต:** 2025-11-30 +**เวอร์ชัน:** 1.5.0 +**อัปเดต:** 2025-12-01 --- @@ -650,4 +650,4 @@ test.describe('Correspondence Workflow', () => { | Version | Date | Changes | | ------- | ---------- | ----------------------------------- | -| 1.0.0 | 2025-11-30 | Initial frontend guidelines created | +| 1.5.0 | 2025-12-01 | Initial frontend guidelines created | diff --git a/specs/03-implementation/fullftack-js-v1.5.0.md b/specs/03-implementation/fullftack-js-v1.5.0.md index e8c3e39..4d15cd3 100644 --- a/specs/03-implementation/fullftack-js-v1.5.0.md +++ b/specs/03-implementation/fullftack-js-v1.5.0.md @@ -1,8 +1,8 @@ -# 📝 **Documents Management System Version 1.4.5: แนวทางการพัฒนา FullStackJS** +# 📝 **Documents Management System Version 1.5.0: แนวทางการพัฒนา FullStackJS** -**สถานะ:** FINAL GUIDELINE Rev.05 -**วันที่:** 2025-11-29 -**อ้างอิง:** Requirements Specification v1.4.4 +**สถานะ:** first-draft +**วันที่:** 2025-12-01 +**อ้างอิง:** Requirements Specification v1.5.0 **Classification:** Internal Technical Documentation ## 🧠 **1. ปรัชญาทั่วไป (General Philosophy)** @@ -1082,14 +1082,14 @@ Views เหล่านี้ทำหน้าที่เป็นแหล ## **Document Control:** -- **Document:** FullStackJS v1.4.5 -- **Version:** 1.4 -- **Date:** 2025-11-29 +- **Document:** FullStackJS v1.5.0 +- **Version:** 1.5 +- **Date:** 2025-12-01 - **Author:** NAP LCBP3-DMS & Gemini -- **Status:** FINAL-Rev.05 +- **Status:** first-draft - **Classification:** Internal Technical Documentation - **Approved By:** Nattanin --- -`End of FullStackJS Guidelines v1.4.5` +`End of FullStackJS Guidelines v1.5.0` diff --git a/specs/03-implementation/testing-strategy.md b/specs/03-implementation/testing-strategy.md index e69de29..72a07c7 100644 --- a/specs/03-implementation/testing-strategy.md +++ b/specs/03-implementation/testing-strategy.md @@ -0,0 +1,1253 @@ +# Testing Strategy + +--- + +title: 'Testing Strategy' +version: 1.5.0 +status: first-draft +owner: Nattanin Peancharoen +last_updated: 2025-11-30 +related: + +- specs/03-implementation/backend-guidelines.md +- specs/03-implementation/frontend-guidelines.md +- specs/02-architecture/system-architecture.md + +--- + +## 📋 Overview + +เอกสารนี้กำหนดกลยุทธ์การทดสอบสำหรับโปรเจกต์ LCBP3-DMS เพื่อให้มั่นใจในคุณภาพ ความถูกต้อง และความปลอดภัยของระบบ + +### Testing Philosophy + +> **"Quality First, Test Everything That Matters"** + +เราเน้นการทดสอบที่มีความหมาย ไม่ใช่แค่เพิ่มตัวเลข Coverage แต่เป็นการทดสอบที่ช่วยป้องกันบั๊กจริง และให้ความมั่นใจว่าระบบทำงานถูกต้อง + +### Key Principles + +1. **Test Early, Test Often** - เขียน Test ควบคู่กับ Code +2. **Critical Path First** - ทดสอบ Business Logic สำคัญก่อน +3. **Automated Testing** - Automate ทุกอย่างที่ทำซ้ำได้ +4. **Fast Feedback** - Unit Tests ต้องรวดเร็ว (< 5 วินาที) +5. **Real-World Scenarios** - E2E Tests ต้องใกล้เคียงกับการใช้งานจริง + +--- + +## 🎯 Testing Pyramid + +``` + /\ + / \ + / E2E \ ~10% + /--------\ + / \ + / Integration \ ~30% + /--------------\ + / \ + / Unit Tests \ ~60% + /--------------------\ +``` + +### Test Distribution + +| Level | Coverage | Speed | Purpose | +| ----------- | -------- | ---------- | ------------------------------- | +| Unit | 60% | Fast (ms) | ทดสอบตรรกะแต่ละ Function | +| Integration | 30% | Medium (s) | ทดสอบการทำงานร่วมกันของ Modules | +| E2E | 10% | Slow (m) | ทดสอบ User Journey ทั้งหมด | + +--- + +## 🧪 Backend Testing (NestJS) + +### 1. Unit Testing + +**Tools:** Jest, @nestjs/testing + +**Target Coverage:** 80% สำหรับ Services, Utilities, Guards + +#### 1.1 Service Unit Tests + +```typescript +// File: src/modules/correspondence/services/correspondence.service.spec.ts +import { Test, TestingModule } from '@nestjs/testing'; +import { getRepositoryToken } from '@nestjs/typeorm'; +import { CorrespondenceService } from './correspondence.service'; +import { Correspondence } from '../entities/correspondence.entity'; +import { Repository } from 'typeorm'; + +describe('CorrespondenceService', () => { + let service: CorrespondenceService; + let repository: Repository; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ + CorrespondenceService, + { + provide: getRepositoryToken(Correspondence), + useClass: Repository, + }, + ], + }).compile(); + + service = module.get(CorrespondenceService); + repository = module.get>( + getRepositoryToken(Correspondence) + ); + }); + + describe('findAll', () => { + it('should return an array of correspondences', async () => { + const mockCorrespondences = [ + { id: '1', title: 'Test 1' }, + { id: '2', title: 'Test 2' }, + ]; + + jest + .spyOn(repository, 'find') + .mockResolvedValue(mockCorrespondences as any); + + const result = await service.findAll(); + expect(result).toEqual(mockCorrespondences); + expect(repository.find).toHaveBeenCalled(); + }); + + it('should throw error when repository fails', async () => { + jest.spyOn(repository, 'find').mockRejectedValue(new Error('DB Error')); + + await expect(service.findAll()).rejects.toThrow('DB Error'); + }); + }); +}); +``` + +#### 1.2 Guard/Interceptor Unit Tests + +```typescript +// File: src/common/guards/rbac.guard.spec.ts +describe('RBACGuard', () => { + let guard: RBACGuard; + let abilityFactory: AbilityFactory; + + beforeEach(() => { + abilityFactory = new AbilityFactory(); + guard = new RBACGuard(abilityFactory); + }); + + it('should allow access when user has permission', () => { + const context = createMockExecutionContext({ + user: { role: 'admin', permissions: ['correspondence.create'] }, + handler: createMockHandler({ permission: 'correspondence.create' }), + }); + + expect(guard.canActivate(context)).toBe(true); + }); + + it('should deny access when user lacks permission', () => { + const context = createMockExecutionContext({ + user: { role: 'viewer', permissions: ['correspondence.view'] }, + handler: createMockHandler({ permission: 'correspondence.create' }), + }); + + expect(guard.canActivate(context)).toBe(false); + }); +}); +``` + +#### 1.3 Critical Business Logic Tests + +**Document Numbering Concurrency Test:** + +```typescript +// File: src/modules/document-numbering/services/numbering.service.spec.ts +describe('DocumentNumberingService - Concurrency', () => { + it('should generate unique numbers for concurrent requests', async () => { + const context = { + projectId: '1', + organizationId: '1', + typeId: '1', + year: 2025, + }; + + // จำลอง 100 requests พร้อมกัน + const promises = Array(100) + .fill(null) + .map(() => service.generateNextNumber(context)); + + const results = await Promise.all(promises); + + // ตรวจสอบว่าไม่มีเลขซ้ำ + const uniqueNumbers = new Set(results); + expect(uniqueNumbers.size).toBe(100); + + // ตรวจสอบว่าเรียงลำดับถูกต้อง + const sorted = [...results].sort(); + expect(results).toEqual(sorted); + }); +}); +``` + +**Idempotency Test:** + +```typescript +describe('IdempotencyInterceptor', () => { + it('should return cached result for duplicate request', async () => { + const idempotencyKey = 'test-key-123'; + const mockResponse = { id: '1', title: 'Test' }; + + // Request 1 + const result1 = await invokeInterceptor(idempotencyKey, mockResponse); + expect(result1).toEqual(mockResponse); + + // Request 2 (same key) + const result2 = await invokeInterceptor(idempotencyKey, mockResponse); + expect(result2).toEqual(mockResponse); + + // Verify business logic only executed once + expect(mockBusinessLogic).toHaveBeenCalledTimes(1); + }); +}); +``` + +--- + +### 2. Integration Testing + +**Tools:** Jest, Supertest, In-Memory Database + +**Target:** ทดสอบ API Endpoints พร้อม Database interactions + +#### 2.1 API Integration Test + +```typescript +// File: test/correspondence.e2e-spec.ts +import { Test, TestingModule } from '@nestjs/testing'; +import { INestApplication } from '@nestjs/common'; +import * as request from 'supertest'; +import { AppModule } from './../src/app.module'; +import { v4 as uuidv4 } from 'uuid'; + +describe('Correspondence API (e2e)', () => { + let app: INestApplication; + let authToken: string; + + beforeAll(async () => { + const moduleFixture: TestingModule = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + + // Login to get token + const loginResponse = await request(app.getHttpServer()) + .post('/auth/login') + .send({ username: 'testuser', password: 'password123' }); + + authToken = loginResponse.body.access_token; + }); + + afterAll(async () => { + await app.close(); + }); + + describe('POST /correspondences', () => { + it('should create correspondence with valid data', async () => { + const createDto = { + title: 'E2E Test Correspondence', + project_id: '1', + correspondence_type_id: '1', + }; + + const response = await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${authToken}`) + .send(createDto) + .expect(201); + + expect(response.body).toMatchObject({ + id: expect.any(String), + title: createDto.title, + correspondence_number: expect.stringMatching(/^TEAM-RFA-\d{4}-\d{4}$/), + }); + }); + + it('should enforce idempotency', async () => { + const idempotencyKey = uuidv4(); + const createDto = { + title: 'Idempotency Test', + project_id: '1', + correspondence_type_id: '1', + }; + + // Request 1 + const response1 = await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${authToken}`) + .set('Idempotency-Key', idempotencyKey) + .send(createDto) + .expect(201); + + // Request 2 (same key) + const response2 = await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${authToken}`) + .set('Idempotency-Key', idempotencyKey) + .send(createDto) + .expect(201); + + // Should return same entity + expect(response1.body.id).toBe(response2.body.id); + }); + + it('should validate input data', async () => { + const invalidDto = { + title: '', // Empty title + }; + + await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${authToken}`) + .send(invalidDto) + .expect(400); + }); + + it('should enforce RBAC permissions', async () => { + // Login as viewer (no create permission) + const viewerResponse = await request(app.getHttpServer()) + .post('/auth/login') + .send({ username: 'viewer', password: 'password123' }); + + const createDto = { + title: 'Test', + project_id: '1', + correspondence_type_id: '1', + }; + + await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${viewerResponse.body.access_token}`) + .send(createDto) + .expect(403); + }); + }); + + describe('File Upload Flow', () => { + it('should complete two-phase file upload', async () => { + // Phase 1: Upload to temp + const uploadResponse = await request(app.getHttpServer()) + .post('/attachments/upload') + .set('Authorization', `Bearer ${authToken}`) + .attach('file', Buffer.from('test file content'), 'test.pdf') + .expect(201); + + const tempId = uploadResponse.body.temp_id; + expect(tempId).toBeDefined(); + + // Phase 2: Commit with correspondence + const createResponse = await request(app.getHttpServer()) + .post('/correspondences') + .set('Authorization', `Bearer ${authToken}`) + .send({ + title: 'Test with Attachment', + project_id: '1', + correspondence_type_id: '1', + temp_file_ids: [tempId], + }) + .expect(201); + + // Verify attachment is committed + const attachments = await request(app.getHttpServer()) + .get(`/correspondences/${createResponse.body.id}/attachments`) + .set('Authorization', `Bearer ${authToken}`) + .expect(200); + + expect(attachments.body).toHaveLength(1); + expect(attachments.body[0].is_temporary).toBe(false); + }); + }); +}); +``` + +--- + +### 3. Database Testing + +#### 3.1 Migration Tests + +```typescript +// File: test/migrations/migration.spec.ts +describe('Database Migrations', () => { + it('should run all migrations without error', async () => { + const dataSource = await createTestDataSource(); + await expect(dataSource.runMigrations()).resolves.not.toThrow(); + await dataSource.destroy(); + }); + + it('should rollback migrations successfully', async () => { + const dataSource = await createTestDataSource(); + await dataSource.runMigrations(); + await expect(dataSource.undoLastMigration()).resolves.not.toThrow(); + await dataSource.destroy(); + }); +}); +``` + +#### 3.2 Transaction Tests + +```typescript +describe('Transaction Handling', () => { + it('should rollback on error', async () => { + const initialCount = await correspondenceRepo.count(); + + await expect( + service.createWithError({ + /* invalid data */ + }) + ).rejects.toThrow(); + + const finalCount = await correspondenceRepo.count(); + expect(finalCount).toBe(initialCount); // No change + }); +}); +``` + +--- + +### 4. Performance Testing + +**Tools:** Artillery, k6, Jest with timing + +#### 4.1 Load Testing Configuration + +```yaml +# File: test/load/correspondence-load.yml +config: + target: 'http://localhost:3000' + phases: + - duration: 60 + arrivalRate: 10 # 10 requests/second + - duration: 120 + arrivalRate: 50 # Ramp up to 50 requests/second + processor: './load-test-processor.js' + +scenarios: + - name: 'Create Correspondence' + weight: 40 + flow: + - post: + url: '/correspondences' + headers: + Authorization: 'Bearer {{ authToken }}' + Idempotency-Key: '{{ $uuid }}' + json: + title: 'Load Test {{ $randomString() }}' + project_id: '{{ projectId }}' + correspondence_type_id: '{{ typeId }}' + + - name: 'Search Correspondences' + weight: 60 + flow: + - get: + url: '/correspondences?project_id={{ projectId }}' + headers: + Authorization: 'Bearer {{ authToken }}' +``` + +#### 4.2 Query Performance Tests + +```typescript +describe('Performance - Database Queries', () => { + it('should fetch 1000 correspondences in < 100ms', async () => { + const startTime = Date.now(); + await service.findAll({ limit: 1000 }); + const duration = Date.now() - startTime; + + expect(duration).toBeLessThan(100); + }); + + it('should use proper indexes for search', async () => { + const queryPlan = await repository.query( + `EXPLAIN SELECT * FROM correspondences + WHERE project_id = ? AND deleted_at IS NULL`, + ['1'] + ); + + expect(queryPlan[0].key).toBe('idx_project_deleted'); + }); +}); +``` + +--- + +## 🎨 Frontend Testing (Next.js) + +### 1. Component Testing + +**Tools:** Vitest, React Testing Library + +**Target Coverage:** 70% สำหรับ Shared Components + +#### 1.1 UI Component Tests + +```tsx +// File: components/forms/correspondence-form.spec.tsx +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { describe, it, expect, vi } from 'vitest'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { CorrespondenceForm } from './correspondence-form'; + +describe('CorrespondenceForm', () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + + const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} + ); + + it('should render all required fields', () => { + render(, { wrapper }); + + expect(screen.getByLabelText('หัวเรื่อง')).toBeInTheDocument(); + expect(screen.getByLabelText('โปรเจกต์')).toBeInTheDocument(); + expect(screen.getByLabelText('ประเภทเอกสาร')).toBeInTheDocument(); + }); + + it('should show validation errors on submit without data', async () => { + const onSubmit = vi.fn(); + render(, { wrapper }); + + const submitButton = screen.getByRole('button', { name: /บันทึก/i }); + fireEvent.click(submitButton); + + expect(await screen.findByText('กรุณาระบุหัวเรื่อง')).toBeInTheDocument(); + expect(onSubmit).not.toHaveBeenCalled(); + }); + + it('should submit form with valid data', async () => { + const onSubmit = vi.fn(); + render(, { wrapper }); + + // Fill form + const titleInput = screen.getByLabelText('หัวเรื่อง'); + fireEvent.change(titleInput, { target: { value: 'Test Title' } }); + + const projectSelect = screen.getByLabelText('โปรเจกต์'); + fireEvent.change(projectSelect, { target: { value: 'project-1' } }); + + const typeSelect = screen.getByLabelText('ประเภทเอกสาร'); + fireEvent.change(typeSelect, { target: { value: 'type-1' } }); + + // Submit + const submitButton = screen.getByRole('button', { name: /บันทึก/i }); + fireEvent.click(submitButton); + + await waitFor(() => { + expect(onSubmit).toHaveBeenCalledWith( + expect.objectContaining({ + title: 'Test Title', + project_id: 'project-1', + correspondence_type_id: 'type-1', + }) + ); + }); + }); + + it('should auto-save draft every 30 seconds', async () => { + vi.useFakeTimers(); + const saveDraft = vi.fn(); + + render(, { wrapper }); + + const titleInput = screen.getByLabelText('หัวเรื่อง'); + fireEvent.change(titleInput, { target: { value: 'Draft Test' } }); + + // Fast-forward 30 seconds + vi.advanceTimersByTime(30000); + + await waitFor(() => { + expect(saveDraft).toHaveBeenCalledWith( + expect.objectContaining({ title: 'Draft Test' }) + ); + }); + + vi.useRealTimers(); + }); +}); +``` + +#### 1.2 Custom Hook Tests + +```tsx +// File: lib/hooks/use-correspondence.spec.ts +import { renderHook, waitFor } from '@testing-library/react'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { useCorrespondences } from './use-correspondence'; +import { correspondenceService } from '@/lib/services/correspondence.service'; + +vi.mock('@/lib/services/correspondence.service'); + +describe('useCorrespondences', () => { + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + + const wrapper = ({ children }: { children: React.ReactNode }) => ( + {children} + ); + + it('should fetch correspondences successfully', async () => { + const mockData = [ + { id: '1', title: 'Test 1' }, + { id: '2', title: 'Test 2' }, + ]; + + vi.mocked(correspondenceService.getAll).mockResolvedValue(mockData); + + const { result } = renderHook(() => useCorrespondences('project-1'), { + wrapper, + }); + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true); + }); + + expect(result.current.data).toEqual(mockData); + }); + + it('should handle error state', async () => { + vi.mocked(correspondenceService.getAll).mockRejectedValue( + new Error('API Error') + ); + + const { result } = renderHook(() => useCorrespondences('project-1'), { + wrapper, + }); + + await waitFor(() => { + expect(result.current.isError).toBe(true); + }); + + expect(result.current.error).toBeDefined(); + }); +}); +``` + +--- + +### 2. E2E Testing + +**Tools:** Playwright + +**Target:** ทดสอบ Critical User Journeys + +#### 2.1 E2E Test Configuration + +```typescript +// File: frontend/playwright.config.ts +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './e2e', + fullyParallel: true, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 2 : 0, + workers: process.env.CI ? 1 : undefined, + reporter: 'html', + use: { + baseURL: 'http://localhost:3000', + trace: 'on-first-retry', + screenshot: 'only-on-failure', + }, + projects: [ + { + name: 'chromium', + use: { ...devices['Desktop Chrome'] }, + }, + { + name: 'Mobile Chrome', + use: { ...devices['Pixel 5'] }, + }, + ], + webServer: { + command: 'npm run dev', + url: 'http://localhost:3000', + reuseExistingServer: !process.env.CI, + }, +}); +``` + +#### 2.2 Critical User Journey Tests + +```typescript +// File: e2e/correspondence-workflow.spec.ts +import { test, expect } from '@playwright/test'; + +test.describe('Correspondence Complete Workflow', () => { + test.beforeEach(async ({ page }) => { + // Login + await page.goto('/login'); + await page.fill('input[name="username"]', 'testuser'); + await page.fill('input[name="password"]', 'password123'); + await page.click('button[type="submit"]'); + await page.waitForURL('/dashboard'); + }); + + test('should create, edit, and submit correspondence', async ({ page }) => { + // 1. Navigate to create page + await page.click('text=สร้างเอกสาร'); + await page.waitForURL('/correspondences/new'); + + // 2. Fill form + await page.fill('input[name="title"]', 'E2E Test Correspondence'); + await page.selectOption('select[name="project_id"]', { index: 1 }); + await page.selectOption('select[name="type_id"]', { index: 1 }); + await page.fill('textarea[name="description"]', 'E2E Test Description'); + + // 3. Upload attachment + const fileInput = page.locator('input[type="file"]'); + await fileInput.setInputFiles('test-fixtures/sample.pdf'); + await expect(page.locator('text=sample.pdf')).toBeVisible(); + + // 4. Save as draft + await page.click('button:has-text("บันทึกแบบร่าง")'); + await expect(page.locator('text=บันทึกแบบร่างสำเร็จ')).toBeVisible(); + + // 5. Edit draft + const docId = page.url().match(/correspondences\/([^/]+)/)?.[1]; + await page.goto(`/correspondences/${docId}/edit`); + await page.fill('input[name="title"]', 'E2E Test Correspondence (Edited)'); + + // 6. Submit for approval + await page.click('button:has-text("ส่งอนุมัติ")'); + await page.waitForSelector('text=ยืนยันการส่งเอกสาร'); + await page.click('button:has-text("ยืนยัน")'); + + // 7. Verify status changed + await expect(page.locator('text=รอการอนุมัติ')).toBeVisible(); + }); + + test('should support offline draft save', async ({ page, context }) => { + await page.goto('/correspondences/new'); + + // Fill form + await page.fill('input[name="title"]', 'Offline Test'); + + // Go offline + await context.setOffline(true); + + // Trigger auto-save + await page.waitForTimeout(31000); // Wait for auto-save (30s) + + // Verify draft saved to localStorage + const localStorage = await page.evaluate(() => window.localStorage); + expect(localStorage).toHaveProperty('correspondence-drafts'); + + // Go back online + await context.setOffline(false); + + // Reload page + await page.reload(); + + // Verify draft restored + const titleValue = await page.inputValue('input[name="title"]'); + expect(titleValue).toBe('Offline Test'); + }); + + test('should handle responsive design', async ({ page }) => { + await page.goto('/correspondences'); + + // Desktop view - should show table + await page.setViewportSize({ width: 1280, height: 720 }); + await expect(page.locator('table')).toBeVisible(); + + // Mobile view - should show card layout + await page.setViewportSize({ width: 375, height: 667 }); + await expect(page.locator('table')).not.toBeVisible(); + await expect(page.locator('[data-testid="card-view"]')).toBeVisible(); + }); +}); +``` + +--- + +## 🔒 Security Testing + +### 1. OWASP Top 10 Testing + +#### 1.1 SQL Injection Protection + +```typescript +describe('Security - SQL Injection', () => { + it('should prevent SQL injection in search', async () => { + const maliciousInput = "'; DROP TABLE correspondences; --"; + + const response = await request(app.getHttpServer()) + .get(`/correspondences/search?title=${maliciousInput}`) + .set('Authorization', `Bearer ${authToken}`) + .expect(200); + + // Should not execute malicious SQL + const tableExists = await repository.query( + `SHOW TABLES LIKE 'correspondences'` + ); + expect(tableExists).toHaveLength(1); + }); +}); +``` + +#### 1.2 XSS Protection + +```typescript +test('should sanitize user input to prevent XSS', async ({ page }) => { + await page.goto('/correspondences/new'); + + const xssPayload = ''; + await page.fill('input[name="title"]', xssPayload); + await page.click('button[type="submit"]'); + + // Verify script not executed + const alerts = []; + page.on('dialog', (dialog) => { + alerts.push(dialog.message()); + dialog.dismiss(); + }); + + await page.waitForTimeout(1000); + expect(alerts).toHaveLength(0); + + // Verify content escaped + const displayedTitle = await page.textContent('h1'); + expect(displayedTitle).not.toContain('