R55 A1-A6:报销统计仪表盘与批量审批

这个提交包含在:
2026-04-08 09:53:47 +08:00
父节点 3e694fa60c
当前提交 40c3b7632a
共修改 12 个文件,包含 2668 行新增和 544 行删除
@@ -0,0 +1,226 @@
const Fastify = require("fastify");
const reimbursementRoutes = require("../../../src/routes/reimbursements");
const { AppError } = require("../../../src/utils/AppError");
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
async function buildApp(options = {}) {
const app = Fastify();
const actor = options.actor ?? {
id: ACTOR_ID,
roleCodes: ["manager"],
permissionCodes: ["expense.view_all"],
};
const queryRaw =
options.queryRaw ??
vi
.fn()
.mockResolvedValueOnce([
{ status: "draft", count: 2, total_amount: "100.00" },
{ status: "paid", count: 1, total_amount: "80.00" },
])
.mockResolvedValueOnce([{ avg_processing_days: 3.5 }]);
app.decorate("authenticate", async (request) => {
request.employee = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissionCodes = employee.permissionCodes ?? [];
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = actor;
if (!app.hasPermission(actor, permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("config", { appTimezone: "Asia/Shanghai" });
app.decorate("prisma", {
$queryRaw: queryRaw,
});
app.setErrorHandler((error, request, reply) => {
reply.status(error.statusCode || 500).send({
requestId: request.id,
error: {
code: error.code || "SYS_001",
message: error.message,
details: error.details ?? null,
},
});
});
await app.register(reimbursementRoutes, { prefix: "/api" });
return { app, queryRaw };
}
describe("reimbursements stats routes", () => {
it("returns summary with filters and zero-filled status buckets", async () => {
const { app, queryRaw } = await buildApp();
const response = await app.inject({
method: "GET",
url: `/api/reimbursements/stats/summary?dateFrom=2026-01-01&dateTo=2026-03-31&departmentId=${DEPARTMENT_ID}`,
});
expect(response.statusCode).toBe(200);
expect(queryRaw).toHaveBeenCalledTimes(2);
expect(queryRaw.mock.calls[0][0].values).toEqual(
expect.arrayContaining([
new Date("2026-01-01T00:00:00.000Z"),
new Date("2026-03-31T00:00:00.000Z"),
DEPARTMENT_ID,
ACTOR_ID,
]),
);
expect(response.json().data).toEqual({
totalCount: 3,
totalAmount: "180.00",
byStatus: {
draft: { count: 2, totalAmount: "100.00" },
reviewing: { count: 0, totalAmount: "0.00" },
approved: { count: 0, totalAmount: "0.00" },
paid: { count: 1, totalAmount: "80.00" },
rejected: { count: 0, totalAmount: "0.00" },
cancelled: { count: 0, totalAmount: "0.00" },
},
avgProcessingDays: 3.5,
});
await app.close();
});
it("returns empty summary when there is no matching data", async () => {
const { app } = await buildApp({
queryRaw: vi.fn().mockResolvedValueOnce([]).mockResolvedValueOnce([{ avg_processing_days: null }]),
});
const response = await app.inject({
method: "GET",
url: "/api/reimbursements/stats/summary",
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toMatchObject({
totalCount: 0,
totalAmount: "0.00",
avgProcessingDays: null,
byStatus: {
draft: { count: 0, totalAmount: "0.00" },
reviewing: { count: 0, totalAmount: "0.00" },
approved: { count: 0, totalAmount: "0.00" },
paid: { count: 0, totalAmount: "0.00" },
rejected: { count: 0, totalAmount: "0.00" },
cancelled: { count: 0, totalAmount: "0.00" },
},
});
await app.close();
});
it("returns monthly trends with count and paid metrics", async () => {
const { app } = await buildApp({
queryRaw: vi.fn().mockResolvedValue([
{
period_start: new Date("2026-02-01T00:00:00.000Z"),
count: 4,
amount: "220.00",
paid_count: 2,
paid_amount: "120.00",
},
]),
});
const response = await app.inject({
method: "GET",
url: "/api/reimbursements/stats/trend?granularity=month",
});
expect(response.statusCode).toBe(200);
expect(response.json().data.items).toEqual([
{
period: "2026-02",
count: 4,
amount: "220.00",
paidCount: 2,
paidAmount: "120.00",
},
]);
await app.close();
});
it("returns top expense types and approval bottlenecks", async () => {
const queryRaw = vi
.fn()
.mockResolvedValueOnce([
{
expense_type_id: "type-1",
expense_type_name: "差旅交通",
count: 5,
total_amount: "520.00",
},
])
.mockResolvedValueOnce([
{
assignee_id: null,
assignee_role: "manager",
assignee_name: null,
pending_count: 3,
oldest_pending_days: 5,
},
]);
const { app } = await buildApp({ queryRaw });
const topResponse = await app.inject({
method: "GET",
url: "/api/reimbursements/stats/top-expense-types?limit=5",
});
const bottleneckResponse = await app.inject({
method: "GET",
url: "/api/reimbursements/stats/approval-bottleneck",
});
expect(topResponse.statusCode).toBe(200);
expect(topResponse.json().data.items).toEqual([
{
expenseTypeId: "type-1",
expenseTypeName: "差旅交通",
count: 5,
totalAmount: "520.00",
},
]);
expect(bottleneckResponse.statusCode).toBe(200);
expect(bottleneckResponse.json().data.items).toEqual([
{
assigneeId: null,
assigneeName: "主管",
pendingCount: 3,
oldestPendingDays: 5,
},
]);
await app.close();
});
it("rejects users without expense.view_all permission", async () => {
const { app } = await buildApp({
actor: {
id: ACTOR_ID,
roleCodes: ["employee"],
permissionCodes: ["expense.view_own"],
},
queryRaw: vi.fn(),
});
const response = await app.inject({
method: "GET",
url: "/api/reimbursements/stats/summary",
});
expect(response.statusCode).toBe(403);
await app.close();
});
});
@@ -0,0 +1,351 @@
const Fastify = require("fastify");
const workflowRoutes = require("../../../src/routes/workflow");
const { AppError } = require("../../../src/utils/AppError");
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
function buildTask(taskId, overrides = {}) {
return {
id: taskId,
instance_id: taskId,
step_id: "approval_1_manager",
step_name: "经理审批",
assignee_id: ACTOR_ID,
assignee_role: null,
status: "pending",
outcome: null,
comment: null,
created_at: new Date("2026-04-08T08:00:00.000Z"),
completed_at: null,
completed_by: null,
...overrides,
};
}
function buildWorkflowInstance(taskId, entityType = "reimbursement") {
return {
id: taskId,
entity_type: entityType,
entity_id: taskId,
current_step_id: "approval_1_manager",
context_data: {},
workflow_definition: {
definition_json: {
steps: [
{
id: "approval_1_manager",
name: "经理审批",
assignee_rule: { type: "role", value: "manager" },
},
],
},
},
};
}
async function buildApp(options = {}) {
const app = Fastify();
const actor = options.actor ?? {
id: ACTOR_ID,
roleCodes: ["manager"],
permissionCodes: ["expense.approve"],
};
const state = {
tasks: new Map(
(options.tasks ?? [
buildTask("11111111-1111-4111-8111-111111111111"),
buildTask("22222222-2222-4222-8222-222222222222", { status: "completed", outcome: "approved" }),
buildTask("33333333-3333-4333-8333-333333333333"),
buildTask("44444444-4444-4444-8444-444444444444"),
]).map((item) => [item.id, { ...item }]),
),
instances: new Map(
(options.instances ?? [
buildWorkflowInstance("11111111-1111-4111-8111-111111111111", "reimbursement"),
buildWorkflowInstance("22222222-2222-4222-8222-222222222222", "reimbursement"),
buildWorkflowInstance("33333333-3333-4333-8333-333333333333", "leave"),
buildWorkflowInstance("44444444-4444-4444-8444-444444444444", "reimbursement"),
]).map((item) => [item.id, { ...item }]),
),
history: [],
};
const tx = {
$queryRaw: vi.fn(async (_strings, ...values) => {
const taskId = String(values[0] ?? "");
const task = state.tasks.get(taskId);
return task ? [{ ...task }] : [];
}),
workflowInstance: {
findUnique: vi.fn(async ({ where }) => {
return state.instances.get(String(where.id)) ?? null;
}),
update: vi.fn(async ({ where, data }) => {
const current = state.instances.get(String(where.id));
if (!current) return null;
state.instances.set(String(where.id), { ...current, ...data });
return state.instances.get(String(where.id));
}),
},
workflowTask: {
update: vi.fn(async ({ where, data }) => {
if (options.updateErrorTaskId && where.id === options.updateErrorTaskId) {
throw new Error("update_failed");
}
const current = state.tasks.get(where.id);
if (!current) return null;
state.tasks.set(where.id, { ...current, ...data });
return state.tasks.get(where.id);
}),
updateMany: vi.fn(async () => ({ count: 0 })),
create: vi.fn(async () => {
throw new Error("unexpected_create");
}),
},
workflowHistory: {
create: vi.fn(async ({ data }) => {
state.history.push(data);
return { id: `history-${state.history.length}` };
}),
count: vi.fn(async () => 0),
},
reimbursementForm: {
update: vi.fn(async () => ({})),
findUnique: vi.fn(async () => null),
},
leaveRequest: {
findUnique: vi.fn(async () => null),
update: vi.fn(async () => ({})),
},
leaveLedger: {
findFirst: vi.fn(async () => null),
},
purchaseRequest: {
update: vi.fn(async () => ({})),
},
travelRequest: {
update: vi.fn(async () => ({})),
},
notificationChannel: {
findMany: vi.fn(async () => []),
},
employee: {
findMany: vi.fn(async () => []),
findUnique: vi.fn(async () => ({
id: "target",
status: "active",
roles: [{ role_code: "manager" }],
})),
},
notificationDelivery: {
create: vi.fn(async () => ({ id: "delivery-1" })),
update: vi.fn(async () => ({})),
},
};
const prisma = {
$transaction: vi.fn(async (callback) => callback(tx)),
};
app.decorate("prisma", prisma);
app.decorate("config", {
imNotifierEnabled: false,
emailEnabled: false,
});
app.decorate("authenticate", async (request) => {
request.employee = actor;
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = actor;
const permissionCodes = actor.permissionCodes ?? [];
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("assertEntityPermission", () => {});
app.setErrorHandler((error, request, reply) => {
reply.status(error.statusCode || 500).send({
requestId: request.id,
error: {
code: error.code || "SYS_001",
message: error.message,
details: error.details ?? null,
},
});
});
await app.register(workflowRoutes, { prefix: "/api" });
return { app, prisma, state, tx };
}
describe("workflow batch routes", () => {
it("approves reimbursement tasks and skips already processed ones", async () => {
const { app, prisma, state } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/workflow/batch-approve",
payload: {
taskIds: [
"11111111-1111-4111-8111-111111111111",
"22222222-2222-4222-8222-222222222222",
],
},
});
expect(response.statusCode).toBe(200);
expect(prisma.$transaction).toHaveBeenCalledTimes(2);
expect(response.json().data).toEqual({
results: [
{
taskId: "11111111-1111-4111-8111-111111111111",
outcome: "approved",
},
{
taskId: "22222222-2222-4222-8222-222222222222",
outcome: "skipped",
reason: "already_processed",
},
],
summary: {
approved: 1,
rejected: 0,
skipped: 1,
errored: 0,
},
});
expect(state.tasks.get("11111111-1111-4111-8111-111111111111").status).toBe("completed");
await app.close();
});
it("rejects reimbursement tasks with required shared comment", async () => {
const { app, state } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/workflow/batch-reject",
payload: {
taskIds: ["44444444-4444-4444-8444-444444444444"],
comment: "材料不完整,请补充说明后重新提交。",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
results: [
{
taskId: "44444444-4444-4444-8444-444444444444",
outcome: "rejected",
},
],
summary: {
approved: 0,
rejected: 1,
skipped: 0,
errored: 0,
},
});
expect(state.tasks.get("44444444-4444-4444-8444-444444444444").status).toBe("rejected");
const invalidResponse = await app.inject({
method: "POST",
url: "/api/workflow/batch-reject",
payload: {
taskIds: ["44444444-4444-4444-8444-444444444444"],
comment: " ",
},
});
expect(invalidResponse.statusCode).toBe(400);
await app.close();
});
it("does not roll back successful tasks when one task fails or has unsupported entity type", async () => {
const { app, state } = await buildApp({
updateErrorTaskId: "44444444-4444-4444-8444-444444444444",
});
const response = await app.inject({
method: "POST",
url: "/api/workflow/batch-approve",
payload: {
taskIds: [
"11111111-1111-4111-8111-111111111111",
"33333333-3333-4333-8333-333333333333",
"44444444-4444-4444-8444-444444444444",
],
},
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
results: [
{
taskId: "11111111-1111-4111-8111-111111111111",
outcome: "approved",
},
{
taskId: "33333333-3333-4333-8333-333333333333",
outcome: "error",
reason: "VALID_001: 参数校验失败",
},
{
taskId: "44444444-4444-4444-8444-444444444444",
outcome: "error",
reason: "update_failed",
},
],
summary: {
approved: 1,
rejected: 0,
skipped: 0,
errored: 2,
},
});
expect(state.tasks.get("11111111-1111-4111-8111-111111111111").status).toBe("completed");
expect(state.tasks.get("44444444-4444-4444-8444-444444444444").status).toBe("pending");
await app.close();
});
it("rejects oversized batch payloads and missing permissions", async () => {
const { app } = await buildApp();
const oversizedPayload = {
taskIds: Array.from({ length: 51 }, (_, index) =>
`00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,
),
};
const invalidResponse = await app.inject({
method: "POST",
url: "/api/workflow/batch-approve",
payload: oversizedPayload,
});
expect(invalidResponse.statusCode).toBe(400);
await app.close();
const noPermission = await buildApp({
actor: {
id: ACTOR_ID,
roleCodes: ["employee"],
permissionCodes: ["expense.view_own"],
},
});
const forbiddenResponse = await noPermission.app.inject({
method: "POST",
url: "/api/workflow/batch-approve",
payload: {
taskIds: ["11111111-1111-4111-8111-111111111111"],
},
});
expect(forbiddenResponse.statusCode).toBe(403);
await noPermission.app.close();
});
});