文件
hyb-oa/server/src/routes/todos.js
T
wangsli和Claude Sonnet 5 cd01e4bf28 迁移首批4个错误码:AP台账/查询、待办、工作台功能开关 [09-05-error-explainability-payment-readiness]
10-05 到期例外清单里已设计好的首批 4 个具体调用,现予落码(原方案见
implement.md §14「首批具体分支与验证要求」):

- ap_operations.feature_disabled(409):AP 台账/明细查询功能关闭
- ap_operations.query_invalid(400):AP 台账查询参数校验失败
- todo.feature_disabled(409):待办功能关闭
- portal.feature_disabled(409):工作台首页功能关闭

四处均改为调用 buildBusinessValidationError(reasonCode, details, statusCode),
保留原 HTTP 状态码、featureFlag/reason 等既有 details 字段不变,仅新增精确
reasonCode;不改功能开关判断逻辑、不改权限校验顺序。

- server/src/constants/errorReasons.js + client/src/api/errorReasons.ts:
  注册 4 条原因码及中文文案,服务端/客户端逐字一致。
- scripts/qa/error-reason-legacy-baseline.json:移除这 4 条已迁移的旧例外
  记录(591 → 587),check-error-reason-contract.mjs 主检查与 self-test
  均 PASS,无 new_legacy/stale_exception/unregistered_reason。
- apOperations.permissions.test.js:扩展"功能关闭"断言校验 reasonCode 与
  原 details 字段共存;新增"查询参数非法(功能开启)"400 用例,断言零
  台账业务查询;新增"合法查询仍 200"用例。
- portal.test.js:新增工作台关闭时 409+reasonCode+零业务查询断言(此前
  完全没有覆盖这条路径)。
- todos.test.js:新建(此前 todos 路由零测试覆盖),聚焦 ensureFeatureEnabled
  网关:关闭时 GET/POST 均 409+reasonCode+零 todoItem 查询;开启时正常放行。

验证:server 5 个相关测试文件 286/286 通过;client typecheck/build 通过;
check-ui-design-rules.mjs --strict、check-trellis-governance.mjs、
git diff --check 通过。routes/ 全量回归 872/874(2 个失败为 paymentBatches
BIFF8 导出的既有环境问题,已用 git stash 验证在改动前的 HEAD 上同样失败,
与本次改动无关,不在本次范围内处理)。

剩余 669 条例外记录不变,尚未处理;B/C 两档 57 文件仍需逐模块确认迁移或
提出延期理由,本次不扩大范围。

Co-Authored-By: Claude Sonnet 5 <[email protected]>
2026-09-25 21:16:55 +08:00

253 行
11 KiB
JavaScript

const { z } = require("zod");
const { AppError } = require("../utils/AppError");
const { buildBusinessValidationError } = require("../utils/businessValidationError");
const { sendData } = require("../utils/reply");
const { createNotifications } = require("../services/notifications");
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
const UUID_SCHEMA = z.string().uuid();
const QUERY_SCHEMA = z.object({
status: z.enum(["todo", "doing", "done", "cancelled"]).optional(),
scope: z.enum(["mine", "team"]).optional(),
assigneeId: UUID_SCHEMA.optional(),
q: z.string().trim().max(100).optional(),
});
const CREATE_SCHEMA = z.object({
title: z.string().trim().min(1).max(200),
description: z.string().trim().max(2000).nullable().optional(),
assigneeEmployeeId: UUID_SCHEMA.optional(),
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),
priority: z.enum(["low", "normal", "high"]).optional(),
source: z.enum(["manual", "weekly_report"]).optional(),
projectId: UUID_SCHEMA.nullable().optional(),
}).strict();
const PATCH_SCHEMA = z.object({
title: z.string().trim().min(1).max(200).optional(),
description: z.string().trim().max(2000).nullable().optional(),
assigneeEmployeeId: UUID_SCHEMA.optional(),
dueDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),
priority: z.enum(["low", "normal", "high"]).optional(),
status: z.enum(["todo", "doing", "done", "cancelled"]).optional(),
projectId: UUID_SCHEMA.nullable().optional(),
}).strict().refine((value) => Object.keys(value).length > 0, { message: "empty_patch" });
function buildValidationError(details, statusCode = 400) {
return new AppError({ code: "VALID_001", message: "参数校验失败", statusCode, details });
}
function parseBody(schema, body) {
const parsed = schema.safeParse(body ?? {});
if (!parsed.success) {
throw buildValidationError(parsed.error.flatten());
}
return parsed.data;
}
function parseUuid(value, fieldName = "id") {
const parsed = UUID_SCHEMA.safeParse(value);
if (!parsed.success) {
throw buildValidationError({ [fieldName]: "invalid_uuid" });
}
return parsed.data;
}
function mapTodo(row) {
return {
id: row.id,
title: row.title,
description: row.description ?? null,
assigneeEmployeeId: row.assignee_employee_id,
createdBy: row.created_by,
dueDate: row.due_date?.toISOString?.()?.slice(0, 10) ?? null,
priority: row.priority,
status: row.status,
source: row.source,
projectId: row.project_id ?? null,
createdAt: row.created_at?.toISOString?.() ?? null,
updatedAt: row.updated_at?.toISOString?.() ?? null,
completedAt: row.completed_at?.toISOString?.() ?? null,
assignee: row.assignee ? { id: row.assignee.id, employeeNo: row.assignee.employee_no, name: row.assignee.name } : null,
creator: row.creator ? { id: row.creator.id, employeeNo: row.creator.employee_no, name: row.creator.name } : null,
project: row.project ? { id: row.project.id, projectNo: row.project.project_no, name: row.project.name } : null,
};
}
async function ensureFeatureEnabled(fastify, request) {
const gate = await evaluateFeatureFlag({
prisma: fastify.prisma,
config: fastify.config,
flagKey: FEATURE_FLAG_KEYS.todoBoard,
departmentId: request.employee.department_id ?? null,
strictDepartment: false,
});
if (!gate.enabled) {
throw buildBusinessValidationError(
"todo.feature_disabled",
{ featureFlag: "todo_board_v1_disabled", reason: gate.reason },
409,
);
}
}
function canManageTeamTodos(fastify, employee) {
return fastify.hasPermission(employee, "report.dashboard.view") || fastify.hasPermission(employee, "system.users");
}
async function todosRoutes(fastify) {
fastify.get("/todos", { preHandler: fastify.authenticate }, async (request, reply) => {
await ensureFeatureEnabled(fastify, request);
const parsed = QUERY_SCHEMA.safeParse(request.query ?? {});
if (!parsed.success) {
throw buildValidationError(parsed.error.flatten());
}
const query = parsed.data;
const canManage = canManageTeamTodos(fastify, request.employee);
const scope = query.scope ?? "mine";
const where = {
AND: [
query.status ? { status: query.status } : {},
query.q
? {
OR: [
{ title: { contains: query.q, mode: "insensitive" } },
{ description: { contains: query.q, mode: "insensitive" } },
],
}
: {},
scope === "team" && canManage
? query.assigneeId
? { assignee_employee_id: query.assigneeId }
: {}
: {
OR: [{ assignee_employee_id: request.employee.id }, { created_by: request.employee.id }],
},
],
};
const rows = await fastify.prisma.todoItem.findMany({
where,
orderBy: [{ status: "asc" }, { priority: "desc" }, { due_date: "asc" }, { updated_at: "desc" }],
include: {
assignee: { select: { id: true, employee_no: true, name: true } },
creator: { select: { id: true, employee_no: true, name: true } },
project: { select: { id: true, project_no: true, name: true } },
},
});
return sendData(reply, request, { items: rows.map(mapTodo) });
});
fastify.post("/todos", { preHandler: fastify.authenticate }, async (request, reply) => {
await ensureFeatureEnabled(fastify, request);
const body = parseBody(CREATE_SCHEMA, request.body);
const assigneeEmployeeId = body.assigneeEmployeeId ?? request.employee.id;
if (assigneeEmployeeId !== request.employee.id && !canManageTeamTodos(fastify, request.employee)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "report.dashboard.view" } });
}
const created = await fastify.prisma.todoItem.create({
data: {
title: body.title,
description: body.description ?? null,
assignee_employee_id: assigneeEmployeeId,
created_by: request.employee.id,
due_date: body.dueDate ? new Date(`${body.dueDate}T00:00:00.000Z`) : null,
priority: body.priority ?? "normal",
status: "todo",
source: body.source ?? "manual",
project_id: body.projectId ?? null,
},
include: {
assignee: { select: { id: true, employee_no: true, name: true } },
creator: { select: { id: true, employee_no: true, name: true } },
project: { select: { id: true, project_no: true, name: true } },
},
});
if (assigneeEmployeeId !== request.employee.id) {
await createNotifications(fastify.prisma, {
recipientEmployeeIds: [assigneeEmployeeId],
type: "todo.assigned",
title: `新的待办:${created.title}`,
body: created.description ?? "请到待办页查看详情。",
targetType: "todo_item",
targetId: created.id,
});
}
return reply.code(201).send({ requestId: request.id, data: { item: mapTodo(created) } });
});
fastify.patch("/todos/:id", { preHandler: fastify.authenticate }, async (request, reply) => {
await ensureFeatureEnabled(fastify, request);
const todoId = parseUuid(request.params?.id);
const body = parseBody(PATCH_SCHEMA, request.body);
const current = await fastify.prisma.todoItem.findUnique({ where: { id: todoId } });
if (!current) {
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
}
const canManage = canManageTeamTodos(fastify, request.employee);
if (!(canManage || current.assignee_employee_id === request.employee.id || current.created_by === request.employee.id)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "todo.write" } });
}
if (body.assigneeEmployeeId && body.assigneeEmployeeId !== request.employee.id && !canManage) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "report.dashboard.view" } });
}
const updated = await fastify.prisma.todoItem.update({
where: { id: todoId },
data: {
...(body.title !== undefined ? { title: body.title } : {}),
...(body.description !== undefined ? { description: body.description ?? null } : {}),
...(body.assigneeEmployeeId !== undefined ? { assignee_employee_id: body.assigneeEmployeeId } : {}),
...(body.dueDate !== undefined ? { due_date: body.dueDate ? new Date(`${body.dueDate}T00:00:00.000Z`) : null } : {}),
...(body.priority !== undefined ? { priority: body.priority } : {}),
...(body.projectId !== undefined ? { project_id: body.projectId ?? null } : {}),
...(body.status !== undefined ? { status: body.status, completed_at: body.status === "done" ? new Date() : body.status === "cancelled" ? current.completed_at : null } : {}),
},
include: {
assignee: { select: { id: true, employee_no: true, name: true } },
creator: { select: { id: true, employee_no: true, name: true } },
project: { select: { id: true, project_no: true, name: true } },
},
});
return sendData(reply, request, { item: mapTodo(updated) });
});
fastify.post("/todos/:id/complete", { preHandler: fastify.authenticate }, async (request, reply) => {
await ensureFeatureEnabled(fastify, request);
const todoId = parseUuid(request.params?.id);
const current = await fastify.prisma.todoItem.findUnique({ where: { id: todoId } });
if (!current) {
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
}
if (!(canManageTeamTodos(fastify, request.employee) || current.assignee_employee_id === request.employee.id || current.created_by === request.employee.id)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "todo.complete" } });
}
const updated = await fastify.prisma.todoItem.update({
where: { id: todoId },
data: { status: "done", completed_at: new Date() },
include: { assignee: { select: { id: true, employee_no: true, name: true } }, creator: { select: { id: true, employee_no: true, name: true } }, project: { select: { id: true, project_no: true, name: true } } },
});
return sendData(reply, request, { item: mapTodo(updated) });
});
fastify.post("/todos/:id/cancel", { preHandler: fastify.authenticate }, async (request, reply) => {
await ensureFeatureEnabled(fastify, request);
const todoId = parseUuid(request.params?.id);
const current = await fastify.prisma.todoItem.findUnique({ where: { id: todoId } });
if (!current) {
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
}
if (!(canManageTeamTodos(fastify, request.employee) || current.assignee_employee_id === request.employee.id || current.created_by === request.employee.id)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "todo.cancel" } });
}
const updated = await fastify.prisma.todoItem.update({
where: { id: todoId },
data: { status: "cancelled", completed_at: null },
include: { assignee: { select: { id: true, employee_no: true, name: true } }, creator: { select: { id: true, employee_no: true, name: true } }, project: { select: { id: true, project_no: true, name: true } } },
});
return sendData(reply, request, { item: mapTodo(updated) });
});
}
module.exports = todosRoutes;