文件
hyb-oa/server/tests/unit/routes/employees.attachments.test.js
T
wangsli 1f8d5b658a 完善借款、编号、付款与预算并发及验收(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

675 行
26 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";
const MINIMAL_PDF = Buffer.from(
"%PDF-1.7\n1 0 obj\n<<>>\nendobj\n%%EOF\n",
"ascii",
);
function buildMultipartRequest({ filename, contentType, content, field = "file" }) {
const boundary = "----codex-employee-attachment-boundary";
const head = Buffer.from(
`--${boundary}\r\nContent-Disposition: form-data; name="${field}"; 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: ["employee.contract.manage"] },
employee = {},
contract = {},
} = {}) {
const app = Fastify();
const logWarn = vi.spyOn(app.log, "warn").mockImplementation(() => {});
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({});
const featureFlagFindUnique = vi.fn().mockResolvedValue(buildFeatureFlagRecord());
const 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),
};
const contractLock = vi.fn(async () => (
state.contract ? [{ id: state.contract.id }] : []
));
const transactionContext = {
employeeContract,
auditLog: { create: auditCreate },
$queryRaw: contractLock,
};
const transaction = vi.fn(async (callback) => callback(transactionContext));
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: featureFlagFindUnique,
},
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,
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,
},
$transaction: transaction,
});
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,
contractLock,
contractDelete,
contractUpdate,
employeeUpdate,
featureFlagFindUnique,
logWarn,
state,
tempDir,
transaction,
transactionContext,
};
}
describe("employee attachment and delete routes", () => {
it("uploads, replaces and downloads contract attachments with dedicated permission and audit", async () => {
const { app, auditCreate, 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: MINIMAL_PDF,
}),
});
expect(uploadResponse.statusCode).toBe(200);
expect(uploadResponse.json().data).toMatchObject({
hasAttachment: true,
attachmentUrl: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(uploadResponse.json().data).not.toHaveProperty("attachmentPath");
expect(state.contract.attachment_path).toMatch(new RegExp(`^contracts/${CONTRACT_ID}-[0-9a-f-]+\\.pdf$`));
expect(await fs.readFile(path.join(tempDir, state.contract.attachment_path))).toEqual(MINIMAL_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/octet-stream");
expect(downloadResponse.headers["x-content-type-options"]).toBe("nosniff");
expect(downloadResponse.headers["content-disposition"]).toContain('filename="LAB-001.pdf"');
expect(downloadResponse.body).toBe(MINIMAL_PDF.toString("utf8"));
expect(auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "EMPLOYEE_CONTRACT_ATTACHMENT_DOWNLOADED",
target_id: CONTRACT_ID,
extra: { employeeId: EMPLOYEE_ID },
}),
});
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
});
it("blocks invalid historical contract bytes before sending attachment headers or file content", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const attachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
const invalidStoredContent = Buffer.from("synthetic-invalid-contract-content", "utf8");
await fs.mkdir(path.dirname(attachmentPath), { recursive: true });
await fs.writeFile(attachmentPath, invalidStoredContent);
const response = await testApp.app.inject({
method: "GET",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(response.statusCode).toBe(409);
expect(response.headers["content-disposition"]).toBeUndefined();
expect(response.rawPayload.equals(invalidStoredContent)).toBe(false);
expect(response.json().error.message).toBe("合同附件未通过安全校验");
expect(response.json().error.details).toEqual({
attachment: "security_validation_failed",
reasonCode: "employee.contract_attachment_download_blocked",
});
expect(testApp.auditCreate).toHaveBeenCalledWith({
data: expect.objectContaining({
action: "EMPLOYEE_CONTRACT_ATTACHMENT_DOWNLOAD_BLOCKED",
target_id: CONTRACT_ID,
}),
});
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("returns no contract bytes or attachment headers when success auditing fails", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const attachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
await fs.mkdir(path.dirname(attachmentPath), { recursive: true });
await fs.writeFile(attachmentPath, MINIMAL_PDF);
testApp.auditCreate.mockRejectedValueOnce(new Error("synthetic audit failure"));
const response = await testApp.app.inject({
method: "GET",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
});
expect(response.statusCode).toBe(500);
expect(response.headers["content-disposition"]).toBeUndefined();
expect(response.rawPayload.equals(MINIMAL_PDF)).toBe(false);
expect(response.json().error.details).toEqual({ attachment: "audit_failed" });
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("rejects contract attachment upload for non-admin users", async () => {
const { app, featureFlagFindUnique, contractUpdate, 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);
expect(featureFlagFindUnique).not.toHaveBeenCalled();
expect(contractUpdate).not.toHaveBeenCalled();
await app.close();
await fs.rm(tempDir, { recursive: true, force: true });
});
it("rejects contract attachment content mismatch before storage, database or audit writes", async () => {
const testApp = await buildApp();
const pngSignatureOnly = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: pngSignatureOnly,
}),
});
expect(response.statusCode).toBe(400);
expect(response.json().error).toEqual(
expect.objectContaining({
code: "VALID_001",
details: { file: "type_mismatch", reasonCode: "employee.contract_attachment_content_invalid" },
}),
);
expect(testApp.contractUpdate).not.toHaveBeenCalled();
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
expect(await fs.readdir(testApp.tempDir)).toEqual([]);
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("keeps a committed replacement successful when old-file cleanup fails and logs only safe metadata", async () => {
const testApp = await buildApp({
contract: {
attachment_path: `contracts/${CONTRACT_ID}.pdf`,
},
});
const oldAttachmentPath = path.join(testApp.tempDir, "contracts", `${CONTRACT_ID}.pdf`);
await fs.mkdir(oldAttachmentPath, { recursive: true });
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: MINIMAL_PDF,
}),
});
expect(response.statusCode).toBe(200);
expect(testApp.state.contract.attachment_path).not.toBe(`contracts/${CONTRACT_ID}.pdf`);
expect(testApp.logWarn).toHaveBeenCalledWith(
{
contractId: CONTRACT_ID,
errorCode: expect.stringMatching(/^[A-Z0-9_]+$/u),
},
"Committed contract attachment cleanup failed",
);
const [metadata] = testApp.logWarn.mock.calls.at(-1);
expect(metadata).not.toHaveProperty("storagePath");
expect(metadata).not.toHaveProperty("fileName");
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
it("cleans the attachment path observed under the replacement row lock", async () => {
const initialAttachmentPath = `contracts/${CONTRACT_ID}-initial.pdf`;
const concurrentAttachmentPath = `contracts/${CONTRACT_ID}-concurrent.pdf`;
const testApp = await buildApp({
contract: {
attachment_path: initialAttachmentPath,
},
});
const initialAbsolutePath = path.join(testApp.tempDir, initialAttachmentPath);
const concurrentAbsolutePath = path.join(testApp.tempDir, concurrentAttachmentPath);
await fs.mkdir(path.dirname(initialAbsolutePath), { recursive: true });
await fs.writeFile(initialAbsolutePath, MINIMAL_PDF);
await fs.writeFile(concurrentAbsolutePath, MINIMAL_PDF);
testApp.transaction.mockImplementationOnce(async (callback) => {
testApp.state.contract = {
...testApp.state.contract,
attachment_path: concurrentAttachmentPath,
};
return callback(testApp.transactionContext);
});
const response = await testApp.app.inject({
method: "PUT",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`,
...buildMultipartRequest({
filename: "labor.pdf",
contentType: "application/pdf",
content: MINIMAL_PDF,
}),
});
expect(response.statusCode).toBe(200);
expect(testApp.contractLock).toHaveBeenCalledTimes(1);
await expect(fs.access(concurrentAbsolutePath)).rejects.toMatchObject({ code: "ENOENT" });
await expect(fs.access(initialAbsolutePath)).resolves.toBeUndefined();
await expect(fs.access(path.join(testApp.tempDir, testApp.state.contract.attachment_path)))
.resolves.toBeUndefined();
await testApp.app.close();
await fs.rm(testApp.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}`,
payload: { reason: "测试删除" },
});
expect(activeResponse.statusCode).toBe(409);
expect(activeResponse.json().error.code).toBe("VALID_001");
expect(activeResponse.json().error.details).toEqual({ contract: "active_contract_must_be_terminated", reasonCode: "employee.active_contract_delete_forbidden" });
expect(activeApp.contractDelete).not.toHaveBeenCalled();
expect(activeApp.auditCreate).not.toHaveBeenCalled();
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}`,
payload: { reason: "合同记录重复" },
});
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,
extra: {
employeeId: EMPLOYEE_ID,
status: "expired",
hadAttachment: true,
reason: "合同记录重复",
},
}),
}),
);
await expiredApp.app.close();
await fs.rm(expiredApp.tempDir, { recursive: true, force: true });
});
it("rejects contract deletion without a usable reason before feature or contract access", async () => {
const testApp = await buildApp({
contract: { end_date: new Date("2025-12-31T00:00:00.000Z") },
});
const response = await testApp.app.inject({
method: "DELETE",
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
payload: { reason: "x" },
});
expect(response.statusCode).toBe(400);
expect(response.json().error.details.reasonCode).toBe("employee.contract_delete_input_invalid");
expect(testApp.featureFlagFindUnique).not.toHaveBeenCalled();
expect(testApp.transaction).not.toHaveBeenCalled();
expect(testApp.contractDelete).not.toHaveBeenCalled();
expect(testApp.auditCreate).not.toHaveBeenCalled();
await testApp.app.close();
await fs.rm(testApp.tempDir, { recursive: true, force: true });
});
});
describe("employee upload error reasons", () => {
const actor = { id: EMPLOYEE_ID, department_id: DEPARTMENT_ID, permissionCodes: ["system.users", "employee.contract.manage"] };
function uploadUrl(kind) { return kind === "avatar" ? `/api/employees/${EMPLOYEE_ID}/avatar` : `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}/attachment`; }
it.each(["avatar", "contract_attachment"].flatMap((kind) => ["multipart_required", "file_required", "field_invalid", "type_invalid", "file_empty", "file_too_large"].map((reason) => [kind, reason])))("rejects %s %s before storage or mutation", async (kind, suffix) => {
const t = await buildApp({ actor });
try {
const boundary = "synthetic-empty-file";
let request;
if (suffix === "multipart_required") request = { payload: { file: "synthetic" } };
else if (suffix === "file_required") request = { headers: { "content-type": `multipart/form-data; boundary=${boundary}` }, payload: `--${boundary}\r\nContent-Disposition: form-data; name="note"\r\n\r\nsynthetic\r\n--${boundary}--\r\n` };
else request = buildMultipartRequest({ filename: kind === "avatar" ? "synthetic.png" : "synthetic.pdf", contentType: suffix === "type_invalid" ? "text/plain" : kind === "avatar" ? "image/png" : "application/pdf", field: suffix === "field_invalid" ? "wrong" : "file", content: suffix === "file_empty" ? Buffer.alloc(0) : suffix === "file_too_large" ? Buffer.alloc((kind === "avatar" ? 2 : 10) * 1024 * 1024 + 1, 65) : Buffer.from("synthetic") });
const response = await t.app.inject({ method: "PUT", url: uploadUrl(kind), ...request });
expect(response.statusCode).toBe(400);
expect(response.json().error.details).toEqual({ file: { multipart_required: "invalid_multipart", file_required: "required", field_invalid: "invalid_field", type_invalid: "invalid_type", file_empty: "empty", file_too_large: "file_too_large" }[suffix], reasonCode: `employee.${kind}_${suffix}` });
expect(t.employeeUpdate).not.toHaveBeenCalled(); expect(t.contractUpdate).not.toHaveBeenCalled(); expect(t.auditCreate).not.toHaveBeenCalled(); expect(t.transaction).not.toHaveBeenCalled(); expect(await fs.readdir(t.tempDir)).toEqual([]);
} finally { await t.app.close(); await fs.rm(t.tempDir, { recursive: true, force: true }); }
});
it("rejects invalid avatar image bytes before persistence", async () => {
const t = await buildApp({ actor });
try {
const response = await t.app.inject({ method: "PUT", url: uploadUrl("avatar"), ...buildMultipartRequest({ filename: "synthetic.png", contentType: "image/png", content: "synthetic-invalid-image" }) });
expect(response.statusCode).toBe(400); expect(response.json().error.details).toEqual({ file: "invalid_image", reasonCode: "employee.avatar_image_invalid" });
expect(t.employeeUpdate).not.toHaveBeenCalled(); expect(await fs.readdir(t.tempDir)).toEqual([]);
} finally { await t.app.close(); await fs.rm(t.tempDir, { recursive: true, force: true }); }
});
it.each(["avatar", "contract_attachment"])("handles request.file size errors for %s and preserves other failures", async (kind) => {
for (const code of ["FST_REQ_FILE_TOO_LARGE", "SYNTHETIC_READ_FAILURE"]) {
const t = await buildApp({ actor });
try {
t.app.addHook("preHandler", async (request) => { request.isMultipart = () => true; request.file = async () => { throw Object.assign(new Error("synthetic_file_read"), { code }); }; });
const response = await t.app.inject({ method: "PUT", url: uploadUrl(kind), payload: {} });
expect(response.statusCode).toBe(code === "FST_REQ_FILE_TOO_LARGE" ? 400 : 500);
if (code === "FST_REQ_FILE_TOO_LARGE") expect(response.json().error.details).toEqual({ file: "file_too_large", reasonCode: `employee.${kind}_file_too_large` });
else expect(response.json().error.details?.reasonCode).toBeUndefined();
expect(t.employeeUpdate).not.toHaveBeenCalled(); expect(t.contractUpdate).not.toHaveBeenCalled(); expect(t.auditCreate).not.toHaveBeenCalled(); expect(await fs.readdir(t.tempDir)).toEqual([]);
} finally { await t.app.close(); await fs.rm(t.tempDir, { recursive: true, force: true }); }
}
});
});