feat(server): 完成 P0+P1 后端能力(工作流、RBAC、付款归档)
P0 MVP: - 认证:login/refresh/logout/forgot/reset + tokenVersion - RBAC:角色到权限映射 + requirePermission - 发票池:upload/bind/signed-url + 判重(VALID_003/VALID_005) - 报销:create/view/submit + 单号生成 - 工作流:approve + department_manager 解析 P1 扩展: - 动作:reject/return/withdraw(含 comment) - transfer:任务转审 + 链路上限 3 - pay:approved -> paid + 发票归档 used_complete - 动态审批链:approval_rules 驱动 回归脚本: - smoke-test.sh / regression-dedup.sh / regression-workflow-actions.sh
这个提交包含在:
@@ -0,0 +1,659 @@
|
||||
const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { resolvePermissionsForRoles, hasPermission } = require("../constants/permissions");
|
||||
const { getWorkflowStepsSnapshot, resolveActionableStep } = require("../utils/workflow");
|
||||
|
||||
const TASK_ID_SCHEMA = z.string().uuid();
|
||||
const REQUIRED_COMMENT_SCHEMA = z.object({
|
||||
comment: z.string().trim().min(1).max(500),
|
||||
});
|
||||
const TRANSFER_BODY_SCHEMA = z.object({
|
||||
toApproverId: z.string().uuid(),
|
||||
reason: z.string().max(500),
|
||||
});
|
||||
|
||||
function parseRequiredComment(body) {
|
||||
const parsed = REQUIRED_COMMENT_SCHEMA.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data.comment;
|
||||
}
|
||||
|
||||
function parseTransferBody(body) {
|
||||
const parsed = TRANSFER_BODY_SCHEMA.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const reason = parsed.data.reason.trim();
|
||||
if (reason.length < 10) {
|
||||
throw new AppError({
|
||||
code: "VALID_002",
|
||||
message: "转审原因不足 10 字",
|
||||
statusCode: 400,
|
||||
details: { reason: "too_short" },
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
toApproverId: parsed.data.toApproverId,
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTaskId(taskId) {
|
||||
const parsed = TASK_ID_SCHEMA.safeParse(taskId);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { taskId: "invalid_uuid" },
|
||||
});
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
async function lockWorkflowTask(tx, taskId) {
|
||||
const taskRows = await tx.$queryRaw`
|
||||
SELECT id, instance_id, step_id, step_name, assignee_id, assignee_role, status
|
||||
FROM "workflow_tasks"
|
||||
WHERE id = ${taskId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
|
||||
if (!Array.isArray(taskRows) || taskRows.length === 0) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return taskRows[0];
|
||||
}
|
||||
|
||||
function ensurePendingTask(task) {
|
||||
if (task.status !== "pending") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { task: "already_processed" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ensureTaskAssignableToCurrentEmployee(task, request) {
|
||||
const matchesAssigneeId = Boolean(task.assignee_id && task.assignee_id === request.employee.id);
|
||||
const matchesAssigneeRole = Boolean(
|
||||
task.assignee_role && request.employee.roleCodes.includes(task.assignee_role),
|
||||
);
|
||||
const isUnassigned = !task.assignee_id && !task.assignee_role;
|
||||
|
||||
if (!(matchesAssigneeId || matchesAssigneeRole || isUnassigned)) {
|
||||
throw new AppError({
|
||||
code: "PERM_002",
|
||||
message: "不在审批范围/非当前处理人",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function loadWorkflowInstanceForTask(tx, instanceId) {
|
||||
const workflowInstance = await tx.workflowInstance.findUnique({
|
||||
where: { id: instanceId },
|
||||
select: {
|
||||
id: true,
|
||||
entity_id: true,
|
||||
current_step_id: true,
|
||||
context_data: true,
|
||||
workflow_definition: {
|
||||
select: {
|
||||
definition_json: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!workflowInstance) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
return workflowInstance;
|
||||
}
|
||||
|
||||
async function createSkipHistoryRecords(tx, workflowInstanceId, actorId, ownerId, skippedSteps) {
|
||||
for (const skipped of skippedSteps) {
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstanceId,
|
||||
actor_id: actorId,
|
||||
action: "skip",
|
||||
payload: {
|
||||
step_id: skipped.step.id,
|
||||
reason: skipped.reason,
|
||||
owner_id: ownerId,
|
||||
depth_checked: skipped.depthChecked,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelOtherPendingTasks(tx, workflowInstanceId, taskId, actorId) {
|
||||
await tx.workflowTask.updateMany({
|
||||
where: {
|
||||
instance_id: workflowInstanceId,
|
||||
status: "pending",
|
||||
NOT: { id: taskId },
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
completed_at: new Date(),
|
||||
completed_by: actorId,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function ensureTransferChainNotExceeded(tx, taskId) {
|
||||
const transferCount = await tx.workflowHistory.count({
|
||||
where: {
|
||||
task_id: taskId,
|
||||
action: "transfer",
|
||||
},
|
||||
});
|
||||
|
||||
if (transferCount >= 3) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { transfer: "chain_limit_exceeded" },
|
||||
});
|
||||
}
|
||||
|
||||
return transferCount;
|
||||
}
|
||||
|
||||
async function ensureTransferTargetEligible(tx, toApproverId) {
|
||||
const target = await tx.employee.findUnique({
|
||||
where: { id: toApproverId },
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
roles: {
|
||||
select: {
|
||||
role_code: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!target || target.status !== "active") {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { toApproverId: "invalid_target" },
|
||||
});
|
||||
}
|
||||
|
||||
const roleCodes = target.roles.map((item) => item.role_code);
|
||||
const permissionCodes = resolvePermissionsForRoles(roleCodes);
|
||||
if (!hasPermission(permissionCodes, "expense.approve")) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { toApproverId: "target_not_approver" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function workflowRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/workflow/tasks",
|
||||
{
|
||||
preHandler: fastify.authenticate,
|
||||
},
|
||||
async (request, reply) => {
|
||||
const querySchema = z.object({
|
||||
status: z.enum(["pending", "completed", "rejected", "cancelled", "skipped"]).optional(),
|
||||
});
|
||||
const parsedQuery = querySchema.safeParse(request.query ?? {});
|
||||
if (!parsedQuery.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsedQuery.error.flatten(),
|
||||
});
|
||||
}
|
||||
|
||||
const status = parsedQuery.data.status ?? "pending";
|
||||
const roleFilters = request.employee.roleCodes.length
|
||||
? [{ assignee_role: { in: request.employee.roleCodes } }]
|
||||
: [];
|
||||
|
||||
const tasks = await fastify.prisma.workflowTask.findMany({
|
||||
where: {
|
||||
status,
|
||||
OR: [{ assignee_id: request.employee.id }, ...roleFilters],
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
instance_id: true,
|
||||
step_id: true,
|
||||
step_name: true,
|
||||
assignee_id: true,
|
||||
assignee_role: true,
|
||||
status: true,
|
||||
outcome: true,
|
||||
created_at: true,
|
||||
completed_at: true,
|
||||
workflow_instance: {
|
||||
select: {
|
||||
entity_type: true,
|
||||
entity_id: true,
|
||||
current_status: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
items: tasks,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/approve",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const steps = getWorkflowStepsSnapshot(workflowInstance);
|
||||
const currentStepIndex = steps.findIndex((step) => step.id === workflowInstance.current_step_id);
|
||||
if (currentStepIndex < 0) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { workflow: "current_step_not_found" },
|
||||
});
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "completed",
|
||||
outcome: "approved",
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
const { actionable, skipped } = await resolveActionableStep({
|
||||
tx,
|
||||
steps,
|
||||
startIndex: currentStepIndex + 1,
|
||||
ownerId: workflowInstance.context_data?.owner_id,
|
||||
logger: fastify.log,
|
||||
});
|
||||
|
||||
await createSkipHistoryRecords(
|
||||
tx,
|
||||
workflowInstance.id,
|
||||
request.employee.id,
|
||||
workflowInstance.context_data?.owner_id,
|
||||
skipped,
|
||||
);
|
||||
|
||||
if (actionable) {
|
||||
const nextTask = await tx.workflowTask.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
step_id: actionable.step.id,
|
||||
step_name: actionable.step.name ?? actionable.step.id,
|
||||
assignee_id: actionable.assigneeId,
|
||||
assignee_role: actionable.assigneeRole,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_step_id: actionable.step.id,
|
||||
current_status: "pending",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "approve",
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
to_step_id: actionable.step.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "approved",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
nextTaskId: nextTask.id,
|
||||
reimbursementStatus: "reviewing",
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "approved",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "approved",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "approve",
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "approved",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
nextTaskId: null,
|
||||
reimbursementStatus: "approved",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/reject",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const comment = parseRequiredComment(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const now = new Date();
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "rejected",
|
||||
outcome: "rejected",
|
||||
comment,
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await cancelOtherPendingTasks(tx, workflowInstance.id, taskId, request.employee.id);
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "rejected",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "rejected",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "reject",
|
||||
comment,
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "rejected",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "rejected",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/return",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.approve"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const comment = parseRequiredComment(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const now = new Date();
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
status: "completed",
|
||||
outcome: "returned",
|
||||
comment,
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await cancelOtherPendingTasks(tx, workflowInstance.id, taskId, request.employee.id);
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: workflowInstance.id },
|
||||
data: {
|
||||
current_status: "terminated",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.reimbursementForm.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
status: "draft",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "return",
|
||||
comment,
|
||||
payload: {
|
||||
from_step_id: task.step_id,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "returned",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "draft",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/workflow/tasks/:taskId/transfer",
|
||||
{
|
||||
preHandler: fastify.requirePermission("expense.transfer"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const taskId = parseTaskId(request.params?.taskId);
|
||||
const { toApproverId, reason } = parseTransferBody(request.body);
|
||||
let result = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const task = await lockWorkflowTask(tx, taskId);
|
||||
ensurePendingTask(task);
|
||||
ensureTaskAssignableToCurrentEmployee(task, request);
|
||||
|
||||
const workflowInstance = await loadWorkflowInstanceForTask(tx, task.instance_id);
|
||||
const transferCount = await ensureTransferChainNotExceeded(tx, taskId);
|
||||
await ensureTransferTargetEligible(tx, toApproverId);
|
||||
|
||||
if (toApproverId === request.employee.id) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { transfer: "same_assignee_not_allowed" },
|
||||
});
|
||||
}
|
||||
|
||||
await tx.workflowTask.update({
|
||||
where: { id: taskId },
|
||||
data: {
|
||||
assignee_id: toApproverId,
|
||||
assignee_role: null,
|
||||
},
|
||||
});
|
||||
|
||||
const transfer = await tx.approvalTransfer.create({
|
||||
data: {
|
||||
reimbursement_id: workflowInstance.entity_id,
|
||||
from_approver_id: request.employee.id,
|
||||
to_approver_id: toApproverId,
|
||||
reason,
|
||||
status: "active",
|
||||
created_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: workflowInstance.id,
|
||||
task_id: taskId,
|
||||
actor_id: request.employee.id,
|
||||
action: "transfer",
|
||||
comment: reason,
|
||||
payload: {
|
||||
from_approver_id: request.employee.id,
|
||||
to_approver_id: toApproverId,
|
||||
reason,
|
||||
transfer_count: transferCount + 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
result = {
|
||||
taskId,
|
||||
outcome: "transferred",
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
reimbursementStatus: "reviewing",
|
||||
transferId: transfer.id,
|
||||
fromApproverId: request.employee.id,
|
||||
toApproverId,
|
||||
transferCount: transferCount + 1,
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, result);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = workflowRoutes;
|
||||
在新工单中引用
屏蔽一个用户