R56 A1-A6:费用标准管控
这个提交包含在:
@@ -0,0 +1,457 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const expenseStandardsRoutes = require("../../../src/routes/expenseStandards");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const EXPENSE_TYPE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const DEPARTMENT_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const STANDARD_ID = "33333333-3333-4333-8333-333333333333";
|
||||
|
||||
function cloneStandard(item) {
|
||||
return {
|
||||
...item,
|
||||
created_at: new Date(item.created_at),
|
||||
updated_at: new Date(item.updated_at),
|
||||
expense_type: item.expense_type ? { ...item.expense_type } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildStandard(overrides = {}) {
|
||||
return {
|
||||
id: STANDARD_ID,
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "日常交通费上限",
|
||||
max_amount: "120.00",
|
||||
per_unit: "item",
|
||||
control_mode: "warn",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
enabled: true,
|
||||
note: "默认提示",
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
updated_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
expense_type: {
|
||||
id: EXPENSE_TYPE_ID,
|
||||
code: "traffic",
|
||||
name: "交通费",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function findDuplicate(items, candidate, currentId = null) {
|
||||
return items.find((item) => {
|
||||
if (currentId && item.id === currentId) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
item.expense_type_id === candidate.expense_type_id &&
|
||||
item.scope_type === candidate.scope_type &&
|
||||
(item.scope_key ?? null) === (candidate.scope_key ?? null)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function makeSelectStandard(state, item) {
|
||||
const expenseType = state.expenseTypes.find((record) => record.id === item.expense_type_id) ?? null;
|
||||
return {
|
||||
...item,
|
||||
expense_type: expenseType
|
||||
? {
|
||||
id: expenseType.id,
|
||||
code: expenseType.code,
|
||||
name: expenseType.name,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: ACTOR_ID,
|
||||
permissionCodes: ["system.settings"],
|
||||
department_id: DEPARTMENT_ID,
|
||||
};
|
||||
|
||||
const state = {
|
||||
expenseTypes: options.expenseTypes ?? [
|
||||
{
|
||||
id: EXPENSE_TYPE_ID,
|
||||
code: "traffic",
|
||||
name: "交通费",
|
||||
},
|
||||
],
|
||||
departments: options.departments ?? [
|
||||
{
|
||||
id: DEPARTMENT_ID,
|
||||
name: "财务部",
|
||||
archived_at: null,
|
||||
},
|
||||
],
|
||||
standards: (options.standards ?? [buildStandard()]).map((item) => cloneStandard(item)),
|
||||
auditLogs: [],
|
||||
};
|
||||
|
||||
function buildPrismaLike(stateRef) {
|
||||
return {
|
||||
expenseStandard: {
|
||||
findMany: vi.fn(async ({ where } = {}) => {
|
||||
return stateRef.standards
|
||||
.filter((item) => {
|
||||
if (where?.expense_type_id && item.expense_type_id !== where.expense_type_id) {
|
||||
return false;
|
||||
}
|
||||
if (where?.scope_type && item.scope_type !== where.scope_type) {
|
||||
return false;
|
||||
}
|
||||
if (typeof where?.enabled === "boolean" && item.enabled !== where.enabled) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map((item) => makeSelectStandard(stateRef, cloneStandard(item)));
|
||||
}),
|
||||
findUnique: vi.fn(async ({ where }) => {
|
||||
const found = stateRef.standards.find((item) => item.id === where.id) ?? null;
|
||||
return found ? makeSelectStandard(stateRef, cloneStandard(found)) : null;
|
||||
}),
|
||||
create: vi.fn(async ({ data }) => {
|
||||
if (findDuplicate(stateRef.standards, data)) {
|
||||
const error = new Error("duplicate");
|
||||
error.code = "P2002";
|
||||
throw error;
|
||||
}
|
||||
|
||||
const record = buildStandard({
|
||||
id: `standard-${stateRef.standards.length + 1}`,
|
||||
expense_type_id: data.expense_type_id,
|
||||
name: data.name,
|
||||
max_amount: data.max_amount,
|
||||
per_unit: data.per_unit,
|
||||
control_mode: data.control_mode,
|
||||
scope_type: data.scope_type,
|
||||
scope_key: data.scope_key ?? null,
|
||||
enabled: data.enabled,
|
||||
note: data.note ?? null,
|
||||
created_at: data.created_at,
|
||||
updated_at: data.updated_at,
|
||||
});
|
||||
stateRef.standards.push(record);
|
||||
return makeSelectStandard(stateRef, cloneStandard(record));
|
||||
}),
|
||||
update: vi.fn(async ({ where, data }) => {
|
||||
const index = stateRef.standards.findIndex((item) => item.id === where.id);
|
||||
if (index < 0) {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
const next = {
|
||||
...stateRef.standards[index],
|
||||
...data,
|
||||
};
|
||||
if (findDuplicate(stateRef.standards, next, where.id)) {
|
||||
const error = new Error("duplicate");
|
||||
error.code = "P2002";
|
||||
throw error;
|
||||
}
|
||||
stateRef.standards[index] = next;
|
||||
return makeSelectStandard(stateRef, cloneStandard(next));
|
||||
}),
|
||||
},
|
||||
expenseType: {
|
||||
findUnique: vi.fn(async ({ where }) => stateRef.expenseTypes.find((item) => item.id === where.id) ?? null),
|
||||
},
|
||||
department: {
|
||||
findUnique: vi.fn(async ({ where }) => stateRef.departments.find((item) => item.id === where.id) ?? null),
|
||||
findMany: vi.fn(async ({ where }) => {
|
||||
const ids = where?.id?.in ?? [];
|
||||
return stateRef.departments.filter((item) => ids.includes(item.id));
|
||||
}),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(async ({ data }) => {
|
||||
stateRef.auditLogs.push(data);
|
||||
return { id: `audit-${stateRef.auditLogs.length}` };
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const prisma = buildPrismaLike(state);
|
||||
prisma.$transaction = vi.fn(async (callback) => {
|
||||
const txState = {
|
||||
expenseTypes: state.expenseTypes.map((item) => ({ ...item })),
|
||||
departments: state.departments.map((item) => ({ ...item })),
|
||||
standards: state.standards.map((item) => cloneStandard(item)),
|
||||
auditLogs: state.auditLogs.map((item) => ({ ...item })),
|
||||
};
|
||||
const tx = buildPrismaLike(txState);
|
||||
const result = await callback(tx);
|
||||
state.expenseTypes = txState.expenseTypes;
|
||||
state.departments = txState.departments;
|
||||
state.standards = txState.standards;
|
||||
state.auditLogs = txState.auditLogs;
|
||||
return result;
|
||||
});
|
||||
|
||||
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("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", {});
|
||||
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(expenseStandardsRoutes, { prefix: "/api" });
|
||||
return { app, state, prisma };
|
||||
}
|
||||
|
||||
describe("expense standards routes", () => {
|
||||
it("lists standards with filters and scope label", async () => {
|
||||
const { app } = await buildApp({
|
||||
standards: [
|
||||
buildStandard(),
|
||||
buildStandard({
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
scope_type: "department",
|
||||
scope_key: DEPARTMENT_ID,
|
||||
control_mode: "block",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/expense-standards?expenseTypeId=${EXPENSE_TYPE_ID}&enabled=true`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const payload = response.json();
|
||||
expect(payload.data.items).toHaveLength(2);
|
||||
expect(payload.data.items[0]).toMatchObject({
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
expenseTypeName: "交通费",
|
||||
scopeLabel: expect.any(String),
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("allows authenticated non-admin to read scoped enabled standards for item editor", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: {
|
||||
id: ACTOR_ID,
|
||||
permissionCodes: ["expense.submit"],
|
||||
department_id: DEPARTMENT_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/expense-standards?expenseTypeId=${EXPENSE_TYPE_ID}&enabled=true`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects broad list read for non-admin users", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: {
|
||||
id: ACTOR_ID,
|
||||
permissionCodes: ["expense.submit"],
|
||||
department_id: DEPARTMENT_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/expense-standards",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("creates a department scoped standard and writes audit log", async () => {
|
||||
const { app, state } = await buildApp({ standards: [] });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/expense-standards",
|
||||
payload: {
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
name: "出差餐补上限",
|
||||
maxAmount: "180.00",
|
||||
perUnit: "day",
|
||||
controlMode: "block",
|
||||
scopeType: "department",
|
||||
scopeKey: DEPARTMENT_ID,
|
||||
note: "财务要求",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(state.standards).toHaveLength(1);
|
||||
expect(state.standards[0]).toMatchObject({
|
||||
scope_type: "department",
|
||||
scope_key: DEPARTMENT_ID,
|
||||
control_mode: "block",
|
||||
per_unit: "day",
|
||||
});
|
||||
expect(state.auditLogs).toHaveLength(1);
|
||||
expect(state.auditLogs[0]).toMatchObject({
|
||||
action: "EXPENSE_STANDARD_CREATED",
|
||||
target_type: "expense_standard",
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects create when expense type does not exist", async () => {
|
||||
const { app } = await buildApp({ standards: [] });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/expense-standards",
|
||||
payload: {
|
||||
expenseTypeId: "55555555-5555-4555-8555-555555555555",
|
||||
name: "无效标准",
|
||||
maxAmount: "50.00",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error.details).toEqual({ expenseTypeId: "not_found" });
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects department scope without scopeKey", async () => {
|
||||
const { app } = await buildApp({ standards: [] });
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/expense-standards",
|
||||
payload: {
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
name: "部门标准",
|
||||
maxAmount: "88.00",
|
||||
scopeType: "department",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error.details).toEqual({ scopeKey: "required_for_department_scope" });
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects duplicate type and scope via unique conflict", async () => {
|
||||
const { app } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/expense-standards",
|
||||
payload: {
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
name: "重复 global",
|
||||
maxAmount: "88.00",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error.details).toEqual({ duplicate: "expense_type_scope_conflict" });
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("updates a standard and writes before/after audit snapshot", async () => {
|
||||
const { app, state } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/expense-standards/${STANDARD_ID}`,
|
||||
payload: {
|
||||
maxAmount: "150.00",
|
||||
controlMode: "block",
|
||||
note: "已升级为阻断",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(state.standards[0]).toMatchObject({
|
||||
max_amount: "150.00",
|
||||
control_mode: "block",
|
||||
note: "已升级为阻断",
|
||||
});
|
||||
expect(state.auditLogs.at(-1)).toMatchObject({
|
||||
action: "EXPENSE_STANDARD_UPDATED",
|
||||
extra: expect.objectContaining({
|
||||
before: expect.any(Object),
|
||||
after: expect.any(Object),
|
||||
}),
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("soft deletes by setting enabled=false and writes delete audit", async () => {
|
||||
const { app, state } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/expense-standards/${STANDARD_ID}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(state.standards[0].enabled).toBe(false);
|
||||
expect(state.auditLogs.at(-1)).toMatchObject({
|
||||
action: "EXPENSE_STANDARD_DELETED",
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("blocks write operations without system.settings permission", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: {
|
||||
id: ACTOR_ID,
|
||||
permissionCodes: ["expense.submit"],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/api/expense-standards",
|
||||
payload: {
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
name: "受限写操作",
|
||||
maxAmount: "30.00",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,363 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
const budgetPool = require("../../../src/services/budgetPool");
|
||||
const feeControl = require("../../../src/services/feeControl");
|
||||
const notifications = require("../../../src/services/notifications");
|
||||
|
||||
const resolveApplicableBudgetPoolByContextMock = vi.fn();
|
||||
const resolveEntityPrecheckMock = vi.fn();
|
||||
const createRiskFlagsFromPrecheckMock = vi.fn();
|
||||
const resolveRecipientsForAssigneeMock = vi.fn();
|
||||
const createNotificationsWithRecordsMock = vi.fn(async () => []);
|
||||
|
||||
const originalResolveApplicableBudgetPoolByContext = budgetPool.resolveApplicableBudgetPoolByContext;
|
||||
const originalResolveEntityPrecheck = feeControl.resolveEntityPrecheck;
|
||||
const originalCreateRiskFlagsFromPrecheck = feeControl.createRiskFlagsFromPrecheck;
|
||||
const originalResolveRecipientsForAssignee = notifications.resolveRecipientsForAssignee;
|
||||
const originalCreateNotificationsWithRecords = notifications.createNotificationsWithRecords;
|
||||
|
||||
budgetPool.resolveApplicableBudgetPoolByContext = resolveApplicableBudgetPoolByContextMock;
|
||||
feeControl.resolveEntityPrecheck = resolveEntityPrecheckMock;
|
||||
feeControl.createRiskFlagsFromPrecheck = createRiskFlagsFromPrecheckMock;
|
||||
notifications.resolveRecipientsForAssignee = resolveRecipientsForAssigneeMock;
|
||||
notifications.createNotificationsWithRecords = createNotificationsWithRecordsMock;
|
||||
|
||||
delete require.cache[require.resolve("../../../src/routes/reimbursements")];
|
||||
const reimbursementRoutes = require("../../../src/routes/reimbursements");
|
||||
|
||||
const REIMBURSEMENT_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const DEPARTMENT_ID = "33333333-3333-4333-8333-333333333333";
|
||||
|
||||
function buildPrecheck(overrides = {}) {
|
||||
return {
|
||||
entityType: "reimbursement",
|
||||
entityId: REIMBURSEMENT_ID,
|
||||
decision: "pass",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [],
|
||||
nextActions: ["可直接提交"],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: EMPLOYEE_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
roleCodes: [],
|
||||
permissionCodes: ["expense.submit"],
|
||||
};
|
||||
const reimbursement = options.reimbursement ?? {
|
||||
id: REIMBURSEMENT_ID,
|
||||
owner_id: EMPLOYEE_ID,
|
||||
submitter_id: EMPLOYEE_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
reimbursement_date: new Date("2026-04-08T00:00:00.000Z"),
|
||||
status: "draft",
|
||||
form_number: "BX-20260408-001",
|
||||
total_amount: "180.00",
|
||||
};
|
||||
const state = {
|
||||
workflowInstanceCreatePayload: null,
|
||||
};
|
||||
|
||||
const tx = {
|
||||
$queryRaw: vi.fn(async () => [reimbursement]),
|
||||
workflowInstance: {
|
||||
findFirst: vi.fn(async () => null),
|
||||
create: vi.fn(async ({ data, select }) => {
|
||||
state.workflowInstanceCreatePayload = data;
|
||||
return {
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
current_step_id: data.current_step_id,
|
||||
...(select?.current_step_id ? {} : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
invoicePool: {
|
||||
count: vi.fn(async () => 1),
|
||||
},
|
||||
budgetLedgerEntry: {
|
||||
create: vi.fn(async () => ({ id: "budget-ledger-1" })),
|
||||
},
|
||||
budgetPool: {
|
||||
update: vi.fn(async () => ({ id: "budget-pool-1" })),
|
||||
},
|
||||
approvalRule: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: "55555555-5555-4555-8555-555555555555",
|
||||
level1_role: "finance",
|
||||
level2_role: null,
|
||||
level3_role: null,
|
||||
priority: 1,
|
||||
})),
|
||||
},
|
||||
workflowDefinition: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: "66666666-6666-4666-8666-666666666666",
|
||||
})),
|
||||
},
|
||||
reimbursementForm: {
|
||||
update: vi.fn(async () => ({
|
||||
id: reimbursement.id,
|
||||
})),
|
||||
},
|
||||
workflowTask: {
|
||||
create: vi.fn(async () => ({
|
||||
id: "77777777-7777-4777-8777-777777777777",
|
||||
assignee_id: null,
|
||||
assignee_role: "finance",
|
||||
})),
|
||||
},
|
||||
workflowHistory: {
|
||||
create: vi.fn(async () => ({ id: "history-1" })),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(async () => ({ id: "audit-1" })),
|
||||
},
|
||||
};
|
||||
|
||||
const prisma = {
|
||||
$transaction: vi.fn(async (callback) => callback(tx)),
|
||||
reimbursementForm: {
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: reimbursement.id,
|
||||
form_number: reimbursement.form_number,
|
||||
total_amount: reimbursement.total_amount,
|
||||
owner: {
|
||||
id: EMPLOYEE_ID,
|
||||
name: "申请人",
|
||||
},
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
budgetControlMode: "warn",
|
||||
imNotifierEnabled: false,
|
||||
emailEnabled: false,
|
||||
});
|
||||
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee?.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
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.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, prisma, tx, state };
|
||||
}
|
||||
|
||||
describe("reimbursements routes expense standard integration", () => {
|
||||
afterAll(() => {
|
||||
budgetPool.resolveApplicableBudgetPoolByContext = originalResolveApplicableBudgetPoolByContext;
|
||||
feeControl.resolveEntityPrecheck = originalResolveEntityPrecheck;
|
||||
feeControl.createRiskFlagsFromPrecheck = originalCreateRiskFlagsFromPrecheck;
|
||||
notifications.resolveRecipientsForAssignee = originalResolveRecipientsForAssignee;
|
||||
notifications.createNotificationsWithRecords = originalCreateNotificationsWithRecords;
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
resolveApplicableBudgetPoolByContextMock.mockResolvedValue(null);
|
||||
createRiskFlagsFromPrecheckMock.mockResolvedValue([]);
|
||||
resolveRecipientsForAssigneeMock.mockResolvedValue([]);
|
||||
});
|
||||
|
||||
it("returns standardChecks from reimbursement precheck", async () => {
|
||||
resolveEntityPrecheckMock.mockResolvedValue(
|
||||
buildPrecheck({
|
||||
decision: "warn",
|
||||
standardChecks: [
|
||||
{
|
||||
itemId: "item-1",
|
||||
expenseTypeId: "88888888-8888-4888-8888-888888888888",
|
||||
expenseTypeName: "交通费",
|
||||
amount: "180.00",
|
||||
standardId: "99999999-9999-4999-8999-999999999999",
|
||||
standardName: "交通费上限",
|
||||
maxAmount: "120.00",
|
||||
perUnit: "item",
|
||||
controlMode: "warn",
|
||||
scopeType: "global",
|
||||
scopeKey: null,
|
||||
exceeded: true,
|
||||
exceededAmount: "60.00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const { app } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/reimbursements/${REIMBURSEMENT_ID}/precheck`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.standardChecks).toEqual([
|
||||
expect.objectContaining({
|
||||
itemId: "item-1",
|
||||
controlMode: "warn",
|
||||
exceededAmount: "60.00",
|
||||
}),
|
||||
]);
|
||||
expect(resolveEntityPrecheckMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
entityType: "reimbursement",
|
||||
entityId: REIMBURSEMENT_ID,
|
||||
actorDepartmentId: DEPARTMENT_ID,
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("blocks submit with 400 and standardViolations when block standard is exceeded", async () => {
|
||||
resolveEntityPrecheckMock.mockResolvedValue(
|
||||
buildPrecheck({
|
||||
decision: "block",
|
||||
blockingReasons: [
|
||||
{
|
||||
code: "expense_standard_blocked",
|
||||
title: "费用标准超限",
|
||||
detail: "交通费超出上限",
|
||||
},
|
||||
],
|
||||
standardChecks: [
|
||||
{
|
||||
itemId: "item-block",
|
||||
expenseTypeId: "88888888-8888-4888-8888-888888888888",
|
||||
expenseTypeName: "交通费",
|
||||
amount: "260.00",
|
||||
standardId: "99999999-9999-4999-8999-999999999999",
|
||||
standardName: "交通费阻断上限",
|
||||
maxAmount: "120.00",
|
||||
perUnit: "item",
|
||||
controlMode: "block",
|
||||
scopeType: "global",
|
||||
scopeKey: null,
|
||||
exceeded: true,
|
||||
exceededAmount: "140.00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const { app, tx } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/reimbursements/${REIMBURSEMENT_ID}/submit`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json().error).toEqual(
|
||||
expect.objectContaining({
|
||||
code: "VALID_001",
|
||||
details: expect.objectContaining({
|
||||
standardViolations: [
|
||||
expect.objectContaining({
|
||||
itemId: "item-block",
|
||||
controlMode: "block",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(tx.workflowInstance.create).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("allows warn submit and persists standardViolations into workflow context", async () => {
|
||||
resolveEntityPrecheckMock.mockResolvedValue(
|
||||
buildPrecheck({
|
||||
decision: "warn",
|
||||
warnings: [
|
||||
{
|
||||
code: "expense_standard_warning",
|
||||
title: "费用标准预警",
|
||||
detail: "交通费超出上限",
|
||||
},
|
||||
],
|
||||
standardChecks: [
|
||||
{
|
||||
itemId: "item-warn",
|
||||
expenseTypeId: "88888888-8888-4888-8888-888888888888",
|
||||
expenseTypeName: "交通费",
|
||||
amount: "180.00",
|
||||
standardId: "99999999-9999-4999-8999-999999999999",
|
||||
standardName: "交通费预警上限",
|
||||
maxAmount: "120.00",
|
||||
perUnit: "item",
|
||||
controlMode: "warn",
|
||||
scopeType: "department",
|
||||
scopeKey: DEPARTMENT_ID,
|
||||
exceeded: true,
|
||||
exceededAmount: "60.00",
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
|
||||
const { app, state } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/reimbursements/${REIMBURSEMENT_ID}/submit`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual(
|
||||
expect.objectContaining({
|
||||
reimbursementId: REIMBURSEMENT_ID,
|
||||
status: "reviewing",
|
||||
precheckDecision: "warn",
|
||||
standardWarnings: [
|
||||
expect.objectContaining({
|
||||
itemId: "item-warn",
|
||||
controlMode: "warn",
|
||||
}),
|
||||
],
|
||||
}),
|
||||
);
|
||||
expect(state.workflowInstanceCreatePayload?.context_data?.standardViolations).toEqual([
|
||||
expect.objectContaining({
|
||||
itemId: "item-warn",
|
||||
exceededAmount: "60.00",
|
||||
}),
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const workflowRoutes = require("../../../src/routes/workflow");
|
||||
|
||||
const TASK_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: EMPLOYEE_ID,
|
||||
roleCodes: [],
|
||||
permissionCodes: [],
|
||||
};
|
||||
|
||||
const prisma = {
|
||||
delegationGrant: {
|
||||
findMany: vi.fn(async () => []),
|
||||
},
|
||||
workflowTask: {
|
||||
findFirst: vi.fn(async () => ({
|
||||
id: TASK_ID,
|
||||
instance_id: "33333333-3333-4333-8333-333333333333",
|
||||
step_id: "approval_1_finance",
|
||||
step_name: "财务审批",
|
||||
assignee_id: EMPLOYEE_ID,
|
||||
assignee_role: null,
|
||||
status: "completed",
|
||||
outcome: "approved",
|
||||
comment: "已核验",
|
||||
created_at: new Date("2026-04-08T08:00:00.000Z"),
|
||||
completed_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
workflow_instance: {
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
entity_type: "reimbursement",
|
||||
entity_id: "44444444-4444-4444-8444-444444444444",
|
||||
current_status: "pending",
|
||||
current_step_id: "approval_1_finance",
|
||||
context_data: {
|
||||
standardViolations: [
|
||||
{
|
||||
itemId: "item-1",
|
||||
expenseTypeName: "交通费",
|
||||
amount: "180.00",
|
||||
standardName: "交通费上限",
|
||||
maxAmount: "120.00",
|
||||
exceededAmount: "60.00",
|
||||
controlMode: "warn",
|
||||
},
|
||||
],
|
||||
},
|
||||
started_at: new Date("2026-04-08T08:00:00.000Z"),
|
||||
completed_at: null,
|
||||
reimbursement_form: {
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
form_number: "BX-20260408-001",
|
||||
status: "reviewing",
|
||||
total_amount: "180.00",
|
||||
reimbursement_date: new Date("2026-04-08T00:00:00.000Z"),
|
||||
description: "测试报销",
|
||||
owner: {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "申请人",
|
||||
},
|
||||
submitter: {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "申请人",
|
||||
},
|
||||
items: [],
|
||||
},
|
||||
leave_request: null,
|
||||
purchase_request: null,
|
||||
travel_request: null,
|
||||
},
|
||||
})),
|
||||
findUnique: vi.fn(async () => ({
|
||||
id: TASK_ID,
|
||||
})),
|
||||
},
|
||||
workflowHistory: {
|
||||
findMany: vi.fn(async () => []),
|
||||
},
|
||||
};
|
||||
|
||||
app.decorate("prisma", prisma);
|
||||
app.decorate("config", {
|
||||
imNotifierEnabled: false,
|
||||
emailEnabled: false,
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", () => async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
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 };
|
||||
}
|
||||
|
||||
describe("workflow task detail route", () => {
|
||||
it("returns reimbursement workflow contextData.standardViolations", async () => {
|
||||
const { app } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/workflow/tasks/${TASK_ID}`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.workflowInstance.contextData.standardViolations).toEqual([
|
||||
expect.objectContaining({
|
||||
itemId: "item-1",
|
||||
controlMode: "warn",
|
||||
exceededAmount: "60.00",
|
||||
}),
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,306 @@
|
||||
const {
|
||||
checkExpenseStandards,
|
||||
mergeReimbursementPrecheck,
|
||||
} = require("../../../src/services/feeControl");
|
||||
|
||||
const REIMBURSEMENT_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const EXPENSE_TYPE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const OTHER_EXPENSE_TYPE_ID = "33333333-3333-4333-8333-333333333333";
|
||||
const DEPARTMENT_ID = "44444444-4444-4444-8444-444444444444";
|
||||
|
||||
function buildTx(options = {}) {
|
||||
return {
|
||||
reimbursementForm: {
|
||||
findUnique: vi.fn().mockResolvedValue(
|
||||
options.reimbursement ?? {
|
||||
id: REIMBURSEMENT_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
items: [
|
||||
{
|
||||
id: "item-1",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
amount: "150.00",
|
||||
expense_type: {
|
||||
id: EXPENSE_TYPE_ID,
|
||||
name: "交通费",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
},
|
||||
expenseStandard: {
|
||||
findMany: vi.fn().mockResolvedValue(
|
||||
options.standards ?? [
|
||||
{
|
||||
id: "standard-global",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "交通费全局上限",
|
||||
max_amount: "120.00",
|
||||
per_unit: "item",
|
||||
control_mode: "warn",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("checkExpenseStandards", () => {
|
||||
it("prefers department scoped standard over global standard", async () => {
|
||||
const tx = buildTx({
|
||||
standards: [
|
||||
{
|
||||
id: "standard-global",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "交通费全局上限",
|
||||
max_amount: "120.00",
|
||||
per_unit: "item",
|
||||
control_mode: "warn",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "standard-department",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "交通费部门上限",
|
||||
max_amount: "100.00",
|
||||
per_unit: "item",
|
||||
control_mode: "block",
|
||||
scope_type: "department",
|
||||
scope_key: DEPARTMENT_ID,
|
||||
created_at: new Date("2026-04-08T10:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await checkExpenseStandards(tx, { reimbursementId: REIMBURSEMENT_ID });
|
||||
|
||||
expect(result).toEqual([
|
||||
expect.objectContaining({
|
||||
standardId: "standard-department",
|
||||
standardName: "交通费部门上限",
|
||||
controlMode: "block",
|
||||
exceeded: true,
|
||||
exceededAmount: "50.00",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns warn level check without blocking when amount only exceeds warn standard", async () => {
|
||||
const tx = buildTx();
|
||||
const result = await checkExpenseStandards(tx, { reimbursementId: REIMBURSEMENT_ID });
|
||||
const merged = mergeReimbursementPrecheck(
|
||||
{
|
||||
entityType: "reimbursement",
|
||||
entityId: REIMBURSEMENT_ID,
|
||||
decision: "pass",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [],
|
||||
nextActions: ["可直接提交"],
|
||||
},
|
||||
result,
|
||||
);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
controlMode: "warn",
|
||||
exceeded: true,
|
||||
});
|
||||
expect(merged.decision).toBe("warn");
|
||||
expect(merged.warnings).toHaveLength(1);
|
||||
expect(merged.blockingReasons).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("turns decision into block when exceeded item hits block standard", async () => {
|
||||
const tx = buildTx({
|
||||
standards: [
|
||||
{
|
||||
id: "standard-block",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "交通费阻断上限",
|
||||
max_amount: "120.00",
|
||||
per_unit: "item",
|
||||
control_mode: "block",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await checkExpenseStandards(tx, { reimbursementId: REIMBURSEMENT_ID });
|
||||
const merged = mergeReimbursementPrecheck(
|
||||
{
|
||||
entityType: "reimbursement",
|
||||
entityId: REIMBURSEMENT_ID,
|
||||
decision: "pass",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [],
|
||||
nextActions: ["可直接提交"],
|
||||
},
|
||||
result,
|
||||
);
|
||||
|
||||
expect(result[0].controlMode).toBe("block");
|
||||
expect(merged.decision).toBe("block");
|
||||
expect(merged.blockingReasons).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("skips items that do not match any standard", async () => {
|
||||
const tx = buildTx({
|
||||
reimbursement: {
|
||||
id: REIMBURSEMENT_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
items: [
|
||||
{
|
||||
id: "item-2",
|
||||
expense_type_id: OTHER_EXPENSE_TYPE_ID,
|
||||
amount: "88.00",
|
||||
expense_type: {
|
||||
id: OTHER_EXPENSE_TYPE_ID,
|
||||
name: "办公费",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
standards: [
|
||||
{
|
||||
id: "standard-global",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "交通费全局上限",
|
||||
max_amount: "120.00",
|
||||
per_unit: "item",
|
||||
control_mode: "warn",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await checkExpenseStandards(tx, { reimbursementId: REIMBURSEMENT_ID });
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps perUnit as display metadata without any day or trip aggregation", async () => {
|
||||
const tx = buildTx({
|
||||
reimbursement: {
|
||||
id: REIMBURSEMENT_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
items: [
|
||||
{
|
||||
id: "item-1",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
amount: "300.00",
|
||||
expense_type: {
|
||||
id: EXPENSE_TYPE_ID,
|
||||
name: "交通费",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "item-2",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
amount: "300.00",
|
||||
expense_type: {
|
||||
id: EXPENSE_TYPE_ID,
|
||||
name: "交通费",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
standards: [
|
||||
{
|
||||
id: "standard-trip",
|
||||
expense_type_id: EXPENSE_TYPE_ID,
|
||||
name: "差旅交通上限",
|
||||
max_amount: "250.00",
|
||||
per_unit: "trip",
|
||||
control_mode: "warn",
|
||||
scope_type: "global",
|
||||
scope_key: null,
|
||||
created_at: new Date("2026-04-08T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await checkExpenseStandards(tx, { reimbursementId: REIMBURSEMENT_ID });
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toMatchObject({
|
||||
perUnit: "trip",
|
||||
exceededAmount: "50.00",
|
||||
});
|
||||
expect(result[1]).toMatchObject({
|
||||
perUnit: "trip",
|
||||
exceededAmount: "50.00",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves manual_review decision priority over warn and under block", () => {
|
||||
const mergedWarn = mergeReimbursementPrecheck(
|
||||
{
|
||||
entityType: "reimbursement",
|
||||
entityId: REIMBURSEMENT_ID,
|
||||
decision: "manual_review",
|
||||
matchedBudgetControlRule: null,
|
||||
budgetHint: null,
|
||||
standardChecks: [],
|
||||
warnings: [],
|
||||
blockingReasons: [],
|
||||
riskFlags: [{ code: "budget_exceeded", level: "high", title: "预算超用", detail: "需要复核" }],
|
||||
nextActions: ["允许提交,但会生成待复核风险项"],
|
||||
},
|
||||
[
|
||||
{
|
||||
itemId: "item-1",
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
expenseTypeName: "交通费",
|
||||
amount: "150.00",
|
||||
standardId: "standard-global",
|
||||
standardName: "交通费全局上限",
|
||||
maxAmount: "120.00",
|
||||
perUnit: "item",
|
||||
controlMode: "warn",
|
||||
scopeType: "global",
|
||||
scopeKey: null,
|
||||
exceeded: true,
|
||||
exceededAmount: "30.00",
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
const mergedBlock = mergeReimbursementPrecheck(mergedWarn, [
|
||||
{
|
||||
itemId: "item-2",
|
||||
expenseTypeId: EXPENSE_TYPE_ID,
|
||||
expenseTypeName: "交通费",
|
||||
amount: "200.00",
|
||||
standardId: "standard-block",
|
||||
standardName: "交通费阻断上限",
|
||||
maxAmount: "120.00",
|
||||
perUnit: "item",
|
||||
controlMode: "block",
|
||||
scopeType: "global",
|
||||
scopeKey: null,
|
||||
exceeded: true,
|
||||
exceededAmount: "80.00",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(mergedWarn.decision).toBe("manual_review");
|
||||
expect(mergedBlock.decision).toBe("block");
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户