690417:1538 Refactor Work flow ADR-021

This commit is contained in:
2026-04-17 15:38:20 +07:00
parent 6d45bdaeb5
commit 3a5fc8d4af
23 changed files with 892 additions and 135 deletions
@@ -49,7 +49,7 @@ export class Attachment extends UuidBaseEntity {
// ADR-021: FK ไปยัง workflow_histories สำหรับไฟล์แนบประจำ Step
// NULL = ไฟล์แนบหลัก (Main Document), NOT NULL = ไฟล์ประจำ Workflow Step
@Column({ name: 'workflow_history_id', length: 36, nullable: true })
@Column({ name: 'workflow_history_id', nullable: true })
workflowHistoryId?: string;
// Lazy relation — ไม่ include ใน default query เพื่อป้องกัน N+1
@@ -5,11 +5,13 @@ import { FileStorageService } from './file-storage.service.js';
import { FileStorageController } from './file-storage.controller.js';
import { FileCleanupService } from './file-cleanup.service.js'; // ✅ Import
import { Attachment } from './entities/attachment.entity';
import { UserModule } from '../../modules/user/user.module';
@Module({
imports: [
TypeOrmModule.forFeature([Attachment]),
ScheduleModule.forRoot(), // ✅ เปิดใช้งาน Cron Job],
UserModule,
],
controllers: [FileStorageController],
providers: [
@@ -8,9 +8,9 @@ export const seedWorkflowDefinitions = async (dataSource: DataSource) => {
const repo = dataSource.getRepository(WorkflowDefinition);
const dslService = new WorkflowDslService();
// 1. RFA Workflow (Standard)
// 1. RFA Workflow — all RFA types (incl. drawing subtypes DDW/SDW/ADW) share one definition
const rfaDsl = {
workflow: 'RFA_FLOW_V1', // [FIX] เปลี่ยนชื่อให้ตรงกับค่าใน RfaWorkflowService
workflow: 'RFA_APPROVAL', // [C2] Single code for all RFA types
version: 1,
description: 'Standard RFA Approval Workflow',
states: [
@@ -52,30 +52,23 @@ export const seedWorkflowDefinitions = async (dataSource: DataSource) => {
],
};
// 2. Circulation Workflow
// 2. Circulation Workflow — org-scoped (contractId = null), states match delta-06
const circulationDsl = {
workflow: 'CIRCULATION_INTERNAL_V1', // [FIX] เปลี่ยนชื่อให้ตรงกับค่าใน CirculationWorkflowService
workflow: 'CIRCULATION_FLOW_V1', // [C1] renamed from CIRCULATION_INTERNAL_V1
version: 1,
description: 'Internal Document Circulation',
description:
'Circulation Workflow — DRAFT → ROUTING → COMPLETED | CANCELLED',
states: [
{
name: 'OPEN',
name: 'DRAFT',
initial: true,
on: {
START: {
// [FIX] เปลี่ยนชื่อ Action ให้ตรงกับที่ Service เรียกใช้ ('START')
to: 'IN_REVIEW',
},
},
on: { START: { to: 'ROUTING' } },
},
{
name: 'IN_REVIEW',
name: 'ROUTING',
on: {
COMPLETE_TASK: {
// [FIX] เปลี่ยนให้สอดคล้องกับ Action ที่ใช้จริง
to: 'COMPLETED',
},
CANCEL: { to: 'CANCELLED' },
COMPLETE: { to: 'COMPLETED' },
FORCE_CLOSE: { to: 'CANCELLED' },
},
},
{ name: 'COMPLETED', terminal: true },
@@ -83,6 +76,28 @@ export const seedWorkflowDefinitions = async (dataSource: DataSource) => {
],
};
// 4. Transmittal Workflow
const transmittalDsl = {
workflow: 'TRANSMITTAL_FLOW_V1',
version: 1,
description: 'Transmittal Submission Workflow',
states: [
{
name: 'DRAFT',
initial: true,
on: { SUBMIT: { to: 'SUBMITTED' } },
},
{
name: 'SUBMITTED',
on: {
ACKNOWLEDGE: { to: 'COMPLETED' },
RETURN: { to: 'DRAFT' },
},
},
{ name: 'COMPLETED', terminal: true },
],
};
// 3. Correspondence Workflow (Optional - ถ้ามี)
const correspondenceDsl = {
workflow: 'CORRESPONDENCE_FLOW_V1',
@@ -106,7 +121,7 @@ export const seedWorkflowDefinitions = async (dataSource: DataSource) => {
],
};
const workflows = [rfaDsl, circulationDsl, correspondenceDsl];
const workflows = [rfaDsl, circulationDsl, correspondenceDsl, transmittalDsl];
for (const dsl of workflows) {
const exists = await repo.findOne({
@@ -17,7 +17,7 @@ import { WorkflowTransitionDto } from '../workflow-engine/dto/workflow-transitio
@Injectable()
export class CirculationWorkflowService {
private readonly logger = new Logger(CirculationWorkflowService.name);
private readonly WORKFLOW_CODE = 'CIRCULATION_INTERNAL_V1';
private readonly WORKFLOW_CODE = 'CIRCULATION_FLOW_V1';
constructor(
private readonly workflowEngine: WorkflowEngineService,
@@ -48,8 +48,9 @@ export class CirculationWorkflowService {
);
}
// Context อาจประกอบด้วย Department หรือ Priority
const context = {
// Context — Circulation เป็น internal document ระดับ Organization (ไม่ผูก contract)
// Guard Level 2 ตรวจ organizationId; Level 2.5 (contract check) จะ skip เมื่อ contractId = null
const context: Record<string, unknown> = {
organizationId: circulation.organization,
creatorId: userId,
};
@@ -377,14 +377,24 @@ export class CorrespondenceService {
await queryRunner.commitTransaction();
// Start Workflow Instance (non-blocking)
// All correspondence types use CORRESPONDENCE_FLOW_V1 (type code is NOT a separate workflow)
try {
const workflowCode = `CORRESPONDENCE_${type.typeCode}`;
let corrContractId: number | null = null;
if (createDto.disciplineId) {
const disciplineRows = await this.dataSource.query<
[{ contract_id: number }]
>('SELECT contract_id FROM disciplines WHERE id = ? LIMIT 1', [
createDto.disciplineId,
]);
corrContractId = disciplineRows[0]?.contract_id ?? null;
}
await this.workflowEngine.createInstance(
workflowCode,
'CORRESPONDENCE_FLOW_V1',
'correspondence',
savedCorr.id.toString(),
{
projectId: resolvedProjectId,
contractId: corrContractId,
originatorId: userOrgId,
disciplineId: createDto.disciplineId,
initiatorId: user.user_id,
@@ -392,7 +402,7 @@ export class CorrespondenceService {
);
} catch (error: unknown) {
this.logger.warn(
`Workflow not started for ${docNumber.number} (Code: CORRESPONDENCE_${type.typeCode}): ${(error as Error).message}`
`Workflow not started for ${docNumber.number}: ${(error as Error).message}`
);
}
@@ -30,7 +30,7 @@ import { WorkflowTransitionDto } from '../workflow-engine/dto/workflow-transitio
@Injectable()
export class RfaWorkflowService {
private readonly logger = new Logger(RfaWorkflowService.name);
private readonly WORKFLOW_CODE = 'RFA_FLOW_V1'; // ควรกำหนดใน Config หรือ Enum
private readonly WORKFLOW_CODE = 'RFA_APPROVAL'; // [C2] All RFA types share one workflow
constructor(
private readonly workflowEngine: WorkflowEngineService,
+3 -2
View File
@@ -440,14 +440,15 @@ export class RfaService {
await queryRunner.commitTransaction();
// [NEW V1.5.1] Start Unified Workflow Instance
// [C2 FIX] Drawing types (DDW/SDW/ADW) are RFA subtypes — all use RFA_APPROVAL
try {
const workflowCode = `RFA_${rfaType.typeCode}`; // e.g., RFA_GEN
await this.workflowEngine.createInstance(
workflowCode,
'RFA_APPROVAL',
'rfa',
savedRfa.id.toString(),
{
projectId: internalProjectId,
contractId: internalContractId,
originatorId: userOrgId,
disciplineId: createDto.disciplineId,
initiatorId: user.user_id,
@@ -250,7 +250,10 @@ export class TransmittalService {
): Promise<{ instanceId: string; currentState: string }> {
const correspondence = await this.dataSource.manager.findOne(
Correspondence,
{ where: { publicId: uuid }, select: ['id', 'correspondenceNumber'] }
{
where: { publicId: uuid },
select: ['id', 'correspondenceNumber', 'disciplineId'],
}
);
if (!correspondence)
throw new NotFoundException(`Transmittal publicId ${uuid}`);
@@ -286,11 +289,20 @@ export class TransmittalService {
const statusDraft = await this.statusRepo.findOne({
where: { statusCode: 'DRAFT' },
});
// [C3] Resolve contractId from discipline for contract-scoped workflow
let contractId: number | null = null;
if (correspondence.disciplineId) {
const rows = await this.dataSource.query<[{ contract_id: number }]>(
'SELECT contract_id FROM disciplines WHERE id = ? LIMIT 1',
[correspondence.disciplineId]
);
contractId = rows[0]?.contract_id ?? null;
}
const instance = await this.workflowEngine.createInstance(
'TRANSMITTAL_FLOW_V1',
'transmittal',
correspondence.id.toString(),
{ ownerId: user.user_id }
{ ownerId: user.user_id, contractId }
);
const result = await this.workflowEngine.processTransition(
@@ -37,6 +37,14 @@ export class WorkflowInstance {
@Column({ name: 'definition_id' })
definitionId!: string;
@Column({
name: 'contract_id',
type: 'int',
nullable: true,
comment: 'Contract ที่ Workflow นี้เป็นส่วนหนึ่ง (NULL = global/legacy)',
})
contractId?: number | null;
// Polymorphic Relation: เชื่อมกับเอกสารได้หลายประเภท (RFA, CORR, etc.) โดยไม่ต้อง Foreign Key จริง
@Column({
name: 'entity_type',
@@ -0,0 +1,328 @@
// File: src/modules/workflow-engine/guards/workflow-transition.guard.spec.ts
// Unit tests for WorkflowTransitionGuard - T030
import { Test, TestingModule } from '@nestjs/testing';
import {
ExecutionContext,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { DataSource } from 'typeorm';
import { getRepositoryToken } from '@nestjs/typeorm';
import { WorkflowTransitionGuard } from './workflow-transition.guard';
import { WorkflowInstance } from '../entities/workflow-instance.entity';
import { UserService } from '../../../modules/user/user.service';
import type { RequestWithUser } from '../../../common/interfaces/request-with-user.interface';
type MockUserPayload = {
user_id: number;
email: string;
primaryOrganizationId: number | null;
} | null;
describe('WorkflowTransitionGuard', () => {
let guard: WorkflowTransitionGuard;
let instanceRepo: { findOne: jest.Mock };
let userService: { getUserPermissions: jest.Mock };
let dataSource: { query: jest.Mock };
const mockUser = {
user_id: 123,
email: 'test@example.com',
primaryOrganizationId: 1,
};
const mockRequest = (
params: Record<string, string> = {},
user: MockUserPayload = mockUser
): Partial<RequestWithUser> => ({
params,
user: user as RequestWithUser['user'],
});
const mockContext = (req: Partial<RequestWithUser>): ExecutionContext =>
({
switchToHttp: () => ({
getRequest: () => req,
}),
}) as ExecutionContext;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
WorkflowTransitionGuard,
{
provide: getRepositoryToken(WorkflowInstance),
useValue: {
findOne: jest.fn(),
},
},
{
provide: UserService,
useValue: {
getUserPermissions: jest.fn(),
},
},
{
provide: DataSource,
useValue: {
query: jest.fn(),
},
},
],
}).compile();
guard = module.get<WorkflowTransitionGuard>(WorkflowTransitionGuard);
instanceRepo = module.get(getRepositoryToken(WorkflowInstance));
userService = module.get(UserService);
dataSource = module.get(DataSource);
instanceRepo.findOne = jest.fn();
userService.getUserPermissions = jest.fn();
dataSource.query = jest.fn();
});
describe('Level 1: Superadmin', () => {
it('should allow access for user with system.manage_all permission', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['system.manage_all']);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act
const result = await guard.canActivate(context);
// Assert
expect(result).toBe(true);
expect(userService.getUserPermissions).toHaveBeenCalledWith(123);
expect(instanceRepo.findOne).not.toHaveBeenCalled();
});
});
describe('Level 2: Org Admin', () => {
it('should allow access for org admin with same organization as document', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue([
'organization.manage_users',
]);
const mockInstance = {
id: 'instance-123',
context: { organizationId: 1 },
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act
const result = await guard.canActivate(context);
// Assert
expect(result).toBe(true);
expect(userService.getUserPermissions).toHaveBeenCalledWith(123);
expect(instanceRepo.findOne).toHaveBeenCalledWith({
where: { id: 'instance-123' },
});
});
it('should deny access for org admin from different organization', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue([
'organization.manage_users',
]);
const mockInstance = {
id: 'instance-123',
context: { organizationId: 2 }, // Different org
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
});
it('should deny access for org admin when document has no organization', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue([
'organization.manage_users',
]);
const mockInstance = {
id: 'instance-123',
context: { organizationId: undefined },
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
});
});
describe('Level 2.5: Contract Membership', () => {
it('should allow access for user in same contract as document AND assigned as handler', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']); // No special permissions
const mockInstance = {
id: 'instance-123',
context: {
organizationId: 2, // Different org from user
assignedUserId: 123, // This user is assigned
},
contractId: 42, // Has contract
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
dataSource.query.mockResolvedValue([{ cnt: '1' }]); // User org in contract
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act
const result = await guard.canActivate(context);
// Assert
expect(result).toBe(true);
expect(dataSource.query).toHaveBeenCalledWith(
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
[42, 1]
);
});
it('should deny access for user not in contract (cross-contract block)', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']);
const mockInstance = {
id: 'instance-123',
context: { organizationId: 1 },
contractId: 42,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
dataSource.query.mockResolvedValue([{ cnt: '0' }]); // User org NOT in contract
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
expect(dataSource.query).toHaveBeenCalledWith(
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
[42, 1]
);
});
it('should deny access for user without primary organization when contract is present', async () => {
// Arrange
const userWithoutOrg = { ...mockUser, primaryOrganizationId: null };
userService.getUserPermissions.mockResolvedValue(['document.view']);
const mockInstance = {
id: 'instance-123',
context: { organizationId: 1 },
contractId: 42,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(
mockRequest({ id: 'instance-123' }, userWithoutOrg)
);
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
expect(dataSource.query).not.toHaveBeenCalled();
});
});
describe('Level 3: Assigned Handler', () => {
it('should allow access for user assigned as handler', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']);
const mockInstance = {
id: 'instance-123',
context: {
organizationId: 2, // Different org
assignedUserId: 123, // This user is assigned
},
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act
const result = await guard.canActivate(context);
// Assert
expect(result).toBe(true);
});
it('should deny access for different assigned user', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']);
const mockInstance = {
id: 'instance-123',
context: {
organizationId: 2,
assignedUserId: 456, // Different user assigned
},
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
});
});
describe('Level 4: Unauthorized Users', () => {
it('should deny access for regular users without any special permissions', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']); // Basic permission only
const mockInstance = {
id: 'instance-123',
context: { organizationId: 2 }, // Different org
contractId: null,
};
instanceRepo.findOne.mockResolvedValue(mockInstance);
const context = mockContext(mockRequest({ id: 'instance-123' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
ForbiddenException
);
});
});
describe('Edge Cases', () => {
it('should throw NotFoundException when workflow instance does not exist', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']);
instanceRepo.findOne.mockResolvedValue(null);
const context = mockContext(mockRequest({ id: 'non-existent' }));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow(
NotFoundException
);
});
it('should handle missing user in request', async () => {
// Arrange
const context = mockContext(mockRequest({ id: 'instance-123' }, null));
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow();
});
it('should handle missing instanceId in params', async () => {
// Arrange
userService.getUserPermissions.mockResolvedValue(['document.view']);
const context = mockContext(mockRequest({})); // No id param
// Act & Assert
await expect(guard.canActivate(context)).rejects.toThrow();
});
});
});
@@ -10,7 +10,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { DataSource, Repository } from 'typeorm';
import { WorkflowInstance } from '../entities/workflow-instance.entity';
import { UserService } from '../../../modules/user/user.service';
import type { RequestWithUser } from '../../../common/interfaces/request-with-user.interface';
@@ -18,10 +18,12 @@ import type { RequestWithUser } from '../../../common/interfaces/request-with-us
/**
* WorkflowTransitionGuard — ตรวจสอบสิทธิ์ 4 ระดับก่อนอนุญาตให้เปลี่ยนสถานะ Workflow
*
* Level 1: system.manage_all (Superadmin) → ผ่านทันที
* Level 2: organization.manage_users + สังกัดองค์กรเดียวกับเอกสาร → ผ่าน
* Level 3: Assigned Handler (context.assignedUserId === req.user.user_id) → ผ่าน
* Level 4: ผู้ใช้ทั่วไป → ForbiddenException
* Level 1: system.manage_all (Superadmin) → ผ่านทันที
* Level 2: organization.manage_users + สังกัดองค์กรเดียวกับเอกสาร → ผ่าน
* Level 2.5: [C3] contract_organizations membership — ถ้า instance.contractId ถูกตั้ง
* และ User ไม่อยู่ใน contract นั้น → ForbiddenException (cross-contract block)
* Level 3: Assigned Handler (context.assignedUserId === req.user.user_id) → ผ่าน
* Level 4: ผู้ใช้ทั่วไป → ForbiddenException
*/
@Injectable()
export class WorkflowTransitionGuard implements CanActivate {
@@ -30,7 +32,8 @@ export class WorkflowTransitionGuard implements CanActivate {
constructor(
@InjectRepository(WorkflowInstance)
private readonly instanceRepo: Repository<WorkflowInstance>,
private readonly userService: UserService
private readonly userService: UserService,
private readonly dataSource: DataSource
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -67,6 +70,35 @@ export class WorkflowTransitionGuard implements CanActivate {
return true;
}
// Level 2.5: [C3] Contract Membership check — ถ้า instance ผูกกับ contract ใด
// User ต้องสังกัดองค์กรที่อยู่ใน contract นั้น ป้องกัน cross-contract access
if (instance.contractId !== null && instance.contractId !== undefined) {
const userOrgId = user.primaryOrganizationId;
if (!userOrgId) {
this.logger.warn(
`No org for User ${user.user_id} attempting contract-scoped workflow ${instanceId}`
);
throw new ForbiddenException({
userMessage:
'คุณไม่ได้สังกัดองค์กรใด ไม่สามารถดำเนินการในสัญญานี้ได้',
recoveryAction: 'ติดต่อ Admin เพื่อกำหนดองค์กร',
});
}
const rows = await this.dataSource.query<[{ cnt: string }]>(
'SELECT COUNT(*) AS cnt FROM contract_organizations WHERE contract_id = ? AND organization_id = ?',
[instance.contractId, userOrgId]
);
if (Number(rows[0]?.cnt ?? 0) === 0) {
this.logger.warn(
`Cross-contract access attempt: User ${user.user_id} (Org ${userOrgId}) on Contract ${instance.contractId} Instance ${instanceId}`
);
throw new ForbiddenException({
userMessage: 'คุณไม่มีสิทธิ์เข้าถึง Workflow ของสัญญานี้',
recoveryAction: 'ตรวจสอบสิทธิ์กับ Project Admin',
});
}
}
// Level 3: Assigned Handler — User นี้ถูก Assign มาให้ทำ Step นี้โดยตรง
const assignedUserId = instance.context?.assignedUserId as
| number
@@ -116,15 +116,15 @@ export class WorkflowEngineController {
throw new BadRequestException('Idempotency-Key header is required');
}
// ตรวจ Redis ว่า Request นี้ถูกส่งมาแล้วหรือไม่
const cacheKey = `idempotency:wf:${idempotencyKey}`;
const userId = req.user?.user_id;
// ตรวจ Redis ว่า Request นี้ถูกส่งมาแล้วหรือไม่ (key ผูกกับ userId ป้องกัน cross-user replay)
const cacheKey = `idempotency:transition:${idempotencyKey}:${userId}`;
const cached = await this.cacheManager.get(cacheKey);
if (cached) {
return cached; // คืนผลเดิม (Idempotent Response)
}
const userId = req.user?.user_id;
const result = await this.workflowService.processTransition(
instanceId,
dto.action,
@@ -1,7 +1,7 @@
import { Test, TestingModule } from '@nestjs/testing';
import { WorkflowEngineService } from './workflow-engine.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { DataSource, Repository } from 'typeorm';
import { DataSource, In, Repository } from 'typeorm';
import { WorkflowDefinition } from './entities/workflow-definition.entity';
import {
WorkflowInstance,
@@ -11,6 +11,7 @@ import { WorkflowHistory } from './entities/workflow-history.entity';
import { Attachment } from '../../common/file-storage/entities/attachment.entity';
import { WorkflowDslService } from './workflow-dsl.service';
import { WorkflowEventService } from './workflow-event.service';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { NotFoundException } from '../../common/exceptions';
import { CreateWorkflowDefinitionDto } from './dto/create-workflow-definition.dto';
@@ -96,6 +97,14 @@ describe('WorkflowEngineService', () => {
{ provide: WorkflowDslService, useValue: mockDslService },
{ provide: WorkflowEventService, useValue: mockEventService },
{ provide: DataSource, useValue: mockDataSource },
{
provide: CACHE_MANAGER,
useValue: {
get: jest.fn().mockResolvedValue(null),
set: jest.fn().mockResolvedValue(undefined),
del: jest.fn().mockResolvedValue(undefined),
},
},
],
}).compile();
@@ -210,5 +219,103 @@ describe('WorkflowEngineService', () => {
expect(mockQueryRunner.rollbackTransaction).toHaveBeenCalled();
expect(mockQueryRunner.release).toHaveBeenCalled();
});
// ADR-021 T031: Tests for step-specific attachments
describe('ADR-021 Step-specific Attachments', () => {
it('should link attachments to workflow history record', async () => {
const instanceId = 'inst-1';
const attachmentPublicIds = ['att-123', 'att-456'];
const mockInstance = {
id: instanceId,
currentState: 'PENDING',
status: WorkflowStatus.ACTIVE,
definition: { compiled: mockCompiledWorkflow },
context: { some: 'data' },
};
// Mock the history object with an ID
const mockHistory = { id: 'history-123' };
mockQueryRunner.manager.findOne.mockResolvedValue(mockInstance);
// Mock save to return the history object when called with any entity
mockQueryRunner.manager.save.mockResolvedValue(mockHistory);
mockDslService.evaluate.mockReturnValue({
nextState: 'APPROVED',
events: [],
});
await service.processTransition(
instanceId,
'APPROVE',
1,
'Test comment',
{},
attachmentPublicIds
);
expect(mockQueryRunner.manager.update).toHaveBeenCalledWith(
Attachment,
{ publicId: In(attachmentPublicIds) },
{ workflowHistoryId: 'history-123' }
);
});
it('should skip attachment linking when no attachmentPublicIds provided', async () => {
const instanceId = 'inst-1';
const mockInstance = {
id: instanceId,
currentState: 'PENDING',
status: WorkflowStatus.ACTIVE,
definition: { compiled: mockCompiledWorkflow },
context: { some: 'data' },
};
mockQueryRunner.manager.findOne.mockResolvedValue(mockInstance);
mockDslService.evaluate.mockReturnValue({
nextState: 'APPROVED',
events: [],
});
await service.processTransition(instanceId, 'APPROVE', 1);
expect(mockQueryRunner.manager.update).not.toHaveBeenCalledWith(
expect.any(Object),
expect.any(Object),
expect.objectContaining({ workflowHistoryId: expect.any(String) })
);
});
it('should handle empty attachmentPublicIds array', async () => {
const instanceId = 'inst-1';
const mockInstance = {
id: instanceId,
currentState: 'PENDING',
status: WorkflowStatus.ACTIVE,
definition: { compiled: mockCompiledWorkflow },
context: { some: 'data' },
};
mockQueryRunner.manager.findOne.mockResolvedValue(mockInstance);
mockDslService.evaluate.mockReturnValue({
nextState: 'APPROVED',
events: [],
});
await service.processTransition(
instanceId,
'APPROVE',
1,
'Test comment',
{},
[] // Empty array
);
expect(mockQueryRunner.manager.update).not.toHaveBeenCalledWith(
expect.any(Object),
expect.any(Object),
expect.objectContaining({ workflowHistoryId: expect.any(String) })
);
});
});
});
});
@@ -1,6 +1,8 @@
// File: src/modules/workflow-engine/workflow-engine.service.ts
import { Injectable, Logger } from '@nestjs/common';
import { Injectable, Inject, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import type { Cache } from 'cache-manager';
import { NotFoundException, WorkflowException } from '../../common/exceptions';
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, In, Repository } from 'typeorm';
@@ -55,7 +57,8 @@ export class WorkflowEngineService {
private readonly attachmentRepo: Repository<Attachment>,
private readonly dslService: WorkflowDslService,
private readonly eventService: WorkflowEventService, // [NEW] Inject Service
private readonly dataSource: DataSource // ใช้สำหรับ Transaction
private readonly dataSource: DataSource, // ใช้สำหรับ Transaction
@Inject(CACHE_MANAGER) private readonly cacheManager: Cache // ADR-021 T024: History cache
) {}
// =================================================================
@@ -215,12 +218,18 @@ export class WorkflowEngineService {
}
// 3. สร้าง Instance
// [C3] Extract contractId from context to persist as searchable column
const contractId =
typeof initialContext.contractId === 'number'
? initialContext.contractId
: null;
const instance = this.instanceRepo.create({
definition,
entityType,
entityId,
currentState: initialState,
status: WorkflowStatus.ACTIVE,
contractId,
context: initialContext,
});
@@ -364,19 +373,22 @@ export class WorkflowEngineService {
payload,
},
});
await queryRunner.manager.save(history);
const savedHistory = await queryRunner.manager.save(history);
// ADR-021: ผูกไฟล์แนบประจำ Step นี้ (ทำในตัว Transaction เดียวกัน)
if (attachmentPublicIds && attachmentPublicIds.length > 0) {
await queryRunner.manager.update(
Attachment,
{ publicId: In(attachmentPublicIds) },
{ workflowHistoryId: history.id }
{ workflowHistoryId: savedHistory.id }
);
}
await queryRunner.commitTransaction();
// ADR-021 T043: Invalidate Workflow History cache หลัง transition สำเร็จ
void this.cacheManager.del(`wf:history:${instanceId}`);
// [NEW] เก็บค่าไว้ Dispatch หลัง Commit
eventsToDispatch = evaluation.events;
updatedContext = context;
@@ -443,6 +455,12 @@ export class WorkflowEngineService {
async getHistoryWithAttachments(
instanceId: string
): Promise<WorkflowHistoryItemDto[]> {
// ADR-021 T024: Redis cache — ป้องกัน N+1 บน repeated view (TTL 1h)
const cacheKey = `wf:history:${instanceId}`;
const cached =
await this.cacheManager.get<WorkflowHistoryItemDto[]>(cacheKey);
if (cached) return cached;
const histories = await this.historyRepo.find({
where: { instanceId },
order: { createdAt: 'ASC' },
@@ -474,7 +492,7 @@ export class WorkflowEngineService {
{}
);
return histories.map((h) => ({
const result: WorkflowHistoryItemDto[] = histories.map((h) => ({
id: h.id,
fromState: h.fromState,
toState: h.toState,
@@ -490,6 +508,10 @@ export class WorkflowEngineService {
})),
createdAt: h.createdAt.toISOString(),
}));
// Cache result (TTL 1h = 3_600_000 ms)
await this.cacheManager.set(cacheKey, result, 3_600_000);
return result;
}
// =================================================================