文件
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

765 行
33 KiB
JavaScript

const Fastify = require("fastify");
const usersRoutes = require("../../../src/routes/users");
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();
const departmentFindUnique = vi.fn().mockResolvedValue({
id: DEPARTMENT_ID,
archived_at: null,
});
const employeeCreate = vi.fn(async ({ data }) => ({
id: USER_ID,
employee_no: data.employee_no ?? createdEmployeeNo,
name: data.name,
phone: data.phone,
email: data.email,
status: data.status,
department_id: data.department_id,
title: data.title,
direct_manager_id: data.direct_manager_id ?? null,
hire_date: data.hire_date,
created_at: data.created_at,
updated_at: data.updated_at,
}));
const employeeFindUnique = vi
.fn()
.mockResolvedValue(
currentEmployee ?? {
id: USER_ID,
employee_no: "HYD000321",
name: "Alice",
phone: "13800000000",
email: "[email protected]",
status: "active",
department_id: DEPARTMENT_ID,
title: "员工",
direct_manager_id: null,
hire_date: new Date("2026-05-01T00:00:00.000Z"),
bank_account_encrypted: "",
bank_name: "",
id_number_encrypted: null,
archived_at: null,
created_at: new Date("2026-05-01T00:00:00.000Z"),
updated_at: new Date("2026-05-01T00:00:00.000Z"),
roles: [{ role_code: "employee" }],
},
);
const employeeUpdate = vi.fn(async ({ data }) => ({
...(currentEmployee ?? {
id: USER_ID,
employee_no: "HYD000321",
name: "Alice",
phone: "13800000000",
email: "[email protected]",
status: "active",
department_id: DEPARTMENT_ID,
title: "员工",
direct_manager_id: null,
hire_date: new Date("2026-05-01T00:00:00.000Z"),
archived_at: null,
created_at: new Date("2026-05-01T00:00:00.000Z"),
updated_at: new Date("2026-05-01T00:00:00.000Z"),
roles: [{ role_code: "employee" }],
wecom_identity_binding: null,
wecom_directory_sync_runs: [],
}),
...data,
}));
const employeeRoleCreateMany = vi.fn().mockResolvedValue({ count: 1 });
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: {
findUnique: departmentFindUnique,
},
employee: {
create: employeeCreate,
findUnique: employeeFindUnique,
update: employeeUpdate,
},
employeeRole: {
createMany: employeeRoleCreateMany,
deleteMany: employeeRoleDeleteMany,
},
employeeLifecycleEvent: {
create: lifecycleEventCreate,
},
employeeChecklistTask: {
createMany: checklistTaskCreateMany,
},
auditLog: {
create: auditCreate,
},
authSession: {
updateMany: authSessionUpdateMany,
},
passwordResetCode: {
updateMany: passwordResetCodeUpdateMany,
},
emailLoginCode: {
updateMany: emailLoginCodeUpdateMany,
},
$queryRaw: queryRaw,
};
app.decorate("config", { employeeLifecycleEnabled: true });
app.decorate("prisma", {
department: {
findUnique: departmentFindUnique,
},
employee: {
findUnique: employeeFindUnique,
},
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,
}),
},
$transaction: vi.fn(async (callback) => callback(tx)),
});
app.decorate("requirePermission", (permissionCode) => async (request) => {
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 = actor;
});
app.decorate("hasPermission", (employee, permissionCode) => {
const permissions = employee?.permissionCodes ?? [];
return permissions.includes("*") || permissions.includes(permissionCode);
});
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: error.code ?? "SYS_001", message: error.message ?? "服务器内部错误", details: error.details ?? {} },
});
});
await app.register(usersRoutes, { prefix: "/api" });
return {
app,
departmentFindUnique,
employeeCreate,
employeeFindUnique,
employeeUpdate,
employeeRoleCreateMany,
employeeRoleFindMany,
employeeRoleDeleteMany,
auditCreate,
authSessionUpdateMany,
passwordResetCodeUpdateMany,
emailLoginCodeUpdateMany,
lifecycleEventCreate,
checklistTaskCreateMany,
wecomSyncRunCreate,
queryRaw,
};
}
describe("usersRoutes write flows", () => {
it("creates a user without employeeNo or password and returns generated credentials", async () => {
const { app, employeeCreate, employeeRoleCreateMany } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/users",
payload: {
name: "张三",
phone: "13800000001",
email: "[email protected]",
roles: ["employee"],
syncWecomDirectory: false,
},
});
expect(response.statusCode).toBe(200);
expect(employeeCreate).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({ email: "[email protected]" }),
}),
);
expect(employeeCreate.mock.calls[0][0].data).not.toHaveProperty("employee_no");
expect(employeeRoleCreateMany).toHaveBeenCalledWith(
expect.objectContaining({
data: [
expect.objectContaining({
employee_id: USER_ID,
role_code: "employee",
}),
],
}),
);
const payload = response.json().data;
expect(payload).toEqual(
expect.objectContaining({
id: USER_ID,
employeeNo: "HYD000001",
name: "张三",
email: "[email protected]",
roleCodes: ["employee"],
}),
);
expect(payload.oneTimePassword).toMatch(/^ResetA1[a-f0-9]{12}$/);
await app.close();
});
it("creates a user with a null phone when the field is omitted", async () => {
const { app, employeeCreate } = await buildApp();
const response = await app.inject({
method: "POST",
url: "/api/users",
payload: {
name: "暂缺手机号成员",
email: "[email protected]",
roles: ["employee"],
syncWecomDirectory: false,
},
});
expect(response.statusCode).toBe(200);
expect(employeeCreate).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ phone: null }),
}));
await app.close();
});
it("allows an administrator to explicitly clear an existing phone to null", async () => {
const { app, employeeUpdate } = await buildApp();
const response = await app.inject({
method: "PATCH",
url: `/api/users/${USER_ID}`,
payload: { phone: null },
});
expect(response.statusCode).toBe(200);
expect(employeeUpdate).toHaveBeenCalledWith(expect.objectContaining({
data: expect.objectContaining({ phone: null }),
}));
await app.close();
});
it("rejects employeeNo changes on patch", async () => {
const { app, employeeFindUnique, employeeUpdate } = await buildApp();
const response = await app.inject({
method: "PATCH",
url: `/api/users/${USER_ID}`,
payload: {
employeeNo: "HYD999999",
name: "李四",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error).toEqual(
expect.objectContaining({
code: "VALID_001",
details: { employeeNo: "immutable", reasonCode: "user.employee_no_immutable" },
}),
);
expect(employeeFindUnique).not.toHaveBeenCalled();
expect(employeeUpdate).not.toHaveBeenCalled();
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,
employeeUpdate,
authSessionUpdateMany,
passwordResetCodeUpdateMany,
emailLoginCodeUpdateMany,
auditCreate,
} = await buildApp();
const response = await app.inject({
method: "POST",
url: `/api/users/${USER_ID}/reset-password`,
payload: { newPassword: "AdministratorReset1234" },
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual({
id: USER_ID,
oneTimePassword: "AdministratorReset1234",
});
expect(employeeUpdate).toHaveBeenCalledWith({
where: { id: USER_ID },
data: expect.objectContaining({
must_change_password: true,
token_version: { increment: 1 },
email_login_code_failed_count: 0,
password_reset_failed_count: 0,
password_reset_request_count: 0,
}),
});
expect(authSessionUpdateMany).toHaveBeenCalledWith({
where: { employee_id: USER_ID, revoked_at: null },
data: { revoked_at: expect.any(Date), last_seen_at: expect.any(Date) },
});
expect(passwordResetCodeUpdateMany).toHaveBeenCalledWith({
where: { employee_id: USER_ID, invalidated_at: null },
data: { invalidated_at: expect.any(Date) },
});
expect(emailLoginCodeUpdateMany).toHaveBeenCalledWith({
where: { employee_id: USER_ID, used_at: null },
data: { used_at: expect.any(Date) },
});
expect(auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({ action: "SYSTEM_USER_PASSWORD_RESET" }),
});
await app.close();
});
});
describe("users hireDate calendar boundary", () => {
it.each(["POST", "PATCH"].flatMap((method) => ["2026-02-29", "2026-04-31", "2026-00-10"].map((date) => [method, date])))(
"%s rejects %s before account, role, audit or lifecycle writes", async (method, hireDate) => {
const fixture = await buildApp();
const { app } = fixture;
try {
const response = await app.inject({ method, url: method === "POST" ? "/api/users" : `/api/users/${USER_ID}`,
payload: method === "POST" ? { name: "Synthetic", email: "[email protected]", roles: ["employee"], syncWecomDirectory: false, hireDate } : { hireDate } });
expect(response.statusCode).toBe(400);
expect(response.json().error.code).toBe("VALID_001");
expect(response.json().error.details).toEqual({ formErrors: [], fieldErrors: { hireDate: ["invalid_calendar_date"] }, reasonCode: method === "POST" ? "user.create_input_invalid" : "user.update_input_invalid" });
expect(app.prisma.$transaction).not.toHaveBeenCalled();
for (const name of ["employeeCreate", "employeeUpdate", "employeeRoleCreateMany", "employeeRoleDeleteMany", "auditCreate", "lifecycleEventCreate", "checklistTaskCreateMany", "wecomSyncRunCreate"]) expect(fixture[name]).not.toHaveBeenCalled();
} finally { await app.close(); }
},
);
it.each(["POST", "PATCH"].flatMap((method) => ["2024-02-29", "2026-04-30", undefined].map((date) => [method, date])))(
"%s preserves valid or omitted hireDate %s", async (method, hireDate) => {
const { app, employeeCreate, employeeUpdate } = await buildApp();
try {
const before = Date.now();
const response = await app.inject({ method, url: method === "POST" ? "/api/users" : `/api/users/${USER_ID}`,
payload: method === "POST" ? { name: "Synthetic", email: "[email protected]", roles: ["employee"], syncWecomDirectory: false, ...(hireDate ? { hireDate } : {}) } : { title: "员工", ...(hireDate ? { hireDate } : {}) } });
expect(response.statusCode).toBe(200);
const data = (method === "POST" ? employeeCreate : employeeUpdate).mock.calls[0][0].data;
if (hireDate) expect(data.hire_date.toISOString()).toBe(`${hireDate}T00:00:00.000Z`);
else if (method === "PATCH") expect(data).not.toHaveProperty("hire_date");
else { expect(data.hire_date.getTime()).toBeGreaterThanOrEqual(before); expect(data.hire_date.getTime()).toBeLessThanOrEqual(Date.now()); }
} finally { await app.close(); }
},
);
});
describe("user immutable and empty update reasons", () => {
it.each([[{ employeeNo: "SYNTHETIC" }, 409, { employeeNo: "immutable", reasonCode: "user.employee_no_immutable" }], [{}, 400, { body: "empty", reasonCode: "user.update_empty" }]])("rejects %j without account writes", async (payload, status, details) => {
const { app, employeeUpdate, auditCreate } = await buildApp();
try {
const response = await app.inject({ method: "PATCH", url: `/api/users/${USER_ID}`, payload });
expect(response.statusCode).toBe(status);
expect(response.json().error).toEqual({ code: "VALID_001", message: "参数校验失败", details });
expect(app.prisma.$transaction).not.toHaveBeenCalled();
expect(employeeUpdate).not.toHaveBeenCalled();
expect(auditCreate).not.toHaveBeenCalled();
} finally { await app.close(); }
});
});
describe("remaining account error reasons", () => {
function expectNoWrites(t) {
for (const fn of [t.employeeCreate, t.employeeUpdate, t.employeeRoleCreateMany, t.employeeRoleDeleteMany, t.auditCreate, t.authSessionUpdateMany, t.passwordResetCodeUpdateMany, t.emailLoginCodeUpdateMany, t.lifecycleEventCreate, t.checklistTaskCreateMany, t.wecomSyncRunCreate]) expect(fn).not.toHaveBeenCalled();
}
it.each([
["PATCH", "/api/users/bad", { name: "合成" }, "user.id_invalid", { id: "invalid_uuid" }],
["POST", `/api/users/${USER_ID}/reset-password`, { newPassword: "" }, "user.reset_password_input_invalid", null],
["POST", `/api/users/${USER_ID}/roles`, { roles: [] }, "user.roles_input_invalid", null],
["POST", "/api/users/batch/transfer-department", { employeeIds: [] }, "user.batch_transfer_input_invalid", null],
["POST", "/api/users/batch/set-manager", { employeeIds: [] }, "user.batch_manager_input_invalid", null],
["POST", "/api/users/batch/disable", { employeeIds: [] }, "user.batch_toggle_input_invalid", null],
["POST", "/api/users/batch/enable", { employeeIds: [] }, "user.batch_toggle_input_invalid", null],
])("%s %s explains invalid input before transactions", async (method, url, payload, reasonCode, details) => {
const t = await buildApp();
try {
const response = await t.app.inject({ method, url, payload });
expect(response.statusCode).toBe(400);
expect(response.json().error).toMatchObject({ code: "VALID_001", details: { reasonCode } });
if (details) expect(response.json().error.details).toEqual({ ...details, reasonCode });
else expect(response.json().error.details).toMatchObject({ formErrors: expect.any(Array), fieldErrors: expect.any(Object) });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it.each(["create", "reset"])("preserves password policy failure for %s", async (operation) => {
const t = await buildApp();
try {
const response = await t.app.inject({ method: "POST", url: operation === "create" ? "/api/users" : `/api/users/${USER_ID}/reset-password`, payload: operation === "create" ? { name: "合成", email: "[email protected]", password: "short" } : { newPassword: "short" } });
expect(response.statusCode).toBe(400);
expect(response.json().error.details).toMatchObject({ reasonCode: "user.password_policy_failed", [operation === "create" ? "password" : "newPassword"]: expect.arrayContaining(["密码长度必须 ≥ 12", "密码必须包含大写字母", "密码必须包含数字"]) });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it.each([
["department", null, { departmentId: DEPARTMENT_ID }, 400, "user.department_not_found", { departmentId: "not_found" }],
["department", { id: DEPARTMENT_ID, archived_at: new Date("2024-01-01T00:00:00Z") }, { departmentId: DEPARTMENT_ID }, 409, "user.department_archived", { departmentId: "archived" }],
["employee", null, { directManagerId: MANAGER_ID }, 400, "user.manager_not_found", { directManagerId: "not_found" }],
["employee", { id: MANAGER_ID, status: "archived" }, { directManagerId: MANAGER_ID }, 409, "user.manager_inactive", { directManagerId: "inactive" }],
["employee", null, { directManagerId: USER_ID }, 409, "user.manager_self_forbidden", { directManagerId: "self_not_allowed" }],
])("explains unavailable %s reference", async (model, row, payload, status, reasonCode, details) => {
const t = await buildApp();
try {
(model === "department" ? t.departmentFindUnique : t.employeeFindUnique).mockResolvedValue(row);
const response = await t.app.inject({ method: "PATCH", url: `/api/users/${USER_ID}`, payload });
expect(response.statusCode).toBe(status); expect(response.json().error.details).toEqual({ ...details, reasonCode });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it.each(["archive", "disable", "batch/disable", "roles"])("keeps the self-protection guard for %s", async (operation) => {
const t = await buildApp({ actor: { id: ACTOR_ID, department_id: DEPARTMENT_ID, roleCodes: ["admin"], permissionCodes: ["*"] } });
try {
const response = await t.app.inject({ method: "POST", url: operation === "batch/disable" ? "/api/users/batch/disable" : `/api/users/${ACTOR_ID}/${operation}`, ...(operation === "batch/disable" ? { payload: { employeeIds: Array(51).fill(ACTOR_ID) } } : operation === "roles" ? { payload: { roles: ["employee"] } } : {}) });
expect(response.statusCode).toBe(409);
expect(response.json().error.details).toEqual(operation === "roles" ? { user: "self_role_change_not_allowed", reasonCode: "user.self_role_change_forbidden" } : { user: "self_disable_not_allowed", reasonCode: "user.self_disable_forbidden" });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it("limits distinct batch employees before transactions", async () => {
const t = await buildApp();
try {
const employeeIds = Array.from({ length: 51 }, (_, i) => `00000000-0000-4000-8000-${String(i + 1).padStart(12, "0")}`);
const response = await t.app.inject({ method: "POST", url: "/api/users/batch/enable", payload: { employeeIds } });
expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ employeeIds: "too_many", reasonCode: "user.batch_limit_exceeded" });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it("preserves feature refusal before batch validation", async () => {
const t = await buildApp();
try {
t.app.prisma.featureFlag.findUnique.mockResolvedValue({ flag_key: "employee_lifecycle_v1", override_mode: "force_off", rollout_type: "global", department_ids: [] });
const response = await t.app.inject({ method: "POST", url: "/api/users/batch/set-manager", payload: {} });
expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ featureFlag: "employee_lifecycle_v1_disabled", reason: "flag_force_off", reasonCode: "user.lifecycle_disabled" });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { await t.app.close(); }
});
it.each(["POST", "PATCH"])("keeps unique-conflict details for %s", async (method) => {
const t = await buildApp();
try {
t.app.prisma.$transaction.mockRejectedValue({ code: "P2002", meta: { target: ["email"] } });
const response = await t.app.inject({ method, url: method === "POST" ? "/api/users" : `/api/users/${USER_ID}`, payload: method === "POST" ? { name: "合成", email: "[email protected]" } : { email: "[email protected]" } });
expect(response.statusCode).toBe(409); expect(response.json().error.details).toEqual({ email: "duplicate", reasonCode: "user.unique_conflict" }); expectNoWrites(t);
} finally { await t.app.close(); }
});
it("fails closed when a synthetic random-source fault produces an unsafe temporary password", async () => {
const t = await buildApp(); const random = vi.spyOn(require("node:crypto"), "randomBytes").mockReturnValueOnce(Buffer.alloc(0));
try {
const response = await t.app.inject({ method: "POST", url: "/api/users", payload: { name: "合成", email: "[email protected]" } });
expect(response.statusCode).toBe(400); expect(response.json().error.details).toMatchObject({ reasonCode: "user.generated_password_unavailable", password: expect.arrayContaining(["密码长度必须 ≥ 12"]) });
expect(t.app.prisma.$transaction).not.toHaveBeenCalled(); expectNoWrites(t);
} finally { random.mockRestore(); await t.app.close(); }
});
});
describe("system-user creation transaction cost boundary", () => {
it("finishes real cost12 hashing before beginning the atomic account-role-audit transaction", async () => {
const t = await buildApp();
const bcrypt = require("bcryptjs");
const realHash = bcrypt.hash;
const events = [];
const hash = vi.spyOn(bcrypt, "hash").mockImplementation(async (...args) => {
expect(args[1]).toBe(12); events.push("hash:start");
const result = await realHash(...args); events.push("hash:done"); return result;
});
const transaction = t.app.prisma.$transaction.getMockImplementation();
t.app.prisma.$transaction.mockImplementation(async cb => {
events.push("begin"); const result = await transaction(cb); events.push("commit"); return result;
});
for (const [name, mock] of [["employee", t.employeeCreate], ["roles", t.employeeRoleCreateMany], ["audit", t.auditCreate]]) {
const original = mock.getMockImplementation();
mock.mockImplementation(async (...args) => { events.push(name); return original(...args); });
}
try {
const r = await t.app.inject({ method: "POST", url: "/api/users", payload: { name: "合成账号", email: "[email protected]", roles: ["employee"], syncWecomDirectory: false } });
expect(r.statusCode).toBe(200); expect(hash).toHaveBeenCalledOnce();
expect(events).toEqual(["hash:start", "hash:done", "begin", "employee", "roles", "audit", "commit"]);
const stored = t.employeeCreate.mock.calls[0][0].data;
expect(stored.must_change_password).toBe(true);
expect(await bcrypt.compare(r.json().data.oneTimePassword, stored.password_hash)).toBe(true);
expect(t.auditCreate.mock.calls[0][0].data).toMatchObject({ action: "SYSTEM_USER_CREATED", actor_id: ACTOR_ID, target_id: USER_ID });
expect(t.wecomSyncRunCreate).not.toHaveBeenCalled();
} finally { hash.mockRestore(); await t.app.close(); }
});
it("does not enter a transaction or create an account if password hashing fails", async () => {
const t = await buildApp();
const hash = vi.spyOn(require("bcryptjs"), "hash").mockRejectedValue(new Error("synthetic hash failure"));
try {
const r = await t.app.inject({ method: "POST", url: "/api/users", payload: { name: "合成账号", email: "[email protected]", syncWecomDirectory: false } });
expect(r.statusCode).toBe(500); expect(hash).toHaveBeenCalledOnce();
expect(t.app.prisma.$transaction).not.toHaveBeenCalled();
for (const mock of [t.employeeCreate, t.employeeRoleCreateMany, t.auditCreate, t.wecomSyncRunCreate]) expect(mock).not.toHaveBeenCalled();
} finally { hash.mockRestore(); await t.app.close(); }
});
it.each(["roles", "audit", "commit"])("does not read completed roles or sync externally after a %s failure", async phase => {
const t = await buildApp();
const failure = new Error("synthetic transaction failure");
if (phase === "roles") t.employeeRoleCreateMany.mockRejectedValue(failure);
if (phase === "audit") t.auditCreate.mockRejectedValue(failure);
if (phase === "commit") {
const original = t.app.prisma.$transaction.getMockImplementation();
t.app.prisma.$transaction.mockImplementation(async cb => { await original(cb); throw failure; });
}
try {
const r = await t.app.inject({ method: "POST", url: "/api/users", payload: { name: "合成账号", email: "[email protected]", roles: ["employee"], syncWecomDirectory: false } });
expect(r.statusCode).toBe(500);
expect(t.app.prisma.$transaction).toHaveBeenCalledOnce();
expect(t.employeeCreate).toHaveBeenCalledOnce();
expect(t.employeeRoleFindMany).not.toHaveBeenCalled();
expect(t.wecomSyncRunCreate).not.toHaveBeenCalled();
if (phase === "roles") expect(t.auditCreate).not.toHaveBeenCalled();
} finally { await t.app.close(); }
});
});