文件
hyb-oa/server/tests/unit/routes/expenseStandards.test.js
wangsli 1f8d5b658a 完善借款、编号、付款与预算并发及验收(09-06-release-gate-integrity)
汇总已落盘的借款本金与还款、兼容历史编号的周期化编号、付款责任与回单核验、报销进度和排序、PWA/采购事务、错误原因与日期校验及ERP退役。
统一共享预算池锁序和锁后判断,恢复差旅原预算选择,补原因码固定夹具及反向完整性检查。
纳入配套迁移、测试、受管QA、分层验收合同、规约及任务记录;原始证据留在ignored artifacts。

关联任务:09-17-company-loan-principal-repayment、09-17-erp-exclusive-retirement、09-18-reimbursement-periodic-numbering、09-08-reimbursement-payment-closeout、09-18-local-concurrency-product-fixes、09-19-budget-pool-concurrency、09-05-error-explainability-payment-readiness。
预算补审由Claude定向验证2文件928项通过,原4446/28及r6结果仍仅对应各自历史输入;本轮未重跑测试。
完整新候选门禁、R1真实入口接入与12项公网义务仍开放。生产编号未启用、差旅仍冻结;不推送、不部署,不宣称发布资格。
2026-09-19 13:11:04 +08:00

458 行
14 KiB
JavaScript

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", reasonCode: "expense_standard.expense_type_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", reasonCode: "expense_standard.department_required" });
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", reasonCode: "expense_standard.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();
});
});