feat(P15B-1,P15B-6): 完成请假V1闭环
这个提交包含在:
@@ -136,6 +136,42 @@ export function mapApiErrorMessage(
|
||||
return "当前报销金额超出预算,系统已阻断提交。";
|
||||
}
|
||||
|
||||
if (details?.leave === "conflict_range") {
|
||||
return "当前时间段与已有请假记录冲突,请调整后再提交。";
|
||||
}
|
||||
|
||||
if (details?.leave === "insufficient_balance") {
|
||||
return "当前假种可用额度不足,无法提交。";
|
||||
}
|
||||
|
||||
if (details?.leave === "invalid_range") {
|
||||
return "请假开始/结束日期与半天时段不合法。";
|
||||
}
|
||||
|
||||
if (details?.leave === "missing_reserve_ledger") {
|
||||
return "请假冻结账本状态异常,请联系管理员处理。";
|
||||
}
|
||||
|
||||
if (details?.file === "required") {
|
||||
return "当前假种要求上传附件后才能提交。";
|
||||
}
|
||||
|
||||
if (details?.file === "unsupported_mime_type") {
|
||||
return "附件类型不被当前假种接受,请重新选择。";
|
||||
}
|
||||
|
||||
if (details?.withdraw === "no_pending_instance") {
|
||||
return "当前请假单不存在可撤回的审批实例。";
|
||||
}
|
||||
|
||||
if (details?.withdraw === "already_processed_by_approver") {
|
||||
return "审批人已处理该请假单,当前不能撤回。";
|
||||
}
|
||||
|
||||
if (details?.leaveTypeId === "missing_active_policy") {
|
||||
return "当前假种未配置可用策略,请联系 HR。";
|
||||
}
|
||||
|
||||
if (details?.integration === "erp_sync_disabled") {
|
||||
return "ERP 同步功能未开启。";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { apiRequestData } from "./http";
|
||||
|
||||
export type LeaveSession = "am" | "pm";
|
||||
export type LeaveRequestStatus = "draft" | "reviewing" | "approved" | "rejected" | "cancelled";
|
||||
|
||||
export type LeaveType = {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
enabled: boolean;
|
||||
requiresAttachment: boolean;
|
||||
attachmentMimeTypes: string[];
|
||||
sortOrder: number;
|
||||
policy: {
|
||||
id: string;
|
||||
annualQuotaDays: number;
|
||||
enabled: boolean;
|
||||
description: string | null;
|
||||
} | null;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type LeaveBalanceItem = {
|
||||
leaveType: LeaveType;
|
||||
policy: {
|
||||
id: string;
|
||||
annualQuotaDays: number;
|
||||
enabled: boolean;
|
||||
description: string | null;
|
||||
};
|
||||
granted: number;
|
||||
adjusted: number;
|
||||
reserved: number;
|
||||
used: number;
|
||||
available: number;
|
||||
periodStart: string | null;
|
||||
periodEnd: string | null;
|
||||
};
|
||||
|
||||
export type LeaveRequestItem = {
|
||||
id: string;
|
||||
ownerId: string;
|
||||
departmentId: string;
|
||||
status: LeaveRequestStatus;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
startSession: LeaveSession;
|
||||
endSession: LeaveSession;
|
||||
requestedDays: number;
|
||||
reason: string | null;
|
||||
attachment: {
|
||||
originalName: string | null;
|
||||
mimeType: string | null;
|
||||
} | null;
|
||||
leaveType: {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
requiresAttachment: boolean;
|
||||
attachmentMimeTypes: string[];
|
||||
} | null;
|
||||
owner: {
|
||||
id: string;
|
||||
employeeNo: string;
|
||||
name: string;
|
||||
} | null;
|
||||
createdAt: string | null;
|
||||
updatedAt: string | null;
|
||||
};
|
||||
|
||||
export type LeaveRequestListResponse = {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
total: number;
|
||||
scope: "own" | "all";
|
||||
items: LeaveRequestItem[];
|
||||
};
|
||||
|
||||
export type LeaveBalanceResponse = {
|
||||
employeeId: string;
|
||||
items: LeaveBalanceItem[];
|
||||
};
|
||||
|
||||
export type LeaveListQuery = {
|
||||
status?: LeaveRequestStatus;
|
||||
scope?: "own" | "all";
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
};
|
||||
|
||||
function toQueryString(query: Record<string, string | number | undefined>) {
|
||||
const params = new URLSearchParams();
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
if (value == null || value === "") {
|
||||
continue;
|
||||
}
|
||||
params.set(key, String(value));
|
||||
}
|
||||
const encoded = params.toString();
|
||||
return encoded ? `?${encoded}` : "";
|
||||
}
|
||||
|
||||
export async function fetchLeaveTypes(params?: { enabled?: boolean }) {
|
||||
return apiRequestData<{ items: LeaveType[] }>(
|
||||
`/api/leave-types${toQueryString({ enabled: params?.enabled == null ? undefined : String(params.enabled) })}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createLeaveType(payload: {
|
||||
code: string;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
enabled?: boolean;
|
||||
requiresAttachment?: boolean;
|
||||
attachmentMimeTypes?: string[];
|
||||
sortOrder?: number;
|
||||
annualQuotaDays: number;
|
||||
policyDescription?: string | null;
|
||||
}) {
|
||||
return apiRequestData<LeaveType>("/api/leave-types", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function patchLeaveType(
|
||||
leaveTypeId: string,
|
||||
payload: Partial<{
|
||||
code: string;
|
||||
name: string;
|
||||
description: string | null;
|
||||
enabled: boolean;
|
||||
requiresAttachment: boolean;
|
||||
attachmentMimeTypes: string[];
|
||||
sortOrder: number;
|
||||
annualQuotaDays: number;
|
||||
policyDescription: string | null;
|
||||
}>,
|
||||
) {
|
||||
return apiRequestData<LeaveType>(`/api/leave-types/${leaveTypeId}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchLeaveBalances(employeeId?: string) {
|
||||
return apiRequestData<LeaveBalanceResponse>(
|
||||
`/api/leave-balances${toQueryString({ employeeId })}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchLeaveRequests(query: LeaveListQuery = {}) {
|
||||
return apiRequestData<LeaveRequestListResponse>(
|
||||
`/api/leave-requests${toQueryString(query as Record<string, string | number | undefined>)}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchLeaveRequestDetail(leaveRequestId: string) {
|
||||
return apiRequestData<LeaveRequestItem>(`/api/leave-requests/${leaveRequestId}`);
|
||||
}
|
||||
|
||||
export async function createLeaveRequest(payload: {
|
||||
leaveTypeId: string;
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
startSession: LeaveSession;
|
||||
endSession: LeaveSession;
|
||||
reason?: string;
|
||||
file?: File | null;
|
||||
}) {
|
||||
const formData = new FormData();
|
||||
formData.append("leaveTypeId", payload.leaveTypeId);
|
||||
formData.append("startDate", payload.startDate);
|
||||
formData.append("endDate", payload.endDate);
|
||||
formData.append("startSession", payload.startSession);
|
||||
formData.append("endSession", payload.endSession);
|
||||
if (payload.reason?.trim()) {
|
||||
formData.append("reason", payload.reason.trim());
|
||||
}
|
||||
if (payload.file) {
|
||||
formData.append("file", payload.file);
|
||||
}
|
||||
|
||||
return apiRequestData<LeaveRequestItem>("/api/leave-requests", {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
});
|
||||
}
|
||||
|
||||
export async function submitLeaveRequest(leaveRequestId: string) {
|
||||
return apiRequestData<Record<string, unknown>>(`/api/leave-requests/${leaveRequestId}/submit`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function withdrawLeaveRequest(leaveRequestId: string, comment?: string) {
|
||||
return apiRequestData<Record<string, unknown>>(`/api/leave-requests/${leaveRequestId}/withdraw`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ comment }),
|
||||
});
|
||||
}
|
||||
@@ -53,6 +53,7 @@ export type WorkflowTaskDetail = {
|
||||
};
|
||||
workflowInstance: {
|
||||
id: string;
|
||||
entityType: string;
|
||||
currentStatus: string;
|
||||
currentStepId: string;
|
||||
startedAt: string | null;
|
||||
@@ -76,6 +77,30 @@ export type WorkflowTaskDetail = {
|
||||
name: string;
|
||||
} | null;
|
||||
} | null;
|
||||
leaveRequest: {
|
||||
id: string;
|
||||
status: string;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
startSession: "am" | "pm";
|
||||
endSession: "am" | "pm";
|
||||
requestedDays: number;
|
||||
reason: string | null;
|
||||
attachment: {
|
||||
originalName: string | null;
|
||||
mimeType: string | null;
|
||||
} | null;
|
||||
leaveType: {
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
} | null;
|
||||
owner: {
|
||||
id: string;
|
||||
employeeNo: string;
|
||||
name: string;
|
||||
} | null;
|
||||
} | null;
|
||||
allowedActions: Array<"approve" | "reject" | "return" | "transfer">;
|
||||
history: WorkflowHistoryItem[];
|
||||
};
|
||||
|
||||
+25
-10
@@ -1,4 +1,4 @@
|
||||
const EMPLOYEE_BASE_PERMISSIONS = [
|
||||
const EXPENSE_SELF_SERVICE_PERMISSIONS = [
|
||||
"expense.create",
|
||||
"expense.view_own",
|
||||
"expense.edit_own",
|
||||
@@ -10,6 +10,17 @@ const EMPLOYEE_BASE_PERMISSIONS = [
|
||||
"expense.proxy_manage",
|
||||
] as const;
|
||||
|
||||
const LEAVE_SELF_SERVICE_PERMISSIONS = [
|
||||
"leave.create",
|
||||
"leave.view_own",
|
||||
"leave.submit",
|
||||
] as const;
|
||||
|
||||
const EMPLOYEE_BASE_PERMISSIONS = [
|
||||
...EXPENSE_SELF_SERVICE_PERMISSIONS,
|
||||
...LEAVE_SELF_SERVICE_PERMISSIONS,
|
||||
] as const;
|
||||
|
||||
const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
employee: EMPLOYEE_BASE_PERMISSIONS,
|
||||
manager: [
|
||||
@@ -17,6 +28,7 @@ const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
"expense.approve",
|
||||
"expense.transfer",
|
||||
"expense.view_all",
|
||||
"leave.approve",
|
||||
"report.dashboard.view",
|
||||
"budget.view",
|
||||
"budget.manage",
|
||||
@@ -26,6 +38,8 @@ const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
"expense.approve",
|
||||
"expense.transfer",
|
||||
"expense.view_all",
|
||||
"leave.approve",
|
||||
"leave.view_all",
|
||||
"report.dashboard.view",
|
||||
"budget.view",
|
||||
],
|
||||
@@ -57,16 +71,17 @@ const ROLE_PERMISSIONS: Record<string, readonly string[]> = {
|
||||
],
|
||||
administration: [
|
||||
"expense.proxy_submit",
|
||||
"expense.create",
|
||||
"expense.view_own",
|
||||
"expense.edit_own",
|
||||
"expense.delete_own",
|
||||
"expense.submit",
|
||||
"expense.withdraw",
|
||||
"invoice.upload",
|
||||
"invoice.view_own",
|
||||
...EMPLOYEE_BASE_PERMISSIONS,
|
||||
],
|
||||
hr: [
|
||||
...LEAVE_SELF_SERVICE_PERMISSIONS,
|
||||
"leave.view_all",
|
||||
"leave.manage",
|
||||
"system.users",
|
||||
"system.users_sensitive",
|
||||
"expense.view_all",
|
||||
"report.dashboard.view",
|
||||
],
|
||||
hr: ["system.users", "system.users_sensitive", "expense.view_all", "report.dashboard.view"],
|
||||
admin: ["*"],
|
||||
};
|
||||
|
||||
|
||||
@@ -18,6 +18,12 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
icon: "request_quote",
|
||||
anyOf: ["expense.view_own", "expense.view_all"],
|
||||
},
|
||||
{
|
||||
to: "/leave-requests",
|
||||
label: "请假申请",
|
||||
icon: "event_available",
|
||||
anyOf: ["leave.view_own", "leave.view_all"],
|
||||
},
|
||||
{
|
||||
to: "/workflow/tasks",
|
||||
label: "待我处理",
|
||||
|
||||
@@ -0,0 +1,536 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { toast } from "sonner";
|
||||
import { mapApiErrorMessage } from "../api/errorMessages";
|
||||
import {
|
||||
createLeaveRequest,
|
||||
fetchLeaveBalances,
|
||||
fetchLeaveRequests,
|
||||
fetchLeaveTypes,
|
||||
submitLeaveRequest,
|
||||
withdrawLeaveRequest,
|
||||
type LeaveRequestStatus,
|
||||
type LeaveSession,
|
||||
} from "../api/leave";
|
||||
import { isApiError } from "../api/types";
|
||||
import { useAuth } from "../auth/AuthContext";
|
||||
import { hasPermission } from "../auth/permissions";
|
||||
import { CardSkeleton } from "../components/common/CardSkeleton";
|
||||
import { ConfirmDialog } from "../components/common/ConfirmDialog";
|
||||
import { PageHeader } from "../components/common/PageHeader";
|
||||
import { Pagination } from "../components/common/Pagination";
|
||||
import { StatusBadge } from "../components/common/StatusBadge";
|
||||
import { TableSkeleton } from "../components/common/TableSkeleton";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Label } from "../components/ui/label";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
|
||||
import { Textarea } from "../components/ui/textarea";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
|
||||
function resolveError(error: unknown) {
|
||||
if (isApiError(error)) {
|
||||
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return "操作失败,请稍后重试。";
|
||||
}
|
||||
|
||||
function calculateRequestedDaysPreview(
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
startSession: LeaveSession,
|
||||
endSession: LeaveSession,
|
||||
) {
|
||||
if (!startDate || !endDate) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const start = new Date(`${startDate}T00:00:00.000Z`);
|
||||
const end = new Date(`${endDate}T00:00:00.000Z`);
|
||||
if (Number.isNaN(start.getTime()) || Number.isNaN(end.getTime())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const dayIndex = (value: Date) => Math.floor(value.getTime() / 86400000);
|
||||
const startSlot = dayIndex(start) * 2 + (startSession === "pm" ? 1 : 0);
|
||||
const endSlot = dayIndex(end) * 2 + (endSession === "pm" ? 1 : 0);
|
||||
if (endSlot < startSlot) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Number((((endSlot - startSlot + 1) / 2)).toFixed(1));
|
||||
}
|
||||
|
||||
function formatRangeLabel(item: {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
startSession: LeaveSession;
|
||||
endSession: LeaveSession;
|
||||
}) {
|
||||
const sessionLabel = (session: LeaveSession) => (session === "am" ? "上午" : "下午");
|
||||
if (item.startDate === item.endDate && item.startSession === item.endSession) {
|
||||
return `${item.startDate} ${sessionLabel(item.startSession)}`;
|
||||
}
|
||||
return `${item.startDate} ${sessionLabel(item.startSession)} → ${item.endDate} ${sessionLabel(item.endSession)}`;
|
||||
}
|
||||
|
||||
export function LeaveRequestPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const { me, permissions } = useAuth();
|
||||
|
||||
const canViewAll = hasPermission(permissions, "leave.view_all") || hasPermission(permissions, "leave.manage");
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState<LeaveRequestStatus | "">("");
|
||||
const [scope, setScope] = useState<"own" | "all">("own");
|
||||
const [page, setPage] = useState(1);
|
||||
|
||||
const [leaveTypeId, setLeaveTypeId] = useState("");
|
||||
const [startDate, setStartDate] = useState("");
|
||||
const [endDate, setEndDate] = useState("");
|
||||
const [startSession, setStartSession] = useState<LeaveSession>("am");
|
||||
const [endSession, setEndSession] = useState<LeaveSession>("pm");
|
||||
const [reason, setReason] = useState("");
|
||||
const [attachmentFile, setAttachmentFile] = useState<File | null>(null);
|
||||
const [formError, setFormError] = useState("");
|
||||
const [withdrawTarget, setWithdrawTarget] = useState<{ id: string; label: string } | null>(null);
|
||||
|
||||
const requestedDaysPreview = useMemo(
|
||||
() => calculateRequestedDaysPreview(startDate, endDate, startSession, endSession),
|
||||
[endDate, endSession, startDate, startSession],
|
||||
);
|
||||
|
||||
const leaveTypesQuery = useQuery({
|
||||
queryKey: ["leave", "types"],
|
||||
queryFn: () => fetchLeaveTypes({ enabled: true }),
|
||||
});
|
||||
|
||||
const balancesQuery = useQuery({
|
||||
queryKey: ["leave", "balances", me?.id],
|
||||
enabled: Boolean(me?.id),
|
||||
queryFn: () => fetchLeaveBalances(),
|
||||
});
|
||||
|
||||
const requestsQuery = useQuery({
|
||||
queryKey: ["leave", "requests", statusFilter, scope, page],
|
||||
queryFn: () =>
|
||||
fetchLeaveRequests({
|
||||
status: statusFilter || undefined,
|
||||
scope: canViewAll ? scope : "own",
|
||||
page,
|
||||
pageSize: PAGE_SIZE,
|
||||
}),
|
||||
});
|
||||
|
||||
const selectedLeaveType = useMemo(() => {
|
||||
return (leaveTypesQuery.data?.items ?? []).find((item) => item.id === leaveTypeId) ?? null;
|
||||
}, [leaveTypeId, leaveTypesQuery.data?.items]);
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!leaveTypeId) {
|
||||
throw new Error("请选择假期类型");
|
||||
}
|
||||
if (!startDate || !endDate) {
|
||||
throw new Error("请选择开始和结束日期");
|
||||
}
|
||||
if (!selectedLeaveType) {
|
||||
throw new Error("假期类型不存在或已失效");
|
||||
}
|
||||
if (requestedDaysPreview == null || requestedDaysPreview <= 0) {
|
||||
throw new Error("请检查开始/结束日期与半天时段");
|
||||
}
|
||||
if (selectedLeaveType.requiresAttachment && !attachmentFile) {
|
||||
throw new Error("当前假种必须上传附件");
|
||||
}
|
||||
if (
|
||||
attachmentFile &&
|
||||
selectedLeaveType.attachmentMimeTypes.length > 0 &&
|
||||
!selectedLeaveType.attachmentMimeTypes.includes(attachmentFile.type)
|
||||
) {
|
||||
throw new Error("附件类型不符合当前假种要求");
|
||||
}
|
||||
|
||||
return createLeaveRequest({
|
||||
leaveTypeId,
|
||||
startDate,
|
||||
endDate,
|
||||
startSession,
|
||||
endSession,
|
||||
reason,
|
||||
file: attachmentFile,
|
||||
});
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "requests"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "balances"] }),
|
||||
]);
|
||||
setLeaveTypeId("");
|
||||
setStartDate("");
|
||||
setEndDate("");
|
||||
setStartSession("am");
|
||||
setEndSession("pm");
|
||||
setReason("");
|
||||
setAttachmentFile(null);
|
||||
setFormError("");
|
||||
toast.success("请假草稿已创建");
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = resolveError(error);
|
||||
setFormError(message);
|
||||
toast.error(message);
|
||||
},
|
||||
});
|
||||
|
||||
const submitMutation = useMutation({
|
||||
mutationFn: (leaveRequestId: string) => submitLeaveRequest(leaveRequestId),
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "requests"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "balances"] }),
|
||||
]);
|
||||
toast.success("请假申请已提交");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(resolveError(error));
|
||||
},
|
||||
});
|
||||
|
||||
const withdrawMutation = useMutation({
|
||||
mutationFn: (leaveRequestId: string) => withdrawLeaveRequest(leaveRequestId),
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "requests"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["leave", "balances"] }),
|
||||
]);
|
||||
toast.success("请假申请已撤回");
|
||||
setWithdrawTarget(null);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(resolveError(error));
|
||||
},
|
||||
});
|
||||
|
||||
const totalPages = Math.max(1, Math.ceil((requestsQuery.data?.total ?? 0) / PAGE_SIZE));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader
|
||||
title="请假申请"
|
||||
subtitle="支持假种选择、半天粒度请假、额度冻结与撤回释放。"
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-base font-semibold text-zinc-900">额度概览</h3>
|
||||
{balancesQuery.isLoading ? (
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
<CardSkeleton lines={4} />
|
||||
<CardSkeleton lines={4} />
|
||||
<CardSkeleton lines={4} />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{balancesQuery.isError ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{resolveError(balancesQuery.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!balancesQuery.isLoading && !balancesQuery.isError ? (
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{(balancesQuery.data?.items ?? []).length ? (
|
||||
balancesQuery.data?.items.map((item) => (
|
||||
<div className="card-std space-y-2 p-5" key={item.leaveType.id}>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-base font-semibold text-zinc-900">{item.leaveType.name}</p>
|
||||
<p className="text-xs text-zinc-500">{item.periodStart} ~ {item.periodEnd}</p>
|
||||
</div>
|
||||
<StatusBadge status={item.leaveType.enabled ? "active" : "archived"} label={item.leaveType.enabled ? "启用" : "停用"} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 text-sm">
|
||||
<div>
|
||||
<p className="text-zinc-500">可用</p>
|
||||
<p className="text-xl font-semibold text-zinc-900">{item.available}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-zinc-500">已冻结</p>
|
||||
<p className="text-xl font-semibold text-zinc-900">{item.reserved}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-zinc-500">已使用</p>
|
||||
<p className="text-xl font-semibold text-zinc-900">{item.used}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-zinc-500">授予额度</p>
|
||||
<p className="text-xl font-semibold text-zinc-900">{item.policy.annualQuotaDays}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="card-std p-6 text-sm text-zinc-500 md:col-span-3">
|
||||
暂无可用假种,请联系 HR 初始化请假类型与策略。
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="card-std space-y-4 p-6">
|
||||
<h3 className="text-base font-semibold text-zinc-900">新建请假草稿</h3>
|
||||
|
||||
{formError ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{formError}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-type">假期类型</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
id="leave-type"
|
||||
value={leaveTypeId}
|
||||
onChange={(event) => setLeaveTypeId(event.target.value)}
|
||||
>
|
||||
<option value="">请选择</option>
|
||||
{(leaveTypesQuery.data?.items ?? []).map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-start-date">开始日期</Label>
|
||||
<Input id="leave-start-date" type="date" value={startDate} onChange={(event) => setStartDate(event.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-start-session">开始时段</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
id="leave-start-session"
|
||||
value={startSession}
|
||||
onChange={(event) => setStartSession(event.target.value as LeaveSession)}
|
||||
>
|
||||
<option value="am">上午</option>
|
||||
<option value="pm">下午</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-end-date">结束日期</Label>
|
||||
<Input id="leave-end-date" type="date" value={endDate} onChange={(event) => setEndDate(event.target.value)} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-end-session">结束时段</Label>
|
||||
<select
|
||||
className="select-std"
|
||||
id="leave-end-session"
|
||||
value={endSession}
|
||||
onChange={(event) => setEndSession(event.target.value as LeaveSession)}
|
||||
>
|
||||
<option value="am">上午</option>
|
||||
<option value="pm">下午</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-attachment">附件</Label>
|
||||
<Input
|
||||
id="leave-attachment"
|
||||
type="file"
|
||||
accept={selectedLeaveType?.attachmentMimeTypes?.join(",") || undefined}
|
||||
onChange={(event) => {
|
||||
const nextFile = event.target.files?.[0] ?? null;
|
||||
setAttachmentFile(nextFile);
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-zinc-500">
|
||||
{selectedLeaveType?.requiresAttachment
|
||||
? `当前假种要求上传附件(允许:${selectedLeaveType.attachmentMimeTypes.join(", ") || "默认文档/图片"})`
|
||||
: "附件为可选项"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="leave-reason">请假说明</Label>
|
||||
<Textarea
|
||||
id="leave-reason"
|
||||
rows={3}
|
||||
value={reason}
|
||||
onChange={(event) => setReason(event.target.value)}
|
||||
placeholder="请输入请假原因、备注或补充说明"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-zinc-200 bg-zinc-50 px-4 py-3 text-sm text-zinc-700">
|
||||
<div>
|
||||
预计请假天数:<span className="font-semibold text-zinc-900">{requestedDaysPreview ?? "-"}</span>
|
||||
</div>
|
||||
<Button type="button" disabled={createMutation.isPending} onClick={() => createMutation.mutate()}>
|
||||
{createMutation.isPending ? "创建中..." : "创建草稿"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std space-y-4 p-6">
|
||||
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
|
||||
<h3 className="text-base font-semibold text-zinc-900">请假记录</h3>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{canViewAll ? (
|
||||
<select
|
||||
className="select-std"
|
||||
value={scope}
|
||||
onChange={(event) => {
|
||||
setScope(event.target.value as "own" | "all");
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<option value="own">只看我的</option>
|
||||
<option value="all">查看全员</option>
|
||||
</select>
|
||||
) : null}
|
||||
<select
|
||||
className="select-std"
|
||||
value={statusFilter}
|
||||
onChange={(event) => {
|
||||
setStatusFilter(event.target.value as LeaveRequestStatus | "");
|
||||
setPage(1);
|
||||
}}
|
||||
>
|
||||
<option value="">全部状态</option>
|
||||
<option value="draft">草稿</option>
|
||||
<option value="reviewing">审批中</option>
|
||||
<option value="approved">已通过</option>
|
||||
<option value="rejected">已驳回</option>
|
||||
<option value="cancelled">已取消</option>
|
||||
</select>
|
||||
<Button type="button" variant="secondary" onClick={() => queryClient.invalidateQueries({ queryKey: ["leave", "requests"] })}>
|
||||
刷新
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{requestsQuery.isLoading ? <TableSkeleton columns={7} rows={5} /> : null}
|
||||
|
||||
{requestsQuery.isError ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{resolveError(requestsQuery.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{!requestsQuery.isLoading && !requestsQuery.isError ? (
|
||||
<div className="rounded-lg border border-zinc-200">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<tr>
|
||||
<TableHead>假种 / 申请人</TableHead>
|
||||
<TableHead>时间段</TableHead>
|
||||
<TableHead>天数</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>附件</TableHead>
|
||||
<TableHead>更新时间</TableHead>
|
||||
<TableHead className="w-44">操作</TableHead>
|
||||
</tr>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{(requestsQuery.data?.items ?? []).length ? (
|
||||
requestsQuery.data?.items.map((item) => {
|
||||
const isOwner = item.ownerId === me?.id;
|
||||
const canSubmit = isOwner && ["draft", "rejected"].includes(item.status);
|
||||
const canWithdraw = isOwner && item.status === "reviewing";
|
||||
|
||||
return (
|
||||
<TableRow key={item.id}>
|
||||
<TableCell>
|
||||
<div className="font-medium text-zinc-900">{item.leaveType?.name ?? "-"}</div>
|
||||
<div className="text-xs text-zinc-500">
|
||||
{item.owner?.name ?? "-"}
|
||||
{item.owner?.employeeNo ? ` (${item.owner.employeeNo})` : ""}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>{formatRangeLabel(item)}</TableCell>
|
||||
<TableCell>{item.requestedDays}</TableCell>
|
||||
<TableCell><StatusBadge status={item.status} /></TableCell>
|
||||
<TableCell className="text-xs text-zinc-500">
|
||||
{item.attachment?.originalName ?? "-"}
|
||||
</TableCell>
|
||||
<TableCell>{item.updatedAt ? new Date(item.updatedAt).toLocaleString() : "-"}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
type="button"
|
||||
disabled={!canSubmit || submitMutation.isPending}
|
||||
onClick={() => submitMutation.mutate(item.id)}
|
||||
>
|
||||
提交
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
type="button"
|
||||
disabled={!canWithdraw || withdrawMutation.isPending}
|
||||
onClick={() =>
|
||||
setWithdrawTarget({
|
||||
id: item.id,
|
||||
label: `${item.leaveType?.name ?? "请假"} · ${formatRangeLabel(item)}`,
|
||||
})
|
||||
}
|
||||
>
|
||||
撤回
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell className="py-4 text-zinc-500" colSpan={7}>
|
||||
暂无请假记录
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Pagination
|
||||
page={page}
|
||||
totalPages={totalPages}
|
||||
onPageChange={setPage}
|
||||
testIdPrefix="leave-requests"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ConfirmDialog
|
||||
open={Boolean(withdrawTarget)}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) {
|
||||
setWithdrawTarget(null);
|
||||
}
|
||||
}}
|
||||
title="确认撤回请假申请?"
|
||||
description={withdrawTarget ? `将撤回:${withdrawTarget.label}` : undefined}
|
||||
confirmLabel="确认撤回"
|
||||
onConfirm={async () => {
|
||||
if (!withdrawTarget) return;
|
||||
await withdrawMutation.mutateAsync(withdrawTarget.id);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,16 @@ import { Textarea } from "../components/ui/textarea";
|
||||
|
||||
type MobileAction = "approve" | "reject" | "return" | "transfer";
|
||||
|
||||
function entityLabel(entityType: string | undefined) {
|
||||
if (entityType === "leave") {
|
||||
return "请假";
|
||||
}
|
||||
if (entityType === "reimbursement") {
|
||||
return "报销";
|
||||
}
|
||||
return entityType || "未知";
|
||||
}
|
||||
|
||||
export function MobileApprovalsPage() {
|
||||
const queryClient = useQueryClient();
|
||||
const [selectedTaskId, setSelectedTaskId] = useState("");
|
||||
@@ -97,6 +107,7 @@ export function MobileApprovalsPage() {
|
||||
|
||||
const pendingTasks = tasksQuery.data?.items ?? [];
|
||||
const selectedTask = detailQuery.data;
|
||||
const isLeaveTask = selectedTask?.workflowInstance?.entityType === "leave";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
@@ -130,7 +141,7 @@ export function MobileApprovalsPage() {
|
||||
>
|
||||
<div className="font-medium">{task.stepName}</div>
|
||||
<div className="text-xs text-zinc-500">任务ID: {task.id}</div>
|
||||
<div className="text-xs text-zinc-500">状态: {task.status}</div>
|
||||
<div className="text-xs text-zinc-500">业务: {entityLabel(task.workflowInstance?.entityType)}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -150,9 +161,21 @@ export function MobileApprovalsPage() {
|
||||
<div className="rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<div>任务状态:{selectedTask.task.status}</div>
|
||||
<div>步骤:{selectedTask.task.stepName}</div>
|
||||
<div>报销单号:{selectedTask.reimbursement?.formNumber ?? "-"}</div>
|
||||
<div>金额:{selectedTask.reimbursement?.totalAmount ?? "-"}</div>
|
||||
<div>提交人:{selectedTask.reimbursement?.submitter?.name ?? "-"}</div>
|
||||
<div>对象类型:{entityLabel(selectedTask.workflowInstance?.entityType)}</div>
|
||||
{selectedTask.reimbursement ? (
|
||||
<>
|
||||
<div>报销单号:{selectedTask.reimbursement.formNumber ?? "-"}</div>
|
||||
<div>金额:{selectedTask.reimbursement.totalAmount ?? "-"}</div>
|
||||
<div>提交人:{selectedTask.reimbursement.submitter?.name ?? "-"}</div>
|
||||
</>
|
||||
) : null}
|
||||
{selectedTask.leaveRequest ? (
|
||||
<>
|
||||
<div>假期类型:{selectedTask.leaveRequest.leaveType?.name ?? "-"}</div>
|
||||
<div>申请人:{selectedTask.leaveRequest.owner?.name ?? "-"}</div>
|
||||
<div>请假天数:{selectedTask.leaveRequest.requestedDays}</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<Textarea
|
||||
@@ -192,40 +215,42 @@ export function MobileApprovalsPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<p className="font-medium text-zinc-800">转审</p>
|
||||
<select
|
||||
className="h-10 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm"
|
||||
data-testid="mobile-approvals-transfer-to"
|
||||
onChange={(event) => setTransferToApproverId(event.target.value)}
|
||||
value={transferToApproverId}
|
||||
>
|
||||
<option value="">请选择目标审批人</option>
|
||||
{(approversQuery.data?.items ?? []).map((approver) => (
|
||||
<option key={approver.id} value={approver.id}>
|
||||
{approver.name} ({approver.employeeNo})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{!isLeaveTask && selectedTask.allowedActions.includes("transfer") ? (
|
||||
<div className="space-y-2 rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<p className="font-medium text-zinc-800">转审</p>
|
||||
<select
|
||||
className="h-10 w-full rounded-lg border border-zinc-300 bg-white px-3 py-2 text-sm"
|
||||
data-testid="mobile-approvals-transfer-to"
|
||||
onChange={(event) => setTransferToApproverId(event.target.value)}
|
||||
value={transferToApproverId}
|
||||
>
|
||||
<option value="">请选择目标审批人</option>
|
||||
{(approversQuery.data?.items ?? []).map((approver) => (
|
||||
<option key={approver.id} value={approver.id}>
|
||||
{approver.name} ({approver.employeeNo})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<Textarea
|
||||
data-testid="mobile-approvals-transfer-reason"
|
||||
onChange={(event) => setTransferReason(event.target.value)}
|
||||
placeholder="转审理由(至少10字)"
|
||||
rows={2}
|
||||
value={transferReason}
|
||||
/>
|
||||
<Textarea
|
||||
data-testid="mobile-approvals-transfer-reason"
|
||||
onChange={(event) => setTransferReason(event.target.value)}
|
||||
placeholder="转审理由(至少10字)"
|
||||
rows={2}
|
||||
value={transferReason}
|
||||
/>
|
||||
|
||||
<Button
|
||||
data-testid="mobile-approvals-transfer"
|
||||
disabled={actionMutation.isPending || !selectedTask.allowedActions.includes("transfer")}
|
||||
onClick={() => actionMutation.mutate("transfer")}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
>
|
||||
提交转审
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
data-testid="mobile-approvals-transfer"
|
||||
disabled={actionMutation.isPending || !selectedTask.allowedActions.includes("transfer")}
|
||||
onClick={() => actionMutation.mutate("transfer")}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
>
|
||||
提交转审
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -20,6 +20,16 @@ import { StatusBadge } from "../components/common/StatusBadge";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Textarea } from "../components/ui/textarea";
|
||||
|
||||
function entityTitle(entityType: string | undefined) {
|
||||
if (entityType === "leave") {
|
||||
return "请假申请";
|
||||
}
|
||||
if (entityType === "reimbursement") {
|
||||
return "报销单";
|
||||
}
|
||||
return entityType || "业务单据";
|
||||
}
|
||||
|
||||
export function WorkflowTaskDetailPage() {
|
||||
const { taskId = "" } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -27,7 +37,7 @@ export function WorkflowTaskDetailPage() {
|
||||
const { permissions } = useAuth();
|
||||
|
||||
const [rejectComment, setRejectComment] = useState("请补充必要说明后重提");
|
||||
const [returnComment, setReturnComment] = useState("请补充报销说明并修正后重新提交");
|
||||
const [returnComment, setReturnComment] = useState("请补充必要信息并修正后重新提交");
|
||||
const [transferReason, setTransferReason] = useState("当前事项需转交对应审批人处理,请尽快处理。");
|
||||
const [selectedApprover, setSelectedApprover] = useState("");
|
||||
const [actionError, setActionError] = useState("");
|
||||
@@ -104,9 +114,7 @@ export function WorkflowTaskDetailPage() {
|
||||
}
|
||||
|
||||
if (detailQuery.isLoading) {
|
||||
return (
|
||||
<CardSkeleton lines={8} />
|
||||
);
|
||||
return <CardSkeleton lines={8} />;
|
||||
}
|
||||
|
||||
if (detailQuery.isError || !detailQuery.data) {
|
||||
@@ -133,6 +141,8 @@ export function WorkflowTaskDetailPage() {
|
||||
}
|
||||
|
||||
const detail = detailQuery.data;
|
||||
const isLeaveTask = detail.workflowInstance?.entityType === "leave";
|
||||
const canTransfer = allowedActions.has("transfer");
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -149,10 +159,30 @@ export function WorkflowTaskDetailPage() {
|
||||
<div className="card-std space-y-2 p-6 text-sm" data-testid="workflow-task-summary">
|
||||
<div>状态:<StatusBadge status={detail.task.status} /></div>
|
||||
<div>实例:{detail.workflowInstance?.id ?? "-"}</div>
|
||||
<div>报销单号:{detail.reimbursement?.formNumber ?? "-"}</div>
|
||||
<div>报销金额:{detail.reimbursement?.totalAmount ?? "-"}</div>
|
||||
<div>提交人:{detail.reimbursement?.submitter?.name ?? "-"}</div>
|
||||
<div>报销人:{detail.reimbursement?.owner?.name ?? "-"}</div>
|
||||
<div>对象类型:{entityTitle(detail.workflowInstance?.entityType)}</div>
|
||||
{detail.reimbursement ? (
|
||||
<>
|
||||
<div>报销单号:{detail.reimbursement.formNumber ?? "-"}</div>
|
||||
<div>报销金额:{detail.reimbursement.totalAmount ?? "-"}</div>
|
||||
<div>提交人:{detail.reimbursement.submitter?.name ?? "-"}</div>
|
||||
<div>报销人:{detail.reimbursement.owner?.name ?? "-"}</div>
|
||||
</>
|
||||
) : null}
|
||||
{detail.leaveRequest ? (
|
||||
<>
|
||||
<div>假期类型:{detail.leaveRequest.leaveType?.name ?? "-"}</div>
|
||||
<div>申请人:{detail.leaveRequest.owner?.name ?? "-"}</div>
|
||||
<div>
|
||||
时间段:
|
||||
{detail.leaveRequest.startDate ?? "-"} {detail.leaveRequest.startSession === "am" ? "上午" : "下午"}
|
||||
{" → "}
|
||||
{detail.leaveRequest.endDate ?? "-"} {detail.leaveRequest.endSession === "am" ? "上午" : "下午"}
|
||||
</div>
|
||||
<div>请假天数:{detail.leaveRequest.requestedDays}</div>
|
||||
<div>说明:{detail.leaveRequest.reason ?? "-"}</div>
|
||||
<div>附件:{detail.leaveRequest.attachment?.originalName ?? "-"}</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="card-std space-y-4 p-6">
|
||||
@@ -216,42 +246,44 @@ export function WorkflowTaskDetailPage() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 rounded-lg border border-zinc-200 p-4">
|
||||
<p className="text-sm font-medium text-zinc-800">转审</p>
|
||||
<select
|
||||
className="select-std"
|
||||
data-testid="workflow-task-transfer-to-approver"
|
||||
onChange={(event) => setSelectedApprover(event.target.value)}
|
||||
value={selectedApprover}
|
||||
>
|
||||
<option value="">请选择目标审批人</option>
|
||||
{(approverQuery.data?.items ?? []).map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name} ({item.employeeNo})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Textarea
|
||||
data-testid="workflow-task-transfer-reason"
|
||||
onChange={(event) => setTransferReason(event.target.value)}
|
||||
rows={2}
|
||||
value={transferReason}
|
||||
/>
|
||||
<Button
|
||||
data-testid="workflow-task-transfer"
|
||||
variant="secondary"
|
||||
disabled={
|
||||
!allowedActions.has("transfer") ||
|
||||
mutation.isPending ||
|
||||
!selectedApprover ||
|
||||
transferReason.trim().length < 10
|
||||
}
|
||||
onClick={() => mutation.mutate("transfer")}
|
||||
type="button"
|
||||
>
|
||||
提交转审
|
||||
</Button>
|
||||
</div>
|
||||
{canTransfer && !isLeaveTask ? (
|
||||
<div className="space-y-2 rounded-lg border border-zinc-200 p-4">
|
||||
<p className="text-sm font-medium text-zinc-800">转审</p>
|
||||
<select
|
||||
className="select-std"
|
||||
data-testid="workflow-task-transfer-to-approver"
|
||||
onChange={(event) => setSelectedApprover(event.target.value)}
|
||||
value={selectedApprover}
|
||||
>
|
||||
<option value="">请选择目标审批人</option>
|
||||
{(approverQuery.data?.items ?? []).map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name} ({item.employeeNo})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Textarea
|
||||
data-testid="workflow-task-transfer-reason"
|
||||
onChange={(event) => setTransferReason(event.target.value)}
|
||||
rows={2}
|
||||
value={transferReason}
|
||||
/>
|
||||
<Button
|
||||
data-testid="workflow-task-transfer"
|
||||
variant="secondary"
|
||||
disabled={
|
||||
!allowedActions.has("transfer") ||
|
||||
mutation.isPending ||
|
||||
!selectedApprover ||
|
||||
transferReason.trim().length < 10
|
||||
}
|
||||
onClick={() => mutation.mutate("transfer")}
|
||||
type="button"
|
||||
>
|
||||
提交转审
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="card-std space-y-3 p-6">
|
||||
|
||||
@@ -13,6 +13,16 @@ import { Tabs, TabsList, TabsTrigger } from "../components/ui/tabs";
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
function entityLabel(entityType: string | undefined) {
|
||||
if (entityType === "leave") {
|
||||
return "请假";
|
||||
}
|
||||
if (entityType === "reimbursement") {
|
||||
return "报销";
|
||||
}
|
||||
return entityType || "-";
|
||||
}
|
||||
|
||||
export function WorkflowTasksPage() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
@@ -35,7 +45,7 @@ export function WorkflowTasksPage() {
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="待我处理" subtitle="审批待办列表(支持筛选与详情动作联动)。" />
|
||||
<PageHeader title="待我处理" subtitle="审批待办列表,覆盖报销与请假流程。" />
|
||||
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<Tabs
|
||||
@@ -68,10 +78,10 @@ export function WorkflowTasksPage() {
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{isApiError(query.error)
|
||||
? `${query.error.code}: ${mapApiErrorMessage(
|
||||
query.error.code,
|
||||
query.error.details,
|
||||
query.error.message,
|
||||
)}`
|
||||
query.error.code,
|
||||
query.error.details,
|
||||
query.error.message,
|
||||
)}`
|
||||
: "加载待办失败,请稍后重试"}
|
||||
</p>
|
||||
) : null}
|
||||
@@ -82,7 +92,7 @@ export function WorkflowTasksPage() {
|
||||
<TableHeader>
|
||||
<tr>
|
||||
<TableHead>任务</TableHead>
|
||||
<TableHead>报销ID</TableHead>
|
||||
<TableHead>业务对象</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>创建时间</TableHead>
|
||||
<TableHead className="w-24">操作</TableHead>
|
||||
@@ -96,8 +106,13 @@ export function WorkflowTasksPage() {
|
||||
<div className="font-medium text-zinc-900">{task.stepName}</div>
|
||||
<div className="text-xs text-zinc-500">{task.id}</div>
|
||||
</TableCell>
|
||||
<TableCell className="font-mono text-xs">
|
||||
{task.workflowInstance?.entityId}
|
||||
<TableCell>
|
||||
<div className="font-medium text-zinc-900">
|
||||
{entityLabel(task.workflowInstance?.entityType)}
|
||||
</div>
|
||||
<div className="font-mono text-xs text-zinc-500">
|
||||
{task.workflowInstance?.entityId ?? "-"}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell><StatusBadge status={task.status} /></TableCell>
|
||||
<TableCell>{new Date(task.createdAt).toLocaleString()}</TableCell>
|
||||
|
||||
@@ -14,6 +14,7 @@ import { MobileApprovalsPage } from "../pages/MobileApprovalsPage";
|
||||
import { MobileCapturePage } from "../pages/MobileCapturePage";
|
||||
import { InvoicePoolPage } from "../pages/InvoicePoolPage";
|
||||
import { LoginPage } from "../pages/LoginPage";
|
||||
import { LeaveRequestPage } from "../pages/LeaveRequestPage";
|
||||
import { NotificationsPage } from "../pages/NotificationsPage";
|
||||
import { NotFoundPage } from "../pages/NotFoundPage";
|
||||
import { ProfilePage } from "../pages/ProfilePage";
|
||||
@@ -87,6 +88,15 @@ export function AppRouter() {
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="leave-requests"
|
||||
element={
|
||||
<RequirePermission anyOf={["leave.view_own", "leave.view_all"]}>
|
||||
<LeaveRequestPage />
|
||||
</RequirePermission>
|
||||
}
|
||||
/>
|
||||
|
||||
<Route
|
||||
path="workflow/tasks"
|
||||
element={
|
||||
|
||||
+21
-4
@@ -1,8 +1,8 @@
|
||||
# hyb-oa 实现状态矩阵(P5-P14)
|
||||
# hyb-oa 实现状态矩阵(P5-P15)
|
||||
|
||||
**快照日期**:2026-02-13
|
||||
**范围**:`F1-F42`(含 `F19b/F19c/F19d`)+ `R1-S2` + `P9A1-P9D1` + `P10E1-P10G1` + `G0-G6` + `H1` + `M1-M4` + `P13-0-P13-8` + `P14-0-P14-8`,共 110 项。
|
||||
**事实源**:`issues/2026-02-09_13-39-02-p5-blueprint-v3.csv` + `issues/2026-02-09_23-30-00-p6-p8-remaining-work-master.csv` + `issues/2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv` + `issues/2026-02-10_10-35-30-p10-production-hardening.csv` + `issues/2026-02-11-p11-p12-governance-mobile.csv` + `issues/2026-02-12_01-09-41-p13-l5-governance.csv` + `issues/2026-02-13_00-11-56-p14-l5-operationalization.csv`(执行合同)
|
||||
**快照日期**:2026-03-07
|
||||
**范围**:`F1-F42`(含 `F19b/F19c/F19d`)+ `R1-S2` + `P9A1-P9D1` + `P10E1-P10G1` + `G0-G6` + `H1` + `M1-M4` + `P13-0-P13-8` + `P14-0-P14-8` + `P15A-0-P15A-5` + `P15B-0-P15B-6`,共 124 项。
|
||||
**事实源**:`issues/2026-02-09_13-39-02-p5-blueprint-v3.csv` + `issues/2026-02-09_23-30-00-p6-p8-remaining-work-master.csv` + `issues/2026-02-10_09-42-31-p9-maintenance-performance-matrix.csv` + `issues/2026-02-10_10-35-30-p10-production-hardening.csv` + `issues/2026-02-11-p11-p12-governance-mobile.csv` + `issues/2026-02-12_01-09-41-p13-l5-governance.csv` + `issues/2026-02-13_00-11-56-p14-l5-operationalization.csv` + `issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv` + `issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv`(执行合同)
|
||||
|
||||
**说明**:
|
||||
- 本矩阵用于全局读图(审计/交接/回归覆盖追踪),不替代 `issues/*.csv` 的执行合同职责。
|
||||
@@ -125,3 +125,20 @@
|
||||
| P14-6 | OpenAPI覆盖扩展与漂移检查 | §16(OpenAPI覆盖扩展) | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13 | DONE | scripts/openapi_diff_check.py | none |
|
||||
| P14-7 | 分布式追踪最小落地 | §16(链路追踪) | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13 | DONE | manual | none |
|
||||
| P14-8 | P14验收与矩阵收口 | §16(验收与同步) | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13_00-11-56-p14-l5-operationalization.csv | 2026-02-13 | DONE | scripts/check-minimal.sh | none |
|
||||
|
||||
|
||||
| P15A-0 | P15A执行合同建档 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06 | DONE | CSV 校验 | none |
|
||||
| P15A-1 | 常量字典与角色补齐 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-07 | DONE | server:test | leave.* 权限与角色映射落地 |
|
||||
| P15A-2 | 工作流动态鉴权剥离 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-07 | DONE | server:test + regression-workflow-actions | workflow 审批按 entityType 动态鉴权 |
|
||||
| P15A-3 | 前端路由与菜单显隐域解耦 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-07 | DONE | client:typecheck/build | 复用审批入口支持 leave.approve |
|
||||
| P15A-4 | OpenAPI Tag分离 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-07 | DONE | /api/docs/json | leave 路由独立归组 |
|
||||
| P15A-5 | P15A全量回归测试 | §17(权限解耦治理) | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | 2026-03-07 | DONE | regression-all | 报销主流程零回归 |
|
||||
| P15B-0 | P15B执行合同建档 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06 | DONE | CSV 校验 | none |
|
||||
| P15B-1 | 国际化四层模型扩展 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | prisma migrate dev + prisma generate | LeaveType / LeavePolicy / LeaveLedger / LeaveRequest 扩展完成 |
|
||||
| P15B-2 | HR业务基础类型维表API | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | manual + server:test | leave-types CRUD 与策略绑定完成 |
|
||||
| P15B-2A | Leave申请列表接口 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | manual | 支持本人/全量视角列表查询 |
|
||||
| P15B-3 | 天数预检与隔离碰撞强设闸 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | manual leave flow | 半天粒度天数与冲突校验返回 422 |
|
||||
| P15B-4 | 状态机与冻结账本流转闭环 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | server:test + manual leave flow | reserve/release/consume 账本联动 workflow 完成 |
|
||||
| P15B-4A | Leave撤回与冻结释放接口 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | manual leave flow | 撤回恢复 draft 并释放冻结额度 |
|
||||
| P15B-5 | Leave申请前端模块集成 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | client:typecheck/build | 请假页面、菜单、路由与审批详情联动完成 |
|
||||
| P15B-6 | P15B验收联调测试 | §17(请假V1治理) | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-06_14-30-00-p15b-l5-leave-v1.csv | 2026-03-07 | DONE | regression-all + manual leave flow | 创建/提交/审批/冲突/撤回全链路通过 |
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
P15B-0,P15B执行合同建档,创建并校验P15B(Leave V1)执行合同CSV,CSV通过校验且字段完整,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,[],"需在P15A完成后建档"
|
||||
P15B-1,国际化四层模型扩展,"Prisma 建立 LeaveType/LeavePolicy/LeaveLedger 和增强的 LeaveRequest 字段(am-pm设计与天数计算)",Migration完成且结构符合国际HR内控原则,npx prisma migrate dev --name init_leave_v1_models,manual,TODO,TODO,TODO,server/prisma/schema.prisma,"[""P15B-0""]","日历与配额前置计算不纳入V1"
|
||||
P15B-2,HR业务基础类型维表API,支持HR增删改查 LeaveType 及绑定策略 (API CRUD),请求返回200并录入数据库,manual,manual,TODO,TODO,TODO,server/src/routes/leave-types.js,"[""P15B-1""]","新建路由"
|
||||
P15B-2A,Leave申请列表接口,补齐员工端与HR端的 Leave 列表查询接口支持按本人或全量视角查看历史申请,列表接口返回200且权限边界正确,manual,manual,TODO,TODO,TODO,server/src/routes/leave.js,"[""P15B-1""]","员工自助可用性的必要补齐"
|
||||
P15B-3,天数预检与隔离碰撞强设闸,"提交 Leave 时进行可用配额强设闸,并做同员工同时间段的日期重叠阻断",接口明确返回 HTTP 422 Conflict Range,"测试脚本 POST 日期交叉单拦截",manual,TODO,TODO,TODO,server/src/routes/leave.js,"[""P15B-1""]","核心规则引擎"
|
||||
P15B-4,状态机与冻结账本流转闭环,在 workflow.js 中的实体业务分支(875/1005处)追加针对 leave实体的账本扣减/释放逻辑,数据库余额按工作流事件准确变更,vitest transaction测试校验冻结数与已用数,manual,TODO,TODO,TODO,server/src/routes/leave.js | server/src/routes/workflow.js,"[""P15B-3""]","避免造不存在的hook"
|
||||
P15B-4A,Leave撤回与冻结释放接口,补齐 POST /leave-requests/:id/withdraw 以允许申请人在未被审批人处理前撤回并释放冻结账本,撤回后状态回到 draft 且冻结账本被释放,manual,manual,TODO,TODO,TODO,server/src/routes/leave.js | server/src/routes/workflow.js,"[""P15B-4""]","与报销撤回语义保持一致"
|
||||
P15B-5,Leave申请前端模块集成,实装半天粒度携带附件类型规则校验的跨天请假界面与剩余账本卡片视图并注册列表与发起入口,联调通过并可创建/查看/撤回请假申请,manual,manual,TODO,TODO,TODO,client/src/pages/LeaveRequestPage.tsx | client/src/router/index.tsx | client/src/components/navigation/NavLinks.tsx,"[""P15B-2"",""P15B-2A"",""P15B-4"",""P15B-4A""]","基于UI8设计结构"
|
||||
P15B-6,P15B验收联调测试,"P15B 全量集成流转,测试休假申请能否走通工作流并闭环实扣配额与撤回释放",回归测试并且手工创建/提交/撤回/审批请假流转完成,cd server && ./scripts/regression-all.sh,manual,TODO,TODO,TODO,none,"[""P15B-5""]","重中之重"
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
P15B-0,P15B执行合同建档,创建并校验P15B(Leave V1)执行合同CSV,CSV通过校验且字段完整,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,[],需在P15A完成后建档
|
||||
P15B-1,国际化四层模型扩展,Prisma 建立 LeaveType/LeavePolicy/LeaveLedger 和增强的 LeaveRequest 字段(am-pm设计与天数计算),Migration完成且结构符合国际HR内控原则,npx prisma migrate dev --name init_leave_v1_models,manual,DONE,DONE,DONE,server/prisma/schema.prisma,"[""P15B-0""]",日历与配额前置计算不纳入V1
|
||||
P15B-2,HR业务基础类型维表API,支持HR增删改查 LeaveType 及绑定策略 (API CRUD),请求返回200并录入数据库,manual,manual,DONE,DONE,DONE,server/src/routes/leave-types.js,"[""P15B-1""]",新建路由
|
||||
P15B-2A,Leave申请列表接口,补齐员工端与HR端的 Leave 列表查询接口支持按本人或全量视角查看历史申请,列表接口返回200且权限边界正确,manual,manual,DONE,DONE,DONE,server/src/routes/leave.js,"[""P15B-1""]",员工自助可用性的必要补齐
|
||||
P15B-3,天数预检与隔离碰撞强设闸,提交 Leave 时进行可用配额强设闸,并做同员工同时间段的日期重叠阻断,接口明确返回 HTTP 422 Conflict Range,测试脚本 POST 日期交叉单拦截,manual,DONE,DONE,DONE,server/src/routes/leave.js,"[""P15B-1""]",核心规则引擎
|
||||
P15B-4,状态机与冻结账本流转闭环,在 workflow.js 中的实体业务分支(875/1005处)追加针对 leave实体的账本扣减/释放逻辑,数据库余额按工作流事件准确变更,vitest transaction测试校验冻结数与已用数,manual,DONE,DONE,DONE,server/src/routes/leave.js | server/src/routes/workflow.js,"[""P15B-3""]",避免造不存在的hook
|
||||
P15B-4A,Leave撤回与冻结释放接口,补齐 POST /leave-requests/:id/withdraw 以允许申请人在未被审批人处理前撤回并释放冻结账本,撤回后状态回到 draft 且冻结账本被释放,manual,manual,DONE,DONE,DONE,server/src/routes/leave.js | server/src/routes/workflow.js,"[""P15B-4""]",与报销撤回语义保持一致
|
||||
P15B-5,Leave申请前端模块集成,实装半天粒度携带附件类型规则校验的跨天请假界面与剩余账本卡片视图并注册列表与发起入口,联调通过并可创建/查看/撤回请假申请,manual,manual,DONE,DONE,DONE,client/src/pages/LeaveRequestPage.tsx | client/src/router/index.tsx | client/src/components/navigation/NavLinks.tsx,"[""P15B-2"",""P15B-2A"",""P15B-4"",""P15B-4A""]",基于UI8设计结构
|
||||
P15B-6,P15B验收联调测试,P15B 全量集成流转,测试休假申请能否走通工作流并闭环实扣配额与撤回释放,回归测试并且手工创建/提交/撤回/审批请假流转完成,cd server && ./scripts/regression-all.sh,manual,DONE,DONE,DONE,none,"[""P15B-5""]",重中之重
|
||||
|
||||
|
@@ -1,10 +1,10 @@
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
R0,P15-P18路线图合同建档,创建并校验P15-P18 roadmap preflight 执行合同CSV,CSV通过校验且字段完整,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_20-00-00-p15-p18-roadmap-preflight.csv,manual,DONE,DONE,DONE,issues/2026-03-06_20-00-00-p15-p18-roadmap-preflight.csv,[],作为后续六个月总控合同
|
||||
R1,P14基线冻结与双提交,封板P14运营化产物并按计划完成基线提交收口,两笔chore提交完成且工作区清空,manual: git status && git log --oneline -n 2,manual,DONE,DONE,DONE,.github/workflows/ci-minimal.yml | .github/workflows/ci-regression.yml | docs/feature-matrix.md | docs/ops/ci-regression-reporting.md | issues/2026-02-13_00-11-56-p14-l5-operationalization.csv | scripts/coverage_gate.js | scripts/openapi_diff_check.py | scripts/validate_regression_report.py | scripts/validate-feature-matrix.py | server/.env.example | server/package.json | server/package-lock.json | server/scripts/export_openapi.js | server/src/app.js | server/src/config.js | server/src/index.js | server/src/observability/tracing.js | server/src/routes/invoicePool/read.js | server/src/routes/reimbursements.js | server/src/routes/workflow.js | server/tests/unit/services/ | server/tests/unit/utils/,"[""R0""]",本次以两笔chore提交完成基线封板
|
||||
R2,P15合同锚点校正,修正P15A伪文件锚点并补齐P15B列表/撤回能力合同,不再引用不存在文件且P15B覆盖列表与撤回流程,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv && python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,"[""R0""]",P15A-2 锚定 constants/auth/workflow;P15B补齐列表与撤回
|
||||
R3,Skills与MCP装配计划建档,固定skills安装与MCP启用边界并完成第一波必要skills安装,playwright与security-best-practices可用且MCP策略已固定,manual: ls -1 /home/shunli/.codex/skills,manual,DONE,DONE,DONE,/home/shunli/.codex/config.toml | /home/shunli/.codex/skills/playwright | /home/shunli/.codex/skills/security-best-practices,"[""R0""]",已安装 playwright 与 security-best-practices;MCP继续按需启用,仅预留postgres/github
|
||||
R4,P15A启动就绪审查,冻结P15A权限矩阵与接口落点避免开工后反复改合同,权限矩阵和落点与真实代码锚点一致,manual,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | server/src/constants/permissions.js | server/src/plugins/auth.js | server/src/routes/workflow.js | server/src/routes/leave.js | client/src/components/navigation/NavLinks.tsx | client/src/router/index.tsx,"[""R2""]",不改表结构;不扩transfer到leave
|
||||
R5,P15B启动就绪审查,冻结P15B四层模型与账本语义及列表/撤回边界,四层模型与账本语义和接口范围全部固定,manual,manual,TODO,TODO,TODO,issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv | server/prisma/schema.prisma | server/src/routes/leave.js | server/src/routes/workflow.js,"[""R2""]",默认自然日+半天边界;日历与节假日算法后置
|
||||
R6,P16共享主数据蓝图,定义 LegalEntity HolidayCalendar CostCenter DocumentCategory Supplier 的模型与API边界,主数据模型和API范围固定且可被leave purchase asset复用,manual,manual,TODO,TODO,TODO,module:master-data,"[""R5""]",先共享主数据后扩业务,避免再次耦回system.settings
|
||||
R7,P17轻采购蓝图,定义轻采购V1范围仅覆盖申请审批预算校验供应商与归档,采购范围固定且明确不含收货三单匹配与ERP过账,manual,manual,TODO,TODO,TODO,module:procurement,"[""R6""]",依赖Supplier与CostCenter等主数据
|
||||
R8,P18固资台账蓝图,定义资产卡片领用归还调拨盘点的V1范围,资产台账范围固定且明确不含折旧过账与ERP集成,manual,manual,TODO,TODO,TODO,module:assets,"[""R6""]",建议引用LegalEntity CostCenter DocumentCategory
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
R0,P15-P18路线图合同建档,创建并校验P15-P18 roadmap preflight 执行合同CSV,CSV通过校验且字段完整,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_20-00-00-p15-p18-roadmap-preflight.csv,manual,DONE,DONE,DONE,issues/2026-03-06_20-00-00-p15-p18-roadmap-preflight.csv,[],作为后续六个月总控合同
|
||||
R1,P14基线冻结与双提交,封板P14运营化产物并按计划完成基线提交收口,两笔chore提交完成且工作区清空,manual: git status && git log --oneline -n 2,manual,DONE,DONE,DONE,.github/workflows/ci-minimal.yml | .github/workflows/ci-regression.yml | docs/feature-matrix.md | docs/ops/ci-regression-reporting.md | issues/2026-02-13_00-11-56-p14-l5-operationalization.csv | scripts/coverage_gate.js | scripts/openapi_diff_check.py | scripts/validate_regression_report.py | scripts/validate-feature-matrix.py | server/.env.example | server/package.json | server/package-lock.json | server/scripts/export_openapi.js | server/src/app.js | server/src/config.js | server/src/index.js | server/src/observability/tracing.js | server/src/routes/invoicePool/read.js | server/src/routes/reimbursements.js | server/src/routes/workflow.js | server/tests/unit/services/ | server/tests/unit/utils/,"[""R0""]",本次以两笔chore提交完成基线封板
|
||||
R2,P15合同锚点校正,修正P15A伪文件锚点并补齐P15B列表/撤回能力合同,不再引用不存在文件且P15B覆盖列表与撤回流程,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv && python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv,"[""R0""]",P15A-2 锚定 constants/auth/workflow;P15B补齐列表与撤回
|
||||
R3,Skills与MCP装配计划建档,固定skills安装与MCP启用边界并完成第一波必要skills安装,playwright与security-best-practices可用且MCP策略已固定,manual: ls -1 /home/shunli/.codex/skills,manual,DONE,DONE,DONE,/home/shunli/.codex/config.toml | /home/shunli/.codex/skills/playwright | /home/shunli/.codex/skills/security-best-practices,"[""R0""]",已安装 playwright 与 security-best-practices;MCP继续按需启用,仅预留postgres/github
|
||||
R4,P15A启动就绪审查,冻结P15A权限矩阵与接口落点避免开工后反复改合同,权限矩阵和落点与真实代码锚点一致,manual,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15a-l5-permission-decouple.csv | server/src/constants/permissions.js | server/src/plugins/auth.js | server/src/routes/workflow.js | server/src/routes/leave.js | client/src/components/navigation/NavLinks.tsx | client/src/router/index.tsx,"[""R2""]",不改表结构;不扩transfer到leave
|
||||
R5,P15B启动就绪审查,冻结P15B四层模型与账本语义及列表/撤回边界,四层模型与账本语义和接口范围全部固定,manual,manual,DONE,DONE,DONE,issues/2026-03-06_14-30-00-p15b-l5-leave-v1.csv | server/prisma/schema.prisma | server/src/routes/leave.js | server/src/routes/workflow.js,"[""R2""]",默认自然日+半天边界;日历与节假日算法后置
|
||||
R6,P16共享主数据蓝图,定义 LegalEntity HolidayCalendar CostCenter DocumentCategory Supplier 的模型与API边界,主数据模型和API范围固定且可被leave purchase asset复用,manual,manual,TODO,TODO,TODO,module:master-data,"[""R5""]",先共享主数据后扩业务,避免再次耦回system.settings
|
||||
R7,P17轻采购蓝图,定义轻采购V1范围仅覆盖申请审批预算校验供应商与归档,采购范围固定且明确不含收货三单匹配与ERP过账,manual,manual,TODO,TODO,TODO,module:procurement,"[""R6""]",依赖Supplier与CostCenter等主数据
|
||||
R8,P18固资台账蓝图,定义资产卡片领用归还调拨盘点的V1范围,资产台账范围固定且明确不含折旧过账与ERP集成,manual,manual,TODO,TODO,TODO,module:assets,"[""R6""]",建议引用LegalEntity CostCenter DocumentCategory
|
||||
|
||||
|
@@ -26,6 +26,8 @@ CSV_FACT_SOURCES = [
|
||||
ROOT / "issues" / "2026-02-11-p11-p12-governance-mobile.csv",
|
||||
ROOT / "issues" / "2026-02-12_01-09-41-p13-l5-governance.csv",
|
||||
ROOT / "issues" / "2026-02-13_00-11-56-p14-l5-operationalization.csv",
|
||||
ROOT / "issues" / "2026-03-06_14-30-00-p15a-l5-permission-decouple.csv",
|
||||
ROOT / "issues" / "2026-03-06_14-30-00-p15b-l5-leave-v1.csv",
|
||||
]
|
||||
|
||||
ID_PATTERN = re.compile(r"^[A-Z][0-9][0-9A-Za-z-]*$")
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/*
|
||||
Warnings:
|
||||
|
||||
- Added the required column `leave_type_id` to the `leave_requests` table without a default value. This is not possible if the table is not empty.
|
||||
- Added the required column `requested_days` to the `leave_requests` table without a default value. This is not possible if the table is not empty.
|
||||
|
||||
*/
|
||||
-- CreateEnum
|
||||
CREATE TYPE "LeaveDaySession" AS ENUM ('am', 'pm');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "LeaveLedgerEntryType" AS ENUM ('grant', 'reserve', 'consume', 'release', 'adjust');
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "leave_requests" ADD COLUMN "attachment_mime_type" TEXT,
|
||||
ADD COLUMN "attachment_original_name" TEXT,
|
||||
ADD COLUMN "attachment_storage_path" TEXT,
|
||||
ADD COLUMN "end_session" "LeaveDaySession" NOT NULL DEFAULT 'pm',
|
||||
ADD COLUMN "leave_type_id" UUID NOT NULL,
|
||||
ADD COLUMN "requested_days" DECIMAL(8,1) NOT NULL,
|
||||
ADD COLUMN "start_session" "LeaveDaySession" NOT NULL DEFAULT 'am';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "leave_types" (
|
||||
"id" UUID NOT NULL,
|
||||
"code" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"description" TEXT,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"requires_attachment" BOOLEAN NOT NULL DEFAULT false,
|
||||
"attachment_mime_types" JSONB,
|
||||
"sort_order" INTEGER NOT NULL DEFAULT 100,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "leave_types_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "leave_policies" (
|
||||
"id" UUID NOT NULL,
|
||||
"leave_type_id" UUID NOT NULL,
|
||||
"annual_quota_days" DECIMAL(8,1) NOT NULL,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"description" TEXT,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "leave_policies_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "leave_ledgers" (
|
||||
"id" UUID NOT NULL,
|
||||
"employee_id" UUID NOT NULL,
|
||||
"leave_type_id" UUID NOT NULL,
|
||||
"leave_policy_id" UUID,
|
||||
"leave_request_id" UUID,
|
||||
"entry_type" "LeaveLedgerEntryType" NOT NULL,
|
||||
"days" DECIMAL(8,1) NOT NULL,
|
||||
"period_start" DATE,
|
||||
"period_end" DATE,
|
||||
"note" TEXT,
|
||||
"payload" JSONB,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"created_by" UUID,
|
||||
|
||||
CONSTRAINT "leave_ledgers_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "leave_types_code_key" ON "leave_types"("code");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_types_enabled_sort_order" ON "leave_types"("enabled", "sort_order");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "leave_policies_leave_type_id_key" ON "leave_policies"("leave_type_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_policies_enabled" ON "leave_policies"("enabled");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_ledger_employee_type_created_at" ON "leave_ledgers"("employee_id", "leave_type_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "leave_ledgers_leave_request_id_idx" ON "leave_ledgers"("leave_request_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_ledger_period" ON "leave_ledgers"("period_start", "period_end");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_ledger_entry_employee" ON "leave_ledgers"("entry_type", "employee_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "leave_requests_leave_type_id_idx" ON "leave_requests"("leave_type_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "idx_leave_owner_date_range" ON "leave_requests"("owner_id", "start_date", "end_date");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_policies" ADD CONSTRAINT "leave_policies_leave_type_id_fkey" FOREIGN KEY ("leave_type_id") REFERENCES "leave_types"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_requests" ADD CONSTRAINT "leave_requests_leave_type_id_fkey" FOREIGN KEY ("leave_type_id") REFERENCES "leave_types"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_ledgers" ADD CONSTRAINT "leave_ledgers_employee_id_fkey" FOREIGN KEY ("employee_id") REFERENCES "employees"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_ledgers" ADD CONSTRAINT "leave_ledgers_leave_type_id_fkey" FOREIGN KEY ("leave_type_id") REFERENCES "leave_types"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_ledgers" ADD CONSTRAINT "leave_ledgers_leave_policy_id_fkey" FOREIGN KEY ("leave_policy_id") REFERENCES "leave_policies"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "leave_ledgers" ADD CONSTRAINT "leave_ledgers_leave_request_id_fkey" FOREIGN KEY ("leave_request_id") REFERENCES "leave_requests"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
+205
-110
@@ -44,6 +44,19 @@ enum LeaveRequestStatus {
|
||||
cancelled
|
||||
}
|
||||
|
||||
enum LeaveDaySession {
|
||||
am
|
||||
pm
|
||||
}
|
||||
|
||||
enum LeaveLedgerEntryType {
|
||||
grant
|
||||
reserve
|
||||
consume
|
||||
release
|
||||
adjust
|
||||
}
|
||||
|
||||
enum InvoicePoolStatus {
|
||||
pending_ocr
|
||||
ocr_failed
|
||||
@@ -159,13 +172,13 @@ model Employee {
|
||||
bank_name String
|
||||
id_number_encrypted String?
|
||||
|
||||
password_hash String
|
||||
token_version Int @default(0)
|
||||
must_change_password Boolean @default(false)
|
||||
login_failed_count Int @default(0)
|
||||
password_hash String
|
||||
token_version Int @default(0)
|
||||
must_change_password Boolean @default(false)
|
||||
login_failed_count Int @default(0)
|
||||
login_failed_first_at DateTime?
|
||||
login_locked_until DateTime?
|
||||
archived_at DateTime?
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
@@ -182,19 +195,20 @@ model Employee {
|
||||
delegation_grants_as_delegate DelegationGrant[] @relation("DelegationDelegate")
|
||||
|
||||
auth_sessions AuthSession[]
|
||||
audit_logs AuditLog[] @relation("AuditActor")
|
||||
audit_logs AuditLog[] @relation("AuditActor")
|
||||
notifications Notification[]
|
||||
|
||||
submitted_reimbursements ReimbursementForm[] @relation("ReimbursementSubmitter")
|
||||
owned_reimbursements ReimbursementForm[] @relation("ReimbursementOwner")
|
||||
paid_reimbursements ReimbursementForm[] @relation("ReimbursementPaidBy")
|
||||
leave_requests LeaveRequest[]
|
||||
leave_ledgers LeaveLedger[]
|
||||
|
||||
owned_invoices InvoicePool[] @relation("InvoiceOwner")
|
||||
uploaded_invoices InvoicePool[] @relation("InvoiceUploader")
|
||||
overridden_invoices InvoicePool[] @relation("InvoiceOverrideBy")
|
||||
owned_invoices InvoicePool[] @relation("InvoiceOwner")
|
||||
uploaded_invoices InvoicePool[] @relation("InvoiceUploader")
|
||||
overridden_invoices InvoicePool[] @relation("InvoiceOverrideBy")
|
||||
requested_invoice_verifications InvoiceVerificationRecord[] @relation("InvoiceVerificationRequester")
|
||||
travel_orders TravelOrder[]
|
||||
travel_orders TravelOrder[]
|
||||
|
||||
workflow_instances_started WorkflowInstance[] @relation("WorkflowInstanceSubmitter")
|
||||
workflow_history_actions WorkflowHistory[] @relation("WorkflowHistoryActor")
|
||||
@@ -302,15 +316,15 @@ model AuditLog {
|
||||
}
|
||||
|
||||
model Notification {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
recipient_employee_id String @db.Uuid
|
||||
type String @db.VarChar(64)
|
||||
title String @db.VarChar(200)
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
recipient_employee_id String @db.Uuid
|
||||
type String @db.VarChar(64)
|
||||
title String @db.VarChar(200)
|
||||
body String?
|
||||
target_type String? @db.VarChar(64)
|
||||
target_id String? @db.Uuid
|
||||
target_type String? @db.VarChar(64)
|
||||
target_id String? @db.Uuid
|
||||
read_at DateTime?
|
||||
created_at DateTime @default(now())
|
||||
created_at DateTime @default(now())
|
||||
|
||||
recipient Employee @relation(fields: [recipient_employee_id], references: [id], onDelete: Cascade)
|
||||
|
||||
@@ -383,10 +397,10 @@ model ReimbursementForm {
|
||||
paid_by_employee Employee? @relation("ReimbursementPaidBy", fields: [paid_by], references: [id], onDelete: SetNull)
|
||||
department Department @relation(fields: [department_id], references: [id], onDelete: Restrict)
|
||||
|
||||
items ReimbursementItem[]
|
||||
invoice_pool_items InvoicePool[]
|
||||
workflow_instances WorkflowInstance[]
|
||||
approval_transfers ApprovalTransfer[]
|
||||
items ReimbursementItem[]
|
||||
invoice_pool_items InvoicePool[]
|
||||
workflow_instances WorkflowInstance[]
|
||||
approval_transfers ApprovalTransfer[]
|
||||
budget_ledger_entries BudgetLedgerEntry[]
|
||||
travel_orders TravelOrder[]
|
||||
|
||||
@@ -424,32 +438,113 @@ model ReimbursementItem {
|
||||
@@map("reimbursement_items")
|
||||
}
|
||||
|
||||
model LeaveRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
owner_id String @db.Uuid
|
||||
department_id String @db.Uuid
|
||||
start_date DateTime @db.Date
|
||||
end_date DateTime @db.Date
|
||||
reason String?
|
||||
status LeaveRequestStatus @default(draft)
|
||||
model LeaveType {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
name String
|
||||
description String?
|
||||
enabled Boolean @default(true)
|
||||
requires_attachment Boolean @default(false)
|
||||
attachment_mime_types Json?
|
||||
sort_order Int @default(100)
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
owner Employee @relation(fields: [owner_id], references: [id], onDelete: Restrict)
|
||||
department Department @relation(fields: [department_id], references: [id], onDelete: Restrict)
|
||||
leave_policy LeavePolicy?
|
||||
leave_requests LeaveRequest[]
|
||||
leave_ledgers LeaveLedger[]
|
||||
|
||||
@@index([enabled, sort_order], map: "idx_leave_types_enabled_sort_order")
|
||||
@@map("leave_types")
|
||||
}
|
||||
|
||||
model LeavePolicy {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
leave_type_id String @unique @db.Uuid
|
||||
annual_quota_days Decimal @db.Decimal(8, 1)
|
||||
enabled Boolean @default(true)
|
||||
description String?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
leave_type LeaveType @relation(fields: [leave_type_id], references: [id], onDelete: Cascade)
|
||||
leave_ledgers LeaveLedger[]
|
||||
|
||||
@@index([enabled], map: "idx_leave_policies_enabled")
|
||||
@@map("leave_policies")
|
||||
}
|
||||
|
||||
model LeaveRequest {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
owner_id String @db.Uuid
|
||||
department_id String @db.Uuid
|
||||
leave_type_id String @db.Uuid
|
||||
start_date DateTime @db.Date
|
||||
end_date DateTime @db.Date
|
||||
start_session LeaveDaySession @default(am)
|
||||
end_session LeaveDaySession @default(pm)
|
||||
requested_days Decimal @db.Decimal(8, 1)
|
||||
reason String?
|
||||
attachment_storage_path String?
|
||||
attachment_original_name String?
|
||||
attachment_mime_type String?
|
||||
status LeaveRequestStatus @default(draft)
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
updated_at DateTime @updatedAt
|
||||
updated_by String? @db.Uuid
|
||||
|
||||
owner Employee @relation(fields: [owner_id], references: [id], onDelete: Restrict)
|
||||
department Department @relation(fields: [department_id], references: [id], onDelete: Restrict)
|
||||
leave_type LeaveType @relation(fields: [leave_type_id], references: [id], onDelete: Restrict)
|
||||
leave_ledgers LeaveLedger[]
|
||||
|
||||
workflow_instances WorkflowInstance[]
|
||||
|
||||
@@index([owner_id])
|
||||
@@index([department_id])
|
||||
@@index([leave_type_id])
|
||||
@@index([status])
|
||||
@@index([owner_id, status, updated_at], map: "idx_leave_owner_status_updated_at")
|
||||
@@index([owner_id, start_date, end_date], map: "idx_leave_owner_date_range")
|
||||
@@map("leave_requests")
|
||||
}
|
||||
|
||||
model LeaveLedger {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
employee_id String @db.Uuid
|
||||
leave_type_id String @db.Uuid
|
||||
leave_policy_id String? @db.Uuid
|
||||
leave_request_id String? @db.Uuid
|
||||
entry_type LeaveLedgerEntryType
|
||||
days Decimal @db.Decimal(8, 1)
|
||||
period_start DateTime? @db.Date
|
||||
period_end DateTime? @db.Date
|
||||
note String?
|
||||
payload Json?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
|
||||
employee Employee @relation(fields: [employee_id], references: [id], onDelete: Restrict)
|
||||
leave_type LeaveType @relation(fields: [leave_type_id], references: [id], onDelete: Restrict)
|
||||
leave_policy LeavePolicy? @relation(fields: [leave_policy_id], references: [id], onDelete: SetNull)
|
||||
leave_request LeaveRequest? @relation(fields: [leave_request_id], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([employee_id, leave_type_id, created_at], map: "idx_leave_ledger_employee_type_created_at")
|
||||
@@index([leave_request_id])
|
||||
@@index([period_start, period_end], map: "idx_leave_ledger_period")
|
||||
@@index([entry_type, employee_id], map: "idx_leave_ledger_entry_employee")
|
||||
@@map("leave_ledgers")
|
||||
}
|
||||
|
||||
model OcrResult {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
file_sha256 String
|
||||
@@ -484,15 +579,15 @@ model InvoicePool {
|
||||
linked_item_id String? @db.Uuid
|
||||
remarks String?
|
||||
|
||||
ocr_provider OcrProvider @default(tencent)
|
||||
ocr_type OcrType @default(general)
|
||||
ocr_result_id String? @db.Uuid
|
||||
ocr_attempts Int @default(0)
|
||||
ocr_provider OcrProvider @default(tencent)
|
||||
ocr_type OcrType @default(general)
|
||||
ocr_result_id String? @db.Uuid
|
||||
ocr_attempts Int @default(0)
|
||||
ocr_last_requested_at DateTime?
|
||||
ocr_last_error String?
|
||||
ocr_completed_at DateTime?
|
||||
ocr_locked_at DateTime?
|
||||
ocr_lock_owner String? @db.VarChar(128)
|
||||
ocr_last_error String?
|
||||
ocr_completed_at DateTime?
|
||||
ocr_locked_at DateTime?
|
||||
ocr_lock_owner String? @db.VarChar(128)
|
||||
|
||||
invoice_code String?
|
||||
invoice_number String?
|
||||
@@ -517,9 +612,9 @@ model InvoicePool {
|
||||
uploaded_by_employee Employee @relation("InvoiceUploader", fields: [uploaded_by_employee_id], references: [id], onDelete: Restrict)
|
||||
overridden_by_employee Employee? @relation("InvoiceOverrideBy", fields: [overridden_by], references: [id], onDelete: Restrict)
|
||||
|
||||
ocr_result OcrResult? @relation(fields: [ocr_result_id], references: [id], onDelete: SetNull)
|
||||
linked_reimbursement ReimbursementForm? @relation(fields: [linked_reimbursement_id], references: [id], onDelete: SetNull)
|
||||
linked_item ReimbursementItem? @relation(fields: [linked_item_id], references: [id], onDelete: SetNull)
|
||||
ocr_result OcrResult? @relation(fields: [ocr_result_id], references: [id], onDelete: SetNull)
|
||||
linked_reimbursement ReimbursementForm? @relation(fields: [linked_reimbursement_id], references: [id], onDelete: SetNull)
|
||||
linked_item ReimbursementItem? @relation(fields: [linked_item_id], references: [id], onDelete: SetNull)
|
||||
verification_records InvoiceVerificationRecord[]
|
||||
|
||||
@@index([owner_employee_id])
|
||||
@@ -534,27 +629,27 @@ model InvoicePool {
|
||||
}
|
||||
|
||||
model InvoiceVerificationRecord {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
invoice_id String @db.Uuid
|
||||
provider String @db.VarChar(32)
|
||||
status String @db.VarChar(16)
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
invoice_id String @db.Uuid
|
||||
provider String @db.VarChar(32)
|
||||
status String @db.VarChar(16)
|
||||
request_payload Json?
|
||||
result_payload Json?
|
||||
result_code String? @db.VarChar(64)
|
||||
result_message String?
|
||||
error_code String? @db.VarChar(64)
|
||||
error_message String?
|
||||
duration_ms Int?
|
||||
requested_by String? @db.Uuid
|
||||
requested_at DateTime @default(now())
|
||||
completed_at DateTime?
|
||||
retry_of_id String? @db.Uuid
|
||||
attempts Int @default(1)
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
result_code String? @db.VarChar(64)
|
||||
result_message String?
|
||||
error_code String? @db.VarChar(64)
|
||||
error_message String?
|
||||
duration_ms Int?
|
||||
requested_by String? @db.Uuid
|
||||
requested_at DateTime @default(now())
|
||||
completed_at DateTime?
|
||||
retry_of_id String? @db.Uuid
|
||||
attempts Int @default(1)
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
invoice InvoicePool @relation(fields: [invoice_id], references: [id], onDelete: Cascade)
|
||||
requester Employee? @relation("InvoiceVerificationRequester", fields: [requested_by], references: [id], onDelete: SetNull)
|
||||
invoice InvoicePool @relation(fields: [invoice_id], references: [id], onDelete: Cascade)
|
||||
requester Employee? @relation("InvoiceVerificationRequester", fields: [requested_by], references: [id], onDelete: SetNull)
|
||||
retry_of InvoiceVerificationRecord? @relation("InvoiceVerificationRetry", fields: [retry_of_id], references: [id], onDelete: SetNull)
|
||||
retries InvoiceVerificationRecord[] @relation("InvoiceVerificationRetry")
|
||||
|
||||
@@ -565,16 +660,16 @@ model InvoiceVerificationRecord {
|
||||
}
|
||||
|
||||
model BudgetPool {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
code String @unique
|
||||
name String
|
||||
department_id String? @db.Uuid
|
||||
status String @default("active") @db.VarChar(16)
|
||||
period_start DateTime @db.Date
|
||||
period_end DateTime @db.Date
|
||||
allocated_amount Decimal @db.Decimal(14, 2)
|
||||
used_amount Decimal @default(0) @db.Decimal(14, 2)
|
||||
warning_threshold_percent Int @default(80)
|
||||
department_id String? @db.Uuid
|
||||
status String @default("active") @db.VarChar(16)
|
||||
period_start DateTime @db.Date
|
||||
period_end DateTime @db.Date
|
||||
allocated_amount Decimal @db.Decimal(14, 2)
|
||||
used_amount Decimal @default(0) @db.Decimal(14, 2)
|
||||
warning_threshold_percent Int @default(80)
|
||||
archived_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
@@ -609,13 +704,13 @@ model BudgetLedgerEntry {
|
||||
}
|
||||
|
||||
model FeatureFlag {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
flag_key String @unique @db.VarChar(64)
|
||||
override_mode String @default("force_off") @db.VarChar(16)
|
||||
rollout_type String @default("global") @db.VarChar(32)
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
flag_key String @unique @db.VarChar(64)
|
||||
override_mode String @default("force_off") @db.VarChar(16)
|
||||
rollout_type String @default("global") @db.VarChar(32)
|
||||
department_ids Json?
|
||||
note String?
|
||||
version Int @default(1)
|
||||
note String?
|
||||
version Int @default(1)
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
@@ -627,16 +722,16 @@ model FeatureFlag {
|
||||
}
|
||||
|
||||
model IntegrationOutbox {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
event_type String @db.VarChar(64)
|
||||
status String @default("pending") @db.VarChar(16)
|
||||
payload Json
|
||||
dedupe_key String? @db.VarChar(128)
|
||||
attempts Int @default(0)
|
||||
max_attempts Int @default(5)
|
||||
last_error String?
|
||||
next_retry_at DateTime?
|
||||
processed_at DateTime?
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
event_type String @db.VarChar(64)
|
||||
status String @default("pending") @db.VarChar(16)
|
||||
payload Json
|
||||
dedupe_key String? @db.VarChar(128)
|
||||
attempts Int @default(0)
|
||||
max_attempts Int @default(5)
|
||||
last_error String?
|
||||
next_retry_at DateTime?
|
||||
processed_at DateTime?
|
||||
dead_letter_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
@@ -650,16 +745,16 @@ model IntegrationOutbox {
|
||||
}
|
||||
|
||||
model TravelOrder {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
source String @default("manual") @db.VarChar(32)
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
source String @default("manual") @db.VarChar(32)
|
||||
external_order_no String
|
||||
employee_id String @db.Uuid
|
||||
department_id String? @db.Uuid
|
||||
linked_reimbursement_id String? @db.Uuid
|
||||
employee_id String @db.Uuid
|
||||
department_id String? @db.Uuid
|
||||
linked_reimbursement_id String? @db.Uuid
|
||||
occurred_at DateTime? @db.Date
|
||||
amount Decimal? @db.Decimal(14, 2)
|
||||
currency String @default("CNY") @db.VarChar(8)
|
||||
status String @default("imported") @db.VarChar(20)
|
||||
amount Decimal? @db.Decimal(14, 2)
|
||||
currency String @default("CNY") @db.VarChar(8)
|
||||
status String @default("imported") @db.VarChar(20)
|
||||
raw_payload Json?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
@@ -678,11 +773,11 @@ model TravelOrder {
|
||||
}
|
||||
|
||||
model NotificationChannel {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
channel_type String @db.VarChar(32)
|
||||
name String
|
||||
enabled Boolean @default(true)
|
||||
config_json Json
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
channel_type String @db.VarChar(32)
|
||||
name String
|
||||
enabled Boolean @default(true)
|
||||
config_json Json
|
||||
template_json Json?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
@@ -714,18 +809,18 @@ model WorkflowDefinition {
|
||||
}
|
||||
|
||||
model WorkflowInstance {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
workflow_id String @db.Uuid
|
||||
entity_type String
|
||||
entity_id String @db.Uuid
|
||||
reimbursement_id String? @db.Uuid
|
||||
leave_request_id String? @db.Uuid
|
||||
submitter_id String @db.Uuid
|
||||
current_status WorkflowInstanceStatus @default(pending)
|
||||
current_step_id String
|
||||
context_data Json
|
||||
started_at DateTime @default(now())
|
||||
completed_at DateTime?
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
workflow_id String @db.Uuid
|
||||
entity_type String
|
||||
entity_id String @db.Uuid
|
||||
reimbursement_id String? @db.Uuid
|
||||
leave_request_id String? @db.Uuid
|
||||
submitter_id String @db.Uuid
|
||||
current_status WorkflowInstanceStatus @default(pending)
|
||||
current_step_id String
|
||||
context_data Json
|
||||
started_at DateTime @default(now())
|
||||
completed_at DateTime?
|
||||
|
||||
created_at DateTime @default(now())
|
||||
created_by String? @db.Uuid
|
||||
|
||||
@@ -21,6 +21,7 @@ const reimbursementRoutes = require("./routes/reimbursements");
|
||||
const invoicePoolRoutes = require("./routes/invoicePool");
|
||||
const workflowRoutes = require("./routes/workflow");
|
||||
const leaveRoutes = require("./routes/leave");
|
||||
const leaveTypesRoutes = require("./routes/leave-types");
|
||||
const delegationRoutes = require("./routes/delegations");
|
||||
const auditRoutes = require("./routes/audit");
|
||||
const usersRoutes = require("./routes/users");
|
||||
@@ -274,6 +275,7 @@ async function buildApp() {
|
||||
await app.register(reimbursementRoutes, { prefix: "/api" });
|
||||
await app.register(invoicePoolRoutes, { prefix: "/api" });
|
||||
await app.register(workflowRoutes, { prefix: "/api" });
|
||||
await app.register(leaveTypesRoutes, { prefix: "/api" });
|
||||
await app.register(leaveRoutes, { prefix: "/api" });
|
||||
await app.register(delegationRoutes, { prefix: "/api" });
|
||||
await app.register(auditRoutes, { prefix: "/api" });
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -105,6 +105,43 @@ const DEFAULT_LEAVE_WORKFLOW_DEFINITION = {
|
||||
],
|
||||
};
|
||||
|
||||
|
||||
const DEFAULT_LEAVE_TYPES = [
|
||||
{
|
||||
code: "annual_leave",
|
||||
name: "年假",
|
||||
description: "按自然日+半天粒度扣减。",
|
||||
enabled: true,
|
||||
requires_attachment: false,
|
||||
attachment_mime_types: null,
|
||||
sort_order: 10,
|
||||
annual_quota_days: "15.0",
|
||||
policy_description: "默认年度授予 15 天。",
|
||||
},
|
||||
{
|
||||
code: "sick_leave",
|
||||
name: "病假",
|
||||
description: "病假需上传诊断或病历附件。",
|
||||
enabled: true,
|
||||
requires_attachment: true,
|
||||
attachment_mime_types: ["application/pdf", "image/jpeg", "image/png"],
|
||||
sort_order: 20,
|
||||
annual_quota_days: "10.0",
|
||||
policy_description: "默认年度授予 10 天。",
|
||||
},
|
||||
{
|
||||
code: "personal_leave",
|
||||
name: "事假",
|
||||
description: "事假默认走经理审批。",
|
||||
enabled: true,
|
||||
requires_attachment: false,
|
||||
attachment_mime_types: null,
|
||||
sort_order: 30,
|
||||
annual_quota_days: "5.0",
|
||||
policy_description: "默认年度授予 5 天。",
|
||||
},
|
||||
];
|
||||
|
||||
async function seedExpenseTypes(prisma) {
|
||||
const now = new Date();
|
||||
const allTypes = [
|
||||
@@ -179,6 +216,61 @@ async function seedDocumentSequence(prisma) {
|
||||
});
|
||||
}
|
||||
|
||||
async function seedLeaveTypes(prisma) {
|
||||
const now = new Date();
|
||||
|
||||
for (const item of DEFAULT_LEAVE_TYPES) {
|
||||
const leaveType = await prisma.leaveType.upsert({
|
||||
where: { code: item.code },
|
||||
update: {
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
enabled: item.enabled,
|
||||
requires_attachment: item.requires_attachment,
|
||||
attachment_mime_types: item.attachment_mime_types,
|
||||
sort_order: item.sort_order,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
create: {
|
||||
code: item.code,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
enabled: item.enabled,
|
||||
requires_attachment: item.requires_attachment,
|
||||
attachment_mime_types: item.attachment_mime_types,
|
||||
sort_order: item.sort_order,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
await prisma.leavePolicy.upsert({
|
||||
where: { leave_type_id: leaveType.id },
|
||||
update: {
|
||||
annual_quota_days: item.annual_quota_days,
|
||||
enabled: item.enabled,
|
||||
description: item.policy_description,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
create: {
|
||||
leave_type_id: leaveType.id,
|
||||
annual_quota_days: item.annual_quota_days,
|
||||
enabled: item.enabled,
|
||||
description: item.policy_description,
|
||||
created_at: now,
|
||||
created_by: null,
|
||||
updated_at: now,
|
||||
updated_by: null,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function seedWorkflowDefinition(prisma) {
|
||||
await prisma.workflowDefinition.updateMany({
|
||||
where: {
|
||||
@@ -254,6 +346,7 @@ async function main() {
|
||||
await seedApprovalRules(prisma);
|
||||
await seedDocumentSequence(prisma);
|
||||
await seedWorkflowDefinition(prisma);
|
||||
await seedLeaveTypes(prisma);
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("Seeded config data:");
|
||||
@@ -267,6 +360,8 @@ async function main() {
|
||||
console.log("- workflow definition: reimbursement v1 (1-step role=ceo)");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log("- workflow definition: leave v1 (1-step department_manager)");
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`- leave types: ${DEFAULT_LEAVE_TYPES.length} seeded with default policies`);
|
||||
} finally {
|
||||
await prisma.$disconnect();
|
||||
await pool.end();
|
||||
|
||||
@@ -0,0 +1,496 @@
|
||||
const crypto = require("node:crypto");
|
||||
const path = require("node:path");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { compactDateString } = require("../utils/date");
|
||||
const { writeBuffer } = require("./storage");
|
||||
|
||||
const DEFAULT_ATTACHMENT_MIME_TYPES = [
|
||||
"application/pdf",
|
||||
"image/jpeg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
];
|
||||
|
||||
const SESSION_ORDER = {
|
||||
am: 0,
|
||||
pm: 1,
|
||||
};
|
||||
|
||||
function buildLeaveValidationError(details, statusCode = 422) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeDateOnly(value) {
|
||||
if (value instanceof Date) {
|
||||
return new Date(`${value.toISOString().slice(0, 10)}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
return new Date(`${value}T00:00:00.000Z`);
|
||||
}
|
||||
|
||||
throw buildLeaveValidationError({ date: "invalid" }, 400);
|
||||
}
|
||||
|
||||
function formatDateOnly(value) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return normalizeDateOnly(value).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function toHalfDayUnits(value) {
|
||||
const numeric = Number(value ?? 0);
|
||||
if (!Number.isFinite(numeric)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return Math.round(numeric * 2);
|
||||
}
|
||||
|
||||
function fromHalfDayUnits(units) {
|
||||
return Number((units / 2).toFixed(1));
|
||||
}
|
||||
|
||||
function toHalfDaySlot(dateValue, session) {
|
||||
const date = normalizeDateOnly(dateValue);
|
||||
const sessionIndex = SESSION_ORDER[session];
|
||||
|
||||
if (sessionIndex == null) {
|
||||
throw buildLeaveValidationError({ session: "invalid" }, 400);
|
||||
}
|
||||
|
||||
const dayIndex = Math.floor(date.getTime() / 86400000);
|
||||
return dayIndex * 2 + sessionIndex;
|
||||
}
|
||||
|
||||
function calculateRequestedDays({ startDate, endDate, startSession, endSession }) {
|
||||
const startSlot = toHalfDaySlot(startDate, startSession);
|
||||
const endSlot = toHalfDaySlot(endDate, endSession);
|
||||
|
||||
if (endSlot < startSlot) {
|
||||
throw buildLeaveValidationError({ leave: "invalid_range" });
|
||||
}
|
||||
|
||||
return fromHalfDayUnits(endSlot - startSlot + 1);
|
||||
}
|
||||
|
||||
function leaveRangesOverlap(left, right) {
|
||||
const leftStart = toHalfDaySlot(left.startDate, left.startSession);
|
||||
const leftEnd = toHalfDaySlot(left.endDate, left.endSession);
|
||||
const rightStart = toHalfDaySlot(right.startDate, right.startSession);
|
||||
const rightEnd = toHalfDaySlot(right.endDate, right.endSession);
|
||||
|
||||
return leftStart <= rightEnd && rightStart <= leftEnd;
|
||||
}
|
||||
|
||||
function normalizeAttachmentMimeTypes(value) {
|
||||
if (!Array.isArray(value)) {
|
||||
return [...DEFAULT_ATTACHMENT_MIME_TYPES];
|
||||
}
|
||||
|
||||
const items = value
|
||||
.map((item) => (typeof item === "string" ? item.trim() : ""))
|
||||
.filter(Boolean);
|
||||
|
||||
return items.length ? items : [...DEFAULT_ATTACHMENT_MIME_TYPES];
|
||||
}
|
||||
|
||||
function summarizeLeaveLedgerEntries(entries) {
|
||||
const totals = {
|
||||
grant: 0,
|
||||
reserve: 0,
|
||||
consume: 0,
|
||||
release: 0,
|
||||
adjust: 0,
|
||||
};
|
||||
|
||||
for (const entry of entries ?? []) {
|
||||
if (!entry?.entry_type || !(entry.entry_type in totals)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
totals[entry.entry_type] += toHalfDayUnits(entry.days);
|
||||
}
|
||||
|
||||
const reservedUnits = Math.max(0, totals.reserve - totals.release);
|
||||
const availableUnits =
|
||||
totals.grant + totals.adjust - totals.reserve + totals.release - totals.consume;
|
||||
|
||||
return {
|
||||
granted: fromHalfDayUnits(totals.grant),
|
||||
adjusted: fromHalfDayUnits(totals.adjust),
|
||||
reserved: fromHalfDayUnits(reservedUnits),
|
||||
used: fromHalfDayUnits(totals.consume),
|
||||
released: fromHalfDayUnits(totals.release),
|
||||
available: fromHalfDayUnits(availableUnits),
|
||||
};
|
||||
}
|
||||
|
||||
function currentLeavePeriod(referenceDate = new Date()) {
|
||||
const date = normalizeDateOnly(referenceDate);
|
||||
const year = date.getUTCFullYear();
|
||||
return {
|
||||
periodStart: new Date(`${year}-01-01T00:00:00.000Z`),
|
||||
periodEnd: new Date(`${year}-12-31T00:00:00.000Z`),
|
||||
};
|
||||
}
|
||||
|
||||
function mapLeaveTypeResponse(leaveType) {
|
||||
const policy = leaveType.leave_policy ?? null;
|
||||
|
||||
return {
|
||||
id: leaveType.id,
|
||||
code: leaveType.code,
|
||||
name: leaveType.name,
|
||||
description: leaveType.description ?? null,
|
||||
enabled: Boolean(leaveType.enabled),
|
||||
requiresAttachment: Boolean(leaveType.requires_attachment),
|
||||
attachmentMimeTypes: normalizeAttachmentMimeTypes(leaveType.attachment_mime_types),
|
||||
sortOrder: leaveType.sort_order,
|
||||
policy: policy
|
||||
? {
|
||||
id: policy.id,
|
||||
annualQuotaDays: Number(policy.annual_quota_days),
|
||||
enabled: Boolean(policy.enabled),
|
||||
description: policy.description ?? null,
|
||||
}
|
||||
: null,
|
||||
createdAt: leaveType.created_at?.toISOString?.() ?? null,
|
||||
updatedAt: leaveType.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function lockEmployeeForLeave(tx, employeeId) {
|
||||
await tx.$queryRaw`
|
||||
SELECT id
|
||||
FROM "employees"
|
||||
WHERE id = ${employeeId}::uuid
|
||||
FOR UPDATE
|
||||
`;
|
||||
}
|
||||
|
||||
async function ensureAnnualLeaveGrant(tx, { employeeId, leaveType, actorId, referenceDate = new Date() }) {
|
||||
const policy = leaveType?.leave_policy;
|
||||
if (!leaveType || !leaveType.enabled || !policy || !policy.enabled) {
|
||||
throw buildLeaveValidationError({ leaveTypeId: "missing_active_policy" }, 409);
|
||||
}
|
||||
|
||||
const { periodStart, periodEnd } = currentLeavePeriod(referenceDate);
|
||||
|
||||
const existingGrant = await tx.leaveLedger.findFirst({
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
leave_type_id: leaveType.id,
|
||||
entry_type: "grant",
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!existingGrant) {
|
||||
await tx.leaveLedger.create({
|
||||
data: {
|
||||
employee_id: employeeId,
|
||||
leave_type_id: leaveType.id,
|
||||
leave_policy_id: policy.id,
|
||||
entry_type: "grant",
|
||||
days: policy.annual_quota_days,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
note: `auto_grant_${periodStart.getUTCFullYear()}`,
|
||||
payload: {
|
||||
source: "leave_policy",
|
||||
annual_quota_days: Number(policy.annual_quota_days),
|
||||
},
|
||||
created_by: actorId ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return { policy, periodStart, periodEnd };
|
||||
}
|
||||
|
||||
async function loadLeaveBalanceSnapshot(tx, { employeeId, leaveType, actorId, referenceDate = new Date() }) {
|
||||
const { policy, periodStart, periodEnd } = await ensureAnnualLeaveGrant(tx, {
|
||||
employeeId,
|
||||
leaveType,
|
||||
actorId,
|
||||
referenceDate,
|
||||
});
|
||||
|
||||
const entries = await tx.leaveLedger.findMany({
|
||||
where: {
|
||||
employee_id: employeeId,
|
||||
leave_type_id: leaveType.id,
|
||||
period_start: periodStart,
|
||||
period_end: periodEnd,
|
||||
},
|
||||
orderBy: { created_at: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
entry_type: true,
|
||||
days: true,
|
||||
leave_request_id: true,
|
||||
created_at: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
policy,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
entries,
|
||||
summary: summarizeLeaveLedgerEntries(entries),
|
||||
};
|
||||
}
|
||||
|
||||
async function loadLeaveBalanceItems(tx, { employeeId, actorId, referenceDate = new Date(), includeDisabled = false }) {
|
||||
const leaveTypes = await tx.leaveType.findMany({
|
||||
where: includeDisabled ? undefined : { 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,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const items = [];
|
||||
for (const leaveType of leaveTypes) {
|
||||
if (!leaveType.leave_policy || !leaveType.leave_policy.enabled) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const snapshot = await loadLeaveBalanceSnapshot(tx, {
|
||||
employeeId,
|
||||
leaveType,
|
||||
actorId,
|
||||
referenceDate,
|
||||
});
|
||||
|
||||
items.push({
|
||||
leaveType: mapLeaveTypeResponse(leaveType),
|
||||
policy: {
|
||||
id: snapshot.policy.id,
|
||||
annualQuotaDays: Number(snapshot.policy.annual_quota_days),
|
||||
enabled: Boolean(snapshot.policy.enabled),
|
||||
description: snapshot.policy.description ?? null,
|
||||
},
|
||||
granted: snapshot.summary.granted,
|
||||
adjusted: snapshot.summary.adjusted,
|
||||
reserved: snapshot.summary.reserved,
|
||||
used: snapshot.summary.used,
|
||||
available: snapshot.summary.available,
|
||||
periodStart: formatDateOnly(snapshot.periodStart),
|
||||
periodEnd: formatDateOnly(snapshot.periodEnd),
|
||||
});
|
||||
}
|
||||
|
||||
return items;
|
||||
}
|
||||
|
||||
async function createLeaveLedgerEntry(tx, data) {
|
||||
return tx.leaveLedger.create({
|
||||
data: {
|
||||
employee_id: data.employeeId,
|
||||
leave_type_id: data.leaveTypeId,
|
||||
leave_policy_id: data.leavePolicyId ?? null,
|
||||
leave_request_id: data.leaveRequestId ?? null,
|
||||
entry_type: data.entryType,
|
||||
days: data.days,
|
||||
period_start: data.periodStart ?? null,
|
||||
period_end: data.periodEnd ?? null,
|
||||
note: data.note ?? null,
|
||||
payload: data.payload ?? null,
|
||||
created_by: data.createdBy ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function loadLeaveLedgerSummaryForRequest(tx, leaveRequestId) {
|
||||
const entries = await tx.leaveLedger.findMany({
|
||||
where: { leave_request_id: leaveRequestId },
|
||||
orderBy: { created_at: "asc" },
|
||||
select: {
|
||||
id: true,
|
||||
entry_type: true,
|
||||
days: true,
|
||||
period_start: true,
|
||||
period_end: true,
|
||||
leave_policy_id: true,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
entries,
|
||||
summary: summarizeLeaveLedgerEntries(entries),
|
||||
};
|
||||
}
|
||||
|
||||
async function releaseReservedLeave(tx, {
|
||||
leaveRequestId,
|
||||
employeeId,
|
||||
leaveTypeId,
|
||||
leavePolicyId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
note,
|
||||
payload,
|
||||
createdBy,
|
||||
}) {
|
||||
const ledger = await loadLeaveLedgerSummaryForRequest(tx, leaveRequestId);
|
||||
const reservedUnits = toHalfDayUnits(ledger.summary.reserved);
|
||||
|
||||
if (reservedUnits <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return createLeaveLedgerEntry(tx, {
|
||||
employeeId,
|
||||
leaveTypeId,
|
||||
leavePolicyId,
|
||||
leaveRequestId,
|
||||
entryType: "release",
|
||||
days: fromHalfDayUnits(reservedUnits),
|
||||
periodStart,
|
||||
periodEnd,
|
||||
note,
|
||||
payload,
|
||||
createdBy,
|
||||
});
|
||||
}
|
||||
|
||||
async function consumeReservedLeave(tx, {
|
||||
leaveRequestId,
|
||||
employeeId,
|
||||
leaveTypeId,
|
||||
leavePolicyId,
|
||||
periodStart,
|
||||
periodEnd,
|
||||
requestedDays,
|
||||
createdBy,
|
||||
}) {
|
||||
const ledger = await loadLeaveLedgerSummaryForRequest(tx, leaveRequestId);
|
||||
const reservedUnits = toHalfDayUnits(ledger.summary.reserved);
|
||||
const requestedUnits = toHalfDayUnits(requestedDays);
|
||||
|
||||
if (reservedUnits < requestedUnits || requestedUnits <= 0) {
|
||||
throw buildLeaveValidationError({ leave: "missing_reserve_ledger" }, 409);
|
||||
}
|
||||
|
||||
await createLeaveLedgerEntry(tx, {
|
||||
employeeId,
|
||||
leaveTypeId,
|
||||
leavePolicyId,
|
||||
leaveRequestId,
|
||||
entryType: "release",
|
||||
days: fromHalfDayUnits(requestedUnits),
|
||||
periodStart,
|
||||
periodEnd,
|
||||
note: "approved_release_reserve",
|
||||
payload: { source: "workflow_approve" },
|
||||
createdBy,
|
||||
});
|
||||
|
||||
await createLeaveLedgerEntry(tx, {
|
||||
employeeId,
|
||||
leaveTypeId,
|
||||
leavePolicyId,
|
||||
leaveRequestId,
|
||||
entryType: "consume",
|
||||
days: fromHalfDayUnits(requestedUnits),
|
||||
periodStart,
|
||||
periodEnd,
|
||||
note: "approved_consume_leave",
|
||||
payload: { source: "workflow_approve" },
|
||||
createdBy,
|
||||
});
|
||||
}
|
||||
|
||||
async function persistLeaveAttachment({ config, employeeId, filePart }) {
|
||||
const chunks = [];
|
||||
let fileSize = 0;
|
||||
|
||||
for await (const chunk of filePart.file) {
|
||||
fileSize += chunk.length;
|
||||
if (fileSize > config.maxUploadSizeBytes) {
|
||||
throw buildLeaveValidationError({ file: "file_too_large" }, 400);
|
||||
}
|
||||
chunks.push(chunk);
|
||||
}
|
||||
|
||||
if (fileSize <= 0) {
|
||||
throw buildLeaveValidationError({ file: "empty" }, 400);
|
||||
}
|
||||
|
||||
const buffer = Buffer.concat(chunks);
|
||||
const safeName = (filePart.filename || "attachment")
|
||||
.replace(/[^a-zA-Z0-9._-]+/g, "_")
|
||||
.replace(/^_+|_+$/g, "") || "attachment";
|
||||
const extension = path.extname(safeName);
|
||||
const basename = extension ? safeName.slice(0, -extension.length) : safeName;
|
||||
const key = path.posix.join(
|
||||
"leave-attachments",
|
||||
compactDateString(config.appTimezone),
|
||||
employeeId,
|
||||
`${basename}-${crypto.randomUUID()}${extension}`,
|
||||
);
|
||||
|
||||
const storagePath = await writeBuffer({
|
||||
config,
|
||||
key,
|
||||
buffer,
|
||||
contentType: filePart.mimetype,
|
||||
});
|
||||
|
||||
return {
|
||||
storagePath,
|
||||
originalName: filePart.filename || safeName,
|
||||
mimeType: filePart.mimetype,
|
||||
fileSize,
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
DEFAULT_ATTACHMENT_MIME_TYPES,
|
||||
calculateRequestedDays,
|
||||
createLeaveLedgerEntry,
|
||||
consumeReservedLeave,
|
||||
currentLeavePeriod,
|
||||
formatDateOnly,
|
||||
leaveRangesOverlap,
|
||||
loadLeaveBalanceItems,
|
||||
loadLeaveBalanceSnapshot,
|
||||
loadLeaveLedgerSummaryForRequest,
|
||||
lockEmployeeForLeave,
|
||||
mapLeaveTypeResponse,
|
||||
normalizeAttachmentMimeTypes,
|
||||
persistLeaveAttachment,
|
||||
releaseReservedLeave,
|
||||
summarizeLeaveLedgerEntries,
|
||||
toHalfDayUnits,
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
const {
|
||||
calculateRequestedDays,
|
||||
leaveRangesOverlap,
|
||||
summarizeLeaveLedgerEntries,
|
||||
} = require("../../../src/services/leave");
|
||||
|
||||
describe("Leave Service", () => {
|
||||
describe("calculateRequestedDays", () => {
|
||||
it("supports same-day half-day requests", () => {
|
||||
expect(
|
||||
calculateRequestedDays({
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-10",
|
||||
startSession: "am",
|
||||
endSession: "am",
|
||||
}),
|
||||
).toBe(0.5);
|
||||
|
||||
expect(
|
||||
calculateRequestedDays({
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-10",
|
||||
startSession: "pm",
|
||||
endSession: "pm",
|
||||
}),
|
||||
).toBe(0.5);
|
||||
});
|
||||
|
||||
it("supports cross-day half-day boundaries", () => {
|
||||
expect(
|
||||
calculateRequestedDays({
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-12",
|
||||
startSession: "pm",
|
||||
endSession: "am",
|
||||
}),
|
||||
).toBe(2);
|
||||
});
|
||||
|
||||
it("rejects invalid session ranges", () => {
|
||||
expect(() =>
|
||||
calculateRequestedDays({
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-10",
|
||||
startSession: "pm",
|
||||
endSession: "am",
|
||||
}),
|
||||
).toThrow(/参数校验失败/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("leaveRangesOverlap", () => {
|
||||
it("detects overlapping half-day ranges", () => {
|
||||
expect(
|
||||
leaveRangesOverlap(
|
||||
{
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-11",
|
||||
startSession: "pm",
|
||||
endSession: "pm",
|
||||
},
|
||||
{
|
||||
startDate: "2026-03-11",
|
||||
endDate: "2026-03-12",
|
||||
startSession: "am",
|
||||
endSession: "am",
|
||||
},
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag non-overlapping adjacent ranges", () => {
|
||||
expect(
|
||||
leaveRangesOverlap(
|
||||
{
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-10",
|
||||
startSession: "am",
|
||||
endSession: "am",
|
||||
},
|
||||
{
|
||||
startDate: "2026-03-10",
|
||||
endDate: "2026-03-10",
|
||||
startSession: "pm",
|
||||
endSession: "pm",
|
||||
},
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("summarizeLeaveLedgerEntries", () => {
|
||||
it("calculates reserve / consume / release balances correctly", () => {
|
||||
const summary = summarizeLeaveLedgerEntries([
|
||||
{ entry_type: "grant", days: 10 },
|
||||
{ entry_type: "reserve", days: 2.5 },
|
||||
{ entry_type: "release", days: 1 },
|
||||
{ entry_type: "consume", days: 1.5 },
|
||||
]);
|
||||
|
||||
expect(summary.granted).toBe(10);
|
||||
expect(summary.reserved).toBe(1.5);
|
||||
expect(summary.used).toBe(1.5);
|
||||
expect(summary.available).toBe(7);
|
||||
});
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户