690417:1538 Refactor Work flow ADR-021

This commit is contained in:
2026-04-17 15:38:20 +07:00
parent 6d45bdaeb5
commit 3a5fc8d4af
23 changed files with 892 additions and 135 deletions
+20 -20
View File
@@ -1,6 +1,6 @@
# Tasks: Transmittals + Circulation Complete Integration (v1.8.7 Post-ADR-021)
**Branch**: `001-transmittals-circulation` | **Total Tasks**: 18 | **Phase**: Implementation
**Branch**: `001-transmittals-circulation` | **Total Tasks**: 18 | **Phase**: ✅ Complete (v1.8.7)
---
@@ -10,49 +10,49 @@
- **File**: `backend/src/modules/workflow-engine/workflow-engine.service.ts`
- **Action**: Add method that queries `WorkflowInstance` by `entityType + entityId`; returns `{ id, currentState, availableActions? } | null`
- **Dependencies**: none
- **Status**: [ ]
- **Status**: [x]
### B2 — TransmittalService: Expose `workflowInstanceId` in `findOneByUuid()`
- **File**: `backend/src/modules/transmittal/transmittal.service.ts`
- **Action**: Call `workflowEngine.getInstanceByEntity('transmittal', correspondenceId.toString())` and merge `workflowInstanceId`, `workflowState` into response
- **Dependencies**: B1
- **Status**: [ ]
- **Status**: [x]
### B3 — TransmittalService: Add `purpose` filter to `findAll()`
- **File**: `backend/src/modules/transmittal/transmittal.service.ts`
- **Action**: Add `purpose?: string` to `SearchTransmittalDto` and apply `andWhere` in `findAll()`
- **Dependencies**: none (parallel with B1)
- **Status**: [ ]
- **Status**: [x]
### B4 — TransmittalService: Add `submit()` with EC-RFA-004 validation
- **File**: `backend/src/modules/transmittal/transmittal.service.ts`
- **Action**: New `submit(uuid, user)` method; fetches all `transmittal_items`, checks each item's correspondence current revision status — throws `422 ValidationException` if any is `DRAFT`; then calls `workflowEngine.createInstance('TRANSMITTAL_FLOW_V1', 'transmittal', ...)` and transitions with `SUBMIT`
- **Dependencies**: B1
- **Status**: [ ]
- **Status**: [x]
### B5 — TransmittalController: Add `POST /:uuid/submit` endpoint
- **File**: `backend/src/modules/transmittal/transmittal.controller.ts`
- **Action**: Add endpoint with `@RequirePermission('document.manage')`, `@Audit('transmittal.submit', 'transmittal')`
- **Dependencies**: B4
- **Status**: [ ]
- **Status**: [x]
### B6 — CirculationService: Expose `workflowInstanceId` in `findOneByUuid()`
- **File**: `backend/src/modules/circulation/circulation.service.ts`
- **Action**: Call `workflowEngine.getInstanceByEntity('circulation', circulation.id.toString())`, merge into response; also compute `isOverdue` per routing based on `deadline_date`
- **Dependencies**: B1
- **Status**: [ ]
- **Status**: [x]
### B7 — CirculationService: Add `reassignRouting()` (EC-CIRC-001)
- **File**: `backend/src/modules/circulation/circulation.service.ts`
- **Action**: Fetch routing, verify user has Document Control permission, resolve `newAssigneeUuid` → INT via `uuidResolver.resolveUserId()`, update `routing.assignedTo`, write audit log
- **Dependencies**: none
- **Status**: [ ]
- **Status**: [x]
### B8 — CirculationService: Add `forceClose()` (EC-CIRC-002)
- **File**: `backend/src/modules/circulation/circulation.service.ts`
- **Action**: Require `reason` (non-empty), update all PENDING routings to `CANCELLED`, set `circulation.statusCode = 'CANCELLED'`, write audit log entry; use `queryRunner` for atomicity
- **Dependencies**: none
- **Status**: [ ]
- **Status**: [x]
### B9 — CirculationController: Add reassign + force-close endpoints
- **File**: `backend/src/modules/circulation/circulation.controller.ts`
@@ -60,7 +60,7 @@
- `PATCH /:uuid/routing/:routingId/reassign``@RequirePermission('circulation.manage')`
- `POST /:uuid/force-close``@RequirePermission('circulation.manage')`
- **Dependencies**: B7, B8
- **Status**: [ ]
- **Status**: [x]
---
@@ -70,25 +70,25 @@
- **File**: `frontend/types/transmittal.ts`
- **Action**: Add `workflowInstanceId?: string`, `workflowState?: string`, `availableActions?: string[]` to `Transmittal` interface; add `purpose?: string` to `SearchTransmittalDto`; no `any` types (ADR-019)
- **Dependencies**: none (parallel with Phase 1)
- **Status**: [ ]
- **Status**: [x]
### F2 — Update `types/circulation.ts`
- **File**: `frontend/types/circulation.ts`
- **Action**: Add `workflowInstanceId?: string`, `workflowState?: string`, `availableActions?: string[]` to `Circulation`; add `deadline?: string`, `assigneeType?: 'MAIN' | 'ACTION' | 'INFORMATION'` to `CirculationRouting`
- **Dependencies**: none
- **Status**: [ ]
- **Status**: [x]
### F3 — Create `hooks/use-transmittal.ts`
- **File**: `frontend/hooks/use-transmittal.ts`
- **Action**: Create `useTransmittal(uuid: string | undefined)` with `queryKey: ['transmittal', uuid]`, `staleTime: 60_000`; export `transmittalKeys` query key factory
- **Dependencies**: F1
- **Status**: [ ]
- **Status**: [x]
### F4 — Update `hooks/use-circulation.ts`
- **File**: `frontend/hooks/use-circulation.ts`
- **Action**: Add `useCirculation(uuid: string | undefined)` hook with `queryKey: ['circulation', uuid]`, `staleTime: 60_000`
- **Dependencies**: F2
- **Status**: [ ]
- **Status**: [x]
---
@@ -103,7 +103,7 @@
- Pass `instanceId`, `workflowState`, `availableActions`, `pendingAttachmentIds` to `IntegratedBanner`
- Pass `history`, `currentState`, `isLoading`, `error`, `onAttachmentsChange` to `WorkflowLifecycle` in Workflow tab
- **Dependencies**: F3, F1
- **Status**: [ ]
- **Status**: [x]
### F6 — Wire Circulation detail page
- **File**: `frontend/app/(dashboard)/circulation/[uuid]/page.tsx`
@@ -116,7 +116,7 @@
- Add Overdue badge to routing rows where `isOverdue(routing.deadline)` is true
- Replace hardcoded "Complete" button with proper workflow action
- **Dependencies**: F4, F2
- **Status**: [ ]
- **Status**: [x]
---
@@ -126,13 +126,13 @@
- **File**: `frontend/app/(dashboard)/transmittals/page.tsx`
- **Action**: Add `purpose` select filter (FOR_APPROVAL / FOR_INFORMATION / FOR_REVIEW / OTHER) passing to `transmittalService.getAll()`. Read current page to assess if pagination works.
- **Dependencies**: F1
- **Status**: [ ]
- **Status**: [x]
### I1 — i18n keys for Transmittal/Circulation workflow
- **Files**: `public/locales/th/*.json`, `public/locales/en/*.json`
- **Action**: Check `use-translations.ts` for key lookup pattern; add missing keys: `transmittal.purpose.*`, `circulation.status.*`, `circulation.overdue`, `circulation.forceClose.*`, `circulation.reassign.*`
- **Dependencies**: F5, F6
- **Status**: [ ]
- **Status**: [ ] *(low priority — pending)*
---
@@ -142,13 +142,13 @@
- **File**: `backend/src/modules/transmittal/transmittal.service.spec.ts` (create if needed)
- **Action**: Test `submit()` throws `ValidationException` when item correspondence is DRAFT; test passes when all items are SUBMITTED
- **Dependencies**: B4
- **Status**: [ ]
- **Status**: [x]
### T2 — Circulation service edge-case unit tests
- **File**: `backend/src/modules/circulation/circulation.service.spec.ts` (create if needed)
- **Action**: Test `reassignRouting()` — permission check, assignment update; test `forceClose()` — all pending routings cancelled, reason logged; test `isOverdue` helper (EC-CIRC-003)
- **Dependencies**: B7, B8
- **Status**: [ ]
- **Status**: [x]
---
@@ -1,9 +1,9 @@
---
title: 'Data & Storage: Data Dictionary and Data Model Architecture'
version: 1.8.0
version: 1.8.7
status: released
owner: Nattanin Peancharoen
last_updated: 2026-02-28
last_updated: 2026-04-14
related:
- specs/01-requirements/02-architecture.md
- specs/01-requirements/03-functional-requirements.md
@@ -1714,24 +1714,33 @@ erDiagram
**Purpose**: เก็บสถานะของ Workflow ที่กำลังรันอยู่จริง (Runtime)
| Column Name | Data Type | Constraints | Description |
| :------------ | :---------- | :--------------- | :--------------------------------------------- |
| id | CHAR(36) | PK, UUID | Unique Instance ID |
| definition_id | CHAR(36) | FK, NOT NULL | อ้างอิง Definition ที่ใช้ |
| entity_type | VARCHAR(50) | NOT NULL | ประเภทเอกสาร (rfa_revision, correspondence...) |
| entity_id | VARCHAR(50) | NOT NULL | ID ของเอกสาร |
| current_state | VARCHAR(50) | NOT NULL | สถานะปัจจุบัน |
| status | ENUM | DEFAULT 'ACTIVE' | ACTIVE, COMPLETED, CANCELLED, TERMINATED |
| context | JSON | NULL | ตัวแปร Context สำหรับตัดสินใจ |
| created_at | TIMESTAMP | DEFAULT NOW | เวลาที่สร้าง |
| updated_at | TIMESTAMP | ON UPDATE | เวลาที่อัปเดตล่าสุด |
| Column Name | Data Type | Constraints | Description |
| :------------ | :---------- | :------------------------- | :---------------------------------------------------------------------------------------------- |
| id | CHAR(36) | PK, UUID | Unique Instance ID |
| definition_id | CHAR(36) | FK, NOT NULL | อ้างอิง Definition ที่ใช้ |
| **contract_id** | **INT** | **NULL, FK** | **[delta-07 / ADR-021 C3]** Contract ที่ Workflow นี้สังกัด (NULL = org-scoped เช่น Circulation) |
| entity_type | VARCHAR(50) | NOT NULL | ประเภทเอกสาร (rfa, correspondence, transmittal, circulation) |
| entity_id | VARCHAR(50) | NOT NULL | ID ของเอกสาร |
| current_state | VARCHAR(50) | NOT NULL | สถานะปัจจุบัน |
| status | ENUM | DEFAULT 'ACTIVE' | ACTIVE, COMPLETED, CANCELLED, TERMINATED |
| context | JSON | NULL | ตัวแปร Context สำหรับตัดสินใจ (รวม contractId, projectId, initiatorId เป็นต้น) |
| created_at | TIMESTAMP | DEFAULT NOW | เวลาที่สร้าง |
| updated_at | TIMESTAMP | ON UPDATE | เวลาที่อัปเดตล่าสุด |
**Business Rules**:
- `contract_id` = NOT NULL → contract-scoped workflow (RFA, Correspondence, Transmittal) — Guard Level 2.5 ตรวจ membership
- `contract_id` = NULL → org-scoped workflow (Circulation) — Guard Level 2 (org match only)
- `context.contractId` mirrors `contract_id` column — redundant by design (ฟิลเตอร์ได้ทั้งสองทาง)
**Indexes**:
- PRIMARY KEY (id)
- FOREIGN KEY (definition_id) REFERENCES workflow_definitions(id) ON DELETE CASCADE
- **FOREIGN KEY (contract_id) REFERENCES contracts(id) ON DELETE SET NULL** [delta-07]
- INDEX (entity_type, entity_id)
- INDEX (current_state)
- **INDEX (contract_id, entity_type, status)** — `idx_wf_inst_contract` [delta-07]
---
@@ -1978,8 +1987,9 @@ PARTITION BY RANGE (YEAR(created_at)) (
| audit_logs | (module, action) | Action type analysis |
| notifications | (user_id, is_read) | Unread notifications query |
| document_number_counters | (project_id, correspondence_type_id, reset_scope) | Running number generation |
| workflow_instances | (entity_type, entity_id) | Workflow lookup by document ID |
| workflow_instances | (current_state) | Monitor active workflows |
| workflow_instances | (entity_type, entity_id) | Workflow lookup by document ID |
| workflow_instances | (current_state) | Monitor active workflows |
| workflow_instances | (contract_id, entity_type, status) | **[delta-07]** Guard contract-membership + dashboard filter |
### 13.2 Unique Constraints
@@ -0,0 +1,87 @@
-- ==========================================================
-- Delta 06: Add CIRCULATION_FLOW_V1 Workflow Definition
-- ==========================================================
-- Purpose : สร้าง Workflow Definition สำหรับใบเวียนภายใน (Circulation)
-- Required : ก่อน delta นี้ ตาราง workflow_definitions ต้องมีอยู่แล้ว (ADR-001)
-- Renamed : CIRCULATION_INTERNAL_V1 → CIRCULATION_FLOW_V1 (ตาม naming convention)
-- States :
-- DRAFT (initial) → START → ROUTING
-- ROUTING → COMPLETE → COMPLETED (terminal)
-- ROUTING → FORCE_CLOSE → CANCELLED (terminal)
-- ==========================================================
INSERT INTO `workflow_definitions` (
`id`,
`workflow_code`,
`version`,
`description`,
`dsl`,
`compiled`,
`is_active`,
`created_at`,
`updated_at`
)
VALUES (
UUID(),
'CIRCULATION_FLOW_V1',
1,
'Circulation Workflow — DRAFT → ROUTING → COMPLETED | CANCELLED',
JSON_OBJECT(
'workflow', 'CIRCULATION_FLOW_V1',
'version', 1,
'states', JSON_ARRAY(
JSON_OBJECT(
'name', 'DRAFT',
'initial', TRUE,
'on', JSON_OBJECT(
'START', JSON_OBJECT('to', 'ROUTING')
)
),
JSON_OBJECT(
'name', 'ROUTING',
'on', JSON_OBJECT(
'COMPLETE', JSON_OBJECT('to', 'COMPLETED'),
'FORCE_CLOSE', JSON_OBJECT('to', 'CANCELLED')
)
),
JSON_OBJECT('name', 'COMPLETED', 'terminal', TRUE),
JSON_OBJECT('name', 'CANCELLED', 'terminal', TRUE)
)
),
JSON_OBJECT(
'initialState', 'DRAFT',
'states', JSON_OBJECT(
'DRAFT', JSON_OBJECT(
'initial', TRUE,
'terminal', FALSE,
'transitions', JSON_OBJECT(
'START', JSON_OBJECT('to', 'ROUTING', 'events', JSON_ARRAY())
)
),
'ROUTING', JSON_OBJECT(
'initial', FALSE,
'terminal', FALSE,
'transitions', JSON_OBJECT(
'COMPLETE', JSON_OBJECT('to', 'COMPLETED', 'events', JSON_ARRAY()),
'FORCE_CLOSE', JSON_OBJECT('to', 'CANCELLED', 'events', JSON_ARRAY())
)
),
'COMPLETED', JSON_OBJECT(
'initial', FALSE,
'terminal', TRUE,
'transitions', JSON_OBJECT()
),
'CANCELLED', JSON_OBJECT(
'initial', FALSE,
'terminal', TRUE,
'transitions', JSON_OBJECT()
)
)
),
TRUE,
NOW(),
NOW()
);
-- Verify
-- SELECT workflow_code, version, is_active FROM workflow_definitions WHERE workflow_code = 'CIRCULATION_FLOW_V1';
@@ -0,0 +1,22 @@
-- ==========================================================
-- Delta 07: Add contract_id to workflow_instances (C3 Contract Scoping)
-- ==========================================================
-- Purpose : เพิ่ม contract_id FK ใน workflow_instances เพื่อให้ Workflow Engine
-- แยก scope ตาม Contract ได้ (C3 ตาม analysis ADR-021)
-- Why : RFA / Correspondence / Transmittal → contract-scoped (contractId ถูกตั้ง)
-- Circulation → organization-scoped (contractId = NULL, ใช้ Level 2 org check)
-- Guard Level 2.5 ตรวจ contract_organizations membership เฉพาะ contractId ≠ NULL
-- ADR : ADR-009 (no migrations — direct SQL only)
-- ==========================================================
ALTER TABLE workflow_instances
ADD COLUMN contract_id INT NULL COMMENT 'Contract ที่ Workflow นี้เป็นส่วนหนึ่ง (NULL = global/legacy)'
AFTER definition_id,
ADD CONSTRAINT fk_wf_inst_contract FOREIGN KEY (contract_id) REFERENCES contracts (id) ON DELETE
SET NULL;
-- Index สำหรับ Guard lookup: "Instances ทั้งหมดในสัญญา X"
CREATE INDEX idx_wf_inst_contract ON workflow_instances (contract_id, entity_type, STATUS);
-- Verify
-- DESCRIBE workflow_instances;
-- SHOW INDEX FROM workflow_instances WHERE Key_name = 'idx_wf_inst_contract';
@@ -1369,6 +1369,8 @@ CREATE INDEX idx_workflow_active ON workflow_definitions (workflow_code, is_acti
CREATE TABLE workflow_instances (
id CHAR(36) NOT NULL PRIMARY KEY COMMENT 'UUID ของ Instance',
definition_id CHAR(36) NOT NULL COMMENT 'อ้างอิง Definition ที่ใช้',
contract_id INT NULL COMMENT 'Contract ที่ Workflow นี้เป็นส่วนหนึ่ง (NULL = org-scoped หรือ legacy)',
-- [delta-07]
entity_type VARCHAR(50) NOT NULL COMMENT 'ประเภทเอกสาร (rfa_revision, correspondence_revision, circulation)',
entity_id VARCHAR(50) NOT NULL COMMENT 'ID ของเอกสาร (String/Int)',
current_state VARCHAR(50) NOT NULL COMMENT 'สถานะปัจจุบัน',
@@ -1381,11 +1383,15 @@ CREATE TABLE workflow_instances (
context JSON NULL COMMENT 'ตัวแปร Context สำหรับตัดสินใจ',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
CONSTRAINT fk_wf_inst_def FOREIGN KEY (definition_id) REFERENCES workflow_definitions (id) ON DELETE CASCADE
CONSTRAINT fk_wf_inst_def FOREIGN KEY (definition_id) REFERENCES workflow_definitions (id) ON DELETE CASCADE,
CONSTRAINT fk_wf_inst_contract FOREIGN KEY (contract_id) REFERENCES contracts (id) ON DELETE
SET NULL -- [delta-07]
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = 'ตารางเก็บสถานะการเดินเรื่องของเอกสาร';
CREATE INDEX idx_wf_inst_entity ON workflow_instances (entity_type, entity_id);
CREATE INDEX idx_wf_inst_contract ON workflow_instances (contract_id, entity_type, STATUS);
CREATE INDEX idx_wf_inst_state ON workflow_instances (current_state);
-- 3. ตารางเก็บประวัติ (Audit Log / History)
@@ -221,7 +221,7 @@ export interface WorkflowTransitionWithAttachmentsDto {
Body: { action, comment, attachmentPublicIds: [uuid1, uuid2] }
[WorkflowTransitionGuard] — RBAC check (4-Level)
[WorkflowTransitionGuard] — RBAC check (4.5-Level: Superadmin / Org Admin / Level 2.5 Contract Membership / Assigned Handler)
│ pass
[WorkflowEngineService.processTransition()]
@@ -253,15 +253,21 @@ export interface WorkflowTransitionWithAttachmentsDto {
## 7. Entity Relationship Diagram
```
contracts
│ 1
│ (FK, nullable) [delta-07]
▼ N
workflow_definitions
│ 1
│ has many
▼ N
workflow_instances ──────────────── documents (RFA/Corr/etc)
│ 1 (entityType + entityId)
workflow_instances ────────────────── documents (RFA/Corr/Transmittal/Circulation)
contract_id: INT NULL [delta-07] (entityType + entityId)
(NULL = org-scoped e.g. Circulation)
│ 1
│ has many
▼ N
workflow_histories ◄─────────────────────────────┐
workflow_histories ◄─────────────────────────
│ id: CHAR(36) UUID │
│ │
│ ◄── attachments.workflow_history_id (FK, nullable)
@@ -281,5 +287,4 @@ attachments
| `attachments` | `idx_att_wfhist_created` (NEW) | `(workflow_history_id, created_at)` | Fetch step attachments sorted by date |
| `workflow_histories` | `idx_wf_hist_instance` (existing) | `(instance_id)` | Fetch all steps for a workflow instance |
| `workflow_histories` | `idx_wf_hist_user` (existing) | `(action_by_user_id)` | Audit queries per user |
**No additional indexes required** — the composite `(workflow_history_id, created_at)` covers the primary access pattern.
| `workflow_instances` | `idx_wf_inst_contract` (NEW — delta-07) | `(contract_id, entity_type, status)` | Guard contract-membership lookup + dashboard queries per contract |
@@ -111,8 +111,8 @@ frontend/hooks/
# 🟡 Frontend — Page Refactors (use new components)
frontend/app/(dashboard)/rfas/[uuid]/page.tsx [MODIFY — integrate IntegratedBanner + WorkflowLifecycle]
frontend/app/(dashboard)/correspondences/[uuid]/page.tsx [MODIFY — same]
frontend/app/(dashboard)/transmittals/[uuid]/page.tsx [MODIFY — same, if detail page exists]
frontend/app/(dashboard)/circulation/[uuid]/page.tsx [MODIFY — same, if detail page exists]
frontend/app/(dashboard)/transmittals/[uuid]/page.tsx [MODIFY — same as RFA/Correspondence]
frontend/app/(dashboard)/circulation/[uuid]/page.tsx [MODIFY — same as RFA/Correspondence]
```
---
@@ -135,6 +135,8 @@ _No constitution violations. Architecture is additive (Nullable FK, extended DTO
| Existing visualizer reuse | `components/custom/workflow-visualizer.tsx` is **horizontal** — new `workflow-lifecycle.tsx` is **vertical** | Different layout semantics; keep both |
| Idempotency storage | Redis key: `idempotency:transition:{idempotencyKey}:{userId}` → serialized response (TTL: 24h) | Per .windsurfrules Security Rule #1 + ADR-021 §5.1 |
| Cache invalidation | On `processTransition()` success → invalidate Redis key `wf:history:{instanceId}` | ADR-021 §9 — override TTL on state change |
| Drawing workflow type (DDW/SDW/ADW) | Drawing types are **RFA subtypes** — all use single `RFA_APPROVAL` workflow code | Removing per-type codes (`RFA_DDW` etc.) eliminates dead workflow definitions; drawing metadata lives on the document, not the workflow |
| Workflow scope per document type | RFA / Correspondence / Transmittal → **contract-scoped** (`contract_id` on `workflow_instances`); Circulation → **org-scoped** (`contract_id = NULL`) | Workflow Guard Level 2.5 blocks cross-contract access; Circulation is internal org document |
---
@@ -221,6 +223,8 @@ Response: WorkflowHistoryItem[] with nested attachments[] per step
| F6 | Create `FilePreviewModal` component | `components/common/file-preview-modal.tsx` | F1 |
| F7 | Refactor RFA detail page — integrate new components | `rfas/[uuid]/page.tsx` | F3F6 |
| F8 | Refactor Correspondence detail page — integrate new components | `correspondences/[uuid]/page.tsx` | F3F6 |
| F9 | Refactor Transmittal detail page — integrate new components | `transmittals/[uuid]/page.tsx` | F3F6 |
| F10 | Refactor Circulation detail page — integrate new components | `circulation/[uuid]/page.tsx` | F3F6 |
### 🟢 GUIDELINES (after F7/F8)
@@ -45,12 +45,12 @@
**⚠️ CRITICAL**: T004 must complete before T005T009. T005T007 must complete before Phase 5 (US3).
- [ ] T004 Apply SQL delta — create `specs/03-Data-and-Storage/deltas/04-add-workflow-history-id-to-attachments.sql` and run against dev DB per quickstart.md Step 1
- [ ] T005 [P] Update `backend/src/common/file-storage/entities/attachment.entity.ts` — add `workflowHistoryId?: string` column + lazy `@ManyToOne(() => WorkflowHistory)` relation (data-model.md §2.1)
- [ ] T006 [P] Update `backend/src/modules/workflow-engine/entities/workflow-history.entity.ts` — add lazy `@OneToMany(() => Attachment)` relation + required imports (data-model.md §2.2)
- [ ] T007 Update `backend/src/modules/workflow-engine/dto/workflow-transition.dto.ts` — add `attachmentPublicIds?: string[]` with `@IsArray()`, `@IsUUID('all', { each: true })`, `@ArrayMaxSize(20)`, `@IsOptional()` (data-model.md §3.1)
- [ ] T008 Create `backend/src/modules/workflow-engine/guards/workflow-transition.guard.ts` — implement 4-Level RBAC: Superadmin (`system.manage_all`) → Org Admin → Assigned Handler → Forbidden (quickstart.md Step 4; contracts/workflow-transition.yaml §403)
- [ ] T009 Register `WorkflowTransitionGuard` as provider in `backend/src/modules/workflow-engine/workflow-engine.module.ts`
- [x] T004 Apply SQL delta — create `specs/03-Data-and-Storage/deltas/04-add-workflow-history-id-to-attachments.sql` and run against dev DB per quickstart.md Step 1
- [x] T005 [P] Update `backend/src/common/file-storage/entities/attachment.entity.ts` — add `workflowHistoryId?: string` column + lazy `@ManyToOne(() => WorkflowHistory)` relation (data-model.md §2.1)
- [x] T006 [P] Update `backend/src/modules/workflow-engine/entities/workflow-history.entity.ts` — add lazy `@OneToMany(() => Attachment)` relation + required imports (data-model.md §2.2)
- [x] T007 Update `backend/src/modules/workflow-engine/dto/workflow-transition.dto.ts` — add `attachmentPublicIds?: string[]` with `@IsArray()`, `@IsUUID('all', { each: true })`, `@ArrayMaxSize(20)`, `@IsOptional()` (data-model.md §3.1)
- [x] T008 Create `backend/src/modules/workflow-engine/guards/workflow-transition.guard.ts` — implement 4-Level RBAC: Superadmin (`system.manage_all`) → Org Admin → Assigned Handler → Forbidden (quickstart.md Step 4; contracts/workflow-transition.yaml §403)
- [x] T009 Register `WorkflowTransitionGuard` as provider in `backend/src/modules/workflow-engine/workflow-engine.module.ts`
**Checkpoint**: Foundation complete — `pnpm tsc --noEmit` in backend must pass before proceeding to Phase 5.
@@ -71,13 +71,13 @@ cd frontend && pnpm test --run --reporter=verbose components/workflow/integrated
### Implementation for User Story 1
- [ ] T010 [P] [US1] Add `WorkflowPriority` enum and `WorkflowHistoryItem` interface to `frontend/types/workflow.ts` (data-model.md §5.1)
- [ ] T011 [P] [US1] Add `WorkflowTransitionWithAttachmentsDto` interface to `frontend/types/dto/workflow-engine/workflow-engine.dto.ts` (data-model.md §5.2)
- [ ] T012 [US1] Create `frontend/components/workflow/integrated-banner.tsx` — props: `{ documentNo, subject, status, priority?, currentState, availableActions, onAction, isLoading? }`, render Priority badge with Tailwind color map from research.md §8 (URGENT=red, HIGH=orange, MEDIUM=yellow, LOW=green), render `WorkflowActionButtons` per `availableActions` array
- [ ] T013 [US1] Update `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` — replace existing header section with `<IntegratedBanner>` using RFA data fields (quickstart.md Step 10)
- [ ] T014 [US1] Update `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same integration as T013 using Correspondence data fields
- [ ] T015 [US1] Update `frontend/app/(dashboard)/transmittals/[uuid]/page.tsx` — same integration as T013 using Transmittal data fields (if detail page has a header section)
- [ ] T016 [US1] Update `frontend/app/(dashboard)/circulation/[uuid]/page.tsx` — same integration as T013 using Circulation data fields (if detail page has a header section)
- [x] T010 [P] [US1] Add `WorkflowPriority` enum and `WorkflowHistoryItem` interface to `frontend/types/workflow.ts` (data-model.md §5.1)
- [x] T011 [P] [US1] Add `WorkflowTransitionWithAttachmentsDto` interface to `frontend/types/dto/workflow-engine/workflow-engine.dto.ts` (data-model.md §5.2)
- [x] T012 [US1] Create `frontend/components/workflow/integrated-banner.tsx` — props: `{ documentNo, subject, status, priority?, currentState, availableActions, onAction, isLoading? }`, render Priority badge with Tailwind color map from research.md §8 (URGENT=red, HIGH=orange, MEDIUM=yellow, LOW=green), render `WorkflowActionButtons` per `availableActions` array
- [x] T013 [US1] Update `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` — replace existing header section with `<IntegratedBanner>` using RFA data fields (quickstart.md Step 10)
- [x] T014 [US1] Update `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same integration as T013 using Correspondence data fields
- [x] T015 [US1] Update `frontend/app/(dashboard)/transmittals/[uuid]/page.tsx` — same integration as T013 using Transmittal data fields
- [x] T016 [US1] Update `frontend/app/(dashboard)/circulation/[uuid]/page.tsx` — same integration as T013 using Circulation data fields
**Checkpoint**: `IntegratedBanner` renders correctly on RFA and Correspondence detail pages. Priority badge and action buttons visible. `pnpm tsc --noEmit` passes.
@@ -98,12 +98,12 @@ cd frontend && pnpm test --run components/workflow/workflow-lifecycle
### Implementation for User Story 2
- [ ] T017 [P] [US2] Create `frontend/components/workflow/workflow-lifecycle.tsx` — props: `{ history: WorkflowHistoryItem[], currentState: string, onFileClick: (a: WorkflowAttachmentSummary) => void }`, vertical timeline layout, Indigo (#6366f1 = `text-indigo-500`) + `animate-pulse` on `isCurrent` step, completed steps show `actorName`, `createdAt`, `comment`, attachment count badge (data-model.md §5.1)
- [ ] T018 [P] [US2] Add `workflowHistory` query to relevant hooks — update `frontend/hooks/use-rfa.ts` (or equivalent) to fetch `GET /workflow-engine/instances/:id/history` using TanStack Query key `['workflow-history', instanceId]`; add same to `frontend/hooks/use-correspondence.ts`
- [ ] T019 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` inside existing `<Tabs>` (or add Tabs if missing) — pass `rfa.workflowHistory` and `currentState` props
- [ ] T020 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same as T019
- [ ] T021 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/transmittals/[uuid]/page.tsx` — same as T019 (if applicable)
- [ ] T022 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/circulation/[uuid]/page.tsx` — same as T019 (if applicable)
- [x] T017 [P] [US2] Create `frontend/components/workflow/workflow-lifecycle.tsx` — props: `{ history: WorkflowHistoryItem[], currentState: string, onFileClick: (a: WorkflowAttachmentSummary) => void }`, vertical timeline layout, Indigo (#6366f1 = `text-indigo-500`) + `animate-pulse` on `isCurrent` step, completed steps show `actorName`, `createdAt`, `comment`, attachment count badge (data-model.md §5.1)
- [x] T018 [P] [US2] Add `workflowHistory` query to relevant hooks — update `frontend/hooks/use-rfa.ts`, `frontend/hooks/use-correspondence.ts`, `frontend/hooks/use-transmittal.ts`, and `frontend/hooks/use-circulation.ts` to fetch `GET /workflow-engine/instances/:id/history` using TanStack Query key `['workflow-history', instanceId]`
- [x] T019 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` inside existing `<Tabs>` (or add Tabs if missing) — pass `rfa.workflowHistory` and `currentState` props
- [x] T020 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same as T019
- [x] T021 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/transmittals/[uuid]/page.tsx` — same as T019
- [x] T022 [US2] Add `WorkflowLifecycle` tab to `frontend/app/(dashboard)/circulation/[uuid]/page.tsx` — same as T019
**Checkpoint**: Workflow tab visible on RFA/Correspondence pages. Current step Indigo+pulse. Completed steps show actor/date. No TypeScript errors. `pnpm lint` passes.
@@ -129,15 +129,15 @@ cd frontend && pnpm test --run hooks/use-workflow-action
### Implementation for User Story 3
- [ ] T023 [US3] Extend `backend/src/modules/workflow-engine/workflow-engine.service.ts` — add `attachmentPublicIds: string[] = []` parameter to `processTransition()`, after `queryRunner.commitTransaction()` run bulk UPDATE to set `workflow_history_id = history.id` WHERE `uuid IN (:publicIds) AND is_temporary = false` (quickstart.md Step 5; data-model.md §6)
- [ ] T024 [US3] Add `getHistoryWithAttachments(instanceId: string)` method to `backend/src/modules/workflow-engine/workflow-engine.service.ts` — query `workflow_histories` WHERE `instance_id = :id` ORDER BY `created_at ASC`, eager-load attachments via LEFT JOIN, apply Redis cache key `wf:history:{instanceId}` TTL 3600s, invalidate on `processTransition()` success (research.md §6; contracts/workflow-transition.yaml)
- [ ] T025 [US3] Update `backend/src/modules/workflow-engine/workflow-engine.controller.ts` — add `@Headers('Idempotency-Key')` validation to `processTransition()` endpoint (throw `BadRequestException` if missing), add Redis idempotency check/store with key `idempotency:transition:{key}:{userId}` TTL 86400, swap `RbacGuard` for `WorkflowTransitionGuard` on transition endpoint (quickstart.md Step 6)
- [ ] T026 [US3] Add `GET /instances/:id/history` endpoint to `backend/src/modules/workflow-engine/workflow-engine.controller.ts` — decorated with `@RequirePermission('document.view')`, calls `workflowService.getHistoryWithAttachments(instanceId)` (contracts/workflow-transition.yaml §/instances/{instanceId}/history)
- [ ] T027 [P] [US3] Create `frontend/hooks/use-workflow-action.ts` — generates UUIDv7 idempotency key once per action intent (via `useState`), calls `workflowEngineService.transition()` with `Idempotency-Key` header, on success invalidates TanStack Query keys `['workflow-history', instanceId]` + parent document queries (quickstart.md Step 8)
- [ ] T028 [P] [US3] Add drag-and-drop file upload zone to `frontend/components/workflow/workflow-lifecycle.tsx` — renders only on `isCurrent` step, uses `<input type="file" multiple accept=".pdf,.docx,.xlsx,.dwg,.zip">` + drag events, calls existing Two-Phase upload service on drop, accumulates `publicId`s in local state, passes to `useWorkflowAction` on submit
- [ ] T029 [US3] Wire `useWorkflowAction` into `IntegratedBanner` action buttons in `frontend/components/workflow/integrated-banner.tsx``onAction` callback receives `(action, comment, attachmentPublicIds[])` and delegates to hook's `execute()` method; show loading spinner during `isPending`
- [ ] T030 [US3] Add `WorkflowTransitionGuard` unit tests in `backend/src/modules/workflow-engine/guards/workflow-transition.guard.spec.ts` — test all 4 RBAC levels: Superadmin pass, Org Admin same-org pass, Assigned Handler pass, unauthorized user → ForbiddenException
- [ ] T031 [US3] Add extended `processTransition()` unit tests in `backend/src/modules/workflow-engine/workflow-engine.service.spec.ts` — test: attachments linked to correct historyId, non-committed attachment rejected, idempotent replay returns cached result, Redlock contention throws 409
- [x] T023 [US3] Extend `backend/src/modules/workflow-engine/workflow-engine.service.ts` — add `attachmentPublicIds: string[] = []` parameter to `processTransition()`, after `queryRunner.commitTransaction()` run bulk UPDATE to set `workflow_history_id = history.id` WHERE `uuid IN (:publicIds) AND is_temporary = false` (quickstart.md Step 5; data-model.md §6)
- [x] T024 [US3] Add `getHistoryWithAttachments(instanceId: string)` method to `backend/src/modules/workflow-engine/workflow-engine.service.ts` — query `workflow_histories` WHERE `instance_id = :id` ORDER BY `created_at ASC`, eager-load attachments via LEFT JOIN, apply Redis cache key `wf:history:{instanceId}` TTL 3600s, invalidate on `processTransition()` success (research.md §6; contracts/workflow-transition.yaml)
- [x] T025 [US3] Update `backend/src/modules/workflow-engine/workflow-engine.controller.ts` — add `@Headers('Idempotency-Key')` validation to `processTransition()` endpoint (throw `BadRequestException` if missing), add Redis idempotency check/store with key `idempotency:transition:{key}:{userId}` TTL 86400, swap `RbacGuard` for `WorkflowTransitionGuard` on transition endpoint (quickstart.md Step 6)
- [x] T026 [US3] Add `GET /instances/:id/history` endpoint to `backend/src/modules/workflow-engine/workflow-engine.controller.ts` — decorated with `@RequirePermission('document.view')`, calls `workflowService.getHistoryWithAttachments(instanceId)` (contracts/workflow-transition.yaml §/instances/{instanceId}/history)
- [x] T027 [P] [US3] Create `frontend/hooks/use-workflow-action.ts` — generates UUIDv7 idempotency key once per action intent (via `useState`), calls `workflowEngineService.transition()` with `Idempotency-Key` header, on success invalidates TanStack Query keys `['workflow-history', instanceId]` + parent document queries (quickstart.md Step 8)
- [x] T028 [P] [US3] Add drag-and-drop file upload zone to `frontend/components/workflow/workflow-lifecycle.tsx` — renders only on `isCurrent` step, uses `<input type="file" multiple accept=".pdf,.docx,.xlsx,.dwg,.zip">` + drag events, calls existing Two-Phase upload service on drop, accumulates `publicId`s in local state, passes to `useWorkflowAction` on submit
- [x] T029 [US3] Wire `useWorkflowAction` into `IntegratedBanner` action buttons in `frontend/components/workflow/integrated-banner.tsx``onAction` callback receives `(action, comment, attachmentPublicIds[])` and delegates to hook's `execute()` method; show loading spinner during `isPending`
- [x] T030 [US3] Add `WorkflowTransitionGuard` unit tests in `backend/src/modules/workflow-engine/guards/workflow-transition.guard.spec.ts` — test all RBAC levels: (1) Superadmin pass, (2) Org Admin same-org pass, (3) Level 2.5 contract membership — user org in same contract pass / cross-contract org → ForbiddenException, (4) Assigned Handler pass, (5) unauthorized user → ForbiddenException
- [x] T031 [US3] Add extended `processTransition()` unit tests in `backend/src/modules/workflow-engine/workflow-engine.service.spec.ts` — test: attachments linked to correct historyId, non-committed attachment rejected, idempotent replay returns cached result, Redlock contention throws 409
**Checkpoint**: POST transition with `attachmentPublicIds` succeeds. `attachment.workflow_history_id` set in DB. Duplicate `Idempotency-Key` returns cached response. Unauthorized user gets 403. Backend unit tests pass ≥80% coverage on new logic.
@@ -161,10 +161,10 @@ cd frontend && pnpm test --run components/common/file-preview-modal
### Implementation for User Story 4
- [ ] T032 [P] [US4] Verify `backend/src/common/file-storage/file-storage.controller.ts` has a preview endpoint (`GET /files/preview/:publicId`) that streams file with `Content-Disposition: inline` and validates `document.view` permission — if missing, add it to `file-storage.controller.ts` and `file-storage.service.ts`
- [ ] T033 [US4] Create `frontend/components/common/file-preview-modal.tsx` — props: `{ attachment: WorkflowAttachmentSummary | null, onClose: () => void }`, detect `mimeType` to render `<iframe>` (PDF) or `<img>` (images), trap Escape key for close, accessible `<dialog>` or shadcn `<Dialog>` wrapper, show filename + fileSize in header (quickstart.md Step 9 `FilePreviewModal Props`)
- [ ] T034 [US4] Wire `FilePreviewModal` into `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` — add `useState<WorkflowAttachmentSummary | null>(null)` state, pass `setPreviewFile` as `onFileClick` to `WorkflowLifecycle`, render `<FilePreviewModal>` at page root (quickstart.md Step 10)
- [ ] T035 [US4] Wire `FilePreviewModal` into `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same pattern as T034
- [x] T032 [P] [US4] Verify `backend/src/common/file-storage/file-storage.controller.ts` has a preview endpoint (`GET /files/preview/:publicId`) that streams file with `Content-Disposition: inline` and validates `document.view` permission — if missing, add it to `file-storage.controller.ts` and `file-storage.service.ts`
- [x] T033 [P] [US4] Create `frontend/components/common/file-preview-modal.tsx` — props: `{ attachment: WorkflowAttachmentSummary | null, onClose: () => void }`, detect `mimeType` to render `<iframe>` (PDF) or `<img>` (images), trap Escape key for close, accessible `<dialog>` or shadcn `<Dialog>` wrapper, show filename + fileSize in header (quickstart.md Step 9 `FilePreviewModal Props`)
- [x] T034 [US4] Wire `FilePreviewModal` into `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` — add `useState<WorkflowAttachmentSummary | null>(null)` state, pass `setPreviewFile` as `onFileClick` to `WorkflowLifecycle`, render `<FilePreviewModal>` at page root (quickstart.md Step 10)
- [x] T035 [US4] Wire `FilePreviewModal` into `frontend/app/(dashboard)/correspondences/[uuid]/page.tsx` — same pattern as T034
**Checkpoint**: Clicking attachment chip in WorkflowLifecycle opens `FilePreviewModal`. PDF renders inline. Image renders inline. Modal closes on X or Escape. No TypeScript errors.
@@ -185,10 +185,10 @@ grep -rn "[ก-๙]" frontend/components/workflow/ frontend/components/common/fi
### Implementation for User Story 5
- [ ] T036 [P] [US5] Add i18n keys for `IntegratedBanner` strings to `frontend/public/locales/th/common.json` and `frontend/public/locales/en/common.json` — keys: `workflow.priority.*`, `workflow.action.*`, `workflow.status.*` (05-08-i18n-guidelines.md)
- [ ] T037 [P] [US5] Add i18n keys for `WorkflowLifecycle` strings — keys: `workflow.timeline.step.*`, `workflow.timeline.noHistory`, `workflow.timeline.uploadHint`
- [ ] T038 [P] [US5] Add i18n keys for `FilePreviewModal` strings — keys: `filePreview.title`, `filePreview.unavailable`, `filePreview.close`
- [ ] T039 [US5] Replace all hardcoded strings in `frontend/components/workflow/integrated-banner.tsx`, `frontend/components/workflow/workflow-lifecycle.tsx`, and `frontend/components/common/file-preview-modal.tsx` with `t('key')` calls using the project's i18n hook
- [x] T036 [P] [US5] Add i18n keys for `IntegratedBanner` strings to `frontend/public/locales/th/common.json` and `frontend/public/locales/en/common.json` — keys: `workflow.priority.*`, `workflow.action.*`, `workflow.status.*` (05-08-i18n-guidelines.md)
- [x] T037 [P] [US5] Add i18n keys for `WorkflowLifecycle` strings — keys: `workflow.timeline.step.*`, `workflow.timeline.noHistory`, `workflow.timeline.uploadHint`
- [x] T038 [P] [US5] Add i18n keys for `FilePreviewModal` strings — keys: `filePreview.title`, `filePreview.unavailable`, `filePreview.close`
- [x] T039 [US5] Replace all hardcoded strings in `frontend/components/workflow/integrated-banner.tsx`, `frontend/components/workflow/workflow-lifecycle.tsx`, and `frontend/components/common/file-preview-modal.tsx` with `t('key')` calls using the project's i18n hook
**Checkpoint**: No hardcoded Thai text in new component JSX. Switching locale changes all new UI strings. `pnpm lint` and `pnpm tsc --noEmit` pass.
@@ -198,14 +198,14 @@ grep -rn "[ก-๙]" frontend/components/workflow/ frontend/components/common/fi
**Purpose**: Documentation, edge case hardening, full regression verification.
- [ ] T040 [P] Update `specs/03-Data-and-Storage/03-01-data-dictionary.md` — add entry for `attachments.workflow_history_id` field with business rule: "NULL = Main Document attachment; NOT NULL = Step-evidence attachment (ADR-021)"
- [ ] T041 [P] Add edge case handling in `frontend/components/workflow/workflow-lifecycle.tsx` — render "File unavailable" chip (not broken link) when attachment `publicId` resolves to 404 (ADR-021 §5.2 — "ไฟล์ถูกลบจาก Storage หลัง Attach")
- [ ] T042 [P] Add error boundary for `WorkflowLifecycle` and `FilePreviewModal` in their parent pages — catches unexpected failures without crashing the full detail page
- [ ] T043 Verify Redis cache invalidation works end-to-end: after `processTransition()`, query `wf:history:{instanceId}` in Redis — must be empty; subsequent GET history refetches from DB
- [ ] T044 Run full backend test suite and confirm coverage ≥70% overall, ≥80% for `workflow-engine.service.ts` new code paths: `cd backend && pnpm test --coverage`
- [ ] T045 Run full frontend type check and lint: `cd frontend && pnpm tsc --noEmit && pnpm lint` — zero errors
- [ ] T046 Run E2E smoke test per quickstart.md verification section — submit RFA approval with 1 attachment, verify DB state
- [ ] T047 Update `CHANGELOG.md` — add entry for v1.8.6: "feat(workflow): ADR-021 Integrated Workflow Context & Step-specific Attachments"
- [x] T040 [P] Update `specs/03-Data-and-Storage/03-01-data-dictionary.md` — add entry for `attachments.workflow_history_id` field with business rule: "NULL = Main Document attachment; NOT NULL = Step-evidence attachment (ADR-021)"
- [x] T041 [P] Add edge case handling in `frontend/components/workflow/workflow-lifecycle.tsx` — render "File unavailable" chip (not broken link) when attachment `publicId` resolves to 404 (ADR-021 §5.2 — "ไฟล์ถูกลบจาก Storage หลัง Attach")
- [x] T042 [P] Add `WorkflowErrorBoundary` wrapper around `WorkflowLifecycle` and `FilePreviewModal` in detail pages to prevent whole-page crashes on unexpected errors
- [x] T043 [P] Verify Redis cache invalidation works: after `processTransition()`, call `GET /instances/:id/history` twice — first call should be cached, second should return fresh data after cache invalidation
- [x] T044 Run full backend test suite and confirm coverage ≥70% overall, ≥80% for `workflow-engine.service.ts` new code paths: `cd backend && pnpm test --coverage`
- [x] T045 Run full frontend type check and lint: `cd frontend && pnpm tsc --noEmit && pnpm lint` — zero errors
- [x] T046 Run E2E smoke test per quickstart.md verification section — submit RFA approval with 1 attachment, verify DB state
- [x] T047 Update `CHANGELOG.md` — add entry for v1.8.8: "feat(workflow): ADR-021 Integrated Workflow Context & Step-specific Attachments"
---