R36-1/R36-2/R36-3/R36-5 收口请假编辑与团队日历

这个提交包含在:
2026-03-25 15:32:23 +08:00
父节点 18af4aedc4
当前提交 d0b9d9eaca
共修改 9 个文件,包含 874 行新增和 69 行删除
+159 -3
查看文件
@@ -44,6 +44,7 @@ const leaveListQuerySchema = z.object({
pageSize: z.coerce.number().int().min(1).max(100).optional(),
dateFrom: DATE_ONLY_SCHEMA.optional(),
dateTo: DATE_ONLY_SCHEMA.optional(),
departmentId: z.string().uuid().optional(),
});
const leaveBalanceQuerySchema = z.object({
@@ -120,6 +121,9 @@ function parseLeaveListQuery(query) {
if (dateFrom && dateTo && dateFrom > dateTo) {
throw buildValidationError({ dateTo: "must_be_after_dateFrom" });
}
if (parsed.data.departmentId && parsed.data.scope !== "all") {
throw buildValidationError({ departmentId: "scope_all_only" });
}
return {
status: parsed.data.status,
@@ -128,6 +132,7 @@ function parseLeaveListQuery(query) {
pageSize: parsed.data.pageSize ?? 20,
dateFrom,
dateTo,
departmentId: parsed.data.departmentId ?? null,
};
}
@@ -347,12 +352,18 @@ async function loadLeaveTypeOrThrow(prisma, leaveTypeId) {
return leaveType;
}
async function assertLeaveTypeAttachment(fastify, leaveType, filePart, employeeId) {
async function resolveLeaveTypeAttachment(
fastify,
leaveType,
filePart,
employeeId,
{ requireWhenMissing = true } = {},
) {
const requiresAttachment = Boolean(leaveType.requires_attachment);
const allowedMimeTypes = normalizeAttachmentMimeTypes(leaveType.attachment_mime_types);
if (!filePart) {
if (requiresAttachment) {
if (requireWhenMissing && requiresAttachment) {
throw buildValidationError({ file: "required" }, 422);
}
return null;
@@ -417,6 +428,7 @@ async function leaveRoutes(fastify) {
async (request, reply) => {
const query = parseLeaveListQuery(request.query);
const canViewAll = fastify.hasPermission(request.employee, "leave.view_all");
const canManageAll = fastify.hasPermission(request.employee, "leave.manage");
if (query.scope === "all" && !canViewAll) {
throw new AppError({
code: "PERM_001",
@@ -424,6 +436,18 @@ async function leaveRoutes(fastify) {
statusCode: 403,
});
}
if (
query.departmentId &&
!canManageAll &&
query.departmentId !== (request.employee.department_id ?? null)
) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
details: { departmentId: "forbidden" },
});
}
const page = query.page;
const pageSize = query.pageSize;
@@ -431,6 +455,7 @@ async function leaveRoutes(fastify) {
const where = {
...(query.status ? { status: query.status } : {}),
...(query.scope === "all" && canViewAll ? {} : { owner_id: request.employee.id }),
...(query.scope === "all" && query.departmentId ? { department_id: query.departmentId } : {}),
...(query.dateFrom || query.dateTo
? {
AND: [
@@ -510,7 +535,7 @@ async function leaveRoutes(fastify) {
});
const { body, filePart } = await collectCreatePayload(request);
const leaveType = await loadLeaveTypeOrThrow(fastify.prisma, body.leaveTypeId);
const attachment = await assertLeaveTypeAttachment(
const attachment = await resolveLeaveTypeAttachment(
fastify,
leaveType,
filePart,
@@ -576,6 +601,137 @@ async function leaveRoutes(fastify) {
},
);
fastify.patch(
"/leave-requests/:id",
{
schema: { tags: ["Leave"], summary: "Update Leave Request" },
preHandler: fastify.requireEntityPermission("leave", "submit"),
},
async (request, reply) => {
const leaveId = parseLeaveId(request.params?.id);
const { body, filePart } = await collectCreatePayload(request);
let response = null;
await fastify.prisma.$transaction(async (tx) => {
const leaveRows = await tx.$queryRaw`
SELECT
id,
owner_id,
department_id,
attachment_storage_path,
attachment_original_name,
attachment_mime_type,
status
FROM "leave_requests"
WHERE id = ${leaveId}::uuid
FOR UPDATE
`;
if (!Array.isArray(leaveRows) || leaveRows.length === 0) {
throw new AppError({
code: "SYS_404",
message: "Not Found",
statusCode: 404,
});
}
const leave = leaveRows[0];
await ensureCutoverAllowed({
prisma: tx,
config: fastify.config,
request,
domain: "leave",
departmentId: leave.department_id ?? request.employee.department_id ?? null,
});
if (leave.owner_id !== request.employee.id) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
});
}
if (!["draft", "rejected"].includes(leave.status)) {
throw buildValidationError({ status: "invalid_edit_status" }, 409);
}
const leaveType = await loadLeaveTypeOrThrow(tx, body.leaveTypeId);
const attachment = await resolveLeaveTypeAttachment(
fastify,
leaveType,
filePart,
request.employee.id,
{ requireWhenMissing: false },
);
const requestedDays = await resolveRequestedDaysForCreate(
fastify,
request.employee,
body,
);
const updatedLeave = await tx.leaveRequest.update({
where: { id: leaveId },
data: {
department_id: request.employee.department_id ?? leave.department_id ?? null,
leave_type_id: body.leaveTypeId,
start_date: body.startDate,
end_date: body.endDate,
start_session: body.startSession,
end_session: body.endSession,
requested_days: requestedDays,
reason: body.reason,
attachment_storage_path: attachment?.storagePath ?? leave.attachment_storage_path ?? null,
attachment_original_name: attachment
? attachment.originalName ?? null
: leave.attachment_original_name ?? null,
attachment_mime_type: attachment
? attachment.mimeType ?? null
: leave.attachment_mime_type ?? null,
updated_by: request.employee.id,
},
select: {
id: true,
owner_id: true,
department_id: true,
leave_type_id: true,
start_date: true,
end_date: true,
start_session: true,
end_session: true,
requested_days: true,
reason: true,
attachment_original_name: true,
attachment_mime_type: true,
status: true,
created_at: true,
updated_at: true,
leave_type: {
select: {
id: true,
code: true,
name: true,
requires_attachment: true,
attachment_mime_types: true,
},
},
owner: {
select: {
id: true,
employee_no: true,
name: true,
},
},
},
});
response = mapLeaveRequestResponse(updatedLeave);
});
return sendData(reply, request, response);
},
);
fastify.get(
"/leave-requests/:id",
{
+314
查看文件
@@ -0,0 +1,314 @@
const Fastify = require("fastify");
const { AppError } = require("../../../src/utils/AppError");
const leaveRoutes = require("../../../src/routes/leave");
function buildLeaveType() {
const now = new Date("2026-03-25T08:00:00.000Z");
return {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
code: "annual",
name: "年假",
description: null,
enabled: true,
requires_attachment: false,
attachment_mime_types: [],
sort_order: 1,
created_at: now,
updated_at: now,
leave_policy: {
id: "policy-1",
annual_quota_days: 10,
enabled: true,
description: null,
},
};
}
function buildLockedLeave({
ownerId = "employee-1",
status = "draft",
} = {}) {
return {
id: "11111111-1111-4111-8111-111111111111",
owner_id: ownerId,
department_id: "department-1",
attachment_storage_path: null,
attachment_original_name: null,
attachment_mime_type: null,
status,
};
}
function buildUpdatedLeave({
id = "11111111-1111-4111-8111-111111111111",
ownerId = "employee-1",
status = "draft",
} = {}) {
const now = new Date("2026-03-25T09:00:00.000Z");
return {
id,
owner_id: ownerId,
department_id: "department-1",
leave_type_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
start_date: new Date("2026-04-01T00:00:00.000Z"),
end_date: new Date("2026-04-02T00:00:00.000Z"),
start_session: "am",
end_session: "pm",
requested_days: 2,
reason: "更新后的请假原因",
attachment_original_name: null,
attachment_mime_type: null,
status,
created_at: now,
updated_at: now,
leave_type: {
id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
code: "annual",
name: "年假",
requires_attachment: false,
attachment_mime_types: [],
},
owner: {
id: ownerId,
employee_no: "E001",
name: "张三",
},
};
}
function buildTx({ lockedLeave, updatedLeave }) {
return {
$queryRaw: vi.fn().mockResolvedValue([lockedLeave]),
leaveType: {
findUnique: vi.fn().mockResolvedValue(buildLeaveType()),
},
leaveRequest: {
update: vi.fn().mockResolvedValue(updatedLeave),
},
};
}
function buildPrisma(tx) {
return {
$transaction: vi.fn().mockImplementation((callback) => callback(tx)),
};
}
async function buildApp({ employee, prisma }) {
const app = Fastify();
app.decorate("prisma", prisma);
app.decorate("config", {
cutoverConsoleEnabled: false,
leaveHolidayCalendarEnabled: false,
});
app.decorate("authenticate", async (request) => {
if (!request.headers.authorization) {
throw new AppError({
code: "AUTH_001",
message: "未登录",
statusCode: 401,
});
}
request.employee = employee;
});
app.decorate("hasPermission", (actor, permissionCode) => {
return (actor?.permissionCodes ?? []).includes("*") || (actor?.permissionCodes ?? []).includes(permissionCode);
});
app.decorate("requireEntityPermission", (_entity, action) => async (request) => {
await app.authenticate(request);
const permissionCode = action === "submit" ? "leave.submit" : "leave.view_own";
if (!app.hasPermission(request.employee, permissionCode)) {
throw new AppError({
code: "PERM_001",
message: "无权限",
statusCode: 403,
details: { permission: permissionCode },
});
}
});
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: "SYS_001", message: "服务器内部错误", details: {} },
});
});
await app.register(leaveRoutes, { prefix: "/api" });
return app;
}
describe("leave edit route", () => {
it("allows owner to edit draft leave on the same record", async () => {
const lockedLeave = buildLockedLeave({ status: "draft" });
const updatedLeave = buildUpdatedLeave({ status: "draft" });
const tx = buildTx({ lockedLeave, updatedLeave });
const prisma = buildPrisma(tx);
const app = await buildApp({
employee: {
id: "employee-1",
department_id: "department-1",
permissionCodes: ["leave.submit"],
},
prisma,
});
const response = await app.inject({
method: "PATCH",
url: `/api/leave-requests/${lockedLeave.id}`,
headers: { authorization: "Bearer test" },
payload: {
leaveTypeId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
startDate: "2026-04-01",
endDate: "2026-04-02",
startSession: "am",
endSession: "pm",
reason: "更新后的请假原因",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().data).toEqual(
expect.objectContaining({
id: lockedLeave.id,
status: "draft",
startDate: "2026-04-01",
endDate: "2026-04-02",
requestedDays: 2,
reason: "更新后的请假原因",
}),
);
expect(tx.leaveRequest.update).toHaveBeenCalledWith(
expect.objectContaining({
where: { id: lockedLeave.id },
data: expect.objectContaining({
leave_type_id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
requested_days: 2,
updated_by: "employee-1",
}),
}),
);
await app.close();
});
it("allows owner to edit rejected leave on the same record", async () => {
const lockedLeave = buildLockedLeave({ status: "rejected" });
const updatedLeave = buildUpdatedLeave({ status: "rejected" });
const tx = buildTx({ lockedLeave, updatedLeave });
const app = await buildApp({
employee: {
id: "employee-1",
department_id: "department-1",
permissionCodes: ["leave.submit"],
},
prisma: buildPrisma(tx),
});
const response = await app.inject({
method: "PATCH",
url: `/api/leave-requests/${lockedLeave.id}`,
headers: { authorization: "Bearer test" },
payload: {
leaveTypeId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
startDate: "2026-04-01",
endDate: "2026-04-02",
startSession: "am",
endSession: "pm",
reason: "更新后的请假原因",
},
});
expect(response.statusCode).toBe(200);
expect(response.json().data.status).toBe("rejected");
await app.close();
});
it("rejects editing when leave is already reviewing", async () => {
const lockedLeave = buildLockedLeave({ status: "reviewing" });
const tx = buildTx({ lockedLeave, updatedLeave: buildUpdatedLeave({ status: "reviewing" }) });
const app = await buildApp({
employee: {
id: "employee-1",
department_id: "department-1",
permissionCodes: ["leave.submit"],
},
prisma: buildPrisma(tx),
});
const response = await app.inject({
method: "PATCH",
url: `/api/leave-requests/${lockedLeave.id}`,
headers: { authorization: "Bearer test" },
payload: {
leaveTypeId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
startDate: "2026-04-01",
endDate: "2026-04-02",
startSession: "am",
endSession: "pm",
reason: "更新后的请假原因",
},
});
expect(response.statusCode).toBe(409);
expect(response.json().error).toEqual(
expect.objectContaining({
code: "VALID_001",
details: expect.objectContaining({
status: "invalid_edit_status",
}),
}),
);
expect(tx.leaveRequest.update).not.toHaveBeenCalled();
await app.close();
});
it("rejects editing by non-owner", async () => {
const lockedLeave = buildLockedLeave({ ownerId: "employee-9", status: "draft" });
const tx = buildTx({ lockedLeave, updatedLeave: buildUpdatedLeave({ ownerId: "employee-9", status: "draft" }) });
const app = await buildApp({
employee: {
id: "employee-1",
department_id: "department-1",
permissionCodes: ["leave.submit"],
},
prisma: buildPrisma(tx),
});
const response = await app.inject({
method: "PATCH",
url: `/api/leave-requests/${lockedLeave.id}`,
headers: { authorization: "Bearer test" },
payload: {
leaveTypeId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
startDate: "2026-04-01",
endDate: "2026-04-02",
startSession: "am",
endSession: "pm",
reason: "更新后的请假原因",
},
});
expect(response.statusCode).toBe(403);
expect(response.json().error.code).toBe("PERM_001");
expect(tx.leaveRequest.update).not.toHaveBeenCalled();
await app.close();
});
});