完成五人团队正式内用最小收口(07-18-small-team-internal-readiness)
这个提交包含在:
@@ -11,6 +11,10 @@ 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 }) {
|
||||
const boundary = "----codex-employee-attachment-boundary";
|
||||
@@ -91,11 +95,12 @@ function buildContractRow(overrides = {}) {
|
||||
}
|
||||
|
||||
async function buildApp({
|
||||
actor = { id: "actor-1", department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] },
|
||||
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),
|
||||
@@ -127,6 +132,32 @@ async function buildApp({
|
||||
});
|
||||
|
||||
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",
|
||||
@@ -149,7 +180,7 @@ async function buildApp({
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||
findUnique: featureFlagFindUnique,
|
||||
},
|
||||
employee: {
|
||||
findUnique: vi.fn(async ({ where }) => (where.id === EMPLOYEE_ID ? state.employee : null)),
|
||||
@@ -157,22 +188,7 @@ async function buildApp({
|
||||
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),
|
||||
},
|
||||
employeeContract,
|
||||
employeeTraining: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
findFirst: vi.fn().mockResolvedValue(null),
|
||||
@@ -204,6 +220,7 @@ async function buildApp({
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
$transaction: transaction,
|
||||
});
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
@@ -232,12 +249,25 @@ async function buildApp({
|
||||
});
|
||||
await app.register(employeesRoutes, { prefix: "/api" });
|
||||
|
||||
return { app, auditCreate, contractDelete, contractUpdate, employeeUpdate, state, tempDir };
|
||||
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 for system.users", async () => {
|
||||
const { app, state, tempDir } = await buildApp({
|
||||
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`,
|
||||
},
|
||||
@@ -253,17 +283,18 @@ describe("employee attachment and delete routes", () => {
|
||||
...buildMultipartRequest({
|
||||
filename: "labor.pdf",
|
||||
contentType: "application/pdf",
|
||||
content: "new-pdf",
|
||||
content: MINIMAL_PDF,
|
||||
}),
|
||||
});
|
||||
|
||||
expect(uploadResponse.statusCode).toBe(200);
|
||||
expect(uploadResponse.json().data).toMatchObject({
|
||||
attachmentPath: `contracts/${CONTRACT_ID}.pdf`,
|
||||
hasAttachment: true,
|
||||
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");
|
||||
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({
|
||||
@@ -272,16 +303,82 @@ describe("employee attachment and delete routes", () => {
|
||||
});
|
||||
|
||||
expect(downloadResponse.statusCode).toBe(200);
|
||||
expect(downloadResponse.headers["content-type"]).toContain("application/pdf");
|
||||
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("new-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.details).toEqual({
|
||||
attachment: "security_validation_failed",
|
||||
});
|
||||
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, tempDir } = await buildApp({
|
||||
const { app, featureFlagFindUnique, contractUpdate, tempDir } = await buildApp({
|
||||
actor: { id: "actor-2", department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||
});
|
||||
|
||||
@@ -296,11 +393,122 @@ describe("employee attachment and delete routes", () => {
|
||||
});
|
||||
|
||||
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" },
|
||||
}),
|
||||
);
|
||||
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"] },
|
||||
@@ -349,6 +557,7 @@ describe("employee attachment and delete routes", () => {
|
||||
const activeResponse = await activeApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
|
||||
payload: { reason: "测试删除" },
|
||||
});
|
||||
|
||||
expect(activeResponse.statusCode).toBe(409);
|
||||
@@ -368,6 +577,7 @@ describe("employee attachment and delete routes", () => {
|
||||
const expiredResponse = await expiredApp.app.inject({
|
||||
method: "DELETE",
|
||||
url: `/api/employees/${EMPLOYEE_ID}/contracts/${CONTRACT_ID}`,
|
||||
payload: { reason: "合同记录重复" },
|
||||
});
|
||||
|
||||
expect(expiredResponse.statusCode).toBe(200);
|
||||
@@ -381,6 +591,12 @@ describe("employee attachment and delete routes", () => {
|
||||
data: expect.objectContaining({
|
||||
action: "EMPLOYEE_CONTRACT_DELETED",
|
||||
target_id: CONTRACT_ID,
|
||||
extra: {
|
||||
employeeId: EMPLOYEE_ID,
|
||||
status: "expired",
|
||||
hadAttachment: true,
|
||||
reason: "合同记录重复",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
@@ -388,4 +604,25 @@ describe("employee attachment and delete routes", () => {
|
||||
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(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 });
|
||||
});
|
||||
});
|
||||
|
||||
在新工单中引用
屏蔽一个用户