R45 A2-A7 员工附件与培训证书管理
这个提交包含在:
@@ -0,0 +1,391 @@
|
||||
const fs = require("node:fs/promises");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
|
||||
const Fastify = require("fastify");
|
||||
const multipart = require("@fastify/multipart");
|
||||
|
||||
const employeesRoutes = require("../../../src/routes/employees");
|
||||
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";
|
||||
|
||||
function buildMultipartRequest({ filename, contentType, content }) {
|
||||
const boundary = "----codex-employee-attachment-boundary";
|
||||
const head = Buffer.from(
|
||||
`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${filename}"\r\nContent-Type: ${contentType}\r\n\r\n`,
|
||||
);
|
||||
const tail = Buffer.from(`\r\n--${boundary}--\r\n`);
|
||||
const body = Buffer.concat([head, Buffer.isBuffer(content) ? content : Buffer.from(content, "utf8"), tail]);
|
||||
|
||||
return {
|
||||
payload: body,
|
||||
headers: {
|
||||
"content-type": `multipart/form-data; boundary=${boundary}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildFeatureFlagRecord() {
|
||||
return {
|
||||
id: "flag-1",
|
||||
flag_key: "employee_lifecycle_v1",
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "",
|
||||
version: 1,
|
||||
created_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
created_by: null,
|
||||
updated_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildEmployeeRow(overrides = {}) {
|
||||
return {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "Alice",
|
||||
phone: "13800000000",
|
||||
email: "[email protected]",
|
||||
status: "active",
|
||||
employment_status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
title: "员工",
|
||||
direct_manager_id: null,
|
||||
hire_date: new Date("2026-01-10T00:00:00.000Z"),
|
||||
probation_end_date: null,
|
||||
last_working_date: null,
|
||||
work_location: "上海",
|
||||
emergency_contact_name: null,
|
||||
emergency_contact_phone: null,
|
||||
notes: null,
|
||||
avatar_path: null,
|
||||
archived_at: null,
|
||||
roles: [],
|
||||
department: { id: DEPARTMENT_ID, name: "行政部" },
|
||||
direct_manager: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildContractRow(overrides = {}) {
|
||||
return {
|
||||
id: CONTRACT_ID,
|
||||
employee_id: EMPLOYEE_ID,
|
||||
contract_no: "LAB-001",
|
||||
contract_type: "labor",
|
||||
start_date: new Date("2026-01-01T00:00:00.000Z"),
|
||||
end_date: new Date("2026-12-31T00:00:00.000Z"),
|
||||
terminated_date: null,
|
||||
attachment_path: null,
|
||||
created_at: new Date("2026-01-01T00:00:00.000Z"),
|
||||
created_by: "actor-1",
|
||||
updated_at: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updated_by: "actor-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp({
|
||||
actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] },
|
||||
employee = {},
|
||||
contract = {},
|
||||
} = {}) {
|
||||
const app = Fastify();
|
||||
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "hyb-oa-r45-attachments-"));
|
||||
const state = {
|
||||
employee: buildEmployeeRow(employee),
|
||||
contract: buildContractRow(contract),
|
||||
};
|
||||
|
||||
const employeeUpdate = vi.fn(async ({ data }) => {
|
||||
state.employee = {
|
||||
...state.employee,
|
||||
...(data.avatar_path !== undefined ? { avatar_path: data.avatar_path } : {}),
|
||||
...(data.updated_by !== undefined ? { updated_by: data.updated_by } : {}),
|
||||
};
|
||||
return state.employee;
|
||||
});
|
||||
|
||||
const contractUpdate = vi.fn(async ({ data }) => {
|
||||
state.contract = {
|
||||
...state.contract,
|
||||
...(data.attachment_path !== undefined ? { attachment_path: data.attachment_path } : {}),
|
||||
...(data.updated_by !== undefined ? { updated_by: data.updated_by } : {}),
|
||||
};
|
||||
return state.contract;
|
||||
});
|
||||
|
||||
const contractDelete = vi.fn(async () => {
|
||||
const deleted = state.contract;
|
||||
state.contract = null;
|
||||
return deleted;
|
||||
});
|
||||
|
||||
const auditCreate = vi.fn().mockResolvedValue({});
|
||||
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
employeeLifecycleEnabled: true,
|
||||
storageDir: tempDir,
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("hasPermission", (employeeRecord, permissionCode) => {
|
||||
const permissionCodes = employeeRecord.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||
},
|
||||
employee: {
|
||||
findUnique: vi.fn(async ({ where }) => (where.id === EMPLOYEE_ID ? state.employee : null)),
|
||||
update: employeeUpdate,
|
||||
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),
|
||||
},
|
||||
employeeTraining: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
employeeCertificate: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
groupBy: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeChecklistTask: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeLifecycleEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
assetCard: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
workflowTask: {
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
});
|
||||
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: error.code ?? "SYS_001",
|
||||
message: error.message ?? "服务器内部错误",
|
||||
details: error.details ?? null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(multipart, {
|
||||
attachFieldsToBody: false,
|
||||
limits: { files: 1, fileSize: 10 * 1024 * 1024 },
|
||||
});
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
|
||||
return { app, auditCreate, contractDelete, contractUpdate, employeeUpdate, state, tempDir };
|
||||
}
|
||||
|
||||
describe("employee attachment and delete routes", () => {
|
||||
it("uploads, replaces and downloads contract attachments for system.users", async () => {
|
||||
const { app, state, tempDir } = await buildApp({
|
||||
contract: {
|
||||
attachment_path: `contracts/${CONTRACT_ID}.png`,
|
||||
},
|
||||
});
|
||||
|
||||
const oldAttachmentPath = path.join(tempDir, "contracts", `${CONTRACT_ID}.png`);
|
||||
await fs.mkdir(path.dirname(oldAttachmentPath), { recursive: true });
|
||||
await fs.writeFile(oldAttachmentPath, Buffer.from("old-image"));
|
||||
|
||||
const uploadResponse = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
|
||||
...buildMultipartRequest({
|
||||
filename: "labor.pdf",
|
||||
contentType: "application/pdf",
|
||||
content: "new-pdf",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(uploadResponse.statusCode).toBe(200);
|
||||
expect(uploadResponse.json().data).toMatchObject({
|
||||
attachmentPath: `contracts/${CONTRACT_ID}.pdf`,
|
||||
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");
|
||||
await expect(fs.access(oldAttachmentPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
const downloadResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
|
||||
});
|
||||
|
||||
expect(downloadResponse.statusCode).toBe(200);
|
||||
expect(downloadResponse.headers["content-type"]).toContain("application/pdf");
|
||||
expect(downloadResponse.headers["content-disposition"]).toContain('filename="LAB-001.pdf"');
|
||||
expect(downloadResponse.body).toBe("new-pdf");
|
||||
|
||||
await app.close();
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("rejects contract attachment upload for non-admin users", async () => {
|
||||
const { app, tempDir } = await buildApp({
|
||||
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
|
||||
...buildMultipartRequest({
|
||||
filename: "labor.pdf",
|
||||
contentType: "application/pdf",
|
||||
content: "new-pdf",
|
||||
}),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
await fs.rm(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"] },
|
||||
employee: { avatar_path: `avatars/${EMPLOYEE_ID}.webp` },
|
||||
});
|
||||
|
||||
const avatarPath = path.join(tempDir, "avatars", `${EMPLOYEE_ID}.webp`);
|
||||
await fs.mkdir(path.dirname(avatarPath), { recursive: true });
|
||||
await fs.writeFile(avatarPath, Buffer.from("avatar"));
|
||||
|
||||
const response = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/avatar`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data).toEqual({
|
||||
employeeId: EMPLOYEE_ID,
|
||||
avatarUrl: null,
|
||||
});
|
||||
expect(state.employee.avatar_path).toBeNull();
|
||||
await expect(fs.access(avatarPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
await app.close();
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("rejects deleting another employee avatar without system.users", async () => {
|
||||
const { app, tempDir } = await buildApp({
|
||||
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/avatar`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
await fs.rm(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("rejects deleting active contracts and allows deleting expired contracts without local file", async () => {
|
||||
const activeApp = await buildApp();
|
||||
const activeResponse = await activeApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
|
||||
});
|
||||
|
||||
expect(activeResponse.statusCode).toBe(409);
|
||||
expect(activeResponse.json().error.code).toBe("VALID_001");
|
||||
expect(activeApp.state.contract).not.toBeNull();
|
||||
|
||||
await activeApp.app.close();
|
||||
await fs.rm(activeApp.tempDir, { recursive: true, force: true });
|
||||
|
||||
const expiredApp = await buildApp({
|
||||
contract: {
|
||||
end_date: new Date("2025-12-31T00:00:00.000Z"),
|
||||
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
|
||||
},
|
||||
});
|
||||
|
||||
const expiredResponse = await expiredApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
|
||||
});
|
||||
|
||||
expect(expiredResponse.statusCode).toBe(200);
|
||||
expect(expiredResponse.json().data).toEqual({
|
||||
contractId: CONTRACT_ID,
|
||||
deleted: true,
|
||||
});
|
||||
expect(expiredApp.state.contract).toBeNull();
|
||||
expect(expiredApp.auditCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "EMPLOYEE_CONTRACT_DELETED",
|
||||
target_id: CONTRACT_ID,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await expiredApp.app.close();
|
||||
await fs.rm(expiredApp.tempDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,232 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const employeesRoutes = require("../../../src/routes/employees");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
|
||||
function buildFeatureFlagRecord() {
|
||||
return {
|
||||
id: "flag-1",
|
||||
flag_key: "employee_lifecycle_v1",
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "",
|
||||
version: 1,
|
||||
created_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
created_by: null,
|
||||
updated_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildCertificateRow(overrides = {}) {
|
||||
return {
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
employee_id: EMPLOYEE_ID,
|
||||
name: "PMP",
|
||||
issuer: "PMI",
|
||||
obtained_date: new Date("2025-01-01T00:00:00.000Z"),
|
||||
expiry_date: null,
|
||||
certificate_no: "CERT-001",
|
||||
attachment_path: "certificates/pmp.pdf",
|
||||
created_at: new Date("2025-01-01T00:00:00.000Z"),
|
||||
created_by: "actor-1",
|
||||
updated_at: new Date("2025-01-01T00:00:00.000Z"),
|
||||
updated_by: "actor-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp({ actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] } } = {}) {
|
||||
const app = Fastify();
|
||||
const state = {
|
||||
certificate: null,
|
||||
};
|
||||
|
||||
const certificateCreate = vi.fn(async ({ data }) => {
|
||||
state.certificate = buildCertificateRow({
|
||||
name: data.name,
|
||||
issuer: data.issuer,
|
||||
obtained_date: data.obtained_date,
|
||||
expiry_date: data.expiry_date,
|
||||
certificate_no: data.certificate_no,
|
||||
attachment_path: data.attachment_path,
|
||||
created_by: data.created_by,
|
||||
updated_by: data.updated_by,
|
||||
});
|
||||
return state.certificate;
|
||||
});
|
||||
|
||||
const certificateUpdate = vi.fn(async ({ data }) => {
|
||||
state.certificate = {
|
||||
...state.certificate,
|
||||
...(data.name !== undefined ? { name: data.name } : {}),
|
||||
...(data.issuer !== undefined ? { issuer: data.issuer } : {}),
|
||||
...(data.obtained_date !== undefined ? { obtained_date: data.obtained_date } : {}),
|
||||
...(data.expiry_date !== undefined ? { expiry_date: data.expiry_date } : {}),
|
||||
...(data.certificate_no !== undefined ? { certificate_no: data.certificate_no } : {}),
|
||||
...(data.attachment_path !== undefined ? { attachment_path: data.attachment_path } : {}),
|
||||
...(data.updated_by !== undefined ? { updated_by: data.updated_by } : {}),
|
||||
};
|
||||
return state.certificate;
|
||||
});
|
||||
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
employeeLifecycleEnabled: true,
|
||||
storageDir: "/tmp",
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("hasPermission", (employeeRecord, permissionCode) => {
|
||||
const permissionCodes = employeeRecord.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||
},
|
||||
employee: {
|
||||
findUnique: vi.fn(async ({ where }) => (where.id === EMPLOYEE_ID ? { id: EMPLOYEE_ID } : null)),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
update: vi.fn(),
|
||||
},
|
||||
employeeContract: {
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
employeeTraining: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
employeeCertificate: {
|
||||
findMany: vi.fn(async () => (state.certificate ? [state.certificate] : [])),
|
||||
findFirst: vi.fn(async ({ where }) => (state.certificate?.id === where.id && state.certificate?.employee_id === where.employee_id ? state.certificate : null)),
|
||||
create: certificateCreate,
|
||||
update: certificateUpdate,
|
||||
groupBy: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeChecklistTask: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeLifecycleEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
assetCard: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
workflowTask: {
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
});
|
||||
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 ?? null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
return { app, certificateCreate, certificateUpdate, state };
|
||||
}
|
||||
|
||||
describe("employee certificate routes", () => {
|
||||
it("allows system.users to create, update and list certificates with derived status", async () => {
|
||||
const { app, certificateCreate, certificateUpdate, state } = await buildApp();
|
||||
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/certificates`,
|
||||
payload: {
|
||||
name: "PMP",
|
||||
issuer: "PMI",
|
||||
obtainedDate: "2025-01-01",
|
||||
expiryDate: null,
|
||||
certificateNo: "CERT-001",
|
||||
attachmentPath: "certificates/pmp.pdf",
|
||||
},
|
||||
});
|
||||
|
||||
expect(createResponse.statusCode).toBe(200);
|
||||
expect(createResponse.json().data).toMatchObject({
|
||||
name: "PMP",
|
||||
issuer: "PMI",
|
||||
status: "valid",
|
||||
attachmentPath: "certificates/pmp.pdf",
|
||||
});
|
||||
expect(certificateCreate).toHaveBeenCalledTimes(1);
|
||||
|
||||
const patchResponse = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/certificates/${state.certificate.id}`,
|
||||
payload: {
|
||||
expiryDate: "2025-02-01",
|
||||
},
|
||||
});
|
||||
|
||||
expect(patchResponse.statusCode).toBe(200);
|
||||
expect(patchResponse.json().data).toMatchObject({
|
||||
expiryDate: "2025-02-01",
|
||||
status: "expired",
|
||||
});
|
||||
expect(certificateUpdate).toHaveBeenCalledTimes(1);
|
||||
|
||||
const listResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/certificates`,
|
||||
});
|
||||
|
||||
expect(listResponse.statusCode).toBe(200);
|
||||
expect(listResponse.json().data.items).toEqual([
|
||||
expect.objectContaining({
|
||||
id: state.certificate.id,
|
||||
status: "expired",
|
||||
}),
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects non-admin users accessing certificates", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/certificates`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -96,6 +96,7 @@ describe("employee profile organization", () => {
|
||||
name: true,
|
||||
title: true,
|
||||
status: true,
|
||||
avatar_path: true,
|
||||
department: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
@@ -183,6 +184,7 @@ describe("employee profile organization", () => {
|
||||
name: "Helen",
|
||||
title: "主管",
|
||||
status: "active",
|
||||
avatarUrl: null,
|
||||
department: {
|
||||
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
|
||||
name: "行政部",
|
||||
|
||||
@@ -21,6 +21,12 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
||||
{ id: "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb", name: "研发部" },
|
||||
]);
|
||||
const contractCount = vi.fn().mockResolvedValue(2);
|
||||
const certificateGroupBy = vi.fn().mockResolvedValue([
|
||||
{ employee_id: "emp-1" },
|
||||
{ employee_id: "emp-2" },
|
||||
{ employee_id: "emp-3" },
|
||||
]);
|
||||
const certificateCount = vi.fn().mockResolvedValue(4);
|
||||
|
||||
app.decorate("prisma", {
|
||||
employee: {
|
||||
@@ -36,6 +42,11 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
||||
count: stats?.employeeContractCount ?? contractCount,
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
employeeCertificate: {
|
||||
groupBy: stats?.employeeCertificateGroupBy ?? certificateGroupBy,
|
||||
count: stats?.employeeCertificateCount ?? certificateCount,
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = {
|
||||
@@ -68,12 +79,12 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
||||
});
|
||||
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
return { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount };
|
||||
return { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount, certificateGroupBy, certificateCount };
|
||||
}
|
||||
|
||||
describe("employees stats route", () => {
|
||||
it("returns aggregated employee stats for read-only viewers", async () => {
|
||||
const { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount } = await buildApp({
|
||||
const { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount, certificateGroupBy, certificateCount } = await buildApp({
|
||||
permissionCodes: ["report.dashboard.view"],
|
||||
});
|
||||
|
||||
@@ -92,10 +103,18 @@ describe("employees stats route", () => {
|
||||
expect(payload.data.recentMovements.hires).toBe(3);
|
||||
expect(payload.data.recentMovements.departures).toBe(1);
|
||||
expect(payload.data.expiringContracts.count).toBe(2);
|
||||
expect(payload.data.certificateSummary).toEqual({
|
||||
dateFrom: payload.data.asOfDate,
|
||||
dateTo: expect.any(String),
|
||||
validHolderCount: 3,
|
||||
expiringSoonCount: 4,
|
||||
});
|
||||
expect(employeeGroupBy).toHaveBeenCalledTimes(2);
|
||||
expect(employeeCount).toHaveBeenCalledTimes(2);
|
||||
expect(departmentFindMany).toHaveBeenCalledTimes(1);
|
||||
expect(contractCount).toHaveBeenCalledTimes(1);
|
||||
expect(certificateGroupBy).toHaveBeenCalledTimes(1);
|
||||
expect(certificateCount).toHaveBeenCalledTimes(1);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const employeesRoutes = require("../../../src/routes/employees");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
|
||||
function buildFeatureFlagRecord() {
|
||||
return {
|
||||
id: "flag-1",
|
||||
flag_key: "employee_lifecycle_v1",
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "",
|
||||
version: 1,
|
||||
created_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
created_by: null,
|
||||
updated_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||
updated_by: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildTrainingRow(overrides = {}) {
|
||||
return {
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
employee_id: EMPLOYEE_ID,
|
||||
name: "入职培训",
|
||||
training_type: "internal",
|
||||
start_date: new Date("2026-03-01T00:00:00.000Z"),
|
||||
end_date: new Date("2026-03-02T00:00:00.000Z"),
|
||||
status: "planned",
|
||||
notes: "首次培训",
|
||||
created_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
created_by: "actor-1",
|
||||
updated_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
updated_by: "actor-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp({ actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] } } = {}) {
|
||||
const app = Fastify();
|
||||
const state = {
|
||||
training: null,
|
||||
};
|
||||
|
||||
const trainingCreate = vi.fn(async ({ data }) => {
|
||||
state.training = buildTrainingRow({
|
||||
name: data.name,
|
||||
training_type: data.training_type,
|
||||
start_date: data.start_date,
|
||||
end_date: data.end_date,
|
||||
status: data.status,
|
||||
notes: data.notes,
|
||||
created_by: data.created_by,
|
||||
updated_by: data.updated_by,
|
||||
});
|
||||
return state.training;
|
||||
});
|
||||
|
||||
const trainingUpdate = vi.fn(async ({ data }) => {
|
||||
state.training = {
|
||||
...state.training,
|
||||
...(data.name !== undefined ? { name: data.name } : {}),
|
||||
...(data.training_type !== undefined ? { training_type: data.training_type } : {}),
|
||||
...(data.start_date !== undefined ? { start_date: data.start_date } : {}),
|
||||
...(data.end_date !== undefined ? { end_date: data.end_date } : {}),
|
||||
...(data.status !== undefined ? { status: data.status } : {}),
|
||||
...(data.notes !== undefined ? { notes: data.notes } : {}),
|
||||
...(data.updated_by !== undefined ? { updated_by: data.updated_by } : {}),
|
||||
};
|
||||
return state.training;
|
||||
});
|
||||
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
employeeLifecycleEnabled: true,
|
||||
storageDir: "/tmp",
|
||||
});
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("hasPermission", (employeeRecord, permissionCode) => {
|
||||
const permissionCodes = employeeRecord.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||
},
|
||||
employee: {
|
||||
findUnique: vi.fn(async ({ where }) => (where.id === EMPLOYEE_ID ? { id: EMPLOYEE_ID } : null)),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
update: vi.fn(),
|
||||
},
|
||||
employeeContract: {
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
update: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
create: vi.fn(),
|
||||
},
|
||||
employeeTraining: {
|
||||
findMany: vi.fn(async () => (state.training ? [state.training] : [])),
|
||||
findFirst: vi.fn(async ({ where }) => (state.training?.id === where.id && state.training?.employee_id === where.employee_id ? state.training : null)),
|
||||
create: trainingCreate,
|
||||
update: trainingUpdate,
|
||||
},
|
||||
employeeCertificate: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
groupBy: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeChecklistTask: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
employeeLifecycleEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
},
|
||||
assetCard: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
workflowTask: {
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn().mockResolvedValue({}),
|
||||
},
|
||||
});
|
||||
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 ?? null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
return { app, state, trainingCreate, trainingUpdate };
|
||||
}
|
||||
|
||||
describe("employee training routes", () => {
|
||||
it("allows system.users to create, update and list employee trainings", async () => {
|
||||
const { app, state, trainingCreate, trainingUpdate } = await buildApp();
|
||||
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/trainings`,
|
||||
payload: {
|
||||
name: "安全培训",
|
||||
trainingType: "external",
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-12",
|
||||
status: "planned",
|
||||
notes: "第一阶段",
|
||||
},
|
||||
});
|
||||
|
||||
expect(createResponse.statusCode).toBe(200);
|
||||
expect(createResponse.json().data).toMatchObject({
|
||||
name: "安全培训",
|
||||
trainingType: "external",
|
||||
status: "planned",
|
||||
notes: "第一阶段",
|
||||
});
|
||||
expect(trainingCreate).toHaveBeenCalledTimes(1);
|
||||
|
||||
const patchResponse = await app.inject({
|
||||
method: "PATCH",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/trainings/${state.training.id}`,
|
||||
payload: {
|
||||
status: "completed",
|
||||
endDate: "2026-03-15",
|
||||
},
|
||||
});
|
||||
|
||||
expect(patchResponse.statusCode).toBe(200);
|
||||
expect(patchResponse.json().data).toMatchObject({
|
||||
status: "completed",
|
||||
endDate: "2026-03-15",
|
||||
});
|
||||
expect(trainingUpdate).toHaveBeenCalledTimes(1);
|
||||
|
||||
const listResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/trainings`,
|
||||
});
|
||||
|
||||
expect(listResponse.statusCode).toBe(200);
|
||||
expect(listResponse.json().data.items).toEqual([
|
||||
expect.objectContaining({
|
||||
id: state.training.id,
|
||||
name: "安全培训",
|
||||
status: "completed",
|
||||
}),
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects non-admin users managing trainings", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/trainings`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户