feat: 完成P6-P8后端能力与P9路由重构(V1-V2,D1,D3,B1-B2,B4,I1-I4,P9A2-P9A3)

这个提交包含在:
2026-02-10 11:28:28 +08:00
父节点 bec21e1b38
当前提交 6bc09f557b
共修改 33 个文件,包含 3467 行新增和 13 行删除
+280
查看文件
@@ -0,0 +1,280 @@
const { z } = require("zod");
const { AppError } = require("../utils/AppError");
const { sendData } = require("../utils/reply");
const { buildAuditLogData } = require("../utils/audit");
const BUDGET_CREATE_SCHEMA = z.object({
code: z.string().trim().min(2).max(32),
name: z.string().trim().min(1).max(120),
departmentId: z.string().uuid().nullable().optional(),
periodStart: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
periodEnd: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
allocatedAmount: z.string().regex(/^\d+(?:\.\d{1,2})?$/),
warningThresholdPercent: z.coerce.number().int().min(1).max(100).optional(),
});
const BUDGET_PATCH_SCHEMA = z
.object({
name: z.string().trim().min(1).max(120).optional(),
allocatedAmount: z.string().regex(/^\d+(?:\.\d{1,2})?$/).optional(),
warningThresholdPercent: z.coerce.number().int().min(1).max(100).optional(),
status: z.enum(["active", "archived"]).optional(),
})
.strict();
const BUDGET_LIST_QUERY_SCHEMA = z.object({
status: z.enum(["active", "archived"]).optional(),
departmentId: z.string().uuid().optional(),
page: z.coerce.number().int().min(1).optional(),
pageSize: z.coerce.number().int().min(1).max(100).optional(),
});
function toDate(value) {
return new Date(`${value}T00:00:00.000Z`);
}
function toMoneyString(value) {
if (value == null) {
return "0.00";
}
const numeric = Number(value);
return Number.isFinite(numeric) ? numeric.toFixed(2) : "0.00";
}
function mapBudget(item) {
const allocated = Number(item.allocated_amount ?? 0);
const used = Number(item.used_amount ?? 0);
const remaining = allocated - used;
return {
id: item.id,
code: item.code,
name: item.name,
departmentId: item.department_id ?? null,
status: item.status,
periodStart: item.period_start?.toISOString?.()?.slice(0, 10) ?? null,
periodEnd: item.period_end?.toISOString?.()?.slice(0, 10) ?? null,
allocatedAmount: toMoneyString(item.allocated_amount),
usedAmount: toMoneyString(item.used_amount),
remainingAmount: toMoneyString(remaining),
warningThresholdPercent: item.warning_threshold_percent,
archivedAt: item.archived_at?.toISOString?.() ?? null,
createdAt: item.created_at?.toISOString?.() ?? null,
updatedAt: item.updated_at?.toISOString?.() ?? null,
};
}
function parseBudgetId(value) {
const parsed = z.string().uuid().safeParse(value);
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { id: "invalid_uuid" },
});
}
return parsed.data;
}
async function budgetsRoutes(fastify) {
fastify.get(
"/budgets",
{
preHandler: fastify.requirePermission("budget.view"),
},
async (request, reply) => {
const parsed = BUDGET_LIST_QUERY_SCHEMA.safeParse(request.query ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
const query = parsed.data;
const page = query.page ?? 1;
const pageSize = query.pageSize ?? 20;
const skip = (page - 1) * pageSize;
const where = {
...(query.status ? { status: query.status } : {}),
...(query.departmentId ? { department_id: query.departmentId } : {}),
};
const [items, total] = await Promise.all([
fastify.prisma.budgetPool.findMany({
where,
orderBy: [{ period_start: "desc" }, { created_at: "desc" }],
skip,
take: pageSize,
}),
fastify.prisma.budgetPool.count({ where }),
]);
return sendData(reply, request, {
page,
pageSize,
total,
items: items.map(mapBudget),
});
},
);
fastify.post(
"/budgets",
{
preHandler: fastify.requirePermission("budget.manage"),
},
async (request, reply) => {
const parsed = BUDGET_CREATE_SCHEMA.safeParse(request.body ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
const body = parsed.data;
const start = toDate(body.periodStart);
const end = toDate(body.periodEnd);
if (start > end) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { periodEnd: "must_be_after_periodStart" },
});
}
const created = await fastify.prisma.budgetPool.create({
data: {
code: body.code.toUpperCase(),
name: body.name,
department_id: body.departmentId ?? null,
status: "active",
period_start: start,
period_end: end,
allocated_amount: body.allocatedAmount,
used_amount: "0.00",
warning_threshold_percent: body.warningThresholdPercent ?? 80,
created_by: request.employee.id,
updated_by: request.employee.id,
},
});
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "BUDGET_CREATED",
targetType: "budget_pool",
targetId: created.id,
extra: {
code: created.code,
allocatedAmount: created.allocated_amount,
},
}),
});
return sendData(reply, request, mapBudget(created));
},
);
fastify.patch(
"/budgets/:id",
{
preHandler: fastify.requirePermission("budget.manage"),
},
async (request, reply) => {
const budgetId = parseBudgetId(request.params?.id);
const parsed = BUDGET_PATCH_SCHEMA.safeParse(request.body ?? {});
if (!parsed.success) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: parsed.error.flatten(),
});
}
if (!Object.keys(parsed.data).length) {
throw new AppError({
code: "VALID_001",
message: "参数校验失败",
statusCode: 400,
details: { body: "empty_patch" },
});
}
const patch = parsed.data;
const updated = await fastify.prisma.budgetPool.update({
where: { id: budgetId },
data: {
...(patch.name != null ? { name: patch.name } : {}),
...(patch.allocatedAmount != null ? { allocated_amount: patch.allocatedAmount } : {}),
...(patch.warningThresholdPercent != null
? { warning_threshold_percent: patch.warningThresholdPercent }
: {}),
...(patch.status ? { status: patch.status } : {}),
...(patch.status === "archived" ? { archived_at: new Date() } : {}),
updated_by: request.employee.id,
},
});
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "BUDGET_UPDATED",
targetType: "budget_pool",
targetId: budgetId,
extra: {
patch,
},
}),
});
return sendData(reply, request, mapBudget(updated));
},
);
fastify.post(
"/budgets/:id/archive",
{
preHandler: fastify.requirePermission("budget.manage"),
},
async (request, reply) => {
const budgetId = parseBudgetId(request.params?.id);
const updated = await fastify.prisma.budgetPool.update({
where: { id: budgetId },
data: {
status: "archived",
archived_at: new Date(),
updated_by: request.employee.id,
},
});
await fastify.prisma.auditLog.create({
data: buildAuditLogData(request, {
actorId: request.employee.id,
action: "BUDGET_ARCHIVED",
targetType: "budget_pool",
targetId: budgetId,
extra: {
code: updated.code,
},
}),
});
return sendData(reply, request, mapBudget(updated));
},
);
}
module.exports = budgetsRoutes;