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
-3
View File
@@ -1,3 +0,0 @@
{
"editor.fontSize": 16
}
+333
View File
@@ -0,0 +1,333 @@
# Implementation Plan: Transmittals + Circulation Complete Integration (v1.8.7 Post-ADR-021)
**Branch**: `001-transmittals-circulation` | **Date**: 2026-04-12 | **Spec**: `specs/001-transmittals-circulation/spec.md`
---
## Summary
Wire up the ADR-021 `IntegratedBanner` + `WorkflowLifecycle` components (already imported as stubs) into the Transmittal and Circulation detail pages with live workflow data, add the missing `workflowInstanceId` exposure on both backend services, implement pending edge-case handlers (EC-RFA-004, EC-CIRC-001/002/003), and create missing TanStack Query hooks and list-page features.
---
## Technical Context
**Language/Version**: TypeScript 5.x (strict)
**Primary Dependencies**: NestJS 10, Next.js 14 (App Router), TypeORM, MariaDB, TanStack Query v5, shadcn/ui, TailwindCSS
**Storage**: MariaDB (via `workflow_instances` + `workflow_history` + `attachments` tables)
**Testing**: Vitest (frontend), Jest (backend)
**Target Platform**: QNAP Container Station (on-prem)
**Performance Goals**: Detail page loads workflow data < 1s; TanStack Query staleTime 60s
**Constraints**: ADR-009 (no migrations), ADR-019 (UUID strings only), ADR-016 (ClamAV), ADR-008 (BullMQ for notifications)
---
## Constitution Check
| Rule | Status | Notes |
|------|--------|-------|
| UUID patterns (ADR-019) — no parseInt | ✅ PASS | Use `publicId` string throughout |
| Schema changes via SQL delta (ADR-009) | ✅ PASS | No schema changes needed — additive response only |
| Security: CASL Guard on new endpoints | ✅ REQUIRED | Reassign/ForceClose endpoints need guards |
| Security: Idempotency-Key on workflow transitions | ✅ PASS | `use-workflow-action.ts` already sends key |
| BullMQ for notifications (ADR-008) | ✅ PASS | Existing NotificationService handles this |
| No `any` types | ✅ REQUIRED | Strict TypeScript enforcement |
| Thin controllers, business logic in services | ✅ PASS | Following existing RFA/Correspondence pattern |
| Test coverage ≥ 80% business logic | ⚠️ REQUIRED | New service methods need unit tests |
| Redis Redlock for document numbering | ✅ N/A | No new document numbering in this feature |
---
## Project Structure
### Documentation
```text
specs/001-transmittals-circulation/
├── spec.md ✅ done
├── plan.md ✅ this file
├── data-model.md (inline in this plan)
└── tasks.md (next step)
```
### Source Code Changes
```text
backend/src/modules/
├── workflow-engine/
│ └── workflow-engine.service.ts [ADD] getInstanceByEntity()
├── transmittal/
│ ├── transmittal.service.ts [MODIFY] findOneByUuid + findAll + EC-RFA-004
│ └── transmittal.controller.ts [MODIFY] add /submit endpoint
├── circulation/
│ ├── circulation.service.ts [MODIFY] findOneByUuid + reassign + forceClose
│ └── circulation.controller.ts [MODIFY] add /reassign + /force-close endpoints
frontend/
├── types/
│ ├── transmittal.ts [MODIFY] add workflowInstanceId, workflowState, availableActions
│ └── circulation.ts [MODIFY] add workflowInstanceId, workflowState, deadline fields
├── hooks/
│ ├── use-transmittal.ts [NEW] useTransmittal(uuid) hook
│ └── use-circulation.ts [MODIFY] add useCirculation(uuid)
├── app/(dashboard)/
│ ├── transmittals/[uuid]/page.tsx [MODIFY] wire IntegratedBanner + WorkflowLifecycle
│ └── circulation/[uuid]/page.tsx [MODIFY] wire IntegratedBanner + WorkflowLifecycle + Overdue
└── public/locales/
├── th/transmittal.json [ADD/UPDATE] i18n keys
└── en/transmittal.json [ADD/UPDATE] i18n keys
```
---
## Phase 0: Research Findings
### Key Design Decisions
1. **`workflowInstanceId` exposure**: No schema changes needed. The `WorkflowInstance` table has `entity_type` + `entity_id` columns. Add `getInstanceByEntity(entityType, entityId)` to `WorkflowEngineService`, then call it in `findOneByUuid` for both modules.
2. **Transmittal entityType**: Use `'transmittal'` (matching the entity ID = `correspondence.id.toString()`). Consistent with how RFA uses `'rfa'`.
3. **Circulation entityType**: Use `'circulation'` (entity ID = `circulation.id.toString()`). The Circulation entity already extends `UuidBaseEntity` (has `publicId`).
4. **Transmittal publicId**: The Transmittal entity has no own `publicId` — it shares `correspondence.publicId`. The service already maps it: `publicId: t.correspondence?.publicId`. This is correct; no change needed.
5. **EC-RFA-004 validation**: Fires in `TransmittalService.submit()` (new method). Check all `transmittal_items` → fetch their correspondence's current revision status → if any is DRAFT, throw `ValidationException`.
6. **EC-CIRC-001 (Reassign)**: New `CirculationService.reassignRouting(routingId, newAssigneeUuid, user)`. Requires `Document Control` or above role. Updates `routing.assignedTo` to the new user's INT id.
7. **EC-CIRC-002 (Force Close)**: New `CirculationService.forceClose(circulationId, reason, user)`. Requires `Document Control` or above. Updates all PENDING routings to `CANCELLED`, sets `circulation.statusCode = 'CANCELLED'`, writes audit log.
8. **EC-CIRC-003 (Overdue)**: Pure frontend logic. Compare `routing.deadline` with `new Date()`. Show `OverdueBadge` if `now > deadline + 1 day`. No backend change needed.
---
## Phase 1: Design Decisions
### Data Model Changes (No SQL delta required)
The `WorkflowInstance` table already exists with `entity_type VARCHAR`, `entity_id VARCHAR`. The only change is:
- **Add** `getInstanceByEntity(entityType, entityId)` to `WorkflowEngineService` (TypeORM query, no schema change).
### API Contract
#### `GET /transmittals/:uuid`
**Response addition** (existing fields unchanged):
```json
{
"data": {
"publicId": "...",
"workflowInstanceId": "019abc...",
"workflowState": "IN_REVIEW",
"availableActions": ["APPROVE", "REJECT"],
...existing fields...
}
}
```
#### `GET /circulation/:uuid`
**Response addition**:
```json
{
"data": {
"publicId": "...",
"workflowInstanceId": "019def...",
"workflowState": "OPEN",
"availableActions": [],
"routings": [
{
"id": 1,
"deadline": "2026-04-20T00:00:00.000Z",
"isOverdue": true,
...
}
],
...
}
}
```
#### `POST /transmittals/:uuid/submit` (NEW)
**Request**:
```json
{ "templateId": "optional-workflow-template-uuid" }
```
**Response**: `{ "instanceId": "...", "currentState": "IN_REVIEW" }`
**Error (EC-RFA-004)**: `422` `{ "message": "RFA [doc-no] ยังอยู่ใน Draft กรุณา Submit ก่อน" }`
#### `PATCH /circulation/:id/routing/:routingId/reassign` (NEW)
**Request**: `{ "newAssigneeId": "uuid" }`
**Guards**: `@RequirePermission('circulation.manage')`
#### `POST /circulation/:id/force-close` (NEW)
**Request**: `{ "reason": "mandatory string" }`
**Guards**: `@RequirePermission('circulation.manage')`
**Response**: `{ "success": true }`
### Frontend Architecture
#### `useTransmittal(uuid)` hook
```ts
useQuery<Transmittal>({
queryKey: ['transmittal', uuid],
queryFn: () => transmittalService.getByUuid(uuid),
enabled: !!uuid,
staleTime: 60_000,
})
```
Returns: `{ transmittal, isLoading, error }` — replaces inline `useQuery` in detail page.
#### `useCirculation(uuid)` hook
```ts
useQuery<Circulation>({
queryKey: ['circulation', uuid],
queryFn: () => circulationService.getByUuid(uuid),
enabled: !!uuid,
staleTime: 60_000,
})
```
#### `useWorkflowHistory(instanceId)` — already exists, use directly in pages.
#### Overdue Badge logic (frontend-only)
```ts
function isOverdue(deadline?: string): boolean {
if (!deadline) return false;
const deadlinePlusOne = new Date(deadline);
deadlinePlusOne.setDate(deadlinePlusOne.getDate() + 1);
return new Date() > deadlinePlusOne;
}
```
---
## Phase 2: Task Breakdown
### Critical (Backend)
| Task | File | Description |
|------|------|-------------|
| B1 | `workflow-engine.service.ts` | Add `getInstanceByEntity(entityType, entityId)` returning `{ id, currentState }` or null |
| B2 | `transmittal.service.ts` | `findOneByUuid`: lookup workflow instance, add to response |
| B3 | `transmittal.service.ts` | `findAll`: add `purpose` filter |
| B4 | `transmittal.service.ts` | Add `submit(uuid, user)` with EC-RFA-004 validation |
| B5 | `transmittal.controller.ts` | Add `POST /:uuid/submit` endpoint with guard |
| B6 | `circulation.service.ts` | `findOneByUuid`: lookup workflow instance, compute overdue |
| B7 | `circulation.service.ts` | Add `reassignRouting(routingId, newAssigneeUuid, user)` |
| B8 | `circulation.service.ts` | Add `forceClose(uuid, reason, user)` with EC-CIRC-002 |
| B9 | `circulation.controller.ts` | Add PATCH `/routing/:id/reassign` + POST `/force-close` |
### Important (Frontend)
| Task | File | Description |
|------|------|-------------|
| F1 | `types/transmittal.ts` | Add `workflowInstanceId?`, `workflowState?`, `availableActions?` |
| F2 | `types/circulation.ts` | Add `workflowInstanceId?`, `workflowState?`, deadline to routing |
| F3 | `hooks/use-transmittal.ts` | New `useTransmittal(uuid)` hook |
| F4 | `hooks/use-circulation.ts` | Add `useCirculation(uuid)` hook |
| F5 | `transmittals/[uuid]/page.tsx` | Wire banner + lifecycle with real data |
| F6 | `circulation/[uuid]/page.tsx` | Wire banner + lifecycle + overdue badge |
| F7 | `transmittals/page.tsx` | Verify list page works, add purpose filter |
### Guidelines (i18n + Tests)
| Task | File | Description |
|------|------|-------------|
| I1 | `public/locales/th/*.json` | Add missing transmittal/circulation workflow keys |
| T1 | `transmittal.service.spec.ts` | Unit test EC-RFA-004 submit validation |
| T2 | `circulation.service.spec.ts` | Unit tests EC-CIRC-001/002/003 handlers |
---
## Phase 3: Verification Plan
### Backend
```bash
# TypeScript compile
cd backend && pnpm tsc --noEmit
# Unit tests (target files)
cd backend && pnpm jest --testPathPattern="transmittal|circulation"
# Manual curl — Transmittal detail with workflowInstanceId
curl http://localhost:3001/api/transmittals/{uuid} | jq '.data.workflowInstanceId'
# Manual curl — Circulation detail with workflowInstanceId
curl http://localhost:3001/api/circulation/{uuid} | jq '.data.workflowInstanceId'
# EC-RFA-004 — submit transmittal with DRAFT item (expect 422)
curl -X POST http://localhost:3001/api/transmittals/{uuid}/submit
# Force Close test
curl -X POST http://localhost:3001/api/circulation/{uuid}/force-close \
-H "Content-Type: application/json" \
-d '{"reason":"Test force close"}'
```
### Frontend
```bash
# TypeScript compile (zero errors)
cd frontend && pnpm tsc --noEmit
# Lint (zero warnings)
cd frontend && pnpm lint
# Vitest unit tests
cd frontend && pnpm test
# Manual: Navigate to /transmittals/{uuid}
# → IntegratedBanner shows doc number + status badge
# → Workflow tab shows history timeline
# → workflowState shown in banner (if instance exists)
# Manual: Navigate to /circulation/{uuid}
# → Overdue badge on past-deadline routings
# → Workflow tab shows history
```
### Security Verification
- [ ] Reassign endpoint: 403 if user is not Document Control or above
- [ ] Force Close endpoint: 403 if user is not Document Control or above
- [ ] Workflow transition: `Idempotency-Key` header enforced
- [ ] No `parseInt` on any UUID in new code
- [ ] `workflowInstanceId` is string (not number) in all responses
---
## Dependencies Map
```
ADR-001 (Unified Workflow Engine)
└→ WorkflowEngineService.getInstanceByEntity() [B1]
├→ TransmittalService.findOneByUuid() [B2]
└→ CirculationService.findOneByUuid() [B6]
├→ types/transmittal.ts [F1]
├→ types/circulation.ts [F2]
├→ useTransmittal() [F3]
├→ useCirculation() [F4]
├→ transmittals/[uuid]/page.tsx [F5]
└→ circulation/[uuid]/page.tsx [F6]
ADR-016 (Security/RBAC)
└→ CirculationService.reassignRouting() [B7]
└→ CirculationService.forceClose() [B8]
ADR-021 (IntegratedBanner/WorkflowLifecycle components)
└→ Already implemented — just need instanceId prop wired [F5, F6]
```
---
## Risk Register
| Risk | Probability | Impact | Mitigation |
|------|------------|--------|-----------|
| `entity_type` mismatch — Transmittal uses wrong entityType in WF instance | Medium | High | Check `workflowEngine.createInstance()` call in `transmittal.service.ts`; use same entityType string consistently |
| Circulation has no WF instance (workflow never started) | High | Medium | `getInstanceByEntity()` returns null → `workflowInstanceId` = undefined → banner shows status only, no actions |
| Transmittal entity has no `publicId` own column | Medium | Low | Already handled: `publicId` maps from `correspondence.publicId` in `findAll()` |
| EC-CIRC-003 timezone issues (deadline at 23:59:59) | Low | Medium | Use UTC comparison; test with mocked date |
+183
View File
@@ -0,0 +1,183 @@
# Feature Specification: Transmittals + Circulation Complete Integration (v1.8.7 Post-ADR-021)
**Feature Branch**: `001-transmittals-circulation`
**Version**: 1.8.7
**Created**: 2026-04-12
**Status**: Draft
**Depends On**: ADR-021 (Integrated Workflow Context & Step-specific Attachments — in `feat/adr-021-integrated-workflow-context`)
**Input**: "Transmittals + Circulation (v1.8.7) Post-ADR-021"
---
## Context
ADR-021 introduced the shared `IntegratedBanner`, `WorkflowLifecycle`, and `use-workflow-action` components, and wired them fully for RFA and Correspondence. Both the **Transmittal** and **Circulation** detail pages already import these components but pass no workflow data — they are currently stub wired.
This feature delivers the **complete, production-ready integration** of both modules with the ADR-021 Workflow Engine, fixes known type violations (ADR-019), implements all pending edge cases (EC-RFA-004, EC-CIRC-001003), and adds missing hooks and list-page functionality.
---
## User Scenarios & Testing _(mandatory)_
### User Story 1 — Transmittal Workflow-Wired Detail Page (Priority: P1) 🎯 MVP
A Document Control officer opens an existing Transmittal and immediately sees the document number, subject, workflow state, and available action buttons in the `IntegratedBanner`. The Workflow tab shows the full vertical timeline with each step's actor, date, comment, and evidence files.
**Why this priority**: The detail page is the primary touchpoint for reviewing/approving a Transmittal. Without live workflow data, reviewers cannot take action — this is a blocking gap.
**Independent Test**: Navigate to `/transmittals/{uuid}`. Verify: (1) `IntegratedBanner` shows real doc number, status badge, and action buttons (when user is the handler); (2) Workflow tab renders `WorkflowLifecycle` with at least the creation step; (3) all `pnpm tsc --noEmit` checks pass.
**Acceptance Scenarios**:
1. **Given** a submitted Transmittal with an active workflow instance, **When** a Document Control user opens its detail page, **Then** the `IntegratedBanner` displays the correct doc number, status, `workflowState`, and the available action buttons (e.g., APPROVE, REJECT).
2. **Given** a Transmittal where the current user is not the assigned handler, **When** they open the detail page, **Then** no action buttons are shown in the banner.
3. **Given** a Transmittal detail page, **When** the user clicks the Workflow tab, **Then** a vertical timeline displays all history steps with actor, date, and comment. The most recent step is highlighted.
---
### User Story 2 — Circulation Workflow-Wired Detail Page (Priority: P1) 🎯 MVP
A Document Control officer opens a Circulation Sheet and sees the circulation number, linked Correspondence, all assignees with their status, a deadline (with Overdue badge if past), and the full workflow timeline — all in one screen. Assignees can mark their task complete via the `IntegratedBanner` actions.
**Why this priority**: Circulation drives internal task tracking. Without live data wiring the page is read-only and useless for task management.
**Independent Test**: Navigate to `/circulation/{uuid}`. Verify: (1) `IntegratedBanner` displays `circulationNo`, `statusCode`; (2) Assignees card shows all routings with status; (3) Overdue badge appears when `deadline_date` is past; (4) Workflow tab shows history.
**Acceptance Scenarios**:
1. **Given** an OPEN Circulation with a past deadline, **When** a user opens the detail page, **Then** an Overdue badge is displayed and the deadline date is highlighted in red.
2. **Given** a Circulation with multiple assignees, **When** an assignee marks their task complete, **Then** their routing status updates to COMPLETED and the page refreshes.
3. **Given** a Circulation where all Main/Action assignees are COMPLETED, **When** the Document Control user views the page, **Then** a "Close Circulation" action is available.
---
### User Story 3 — Transmittal List Page with Search & Filter (Priority: P1)
A Document Control officer browses all Transmittals for a project, filters by purpose (FOR_APPROVAL, FOR_REVIEW, etc.), and searches by document number or subject.
**Why this priority**: The list page is the entry point for the module. Without working filters it cannot be used in production.
**Independent Test**: Navigate to `/transmittals`. Verify: paginated list loads; purpose filter updates results; search input filters by doc number/subject; clicking a row navigates to the detail page.
**Acceptance Scenarios**:
1. **Given** the Transmittals list page, **When** a user selects purpose "FOR_APPROVAL", **Then** only Transmittals with that purpose are shown.
2. **Given** the Transmittals list page, **When** a user types in the search box, **Then** results are filtered to matching document numbers or subjects within 500ms.
3. **Given** no Transmittals in the project, **When** the list page loads, **Then** an "empty state" message is shown.
---
### User Story 4 — Transmittal EC-RFA-004 Submit Validation (Priority: P2)
A Document Control officer tries to submit a Transmittal whose items include a DRAFT correspondence. The system blocks the submission with a clear, actionable error message.
**Why this priority**: EC-RFA-004 is a business integrity rule. Submitting a Transmittal with unsubmitted items violates the document lifecycle and must be blocked.
**Independent Test**: Create a Transmittal with one DRAFT item. Attempt to submit. Verify: 422 response with message "RFA [doc number] ยังอยู่ใน Draft กรุณา Submit ก่อน"; item is highlighted in the UI.
**Acceptance Scenarios**:
1. **Given** a Transmittal containing a DRAFT correspondence, **When** a user submits the Transmittal, **Then** the system returns an error identifying which item is in DRAFT status.
2. **Given** all Transmittal items are in SUBMITTED/APPROVED status, **When** a user submits the Transmittal, **Then** the submission succeeds and the status updates.
---
### User Story 5 — Circulation Edge Cases: Re-assign & Force Close (Priority: P2)
Document Control can re-assign a Circulation when an assignee is deactivated (EC-CIRC-001), and can force-close a Circulation with a mandatory reason when some assignees have not responded (EC-CIRC-002).
**Why this priority**: Without these controls, Circulations can get permanently stuck, blocking downstream work.
**Independent Test**: Deactivate an assignee in an OPEN Circulation. Verify: Document Control sees a "Re-assign" button for that routing. Force-close a Circulation with partial responses; verify reason is recorded in audit log.
**Acceptance Scenarios**:
1. **Given** an OPEN Circulation where one assignee has been deactivated, **When** Document Control opens the page, **Then** a "Re-assign" action is available for that assignee's routing.
2. **Given** an OPEN Circulation where some assignees have not responded, **When** Document Control performs Force Close with a reason, **Then** the Circulation status changes to CANCELLED, all pending routings are force-closed, and the reason is logged.
---
### Edge Cases
- **EC-RFA-004**: Transmittal with DRAFT items cannot be submitted → `422 Unprocessable Entity` with item identification.
- **EC-CIRC-001**: Assignee deactivated before responding → Document Control can re-assign.
- **EC-CIRC-002**: Multi-assignee, some not responded → Document Control can Force Close with mandatory reason.
- **EC-CIRC-003**: Deadline = today `23:59:59`; Overdue Badge the following day at `00:00`.
- **EC-CORR-001**: Cancelling a Correspondence with open Circulations → all Circulations force-closed + audit log.
- Transmittal `workflowInstanceId` is `null` when no workflow has been started (Draft state) → banner shows status only, no action buttons.
- Circulation data is scoped to the user's organization — users from other organizations must receive a 403 response.
- Duplicate `Idempotency-Key` on workflow transition → return cached response, no re-processing.
---
## Requirements _(mandatory)_
### Functional Requirements
**Transmittal Module:**
- **FR-T01**: The Transmittal detail page MUST display `workflowState`, `availableActions`, and action buttons via `IntegratedBanner` using the live workflow instance.
- **FR-T02**: The Transmittal detail page Workflow tab MUST render `WorkflowLifecycle` wired to the workflow history of the Transmittal's workflow instance.
- **FR-T03**: The Transmittal list page MUST support pagination, search by document number/subject, and filter by `purpose`.
- **FR-T04**: The Transmittal `Transmittal` frontend type MUST include `workflowInstanceId?: string` and `workflowState?: string` fields (ADR-019: string UUID only).
- **FR-T05**: The `transmittalService.getByUuid()` response MUST include `workflowInstanceId` from the backend.
- **FR-T06**: A dedicated `useTransmittal(uuid)` TanStack Query hook MUST be created for the detail page.
- **FR-T07**: Submitting a Transmittal with DRAFT items MUST return a `422` error identifying the offending item (EC-RFA-004).
**Circulation Module:**
- **FR-C01**: The Circulation detail page MUST display `workflowState`, `availableActions`, and action buttons via `IntegratedBanner` using the live workflow instance.
- **FR-C02**: The Circulation detail page Workflow tab MUST render `WorkflowLifecycle` wired to the workflow history.
- **FR-C03**: The Circulation detail page assignee section MUST display deadline per assignee type and an Overdue badge when `NOW() > deadline_date + 1 day` (EC-CIRC-003).
- **FR-C04**: The Circulation `Circulation` frontend type MUST include `workflowInstanceId?: string` and `workflowState?: string`.
- **FR-C05**: The `circulationService.getByUuid()` response MUST include `workflowInstanceId` from the backend.
- **FR-C06**: A dedicated `useCirculation(uuid)` TanStack Query hook MUST be created for the detail page.
- **FR-C07**: Document Control MUST be able to re-assign a routing when the assignee is deactivated (EC-CIRC-001).
- **FR-C08**: Document Control MUST be able to Force Close a Circulation with a mandatory reason; all pending routings are force-closed and the reason is logged in the audit trail (EC-CIRC-002).
**Cross-Cutting:**
- **FR-X01**: All new API calls MUST use `publicId` (UUIDv7 string) — no `parseInt` on UUID values (ADR-019).
- **FR-X02**: All new frontend types MUST NOT use `any` — strict TypeScript required.
- **FR-X03**: All backend responses for these modules MUST include `workflowInstanceId?: string` in the data shape.
- **FR-X04**: All new user-facing strings MUST use i18n keys — no hardcoded Thai/English text in JSX.
### Key Entities
- **Transmittal**: Extends Correspondence (`type_code = 'TRANSMITTAL'`). Has `purpose`, `remarks`, and a list of `transmittal_items`. Has one `WorkflowInstance` via the Unified Workflow Engine.
- **TransmittalItem**: Links a Transmittal to the document it carries (`correspondences` M:N). Has `quantity`, `itemType`, `remarks`.
- **Circulation**: Internal task-tracking document linked 1:1 to a Correspondence per organization. Has `statusCode`, `deadline`, and a list of `routings` (assignees with type: Main/Action/Information).
- **CirculationRouting**: A single assignee entry in a Circulation. Has `assigneeType`, `status`, `deadline`, `comments`.
---
## Assumptions
- ADR-021 backend is fully deployed — `workflow_history_id` column exists on `attachments`, `workflowInstanceId` is exposed from the Workflow Engine module.
- The backend `transmittal` module already has a `workflowInstance` relation or can join it via the Correspondence FK chain.
- The backend `circulation` module already has a `workflowInstance` relation available.
- The Unified Workflow Engine (`WorkflowEngineService`) is the single source of truth for state and transitions — Transmittal and Circulation statuses are NOT independently maintained once a workflow is started.
---
## Success Criteria _(mandatory)_
### Measurable Outcomes
- **SC-001**: Both Transmittal and Circulation detail pages display live workflow state and action buttons in under 1 second after page load (TanStack Query with staleTime 60s).
- **SC-002**: Submitting a Transmittal with a DRAFT item is rejected 100% of the time with a user-readable error message identifying the offending document.
- **SC-003**: Force-closing a Circulation with partial responses succeeds in a single action with the mandatory reason captured in the audit log every time.
- **SC-004**: All new TypeScript code passes `pnpm tsc --noEmit` with zero errors and `pnpm lint` with zero warnings.
- **SC-005**: No hardcoded Thai or English text in any new JSX component — verified by grep.
- **SC-006**: Unit test coverage ≥ 80% on new business logic (EC-RFA-004 validation, EC-CIRC-001/002/003 handlers).
- **SC-007**: Overdue Badge appears correctly when `NOW() > deadline_date + 1 day` — verified by unit test with mocked date.
---
## Clarifications
### Session 2026-04-12
- Q: Should the Transmittal "Submit" action go through the Workflow Engine transition (ADR-021 pattern), or does it remain a direct status update on the `correspondences` table? → A: Submit uses the Workflow Engine transition (`action: 'SUBMIT'`), consistent with ADR-001 Unified Workflow Engine for all document types. EC-RFA-004 validation fires as a pre-transition check in the service.
- Q: Should Circulation `routings` "Complete" action be a Workflow Engine transition or a direct routing status update? → A: Direct routing status update (not a full Workflow Engine transition) because Circulation workflow state is controlled at the Circulation level, not per-routing. The overall Circulation transitions (OPEN → IN_REVIEW → COMPLETED) go through the Workflow Engine.
- Q: For `workflowInstanceId` in the Transmittal/Circulation API response — should it be added to the existing response shape or is a dedicated `/workflow` sub-resource needed? → A: Add `workflowInstanceId` directly to the existing `findOneByUuid` response shape (additive, backward-compatible). Consistent with how RFA/Correspondence expose it.
+182
View File
@@ -0,0 +1,182 @@
# Tasks: Transmittals + Circulation Complete Integration (v1.8.7 Post-ADR-021)
**Branch**: `001-transmittals-circulation` | **Total Tasks**: 18 | **Phase**: Implementation
---
## Phase 1 — Backend Foundation (Critical — blocks all frontend work)
### B1 — WorkflowEngineService: Add `getInstanceByEntity()`
- **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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
### B9 — CirculationController: Add reassign + force-close endpoints
- **File**: `backend/src/modules/circulation/circulation.controller.ts`
- **Action**:
- `PATCH /:uuid/routing/:routingId/reassign``@RequirePermission('circulation.manage')`
- `POST /:uuid/force-close``@RequirePermission('circulation.manage')`
- **Dependencies**: B7, B8
- **Status**: [ ]
---
## Phase 2 — Frontend Types & Hooks (Important — depends on Phase 1)
### F1 — Update `types/transmittal.ts`
- **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**: [ ]
### 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**: [ ]
### 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**: [ ]
### 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**: [ ]
---
## Phase 3 — Frontend Detail Pages (Important — depends on Phase 2 + Phase 1 deployed)
### F5 — Wire Transmittal detail page
- **File**: `frontend/app/(dashboard)/transmittals/[uuid]/page.tsx`
- **Action**:
- Replace inline `useQuery` with `useTransmittal(uuid)`
- Add `useWorkflowHistory(transmittal?.workflowInstanceId)`
- Add `const [pendingAttachmentIds, setPendingAttachmentIds] = useState<string[]>([])`
- Pass `instanceId`, `workflowState`, `availableActions`, `pendingAttachmentIds` to `IntegratedBanner`
- Pass `history`, `currentState`, `isLoading`, `error`, `onAttachmentsChange` to `WorkflowLifecycle` in Workflow tab
- **Dependencies**: F3, F1
- **Status**: [ ]
### F6 — Wire Circulation detail page
- **File**: `frontend/app/(dashboard)/circulation/[uuid]/page.tsx`
- **Action**:
- Replace inline `useQuery` with `useCirculation(uuid)`
- Add `useWorkflowHistory(circulation?.workflowInstanceId)`
- Add `isOverdue(deadline?)` helper function
- Wire `IntegratedBanner` with `instanceId`, `workflowState`, `availableActions`
- Wire `WorkflowLifecycle` with history in Workflow tab
- Add Overdue badge to routing rows where `isOverdue(routing.deadline)` is true
- Replace hardcoded "Complete" button with proper workflow action
- **Dependencies**: F4, F2
- **Status**: [ ]
---
## Phase 4 — List Page & i18n (Guidelines)
### F7 — Transmittal list page: add purpose filter
- **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**: [ ]
### 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**: [ ]
---
## Phase 5 — Tests (Tier 2 — required before merge)
### T1 — Transmittal service EC-RFA-004 unit test
- **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**: [ ]
### 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**: [ ]
---
## Execution Order
```
B1 (parallel: B3, F1, F2)
→ B2, B4 (parallel), B6 (parallel)
→ B5 → T1
→ B7, B8 (parallel)
→ B9 → T2
→ F3, F4 (parallel after F1, F2)
→ F5, F6 (parallel after F3, F4)
→ F7, I1 (polish)
```
---
## Commit Message Convention
```
feat(transmittal): expose workflowInstanceId in findOneByUuid response
feat(circulation): expose workflowInstanceId + overdue in findOneByUuid
feat(circulation): add reassignRouting EC-CIRC-001 handler
feat(circulation): add forceClose EC-CIRC-002 handler
feat(transmittal): add submit endpoint with EC-RFA-004 validation
feat(frontend): wire WorkflowLifecycle in transmittal detail page
feat(frontend): wire WorkflowLifecycle + overdue badge in circulation detail
test(transmittal): EC-RFA-004 submit validation unit tests
test(circulation): EC-CIRC-001/002/003 edge case unit tests
```
@@ -1371,6 +1371,7 @@ erDiagram
| expires_at | DATETIME | NULL | เวลาหมดอายุของไฟล์ Temp (เพื่อให้ Cron Job ลบออก) |
| checksum | VARCHAR(64) | NULL | SHA-256 Checksum สำหรับ Verify File Integrity [Req 3.9.3] |
| reference_date | DATE | NULL | Date used for folder structure (e.g. Issue Date) to prevent broken paths |
| workflow_history_id | VARCHAR(36) | NULL, FK | **[ADR-021]** อ้างอิง workflow_histories.publicId — NULL = ไฟล์แนบหลักของเอกสาร; NOT NULL = ไฟล์หลักฐานประจำ Workflow Step |
**Indexes**:
@@ -1382,10 +1383,11 @@ erDiagram
- UNIQUE INDEX idx_attachments_uuid (uuid)
- INDEX (created_at)
- INDEX (reference_date)
- INDEX (workflow_history_id)
**Relationships**:
- Parent: users
- Parent: users, workflow_histories (via workflow_history_id)
- Referenced by: correspondence_revision_attachments, circulation_attachments, shop_drawing_revision_attachments, contract_drawing_attachments
**Business Rules**:
@@ -1395,6 +1397,10 @@ erDiagram
- File path points to QNAP NAS storage
- Original filename preserved for download
- One file record can be linked to multiple documents
- **[ADR-021]** `workflow_history_id = NULL` → Main Document attachment (linked via junction tables)
- **[ADR-021]** `workflow_history_id IS NOT NULL` → Step-evidence attachment — linked exclusively to a single workflow transition history record (Approve/Reject/Return evidence)
- Step-evidence attachments are committed (is_temporary = false) during `processTransition()` in the same transaction as the history record
- Cleanup jobs MUST NOT delete attachments where `workflow_history_id IS NOT NULL`
---
@@ -0,0 +1,25 @@
-- ============================================================
-- 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);
-- ============================================================
-- Rollback:
-- ALTER TABLE attachments DROP FOREIGN KEY fk_attachments_workflow_history;
-- ALTER TABLE attachments DROP COLUMN workflow_history_id;
-- ============================================================
@@ -0,0 +1,13 @@
-- Delta 05: Add deadline_date to circulations (v1.8.7 — EC-CIRC-003)
-- Purpose: เพิ่มคอลัมน์ deadline_date ที่ตาราง circulations
-- เพื่อรองรับ EC-CIRC-003 (Overdue Badge) และการตั้งค่ากำหนดเวลา
-- Applied: เพิ่มทีหลัง Schema v1.8.0
-- Author: NAP-DMS v1.8.7
ALTER TABLE circulations
ADD COLUMN deadline_date DATE NULL
COMMENT 'วันครบกำหนดส่งงาน (nullable — ถ้า NULL = ไม่มีกำหนด)'
AFTER closed_at;
-- Index สำหรับ query Overdue Circulations ที่ Dashboard
CREATE INDEX idx_circulations_deadline ON circulations (deadline_date);
@@ -781,6 +781,7 @@ CREATE TABLE circulations (
created_by_user_id INT NOT NULL COMMENT 'ID ของผู้สร้างใบเวียน',
submitted_at TIMESTAMP NULL COMMENT 'วันที่ส่งใบเวียน',
closed_at TIMESTAMP NULL COMMENT 'วันที่ปิดใบเวียน',
deadline_date DATE NULL COMMENT 'วันที่กำหนดส่งมอบ',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT 'วันที่สร้าง',
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'วันที่แก้ไขล่าสุด',
FOREIGN KEY (correspondence_id) REFERENCES correspondences (id),
@@ -868,9 +869,13 @@ CREATE TABLE attachments (
expires_at DATETIME NULL COMMENT 'เวลาหมดอายุของไฟล์ Temp',
CHECKSUM VARCHAR(64) NULL COMMENT 'SHA-256 Checksum',
reference_date DATE NULL COMMENT 'Date used for folder structure (e.g. Issue Date) to prevent broken paths',
workflow_history_id CHAR(36) NULL COMMENT 'FK to workflow_histories.id for step-specific attachments (ADR-021). NULL = main document',
FOREIGN KEY (uploaded_by_user_id) REFERENCES users (user_id) ON DELETE CASCADE,
INDEX idx_attachments_reference_date (reference_date),
UNIQUE INDEX idx_attachments_uuid (uuid)
FOREIGN KEY (workflow_history_id) REFERENCES workflow_histories (id) ON DELETE
SET NULL ON UPDATE CASCADE,
INDEX idx_attachments_reference_date (reference_date),
INDEX idx_att_wfhist_created (workflow_history_id, created_at),
UNIQUE INDEX idx_attachments_uuid (uuid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = 'ตาราง "กลาง" เก็บไฟล์แนบทั้งหมดของระบบ';
-- ตารางเชื่อม correspondence_revisions กับ attachments (M:N)
@@ -49,6 +49,9 @@ CREATE INDEX idx_tags_name ON tags (tag_name);
CREATE INDEX idx_tags_created_at ON tags (created_at);
-- Index for circulations deadline_date (EC-CIRC-003 Overdue Badge)
CREATE INDEX idx_circulations_deadline ON circulations (deadline_date);
-- Indexes for correspondence_tags
CREATE INDEX idx_correspondence_tags_correspondence ON correspondence_tags (correspondence_id);
@@ -0,0 +1,224 @@
# ADR-021: Integrated Workflow Context & Step-specific Attachments
## 1. ข้อมูลทั่วไป (General Information)
- **Status:** Proposed
- **Version:** 1.8.6
- **Date:** 2026-04-12
- **Author:** Senior Full Stack Developer (Windsurf AI)
- **Reference:** ADR-001 (Workflow Engine), ADR-002 (Redlock), ADR-016 (Security)
---
## Clarifications
### Session 2026-04-12
- **Q:** What are the file size and attachment count limits per workflow step? → **A:** No explicit limit (controlled by infrastructure only)
- **Q:** What are the specific values and storage format for the "Priority" field in the Integrated Banner? → **A:** Enum "URGENT", "HIGH", "MEDIUM", "LOW" — 4-tier system with visual indicators
- **Q:** How should the system handle virus/malware detection during step-specific file upload? → **A:** Block upload immediately, delete temp file, show error "File rejected" to user
- **Q:** What is the cache TTL for Workflow History data to reduce join query overhead? → **A:** 1 hour — balanced cache duration for workflow history data
- **Q:** Who is authorized to upload step-specific attachments during a workflow transition? → **A:** Only assigned handler can upload; superadmin and organization admin can upload on behalf (impersonation)
---
## 2. บริบทและความสำคัญ (Context & Problem Statement)
ในเวอร์ชันปัจจุบัน (v1.8.5) ระบบ DMS ประสบปัญหาด้าน User Experience และ Data Traceability ใน 2 จุดหลัก:
1. **Context Fragmentation:** ข้อมูลเอกสารและหน้าจอควบคุม Workflow แยกออกจากกัน ทำให้ Reviewer/Approver ต้องสลับหน้าจอไปมาเพื่อตรวจสอบข้อมูลก่อนตัดสินใจ
2. **Generic Attachments:** ไฟล์แนบถูกเก็บรวมไว้ที่ระดับตัวเอกสารหลัก (Root Document) ทำให้ไม่สามารถระบุได้ว่าไฟล์ใดถูกเพิ่มเข้ามาเพื่อประกอบการตัดสินใจในขั้นตอน (Step) ใดเป็นพิเศษ
---
## 3. การตัดสินใจเชิงสถาปัตยกรรม (Architecture Decision)
เราจะเปลี่ยนไปใช้แนวทาง **Integrated Contextual Workflow** โดยมีรายละเอียดดังนี้:
### 3.1 Status Banner Integration
- ยุบรวม Metadata ที่สำคัญของเอกสาร (Doc No, Subject, Initiator, Priority) ไว้ใน Header เดียวกันกับส่วนแสดงสถานะ (Status) และปุ่มดำเนินการ (Actions)
- เพื่อให้ผู้ใช้งานเห็น "บริบททั้งหมด" ในแถวสายตาเดียว (Single Row Visibility)
### 3.2 Workflow Lifecycle Visualization
- แสดงขั้นตอนทั้งหมด (Full Path) ในรูปแบบ Vertical Timeline ภายใน Tab
- **Active Highlighting:** ขั้นตอนปัจจุบันต้องใช้สีเด่น (Indigo) และ Animation (Pulse) เพื่อระบุตำแหน่งงาน
- **Completed/Pending States:** ขั้นตอนที่ผ่านมาแล้วและในอนาคตต้องมี Visual State ที่แตกต่างกันอย่างชัดเจน
### 3.3 Step-specific Attachments & Preview
- **Linked Data:** ปรับปรุง Schema ให้ไฟล์แนบสามารถเชื่อมโยงกับ `workflow_history` ได้
- **Contextual Upload:** อนุญาตให้อัปโหลดไฟล์ได้ "เฉพาะ" ในขั้นตอนที่กำลังดำเนินการอยู่ (Active Step) เท่านั้น
- **Unified Preview:** สร้างระบบ Preview Modal กลางที่เรียกดูไฟล์ได้จากทุกจุดโดยไม่ต้องเปลี่ยนหน้า
---
## 4. รายละเอียดความต้องการ (Functional Requirements)
| ID | Feature | Description |
| :--- | :--- | :--- |
| REQ-01 | **Integrated Banner** | แสดง ID, Status, Priority (`URGENT`/`HIGH`/`MEDIUM`/`LOW` พร้อม visual indicators) และปุ่ม Approve/Reject ไว้ในแถบด้านบนสุด |
| REQ-02 | **Step Detail View** | ใน Tab Workflow Engine ต้องแสดงรายละเอียด Role, Handler และ Description ของทุกขั้นตอน |
| REQ-03 | **Active Step Color** | ขั้นตอนปัจจุบันใช้สี Indigo (#6366f1) พร้อม Pulse effect |
| REQ-04 | **Step-safe Upload** | รองรับการลากวางไฟล์ (Drag & Drop) เพื่อแนบหลักฐานประจำขั้นตอนนั้นๆ |
| REQ-05 | **Internal Preview** | คลิกดูไฟล์ PDF/Images ได้ทันทีผ่าน Modal ภายในระบบ |
| REQ-06 | **i18n Support** | ทุก UI text ต้องใช้ i18n keys ตาม `05-08-i18n-guidelines.md` |
---
## 5. ข้อกำหนดทางเทคนิค (Technical Requirements - Tier 1 Critical)
1. **Database Consistency:** ต้องเพิ่ม `workflow_history_id` ในตาราง `attachments` โดยรักษาค่าเป็น Nullable สำหรับไฟล์หลัก (Main Docs)
2. **Concurrency Control:**
- **Transition Lock:** ใช้ Redis Redlock เมื่อมีการเปลี่ยนสถานะพร้อมอัปโหลดไฟล์ (Two-Phase: Lock → Upload + Transition → Unlock)
- **File Upload:** ใช้ Temp Storage ก่อน (ADR-016 Two-Phase Upload) แล้วย้ายไป Permanent หลัง Transition สำเร็จ
3. **Security Audit:** ทุกไฟล์แนบราย Step ต้องผ่านการสแกน **ClamAV** และบันทึกข้อมูล Who/When ลงใน Audit Log (ADR-016)
4. **Identifier Strategy:** อ้างอิงไฟล์ผ่าน **UUIDv7** (publicId) เท่านั้น ห้ามใช้ ID ที่เป็น Integer ใน API (ADR-019)
5. **Database Indexing:** ต้องสร้าง Index บน `(workflow_history_id, created_at)` สำหรับตาราง `attachments` เพื่อ optimize การดึงไฟล์แนบตาม Step
6. **i18n Support:** ทุก UI text ต้องใช้ i18n keys ตาม `05-08-i18n-guidelines.md`
7. **File Size Limits:** ไม่กำหนด Limit ที่ Application Layer — ควบคุมโดย Infrastructure (Reverse Proxy / Storage Config) เท่านั้น
8. **Idempotency Control:** ทุกการอัปโหลดไฟล์พร้อม Transition ต้องมีการตรวจสอบ `Idempotency-Key` header (per .windsurfrules Security Rule #1)
9. **Async Event Processing:** Notifications และ Events จาก workflow transitions ต้องใช้ **BullMQ** queue (ADR-008) — ห้าม inline ใน Service
---
## 5.1 Idempotency & Duplicate Prevention
| Mechanism | Implementation |
|-----------|----------------|
| **Idempotency-Key** | ทุก `POST/PUT` สำหรับ upload + transition ต้องส่ง header `Idempotency-Key` (UUID) |
| **Redis Store** | เก็บ key mapping `(idempotency_key, user_id)` → response (TTL: 24 ชั่วโมง) |
| **Duplicate Detection** | หาก key ซ้ำ → return cached response (201/200) ไม่ทำซ้ำ |
---
## 5.2 กรณีขอบเขตและการจัดการข้อผิดพลาด (Edge Cases & Error Handling)
| Scenario | Behavior |
|----------|----------|
| **ClamAV ตรวจพบไวรัส/มัลแวร์** | Block upload ทันที, ลบ temp file, แสดง error "File rejected" แก่ user |
| **Upload ไฟล์ระหว่าง Transition ล้มเหลว** | Rollback transaction ทั้งหมด, ลบ temp files, คงสถานะ workflow เดิม |
| **ไฟล์ถูกลบจาก Storage หลัง Attach** | แสดง "File unavailable" ใน UI, บันทึก metadata ไว้ตามเดิม |
| **Concurrent Transition พร้อม Upload** | Redis Redlock จัดการ queue, อนุญาตเพียง 1 transition พร้อมกัน |
| **Invalid File Type** | Reject ตั้งแต่ client-side (whitelist: PDF, DOCX, XLSX, DWG, ZIP) |
| **Unauthorized Upload Attempt** | ตรวจสอบสิทธิ์: เฉพาะ assigned handler, superadmin, หรือ org admin เท่านั้น |
| **Duplicate Upload (Network Retry)** | ตรวจสอบ `Idempotency-Key` — reject duplicate พร้อม return existing result |
| **Cache Stale Data** | Invalidate Redis Cache ทันทีเมื่อ workflow state เปลี่ยน (TTL override)
---
## 6. รายการไฟล์ที่ต้องอัพเดท (Impacted Files)
### 🔴 Backend Layer (Data & Logic)
- `specs/03-Data-and-Storage/lcbp3-v1.8.0-schema-02-tables.sql`
- *Action:* เพิ่ม FK `workflow_history_id` ในตาราง `attachments`
- `backend/src/common/file-storage/entities/attachment.entity.ts`
- *Action:* เพิ่ม Relation `@ManyToOne(() => WorkflowHistory)`
- `backend/src/modules/workflow-engine/entities/workflow-history.entity.ts`
- *Action:* เพิ่ม Relation `@OneToMany(() => Attachment)`
- `backend/src/modules/workflow-engine/workflow-engine.service.ts`
- *Action:* ปรับปรุง Method `transition()` ให้รองรับการรับไฟล์แนบ (Array of Files)
- `backend/src/modules/workflow-engine/dto/workflow-transition.dto.ts`
- *Action:* เพิ่ม Field สำหรับรับ Metadata ของไฟล์ที่อัปโหลด และ `Idempotency-Key` header
- `backend/src/modules/workflow-engine/guards/workflow-transition.guard.ts` (สร้างใหม่)
- *Action:* Implement **CASL Guard** สำหรับ 4-Level RBAC: Superadmin > Org Admin > Assigned Handler > Read-only
### 🟡 Frontend Layer (UI & Interaction)
- `frontend/app/(dashboard)/rfas/[uuid]/page.tsx` (และโมดูลอื่นที่เกี่ยวข้อง เช่น correspondences, circulations)
- *Action:* Refactor Header เป็น Integrated Banner และเพิ่ม Tab Workflow Lifecycle
- `frontend/components/workflow/workflow-visualizer.tsx` (สร้างใหม่)
- *Action:* พัฒนาการแสดงผล Vertical Timeline พร้อมระบบสี Active/Inactive
- `frontend/components/common/file-preview-modal.tsx` (สร้างใหม่)
- *Action:* พัฒนาคอมโพเนนต์ Modal สำหรับจำลอง PDF Viewer
- `frontend/hooks/use-workflow-action.ts` (สร้างใหม่)
- *Action:* จัดการ State การอัปโหลดไฟล์และการยิง API Transition พร้อมกัน
- `frontend/types/workflow.ts`
- *Action:* อัปเดต Interface ให้รองรับ `attachments` ภายในแต่ละ `WorkflowStep`
---
## 7. 🔍 Impact Analysis
| Component | Level | Impact Description | Required Action |
|-----------|-------|-------------------|-----------------|
| **Backend** | 🔴 High | เพิ่ม FK `workflow_history_id` และ Entity Relations ใหม่ | Update `attachment.entity.ts`, `workflow-history.entity.ts`, Schema SQL |
| **Database** | 🔴 High | Schema migration เพิ่ม column และ index | Run SQL delta, สร้าง Index |
| **Frontend** | 🟡 Medium | Refactor Detail Pages, สร้าง Workflow Visualizer | Update Page Components, สร้างใหม่ 3 ไฟล์ |
| **API** | 🟡 Medium | DTO changes รองรับ file metadata | Update `workflow-transition.dto.ts` |
| **Workflow Engine** | 🟡 Medium | ปรับปรุง `processTransition()` รองรับ attachments | Update `workflow-engine.service.ts` |
---
## 8. Migration Strategy
- **Existing Attachments:** ไฟล์แนบที่มีอยู่แล้วจะมี `workflow_history_id = NULL` (ถือเป็น Main Document attachments)
- **New Attachments:** ไฟล์แนบใหม่ที่อัปโหลดพร้อม Transition จะถูกเชื่อมโยงกับ `workflow_history` ของ Step นั้น
- **Rollback Plan:** หากการ migrate มีปัญหา สามารถตั้ง `workflow_history_id = NULL` กลับได้ทั้งหมด (Nullable FK)
---
## 9. ผลกระทบ (Consequences)
- **Positive:** เพิ่มความน่าเชื่อถือของข้อมูล (Data Integrity) และลดระยะเวลาในการอนุมัติเอกสาร
- **Negative:** เพิ่มความซับซ้อนในการ Join ตารางระหว่างการดึงข้อมูลประวัติและไฟล์แนบ — **Mitigation:** ใช้ Redis Cache สำหรับ Workflow History (TTL: 1 ชั่วโมง) พร้อม **Cache Invalidation** เมื่อ state เปลี่ยน
---
## 9.1 Testing Requirements (Tier 2 - Important)
ตาม .windsurfrules Tier 2 ต้องมี:
- **Business Logic Coverage:** 80%+ (Workflow transition logic, RBAC checks, file upload validation)
- **Backend Overall Coverage:** 70%+
- **Frontend Component Tests:** สำหรับ Integrated Banner, Workflow Visualizer, File Preview Modal
- **E2E Tests:** สำหรับ complete workflow พร้อม file upload
---
## 10. Compliance
เป็นไปตาม:
- [Backend Guidelines](../05-Engineering-Guidelines/05-02-backend-guidelines.md) - NestJS patterns, TypeORM relations
- [Frontend Guidelines](../05-Engineering-Guidelines/05-03-frontend-guidelines.md) - React/Next.js patterns
- [i18n Guidelines](../05-Engineering-Guidelines/05-08-i18n-guidelines.md) - การรองรับหลายภาษา
- [Testing Strategy](../05-Engineering-Guidelines/05-04-testing-strategy.md) - Coverage goals
---
## 11. Related ADRs
- [ADR-001: Unified Workflow Engine](./ADR-001-unified-workflow-engine.md) - พื้นฐาน Workflow Engine ที่ ADR-021 ขยายต่อ
- [ADR-002: Document Numbering Strategy](./ADR-002-document-numbering-strategy.md) - Redis Redlock สำหรับ Concurrency Control
- [ADR-016: Security and Authentication](./ADR-016-security-authentication.md) - ClamAV, Audit Log, Two-Phase Upload
- [ADR-019: Hybrid Identifier Strategy](./ADR-019-hybrid-identifier-strategy.md) - UUIDv7 / publicId ใช้ใน API
---
## 12. 📋 Version Dependency Matrix
| ADR | Version | Dependency Type | Affected Version(s) | Implementation Status |
|-----|---------|-----------------|---------------------|----------------------|
| **ADR-021** | 1.8.6 | Core | v1.8.6+ | 🔄 Proposed |
| **ADR-001** | 1.0 | Required By | v1.8.6+ | ✅ Active |
| **ADR-002** | 1.0 | Uses | v1.8.6+ | ✅ Active |
| **ADR-016** | 1.0 | Security | v1.8.6+ | ✅ Active |
| **ADR-019** | 1.0 | Identifier | v1.8.6+ | ✅ Active |
### Version Compatibility Rules
- **Minimum Version:** v1.8.6 (ADR-021 มีผลบังคับใช้)
- **Breaking Changes:** มี (Schema changes, API DTO changes)
- **Deprecation Timeline:** ไม่มี (Feature addition)
---
## 13. 🔄 Review Cycle & Maintenance
### Review Schedule
- **Next Review:** 2026-10-12 (6 months from creation)
- **Review Type:** Scheduled (Architecture Decision Review)
- **Reviewers:** System Architect, Development Team Lead, Product Owner
### Review Checklist
- [ ] การ implement ครบถ้วนตาม requirements (REQ-01 ถึง REQ-06)
- [ ] Database migration สำเร็จและ performance อยู่ในเกณฑ์ที่ยอมรับได้
- [ ] Frontend components ผ่าน UI/UX review
- [ ] มีปัญหา Integration กับ Module อื่นหรือไม่
- [ ] ต้องการ Update DSL structure หรือไม่
### Version History
| Version | Date | Changes | Status |
|---------|------|---------|--------|
| 1.8.6 | 2026-04-12 | Initial version - Integrated Workflow Context & Step-specific Attachments | 🔄 Proposed |
@@ -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)
```
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,105 @@
# Implementation Plan: [FEATURE]
**Branch**: `[###-feature-name]` | **Date**: [DATE] | **Spec**: [link]
**Input**: Feature specification from `/specs/[###-feature-name]/spec.md`
**Note**: This template is filled in by the `/speckit.plan` command. See `.specify/templates/commands/plan.md` for the execution workflow.
## Summary
[Extract from feature spec: primary requirement + technical approach from research]
## Technical Context
<!--
ACTION REQUIRED: Replace the content in this section with the technical details
for the project. The structure here is presented in advisory capacity to guide
the iteration process.
-->
**Language/Version**: [e.g., Python 3.11, Swift 5.9, Rust 1.75 or NEEDS CLARIFICATION]
**Primary Dependencies**: [e.g., FastAPI, UIKit, LLVM or NEEDS CLARIFICATION]
**Storage**: [if applicable, e.g., PostgreSQL, CoreData, files or N/A]
**Testing**: [e.g., pytest, XCTest, cargo test or NEEDS CLARIFICATION]
**Target Platform**: [e.g., Linux server, iOS 15+, WASM or NEEDS CLARIFICATION]
**Project Type**: [single/web/mobile - determines source structure]
**Performance Goals**: [domain-specific, e.g., 1000 req/s, 10k lines/sec, 60 fps or NEEDS CLARIFICATION]
**Constraints**: [domain-specific, e.g., <200ms p95, <100MB memory, offline-capable or NEEDS CLARIFICATION]
**Scale/Scope**: [domain-specific, e.g., 10k users, 1M LOC, 50 screens or NEEDS CLARIFICATION]
## Constitution Check
_GATE: Must pass before Phase 0 research. Re-check after Phase 1 design._
[Gates determined based on constitution file]
## Project Structure
### Documentation (this feature)
```text
specs/[###-feature]/
├── plan.md # This file (/speckit.plan command output)
├── research.md # Phase 0 output (/speckit.plan command)
├── data-model.md # Phase 1 output (/speckit.plan command)
├── quickstart.md # Phase 1 output (/speckit.plan command)
├── contracts/ # Phase 1 output (/speckit.plan command)
└── tasks.md # Phase 2 output (/speckit.tasks command - NOT created by /speckit.plan)
```
### Source Code (repository root)
<!--
ACTION REQUIRED: Replace the placeholder tree below with the concrete layout
for this feature. Delete unused options and expand the chosen structure with
real paths (e.g., apps/admin, packages/something). The delivered plan must
not include Option labels.
-->
```text
# [REMOVE IF UNUSED] Option 1: Single project (DEFAULT)
src/
├── models/
├── services/
├── cli/
└── lib/
tests/
├── contract/
├── integration/
└── unit/
# [REMOVE IF UNUSED] Option 2: Web application (when "frontend" + "backend" detected)
backend/
├── src/
│ ├── models/
│ ├── services/
│ └── api/
└── tests/
frontend/
├── src/
│ ├── components/
│ ├── pages/
│ └── services/
└── tests/
# [REMOVE IF UNUSED] Option 3: Mobile + API (when "iOS/Android" detected)
api/
└── [same as backend above]
ios/ or android/
└── [platform-specific structure: feature modules, UI flows, platform tests]
```
**Structure Decision**: [Document the selected structure and reference the real
directories captured above]
## Complexity Tracking
> **Fill ONLY if Constitution Check has violations that must be justified**
| Violation | Why Needed | Simpler Alternative Rejected Because |
| -------------------------- | ------------------ | ------------------------------------ |
| [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
| [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |