feat(P15B-1,P15B-6): 完成请假V1闭环
这个提交包含在:
+648
-76
@@ -3,17 +3,54 @@ const { z } = require("zod");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { resolveActionableStep } = require("../utils/workflow");
|
||||
const {
|
||||
DEFAULT_ATTACHMENT_MIME_TYPES,
|
||||
calculateRequestedDays,
|
||||
createLeaveLedgerEntry,
|
||||
formatDateOnly,
|
||||
leaveRangesOverlap,
|
||||
loadLeaveBalanceItems,
|
||||
loadLeaveBalanceSnapshot,
|
||||
loadLeaveLedgerSummaryForRequest,
|
||||
lockEmployeeForLeave,
|
||||
normalizeAttachmentMimeTypes,
|
||||
persistLeaveAttachment,
|
||||
releaseReservedLeave,
|
||||
toHalfDayUnits,
|
||||
} = require("../services/leave");
|
||||
|
||||
const DATE_ONLY_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const SESSION_SCHEMA = z.enum(["am", "pm"]);
|
||||
const STATUS_SCHEMA = z.enum(["draft", "reviewing", "approved", "rejected", "cancelled"]);
|
||||
|
||||
const createLeaveSchema = z
|
||||
.object({
|
||||
leaveTypeId: z.string().uuid(),
|
||||
startDate: DATE_ONLY_SCHEMA,
|
||||
endDate: DATE_ONLY_SCHEMA,
|
||||
startSession: SESSION_SCHEMA.optional(),
|
||||
endSession: SESSION_SCHEMA.optional(),
|
||||
reason: z.string().trim().max(500).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const leaveListQuerySchema = z.object({
|
||||
status: STATUS_SCHEMA.optional(),
|
||||
scope: z.enum(["own", "all"]).optional(),
|
||||
page: z.coerce.number().int().min(1).optional(),
|
||||
pageSize: z.coerce.number().int().min(1).max(100).optional(),
|
||||
});
|
||||
|
||||
const leaveBalanceQuerySchema = z.object({
|
||||
employeeId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
const withdrawBodySchema = z
|
||||
.object({
|
||||
comment: z.string().trim().max(500).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const LEAVE_WORKFLOW_STEPS_V1 = [
|
||||
{
|
||||
id: "leave_approval_manager",
|
||||
@@ -23,53 +60,185 @@ const LEAVE_WORKFLOW_STEPS_V1 = [
|
||||
},
|
||||
];
|
||||
|
||||
const LEAVE_TYPE_SELECT = {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
description: true,
|
||||
enabled: true,
|
||||
requires_attachment: true,
|
||||
attachment_mime_types: true,
|
||||
sort_order: true,
|
||||
created_at: true,
|
||||
updated_at: true,
|
||||
leave_policy: {
|
||||
select: {
|
||||
id: true,
|
||||
annual_quota_days: true,
|
||||
enabled: true,
|
||||
description: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function parseLeaveId(value) {
|
||||
const parsed = z.string().uuid().safeParse(value);
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { id: "invalid_uuid" },
|
||||
});
|
||||
throw buildValidationError({ id: "invalid_uuid" });
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseLeaveListQuery(query) {
|
||||
const parsed = leaveListQuerySchema.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return {
|
||||
status: parsed.data.status,
|
||||
scope: parsed.data.scope ?? "own",
|
||||
page: parsed.data.page ?? 1,
|
||||
pageSize: parsed.data.pageSize ?? 20,
|
||||
};
|
||||
}
|
||||
|
||||
function parseLeaveBalanceQuery(query) {
|
||||
const parsed = leaveBalanceQuerySchema.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseWithdrawBody(body) {
|
||||
const parsed = withdrawBodySchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return {
|
||||
comment: parsed.data.comment?.trim() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function parseCreateBody(body) {
|
||||
const parsed = createLeaveSchema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: parsed.error.flatten(),
|
||||
});
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
const start = new Date(`${parsed.data.startDate}T00:00:00.000Z`);
|
||||
const end = new Date(`${parsed.data.endDate}T00:00:00.000Z`);
|
||||
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { date: "invalid" },
|
||||
});
|
||||
const startDate = new Date(`${parsed.data.startDate}T00:00:00.000Z`);
|
||||
const endDate = new Date(`${parsed.data.endDate}T00:00:00.000Z`);
|
||||
|
||||
if (Number.isNaN(startDate.getTime()) || Number.isNaN(endDate.getTime())) {
|
||||
throw buildValidationError({ date: "invalid" });
|
||||
}
|
||||
if (end.getTime() < start.getTime()) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { endDate: "before_start" },
|
||||
});
|
||||
|
||||
const startSession = parsed.data.startSession ?? "am";
|
||||
const endSession = parsed.data.endSession ?? "pm";
|
||||
const requestedDays = calculateRequestedDays({
|
||||
startDate,
|
||||
endDate,
|
||||
startSession,
|
||||
endSession,
|
||||
});
|
||||
|
||||
return {
|
||||
leaveTypeId: parsed.data.leaveTypeId,
|
||||
startDate,
|
||||
endDate,
|
||||
startSession,
|
||||
endSession,
|
||||
requestedDays,
|
||||
reason: parsed.data.reason?.trim() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function collectCreatePayload(request) {
|
||||
if (typeof request.isMultipart === "function" && request.isMultipart()) {
|
||||
const fields = {};
|
||||
let filePart = null;
|
||||
|
||||
try {
|
||||
for await (const part of request.parts()) {
|
||||
if (part.type === "file") {
|
||||
if (filePart) {
|
||||
throw buildValidationError({ file: "only_single_file_supported" });
|
||||
}
|
||||
filePart = part;
|
||||
} else {
|
||||
fields[part.fieldname] = part.value;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.code === "FST_REQ_FILE_TOO_LARGE") {
|
||||
throw buildValidationError({ file: "file_too_large" });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
body: parseCreateBody(fields),
|
||||
filePart,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
startDate: start,
|
||||
endDate: end,
|
||||
reason: parsed.data.reason?.trim() ?? null,
|
||||
body: parseCreateBody(request.body),
|
||||
filePart: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mapLeaveTypeSummary(leaveType) {
|
||||
return {
|
||||
id: leaveType.id,
|
||||
code: leaveType.code,
|
||||
name: leaveType.name,
|
||||
requiresAttachment: Boolean(leaveType.requires_attachment),
|
||||
attachmentMimeTypes: normalizeAttachmentMimeTypes(leaveType.attachment_mime_types),
|
||||
};
|
||||
}
|
||||
|
||||
function mapLeaveRequestResponse(leave) {
|
||||
return {
|
||||
id: leave.id,
|
||||
ownerId: leave.owner_id,
|
||||
departmentId: leave.department_id,
|
||||
status: leave.status,
|
||||
startDate: formatDateOnly(leave.start_date),
|
||||
endDate: formatDateOnly(leave.end_date),
|
||||
startSession: leave.start_session,
|
||||
endSession: leave.end_session,
|
||||
requestedDays: Number(leave.requested_days),
|
||||
reason: leave.reason ?? null,
|
||||
attachment:
|
||||
leave.attachment_original_name || leave.attachment_mime_type
|
||||
? {
|
||||
originalName: leave.attachment_original_name ?? null,
|
||||
mimeType: leave.attachment_mime_type ?? null,
|
||||
}
|
||||
: null,
|
||||
leaveType: leave.leave_type ? mapLeaveTypeSummary(leave.leave_type) : null,
|
||||
owner: leave.owner
|
||||
? {
|
||||
id: leave.owner.id,
|
||||
employeeNo: leave.owner.employee_no,
|
||||
name: leave.owner.name,
|
||||
}
|
||||
: null,
|
||||
createdAt: leave.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: leave.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -91,7 +260,158 @@ async function createSkipHistoryRecords(tx, workflowInstanceId, actorId, ownerId
|
||||
}
|
||||
}
|
||||
|
||||
async function loadLeaveTypeOrThrow(prisma, leaveTypeId) {
|
||||
const leaveType = await prisma.leaveType.findUnique({
|
||||
where: { id: leaveTypeId },
|
||||
select: LEAVE_TYPE_SELECT,
|
||||
});
|
||||
|
||||
if (!leaveType || !leaveType.enabled || !leaveType.leave_policy || !leaveType.leave_policy.enabled) {
|
||||
throw buildValidationError({ leaveTypeId: "missing_active_policy" }, 409);
|
||||
}
|
||||
|
||||
return leaveType;
|
||||
}
|
||||
|
||||
async function assertLeaveTypeAttachment(fastify, leaveType, filePart, employeeId) {
|
||||
const requiresAttachment = Boolean(leaveType.requires_attachment);
|
||||
const allowedMimeTypes = normalizeAttachmentMimeTypes(leaveType.attachment_mime_types);
|
||||
|
||||
if (!filePart) {
|
||||
if (requiresAttachment) {
|
||||
throw buildValidationError({ file: "required" }, 422);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const mimeAllowlist = new Set(allowedMimeTypes.length ? allowedMimeTypes : DEFAULT_ATTACHMENT_MIME_TYPES);
|
||||
if (!mimeAllowlist.has(filePart.mimetype)) {
|
||||
throw buildValidationError({ file: "unsupported_mime_type" });
|
||||
}
|
||||
|
||||
return persistLeaveAttachment({
|
||||
config: fastify.config,
|
||||
employeeId,
|
||||
filePart,
|
||||
});
|
||||
}
|
||||
|
||||
async function leaveRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/leave-balances",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "Get Leave Balances" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "view_own"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const query = parseLeaveBalanceQuery(request.query);
|
||||
const canViewAll =
|
||||
fastify.hasPermission(request.employee, "leave.view_all") ||
|
||||
fastify.hasPermission(request.employee, "leave.manage");
|
||||
const targetEmployeeId = query.employeeId ?? request.employee.id;
|
||||
|
||||
if (targetEmployeeId !== request.employee.id && !canViewAll) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
let items = [];
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
await lockEmployeeForLeave(tx, targetEmployeeId);
|
||||
items = await loadLeaveBalanceItems(tx, {
|
||||
employeeId: targetEmployeeId,
|
||||
actorId: request.employee.id,
|
||||
});
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
employeeId: targetEmployeeId,
|
||||
items,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/leave-requests",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "List Leave Requests" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "view_own"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const query = parseLeaveListQuery(request.query);
|
||||
const canViewAll = fastify.hasPermission(request.employee, "leave.view_all");
|
||||
if (query.scope === "all" && !canViewAll) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const page = query.page;
|
||||
const pageSize = query.pageSize;
|
||||
const skip = (page - 1) * pageSize;
|
||||
const where = {
|
||||
...(query.status ? { status: query.status } : {}),
|
||||
...(query.scope === "all" && canViewAll ? {} : { owner_id: request.employee.id }),
|
||||
};
|
||||
|
||||
const [items, total] = await Promise.all([
|
||||
fastify.prisma.leaveRequest.findMany({
|
||||
where,
|
||||
orderBy: { updated_at: "desc" },
|
||||
skip,
|
||||
take: pageSize,
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
fastify.prisma.leaveRequest.count({ where }),
|
||||
]);
|
||||
|
||||
return sendData(reply, request, {
|
||||
page,
|
||||
pageSize,
|
||||
total,
|
||||
scope: query.scope === "all" && canViewAll ? "all" : "own",
|
||||
items: items.map(mapLeaveRequestResponse),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/leave-requests",
|
||||
{
|
||||
@@ -99,33 +419,69 @@ async function leaveRoutes(fastify) {
|
||||
preHandler: fastify.requireEntityPermission("leave", "create"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const body = parseCreateBody(request.body);
|
||||
const { body, filePart } = await collectCreatePayload(request);
|
||||
const leaveType = await loadLeaveTypeOrThrow(fastify.prisma, body.leaveTypeId);
|
||||
const attachment = await assertLeaveTypeAttachment(
|
||||
fastify,
|
||||
leaveType,
|
||||
filePart,
|
||||
request.employee.id,
|
||||
);
|
||||
|
||||
const leave = await fastify.prisma.leaveRequest.create({
|
||||
data: {
|
||||
owner_id: request.employee.id,
|
||||
department_id: request.employee.department_id,
|
||||
leave_type_id: body.leaveTypeId,
|
||||
start_date: body.startDate,
|
||||
end_date: body.endDate,
|
||||
start_session: body.startSession,
|
||||
end_session: body.endSession,
|
||||
requested_days: body.requestedDays,
|
||||
reason: body.reason,
|
||||
attachment_storage_path: attachment?.storagePath ?? null,
|
||||
attachment_original_name: attachment?.originalName ?? null,
|
||||
attachment_mime_type: attachment?.mimeType ?? null,
|
||||
status: "draft",
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
status: 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
id: leave.id,
|
||||
status: leave.status,
|
||||
startDate: leave.start_date.toISOString().slice(0, 10),
|
||||
endDate: leave.end_date.toISOString().slice(0, 10),
|
||||
});
|
||||
return sendData(reply, request, mapLeaveRequestResponse(leave));
|
||||
},
|
||||
);
|
||||
|
||||
@@ -144,12 +500,34 @@ async function leaveRoutes(fastify) {
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -170,17 +548,7 @@ async function leaveRoutes(fastify) {
|
||||
});
|
||||
}
|
||||
|
||||
return sendData(reply, request, {
|
||||
id: leave.id,
|
||||
ownerId: leave.owner_id,
|
||||
departmentId: leave.department_id,
|
||||
status: leave.status,
|
||||
startDate: leave.start_date.toISOString().slice(0, 10),
|
||||
endDate: leave.end_date.toISOString().slice(0, 10),
|
||||
reason: leave.reason ?? null,
|
||||
createdAt: leave.created_at.toISOString(),
|
||||
updatedAt: leave.updated_at.toISOString(),
|
||||
});
|
||||
return sendData(reply, request, mapLeaveRequestResponse(leave));
|
||||
},
|
||||
);
|
||||
|
||||
@@ -196,7 +564,18 @@ async function leaveRoutes(fastify) {
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const leaveRows = await tx.$queryRaw`
|
||||
SELECT id, owner_id, department_id, status
|
||||
SELECT
|
||||
id,
|
||||
owner_id,
|
||||
department_id,
|
||||
leave_type_id,
|
||||
start_date,
|
||||
end_date,
|
||||
start_session::text AS start_session,
|
||||
end_session::text AS end_session,
|
||||
requested_days::text AS requested_days,
|
||||
attachment_storage_path,
|
||||
status
|
||||
FROM "leave_requests"
|
||||
WHERE id = ${leaveId}::uuid
|
||||
FOR UPDATE
|
||||
@@ -219,12 +598,7 @@ async function leaveRoutes(fastify) {
|
||||
}
|
||||
|
||||
if (!["draft", "rejected"].includes(leave.status)) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { status: "invalid_submit_status" },
|
||||
});
|
||||
throw buildValidationError({ status: "invalid_submit_status" }, 409);
|
||||
}
|
||||
|
||||
const activeInstance = await tx.workflowInstance.findFirst({
|
||||
@@ -236,12 +610,66 @@ async function leaveRoutes(fastify) {
|
||||
select: { id: true },
|
||||
});
|
||||
if (activeInstance) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { submit: "already_in_review" },
|
||||
});
|
||||
throw buildValidationError({ submit: "already_in_review" }, 409);
|
||||
}
|
||||
|
||||
const leaveType = await loadLeaveTypeOrThrow(tx, leave.leave_type_id);
|
||||
if (leaveType.requires_attachment && !leave.attachment_storage_path) {
|
||||
throw buildValidationError({ file: "required" }, 422);
|
||||
}
|
||||
|
||||
const overlappingRequests = await tx.leaveRequest.findMany({
|
||||
where: {
|
||||
owner_id: leave.owner_id,
|
||||
id: { not: leaveId },
|
||||
status: { in: ["reviewing", "approved"] },
|
||||
start_date: { lte: leave.end_date },
|
||||
end_date: { gte: leave.start_date },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
start_date: true,
|
||||
end_date: true,
|
||||
start_session: true,
|
||||
end_session: true,
|
||||
},
|
||||
});
|
||||
|
||||
const conflicting = overlappingRequests.find((item) =>
|
||||
leaveRangesOverlap(
|
||||
{
|
||||
startDate: leave.start_date,
|
||||
endDate: leave.end_date,
|
||||
startSession: leave.start_session,
|
||||
endSession: leave.end_session,
|
||||
},
|
||||
{
|
||||
startDate: item.start_date,
|
||||
endDate: item.end_date,
|
||||
startSession: item.start_session,
|
||||
endSession: item.end_session,
|
||||
},
|
||||
),
|
||||
);
|
||||
if (conflicting) {
|
||||
throw buildValidationError(
|
||||
{ leave: "conflict_range", conflictLeaveRequestId: conflicting.id },
|
||||
422,
|
||||
);
|
||||
}
|
||||
|
||||
await lockEmployeeForLeave(tx, leave.owner_id);
|
||||
const balanceSnapshot = await loadLeaveBalanceSnapshot(tx, {
|
||||
employeeId: leave.owner_id,
|
||||
leaveType,
|
||||
actorId: request.employee.id,
|
||||
referenceDate: leave.start_date,
|
||||
});
|
||||
|
||||
if (
|
||||
toHalfDayUnits(balanceSnapshot.summary.available) < toHalfDayUnits(leave.requested_days)
|
||||
) {
|
||||
throw buildValidationError({ leave: "insufficient_balance" }, 422);
|
||||
}
|
||||
|
||||
const workflowDefinition = await tx.workflowDefinition.findFirst({
|
||||
@@ -250,12 +678,7 @@ async function leaveRoutes(fastify) {
|
||||
select: { id: true },
|
||||
});
|
||||
if (!workflowDefinition) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 400,
|
||||
details: { workflow: "missing_definition" },
|
||||
});
|
||||
throw buildValidationError({ workflow: "missing_definition" });
|
||||
}
|
||||
|
||||
const { actionable, skipped } = await resolveActionableStep({
|
||||
@@ -266,12 +689,7 @@ async function leaveRoutes(fastify) {
|
||||
logger: fastify.log,
|
||||
});
|
||||
if (!actionable) {
|
||||
throw new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode: 409,
|
||||
details: { workflow: "no_actionable_approver" },
|
||||
});
|
||||
throw buildValidationError({ workflow: "no_actionable_approver" }, 409);
|
||||
}
|
||||
|
||||
await tx.leaveRequest.update({
|
||||
@@ -338,6 +756,23 @@ async function leaveRoutes(fastify) {
|
||||
},
|
||||
});
|
||||
|
||||
await createLeaveLedgerEntry(tx, {
|
||||
employeeId: leave.owner_id,
|
||||
leaveTypeId: leave.leave_type_id,
|
||||
leavePolicyId: balanceSnapshot.policy.id,
|
||||
leaveRequestId: leaveId,
|
||||
entryType: "reserve",
|
||||
days: Number(leave.requested_days),
|
||||
periodStart: balanceSnapshot.periodStart,
|
||||
periodEnd: balanceSnapshot.periodEnd,
|
||||
note: "submit_reserve_leave",
|
||||
payload: {
|
||||
source: "leave_submit",
|
||||
workflow_instance_id: workflowInstance.id,
|
||||
},
|
||||
createdBy: request.employee.id,
|
||||
});
|
||||
|
||||
submitResult = {
|
||||
leaveRequestId: leaveId,
|
||||
workflowInstanceId: workflowInstance.id,
|
||||
@@ -349,7 +784,144 @@ async function leaveRoutes(fastify) {
|
||||
return sendData(reply, request, submitResult);
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/leave-requests/:id/withdraw",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "Withdraw Leave Request" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "submit"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const leaveId = parseLeaveId(request.params?.id);
|
||||
const { comment } = parseWithdrawBody(request.body);
|
||||
let response = null;
|
||||
|
||||
await fastify.prisma.$transaction(async (tx) => {
|
||||
const leaveRows = await tx.$queryRaw`
|
||||
SELECT
|
||||
id,
|
||||
owner_id,
|
||||
leave_type_id,
|
||||
requested_days::text AS requested_days,
|
||||
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];
|
||||
if (leave.owner_id !== request.employee.id) {
|
||||
throw new AppError({
|
||||
code: "PERM_001",
|
||||
message: "无权限",
|
||||
statusCode: 403,
|
||||
});
|
||||
}
|
||||
|
||||
if (leave.status !== "reviewing") {
|
||||
throw buildValidationError({ status: "invalid_withdraw_status" }, 409);
|
||||
}
|
||||
|
||||
const activeInstance = await tx.workflowInstance.findFirst({
|
||||
where: {
|
||||
entity_type: "leave",
|
||||
entity_id: leaveId,
|
||||
current_status: "pending",
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!activeInstance) {
|
||||
throw buildValidationError({ withdraw: "no_pending_instance" }, 409);
|
||||
}
|
||||
|
||||
const processedTaskCount = await tx.workflowTask.count({
|
||||
where: {
|
||||
instance_id: activeInstance.id,
|
||||
status: { in: ["completed", "rejected"] },
|
||||
},
|
||||
});
|
||||
if (processedTaskCount > 0) {
|
||||
throw buildValidationError({ withdraw: "already_processed_by_approver" }, 409);
|
||||
}
|
||||
|
||||
const ledger = await loadLeaveLedgerSummaryForRequest(tx, leaveId);
|
||||
const reserveAnchor = ledger.entries.find((item) => item.entry_type === "reserve") ?? null;
|
||||
const now = new Date();
|
||||
|
||||
await tx.workflowTask.updateMany({
|
||||
where: {
|
||||
instance_id: activeInstance.id,
|
||||
status: "pending",
|
||||
},
|
||||
data: {
|
||||
status: "cancelled",
|
||||
completed_at: now,
|
||||
completed_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.workflowInstance.update({
|
||||
where: { id: activeInstance.id },
|
||||
data: {
|
||||
current_status: "cancelled",
|
||||
completed_at: now,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.leaveRequest.update({
|
||||
where: { id: leaveId },
|
||||
data: {
|
||||
status: "draft",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
await releaseReservedLeave(tx, {
|
||||
leaveRequestId: leaveId,
|
||||
employeeId: leave.owner_id,
|
||||
leaveTypeId: leave.leave_type_id,
|
||||
leavePolicyId: reserveAnchor?.leave_policy_id ?? null,
|
||||
periodStart: reserveAnchor?.period_start ?? null,
|
||||
periodEnd: reserveAnchor?.period_end ?? null,
|
||||
note: "withdraw_release_leave",
|
||||
payload: { source: "leave_withdraw" },
|
||||
createdBy: request.employee.id,
|
||||
});
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
data: {
|
||||
instance_id: activeInstance.id,
|
||||
actor_id: request.employee.id,
|
||||
action: "withdraw",
|
||||
comment: comment ?? null,
|
||||
payload: {
|
||||
leave_request_id: leaveId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
response = {
|
||||
leaveRequestId: leaveId,
|
||||
outcome: "withdrawn",
|
||||
workflowInstanceId: activeInstance.id,
|
||||
leaveStatus: "draft",
|
||||
};
|
||||
});
|
||||
|
||||
return sendData(reply, request, response);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = leaveRoutes;
|
||||
|
||||
|
||||
在新工单中引用
屏蔽一个用户