feat(P15B-1,P15B-6): 完成请假V1闭环
这个提交包含在:
@@ -0,0 +1,314 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { mapLeaveTypeResponse } = require("../services/leave");
|
||||
|
||||
const LEAVE_TYPE_ID_SCHEMA = z.string().uuid();
|
||||
const LEAVE_TYPE_QUERY_SCHEMA = z.object({
|
||||
enabled: z
|
||||
.enum(["true", "false"])
|
||||
.transform((value) => value === "true")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
const LEAVE_TYPE_BODY_SCHEMA = z
|
||||
.object({
|
||||
code: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(64)
|
||||
.regex(/^[a-z][a-z0-9_]*$/i),
|
||||
name: z.string().trim().min(1).max(64),
|
||||
description: z.string().trim().max(500).nullable().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
requiresAttachment: z.boolean().optional(),
|
||||
attachmentMimeTypes: z.array(z.string().trim().min(1).max(128)).max(10).optional(),
|
||||
sortOrder: z.number().int().min(0).max(9999).optional(),
|
||||
annualQuotaDays: z
|
||||
.number()
|
||||
.min(0)
|
||||
.max(365)
|
||||
.refine((value) => Math.round(value * 2) === value * 2, "half_day_only"),
|
||||
policyDescription: z.string().trim().max(500).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const LEAVE_TYPE_PATCH_SCHEMA = LEAVE_TYPE_BODY_SCHEMA.partial();
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function parseTypeId(value) {
|
||||
const parsed = LEAVE_TYPE_ID_SCHEMA.safeParse(value);
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError({ id: "invalid_uuid" });
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseTypeQuery(query) {
|
||||
const parsed = LEAVE_TYPE_QUERY_SCHEMA.safeParse(query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function parseTypeBody(schema, body) {
|
||||
const parsed = schema.safeParse(body ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
|
||||
return {
|
||||
code: typeof parsed.data.code === "string" ? parsed.data.code.trim().toLowerCase() : undefined,
|
||||
name: typeof parsed.data.name === "string" ? parsed.data.name.trim() : undefined,
|
||||
description:
|
||||
parsed.data.description === undefined ? undefined : parsed.data.description?.trim() ?? null,
|
||||
enabled: parsed.data.enabled,
|
||||
requiresAttachment: parsed.data.requiresAttachment,
|
||||
attachmentMimeTypes: parsed.data.attachmentMimeTypes,
|
||||
sortOrder: parsed.data.sortOrder,
|
||||
annualQuotaDays: parsed.data.annualQuotaDays,
|
||||
policyDescription:
|
||||
parsed.data.policyDescription === undefined
|
||||
? undefined
|
||||
: parsed.data.policyDescription?.trim() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePrismaLeaveType(record) {
|
||||
return mapLeaveTypeResponse({
|
||||
...record,
|
||||
leave_policy: record.leave_policy,
|
||||
});
|
||||
}
|
||||
|
||||
function isUniqueConstraint(error, targetField) {
|
||||
if (!error || error.code !== "P2002") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const target = error.meta?.target;
|
||||
if (Array.isArray(target)) {
|
||||
return target.includes(targetField);
|
||||
}
|
||||
|
||||
return typeof target === "string" && target.includes(targetField);
|
||||
}
|
||||
|
||||
async function leaveTypesRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/leave-types",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "List Leave Types" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "view_own"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const query = parseTypeQuery(request.query);
|
||||
const canManage = fastify.hasPermission(request.employee, "leave.manage");
|
||||
|
||||
const items = await fastify.prisma.leaveType.findMany({
|
||||
where: {
|
||||
...(canManage
|
||||
? query.enabled == null
|
||||
? {}
|
||||
: { enabled: query.enabled }
|
||||
: { enabled: true }),
|
||||
},
|
||||
orderBy: [{ sort_order: "asc" }, { code: "asc" }],
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
items: items.map(normalizePrismaLeaveType),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
"/leave-types",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "Create Leave Type" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "manage"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const body = parseTypeBody(LEAVE_TYPE_BODY_SCHEMA, request.body);
|
||||
|
||||
try {
|
||||
const leaveType = await fastify.prisma.leaveType.create({
|
||||
data: {
|
||||
code: body.code,
|
||||
name: body.name,
|
||||
description: body.description ?? null,
|
||||
enabled: body.enabled ?? true,
|
||||
requires_attachment: body.requiresAttachment ?? false,
|
||||
attachment_mime_types: body.attachmentMimeTypes ?? null,
|
||||
sort_order: body.sortOrder ?? 100,
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
leave_policy: {
|
||||
create: {
|
||||
annual_quota_days: body.annualQuotaDays,
|
||||
enabled: body.enabled ?? true,
|
||||
description: body.policyDescription ?? null,
|
||||
created_by: request.employee.id,
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
},
|
||||
},
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, normalizePrismaLeaveType(leaveType));
|
||||
} catch (error) {
|
||||
if (isUniqueConstraint(error, "code")) {
|
||||
throw buildValidationError({ code: "duplicate" }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
fastify.patch(
|
||||
"/leave-types/:id",
|
||||
{
|
||||
schema: { tags: ["Leave"], summary: "Patch Leave Type" },
|
||||
preHandler: fastify.requireEntityPermission("leave", "manage"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const leaveTypeId = parseTypeId(request.params?.id);
|
||||
const body = parseTypeBody(LEAVE_TYPE_PATCH_SCHEMA, request.body);
|
||||
|
||||
const existing = await fastify.prisma.leaveType.findUnique({
|
||||
where: { id: leaveTypeId },
|
||||
select: {
|
||||
id: true,
|
||||
leave_policy: {
|
||||
select: {
|
||||
id: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!existing) {
|
||||
throw new AppError({
|
||||
code: "SYS_404",
|
||||
message: "Not Found",
|
||||
statusCode: 404,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const leaveType = await fastify.prisma.leaveType.update({
|
||||
where: { id: leaveTypeId },
|
||||
data: {
|
||||
...(body.code !== undefined ? { code: body.code } : {}),
|
||||
...(body.name !== undefined ? { name: body.name } : {}),
|
||||
...(body.description !== undefined ? { description: body.description } : {}),
|
||||
...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
|
||||
...(body.requiresAttachment !== undefined
|
||||
? { requires_attachment: body.requiresAttachment }
|
||||
: {}),
|
||||
...(body.attachmentMimeTypes !== undefined
|
||||
? { attachment_mime_types: body.attachmentMimeTypes }
|
||||
: {}),
|
||||
...(body.sortOrder !== undefined ? { sort_order: body.sortOrder } : {}),
|
||||
updated_by: request.employee.id,
|
||||
leave_policy:
|
||||
body.annualQuotaDays !== undefined || body.policyDescription !== undefined || body.enabled !== undefined
|
||||
? {
|
||||
update: {
|
||||
...(body.annualQuotaDays !== undefined
|
||||
? { annual_quota_days: body.annualQuotaDays }
|
||||
: {}),
|
||||
...(body.policyDescription !== undefined
|
||||
? { description: body.policyDescription }
|
||||
: {}),
|
||||
...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, normalizePrismaLeaveType(leaveType));
|
||||
} catch (error) {
|
||||
if (isUniqueConstraint(error, "code")) {
|
||||
throw buildValidationError({ code: "duplicate" }, 409);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = leaveTypesRoutes;
|
||||
+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;
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { resolvePermissionsForRoles, hasPermission, ROLE_PERMISSIONS, resolveEntityPermission } = require("../constants/permissions");
|
||||
const { getWorkflowStepsSnapshot, resolveActionableStep, toMoneyString } = require("../utils/workflow");
|
||||
const { consumeReservedLeave, releaseReservedLeave, formatDateOnly } = require("../services/leave");
|
||||
const {
|
||||
createNotifications,
|
||||
resolveRecipientsForAssignee,
|
||||
@@ -538,6 +539,34 @@ async function workflowRoutes(fastify) {
|
||||
},
|
||||
},
|
||||
},
|
||||
leave_request: {
|
||||
select: {
|
||||
id: true,
|
||||
status: 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,
|
||||
leave_type: {
|
||||
select: {
|
||||
id: true,
|
||||
code: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
owner: {
|
||||
select: {
|
||||
id: true,
|
||||
employee_no: true,
|
||||
name: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -616,6 +645,7 @@ async function workflowRoutes(fastify) {
|
||||
workflowInstance: task.workflow_instance
|
||||
? {
|
||||
id: task.workflow_instance.id,
|
||||
entityType: task.workflow_instance.entity_type,
|
||||
currentStatus: task.workflow_instance.current_status,
|
||||
currentStepId: task.workflow_instance.current_step_id,
|
||||
startedAt: isoOrNull(task.workflow_instance.started_at),
|
||||
@@ -649,6 +679,40 @@ async function workflowRoutes(fastify) {
|
||||
: null,
|
||||
}
|
||||
: null,
|
||||
leaveRequest: task.workflow_instance?.leave_request
|
||||
? {
|
||||
id: task.workflow_instance.leave_request.id,
|
||||
status: task.workflow_instance.leave_request.status,
|
||||
startDate: formatDateOnly(task.workflow_instance.leave_request.start_date),
|
||||
endDate: formatDateOnly(task.workflow_instance.leave_request.end_date),
|
||||
startSession: task.workflow_instance.leave_request.start_session,
|
||||
endSession: task.workflow_instance.leave_request.end_session,
|
||||
requestedDays: Number(task.workflow_instance.leave_request.requested_days),
|
||||
reason: task.workflow_instance.leave_request.reason ?? null,
|
||||
attachment:
|
||||
task.workflow_instance.leave_request.attachment_original_name ||
|
||||
task.workflow_instance.leave_request.attachment_mime_type
|
||||
? {
|
||||
originalName: task.workflow_instance.leave_request.attachment_original_name ?? null,
|
||||
mimeType: task.workflow_instance.leave_request.attachment_mime_type ?? null,
|
||||
}
|
||||
: null,
|
||||
leaveType: task.workflow_instance.leave_request.leave_type
|
||||
? {
|
||||
id: task.workflow_instance.leave_request.leave_type.id,
|
||||
code: task.workflow_instance.leave_request.leave_type.code,
|
||||
name: task.workflow_instance.leave_request.leave_type.name,
|
||||
}
|
||||
: null,
|
||||
owner: task.workflow_instance.leave_request.owner
|
||||
? {
|
||||
id: task.workflow_instance.leave_request.owner.id,
|
||||
employeeNo: task.workflow_instance.leave_request.owner.employee_no,
|
||||
name: task.workflow_instance.leave_request.owner.name,
|
||||
}
|
||||
: null,
|
||||
}
|
||||
: null,
|
||||
allowedActions: listAllowedActionsForTask(request, task, actionable),
|
||||
history: historyItems.map((item) => ({
|
||||
id: item.id,
|
||||
@@ -885,6 +949,28 @@ async function workflowRoutes(fastify) {
|
||||
},
|
||||
});
|
||||
} else if (workflowInstance.entity_type === "leave") {
|
||||
const leaveRequest = await tx.leaveRequest.findUnique({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
select: {
|
||||
id: true,
|
||||
owner_id: true,
|
||||
leave_type_id: true,
|
||||
requested_days: true,
|
||||
},
|
||||
});
|
||||
const reserveAnchor = await tx.leaveLedger.findFirst({
|
||||
where: {
|
||||
leave_request_id: workflowInstance.entity_id,
|
||||
entry_type: "reserve",
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: {
|
||||
leave_policy_id: true,
|
||||
period_start: true,
|
||||
period_end: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.leaveRequest.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
@@ -892,6 +978,19 @@ async function workflowRoutes(fastify) {
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (leaveRequest) {
|
||||
await consumeReservedLeave(tx, {
|
||||
leaveRequestId: workflowInstance.entity_id,
|
||||
employeeId: leaveRequest.owner_id,
|
||||
leaveTypeId: leaveRequest.leave_type_id,
|
||||
leavePolicyId: reserveAnchor?.leave_policy_id ?? null,
|
||||
periodStart: reserveAnchor?.period_start ?? null,
|
||||
periodEnd: reserveAnchor?.period_end ?? null,
|
||||
requestedDays: leaveRequest.requested_days,
|
||||
createdBy: request.employee.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
@@ -1016,6 +1115,27 @@ async function workflowRoutes(fastify) {
|
||||
},
|
||||
});
|
||||
} else if (workflowInstance.entity_type === "leave") {
|
||||
const leaveRequest = await tx.leaveRequest.findUnique({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
select: {
|
||||
id: true,
|
||||
owner_id: true,
|
||||
leave_type_id: true,
|
||||
},
|
||||
});
|
||||
const reserveAnchor = await tx.leaveLedger.findFirst({
|
||||
where: {
|
||||
leave_request_id: workflowInstance.entity_id,
|
||||
entry_type: "reserve",
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: {
|
||||
leave_policy_id: true,
|
||||
period_start: true,
|
||||
period_end: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.leaveRequest.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
@@ -1023,6 +1143,20 @@ async function workflowRoutes(fastify) {
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (leaveRequest) {
|
||||
await releaseReservedLeave(tx, {
|
||||
leaveRequestId: workflowInstance.entity_id,
|
||||
employeeId: leaveRequest.owner_id,
|
||||
leaveTypeId: leaveRequest.leave_type_id,
|
||||
leavePolicyId: reserveAnchor?.leave_policy_id ?? null,
|
||||
periodStart: reserveAnchor?.period_start ?? null,
|
||||
periodEnd: reserveAnchor?.period_end ?? null,
|
||||
note: "rejected_release_leave",
|
||||
payload: { source: "workflow_reject" },
|
||||
createdBy: request.employee.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
@@ -1146,6 +1280,27 @@ async function workflowRoutes(fastify) {
|
||||
},
|
||||
});
|
||||
} else if (workflowInstance.entity_type === "leave") {
|
||||
const leaveRequest = await tx.leaveRequest.findUnique({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
select: {
|
||||
id: true,
|
||||
owner_id: true,
|
||||
leave_type_id: true,
|
||||
},
|
||||
});
|
||||
const reserveAnchor = await tx.leaveLedger.findFirst({
|
||||
where: {
|
||||
leave_request_id: workflowInstance.entity_id,
|
||||
entry_type: "reserve",
|
||||
},
|
||||
orderBy: { created_at: "desc" },
|
||||
select: {
|
||||
leave_policy_id: true,
|
||||
period_start: true,
|
||||
period_end: true,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.leaveRequest.update({
|
||||
where: { id: workflowInstance.entity_id },
|
||||
data: {
|
||||
@@ -1153,6 +1308,20 @@ async function workflowRoutes(fastify) {
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
if (leaveRequest) {
|
||||
await releaseReservedLeave(tx, {
|
||||
leaveRequestId: workflowInstance.entity_id,
|
||||
employeeId: leaveRequest.owner_id,
|
||||
leaveTypeId: leaveRequest.leave_type_id,
|
||||
leavePolicyId: reserveAnchor?.leave_policy_id ?? null,
|
||||
periodStart: reserveAnchor?.period_start ?? null,
|
||||
periodEnd: reserveAnchor?.period_end ?? null,
|
||||
note: "returned_release_leave",
|
||||
payload: { source: "workflow_return" },
|
||||
createdBy: request.employee.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await tx.workflowHistory.create({
|
||||
|
||||
在新工单中引用
屏蔽一个用户