完成五人团队正式内用最小收口(07-18-small-team-internal-readiness)

这个提交包含在:
2026-07-18 15:46:14 +08:00
父节点 58c8decef9
当前提交 5d0a5f9a38
共修改 134 个文件,包含 10790 行新增和 1413 行删除
@@ -42,6 +42,40 @@ describe("Permission Constants", () => {
expect(hrPermissions).toEqual(expect.arrayContaining(["leave.view_all", "leave.manage"]));
});
it("keeps the OA system administrator separate from business and sensitive-data roles", () => {
const permissions = resolvePermissionsForRoles(["system_admin"]);
expect(permissions).toEqual(expect.arrayContaining([
"system.accounts.manage",
"system.roles.manage",
"system.settings",
"integration.manage",
"notification.channel.manage",
"system.audit.view",
]));
expect(hasPermission(permissions, "expense.approve")).toBe(false);
expect(hasPermission(permissions, "expense.finance.pay")).toBe(false);
expect(hasPermission(permissions, "payment.batch.manage")).toBe(false);
expect(hasPermission(permissions, "payment.batch.review")).toBe(false);
expect(hasPermission(permissions, "payroll.manage")).toBe(false);
expect(hasPermission(permissions, "employee.bank.read")).toBe(false);
expect(hasPermission(permissions, "employee.bank.manage")).toBe(false);
expect(hasPermission(permissions, "employee.identity.manage")).toBe(false);
expect(hasPermission(permissions, "employee.contract.manage")).toBe(false);
});
it("assigns the new sensitive permissions only to their intended duties", () => {
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "employee.bank.read")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "employee.bank.manage")).toBe(false);
expect(hasPermission(resolvePermissionsForRoles(["finance"]), "payroll.manage")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["finance_mgr"]), "payroll.manage")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["hr"]), "employee.bank.manage")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["hr"]), "employee.identity.manage")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["hr"]), "employee.contract.manage")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["manager"]), "payment.batch.review")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["ceo"]), "payment.batch.review")).toBe(true);
});
it("grants procurement permissions to configured roles", () => {
expect(hasPermission(resolvePermissionsForRoles(["employee"]), "procurement.create")).toBe(true);
expect(hasPermission(resolvePermissionsForRoles(["employee"]), "procurement.view_own")).toBe(true);
@@ -0,0 +1,145 @@
const Fastify = require("fastify");
const approvalRulesRoutes = require("../../../src/routes/approvalRules");
const { AppError } = require("../../../src/utils/AppError");
const ACTOR_ID = "11111111-1111-4111-8111-111111111111";
const APPROVAL_RULE_ID = "22222222-2222-4222-8222-222222222222";
function buildCreatePayload(roleCode) {
return {
name: `合成规则-${roleCode}`,
minAmount: "0.00",
maxAmount: "1000.00",
level1Role: roleCode,
level2Role: null,
level3Role: null,
ownerSelfFallbackRole: "finance_mgr",
enabled: true,
priority: 1,
};
}
async function buildApp() {
const app = Fastify();
const approvalRuleCreate = vi.fn(async ({ data }) => ({
id: APPROVAL_RULE_ID,
name: data.name,
min_amount: data.min_amount,
max_amount: data.max_amount,
level1_role: data.level1_role,
level2_role: data.level2_role,
level3_role: data.level3_role,
owner_self_fallback_role: data.owner_self_fallback_role,
enabled: data.enabled,
priority: data.priority,
created_at: new Date("2026-07-18T00:00:00.000Z"),
updated_at: new Date("2026-07-18T00:00:00.000Z"),
}));
const transactionContext = {
approvalRule: {
aggregate: vi.fn().mockResolvedValue({ _max: { priority: 0 } }),
create: approvalRuleCreate,
},
auditLog: {
create: vi.fn().mockResolvedValue({ id: "audit-1" }),
},
};
const transaction = vi.fn(async (callback) => callback(transactionContext));
app.decorate("requirePermission", () => async (request) => {
request.employee = {
id: ACTOR_ID,
permissionCodes: ["system.settings"],
};
});
app.decorate("prisma", {
$transaction: transaction,
});
app.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
return reply.status(error.statusCode).send({
requestId: request.id,
error: {
code: error.code,
message: error.message,
details: error.details ?? null,
},
});
}
return reply.status(500).send({
requestId: request.id,
error: {
code: "SYS_001",
message: "服务器内部错误",
details: null,
},
});
});
await app.register(approvalRulesRoutes, { prefix: "/api" });
return { app, approvalRuleCreate, transaction };
}
describe("reimbursement approval-rule role whitelist", () => {
it.each(["manager", "ceo", "finance", "finance_mgr"])(
"allows role %s because it carries expense.approve",
async (roleCode) => {
const testApp = await buildApp();
try {
const response = await testApp.app.inject({
method: "POST",
url: "/api/approval-rules",
payload: buildCreatePayload(roleCode),
});
expect(response.statusCode).toBe(200);
expect(response.json().data.level1Role).toBe(roleCode);
expect(testApp.approvalRuleCreate).toHaveBeenCalledTimes(1);
} finally {
await testApp.app.close();
}
},
);
it.each(["employee", "hr", "administration", "admin", "system_admin"])(
"rejects role %s before a reimbursement approval rule is saved",
async (roleCode) => {
const testApp = await buildApp();
try {
const response = await testApp.app.inject({
method: "POST",
url: "/api/approval-rules",
payload: buildCreatePayload(roleCode),
});
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe("VALID_001");
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.approvalRuleCreate).not.toHaveBeenCalled();
} finally {
await testApp.app.close();
}
},
);
it.each(["level1Role", "level2Role", "level3Role"])(
"applies the reimbursement role whitelist to %s on update",
async (fieldName) => {
const testApp = await buildApp();
try {
const response = await testApp.app.inject({
method: "PATCH",
url: `/api/approval-rules/${APPROVAL_RULE_ID}`,
payload: { [fieldName]: "employee" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe("VALID_001");
expect(testApp.transaction).not.toHaveBeenCalled();
} finally {
await testApp.app.close();
}
},
);
});
@@ -11,6 +11,10 @@ const { AppError } = require("../../../src/utils/AppError");
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
const CONTRACT_ID = "22222222-2222-4222-8222-222222222222";
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const MINIMAL_PDF = Buffer.from(
"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n",
"ascii",
);
function buildMultipartRequest({ filename, contentType, content }) {
const boundary = "----codex-employee-attachment-boundary";
@@ -91,11 +95,12 @@ function buildContractRow(overrides = {}) {
}
async function buildApp({
actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] },
actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["employee.contract.manage"] },
employee = {},
contract = {},
} = {}) {
const app = Fastify();
const logWarn = vi.spyOn(app.log, "warn").mockImplementation(() => {});
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "hyb-oa-r45-attachments-"));
const state = {
employee: buildEmployeeRow(employee),
@@ -127,6 +132,32 @@ async function buildApp({
});
const auditCreate = vi.fn().mockResolvedValue({});
const featureFlagFindUnique = vi.fn().mockResolvedValue(buildFeatureFlagRecord());
const employeeContract = {
findFirst: vi.fn(async ({ where }) => {
if (!state.contract) {
return null;
}
if (where.id === state.contract.id && where.employee_id === state.contract.employee_id) {
return state.contract;
}
return null;
}),
findMany: vi.fn(async () => (state.contract ? [state.contract] : [])),
update: contractUpdate,
delete: contractDelete,
create: vi.fn(),
count: vi.fn().mockResolvedValue(0),
};
const contractLock = vi.fn(async () => (
state.contract ? [{ id: state.contract.id }] : []
));
const transactionContext = {
employeeContract,
auditLog: { create: auditCreate },
$queryRaw: contractLock,
};
const transaction = vi.fn(async (callback) => callback(transactionContext));
app.decorate("config", {
appTimezone: "Asia/Shanghai",
@@ -149,7 +180,7 @@ async function buildApp({
});
app.decorate("prisma", {
featureFlag: {
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
findUnique: featureFlagFindUnique,
},
employee: {
findUnique: vi.fn(async ({ where }) => (where.id === EMPLOYEE_ID ? state.employee : null)),
@@ -157,22 +188,7 @@ async function buildApp({
findMany: vi.fn().mockResolvedValue([]),
count: vi.fn().mockResolvedValue(0),
},
employeeContract: {
findFirst: vi.fn(async ({ where }) => {
if (!state.contract) {
return null;
}
if (where.id === state.contract.id && where.employee_id === state.contract.employee_id) {
return state.contract;
}
return null;
}),
findMany: vi.fn(async () => (state.contract ? [state.contract] : [])),
update: contractUpdate,
delete: contractDelete,
create: vi.fn(),
count: vi.fn().mockResolvedValue(0),
},
employeeContract,
employeeTraining: {
findMany: vi.fn().mockResolvedValue([]),
findFirst: vi.fn().mockResolvedValue(null),
@@ -204,6 +220,7 @@ async function buildApp({
auditLog: {
create: auditCreate,
},
$transaction: transaction,
});
app.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
@@ -232,12 +249,25 @@ async function buildApp({
});
await app.register(employeesRoutes, { prefix: "/api" });
return { app, auditCreate, contractDelete, contractUpdate, employeeUpdate, state, tempDir };
return {
app,
auditCreate,
contractLock,
contractDelete,
contractUpdate,
employeeUpdate,
featureFlagFindUnique,
logWarn,
state,
tempDir,
transaction,
transactionContext,
};
}
describe("employee attachment and delete routes", () => {
it("uploads, replaces and downloads contract attachments for system.users", async () => {
const { app, state, tempDir } = await buildApp({
it("uploads, replaces and downloads contract attachments with dedicated permission and audit", async () => {
const { app, auditCreate, state, tempDir } = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.png`,
},
@@ -253,17 +283,18 @@ describe("employee attachment and delete routes", () => {
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: "new-pdf",
content: MINIMAL_PDF,
}),
});
expect(uploadResponse.statusCode).toBe(200);
expect(uploadResponse.json().data).toMatchObject({
attachmentPath: `contracts/${CONTRACT_ID}.pdf`,
hasAttachment: true,
attachmentUrl: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(state.contract.attachment_path).toBe(`contracts/${CONTRACT_ID}.pdf`);
expect(await fs.readFile(path.join(tempDir, "contracts", `${CONTRACT_ID}.pdf`), "utf8")).toBe("new-pdf");
expect(uploadResponse.json().data).not.toHaveProperty("attachmentPath");
expect(state.contract.attachment_path).toMatch(new RegExp(`^contracts/${CONTRACT_ID}-[0-9a-f-]+\\.pdf$`));
expect(await fs.readFile(path.join(tempDir, state.contract.attachment_path))).toEqual(MINIMAL_PDF);
await expect(fs.access(oldAttachmentPath)).rejects.toMatchObject({ code: "ENOENT" });
const downloadResponse = await app.inject({
@@ -272,16 +303,82 @@ describe("employee attachment and delete routes", () => {
});
expect(downloadResponse.statusCode).toBe(200);
expect(downloadResponse.headers["content-type"]).toContain("application/pdf");
expect(downloadResponse.headers["content-type"]).toContain("application/octet-stream");
expect(downloadResponse.headers["x-content-type-options"]).toBe("nosniff");
expect(downloadResponse.headers["content-disposition"]).toContain('filename="LAB-001.pdf"');
expect(downloadResponse.body).toBe("new-pdf");
expect(downloadResponse.body).toBe(MINIMAL_PDF.toString("utf8"));
expect(auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "EMPLOYEE_CONTRACT_ATTACHMENT_DOWNLOADED",
target_id: CONTRACT_ID,
extra: { employeeId: EMPLOYEE_ID },
}),
});
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
});
it("blocks invalid historical contract bytes before sending attachment headers or file content", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const attachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
const invalidStoredContent = Buffer.from("synthetic-invalid-contract-content", "utf8");
await fs.mkdir(path.dirname(attachmentPath), { recursive: true });
await fs.writeFile(attachmentPath, invalidStoredContent);
const response = await testApp.app.inject({
method: "GET",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(response.statusCode).toBe(409);
expect(response.headers["content-disposition"]).toBeUndefined();
expect(response.rawPayload.equals(invalidStoredContent)).toBe(false);
expect(response.json().error.details).toEqual({
attachment: "security_validation_failed",
});
expect(testApp.auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "EMPLOYEE_CONTRACT_ATTACHMENT_DOWNLOAD_BLOCKED",
target_id: CONTRACT_ID,
}),
});
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("returns no contract bytes or attachment headers when success auditing fails", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const attachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
await fs.mkdir(path.dirname(attachmentPath), { recursive: true });
await fs.writeFile(attachmentPath, MINIMAL_PDF);
testApp.auditCreate.mockRejectedValueOnce(new Error("synthetic audit failure"));
const response = await testApp.app.inject({
method: "GET",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(response.statusCode).toBe(500);
expect(response.headers["content-disposition"]).toBeUndefined();
expect(response.rawPayload.equals(MINIMAL_PDF)).toBe(false);
expect(response.json().error.details).toEqual({ attachment: "audit_failed" });
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("rejects contract attachment upload for non-admin users", async () => {
const { app, tempDir } = await buildApp({
const { app, featureFlagFindUnique, contractUpdate, tempDir } = await buildApp({
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
});
@@ -296,11 +393,122 @@ describe("employee attachment and delete routes", () => {
});
expect(response.statusCode).toBe(403);
expect(featureFlagFindUnique).not.toHaveBeenCalled();
expect(contractUpdate).not.toHaveBeenCalled();
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
});
it("rejects contract attachment content mismatch before storage, database or audit writes", async () => {
const testApp = await buildApp();
const pngSignatureOnly = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: pngSignatureOnly,
}),
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toEqual(
expect.objectContaining({
code: "VALID_001",
details: { file: "type_mismatch" },
}),
);
expect(testApp.contractUpdate).not.toHaveBeenCalled();
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
expect(await fs.readdir(testApp.tempDir)).toEqual([]);
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("keeps a committed replacement successful when old-file cleanup fails and logs only safe metadata", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const oldAttachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
await fs.mkdir(oldAttachmentPath, { recursive: true });
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: MINIMAL_PDF,
}),
});
expect(response.statusCode).toBe(200);
expect(testApp.state.contract.attachment_path).not.toBe(`contracts/${CONTRACT_ID}.pdf`);
expect(testApp.logWarn).toHaveBeenCalledWith(
{
contractId: CONTRACT_ID,
errorCode: expect.stringMatching(/^[A-Z0-9_]+$/u),
},
"Committed contract attachment cleanup failed",
);
const [metadata] = testApp.logWarn.mock.calls.at(-1);
expect(metadata).not.toHaveProperty("storagePath");
expect(metadata).not.toHaveProperty("fileName");
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("cleans the attachment path observed under the replacement row lock", async () => {
const initialAttachmentPath = `contracts/${CONTRACT_ID}-initial.pdf`;
const concurrentAttachmentPath = `contracts/${CONTRACT_ID}-concurrent.pdf`;
const testApp = await buildApp({
contract: {
attachment_path: initialAttachmentPath,
},
});
const initialAbsolutePath = path.join(testApp.tempDir, initialAttachmentPath);
const concurrentAbsolutePath = path.join(testApp.tempDir, concurrentAttachmentPath);
await fs.mkdir(path.dirname(initialAbsolutePath), { recursive: true });
await fs.writeFile(initialAbsolutePath, MINIMAL_PDF);
await fs.writeFile(concurrentAbsolutePath, MINIMAL_PDF);
testApp.transaction.mockImplementationOnce(async (callback) => {
testApp.state.contract = {
...testApp.state.contract,
attachment_path: concurrentAttachmentPath,
};
return callback(testApp.transactionContext);
});
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: MINIMAL_PDF,
}),
});
expect(response.statusCode).toBe(200);
expect(testApp.contractLock).toHaveBeenCalledTimes(1);
await expect(fs.access(concurrentAbsolutePath)).rejects.toMatchObject({ code: "ENOENT" });
await expect(fs.access(initialAbsolutePath)).resolves.toBeUndefined();
await expect(fs.access(path.join(testApp.tempDir, testApp.state.contract.attachment_path)))
.resolves.toBeUndefined();
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("allows self-service avatar deletion and clears stored file", async () => {
const { app, state, tempDir } = await buildApp({
actor: { id: EMPLOYEE_ID, department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
@@ -349,6 +557,7 @@ describe("employee attachment and delete routes", () => {
const activeResponse = await activeApp.app.inject({
method: "DELETE",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
payload: { reason: "测试删除" },
});
expect(activeResponse.statusCode).toBe(409);
@@ -368,6 +577,7 @@ describe("employee attachment and delete routes", () => {
const expiredResponse = await expiredApp.app.inject({
method: "DELETE",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
payload: { reason: "合同记录重复" },
});
expect(expiredResponse.statusCode).toBe(200);
@@ -381,6 +591,12 @@ describe("employee attachment and delete routes", () => {
data: expect.objectContaining({
action: "EMPLOYEE_CONTRACT_DELETED",
target_id: CONTRACT_ID,
extra: {
employeeId: EMPLOYEE_ID,
status: "expired",
hadAttachment: true,
reason: "合同记录重复",
},
}),
}),
);
@@ -388,4 +604,25 @@ describe("employee attachment and delete routes", () => {
await expiredApp.app.close();
await fs.rm(expiredApp.tempDir, { recursive: true, force: true });
});
it("rejects contract deletion without a usable reason before feature or contract access", async () => {
const testApp = await buildApp({
contract: { end_date: new Date("2025-12-31T00:00:00.000Z") },
});
const response = await testApp.app.inject({
method: "DELETE",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
payload: { reason: "x" },
});
expect(response.statusCode).toBe(400);
expect(testApp.featureFlagFindUnique).not.toHaveBeenCalled();
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.contractDelete).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
});
@@ -1,6 +1,7 @@
const Fastify = require("fastify");
const employeesRoutes = require("../../../src/routes/employees");
const { resolvePermissionsForRoles } = require("../../../src/constants/permissions");
const { AppError } = require("../../../src/utils/AppError");
async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
@@ -202,9 +203,54 @@ describe("employees stats route", () => {
await app.close();
});
it("returns salary and performance summary for system settings viewers", async () => {
const { app, payslipAggregate } = await buildApp({
permissionCodes: ["system.users", "system.settings"],
it("does not expose sensitive summaries to system administrators with ordinary stats access", async () => {
const {
app,
performanceCycleFindFirst,
performanceReviewAggregate,
performanceReviewGroupBy,
payslipAggregate,
} = await buildApp({
permissionCodes: [
...resolvePermissionsForRoles(["system_admin"]),
"report.dashboard.view",
],
});
const response = await app.inject({
method: "GET",
url: "/api/employees/stats",
});
expect(response.statusCode).toBe(200);
expect(response.json().data.salarySummary).toBeNull();
expect(response.json().data.performanceSummary).toEqual({
cycle: null,
averageScore: null,
reviewedCount: 0,
distribution: [],
});
expect(performanceCycleFindFirst).not.toHaveBeenCalled();
expect(performanceReviewAggregate).not.toHaveBeenCalled();
expect(performanceReviewGroupBy).not.toHaveBeenCalled();
expect(payslipAggregate).not.toHaveBeenCalled();
await app.close();
});
it("returns salary and performance summaries with explicit sensitive permissions", async () => {
const {
app,
performanceCycleFindFirst,
performanceReviewAggregate,
performanceReviewGroupBy,
payslipAggregate,
} = await buildApp({
permissionCodes: [
"report.dashboard.view",
"payroll.manage",
"system.users_sensitive",
],
});
const response = await app.inject({
@@ -231,6 +277,9 @@ describe("employees stats route", () => {
id: "cycle-active",
name: "2026 Q2",
});
expect(performanceCycleFindFirst).toHaveBeenCalledTimes(2);
expect(performanceReviewAggregate).toHaveBeenCalledTimes(1);
expect(performanceReviewGroupBy).toHaveBeenCalledTimes(1);
expect(payslipAggregate).toHaveBeenCalledTimes(2);
await app.close();
文件差异内容过多而无法显示 加载差异
@@ -24,7 +24,7 @@ function buildPayslipRow() {
}
async function buildApp({
actor = { id: ADMIN_ID, permissionCodes: ["system.settings"] },
actor = { id: ADMIN_ID, permissionCodes: ["payroll.manage"] },
} = {}) {
const app = Fastify();
const salaryItems = [
+16 -2
查看文件
@@ -21,7 +21,7 @@ function buildSalaryItem(overrides = {}) {
}
async function buildApp({
actor = { id: ADMIN_ID, permissionCodes: ["system.settings"] },
actor = { id: ADMIN_ID, permissionCodes: ["payroll.manage"] },
} = {}) {
const app = Fastify();
const state = {
@@ -90,7 +90,7 @@ async function buildApp({
}
describe("payroll salary item routes", () => {
it("allows admins to create, list and patch salary items", async () => {
it("allows payroll managers to create, list and patch salary items", async () => {
const { app, state, salaryItem } = await buildApp();
const createResponse = await app.inject({
@@ -157,4 +157,18 @@ describe("payroll salary item routes", () => {
await app.close();
});
it("does not accept system.settings as a substitute for payroll.manage", async () => {
const { app } = await buildApp({
actor: {
id: "system-admin-1",
permissionCodes: ["system.settings", "system.accounts.manage"],
},
});
const response = await app.inject({ method: "GET", url: "/api/payroll/items" });
expect(response.statusCode).toBe(403);
await app.close();
});
});
@@ -48,7 +48,7 @@ const PAYSLIP_IDS = [
];
async function buildApp({
actor = { id: ADMIN_ID, permissionCodes: ["system.settings"] },
actor = { id: ADMIN_ID, permissionCodes: ["payroll.manage"] },
omitProfileFor = [],
} = {}) {
const app = Fastify();
@@ -50,7 +50,7 @@ function buildSalaryRow(overrides = {}) {
}
async function buildApp({
actor = { id: ADMIN_ID, permissionCodes: ["system.settings"] },
actor = { id: ADMIN_ID, permissionCodes: ["payroll.manage"] },
} = {}) {
const app = Fastify();
const state = {
@@ -131,9 +131,15 @@ async function buildApp({
},
};
});
const attachmentDelete = vi.fn(async ({ where }) => {
if (state.attachment?.id === where.id) {
state.attachment = null;
}
return { id: where.id };
});
const tx = {
purchaseAttachment: { create: attachmentCreate },
purchaseAttachment: { create: attachmentCreate, delete: attachmentDelete },
auditLog: { create: uploadAuditCreate },
};
const prisma = {
@@ -211,6 +217,7 @@ async function buildApp({
return {
app,
attachmentCreate,
attachmentDelete,
downloadAuditCreate,
prisma,
state,
@@ -470,6 +477,58 @@ describe("purchase attachment upload", () => {
});
});
describe("purchase attachment delete", () => {
it("requires a reason and records it with the attachment audit", async () => {
const { app, attachmentDelete, state, uploadAuditCreate } = await buildApp();
try {
const response = await app.inject({
method: "DELETE",
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}/attachments/${ATTACHMENT_ID}`,
headers: { authorization: "Bearer unit-test", "content-type": "application/json" },
payload: { reason: "重复上传" },
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({ outcome: "deleted", attachmentId: ATTACHMENT_ID });
expect(attachmentDelete).toHaveBeenCalledWith({ where: { id: ATTACHMENT_ID } });
expect(uploadAuditCreate).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: "PURCHASE_ATTACHMENT_DELETED",
target_id: ATTACHMENT_ID,
extra: expect.objectContaining({ purchaseRequestId: PURCHASE_REQUEST_ID, reason: "重复上传" }),
}),
}),
);
expect(state.attachment).toBeNull();
} finally {
await app.close();
}
});
it("rejects a missing reason before attachment lookup or deletion", async () => {
const { app, attachmentDelete, prisma, uploadAuditCreate } = await buildApp();
try {
const response = await app.inject({
method: "DELETE",
url: `/api/purchase-requests/${PURCHASE_REQUEST_ID}/attachments/${ATTACHMENT_ID}`,
headers: { authorization: "Bearer unit-test", "content-type": "application/json" },
payload: {},
});
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe("VALID_001");
expect(prisma.purchaseRequest.findUnique).not.toHaveBeenCalled();
expect(attachmentDelete).not.toHaveBeenCalled();
expect(uploadAuditCreate).not.toHaveBeenCalled();
} finally {
await app.close();
}
});
});
describe("purchase attachment authenticated download", () => {
const downloadUrl = `/api/purchase-requests/${PURCHASE_REQUEST_ID}/attachments/${ATTACHMENT_ID}/download`;
@@ -327,7 +327,8 @@ describe("reimbursement attachment routes", () => {
const deleteResponse = await app.inject({
method: "DELETE",
url: `/api/reimbursements/${reimbursementId}/attachments/${attachmentId}`,
headers: { authorization: "Bearer test" },
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: { reason: "重复上传" },
});
expect(deleteResponse.statusCode).toBe(200);
@@ -341,10 +342,40 @@ describe("reimbursement attachment routes", () => {
reimbursement_id: reimbursementId,
},
});
expect(prisma.auditLog.create).toHaveBeenLastCalledWith(
expect.objectContaining({
data: expect.objectContaining({
action: "REIMBURSEMENT_ATTACHMENT_DELETED",
target_id: attachmentId,
extra: expect.objectContaining({ reimbursementId, reason: "重复上传" }),
}),
}),
);
expect(createdAttachments).toHaveLength(0);
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
it("rejects attachment deletion without a meaningful reason before mutation", async () => {
const { app, prisma, tempDir, reimbursementId } = await buildApp();
try {
const response = await app.inject({
method: "DELETE",
url: `/api/reimbursements/${reimbursementId}/attachments/bbbbbbbb-bbbb-4bbb-8bbb-000000000001`,
headers: { authorization: "Bearer test", "content-type": "application/json" },
payload: { reason: " " },
});
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe("VALID_001");
expect(prisma.reimbursementAttachment.deleteMany).not.toHaveBeenCalled();
expect(prisma.auditLog.create).not.toHaveBeenCalled();
} finally {
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
}
});
});
@@ -0,0 +1,186 @@
const Fastify = require("fastify");
const { AppError } = require("../../../src/utils/AppError");
const reimbursementRoutes = require("../../../src/routes/reimbursements");
const REIMBURSEMENT_ID = "11111111-1111-4111-8111-111111111111";
const ACTOR_ID = "22222222-2222-4222-8222-222222222222";
const DEPARTMENT_ID = "33333333-3333-4333-8333-333333333333";
async function buildApp(options = {}) {
const rolloutType = options.rolloutType ?? "global";
const departmentIds = options.departmentIds ?? [];
const activePaymentBatch = options.activePaymentBatch ?? false;
const tx = {
$queryRaw: vi.fn(async () => [{
id: REIMBURSEMENT_ID,
status: "approved",
form_number: "BX-20260718-001",
owner_id: ACTOR_ID,
submitter_id: ACTOR_ID,
department_id: DEPARTMENT_ID,
payment_voucher_no: null,
payment_date: null,
payment_channel: null,
paid_at: null,
paid_by: null,
}]),
featureFlag: {
findUnique: vi.fn(async ({ where }) => {
if (where.flag_key !== "payment_batch_v1") return null;
return {
id: "flag-payment-batch",
flag_key: "payment_batch_v1",
override_mode: "force_on",
rollout_type: rolloutType,
department_ids: departmentIds,
note: "",
version: 1,
created_at: null,
created_by: null,
updated_at: null,
updated_by: null,
};
}),
},
paymentBatchItem: {
findFirst: vi.fn(async () => activePaymentBatch ? { id: "active-batch-item" } : null),
},
reimbursementForm: { update: vi.fn() },
invoicePool: { updateMany: vi.fn() },
auditLog: { create: vi.fn() },
};
const prisma = {
...tx,
$transaction: vi.fn(async (callback) => callback(tx)),
};
const app = Fastify();
app.decorate("prisma", prisma);
app.decorate("config", {
paymentBatchEnabled: true,
cutoverConsoleEnabled: false,
appTimezone: "Asia/Shanghai",
});
app.decorate("authenticate", async (request) => {
if (!request.headers.authorization) {
throw new AppError({ code: "AUTH_001", message: "未登录", statusCode: 401 });
}
request.employee = {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
legal_entity_id: null,
roleCodes: ["finance"],
permissionCodes: ["expense.finance.pay"],
};
});
app.decorate("hasPermission", (employee, permissionCode) =>
(employee?.permissionCodes ?? []).includes("*") ||
(employee?.permissionCodes ?? []).includes(permissionCode),
);
app.decorate("requirePermission", (permissionCode) => async (request) => {
await app.authenticate(request);
if (!app.hasPermission(request.employee, permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("assertEntityPermission", () => {});
app.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
return reply.status(error.statusCode).send({
requestId: request.id,
error: { code: error.code, message: error.message, details: error.details ?? {} },
});
}
return reply.status(500).send({
requestId: request.id,
error: { code: "SYS_001", message: "服务器内部错误", details: {} },
});
});
await app.register(reimbursementRoutes, { prefix: "/api" });
return { app, prisma, tx };
}
describe("reimbursement direct payment batch gate", () => {
it("returns 409 with zero payment writes when payment_batch_v1 is enabled", async () => {
const { app, prisma, tx } = await buildApp();
const response = await app.inject({
method: "POST",
url: `/api/reimbursements/${REIMBURSEMENT_ID}/pay`,
headers: { authorization: "Bearer test" },
payload: {
paymentVoucherNo: "SYNTHETIC-001",
paymentDate: "2026-07-18",
paymentChannel: "bank",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error.details.payment).toBe("payment_batch_v1_required");
expect(prisma.$transaction).toHaveBeenCalledTimes(1);
expect(tx.reimbursementForm.update).not.toHaveBeenCalled();
expect(tx.invoicePool.updateMany).not.toHaveBeenCalled();
expect(tx.auditLog.create).not.toHaveBeenCalled();
await app.close();
});
it("requires the batch path when the source department is in the rollout allowlist", async () => {
const { app, tx } = await buildApp({
rolloutType: "department_allowlist",
departmentIds: [DEPARTMENT_ID],
});
const response = await app.inject({
method: "POST",
url: `/api/reimbursements/${REIMBURSEMENT_ID}/pay`,
headers: { authorization: "Bearer test" },
payload: {
paymentVoucherNo: "SYNTHETIC-ALLOWLIST-001",
paymentDate: "2026-07-18",
paymentChannel: "bank",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error.details.payment).toBe("payment_batch_v1_required");
expect(tx.reimbursementForm.update).not.toHaveBeenCalled();
expect(tx.invoicePool.updateMany).not.toHaveBeenCalled();
expect(tx.auditLog.create).not.toHaveBeenCalled();
await app.close();
});
it("keeps direct payment closed for an active batch after the source department leaves rollout", async () => {
const { app, tx } = await buildApp({
rolloutType: "department_allowlist",
departmentIds: ["44444444-4444-4444-8444-444444444444"],
activePaymentBatch: true,
});
const response = await app.inject({
method: "POST",
url: `/api/reimbursements/${REIMBURSEMENT_ID}/pay`,
headers: { authorization: "Bearer test" },
payload: {
paymentVoucherNo: "SYNTHETIC-ACTIVE-BATCH-001",
paymentDate: "2026-07-18",
paymentChannel: "bank",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error.details).toMatchObject({
payment: "payment_batch_v1_required",
paymentBatch: "active_batch_exists",
});
expect(tx.paymentBatchItem.findFirst).toHaveBeenCalledTimes(1);
expect(tx.reimbursementForm.update).not.toHaveBeenCalled();
expect(tx.invoicePool.updateMany).not.toHaveBeenCalled();
expect(tx.auditLog.create).not.toHaveBeenCalled();
await app.close();
});
});
+80 -11
查看文件
@@ -55,6 +55,12 @@ async function buildXlsxBuffer(rows) {
async function buildApp(options = {}) {
const app = Fastify();
const actor = options.actor ?? {
id: "actor-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
roleCodes: ["employee", "system_admin"],
permissionCodes: ["system.accounts.manage"],
};
const existingEmployees = options.existingEmployees ?? [];
const departments = options.departments ?? [];
const auditCreate = vi.fn().mockResolvedValue({});
@@ -100,24 +106,19 @@ async function buildApp(options = {}) {
$transaction: vi.fn(async (callback) => callback(tx)),
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = {
id: "actor-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
permissionCodes: ["system.users"],
};
request.employee = actor;
const permissions = request.employee.permissionCodes ?? [];
if (!permissions.includes("*") && !permissions.includes(permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("authenticate", async (request) => {
request.employee = {
id: "actor-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
permissionCodes: ["system.users"],
};
request.employee = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissions = employee?.permissionCodes ?? [];
return permissions.includes("*") || permissions.includes(permissionCode);
});
app.decorate("hasPermission", () => true);
await app.register(multipart, {
attachFieldsToBody: false,
@@ -137,6 +138,35 @@ async function buildApp(options = {}) {
}
describe("users import routes", () => {
it("rejects the legacy system.users permission before reading the import", async () => {
const { app, auditCreate, departmentFindMany, employeeFindMany } = await buildApp({
actor: {
id: "actor-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
roleCodes: ["employee"],
permissionCodes: ["system.users"],
},
});
const multipartRequest = buildMultipartRequest({
filename: "users.csv",
contentType: "text/csv",
content: "employeeNo,name,phone,email,departmentName\nE001,Alice,13800000000,[email protected],行政部\n",
});
const response = await app.inject({
method: "POST",
url: "/api/users/import/dry-run",
...multipartRequest,
});
expect(response.statusCode).toBe(403);
expect(departmentFindMany).not.toHaveBeenCalled();
expect(employeeFindMany).not.toHaveBeenCalled();
expect(auditCreate).not.toHaveBeenCalled();
await app.close();
});
it("supports xlsx dry-run and allows manager references to later rows in the same file", async () => {
const { app } = await buildApp({
departments: [{ id: "dept-1", name: "行政部", archived_at: null }],
@@ -321,6 +351,45 @@ describe("users import routes", () => {
await app.close();
});
it.each(["admin", "system_admin"])(
"prevents a system administrator from importing the protected %s role",
async (protectedRole) => {
const {
app,
auditCreate,
departmentFindMany,
employeeCreate,
employeeFindMany,
roleCreateMany,
} = await buildApp({
departments: [{ id: "dept-1", name: "行政部", archived_at: null }],
});
const multipartRequest = buildMultipartRequest({
filename: "users.csv",
contentType: "text/csv",
content: [
"employeeNo,name,phone,email,departmentName,title,directManagerEmployeeNo,roles,hireDate",
`E004,Dana,13800000004,[email protected],行政部,,,${protectedRole},2026-03-29`,
].join("\n"),
});
const response = await app.inject({
method: "POST",
url: "/api/users/import/apply",
...multipartRequest,
});
expect(response.statusCode).toBe(403);
expect(departmentFindMany).toHaveBeenCalledTimes(1);
expect(employeeFindMany).toHaveBeenCalledTimes(1);
expect(employeeCreate).not.toHaveBeenCalled();
expect(roleCreateMany).not.toHaveBeenCalled();
expect(auditCreate).not.toHaveBeenCalled();
await app.close();
},
);
it("refuses apply when preview contains invalid rows and does not create employees", async () => {
const { app, employeeCreate } = await buildApp();
const multipartRequest = buildMultipartRequest({
+76 -1
查看文件
@@ -30,7 +30,7 @@ async function buildApp({ routeOptions = {}, employee } = {}) {
{
id: "actor-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
permissionCodes: ["system.users"],
permissionCodes: ["system.accounts.manage"],
};
app.decorate("prisma", {
@@ -53,6 +53,13 @@ async function buildApp({ routeOptions = {}, employee } = {}) {
const permissionCodes = requestEmployee.permissionCodes ?? [];
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
});
app.decorate("assertPermission", (requestEmployee, permissionCode) => {
const permissionCodes = requestEmployee.permissionCodes ?? [];
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
return permissionCode;
});
app.decorate("config", {});
await app.register(usersRoutes, { prefix: "/api", ...routeOptions });
@@ -193,4 +200,72 @@ describe("usersRoutes list query", () => {
await app.close();
});
it("returns a minimal directory DTO and does not select or search contact fields", async () => {
const { app, findMany } = await buildApp({
routeOptions: {
basePath: "/employees",
allowDepartmentFilter: true,
directoryOnly: true,
managementPermissionCode: "system.users",
listPermissionCodes: ["expense.view_own"],
},
employee: {
id: "viewer-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
permissionCodes: ["expense.view_own"],
},
});
const response = await app.inject({ method: "GET", url: "/api/employees?q=alice" });
expect(response.statusCode).toBe(200);
expect(response.json().data.items[0]).toEqual({
id: "11111111-1111-4111-8111-111111111111",
employeeNo: "E001",
name: "Alice",
title: "员工",
status: "active",
department: null,
avatarUrl: null,
});
const query = findMany.mock.calls[0][0];
expect(query.select).toEqual({
id: true,
employee_no: true,
name: true,
title: true,
status: true,
avatar_path: true,
department: { select: { id: true, name: true } },
});
const searchFields = query.where.AND[0].OR.map((item) => Object.keys(item)[0]);
expect(searchFields).toEqual(["employee_no", "name"]);
await app.close();
});
it("rejects management scope before directory queries without the personnel permission", async () => {
const { app, findMany, count } = await buildApp({
routeOptions: {
basePath: "/employees",
allowDepartmentFilter: true,
directoryOnly: true,
managementPermissionCode: "system.users",
listPermissionCodes: ["expense.view_own"],
},
employee: {
id: "system-admin-1",
department_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
permissionCodes: ["expense.view_own", "system.accounts.manage"],
},
});
const response = await app.inject({ method: "GET", url: "/api/employees?scope=management" });
expect(response.statusCode).toBe(403);
expect(findMany).not.toHaveBeenCalled();
expect(count).not.toHaveBeenCalled();
await app.close();
});
});
@@ -0,0 +1,171 @@
const Fastify = require("fastify");
const usersRoutes = require("../../../src/routes/users");
const { encryptStringOrThrow } = require("../../../src/services/crypto");
const { AppError } = require("../../../src/utils/AppError");
const ACTOR_ID = "11111111-1111-4111-8111-111111111111";
const EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const FIELD_ENCRYPTION_KEY = Buffer.alloc(32, 7).toString("base64");
async function buildApp(permissionCodes) {
const app = Fastify();
const encryptedBank = encryptStringOrThrow({ fieldEncryptionKey: FIELD_ENCRYPTION_KEY }, "6222000012345678");
const encryptedIdentity = encryptStringOrThrow({ fieldEncryptionKey: FIELD_ENCRYPTION_KEY }, "110101199001011234");
const actor = {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
roleCodes: [],
permissionCodes,
};
const employeeFindUnique = vi.fn().mockResolvedValue({
id: EMPLOYEE_ID,
bank_name: "合成银行",
bank_account_encrypted: encryptedBank,
id_number_encrypted: encryptedIdentity,
});
const employeeUpdate = vi.fn(async ({ data }) => ({ id: EMPLOYEE_ID, ...data }));
const auditCreate = vi.fn().mockResolvedValue({ id: "audit-1" });
const transaction = vi.fn(async (callback) => callback({
employee: {
findUnique: employeeFindUnique,
update: employeeUpdate,
},
auditLog: { create: auditCreate },
}));
app.decorate("config", { fieldEncryptionKey: FIELD_ENCRYPTION_KEY });
app.decorate("prisma", {
employee: { findUnique: employeeFindUnique },
auditLog: { create: auditCreate },
$transaction: transaction,
});
app.decorate("authenticate", async (request) => {
request.employee = actor;
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = actor;
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissions = employee?.permissionCodes ?? [];
return permissions.includes("*") || permissions.includes(permissionCode);
});
app.decorate("assertPermission", (employee, permissionCode) => {
if (!app.hasPermission(employee, permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
return permissionCode;
});
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 ?? {},
},
}));
await app.register(usersRoutes, { prefix: "/api" });
return { app, auditCreate, employeeFindUnique, employeeUpdate, transaction };
}
describe("user sensitive field permissions", () => {
it("rejects an OA system administrator before any sensitive employee query", async () => {
const testApp = await buildApp(["system.accounts.manage", "system.roles.manage", "system.settings"]);
const response = await testApp.app.inject({ method: "GET", url: `/api/users/${EMPLOYEE_ID}/sensitive` });
expect(response.statusCode).toBe(403);
expect(testApp.employeeFindUnique).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
await testApp.app.close();
});
it("returns only bank fields to finance and audits the authorized scope", async () => {
const testApp = await buildApp(["employee.bank.read"]);
const response = await testApp.app.inject({ method: "GET", url: `/api/users/${EMPLOYEE_ID}/sensitive` });
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
bankName: "合成银行",
bankAccount: "6222000012345678",
});
expect(response.json().data).not.toHaveProperty("idNumber");
expect(testApp.employeeFindUnique).toHaveBeenCalledWith({
where: { id: EMPLOYEE_ID },
select: {
id: true,
bank_name: true,
bank_account_encrypted: true,
},
});
expect(testApp.auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "SYSTEM_USER_SENSITIVE_VIEWED",
extra: { scopes: ["bank"] },
}),
});
await testApp.app.close();
});
it("rejects finance writes before opening a transaction", async () => {
const testApp = await buildApp(["employee.bank.read"]);
const response = await testApp.app.inject({
method: "PATCH",
url: `/api/users/${EMPLOYEE_ID}/sensitive`,
payload: { bankName: "新银行" },
});
expect(response.statusCode).toBe(403);
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.employeeUpdate).not.toHaveBeenCalled();
await testApp.app.close();
});
it("requires every requested sensitive-field permission before mutation", async () => {
const testApp = await buildApp(["employee.bank.manage"]);
const response = await testApp.app.inject({
method: "PATCH",
url: `/api/users/${EMPLOYEE_ID}/sensitive`,
payload: { bankName: "新银行", idNumber: "110101199001011234" },
});
expect(response.statusCode).toBe(403);
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.employeeUpdate).not.toHaveBeenCalled();
await testApp.app.close();
});
it("writes only authorized fields and keeps plaintext out of the audit", async () => {
const testApp = await buildApp(["employee.bank.manage", "employee.identity.manage"]);
const response = await testApp.app.inject({
method: "PATCH",
url: `/api/users/${EMPLOYEE_ID}/sensitive`,
payload: { bankAccount: "6222000099995678", idNumber: "110101199901011234" },
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
id: EMPLOYEE_ID,
updatedFields: ["bankAccountMasked", "idNumberMasked"],
});
const auditArgument = testApp.auditCreate.mock.calls[0][0];
expect(auditArgument.data.extra).toEqual({
changes: {
bankAccountMasked: "6222********5678",
idNumberMasked: "110101********1234",
},
});
expect(JSON.stringify(auditArgument)).not.toContain("6222000099995678");
expect(JSON.stringify(auditArgument)).not.toContain("110101199901011234");
await testApp.app.close();
});
});
+237 -13
查看文件
@@ -6,10 +6,18 @@ const { AppError } = require("../../../src/utils/AppError");
const ACTOR_ID = "11111111-1111-4111-8111-111111111111";
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
const USER_ID = "22222222-2222-4222-8222-222222222222";
const MANAGER_ID = "33333333-3333-4333-8333-333333333333";
async function buildApp({
createdEmployeeNo = "HYD000001",
currentEmployee = null,
actor = {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
roleCodes: ["system_admin"],
permissionCodes: ["system.accounts.manage", "system.roles.manage"],
},
currentRoles = ["employee"],
} = {}) {
const app = Fastify();
@@ -56,11 +64,25 @@ async function buildApp({
);
const employeeUpdate = vi.fn();
const employeeRoleCreateMany = vi.fn().mockResolvedValue({ count: 1 });
const employeeRoleFindMany = vi.fn().mockResolvedValue([{ role_code: "employee" }]);
const employeeRoleFindMany = vi.fn().mockResolvedValue(currentRoles.map((role_code) => ({ role_code })));
const employeeRoleDeleteMany = vi.fn().mockResolvedValue({ count: currentRoles.length });
const auditCreate = vi.fn().mockResolvedValue({ id: "audit-1" });
const authSessionUpdateMany = vi.fn().mockResolvedValue({ count: 0 });
const passwordResetCodeUpdateMany = vi.fn().mockResolvedValue({ count: 0 });
const emailLoginCodeUpdateMany = vi.fn().mockResolvedValue({ count: 0 });
const lifecycleEventCreate = vi.fn().mockResolvedValue({ id: "lifecycle-1" });
const checklistTaskCreateMany = vi.fn().mockResolvedValue({ count: 1 });
const wecomSyncRunCreate = vi.fn().mockResolvedValue({ id: "sync-run-1" });
const queryRaw = vi.fn(async (strings, employeeId) => {
const sql = Array.isArray(strings) ? strings.join(" ") : String(strings ?? "");
if (sql.includes('FROM "employee_roles"')) {
return currentRoles.map((role_code) => ({ role_code }));
}
if (sql.includes('FROM "employees"')) {
return [{ id: employeeId }];
}
return [];
});
const tx = {
department: {
@@ -73,6 +95,13 @@ async function buildApp({
},
employeeRole: {
createMany: employeeRoleCreateMany,
deleteMany: employeeRoleDeleteMany,
},
employeeLifecycleEvent: {
create: lifecycleEventCreate,
},
employeeChecklistTask: {
createMany: checklistTaskCreateMany,
},
auditLog: {
create: auditCreate,
@@ -86,9 +115,10 @@ async function buildApp({
emailLoginCode: {
updateMany: emailLoginCodeUpdateMany,
},
$queryRaw: queryRaw,
};
app.decorate("config", {});
app.decorate("config", { employeeLifecycleEnabled: true });
app.decorate("prisma", {
department: {
findUnique: departmentFindUnique,
@@ -99,27 +129,36 @@ async function buildApp({
employeeRole: {
findMany: employeeRoleFindMany,
},
featureFlag: {
findUnique: vi.fn().mockResolvedValue({
id: "flag-employee-lifecycle",
flag_key: "employee_lifecycle_v1",
override_mode: "force_on",
rollout_type: "global",
department_ids: [],
version: 1,
}),
},
wecomDirectorySyncRun: {
create: wecomSyncRunCreate,
},
wecomIdentityBinding: {},
$transaction: vi.fn(async (callback) => callback(tx)),
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
request.employee = {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
permissionCodes: ["system.users"],
};
request.employee = actor;
const permissions = request.employee.permissionCodes ?? [];
if (!permissions.includes("*") && !permissions.includes(permissionCode)) {
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
}
});
app.decorate("authenticate", async (request) => {
request.employee = {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
permissionCodes: ["system.users"],
};
request.employee = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissions = employee?.permissionCodes ?? [];
return permissions.includes("*") || permissions.includes(permissionCode);
});
app.decorate("hasPermission", () => true);
app.setErrorHandler((error, request, reply) => {
if (error instanceof AppError) {
return reply.status(error.statusCode).send({
@@ -143,10 +182,15 @@ async function buildApp({
employeeUpdate,
employeeRoleCreateMany,
employeeRoleFindMany,
employeeRoleDeleteMany,
auditCreate,
authSessionUpdateMany,
passwordResetCodeUpdateMany,
emailLoginCodeUpdateMany,
lifecycleEventCreate,
checklistTaskCreateMany,
wecomSyncRunCreate,
queryRaw,
};
}
@@ -162,6 +206,7 @@ describe("usersRoutes write flows", () => {
phone: "13800000001",
email: "[email protected]",
roles: ["employee"],
syncWecomDirectory: false,
},
});
@@ -223,6 +268,185 @@ describe("usersRoutes write flows", () => {
await app.close();
});
it("prevents a system administrator from creating protected administrator roles", async () => {
const { app, departmentFindUnique, employeeCreate } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/users",
payload: {
name: "受限账号",
phone: "13800000002",
email: "[email protected]",
roles: ["employee", "system_admin"],
},
});
expect(response.statusCode).toBe(403);
expect(response.json().error.details).toEqual({ role: "protected_role_change_not_allowed" });
expect(departmentFindUnique).not.toHaveBeenCalled();
expect(employeeCreate).not.toHaveBeenCalled();
await app.close();
});
it("prevents a system administrator from granting or revoking protected roles before mutation", async () => {
const grantApp = await buildApp();
const grantResponse = await grantApp.app.inject({
method: "POST",
url: `/api/users/${USER_ID}/roles`,
payload: { roles: ["employee", "admin"] },
});
expect(grantResponse.statusCode).toBe(403);
expect(grantApp.employeeRoleDeleteMany).not.toHaveBeenCalled();
expect(grantApp.employeeRoleCreateMany).not.toHaveBeenCalled();
await grantApp.app.close();
const revokeApp = await buildApp({ currentRoles: ["employee", "system_admin"] });
const revokeResponse = await revokeApp.app.inject({
method: "POST",
url: `/api/users/${USER_ID}/roles`,
payload: { roles: ["employee"] },
});
expect(revokeResponse.statusCode).toBe(403);
expect(revokeApp.employeeRoleDeleteMany).not.toHaveBeenCalled();
expect(revokeApp.employeeRoleCreateMany).not.toHaveBeenCalled();
await revokeApp.app.close();
});
it("prevents a system administrator from changing their own business roles before lookup", async () => {
const testApp = await buildApp();
const response = await testApp.app.inject({
method: "POST",
url: `/api/users/${ACTOR_ID}/roles`,
payload: { roles: ["employee", "manager", "system_admin"] },
});
expect(response.statusCode).toBe(403);
expect(response.json().error.details).toEqual({ user: "self_role_change_not_allowed" });
expect(testApp.employeeRoleFindMany).not.toHaveBeenCalled();
expect(testApp.employeeRoleDeleteMany).not.toHaveBeenCalled();
expect(testApp.employeeRoleCreateMany).not.toHaveBeenCalled();
await testApp.app.close();
});
it.each([
{
name: "批量调部门",
url: "/api/users/batch/transfer-department",
payload: { employeeIds: [USER_ID], departmentId: DEPARTMENT_ID },
},
{
name: "批量设直属经理",
url: "/api/users/batch/set-manager",
payload: { employeeIds: [USER_ID], managerId: MANAGER_ID },
},
{
name: "批量停用",
url: "/api/users/batch/disable",
payload: { employeeIds: [USER_ID] },
},
{
name: "批量启用",
url: "/api/users/batch/enable",
payload: { employeeIds: [USER_ID] },
},
])("rejects $name when any target has a protected role before all writes", async ({ url, payload }) => {
const testApp = await buildApp({ currentRoles: ["employee", "system_admin"] });
const response = await testApp.app.inject({ method: "POST", url, payload });
expect(response.statusCode).toBe(403);
expect(response.json().error.details).toEqual({ user: "protected_account_not_manageable" });
expect(testApp.queryRaw).toHaveBeenCalledTimes(2);
expect(testApp.employeeUpdate).not.toHaveBeenCalled();
expect(testApp.lifecycleEventCreate).not.toHaveBeenCalled();
expect(testApp.checklistTaskCreateMany).not.toHaveBeenCalled();
expect(testApp.authSessionUpdateMany).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
expect(testApp.wecomSyncRunCreate).not.toHaveBeenCalled();
await testApp.app.close();
});
it.each([
{ name: "更新账号", method: "PATCH", path: "", payload: { name: "受保护账号" } },
{ name: "归档账号", method: "POST", path: "/archive" },
{ name: "停用账号", method: "POST", path: "/disable" },
{ name: "启用账号", method: "POST", path: "/enable" },
{ name: "解锁账号", method: "POST", path: "/unlock" },
])("rejects $name for a protected target before account side effects", async ({ method, path, payload }) => {
const testApp = await buildApp({ currentRoles: ["employee", "admin"] });
const response = await testApp.app.inject({
method,
url: `/api/users/${USER_ID}${path}`,
...(payload ? { payload } : {}),
});
expect(response.statusCode).toBe(403);
expect(response.json().error.details).toEqual({ user: "protected_account_not_manageable" });
expect(testApp.employeeUpdate).not.toHaveBeenCalled();
expect(testApp.authSessionUpdateMany).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
expect(testApp.wecomSyncRunCreate).not.toHaveBeenCalled();
await testApp.app.close();
});
it("allows an emergency administrator to assign system_admin with before/after role audit", async () => {
const testApp = await buildApp({
actor: {
id: ACTOR_ID,
department_id: DEPARTMENT_ID,
roleCodes: ["admin"],
permissionCodes: ["*"],
},
});
const response = await testApp.app.inject({
method: "POST",
url: `/api/users/${USER_ID}/roles`,
payload: { roles: ["employee", "system_admin"] },
});
expect(response.statusCode).toBe(200);
expect(testApp.employeeRoleDeleteMany).toHaveBeenCalledTimes(1);
expect(testApp.auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "SYSTEM_USER_ROLES_SET",
extra: {
beforeRoleCodes: ["employee"],
afterRoleCodes: ["employee", "system_admin"],
},
}),
});
await testApp.app.close();
});
it("prevents a system administrator from resetting a protected account", async () => {
const testApp = await buildApp({ currentRoles: ["employee", "admin"] });
const response = await testApp.app.inject({
method: "POST",
url: `/api/users/${USER_ID}/reset-password`,
payload: { newPassword: "AdministratorReset1234" },
});
expect(response.statusCode).toBe(403);
expect(response.json().error.details).toEqual({ user: "protected_account_not_manageable" });
expect(testApp.employeeUpdate).not.toHaveBeenCalled();
expect(testApp.authSessionUpdateMany).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
await testApp.app.close();
});
it("revokes sessions and outstanding challenges during an administrator password reset", async () => {
const {
app,
@@ -4,10 +4,21 @@ describe("Workflow Route Permissions", () => {
const {
buildWorkflowEntityVisibilityWhere,
canViewWorkflowEntityType,
employeeHasBusinessApproveRole,
listAllowedActionsForTask,
parseTaskListQuery,
} = workflowRoutes.__testables;
it.each(["admin", "system_admin"])(
"does not treat %s as a business approval role even with broad runtime permissions",
(roleCode) => {
expect(employeeHasBusinessApproveRole({
roleCodes: [roleCode],
permissionCodes: ["*", "expense.approve"],
}, "reimbursement")).toBe(false);
},
);
it("allows leave approvers to act on leave tasks", () => {
const actions = listAllowedActionsForTask(
{ employee: { permissionCodes: ["leave.approve"] } },
@@ -279,37 +279,40 @@ describe("workflow transfer route", () => {
await app.close();
});
it("does not treat admin-only target as a business approver", async () => {
const tx = buildTx({ entityType: "reimbursement", targetRoleCode: "admin" });
const app = await buildApp({
prisma: buildPrisma(tx),
employee: {
id: "actor-1",
roleCodes: ["manager"],
permissionCodes: ["expense.transfer"],
},
});
it.each(["admin", "system_admin"])(
"does not treat %s-only target as a business approver",
async (targetRoleCode) => {
const tx = buildTx({ entityType: "reimbursement", targetRoleCode });
const app = await buildApp({
prisma: buildPrisma(tx),
employee: {
id: "actor-1",
roleCodes: ["manager"],
permissionCodes: ["expense.transfer"],
},
});
const response = await app.inject({
method: "POST",
url: `/api/workflow/tasks/${buildTaskRow().id}/transfer`,
headers: { authorization: "Bearer test" },
payload: {
toApproverId: "44444444-4444-4444-8444-444444444444",
reason: "当前事项需转交对应审批人继续处理,请及时跟进。",
},
});
const response = await app.inject({
method: "POST",
url: `/api/workflow/tasks/${buildTaskRow().id}/transfer`,
headers: { authorization: "Bearer test" },
payload: {
toApproverId: "44444444-4444-4444-8444-444444444444",
reason: "当前事项需转交对应审批人继续处理,请及时跟进。",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error.details).toEqual(
expect.objectContaining({
toApproverId: "target_not_approver",
}),
);
expect(tx.workflowTask.update).not.toHaveBeenCalled();
expect(response.statusCode).toBe(409);
expect(response.json().error.details).toEqual(
expect.objectContaining({
toApproverId: "target_not_approver",
}),
);
expect(tx.workflowTask.update).not.toHaveBeenCalled();
await app.close();
});
await app.close();
},
);
it("rejects transfer to the applicant", async () => {
const tx = buildTx({ entityType: "leave", targetRoleCode: "manager" });
@@ -0,0 +1,167 @@
const fs = require("node:fs");
const path = require("node:path");
const {
PaymentConcurrencyCheckError,
validatePaymentConcurrencyEnvironment,
} = require("../../../src/scripts/check-payment-postgres-concurrency");
const REPO_ROOT = path.resolve(__dirname, "../../../..");
function validEnv() {
return {
RUN_PAYMENT_POSTGRES_CONCURRENCY: "1",
NODE_ENV: "test",
JOBS_ENABLED: "false",
RATE_LIMIT_ENABLED: "false",
TRUST_PROXY_HOPS: "0",
PAYMENT_BATCH_ENABLED: "true",
ERP_SYNC_ENABLED: "false",
EMAIL_ENABLED: "false",
SMTP_HOST: "",
SMTP_USER: "",
SMTP_PASS: "",
IM_NOTIFIER_ENABLED: "false",
WECOM_ENABLED: "false",
WECOM_AGENT_SECRET: "",
WECOM_CONTACT_SECRET: "",
WECOM_HR_ASSISTANT_SECRET: "",
OIDC_ENABLED: "false",
OIDC_CLIENT_SECRET: "",
SERVE_CLIENT_DIST: "false",
DATABASE_URL:
"postgresql://synthetic:[email protected]:5432/hyb_oa_payment_test?schema=public",
PAYMENT_CONCURRENCY_DATABASE_CONFIRM: "hyb_oa_payment_test",
JWT_SECRET: "synthetic-jwt-secret",
FIELD_ENCRYPTION_KEY: "synthetic-field-key",
};
}
function expectSafeFailure(env, expectedCode) {
try {
validatePaymentConcurrencyEnvironment(env);
throw new Error("expected validation to fail");
} catch (error) {
expect(error).toBeInstanceOf(PaymentConcurrencyCheckError);
expect(error.safeCode).toBe(expectedCode);
expect(error.message).toBe(expectedCode);
}
}
describe("payment PostgreSQL concurrency guard", () => {
it("accepts only an explicitly confirmed isolated loopback target", () => {
expect(validatePaymentConcurrencyEnvironment(validEnv())).toEqual(
expect.objectContaining({
databaseName: "hyb_oa_payment_test",
}),
);
});
it("requires explicit opt-in and test-only execution", () => {
expectSafeFailure(
{ ...validEnv(), RUN_PAYMENT_POSTGRES_CONCURRENCY: "0" },
"explicit_opt_in_required",
);
expectSafeFailure(
{ ...validEnv(), NODE_ENV: "production" },
"test_environment_required",
);
});
it("requires jobs, rate limiting and proxy trust to be disabled", () => {
expectSafeFailure({ ...validEnv(), JOBS_ENABLED: "true" }, "jobs_must_be_disabled");
expectSafeFailure(
{ ...validEnv(), RATE_LIMIT_ENABLED: "true" },
"rate_limit_must_be_disabled",
);
expectSafeFailure(
{ ...validEnv(), TRUST_PROXY_HOPS: "1" },
"trust_proxy_must_be_disabled",
);
});
it("requires the payment path on and external financial sync off", () => {
expectSafeFailure(
{ ...validEnv(), PAYMENT_BATCH_ENABLED: "false" },
"payment_batch_must_be_enabled",
);
expectSafeFailure(
{ ...validEnv(), ERP_SYNC_ENABLED: "true" },
"erp_sync_must_be_disabled",
);
});
it("refuses external notification and identity providers", () => {
expectSafeFailure(
{ ...validEnv(), EMAIL_ENABLED: "true" },
"email_provider_must_be_disabled",
);
expectSafeFailure(
{ ...validEnv(), SMTP_HOST: "smtp.example.test" },
"smtp_host_forbidden",
);
expectSafeFailure(
{ ...validEnv(), IM_NOTIFIER_ENABLED: "true" },
"im_notifier_must_be_disabled",
);
expectSafeFailure(
{ ...validEnv(), WECOM_ENABLED: "true" },
"wecom_must_be_disabled",
);
expectSafeFailure(
{ ...validEnv(), OIDC_ENABLED: "true" },
"oidc_must_be_disabled",
);
});
it("refuses remote, shared-looking and unconfirmed databases", () => {
expectSafeFailure(
{
...validEnv(),
DATABASE_URL:
"postgresql://synthetic:[email protected]:5432/hyb_oa_payment_test",
},
"database_host_not_loopback",
);
expectSafeFailure(
{
...validEnv(),
DATABASE_URL:
"postgresql://synthetic:[email protected]:5432/hyb_oa_payment_test?host=db.example.test",
},
"database_host_not_loopback",
);
expectSafeFailure(
{
...validEnv(),
DATABASE_URL: "postgresql://synthetic:[email protected]:5432/hyb_oa",
PAYMENT_CONCURRENCY_DATABASE_CONFIRM: "hyb_oa",
},
"database_name_not_isolated",
);
expectSafeFailure(
{ ...validEnv(), PAYMENT_CONCURRENCY_DATABASE_CONFIRM: "hyb_oa_payment_other" },
"database_confirmation_mismatch",
);
});
it("keeps the repository runner isolated and cleanup authoritative", () => {
const source = fs.readFileSync(
path.join(REPO_ROOT, "scripts/qa/run-web-gates.sh"),
"utf8",
);
const dropFunction = source.slice(
source.indexOf("qa_dropdb()"),
source.indexOf("qa_cleanup_server()"),
);
expect(source).toContain('DEFAULT_QA_DB_PREFIX="hyb_oa_payment"');
expect(source).toContain('RUN_PAYMENT_POSTGRES_CONCURRENCY=1');
expect(source).toContain('export PAYMENT_CONCURRENCY_DATABASE_CONFIRM="$QA_DB_NAME"');
expect(source).toContain('export ERP_SYNC_ENABLED=false');
expect(source).toContain('export IM_NOTIFIER_ENABLED=false');
expect(dropFunction).toContain("dropdb --force --if-exists");
expect(dropFunction).toContain("return 1");
expect(dropFunction).not.toContain("|| true");
});
});
+37
查看文件
@@ -86,6 +86,32 @@ describe("workflow assignee resolution", () => {
it("throws if rule is empty or missing roles", () => {
expect(() => workflowUtils.buildWorkflowStepsFromApprovalRule({})).toThrow(/参数校验失败/);
});
it.each(["admin", "system_admin"])(
"rejects protected system role %s in approval rules",
(roleCode) => {
expect(() => workflowUtils.buildWorkflowStepsFromApprovalRule({ level1_role: roleCode }))
.toThrow(/参数校验失败/);
},
);
});
describe("getWorkflowStepsSnapshot", () => {
it.each(["admin", "system_admin"])(
"rejects protected system role %s in historical snapshots",
(roleCode) => {
expect(() => workflowUtils.getWorkflowStepsSnapshot({
context_data: {
workflow_steps_snapshot: [
{
id: `approval_1_${roleCode}`,
assignee_rule: { type: "role", value: roleCode },
},
],
},
})).toThrow(/参数校验失败/);
},
);
});
describe("buildApprovalWorkflowSnapshot", () => {
@@ -265,6 +291,17 @@ describe("workflow assignee resolution", () => {
await expect(workflowUtils.resolveAssigneeFromRule(null)).rejects.toThrow(/参数校验失败/);
await expect(workflowUtils.resolveAssigneeFromRule({ type: "unknown" })).rejects.toThrow(/参数校验失败/);
});
it.each(["admin", "system_admin"])(
"rejects protected system role %s during runtime resolution",
async (roleCode) => {
await expect(
workflowUtils.resolveAssigneeFromRule({ type: "role", value: roleCode }),
).rejects.toMatchObject({
details: { workflow: "unsupported_business_approval_role" },
});
},
);
});
describe("toMoneyString", () => {
@@ -206,4 +206,25 @@ describe("workspace small-team navigation defaults", () => {
expect(mainLabels).not.toContain("AP 运营");
expect(mainLabels).not.toContain("付款批次");
});
it("shows payment review navigation to manager reviewers without granting finance-only invoice tools", async () => {
const manager = {
id: "manager-reviewer-1",
department_id: "dept-1",
roleCodes: ["manager"],
permissionCodes: resolvePermissionsForRoles(["manager"]),
};
const navigation = await getSystemNavigation({
prisma: buildPrisma(["payment_batch_v1"]),
config: { ...buildConfig(), paymentBatchEnabled: true },
employee: manager,
hasPermission: (candidate, permissionCode) => hasPermission(candidate.permissionCodes, permissionCode),
});
const mainLabels = navigation.sections.main.map((item) => item.label);
expect(mainLabels).toContain("付款");
expect(mainLabels).toContain("应付账款");
expect(mainLabels).not.toContain("票据");
});
});