完善借款、编号、付款与预算并发及验收(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
父节点 729d90576f
当前提交 1f8d5b658a
共修改 367 个文件,包含 21079 行新增和 12287 行删除
+211 -1
查看文件
@@ -314,7 +314,7 @@ describe("usersRoutes write flows", () => {
expect(response.json().error).toEqual(
expect.objectContaining({
code: "VALID_001",
details: { employeeNo: "immutable" },
details: { employeeNo: "immutable", reasonCode: "user.employee_no_immutable" },
}),
);
expect(employeeFindUnique).not.toHaveBeenCalled();
@@ -552,3 +552,213 @@ describe("usersRoutes write flows", () => {
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(); }
});
});