690414:1113 Update README.md /.agents/skills, /.windsurf/workflows

This commit is contained in:
2026-04-14 11:13:42 +07:00
parent 02400fd88c
commit 6d45bdaeb5
194 changed files with 12708 additions and 8762 deletions
@@ -0,0 +1,355 @@
openapi: "3.0.3"
info:
title: "ADR-021: Workflow Transition with Step-specific Attachments"
version: "1.8.6"
description: |
Extended Workflow Engine API contracts for ADR-021.
- POST /instances/:id/transition — extended with attachmentPublicIds
- GET /instances/:id/history — new endpoint returning history with attachments per step
servers:
- url: "/api/workflow-engine"
description: "NAP-DMS Backend API"
security:
- BearerAuth: []
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
bearerFormat: JWT
headers:
IdempotencyKey:
description: |
UUIDv7 idempotency token. If the same key+userId is received within 24h,
the cached response is returned without re-processing. (ADR-021 §5.1)
schema:
type: string
format: uuid
required: true
schemas:
WorkflowTransitionRequest:
type: object
required:
- action
properties:
action:
type: string
description: "Action ที่ต้องการทำ — ต้องตรงกับ DSL ของ Workflow นี้"
example: "APPROVE"
enum: [APPROVE, REJECT, RETURN, ACKNOWLEDGE]
comment:
type: string
description: "ความเห็นประกอบการอนุมัติ"
example: "อนุมัติแล้ว ดำเนินการต่อได้เลย"
nullable: true
payload:
type: object
description: "ข้อมูลเพิ่มเติมสำหรับ DSL Context"
additionalProperties: true
nullable: true
example:
urgent: true
attachmentPublicIds:
type: array
description: |
รายการ publicId (UUIDv7) ของไฟล์แนบที่ต้องการผูกกับขั้นตอนนี้.
ไฟล์ต้องผ่าน Two-Phase Upload ก่อน (is_temporary = false, ClamAV passed).
ADR-019: ใช้ publicId เท่านั้น — ห้ามใช้ INT id.
items:
type: string
format: uuid
example: "019505a1-7c3e-7000-8000-abc123def456"
maxItems: 20
nullable: true
WorkflowTransitionResponse:
type: object
properties:
success:
type: boolean
example: true
nextState:
type: string
description: "สถานะใหม่หลัง Transition"
example: "APPROVED"
historyId:
type: string
format: uuid
description: "ID ของ WorkflowHistory record ที่เพิ่งสร้าง"
example: "b8a2e3c1-4567-4abc-8def-0123456789ab"
isCompleted:
type: boolean
description: "true ถ้า Workflow สิ้นสุดแล้ว (Terminal State)"
example: false
attachmentsLinked:
type: integer
description: "จำนวนไฟล์แนบที่ถูก link กับ History record นี้"
example: 2
AttachmentSummary:
type: object
properties:
publicId:
type: string
format: uuid
description: "UUIDv7 identifier (ADR-019)"
example: "019505a1-7c3e-7000-8000-abc123def456"
originalFilename:
type: string
example: "drawing-rev-A.pdf"
mimeType:
type: string
example: "application/pdf"
fileSize:
type: integer
description: "ขนาดไฟล์ (bytes)"
example: 2048000
createdAt:
type: string
format: date-time
example: "2026-04-12T10:30:00Z"
WorkflowHistoryItem:
type: object
properties:
id:
type: string
format: uuid
description: "UUID ของ history record (PK โดยตรง)"
example: "b8a2e3c1-4567-4abc-8def-0123456789ab"
fromState:
type: string
example: "PENDING_REVIEW"
toState:
type: string
example: "APPROVED"
action:
type: string
example: "APPROVE"
actorName:
type: string
description: "ชื่อผู้ดำเนินการ (populated via user join)"
example: "สมชาย ใจดี"
nullable: true
comment:
type: string
nullable: true
example: "อนุมัติแล้ว"
createdAt:
type: string
format: date-time
example: "2026-04-12T10:30:00Z"
attachments:
type: array
description: "ไฟล์แนบที่อัปโหลดพร้อมขั้นตอนนี้ (Step-specific)"
items:
$ref: "#/components/schemas/AttachmentSummary"
ErrorResponse:
type: object
properties:
statusCode:
type: integer
message:
type: string
description: "Technical error message (for developers)"
userMessage:
type: string
description: "User-friendly message (Thai, for display)"
recoveryAction:
type: string
description: "คำแนะนำสำหรับผู้ใช้ในการแก้ปัญหา"
nullable: true
errorCode:
type: string
nullable: true
paths:
/instances/{instanceId}/transition:
post:
operationId: processWorkflowTransition
summary: "ดำเนินการเปลี่ยนสถานะ Workflow พร้อมแนบไฟล์ประจำขั้นตอน"
description: |
Executes a workflow state transition. Optionally links pre-uploaded attachments
to this workflow history step.
**Security:**
- Requires `workflow.action_review` permission
- 4-Level RBAC: Superadmin > Org Admin > Assigned Handler > Read-only
- Idempotency-Key header REQUIRED (prevents duplicate submissions)
**File Attachment:**
- Files must be pre-uploaded via Two-Phase upload endpoint
- Files must be committed (is_temporary = false, ClamAV passed)
- Max 20 attachments per transition
**Concurrency:**
- Redis Redlock applied to instanceId
- Only 1 concurrent transition allowed per instance
parameters:
- name: instanceId
in: path
required: true
schema:
type: string
format: uuid
description: "Workflow Instance ID (UUID)"
- name: Idempotency-Key
in: header
required: true
schema:
type: string
format: uuid
description: "UUIDv7 idempotency token (TTL: 24h). Re-use returns cached response."
requestBody:
required: true
content:
application/json:
schema:
$ref: "#/components/schemas/WorkflowTransitionRequest"
examples:
approve_with_attachments:
summary: "อนุมัติพร้อมไฟล์แนบ"
value:
action: "APPROVE"
comment: "อนุมัติแล้ว เอกสารครบถ้วน"
attachmentPublicIds:
- "019505a1-7c3e-7000-8000-abc123def456"
- "019505b2-8d4f-7000-9000-def456abc789"
reject_no_attachments:
summary: "ปฏิเสธโดยไม่มีไฟล์แนบ"
value:
action: "REJECT"
comment: "เอกสารไม่ครบถ้วน กรุณาแก้ไขและส่งใหม่"
responses:
"200":
description: "Transition executed successfully"
content:
application/json:
schema:
type: object
properties:
data:
$ref: "#/components/schemas/WorkflowTransitionResponse"
"200_idempotent":
description: "Idempotent response — duplicate key detected, cached result returned"
headers:
X-Idempotent-Replay:
schema:
type: string
enum: ["true"]
content:
application/json:
schema:
type: object
properties:
data:
$ref: "#/components/schemas/WorkflowTransitionResponse"
"400":
description: |
Bad Request — possible causes:
- Missing Idempotency-Key header
- Invalid action for current state
- attachmentPublicIds contains non-committed or non-existent UUIDs
- Workflow not in ACTIVE status
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
"403":
description: "Forbidden — user does not have permission for this transition"
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
example:
statusCode: 403
userMessage: "คุณไม่มีสิทธิ์ดำเนินการในขั้นตอนนี้"
recoveryAction: "ติดต่อผู้รับผิดชอบหรือ Admin หากคิดว่านี่เป็นข้อผิดพลาด"
"404":
description: "Workflow Instance not found"
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
"409":
description: "Conflict — Concurrent transition in progress (Redlock busy)"
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
example:
statusCode: 409
userMessage: "มีการดำเนินการอื่นอยู่ระหว่างดำเนินการ กรุณารอสักครู่แล้วลองใหม่"
recoveryAction: "รอ 5 วินาทีแล้วลองใหม่อีกครั้ง"
/instances/{instanceId}/history:
get:
operationId: getWorkflowHistory
summary: "ดึงประวัติการเปลี่ยนสถานะพร้อมไฟล์แนบประจำแต่ละขั้นตอน"
description: |
Returns the complete workflow history for an instance, including
step-specific attachments for each transition.
**Caching:** Redis cache TTL 1h, invalidated on state change.
**Security:** Requires `document.view` permission.
parameters:
- name: instanceId
in: path
required: true
schema:
type: string
format: uuid
description: "Workflow Instance ID (UUID)"
responses:
"200":
description: "History with step attachments"
content:
application/json:
schema:
type: object
properties:
data:
type: array
items:
$ref: "#/components/schemas/WorkflowHistoryItem"
example:
data:
- id: "b8a2e3c1-4567-4abc-8def-0123456789ab"
fromState: "DRAFT"
toState: "PENDING_REVIEW"
action: "SUBMIT"
actorName: "สมชาย ใจดี"
comment: "ส่งเพื่อตรวจสอบ"
createdAt: "2026-04-10T09:00:00Z"
attachments: []
- id: "c9b3f4d2-5678-5bcd-9ef0-1234567890bc"
fromState: "PENDING_REVIEW"
toState: "APPROVED"
action: "APPROVE"
actorName: "วิชัย รักดี"
comment: "อนุมัติแล้ว"
createdAt: "2026-04-12T10:30:00Z"
attachments:
- publicId: "019505a1-7c3e-7000-8000-abc123def456"
originalFilename: "drawing-rev-A.pdf"
mimeType: "application/pdf"
fileSize: 2048000
createdAt: "2026-04-12T10:25:00Z"
"403":
description: "Forbidden"
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
"404":
description: "Instance not found"
content:
application/json:
schema:
$ref: "#/components/schemas/ErrorResponse"
@@ -0,0 +1,285 @@
# Data Model: ADR-021 Integrated Workflow Context & Step-specific Attachments
**Phase 1 Output** | Generated: 2026-04-12
---
## 1. SQL Delta
**File:** `specs/03-Data-and-Storage/deltas/04-add-workflow-history-id-to-attachments.sql`
```sql
-- ============================================================
-- Delta 04: ADR-021 — Step-specific Attachments
-- เพิ่ม FK workflow_history_id ใน attachments table
-- ============================================================
-- ข้อควรระวัง: ค่า NULL = ไฟล์แนบหลัก (Main Document)
-- ค่าไม่ NULL = ไฟล์ประจำ Workflow Step นั้น
ALTER TABLE attachments
ADD COLUMN workflow_history_id CHAR(36) NULL
COMMENT 'FK to workflow_histories.id สำหรับไฟล์แนบประจำ Step (ADR-021). NULL = ไฟล์แนบหลัก',
ADD CONSTRAINT fk_attachments_workflow_history
FOREIGN KEY (workflow_history_id)
REFERENCES workflow_histories (id)
ON DELETE SET NULL
ON UPDATE CASCADE;
-- Index สำหรับ optimize การดึงไฟล์แนบตาม Step + เรียงตามวันที่
CREATE INDEX idx_att_wfhist_created
ON attachments (workflow_history_id, created_at);
```
**Migration Notes (ADR-009):**
- Apply via `MariaDB CLI` หรือผ่าน n8n delta workflow
- ไม่มี TypeORM migration file — ห้ามสร้าง (ADR-009)
- Rollback: `ALTER TABLE attachments DROP FOREIGN KEY fk_attachments_workflow_history; ALTER TABLE attachments DROP COLUMN workflow_history_id;`
---
## 2. Backend Entity Changes
### 2.1 `attachment.entity.ts` — Add `workflowHistoryId`
**Current state (existing columns):**
```@/e:/np-dms/lcbp3/backend/src/common/file-storage/entities/attachment.entity.ts:43-58```
**Required additions:**
```typescript
// เพิ่มหลัง referenceDate column
@Column({ name: 'workflow_history_id', length: 36, nullable: true })
workflowHistoryId?: string;
// Lazy relation — ไม่ include ใน default query เพื่อป้องกัน N+1
@ManyToOne(
() => WorkflowHistory,
(history: WorkflowHistory) => history.attachments,
{ nullable: true, onDelete: 'SET NULL', lazy: true }
)
@JoinColumn({ name: 'workflow_history_id' })
workflowHistory?: Promise<WorkflowHistory>;
```
**Import to add:**
```typescript
import { WorkflowHistory } from '../../../modules/workflow-engine/entities/workflow-history.entity';
```
---
### 2.2 `workflow-history.entity.ts` — Add `attachments` relation
**Current state:**
```@/e:/np-dms/lcbp3/backend/src/modules/workflow-engine/entities/workflow-history.entity.ts:18-61```
**Required additions:**
```typescript
// เพิ่ม import
import { OneToMany } from 'typeorm';
import { Attachment } from '../../../common/file-storage/entities/attachment.entity';
// เพิ่มใน Class (หลัง createdAt)
// Lazy relation — โหลดเฉพาะเมื่อต้องการ (ป้องกัน N+1 ใน History list queries)
@OneToMany(
() => Attachment,
(attachment: Attachment) => attachment.workflowHistory,
{ lazy: true }
)
attachments?: Promise<Attachment[]>;
```
---
## 3. DTO Changes
### 3.1 `workflow-transition.dto.ts` — Add `attachmentPublicIds`
**Extended DTO:**
```typescript
// เพิ่ม imports
import { IsArray, IsUUID, ArrayMaxSize } from 'class-validator';
// เพิ่ม field ใน WorkflowTransitionDto
@ApiPropertyOptional({
description: 'รายการ publicId ของไฟล์แนบ (ต้องอัปโหลดผ่าน Two-Phase ก่อน — ADR-016)',
example: ['019505a1-7c3e-7000-8000-abc123def456'],
type: [String],
})
@IsArray()
@IsUUID('all', { each: true })
@ArrayMaxSize(20) // ป้องกัน payload ขนาดใหญ่เกิน (controlled by infra, this is soft guard)
@IsOptional()
attachmentPublicIds?: string[];
```
---
## 4. New Types
### 4.1 Backend — `WorkflowHistoryResponseDto`
**File:** `backend/src/modules/workflow-engine/dto/workflow-history-response.dto.ts` (NEW)
```typescript
export class AttachmentSummaryDto {
publicId!: string; // UUIDv7 (ADR-019)
originalFilename!: string;
mimeType!: string;
fileSize!: number;
createdAt!: Date;
}
export class WorkflowHistoryItemDto {
id!: string; // UUID — เป็น PK โดยตรง (ไม่ใช่ UuidBaseEntity)
fromState!: string;
toState!: string;
action!: string;
actionByUserId?: number;
comment?: string;
createdAt!: Date;
attachments!: AttachmentSummaryDto[]; // ไฟล์แนบประจำ Step นี้
}
```
---
## 5. Frontend Type Changes
### 5.1 `frontend/types/workflow.ts` — Add `WorkflowHistoryItem`
**Addition to existing file:**
```typescript
// ไฟล์แนบสรุปสำหรับแสดงใน Workflow Timeline
export interface WorkflowAttachmentSummary {
publicId: string; // ADR-019: ใช้ publicId เท่านั้น
originalFilename: string;
mimeType: string;
fileSize: number;
createdAt: string;
}
// ประวัติ 1 ขั้นตอนใน Workflow Timeline
export interface WorkflowHistoryItem {
id: string; // UUID — history record ID
fromState: string;
toState: string;
action: WorkflowAction;
actorName?: string; // ชื่อผู้ดำเนินการ (populated via join)
comment?: string;
createdAt: string;
attachments: WorkflowAttachmentSummary[];
isCurrent?: boolean; // computed by frontend
}
// Priority Enum สำหรับ Integrated Banner
export enum WorkflowPriority {
URGENT = 'URGENT',
HIGH = 'HIGH',
MEDIUM = 'MEDIUM',
LOW = 'LOW',
}
```
### 5.2 `frontend/types/dto/workflow-engine/workflow-engine.dto.ts` — Add transition DTO
**Addition:**
```typescript
// Extended Transition DTO รองรับ Step-specific Attachments (ADR-021)
export interface WorkflowTransitionWithAttachmentsDto {
action: string;
comment?: string;
payload?: Record<string, unknown>;
attachmentPublicIds?: string[]; // pre-uploaded UUIDv7 list
}
```
---
## 6. State Transition with Attachment Flow
```
[User reviews document]
[Upload files via POST /files/upload (Two-Phase)]
→ ClamAV scan (auto)
→ Returns: { publicId, tempId, ... }[]
[User clicks Approve/Reject/Return]
→ use-workflow-action hook:
1. Generates Idempotency-Key (UUIDv7)
2. POST /workflow-engine/instances/:id/transition
Header: Idempotency-Key
Body: { action, comment, attachmentPublicIds: [uuid1, uuid2] }
[WorkflowTransitionGuard] — RBAC check (4-Level)
│ pass
[WorkflowEngineService.processTransition()]
→ Check Redis idempotency key (return cached if duplicate)
→ Acquire Redis Redlock on instanceId
→ Begin DB Transaction:
1. Lock WorkflowInstance (pessimistic_write)
2. Evaluate DSL transition
3. Update WorkflowInstance.currentState
4. Create WorkflowHistory record
5. Resolve attachmentPublicIds → internal IDs
6. UPDATE attachments SET workflow_history_id = :historyId
WHERE uuid IN (:publicIds) AND is_temporary = false
7. Commit Transaction
→ Release Redlock
→ Dispatch BullMQ events (notification, audit)
→ Invalidate Redis cache key wf:history:{instanceId}
→ Store idempotency response in Redis (TTL 24h)
[Response: { success, nextState, historyId, isCompleted }]
[Frontend: invalidate TanStack Query cache → reload document + timeline]
```
---
## 7. Entity Relationship Diagram
```
workflow_definitions
│ 1
│ has many
▼ N
workflow_instances ──────────────── documents (RFA/Corr/etc)
│ 1 (entityType + entityId)
│ has many
▼ N
workflow_histories ◄─────────────────────────────┐
│ id: CHAR(36) UUID │
│ │
│ ◄── attachments.workflow_history_id (FK, nullable)
attachments
id: INT (internal, @Exclude)
uuid: UUID (publicId — ADR-019)
workflow_history_id: CHAR(36) NULL ← NEW (ADR-021)
```
---
## 8. Index Strategy
| Table | Index | Columns | Purpose |
|-------|-------|---------|---------|
| `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.
@@ -0,0 +1,301 @@
# Implementation Plan: ADR-021 Integrated Workflow Context & Step-specific Attachments
**Branch**: `feat/adr-021-integrated-workflow-context` | **Date**: 2026-04-12 | **ADR**: [ADR-021](../../06-Decision-Records/ADR-021-integrated-workflow-context.md%20.md)
**Input**: Feature specification from `specs/06-Decision-Records/ADR-021-integrated-workflow-context.md .md`
---
## Summary
ปรับปรุง Workflow Engine ให้รองรับ (1) **Integrated Banner** ที่ยุบรวม Metadata + Status + Actions ไว้ด้วยกัน (2) **Vertical Timeline Lifecycle** พร้อม Active Step Highlighting และ (3) **Step-specific Attachments** ที่เชื่อมโยงไฟล์แนบกับ `workflow_history` ของแต่ละขั้นตอนโดยตรง
แนวทางเทคนิค: ขยาย `workflow_histories` ด้วย FK ใน `attachments` (Nullable) + ขยาย `WorkflowTransitionDto` รับ `attachmentPublicIds` (pre-uploaded UUIDv7 list) + สร้าง Frontend components ใหม่ 4 ชิ้น
---
## Technical Context
**Language/Version**: TypeScript 5.x (strict mode), Node.js 20+
**Primary Dependencies**:
- Backend: NestJS 10, TypeORM 0.3, MariaDB 10.6+, Redis (Redlock), BullMQ
- Frontend: Next.js 14 (App Router), TailwindCSS 3.4, shadcn/ui, TanStack Query v5, React Hook Form + Zod
**Storage**: MariaDB (schema via SQL delta — ADR-009), MinIO / Local FS via `StorageService`
**Testing**: Jest (backend unit + e2e), Vitest (frontend)
**Target Platform**: QNAP Container Station (Docker), Browser (Chrome/Edge latest)
**Project Type**: Web application (backend/ + frontend/ monorepo)
**Performance Goals**: Workflow history + attachment join query < 200ms p95 (mitigated by Redis Cache TTL 1h)
**Constraints**: No TypeORM migrations (ADR-009); UUID via `publicId` only (ADR-019); ClamAV scan mandatory (ADR-016); BullMQ for all async jobs (ADR-008)
**Scale/Scope**: ~50 concurrent users, documents in hundreds per project
---
## Constitution Check
_GATE: Checked against `.windsurfrules` before Phase 0. Re-verified after Phase 1._
| Gate | Status | Notes |
|------|--------|-------|
| **🔴 UUID Pattern (ADR-019)** | ✅ PASS | All attachment references via `publicId` (UUIDv7 string). `workflow_history_id` FK value is CHAR(36) UUID from `workflow_histories.id`. No `parseInt` usage. |
| **🔴 Schema via SQL Delta (ADR-009)** | ✅ PASS | Delta file `04-add-workflow-history-id-to-attachments.sql` — no TypeORM migration |
| **🔴 Two-Phase Upload (ADR-016)** | ✅ PASS | Files uploaded via existing Two-Phase endpoint first; `publicId`s referenced in transition DTO |
| **🔴 ClamAV Scan (ADR-016)** | ✅ PASS | ClamAV scan runs during Phase 1 of file upload (before transition) |
| **🔴 CASL Guard (ADR-016)** | ✅ PASS | New `WorkflowTransitionGuard` implements 4-Level RBAC |
| **🔴 Idempotency-Key (Security Rule #1)** | ✅ PASS | `POST /instances/:id/transition` validates `Idempotency-Key` header |
| **🔴 BullMQ Async (ADR-008)** | ✅ PASS | Notifications dispatched via `WorkflowEventService` (existing BullMQ pattern) |
| **🔴 No `any` types** | ✅ PASS | All new types fully typed — see data-model.md |
| **🟡 Thin Controller** | ✅ PASS | Controller delegates to Service; Guard handles RBAC |
| **🟡 Test Coverage 80% business logic** | ⚠️ REQUIRED | See testing plan in Phase 3 |
| **🔴 Redis Redlock (ADR-002)** | ✅ PASS | Redlock applied to `instanceId` during `processTransition()` — existing pattern extended |
---
## Project Structure
### Documentation (this feature)
```text
specs/08-Tasks/ADR-021-workflow-context/
├── plan.md ← this file
├── research.md ← Phase 0 output
├── data-model.md ← Phase 1 output
├── quickstart.md ← Phase 1 output
└── contracts/
├── workflow-transition.yaml ← extended transition API contract
└── workflow-history-list.yaml ← attachment query API contract
```
### Source Code (impacted files)
```text
# 🔴 Backend — DB & Entities
specs/03-Data-and-Storage/deltas/
└── 04-add-workflow-history-id-to-attachments.sql [NEW]
backend/src/common/file-storage/entities/
└── attachment.entity.ts [MODIFY — add workflowHistoryId + relation]
backend/src/modules/workflow-engine/entities/
└── workflow-history.entity.ts [MODIFY — add OneToMany attachments]
# 🔴 Backend — API & Guards
backend/src/modules/workflow-engine/dto/
└── workflow-transition.dto.ts [MODIFY — add attachmentPublicIds]
backend/src/modules/workflow-engine/guards/
└── workflow-transition.guard.ts [NEW — 4-Level RBAC]
backend/src/modules/workflow-engine/
├── workflow-engine.service.ts [MODIFY — extend processTransition()]
├── workflow-engine.controller.ts [MODIFY — add idempotency header, guard]
└── workflow-engine.module.ts [MODIFY — register guard]
# 🟡 Frontend — Types
frontend/types/
└── workflow.ts [MODIFY — add attachments to WorkflowHistoryStep]
frontend/types/dto/workflow-engine/
└── workflow-engine.dto.ts [MODIFY — add WorkflowTransitionWithAttachmentsDto]
# 🟡 Frontend — New Components
frontend/components/workflow/
├── integrated-banner.tsx [NEW — Status + Metadata + Action bar]
└── workflow-lifecycle.tsx [NEW — Vertical timeline with Indigo active step]
frontend/components/common/
└── file-preview-modal.tsx [NEW — PDF/Image inline preview]
# 🟡 Frontend — New Hook
frontend/hooks/
└── use-workflow-action.ts [NEW — upload + transition orchestration]
# 🟡 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]
```
---
## Complexity Tracking
_No constitution violations. Architecture is additive (Nullable FK, extended DTO, new components)._
---
## Phase 0: Research Findings
→ See `research.md` for full details. Summary:
| Unknown | Decision | Rationale |
|---------|----------|-----------|
| File attachment strategy during transition | **Upload-Then-Reference** (not multipart) | Consistent with ADR-016 Two-Phase; ClamAV runs before transition; simpler transaction boundary |
| FK structure for step-attachments | Add `workflow_history_id CHAR(36) NULL` to `attachments` table | ADR-021 explicit; backward-compatible (existing attachments = NULL) |
| Workflow History UUID type | `CHAR(36)``@PrimaryGeneratedColumn('uuid')` (NOT `UuidBaseEntity`) | Existing entity pattern; FK in attachments mirrors this |
| 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 |
---
## Phase 1: Design Decisions
### 1.1 Data Model
→ See `data-model.md` for complete entity definitions.
**Key decisions:**
- `attachments.workflow_history_id` = `CHAR(36) NULL` FK → `workflow_histories.id`
- `ON DELETE SET NULL` (preserve attachment records if history row deleted)
- Composite index: `INDEX idx_att_wfhist_created (workflow_history_id, created_at)`
- `WorkflowHistory` gains `@OneToMany(() => Attachment, a => a.workflowHistory)`**lazy-loaded only** (don't include in default `findOne` to avoid N+1)
### 1.2 API Contract
→ See `contracts/workflow-transition.yaml` for OpenAPI spec.
**Extended `POST /workflow-engine/instances/:instanceId/transition`:**
```
Header: Idempotency-Key: <UUIDv7>
Body: {
action: string // existing
comment?: string // existing
payload?: Record // existing
attachmentPublicIds?: string[] // NEW — UUIDv7 list of pre-uploaded attachments
}
```
**New `GET /workflow-engine/instances/:instanceId/history`:**
```
Response: WorkflowHistoryItem[] with nested attachments[] per step
```
### 1.3 Frontend Architecture
3 new components follow **compound pattern**:
```
<IntegratedBanner document={doc} workflowInstance={instance} onAction={...} />
└── uses: <PriorityBadge />, <StatusBadge />, <WorkflowActionButtons />
<WorkflowLifecycle instance={instance} onFileClick={openPreview} />
└── vertical timeline, Indigo active step (pulse animation)
└── each step: StepCard with date, actor, comment, attachments[]
<FilePreviewModal file={attachment} onClose={...} />
└── PDF: <iframe src="/api/files/preview/:publicId" />
└── Image: <img src="/api/files/preview/:publicId" />
```
**`use-workflow-action` hook responsibilities:**
1. Validate `Idempotency-Key` (generate UUIDv7 once per action intent)
2. Ensure all `attachmentPublicIds` are committed (not temp) before transition
3. Call `POST /instances/:id/transition` with `Idempotency-Key` header
4. Invalidate TanStack Query cache for the document + workflow instance
---
## Phase 2: Task Breakdown
### 🔴 CRITICAL (must complete in order)
| # | Task | File(s) | Dependencies |
|---|------|---------|--------------|
| T1 | Create SQL delta — add `workflow_history_id` to `attachments` | `deltas/04-*.sql` | None |
| T2 | Update `attachment.entity.ts` — add `workflowHistoryId` column + relation | `attachment.entity.ts` | T1 |
| T3 | Update `workflow-history.entity.ts` — add `@OneToMany attachments` | `workflow-history.entity.ts` | T1 |
| T4 | Extend `WorkflowTransitionDto` — add `attachmentPublicIds` | `workflow-transition.dto.ts` | None |
| T5 | Create `WorkflowTransitionGuard` (CASL 4-Level RBAC) | `guards/workflow-transition.guard.ts` | None |
| T6 | Extend `WorkflowEngineService.processTransition()` — resolve attachment IDs + link to history | `workflow-engine.service.ts` | T2, T3, T4 |
| T7 | Update `WorkflowEngineController` — add idempotency header validation + guard + history endpoint | `workflow-engine.controller.ts` | T5, T6 |
| T8 | Register guard in `WorkflowEngineModule` | `workflow-engine.module.ts` | T5 |
### 🟡 IMPORTANT (frontend, after backend complete)
| # | Task | File(s) | Dependencies |
|---|------|---------|--------------|
| F1 | Update `frontend/types/workflow.ts` — add `WorkflowHistoryItem` with `attachments[]` | `types/workflow.ts` | T7 |
| F2 | Update `workflow-engine.dto.ts` — add `WorkflowTransitionWithAttachmentsDto` | `types/dto/workflow-engine/workflow-engine.dto.ts` | T4 |
| F3 | Create `use-workflow-action.ts` hook | `hooks/use-workflow-action.ts` | F2 |
| F4 | Create `IntegratedBanner` component | `components/workflow/integrated-banner.tsx` | F1 |
| F5 | Create `WorkflowLifecycle` component (vertical timeline) | `components/workflow/workflow-lifecycle.tsx` | F1 |
| 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 |
### 🟢 GUIDELINES (after F7/F8)
| # | Task | File(s) | Dependencies |
|---|------|---------|--------------|
| G1 | Add i18n keys for all new UI text | `locales/th.json`, `locales/en.json` | F4F8 |
| G2 | Write unit tests — `WorkflowEngineService.processTransition()` extended paths | `workflow-engine.service.spec.ts` | T6 |
| G3 | Write unit tests — `WorkflowTransitionGuard` RBAC paths | `guards/workflow-transition.guard.spec.ts` | T5 |
| G4 | Write component tests — `IntegratedBanner`, `WorkflowLifecycle`, `FilePreviewModal` | `*.test.tsx` | F4F6 |
| G5 | E2E test — complete workflow transition with file upload | `test/workflow-with-attachment.e2e-spec.ts` | All |
---
## Phase 3: Verification Plan
### Backend Verification
```bash
# 1. Schema check
grep -n "workflow_history_id" specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql
# after applying delta — should exist
# 2. Unit tests
cd backend && pnpm test --testPathPattern=workflow-engine.service
cd backend && pnpm test --testPathPattern=workflow-transition.guard
# 3. Integration — transition with attachment
curl -X POST http://localhost:3001/api/workflow-engine/instances/:id/transition \
-H "Authorization: Bearer $TOKEN" \
-H "Idempotency-Key: $(uuidgen)" \
-H "Content-Type: application/json" \
-d '{"action":"APPROVE","comment":"OK","attachmentPublicIds":["<uuid>"]}'
# Expect 200 { success: true, nextState: "...", historyId: "..." }
# 4. Verify attachment linked
curl http://localhost:3001/api/workflow-engine/instances/:id/history
# attachment in correct step should have workflowHistoryId set
```
### Frontend Verification
```bash
cd frontend && pnpm test --run # Vitest
# All component tests pass
# IntegratedBanner renders Priority badge correctly (URGENT/HIGH/MEDIUM/LOW)
# WorkflowLifecycle highlights active step with Indigo + pulse
# FilePreviewModal opens PDF in iframe
```
### Security Verification
- [ ] `Idempotency-Key` missing → `400 Bad Request`
- [ ] Duplicate `Idempotency-Key``200` with cached response (no re-processing)
- [ ] Unauthorized user (not handler, not admin) → `403 Forbidden`
- [ ] ClamAV test file (EICAR) upload → blocked before transition
- [ ] `attachmentPublicIds` with non-temp (already-committed) UUID → rejected
---
## Dependencies Map
```
ADR-021
├── ADR-001 (Workflow Engine DSL) — extends processTransition()
├── ADR-002 (Redis Redlock) — existing lock pattern applied to transition
├── ADR-016 (Security) — Two-Phase upload, ClamAV, CASL Guard
├── ADR-019 (UUID) — publicId for all attachment references
└── ADR-008 (BullMQ) — notification dispatch (unchanged, existing pattern)
```
---
## Risk Register
| Risk | Likelihood | Impact | Mitigation |
|------|-----------|--------|------------|
| N+1 query on history + attachments join | Medium | High | Eager-load only when explicitly querying history; Redis cache TTL 1h |
| Race condition: 2 users upload to same step simultaneously | Low | High | Redis Redlock on `instanceId` — only 1 transition allowed at a time |
| Attachment linked to wrong history record | Low | High | `processTransition()` creates history row first, then links attachments in same transaction |
| ClamAV timeout during upload | Low | Medium | Upload endpoint has its own timeout; transition is decoupled |
| Frontend: stale workflow state after transition | Medium | Medium | `use-workflow-action` hook invalidates TanStack Query cache on success |
@@ -0,0 +1,402 @@
# Quickstart: ADR-021 Implementation Guide
**Phase 1 Output** | Generated: 2026-04-12 | Branch: `feat/adr-021-integrated-workflow-context`
---
## Prerequisites
- `backend/` and `frontend/` dev servers running
- MariaDB accessible
- Redis running (Redlock + Cache)
- ClamAV running (file upload pipeline)
---
## Step 1: Apply SQL Delta (🔴 CRITICAL FIRST)
```bash
# Apply delta to DB before touching any entity code
# ตรวจสอบ DB connection ก่อน
mysql -h <DB_HOST> -u <USER> -p <DB_NAME> < \
specs/03-Data-and-Storage/deltas/04-add-workflow-history-id-to-attachments.sql
```
**Verify:**
```sql
DESCRIBE attachments;
-- ต้องเห็น workflow_history_id CHAR(36) NULL
SHOW INDEX FROM attachments;
-- ต้องเห็น idx_att_wfhist_created
```
---
## Step 2: Backend — Entity Updates (T2, T3)
### T2: `attachment.entity.ts`
เพิ่มหลัง `referenceDate` column:
```typescript
@Column({ name: 'workflow_history_id', length: 36, nullable: true })
workflowHistoryId?: string;
@ManyToOne(
() => WorkflowHistory,
(history: WorkflowHistory) => history.attachments,
{ nullable: true, onDelete: 'SET NULL', lazy: true }
)
@JoinColumn({ name: 'workflow_history_id' })
workflowHistory?: Promise<WorkflowHistory>;
```
เพิ่ม import:
```typescript
import { WorkflowHistory } from '../../../modules/workflow-engine/entities/workflow-history.entity';
```
### T3: `workflow-history.entity.ts`
เพิ่มหลัง `createdAt`:
```typescript
@OneToMany(
() => Attachment,
(attachment: Attachment) => attachment.workflowHistory,
{ lazy: true }
)
attachments?: Promise<Attachment[]>;
```
เพิ่ม import:
```typescript
import { OneToMany } from 'typeorm';
import { Attachment } from '../../../common/file-storage/entities/attachment.entity';
```
---
## Step 3: Backend — DTO Update (T4)
### `workflow-transition.dto.ts`
เพิ่มใน `WorkflowTransitionDto`:
```typescript
@ApiPropertyOptional({
description: 'รายการ publicId ของไฟล์แนบ (ต้องอัปโหลดผ่าน Two-Phase ก่อน)',
type: [String],
})
@IsArray()
@IsUUID('all', { each: true })
@ArrayMaxSize(20)
@IsOptional()
attachmentPublicIds?: string[];
```
---
## Step 4: Backend — Guard (T5)
สร้าง `backend/src/modules/workflow-engine/guards/workflow-transition.guard.ts`:
```typescript
// Guard ตรวจสอบสิทธิ์ 4-Level RBAC ตาม ADR-021 §6
// Level 1: system.manage_all (Superadmin)
// Level 2: organization.manage_users + same org
// Level 3: Assigned handler (context.userId matches req.user.user_id)
// Level 4: Read-only → FORBIDDEN
@Injectable()
export class WorkflowTransitionGuard implements CanActivate {
constructor(
private readonly caslFactory: CaslAbilityFactory,
@InjectRepository(WorkflowInstance)
private readonly instanceRepo: Repository<WorkflowInstance>,
private readonly logger = new Logger(WorkflowTransitionGuard.name)
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest<RequestWithUser>();
const instanceId = request.params['id'];
const user = request.user;
// Level 1: Superadmin bypass
if (user.permissions?.includes('system.manage_all')) {
return true;
}
// ดึง Instance เพื่อตรวจสอบ Context
const instance = await this.instanceRepo.findOne({
where: { id: instanceId },
});
if (!instance) {
throw new NotFoundException('Workflow Instance', instanceId);
}
// Level 2: Org Admin (organization.manage_users + same org)
const docOrgId = instance.context?.organizationId as number | undefined;
if (
user.permissions?.includes('organization.manage_users') &&
docOrgId &&
user.organizationId === docOrgId
) {
return true;
}
// Level 3: Assigned Handler
const assignedUserId = instance.context?.assignedUserId as number | undefined;
if (assignedUserId && user.user_id === assignedUserId) {
return true;
}
this.logger.warn(
`Unauthorized transition attempt: User ${user.user_id} on Instance ${instanceId}`
);
throw new ForbiddenException({
userMessage: 'คุณไม่มีสิทธิ์ดำเนินการในขั้นตอนนี้',
recoveryAction: 'ติดต่อผู้รับผิดชอบหรือ Admin',
});
}
}
```
---
## Step 5: Backend — Service Extension (T6)
ใน `WorkflowEngineService.processTransition()` — เพิ่มหลัง `queryRunner.commitTransaction()`:
```typescript
// Link attachments ไปยัง history record (ถ้ามี)
if (attachmentPublicIds && attachmentPublicIds.length > 0) {
await queryRunner.manager
.createQueryBuilder()
.update(Attachment)
.set({ workflowHistoryId: history.id })
.where('uuid IN (:...publicIds)', { publicIds: attachmentPublicIds })
.andWhere('is_temporary = :temp', { temp: false }) // ต้องเป็น committed files เท่านั้น
.execute();
}
```
**Signature change:**
```typescript
async processTransition(
instanceId: string,
action: string,
userId: number,
comment?: string,
payload: Record<string, unknown> = {},
attachmentPublicIds: string[] = [] // NEW parameter
): Promise<WorkflowTransitionResponseDto>
```
---
## Step 6: Backend — Controller Update (T7)
```typescript
// เพิ่ม Idempotency-Key header validation + guard + history endpoint
// 1. เพิ่ม Guard บน transition endpoint
@Post('instances/:id/transition')
@UseGuards(JwtAuthGuard, WorkflowTransitionGuard)
async processTransition(
@Param('id') instanceId: string,
@Body() dto: WorkflowTransitionDto,
@Headers('Idempotency-Key') idempotencyKey: string,
@Request() req: RequestWithUser
) {
if (!idempotencyKey) {
throw new BadRequestException({
userMessage: 'กรุณาระบุ Idempotency-Key header',
errorCode: 'MISSING_IDEMPOTENCY_KEY',
});
}
// ตรวจสอบ Redis idempotency key
const cached = await this.redisService.get(
`idempotency:transition:${idempotencyKey}:${req.user.user_id}`
);
if (cached) {
return JSON.parse(cached);
}
const result = await this.workflowService.processTransition(
instanceId,
dto.action,
req.user.user_id,
dto.comment,
dto.payload,
dto.attachmentPublicIds ?? []
);
// บันทึก idempotency key (TTL 24h)
await this.redisService.set(
`idempotency:transition:${idempotencyKey}:${req.user.user_id}`,
JSON.stringify(result),
86400
);
return result;
}
// 2. New history endpoint
@Get('instances/:id/history')
@RequirePermission('document.view')
async getInstanceHistory(@Param('id') instanceId: string) {
return this.workflowService.getHistoryWithAttachments(instanceId);
}
```
---
## Step 7: Frontend — Types (F1, F2)
อัปเดต `frontend/types/workflow.ts` และ `frontend/types/dto/workflow-engine/workflow-engine.dto.ts` ตาม `data-model.md` ส่วน 5.
---
## Step 8: Frontend — `use-workflow-action` Hook (F3)
```typescript
// frontend/hooks/use-workflow-action.ts
export function useWorkflowAction(instanceId: string) {
const queryClient = useQueryClient();
const [idempotencyKey] = useState(() => generateUUIDv7()); // สร้าง 1 ครั้งต่อ action intent
const mutation = useMutation({
mutationFn: async (dto: WorkflowTransitionWithAttachmentsDto) => {
return workflowEngineService.transition(instanceId, dto, idempotencyKey);
},
onSuccess: () => {
// Invalidate cache สำหรับ document + history
void queryClient.invalidateQueries({ queryKey: ['workflow-history', instanceId] });
// Invalidate parent document queries (RFA, Correspondence, etc.)
void queryClient.invalidateQueries({ queryKey: ['rfa'] });
void queryClient.invalidateQueries({ queryKey: ['correspondence'] });
},
});
return { execute: mutation.mutateAsync, isPending: mutation.isPending };
}
```
---
## Step 9: Frontend — Components (F4F6)
### `IntegratedBanner` Props:
```typescript
interface IntegratedBannerProps {
documentNo: string;
subject: string;
status: string;
priority?: WorkflowPriority;
currentState: string;
availableActions: string[];
onAction: (action: string, comment?: string, files?: string[]) => void;
isLoading?: boolean;
}
```
### `WorkflowLifecycle` Props:
```typescript
interface WorkflowLifecycleProps {
history: WorkflowHistoryItem[];
currentState: string;
onFileClick: (attachment: WorkflowAttachmentSummary) => void;
}
```
### `FilePreviewModal` Props:
```typescript
interface FilePreviewModalProps {
attachment: WorkflowAttachmentSummary | null;
onClose: () => void;
}
```
---
## Step 10: Page Refactors (F7, F8)
ตัวอย่าง RFA detail page integration:
```tsx
// frontend/app/(dashboard)/rfas/[uuid]/page.tsx
export default function RFADetailPage() {
const { uuid } = useParams();
const { data: rfa, isLoading } = useRFA(String(uuid));
const [previewFile, setPreviewFile] = useState<WorkflowAttachmentSummary | null>(null);
const { execute, isPending } = useWorkflowAction(rfa?.workflowInstanceId ?? '');
return (
<>
<IntegratedBanner
documentNo={rfa?.rfaNo ?? ''}
subject={rfa?.subject ?? ''}
status={rfa?.status ?? ''}
priority={rfa?.priority}
currentState={rfa?.workflowState ?? ''}
availableActions={rfa?.availableActions ?? []}
onAction={(action, comment, files) =>
execute({ action, comment, attachmentPublicIds: files })
}
isLoading={isPending}
/>
<Tabs>
<TabsContent value="workflow">
<WorkflowLifecycle
history={rfa?.workflowHistory ?? []}
currentState={rfa?.workflowState ?? ''}
onFileClick={setPreviewFile}
/>
</TabsContent>
</Tabs>
<FilePreviewModal attachment={previewFile} onClose={() => setPreviewFile(null)} />
</>
);
}
```
---
## Testing Checklist
```bash
# Backend unit tests
cd backend
pnpm test --testPathPattern=workflow-engine.service
pnpm test --testPathPattern=workflow-transition.guard
# Frontend component tests
cd frontend
pnpm test --run --reporter=verbose
# TypeScript check (both)
cd backend && pnpm tsc --noEmit
cd frontend && pnpm tsc --noEmit
# Lint (both)
cd backend && pnpm lint
cd frontend && pnpm lint
```
---
## Security Pre-commit Checklist
- [ ] `workflow_history_id` FK applied and verified in DB
- [ ] `attachmentPublicIds` validates UUID format + `is_temporary = false`
- [ ] `Idempotency-Key` header required — missing returns `400`
- [ ] `WorkflowTransitionGuard` blocks Level 4 users with `403`
- [ ] ClamAV test: EICAR test file blocked before transition
- [ ] No `parseInt()` on any UUID in new code
- [ ] No `console.log` in committed code
- [ ] Comments in Thai, identifiers in English
- [ ] TypeScript strict — no `any` types
@@ -0,0 +1,216 @@
# Research: ADR-021 Integrated Workflow Context & Step-specific Attachments
**Phase 0 Output** | Generated: 2026-04-12
---
## Research Question 1: File Attachment Strategy During Workflow Transition
**Question:** Should files be uploaded atomically with the transition (multipart), or pre-uploaded and referenced by ID?
### Option A: Upload-Then-Reference (Selected ✅)
Client uploads files first via existing Two-Phase upload endpoint → receives `publicId`s → sends `publicId`s in `WorkflowTransitionDto.attachmentPublicIds`.
**Pros:**
- ClamAV scan and file validation run **independently** before the transition DB transaction
- Simpler transaction boundary (no file I/O inside Redlock + DB transaction)
- Compatible with existing `file-storage.service.ts` Two-Phase pattern (ADR-016)
- Incremental upload UX (user can upload as they review, then click Approve)
- No multipart complexity in transition controller
**Cons:**
- Two API round-trips from client
- Orphaned temp files possible if user abandons without transitioning (mitigated by existing `FileCleanupService` cron job)
### Option B: Multipart Transition Request (Rejected ❌)
Single multipart request combining DTO JSON + files.
**Cons:**
- ClamAV scan must happen inside the Redlock-protected transaction — high latency risk
- Breaks ADR-016 Two-Phase Upload contract
- Controller complexity (Multer + DTO parsing + ClamAV + Redlock + TypeORM transaction)
**Decision:** Option A — Upload-Then-Reference.
**Rationale:** Consistent with ADR-016 Two-Phase and existing `file-storage.controller.ts` patterns. Zero change to ClamAV pipeline.
---
## Research Question 2: FK Structure for Step-Specific Attachments
**Question:** Add `workflow_history_id` directly to `attachments` table, or create a junction table `workflow_history_attachments`?
### Option A: Direct FK on `attachments` (Selected ✅)
```sql
ALTER TABLE attachments
ADD COLUMN workflow_history_id CHAR(36) NULL;
```
**Pros:**
- Specified explicitly in ADR-021 §5
- Single JOIN to get step attachments
- Backward-compatible: existing records have `NULL` (treated as main-doc attachments)
- Simpler query: `WHERE workflow_history_id = :historyId`
**Cons:**
- `attachments` table grows slightly (one nullable column)
### Option B: Junction Table `workflow_history_attachments` (Rejected ❌)
```sql
CREATE TABLE workflow_history_attachments (
history_id CHAR(36) NOT NULL,
attachment_id INT NOT NULL,
PRIMARY KEY (history_id, attachment_id)
);
```
**Cons:**
- Extra table + extra JOIN
- ADR-021 explicitly mandates Approach A
- More complex service code
**Decision:** Option A — Direct FK on `attachments` table.
**Rationale:** Explicitly mandated by ADR-021 §5 §6. Nullable FK provides backward compatibility.
---
## Research Question 3: `workflow_histories.id` UUID Type
**Finding from codebase:**
`@/e:/np-dms/lcbp3/backend/src/modules/workflow-engine/entities/workflow-history.entity.ts:22-23`
```typescript
@PrimaryGeneratedColumn('uuid')
id!: string;
```
**Conclusion:** `workflow_histories.id` is `CHAR(36)` UUID generated by TypeORM `@PrimaryGeneratedColumn('uuid')`. This is **NOT** `UuidBaseEntity` pattern (which uses INT PK + `uuid` column separately).
**Impact on FK:** `attachments.workflow_history_id` must be `CHAR(36)` to match.
**ADR-019 compliance:** `WorkflowHistory` does NOT have the standard `publicId`/`@Exclude() id` pattern — it uses UUID as its primary key directly. When exposing history via API, use `id` (which is already a UUID string). No conversion needed.
---
## Research Question 4: Existing Workflow Visualizer — Reuse vs. New
**Finding:**
`@/e:/np-dms/lcbp3/frontend/components/custom/workflow-visualizer.tsx:26-28`
```typescript
// WorkflowVisualizer Component
// แสดงเส้นเวลา (Timeline) ของกระบวนการอนุมัติแบบแนวนอน
export function WorkflowVisualizer({ steps, className }: WorkflowVisualizerProps)
```
The existing component is **horizontal** layout. ADR-021 §3.2 requires **Vertical Timeline** with Indigo active highlighting.
**Decision:** Create NEW `frontend/components/workflow/workflow-lifecycle.tsx` (vertical). Keep existing `workflow-visualizer.tsx` (horizontal) for backward compat on other pages.
**Interface Difference:**
- Existing: `WorkflowStep { id, label, subLabel, status, date }`
- New: `WorkflowHistoryStep { id, fromState, toState, action, actor, comment, date, attachments[], isCurrent }`
---
## Research Question 5: Idempotency-Key Implementation
**Existing pattern:** No existing idempotency implementation found in workflow engine.
**Design:**
- Key format: `idempotency:transition:{idempotencyKey}:{userId}`
- Storage: Redis `SET` with `EX 86400` (24h TTL)
- Value: Serialized transition response `{ success, nextState, historyId, isCompleted }`
- On hit: Return cached value, HTTP 200 (or original status code if stored)
- On miss: Execute transition, store result, return
**Where to implement:** `WorkflowEngineController.processTransition()` — pre-execution check using `RedisService`. If key exists → return cached. If not → run `workflowService.processTransition()` → store result.
**Frontend:** `use-workflow-action` hook generates a UUIDv7 idempotency key once per "action intent" (when user clicks Approve/Reject). Key is regenerated if the user cancels and re-opens the action dialog.
---
## Research Question 6: Cache Strategy for Workflow History
**ADR-021 §9:** Redis Cache TTL 1 hour for workflow history data. Invalidate immediately on state change.
**Cache key pattern:**
- `wf:history:{instanceId}` → JSON of history items with attachments
- Invalidated in `WorkflowEngineService.processTransition()` after `commitTransaction()`
**Implementation:** Use existing `CacheService` or `@nestjs/cache-manager` with Redis store. Set `ttl: 3600` on history queries.
---
## Research Question 7: CASL 4-Level RBAC for Transition Guard
**ADR-021 §6:** 4-Level hierarchy: Superadmin > Org Admin > Assigned Handler > Read-only
**Existing patterns:**
- `RbacGuard` + `@RequirePermission()` in `workflow-engine.controller.ts`
- CASL ability checked via `CaslAbilityFactory`
**New `WorkflowTransitionGuard` logic:**
```typescript
// Level 1: system.manage_all (Superadmin) → always allowed
// Level 2: organization.manage_users AND same org as document → allowed
// Level 3: Assigned handler (workflow instance context.userId === req.user.user_id) → allowed
// Level 4: Read-only → FORBIDDEN (403)
```
**Impersonation (Upload on behalf):** Superadmin and Org Admin may supply `actingAsUserId` in payload to impersonate the handler for upload. Guard validates this permission level.
---
## Research Question 8: Priority Enum Visual Indicators
**ADR-021 Clarification:** `URGENT`, `HIGH`, `MEDIUM`, `LOW` — 4-tier system with visual indicators.
**Proposed Tailwind classes:**
| Priority | Badge Color | Dot/Icon |
|----------|------------|---------|
| `URGENT` | `bg-red-100 text-red-800 border-red-300` | 🔴 Pulse animation |
| `HIGH` | `bg-orange-100 text-orange-800 border-orange-300` | 🟠 |
| `MEDIUM` | `bg-yellow-100 text-yellow-800 border-yellow-300` | 🟡 |
| `LOW` | `bg-green-100 text-green-800 border-green-300` | 🟢 |
**Note:** Priority field source — `workflow_instances.context` JSON (existing `metadata`/`payload` field) or document master table. Needs clarification on which document modules expose `priority`. **Interim:** Render from `WorkflowInstance.context.priority` if present.
---
## Research Question 9: File Preview — Security Considerations
**Requirements:** PDF and Image preview via Modal (inline, no tab change).
**Backend:** Need a `GET /files/preview/:publicId` or `GET /attachments/:publicId/preview` endpoint that:
1. Validates user has `document.view` permission on the parent document
2. Streams file with `Content-Disposition: inline` (not `attachment`)
3. Sets `Content-Security-Policy: frame-src 'self'` for PDFs in `<iframe>`
**Frontend:**
- PDF: `<iframe src="/api/files/preview/:publicId" className="w-full h-full" />`
- Image: `<img src="/api/files/preview/:publicId" alt={filename} />`
- Detection: by `mimeType` field from attachment metadata
**Finding:** `file-storage.controller.ts` exists — check if preview endpoint already implemented or needs addition.
---
## Summary of All Decisions
| # | Decision | Chosen | Rejected |
|---|---------|--------|---------|
| 1 | File attachment strategy | Upload-Then-Reference | Multipart atomic |
| 2 | FK structure | Direct nullable FK on `attachments` | Junction table |
| 3 | `workflow_histories.id` type | `CHAR(36)` UUID direct PK | N/A |
| 4 | Visualizer reuse | New vertical `workflow-lifecycle.tsx` | Reuse horizontal |
| 5 | Idempotency storage | Redis key `idempotency:transition:{key}:{userId}` TTL 24h | DB table |
| 6 | History cache | Redis `wf:history:{instanceId}` TTL 1h, invalidate on transition | No cache |
| 7 | Transition RBAC | New `WorkflowTransitionGuard` 4-Level | Extend existing `RbacGuard` |
| 8 | Priority display | Tailwind badges from `instance.context.priority` | Hardcoded status |
| 9 | File preview security | `Content-Disposition: inline` + permission check | Direct storage URL |
@@ -0,0 +1,331 @@
# Tasks: ADR-021 Integrated Workflow Context & Step-specific Attachments
**Input**: Design documents from `specs/08-Tasks/ADR-021-workflow-context/`
**ADR**: `specs/06-Decision-Records/ADR-021-integrated-workflow-context.md .md`
**Branch**: `feat/adr-021-integrated-workflow-context`
**Version**: 1.8.6 | **Date**: 2026-04-12
**Prerequisites**: plan.md ✅ | research.md ✅ | data-model.md ✅ | contracts/ ✅ | quickstart.md ✅
---
## Format: `[ID] [P?] [Story?] Description`
- **[P]**: Can run in parallel (different files, no shared dependencies)
- **[US#]**: User Story this task belongs to
- All paths are absolute from monorepo root
---
## User Story Map
| Story | Priority | Description | REQ |
|-------|----------|-------------|-----|
| **US1** | P1 🎯 MVP | Integrated Banner — single-row metadata + status + actions | REQ-01 |
| **US2** | P1 🎯 MVP | Workflow Lifecycle Visualization — vertical timeline + active step | REQ-02, REQ-03 |
| **US3** | P2 | Step-specific Attachments — drag & drop upload linked to workflow step | REQ-04 |
| **US4** | P2 | Internal File Preview — PDF/Image modal without tab switch | REQ-05 |
| **US5** | P3 | i18n Support — all UI text via i18n keys | REQ-06 |
---
## Phase 1: Setup
**Purpose**: Branch and project initialization
- [ ] T001 Create feature branch `feat/adr-021-integrated-workflow-context` from `main`
- [ ] T002 [P] Verify MariaDB, Redis, and ClamAV are accessible in dev environment (per quickstart.md Step 1 prerequisites)
- [ ] T003 [P] Create frontend component directory `frontend/components/workflow/` (for IntegratedBanner and WorkflowLifecycle)
---
## Phase 2: Foundation — Backend DB & Entities (🔴 CRITICAL — Blocks US3, US4)
**Purpose**: Schema change + entity wiring that must complete before any step-attachment work. US1 and US2 (pure frontend) can proceed in parallel.
**⚠️ 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`
**Checkpoint**: Foundation complete — `pnpm tsc --noEmit` in backend must pass before proceeding to Phase 5.
---
## Phase 3: User Story 1 — Integrated Banner (Priority: P1) 🎯 MVP
**Goal**: Reviewer/Approver sees Doc No, Subject, Status, Priority badge, and Approve/Reject/Return buttons in a single sticky header bar — without scrolling or switching screens.
**Independent Test**:
```bash
# Render IntegratedBanner with mock data, verify:
# 1. Priority URGENT shows red pulse badge
# 2. Approve/Reject buttons present and call onAction
# 3. Status badge matches workflowState
cd frontend && pnpm test --run --reporter=verbose components/workflow/integrated-banner
```
### 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)
**Checkpoint**: `IntegratedBanner` renders correctly on RFA and Correspondence detail pages. Priority badge and action buttons visible. `pnpm tsc --noEmit` passes.
---
## Phase 4: User Story 2 — Workflow Lifecycle Visualization (Priority: P1) 🎯 MVP
**Goal**: User sees a vertical timeline of ALL workflow steps. Current step highlighted with Indigo (#6366f1) + pulse animation. Completed steps show actor name, date, and comment. Pending steps are visually distinct (muted).
**Independent Test**:
```bash
# Render WorkflowLifecycle with mock 4-step history (1 completed, 1 current, 2 pending)
# Verify: current step has 'bg-indigo-500' + 'animate-pulse' class
# Verify: completed steps show actor name and date
# Verify: pending steps are muted (opacity-50 or gray)
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)
**Checkpoint**: Workflow tab visible on RFA/Correspondence pages. Current step Indigo+pulse. Completed steps show actor/date. No TypeScript errors. `pnpm lint` passes.
---
## Phase 5: User Story 3 — Step-specific Attachments (Priority: P2)
**Goal**: Assigned Handler (or Superadmin/Org Admin on behalf) can drag-and-drop evidence files when submitting an Approve/Reject/Return action. Files are linked exclusively to that workflow history record. Concurrent transitions are serialized via Redis Redlock. Duplicate submissions detected via Idempotency-Key.
**Dependencies**: Phase 2 (Foundation) must be ✅ complete before starting.
**Independent Test**:
```bash
# Backend: POST /workflow-engine/instances/:id/transition
# with Idempotency-Key header + attachmentPublicIds
# Verify: 200 success, history record created, attachment.workflow_history_id set
cd backend && pnpm test --testPathPattern=workflow-engine.service
cd backend && pnpm test --testPathPattern=workflow-transition.guard
# Frontend: use-workflow-action hook mock test
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
**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.
---
## Phase 6: User Story 4 — Internal File Preview (Priority: P2)
**Goal**: User clicks any attachment in the Workflow Lifecycle timeline and a modal opens showing the file inline (PDF in `<iframe>`, images in `<img>`). No new browser tab opened.
**Dependencies**: Phase 5 (US3) attachments must exist to preview. Phase 4 (US2) timeline must be rendered.
**Independent Test**:
```bash
# Render FilePreviewModal with mock PDF attachment (mimeType: application/pdf)
# Verify: <iframe> rendered with correct /api/files/preview/:publicId src
# Render with mock image (mimeType: image/png)
# Verify: <img> rendered (no iframe)
# Verify: onClose called when Escape key pressed or X button clicked
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
**Checkpoint**: Clicking attachment chip in WorkflowLifecycle opens `FilePreviewModal`. PDF renders inline. Image renders inline. Modal closes on X or Escape. No TypeScript errors.
---
## Phase 7: User Story 5 — i18n Support (Priority: P3)
**Goal**: All new UI strings introduced by US1US4 use i18n keys (no hardcoded Thai or English text in component JSX).
**Dependencies**: US1US4 must be complete to know all string keys.
**Independent Test**:
```bash
# grep for hardcoded Thai text in new components
grep -rn "[ก-๙]" frontend/components/workflow/ frontend/components/common/file-preview-modal.tsx
# Should return 0 results in JSX/TSX (comments excluded)
```
### 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
**Checkpoint**: No hardcoded Thai text in new component JSX. Switching locale changes all new UI strings. `pnpm lint` and `pnpm tsc --noEmit` pass.
---
## Phase 8: Polish & Cross-Cutting Concerns
**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"
---
## Dependencies & Execution Order
### Phase Dependencies
```
Phase 1 (Setup)
└─► Phase 2 (Foundation) ◄─────────────── BLOCKS Phase 5, 6
├─► Phase 3 (US1 — Banner) [CAN START SAME TIME AS PHASE 2]
├─► Phase 4 (US2 — Timeline) [CAN START SAME TIME AS PHASE 2]
└─► Phase 5 (US3 — Attachments) [NEEDS PHASE 2 COMPLETE]
└─► Phase 6 (US4 — Preview) [NEEDS PHASE 5 DATA]
└─► Phase 7 (US5 — i18n) [NEEDS US1-US4 COMPLETE]
└─► Phase 8 (Polish) [NEEDS ALL STORIES]
```
### User Story Dependencies
| Story | Depends On | Can Parallel With |
|-------|-----------|------------------|
| **US1** | Phase 1 only | US2, Phase 2 |
| **US2** | Phase 1 only | US1, Phase 2 |
| **US3** | Phase 2 ✅ | — |
| **US4** | US3 (attachment data) | — |
| **US5** | US1, US2, US3, US4 | Phase 8 polish tasks |
### Within Each Phase (Task Order)
- **Phase 2**: T004 → (T005, T006 in parallel) → T007 → T008 → T009
- **Phase 3**: T010, T011 (parallel) → T012 → T013, T014, T015, T016 (parallel)
- **Phase 4**: T017, T018 (parallel) → T019, T020, T021, T022 (parallel)
- **Phase 5**: T023 → T024 → T025 → T026 → (T027, T028 parallel) → T029 → T030, T031 (parallel)
- **Phase 6**: T032 → T033 → T034, T035 (parallel)
- **Phase 7**: T036, T037, T038 (parallel) → T039
- **Phase 8**: T040T042 (parallel) → T043 → T044 → T045 → T046 → T047
---
## Parallel Execution Examples
### Backend Foundation (Phase 2, after T004)
```text
[T005] attachment.entity.ts — add workflowHistoryId + ManyToOne
[T006] workflow-history.entity.ts — add OneToMany attachments
← Run simultaneously (different files, no conflict)
```
### Frontend US1 + US2 + Backend Foundation (After Phase 1)
```text
[Phase 2] Backend DB + Entities
[Phase 3] Frontend IntegratedBanner
[Phase 4] Frontend WorkflowLifecycle Timeline
← All three can proceed simultaneously
```
### Within US3 Implementation
```text
[T027] use-workflow-action.ts hook
[T028] Drag-and-drop upload zone in workflow-lifecycle.tsx
← Run simultaneously (different files)
```
---
## Implementation Strategy
### MVP First (US1 + US2 — Frontend only, no backend changes)
1. Complete **Phase 1** (Setup)
2. Complete **Phase 3** (US1 — IntegratedBanner) — pure frontend
3. Complete **Phase 4** (US2 — WorkflowLifecycle) — pure frontend, reads existing history API
4. **STOP and VALIDATE**: RFA and Correspondence pages show new banner and timeline
5. Demo/review with stakeholders before building the attachment feature
### Full Feature Delivery
1. Setup + Foundation (Phase 1 + 2)
2. US1 + US2 in parallel with Foundation (Phase 3 + 4)
3. US3 — Step-specific Attachments backend + frontend (Phase 5)
4. US4 — File Preview (Phase 6)
5. US5 — i18n (Phase 7)
6. Polish + QA (Phase 8)
### Parallel Team Strategy
With 2 developers:
- **Dev A**: Phase 2 (Backend Foundation) → Phase 5 (US3 backend) → Phase 6 (US4 backend)
- **Dev B**: Phase 3 (US1 Banner) → Phase 4 (US2 Timeline) → Phase 5 (US3 frontend) → Phase 6 (US4 frontend)
---
## Summary
| Metric | Count |
|--------|-------|
| **Total Tasks** | 47 |
| **Phase 1 (Setup)** | 3 |
| **Phase 2 (Foundation)** | 6 |
| **Phase 3 (US1 — Banner)** | 7 |
| **Phase 4 (US2 — Timeline)** | 6 |
| **Phase 5 (US3 — Attachments)** | 9 |
| **Phase 6 (US4 — Preview)** | 4 |
| **Phase 7 (US5 — i18n)** | 4 |
| **Phase 8 (Polish)** | 8 |
| **Parallelizable [P] tasks** | 22 |
| **MVP scope (US1+US2 only)** | 19 tasks |
### Commit Message Convention
```
feat(workflow): T004 apply ADR-021 schema delta — workflow_history_id on attachments
feat(workflow): T012 add IntegratedBanner component (US1)
feat(workflow): T017 add WorkflowLifecycle vertical timeline (US2)
feat(workflow): T023 extend processTransition with attachmentPublicIds (US3)
feat(workflow): T033 add FilePreviewModal for inline PDF/image (US4)
feat(i18n): T036-T039 add i18n keys for ADR-021 UI strings (US5)
```