392 行
12 KiB
JavaScript
392 行
12 KiB
JavaScript
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 });
|
|
});
|
|
});
|