From 8f082438829173c7b29219f6d64e0012562237d3 Mon Sep 17 00:00:00 2001 From: shunli Date: Tue, 5 May 2026 00:05:49 +0800 Subject: [PATCH] =?UTF-8?q?R83=20=E5=91=98=E5=B7=A5=E5=8F=B7=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E7=94=9F=E6=88=90=E4=B8=8E=E5=8D=95=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E5=BC=80=E9=80=9A=E5=90=8E=E7=AB=AF=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../migration.sql | 54 +++++ server/prisma/schema.prisma | 2 +- server/src/routes/users.js | 52 +++-- server/tests/unit/routes/users.write.test.js | 213 ++++++++++++++++++ 4 files changed, 300 insertions(+), 21 deletions(-) create mode 100644 server/prisma/migrations/20260504234500_r83_employee_no_default/migration.sql create mode 100644 server/tests/unit/routes/users.write.test.js diff --git a/server/prisma/migrations/20260504234500_r83_employee_no_default/migration.sql b/server/prisma/migrations/20260504234500_r83_employee_no_default/migration.sql new file mode 100644 index 00000000..552976ed --- /dev/null +++ b/server/prisma/migrations/20260504234500_r83_employee_no_default/migration.sql @@ -0,0 +1,54 @@ +CREATE SEQUENCE "employee_number_seq" + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +DO $$ +DECLARE + v_next_value INTEGER; +BEGIN + SELECT COALESCE(MAX(SUBSTRING(employee_no FROM 4)::INTEGER), 0) + 1 + INTO v_next_value + FROM employees + WHERE employee_no ~ '^HYD[0-9]{6}$'; + + EXECUTE format('ALTER SEQUENCE "employee_number_seq" RESTART WITH %s', v_next_value); +END; +$$; + +CREATE OR REPLACE FUNCTION generate_employee_number() +RETURNS TEXT +LANGUAGE plpgsql +AS $$ +DECLARE + v_seq INTEGER; +BEGIN + v_seq := nextval('"employee_number_seq"'); + IF v_seq > 999999 THEN + RAISE EXCEPTION '员工编号序列已达上限 999999'; + END IF; + RETURN 'HYD' || LPAD(v_seq::TEXT, 6, '0'); +END; +$$; + +ALTER TABLE "employees" + ALTER COLUMN "employee_no" SET DEFAULT generate_employee_number(); + +CREATE OR REPLACE FUNCTION prevent_employee_no_update() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF OLD.employee_no IS DISTINCT FROM NEW.employee_no THEN + RAISE EXCEPTION '禁止修改员工编号:employee_no 是不可变字段'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER prevent_employee_no_update_trigger +BEFORE UPDATE ON "employees" +FOR EACH ROW +EXECUTE FUNCTION prevent_employee_no_update(); diff --git a/server/prisma/schema.prisma b/server/prisma/schema.prisma index a1dee538..236d087c 100644 --- a/server/prisma/schema.prisma +++ b/server/prisma/schema.prisma @@ -545,7 +545,7 @@ model Department { model Employee { id String @id @default(uuid()) @db.Uuid - employee_no String @unique + employee_no String @unique @default(dbgenerated("generate_employee_number()")) name String phone String @unique email String @unique diff --git a/server/src/routes/users.js b/server/src/routes/users.js index 9be5d522..3e521ffe 100644 --- a/server/src/routes/users.js +++ b/server/src/routes/users.js @@ -43,7 +43,7 @@ const listPaginationSchema = z.object({ }); const createBodySchema = z.object({ - employeeNo: z.string().min(1).max(50), + employeeNo: z.string().trim().min(1).max(50).optional(), name: z.string().min(1).max(100), phone: z.string().min(6).max(30), email: z.string().email().max(200), @@ -52,11 +52,10 @@ const createBodySchema = z.object({ directManagerId: z.string().uuid().nullable().optional(), hireDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(), roles: z.array(roleCodeSchema).min(1).optional(), - password: z.string().min(1), + password: z.string().trim().min(1).optional(), }); const updateBodySchema = z.object({ - employeeNo: z.string().trim().min(1).max(50).optional(), name: z.string().trim().min(1).max(100).optional(), phone: z.string().trim().min(6).max(30).optional(), email: z.string().trim().email().max(200).optional(), @@ -147,14 +146,16 @@ function parseCreateBody(body) { }); } - const errors = validatePassword(parsed.data.password); - if (errors.length) { - throw new AppError({ - code: "VALID_001", - message: "参数校验失败", - statusCode: 400, - details: { password: errors }, - }); + if (typeof parsed.data.password === "string" && parsed.data.password.length > 0) { + const errors = validatePassword(parsed.data.password); + if (errors.length) { + throw new AppError({ + code: "VALID_001", + message: "参数校验失败", + statusCode: 400, + details: { password: errors }, + }); + } } return { @@ -164,6 +165,14 @@ function parseCreateBody(body) { } function parseUpdateBody(body) { + if (body && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "employeeNo")) { + throw new AppError({ + code: "VALID_001", + message: "参数校验失败", + statusCode: 409, + details: { employeeNo: "immutable" }, + }); + } const parsed = updateBodySchema.safeParse(body ?? {}); if (!parsed.success) { throw new AppError({ @@ -872,7 +881,9 @@ async function createSystemUser(tx, options) { const employee = await tx.employee.create({ data: { - employee_no: options.employeeNo, + ...(typeof options.employeeNo === "string" && options.employeeNo.trim() + ? { employee_no: options.employeeNo.trim() } + : {}), name: options.name, phone: options.phone, email: options.email, @@ -1050,6 +1061,7 @@ async function usersRoutes(fastify, opts = {}) { const body = parseCreateBody(request.body); const hireDate = body.hireDate ? new Date(`${body.hireDate}T00:00:00.000Z`) : new Date(); const departmentId = body.departmentId ?? request.employee.department_id; + const oneTimePassword = body.password ?? generateOneTimePassword(); await ensureDepartmentUsable(fastify.prisma, departmentId); @@ -1072,7 +1084,7 @@ async function usersRoutes(fastify, opts = {}) { title: body.title ?? "员工", directManagerId: body.directManagerId ?? null, hireDate, - password: body.password, + password: oneTimePassword, roles: body.roles, actorId: request.employee.id, now, @@ -1093,7 +1105,10 @@ async function usersRoutes(fastify, opts = {}) { }), }); - return employee; + return { + employee, + oneTimePassword, + }; }); } catch (error) { if (error?.code === "P2002") { @@ -1108,12 +1123,13 @@ async function usersRoutes(fastify, opts = {}) { } const roles = await fastify.prisma.employeeRole.findMany({ - where: { employee_id: created.id }, + where: { employee_id: created.employee.id }, select: { role_code: true }, }); return sendData(reply, request, { - ...mapEmployeeSummary({ ...created, roles }), + ...mapEmployeeSummary({ ...created.employee, roles }), + oneTimePassword: created.oneTimePassword, }); }, ); @@ -1515,9 +1531,6 @@ async function usersRoutes(fastify, opts = {}) { } const changes = {}; - if (typeof body.employeeNo === "string" && body.employeeNo !== current.employee_no) { - changes.employeeNo = { before: current.employee_no, after: body.employeeNo }; - } if (typeof body.name === "string" && body.name !== current.name) { changes.name = { before: current.name, after: body.name }; } @@ -1546,7 +1559,6 @@ async function usersRoutes(fastify, opts = {}) { const employee = await tx.employee.update({ where: { id: userId }, data: { - ...(typeof body.employeeNo === "string" ? { employee_no: body.employeeNo } : {}), ...(typeof body.name === "string" ? { name: body.name } : {}), ...(typeof body.phone === "string" ? { phone: body.phone } : {}), ...(typeof body.email === "string" ? { email: body.email } : {}), diff --git a/server/tests/unit/routes/users.write.test.js b/server/tests/unit/routes/users.write.test.js new file mode 100644 index 00000000..94c7d090 --- /dev/null +++ b/server/tests/unit/routes/users.write.test.js @@ -0,0 +1,213 @@ +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"; + +async function buildApp({ + createdEmployeeNo = "HYD000001", + currentEmployee = null, +} = {}) { + 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: "alice@example.com", + 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(); + const employeeRoleCreateMany = vi.fn().mockResolvedValue({ count: 1 }); + const employeeRoleFindMany = vi.fn().mockResolvedValue([{ role_code: "employee" }]); + const auditCreate = vi.fn().mockResolvedValue({ id: "audit-1" }); + + const tx = { + department: { + findUnique: departmentFindUnique, + }, + employee: { + create: employeeCreate, + findUnique: employeeFindUnique, + update: employeeUpdate, + }, + employeeRole: { + createMany: employeeRoleCreateMany, + }, + auditLog: { + create: auditCreate, + }, + authSession: { + updateMany: vi.fn().mockResolvedValue({ count: 0 }), + }, + }; + + app.decorate("config", {}); + app.decorate("prisma", { + department: { + findUnique: departmentFindUnique, + }, + employee: { + findUnique: employeeFindUnique, + }, + employeeRole: { + findMany: employeeRoleFindMany, + }, + $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"], + }; + 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"], + }; + }); + app.decorate("hasPermission", () => true); + 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, + }; +} + +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: "zhangsan@example.com", + roles: ["employee"], + }, + }); + + expect(response.statusCode).toBe(200); + expect(employeeCreate).toHaveBeenCalledWith( + expect.objectContaining({ + data: expect.not.objectContaining({ + employee_no: expect.anything(), + }), + }), + ); + 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: "zhangsan@example.com", + roleCodes: ["employee"], + }), + ); + expect(payload.oneTimePassword).toMatch(/^ResetA1[a-f0-9]{12}$/); + + 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" }, + }), + ); + expect(employeeFindUnique).not.toHaveBeenCalled(); + expect(employeeUpdate).not.toHaveBeenCalled(); + + await app.close(); + }); +});