R83 员工号自动生成与单用户开通后端闭环
这个提交包含在:
@@ -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();
|
||||||
@@ -545,7 +545,7 @@ model Department {
|
|||||||
|
|
||||||
model Employee {
|
model Employee {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
employee_no String @unique
|
employee_no String @unique @default(dbgenerated("generate_employee_number()"))
|
||||||
name String
|
name String
|
||||||
phone String @unique
|
phone String @unique
|
||||||
email String @unique
|
email String @unique
|
||||||
|
|||||||
+32
-20
@@ -43,7 +43,7 @@ const listPaginationSchema = z.object({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const createBodySchema = 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),
|
name: z.string().min(1).max(100),
|
||||||
phone: z.string().min(6).max(30),
|
phone: z.string().min(6).max(30),
|
||||||
email: z.string().email().max(200),
|
email: z.string().email().max(200),
|
||||||
@@ -52,11 +52,10 @@ const createBodySchema = z.object({
|
|||||||
directManagerId: z.string().uuid().nullable().optional(),
|
directManagerId: z.string().uuid().nullable().optional(),
|
||||||
hireDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
hireDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||||
roles: z.array(roleCodeSchema).min(1).optional(),
|
roles: z.array(roleCodeSchema).min(1).optional(),
|
||||||
password: z.string().min(1),
|
password: z.string().trim().min(1).optional(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const updateBodySchema = z.object({
|
const updateBodySchema = z.object({
|
||||||
employeeNo: z.string().trim().min(1).max(50).optional(),
|
|
||||||
name: z.string().trim().min(1).max(100).optional(),
|
name: z.string().trim().min(1).max(100).optional(),
|
||||||
phone: z.string().trim().min(6).max(30).optional(),
|
phone: z.string().trim().min(6).max(30).optional(),
|
||||||
email: z.string().trim().email().max(200).optional(),
|
email: z.string().trim().email().max(200).optional(),
|
||||||
@@ -147,14 +146,16 @@ function parseCreateBody(body) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const errors = validatePassword(parsed.data.password);
|
if (typeof parsed.data.password === "string" && parsed.data.password.length > 0) {
|
||||||
if (errors.length) {
|
const errors = validatePassword(parsed.data.password);
|
||||||
throw new AppError({
|
if (errors.length) {
|
||||||
code: "VALID_001",
|
throw new AppError({
|
||||||
message: "参数校验失败",
|
code: "VALID_001",
|
||||||
statusCode: 400,
|
message: "参数校验失败",
|
||||||
details: { password: errors },
|
statusCode: 400,
|
||||||
});
|
details: { password: errors },
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -164,6 +165,14 @@ function parseCreateBody(body) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function parseUpdateBody(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 ?? {});
|
const parsed = updateBodySchema.safeParse(body ?? {});
|
||||||
if (!parsed.success) {
|
if (!parsed.success) {
|
||||||
throw new AppError({
|
throw new AppError({
|
||||||
@@ -872,7 +881,9 @@ async function createSystemUser(tx, options) {
|
|||||||
|
|
||||||
const employee = await tx.employee.create({
|
const employee = await tx.employee.create({
|
||||||
data: {
|
data: {
|
||||||
employee_no: options.employeeNo,
|
...(typeof options.employeeNo === "string" && options.employeeNo.trim()
|
||||||
|
? { employee_no: options.employeeNo.trim() }
|
||||||
|
: {}),
|
||||||
name: options.name,
|
name: options.name,
|
||||||
phone: options.phone,
|
phone: options.phone,
|
||||||
email: options.email,
|
email: options.email,
|
||||||
@@ -1050,6 +1061,7 @@ async function usersRoutes(fastify, opts = {}) {
|
|||||||
const body = parseCreateBody(request.body);
|
const body = parseCreateBody(request.body);
|
||||||
const hireDate = body.hireDate ? new Date(`${body.hireDate}T00:00:00.000Z`) : new Date();
|
const hireDate = body.hireDate ? new Date(`${body.hireDate}T00:00:00.000Z`) : new Date();
|
||||||
const departmentId = body.departmentId ?? request.employee.department_id;
|
const departmentId = body.departmentId ?? request.employee.department_id;
|
||||||
|
const oneTimePassword = body.password ?? generateOneTimePassword();
|
||||||
|
|
||||||
await ensureDepartmentUsable(fastify.prisma, departmentId);
|
await ensureDepartmentUsable(fastify.prisma, departmentId);
|
||||||
|
|
||||||
@@ -1072,7 +1084,7 @@ async function usersRoutes(fastify, opts = {}) {
|
|||||||
title: body.title ?? "员工",
|
title: body.title ?? "员工",
|
||||||
directManagerId: body.directManagerId ?? null,
|
directManagerId: body.directManagerId ?? null,
|
||||||
hireDate,
|
hireDate,
|
||||||
password: body.password,
|
password: oneTimePassword,
|
||||||
roles: body.roles,
|
roles: body.roles,
|
||||||
actorId: request.employee.id,
|
actorId: request.employee.id,
|
||||||
now,
|
now,
|
||||||
@@ -1093,7 +1105,10 @@ async function usersRoutes(fastify, opts = {}) {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
return employee;
|
return {
|
||||||
|
employee,
|
||||||
|
oneTimePassword,
|
||||||
|
};
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error?.code === "P2002") {
|
if (error?.code === "P2002") {
|
||||||
@@ -1108,12 +1123,13 @@ async function usersRoutes(fastify, opts = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const roles = await fastify.prisma.employeeRole.findMany({
|
const roles = await fastify.prisma.employeeRole.findMany({
|
||||||
where: { employee_id: created.id },
|
where: { employee_id: created.employee.id },
|
||||||
select: { role_code: true },
|
select: { role_code: true },
|
||||||
});
|
});
|
||||||
|
|
||||||
return sendData(reply, request, {
|
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 = {};
|
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) {
|
if (typeof body.name === "string" && body.name !== current.name) {
|
||||||
changes.name = { before: current.name, after: body.name };
|
changes.name = { before: current.name, after: body.name };
|
||||||
}
|
}
|
||||||
@@ -1546,7 +1559,6 @@ async function usersRoutes(fastify, opts = {}) {
|
|||||||
const employee = await tx.employee.update({
|
const employee = await tx.employee.update({
|
||||||
where: { id: userId },
|
where: { id: userId },
|
||||||
data: {
|
data: {
|
||||||
...(typeof body.employeeNo === "string" ? { employee_no: body.employeeNo } : {}),
|
|
||||||
...(typeof body.name === "string" ? { name: body.name } : {}),
|
...(typeof body.name === "string" ? { name: body.name } : {}),
|
||||||
...(typeof body.phone === "string" ? { phone: body.phone } : {}),
|
...(typeof body.phone === "string" ? { phone: body.phone } : {}),
|
||||||
...(typeof body.email === "string" ? { email: body.email } : {}),
|
...(typeof body.email === "string" ? { email: body.email } : {}),
|
||||||
|
|||||||
@@ -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: "[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();
|
||||||
|
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: "[email protected]",
|
||||||
|
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: "[email protected]",
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
});
|
||||||
在新工单中引用
屏蔽一个用户