文件
hyb-oa/server/src/routes/todos.js
T

248 行
11 KiB
JavaScript

const { z } = require("zod");
const { AppError } = require("../utils/AppError");
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 buildValidationError({ 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;