R46 A1-A7:落地绩效考核模块首版
这个提交包含在:
@@ -250,6 +250,22 @@ export type EmployeeStatsResponse = {
|
|||||||
validHolderCount: number;
|
validHolderCount: number;
|
||||||
expiringSoonCount: number;
|
expiringSoonCount: number;
|
||||||
};
|
};
|
||||||
|
performanceSummary: {
|
||||||
|
cycle: {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
cycleType: "monthly" | "quarterly" | "semi_annual" | "annual";
|
||||||
|
status: "draft" | "active" | "completed";
|
||||||
|
startDate: string | null;
|
||||||
|
endDate: string | null;
|
||||||
|
} | null;
|
||||||
|
averageScore: number | null;
|
||||||
|
reviewedCount: number;
|
||||||
|
distribution: Array<{
|
||||||
|
score: number;
|
||||||
|
count: number;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export type BatchTransferDepartmentPayload = {
|
export type BatchTransferDepartmentPayload = {
|
||||||
|
|||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import { apiRequestData } from "./http";
|
||||||
|
import type { EmployeeDepartmentSummary, EmployeeStatus } from "./employees";
|
||||||
|
|
||||||
|
export type PerformanceReviewCycleType = "monthly" | "quarterly" | "semi_annual" | "annual";
|
||||||
|
export type PerformanceReviewCycleStatus = "draft" | "active" | "completed";
|
||||||
|
export type PerformanceReviewDimensionType =
|
||||||
|
| "work_quality"
|
||||||
|
| "work_efficiency"
|
||||||
|
| "teamwork"
|
||||||
|
| "initiative"
|
||||||
|
| "professional_skill";
|
||||||
|
|
||||||
|
export type PerformanceEmployeeSummary = {
|
||||||
|
id: string;
|
||||||
|
employeeNo: string;
|
||||||
|
name: string;
|
||||||
|
title: string;
|
||||||
|
status: EmployeeStatus;
|
||||||
|
avatarUrl: string | null;
|
||||||
|
department: EmployeeDepartmentSummary | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PerformanceReviewCycle = {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
cycleType: PerformanceReviewCycleType;
|
||||||
|
status: PerformanceReviewCycleStatus;
|
||||||
|
startDate: string | null;
|
||||||
|
endDate: string | null;
|
||||||
|
activatedAt: string | null;
|
||||||
|
completedAt: string | null;
|
||||||
|
createdAt: string | null;
|
||||||
|
createdBy: string | null;
|
||||||
|
updatedAt: string | null;
|
||||||
|
updatedBy: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PerformanceReviewDimension = {
|
||||||
|
dimensionType: PerformanceReviewDimensionType;
|
||||||
|
score: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PerformanceReview = {
|
||||||
|
id: string;
|
||||||
|
cycleId: string;
|
||||||
|
employeeId: string;
|
||||||
|
reviewerEmployeeId: string;
|
||||||
|
overallScore: number;
|
||||||
|
comment: string | null;
|
||||||
|
reviewer: {
|
||||||
|
id: string;
|
||||||
|
employeeNo: string;
|
||||||
|
name: string;
|
||||||
|
} | null;
|
||||||
|
dimensions: PerformanceReviewDimension[];
|
||||||
|
createdAt: string | null;
|
||||||
|
createdBy: string | null;
|
||||||
|
updatedAt: string | null;
|
||||||
|
updatedBy: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PerformanceCycleOverview = {
|
||||||
|
cycle: PerformanceReviewCycle;
|
||||||
|
items: Array<{
|
||||||
|
employee: PerformanceEmployeeSummary;
|
||||||
|
review: PerformanceReview | null;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PerformanceEmployeeReviewTimeline = {
|
||||||
|
employee: PerformanceEmployeeSummary;
|
||||||
|
viewerRole: "self" | "manager" | "admin";
|
||||||
|
items: Array<{
|
||||||
|
cycle: PerformanceReviewCycle;
|
||||||
|
review: PerformanceReview | null;
|
||||||
|
canEdit: boolean;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CreatePerformanceCyclePayload = {
|
||||||
|
name: string;
|
||||||
|
cycleType: PerformanceReviewCycleType;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PatchPerformanceCyclePayload = Partial<CreatePerformanceCyclePayload> & {
|
||||||
|
status?: PerformanceReviewCycleStatus;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type UpsertPerformanceReviewPayload = {
|
||||||
|
overallScore: number;
|
||||||
|
comment?: string | null;
|
||||||
|
dimensions?: PerformanceReviewDimension[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function fetchPerformanceCycles() {
|
||||||
|
return apiRequestData<{ items: PerformanceReviewCycle[] }>("/api/performance/cycles");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createPerformanceCycle(payload: CreatePerformanceCyclePayload) {
|
||||||
|
return apiRequestData<PerformanceReviewCycle>("/api/performance/cycles", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function patchPerformanceCycle(cycleId: string, payload: PatchPerformanceCyclePayload) {
|
||||||
|
return apiRequestData<PerformanceReviewCycle>(`/api/performance/cycles/${cycleId}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchPerformanceCycleOverview(cycleId: string) {
|
||||||
|
return apiRequestData<PerformanceCycleOverview>(`/api/performance/cycles/${cycleId}/reviews`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchEmployeePerformanceTimeline(employeeId: string) {
|
||||||
|
return apiRequestData<PerformanceEmployeeReviewTimeline>(`/api/performance/employees/${employeeId}/reviews`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function upsertPerformanceReview(cycleId: string, employeeId: string, payload: UpsertPerformanceReviewPayload) {
|
||||||
|
return apiRequestData<PerformanceReview>(`/api/performance/cycles/${cycleId}/reviews/${employeeId}`, {
|
||||||
|
method: "PUT",
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
upsertPerformanceReview,
|
||||||
|
type PerformanceEmployeeReviewTimeline,
|
||||||
|
type PerformanceReviewDimensionType,
|
||||||
|
} from "../../api/performance";
|
||||||
|
import { mapApiErrorMessage } from "../../api/errorMessages";
|
||||||
|
import { isApiError } from "../../api/types";
|
||||||
|
import { StatusBadge } from "../common/StatusBadge";
|
||||||
|
import { Button } from "../ui/button";
|
||||||
|
import { Input } from "../ui/input";
|
||||||
|
import { Textarea } from "../ui/textarea";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
type PerformanceFormState = {
|
||||||
|
overallScore: string;
|
||||||
|
comment: string;
|
||||||
|
dimensions: Record<PerformanceReviewDimensionType, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
type EmployeePerformancePanelProps = {
|
||||||
|
employeeId: string;
|
||||||
|
timeline: PerformanceEmployeeReviewTimeline;
|
||||||
|
invalidateKeys?: Array<readonly unknown[]>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const DIMENSION_OPTIONS: Array<{ value: PerformanceReviewDimensionType; label: string }> = [
|
||||||
|
{ value: "work_quality", label: "工作质量" },
|
||||||
|
{ value: "work_efficiency", label: "工作效率" },
|
||||||
|
{ value: "teamwork", label: "团队协作" },
|
||||||
|
{ value: "initiative", label: "主动性" },
|
||||||
|
{ value: "professional_skill", label: "专业能力" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function buildEmptyDimensions(): Record<PerformanceReviewDimensionType, string> {
|
||||||
|
return {
|
||||||
|
work_quality: "",
|
||||||
|
work_efficiency: "",
|
||||||
|
teamwork: "",
|
||||||
|
initiative: "",
|
||||||
|
professional_skill: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFormState(review: PerformanceEmployeeReviewTimeline["items"][number]["review"]): PerformanceFormState {
|
||||||
|
const dimensions = buildEmptyDimensions();
|
||||||
|
for (const item of review?.dimensions ?? []) {
|
||||||
|
dimensions[item.dimensionType] = String(item.score);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
overallScore: review ? String(review.overallScore) : "",
|
||||||
|
comment: review?.comment ?? "",
|
||||||
|
dimensions,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(error: unknown, fallback: string) {
|
||||||
|
if (isApiError(error)) {
|
||||||
|
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
|
||||||
|
}
|
||||||
|
return error instanceof Error ? error.message : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cycleStatusLabel(status: string) {
|
||||||
|
return status === "active" ? "进行中" : status === "completed" ? "已完成" : "草稿";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmployeePerformancePanel({ employeeId, timeline, invalidateKeys = [] }: EmployeePerformancePanelProps) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [selectedCycleId, setSelectedCycleId] = useState<string>(timeline.items[0]?.cycle.id ?? "");
|
||||||
|
const selectedItem = timeline.items.find((item) => item.cycle.id === selectedCycleId) ?? timeline.items[0] ?? null;
|
||||||
|
const [form, setForm] = useState<PerformanceFormState>(buildFormState(selectedItem?.review ?? null));
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!timeline.items.length) {
|
||||||
|
setSelectedCycleId("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!timeline.items.some((item) => item.cycle.id === selectedCycleId)) {
|
||||||
|
setSelectedCycleId(timeline.items[0].cycle.id);
|
||||||
|
}
|
||||||
|
}, [selectedCycleId, timeline.items]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setForm(buildFormState(selectedItem?.review ?? null));
|
||||||
|
}, [selectedItem?.cycle.id, selectedItem?.review?.updatedAt]);
|
||||||
|
|
||||||
|
const saveMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
if (!selectedItem) {
|
||||||
|
throw new Error("未选中考核周期");
|
||||||
|
}
|
||||||
|
|
||||||
|
return upsertPerformanceReview(selectedItem.cycle.id, employeeId, {
|
||||||
|
overallScore: Number(form.overallScore),
|
||||||
|
comment: form.comment.trim() ? form.comment.trim() : null,
|
||||||
|
dimensions: DIMENSION_OPTIONS.flatMap((item) => {
|
||||||
|
const raw = form.dimensions[item.value].trim();
|
||||||
|
return raw
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
dimensionType: item.value,
|
||||||
|
score: Number(raw),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
},
|
||||||
|
onSuccess: async () => {
|
||||||
|
await Promise.all(
|
||||||
|
invalidateKeys.map((queryKey) =>
|
||||||
|
queryClient.invalidateQueries({
|
||||||
|
queryKey: [...queryKey],
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
toast.success("绩效评分已保存");
|
||||||
|
},
|
||||||
|
onError: (error) => toast.error(errorMessage(error, "保存绩效评分失败")),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!timeline.items.length) {
|
||||||
|
return <div className="card-std p-6 text-sm text-zinc-500">暂无可展示的绩效记录。</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="grid gap-6 xl:grid-cols-[0.95fr,1.05fr]">
|
||||||
|
<section className="card-std p-6">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-semibold text-zinc-900">考核周期</h3>
|
||||||
|
<p className="mt-1 text-sm text-zinc-500">
|
||||||
|
{timeline.viewerRole === "self" ? "仅展示已完成且本人可见的结果。" : "可查看历史周期,并在进行中周期填写或修改评分。"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-zinc-500">{timeline.items.length} 个周期</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-3">
|
||||||
|
{timeline.items.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.cycle.id}
|
||||||
|
type="button"
|
||||||
|
className={`w-full rounded-2xl border px-4 py-3 text-left transition ${
|
||||||
|
item.cycle.id === selectedItem?.cycle.id ? "border-zinc-900 bg-zinc-50" : "border-zinc-200 hover:border-zinc-300"
|
||||||
|
}`}
|
||||||
|
onClick={() => setSelectedCycleId(item.cycle.id)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="text-sm font-semibold text-zinc-900">{item.cycle.name}</div>
|
||||||
|
<div className="mt-1 text-xs text-zinc-500">
|
||||||
|
{item.cycle.startDate ?? "-"} 至 {item.cycle.endDate ?? "-"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<StatusBadge status={item.cycle.status} label={cycleStatusLabel(item.cycle.status)} />
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex items-center justify-between gap-3 text-sm">
|
||||||
|
<span className="text-zinc-500">{item.review ? "已评分" : item.canEdit ? "待评分" : "暂无评分"}</span>
|
||||||
|
<span className="font-medium text-zinc-900">{item.review ? `${item.review.overallScore.toFixed(1)} 分` : "-"}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{selectedItem ? (
|
||||||
|
<section className="card-std space-y-5 p-6">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-semibold text-zinc-900">{selectedItem.cycle.name}</h3>
|
||||||
|
<p className="mt-1 text-sm text-zinc-500">
|
||||||
|
{selectedItem.cycle.startDate ?? "-"} 至 {selectedItem.cycle.endDate ?? "-"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<StatusBadge status={selectedItem.cycle.status} label={cycleStatusLabel(selectedItem.cycle.status)} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedItem.canEdit ? (
|
||||||
|
<>
|
||||||
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">总分</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="5"
|
||||||
|
step="0.5"
|
||||||
|
value={form.overallScore}
|
||||||
|
onChange={(event) => setForm((prev) => ({ ...prev, overallScore: event.target.value }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">评语</label>
|
||||||
|
<Textarea
|
||||||
|
value={form.comment}
|
||||||
|
onChange={(event) => setForm((prev) => ({ ...prev, comment: event.target.value }))}
|
||||||
|
placeholder="填写绩效反馈"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
|
{DIMENSION_OPTIONS.map((item) => (
|
||||||
|
<div key={item.value} className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">{item.label}</label>
|
||||||
|
<Input
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="5"
|
||||||
|
step="0.5"
|
||||||
|
placeholder="留空则不记录"
|
||||||
|
value={form.dimensions[item.value]}
|
||||||
|
onChange={(event) =>
|
||||||
|
setForm((prev) => ({
|
||||||
|
...prev,
|
||||||
|
dimensions: {
|
||||||
|
...prev.dimensions,
|
||||||
|
[item.value]: event.target.value,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => saveMutation.mutate()}
|
||||||
|
disabled={saveMutation.isPending || !form.overallScore.trim()}
|
||||||
|
>
|
||||||
|
{saveMutation.isPending ? "保存中..." : selectedItem.review ? "保存修改" : "提交评分"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : selectedItem.review ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
|
<div className="rounded-2xl border border-zinc-200 px-4 py-3">
|
||||||
|
<div className="text-sm text-zinc-500">总分</div>
|
||||||
|
<div className="mt-2 text-2xl font-semibold text-zinc-900">{selectedItem.review.overallScore.toFixed(1)}</div>
|
||||||
|
</div>
|
||||||
|
<div className="rounded-2xl border border-zinc-200 px-4 py-3">
|
||||||
|
<div className="text-sm text-zinc-500">评分人</div>
|
||||||
|
<div className="mt-2 text-sm font-medium text-zinc-900">
|
||||||
|
{selectedItem.review.reviewer?.name ?? "-"}
|
||||||
|
</div>
|
||||||
|
<div className="mt-1 text-xs text-zinc-500">{selectedItem.review.updatedAt ?? selectedItem.review.createdAt ?? "-"}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-zinc-200 px-4 py-3">
|
||||||
|
<div className="text-sm text-zinc-500">评语</div>
|
||||||
|
<div className="mt-2 whitespace-pre-wrap text-sm text-zinc-900">{selectedItem.review.comment ?? "-"}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-zinc-200 px-4 py-3">
|
||||||
|
<div className="text-sm text-zinc-500">考核维度</div>
|
||||||
|
<div className="mt-3 grid gap-3 md:grid-cols-2">
|
||||||
|
{selectedItem.review.dimensions.length ? (
|
||||||
|
selectedItem.review.dimensions.map((item) => (
|
||||||
|
<div key={item.dimensionType} className="flex items-center justify-between rounded-xl bg-zinc-50 px-3 py-2 text-sm">
|
||||||
|
<span className="text-zinc-700">
|
||||||
|
{DIMENSION_OPTIONS.find((option) => option.value === item.dimensionType)?.label ?? item.dimensionType}
|
||||||
|
</span>
|
||||||
|
<span className="font-semibold text-zinc-900">{item.score.toFixed(1)}</span>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-sm text-zinc-500">未记录维度明细。</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="rounded-2xl border border-dashed border-zinc-300 px-4 py-6 text-sm text-zinc-500">
|
||||||
|
当前周期尚未生成评分记录。
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default EmployeePerformancePanel;
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { useParams } from "react-router-dom";
|
import { Link, useParams, useSearchParams } from "react-router-dom";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import {
|
import {
|
||||||
completeEmployeeChecklistTask,
|
completeEmployeeChecklistTask,
|
||||||
@@ -30,10 +30,12 @@ import {
|
|||||||
type EmployeeTrainingStatus,
|
type EmployeeTrainingStatus,
|
||||||
type EmployeeTrainingType,
|
type EmployeeTrainingType,
|
||||||
} from "../api/employees";
|
} from "../api/employees";
|
||||||
|
import { fetchEmployeePerformanceTimeline } from "../api/performance";
|
||||||
import { useAuth } from "../auth/AuthContext";
|
import { useAuth } from "../auth/AuthContext";
|
||||||
import { hasPermission } from "../auth/permissions";
|
import { hasPermission } from "../auth/permissions";
|
||||||
import { EmployeeAvatar } from "../components/common/EmployeeAvatar";
|
import { EmployeeAvatar } from "../components/common/EmployeeAvatar";
|
||||||
import { PageHeader } from "../components/common/PageHeader";
|
import { PageHeader } from "../components/common/PageHeader";
|
||||||
|
import { EmployeePerformancePanel } from "../components/people/EmployeePerformancePanel";
|
||||||
import { StatusBadge } from "../components/common/StatusBadge";
|
import { StatusBadge } from "../components/common/StatusBadge";
|
||||||
import { Button } from "../components/ui/button";
|
import { Button } from "../components/ui/button";
|
||||||
import { Input } from "../components/ui/input";
|
import { Input } from "../components/ui/input";
|
||||||
@@ -45,7 +47,7 @@ import { mapApiErrorMessage } from "../api/errorMessages";
|
|||||||
import { isApiError } from "../api/types";
|
import { isApiError } from "../api/types";
|
||||||
import { downloadBlob } from "../lib/download";
|
import { downloadBlob } from "../lib/download";
|
||||||
|
|
||||||
type ProfileTab = "profile" | "contracts" | "trainingCertificates";
|
type ProfileTab = "profile" | "contracts" | "trainingCertificates" | "performance";
|
||||||
|
|
||||||
type ContractFormState = {
|
type ContractFormState = {
|
||||||
contractNo: string;
|
contractNo: string;
|
||||||
@@ -119,6 +121,13 @@ function buildEmptyCertificateForm(): CertificateFormState {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseProfileTab(value: string | null): ProfileTab {
|
||||||
|
if (value === "contracts" || value === "trainingCertificates" || value === "performance") {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
return "profile";
|
||||||
|
}
|
||||||
|
|
||||||
function contractTypeLabel(type: EmployeeContractType) {
|
function contractTypeLabel(type: EmployeeContractType) {
|
||||||
return CONTRACT_TYPE_OPTIONS.find((item) => item.value === type)?.label ?? type;
|
return CONTRACT_TYPE_OPTIONS.find((item) => item.value === type)?.label ?? type;
|
||||||
}
|
}
|
||||||
@@ -142,8 +151,10 @@ function trainingTypeLabel(type: EmployeeTrainingType) {
|
|||||||
|
|
||||||
export function EmployeeProfilePage() {
|
export function EmployeeProfilePage() {
|
||||||
const { employeeId = "" } = useParams();
|
const { employeeId = "" } = useParams();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
const { permissions, me } = useAuth();
|
const { permissions, me } = useAuth();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
|
const requestedTab = parseProfileTab(searchParams.get("tab"));
|
||||||
const profileQuery = useQuery({
|
const profileQuery = useQuery({
|
||||||
enabled: Boolean(employeeId),
|
enabled: Boolean(employeeId),
|
||||||
queryKey: ["employee-profile", employeeId],
|
queryKey: ["employee-profile", employeeId],
|
||||||
@@ -154,7 +165,7 @@ export function EmployeeProfilePage() {
|
|||||||
const canEditBaseFields = canManageEmployeeProfile || canEditSelfProfile;
|
const canEditBaseFields = canManageEmployeeProfile || canEditSelfProfile;
|
||||||
const canEditExtendedFields = canManageEmployeeProfile;
|
const canEditExtendedFields = canManageEmployeeProfile;
|
||||||
const canUploadAvatar = canManageEmployeeProfile || canEditSelfProfile;
|
const canUploadAvatar = canManageEmployeeProfile || canEditSelfProfile;
|
||||||
const [activeTab, setActiveTab] = useState<ProfileTab>("profile");
|
const [activeTab, setActiveTab] = useState<ProfileTab>(requestedTab);
|
||||||
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
const [avatarFile, setAvatarFile] = useState<File | null>(null);
|
||||||
const [avatarInputKey, setAvatarInputKey] = useState(0);
|
const [avatarInputKey, setAvatarInputKey] = useState(0);
|
||||||
const [editingContractId, setEditingContractId] = useState<string | null>(null);
|
const [editingContractId, setEditingContractId] = useState<string | null>(null);
|
||||||
@@ -192,6 +203,22 @@ export function EmployeeProfilePage() {
|
|||||||
queryKey: ["employee-certificates", employeeId],
|
queryKey: ["employee-certificates", employeeId],
|
||||||
queryFn: () => fetchEmployeeCertificates(employeeId),
|
queryFn: () => fetchEmployeeCertificates(employeeId),
|
||||||
});
|
});
|
||||||
|
const performanceQuery = useQuery({
|
||||||
|
enabled: Boolean(employeeId) && activeTab === "performance",
|
||||||
|
queryKey: ["employee-performance", employeeId],
|
||||||
|
queryFn: () => fetchEmployeePerformanceTimeline(employeeId),
|
||||||
|
});
|
||||||
|
|
||||||
|
function updateActiveTab(nextTab: ProfileTab) {
|
||||||
|
setActiveTab(nextTab);
|
||||||
|
const nextSearchParams = new URLSearchParams(searchParams);
|
||||||
|
if (nextTab === "profile") {
|
||||||
|
nextSearchParams.delete("tab");
|
||||||
|
} else {
|
||||||
|
nextSearchParams.set("tab", nextTab);
|
||||||
|
}
|
||||||
|
setSearchParams(nextSearchParams, { replace: true });
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!profileQuery.data) {
|
if (!profileQuery.data) {
|
||||||
@@ -210,11 +237,15 @@ export function EmployeeProfilePage() {
|
|||||||
}, [profileQuery.data]);
|
}, [profileQuery.data]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (canManageEmployeeProfile || activeTab === "profile") {
|
setActiveTab(requestedTab);
|
||||||
|
}, [employeeId, requestedTab]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (canManageEmployeeProfile || canEditSelfProfile || activeTab === "profile" || activeTab === "performance") {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setActiveTab("profile");
|
updateActiveTab("profile");
|
||||||
}, [activeTab, canManageEmployeeProfile]);
|
}, [activeTab, canEditSelfProfile, canManageEmployeeProfile]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setAvatarFile(null);
|
setAvatarFile(null);
|
||||||
@@ -227,6 +258,7 @@ export function EmployeeProfilePage() {
|
|||||||
setTrainingForm(buildEmptyTrainingForm());
|
setTrainingForm(buildEmptyTrainingForm());
|
||||||
setEditingCertificateId(null);
|
setEditingCertificateId(null);
|
||||||
setCertificateForm(buildEmptyCertificateForm());
|
setCertificateForm(buildEmptyCertificateForm());
|
||||||
|
setActiveTab(requestedTab);
|
||||||
}, [employeeId]);
|
}, [employeeId]);
|
||||||
|
|
||||||
const saveMutation = useMutation({
|
const saveMutation = useMutation({
|
||||||
@@ -445,10 +477,76 @@ export function EmployeeProfilePage() {
|
|||||||
onError: (error) => toast.error(errorMessage(error, editingCertificateId ? "更新证书记录失败" : "新增证书记录失败")),
|
onError: (error) => toast.error(errorMessage(error, editingCertificateId ? "更新证书记录失败" : "新增证书记录失败")),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (profileQuery.isLoading) {
|
const profilePermissionDenied =
|
||||||
|
profileQuery.isError && isApiError(profileQuery.error) && profileQuery.error.status === 403;
|
||||||
|
const performanceOnlyMode = activeTab === "performance" && profilePermissionDenied && Boolean(performanceQuery.data);
|
||||||
|
const showPerformanceTab =
|
||||||
|
canManageEmployeeProfile || canEditSelfProfile || performanceOnlyMode || performanceQuery.data?.viewerRole === "manager";
|
||||||
|
|
||||||
|
const performanceContent =
|
||||||
|
performanceQuery.isLoading ? (
|
||||||
|
<div className="card-std p-6 text-sm text-zinc-500">加载绩效记录中...</div>
|
||||||
|
) : performanceQuery.isError || !performanceQuery.data ? (
|
||||||
|
<div className="card-std p-6 text-sm text-red-600">{errorMessage(performanceQuery.error, "加载绩效记录失败")}</div>
|
||||||
|
) : (
|
||||||
|
<EmployeePerformancePanel
|
||||||
|
employeeId={employeeId}
|
||||||
|
timeline={performanceQuery.data}
|
||||||
|
invalidateKeys={[
|
||||||
|
["employee-performance", employeeId],
|
||||||
|
["employee-stats"],
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
if (profileQuery.isLoading || (activeTab === "performance" && profilePermissionDenied && performanceQuery.isLoading)) {
|
||||||
return <div className="card-std p-6 text-sm text-zinc-500">加载员工档案中...</div>;
|
return <div className="card-std p-6 text-sm text-zinc-500">加载员工档案中...</div>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (performanceOnlyMode && performanceQuery.data) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<PageHeader
|
||||||
|
title={`${performanceQuery.data.employee.name} 绩效`}
|
||||||
|
subtitle={`${performanceQuery.data.employee.employeeNo} · ${performanceQuery.data.employee.title}`}
|
||||||
|
actions={
|
||||||
|
<Button asChild variant="secondary" type="button">
|
||||||
|
<Link to="/people">返回人员管理</Link>
|
||||||
|
</Button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="card-std p-6">
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<EmployeeAvatar
|
||||||
|
name={performanceQuery.data.employee.name}
|
||||||
|
src={performanceQuery.data.employee.avatarUrl}
|
||||||
|
size="xl"
|
||||||
|
/>
|
||||||
|
<div>
|
||||||
|
<div className="text-xl font-semibold text-zinc-900">{performanceQuery.data.employee.name}</div>
|
||||||
|
<div className="mt-1 text-sm text-zinc-500">
|
||||||
|
{performanceQuery.data.employee.employeeNo} · {performanceQuery.data.employee.department?.name ?? "-"}
|
||||||
|
</div>
|
||||||
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
<StatusBadge status={performanceQuery.data.employee.status} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Tabs value="performance" onValueChange={() => {}}>
|
||||||
|
<TabsList className="flex w-full flex-wrap justify-start gap-1">
|
||||||
|
<TabsTrigger value="performance">绩效</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent value="performance" className="space-y-6">
|
||||||
|
{performanceContent}
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (profileQuery.isError || !profileQuery.data) {
|
if (profileQuery.isError || !profileQuery.data) {
|
||||||
return <div className="card-std p-6 text-sm text-red-600">{errorMessage(profileQuery.error, "加载员工档案失败")}</div>;
|
return <div className="card-std p-6 text-sm text-red-600">{errorMessage(profileQuery.error, "加载员工档案失败")}</div>;
|
||||||
}
|
}
|
||||||
@@ -582,11 +680,12 @@ export function EmployeeProfilePage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as ProfileTab)}>
|
<Tabs value={activeTab} onValueChange={(value) => updateActiveTab(value as ProfileTab)}>
|
||||||
<TabsList className="flex w-full flex-wrap justify-start gap-1">
|
<TabsList className="flex w-full flex-wrap justify-start gap-1">
|
||||||
<TabsTrigger value="profile">档案</TabsTrigger>
|
<TabsTrigger value="profile">档案</TabsTrigger>
|
||||||
{canManageEmployeeProfile ? <TabsTrigger value="contracts">合同</TabsTrigger> : null}
|
{canManageEmployeeProfile ? <TabsTrigger value="contracts">合同</TabsTrigger> : null}
|
||||||
{canManageEmployeeProfile ? <TabsTrigger value="trainingCertificates">培训与证书</TabsTrigger> : null}
|
{canManageEmployeeProfile ? <TabsTrigger value="trainingCertificates">培训与证书</TabsTrigger> : null}
|
||||||
|
{showPerformanceTab ? <TabsTrigger value="performance">绩效</TabsTrigger> : null}
|
||||||
</TabsList>
|
</TabsList>
|
||||||
|
|
||||||
<TabsContent value="profile" className="space-y-6">
|
<TabsContent value="profile" className="space-y-6">
|
||||||
@@ -786,7 +885,14 @@ export function EmployeeProfilePage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<StatusBadge status={item.status} />
|
<div className="flex items-center gap-2">
|
||||||
|
{(canManageEmployeeProfile || canEditSelfProfile) && item.status === "active" ? (
|
||||||
|
<Button asChild type="button" size="sm" variant="secondary">
|
||||||
|
<Link to={`/people/${item.id}?tab=performance`}>绩效</Link>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
<StatusBadge status={item.status} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))
|
))
|
||||||
@@ -1308,6 +1414,12 @@ export function EmployeeProfilePage() {
|
|||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
{showPerformanceTab ? (
|
||||||
|
<TabsContent value="performance" className="space-y-6">
|
||||||
|
{performanceContent}
|
||||||
|
</TabsContent>
|
||||||
|
) : null}
|
||||||
</Tabs>
|
</Tabs>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -292,6 +292,11 @@ export function PeoplePage() {
|
|||||||
subtitle="按当前员工档案与账号状态做筛选、批量处理和统计查看。"
|
subtitle="按当前员工档案与账号状态做筛选、批量处理和统计查看。"
|
||||||
actions={
|
actions={
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{canManageUsers ? (
|
||||||
|
<Button asChild variant="secondary" type="button">
|
||||||
|
<Link to="/performance">绩效考核</Link>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
{canViewStats ? (
|
{canViewStats ? (
|
||||||
<Button asChild variant="secondary" type="button">
|
<Button asChild variant="secondary" type="button">
|
||||||
<Link to="/people/stats">员工统计</Link>
|
<Link to="/people/stats">员工统计</Link>
|
||||||
|
|||||||
@@ -83,6 +83,22 @@ export function PeopleStatsPage() {
|
|||||||
{stats.certificateSummary.dateFrom} 至 {stats.certificateSummary.dateTo}
|
{stats.certificateSummary.dateFrom} 至 {stats.certificateSummary.dateTo}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
<section className="card-std p-5">
|
||||||
|
<div className="text-sm text-zinc-500">当前 / 最近周期平均分</div>
|
||||||
|
<div className="mt-2 text-3xl font-semibold text-zinc-900">
|
||||||
|
{stats.performanceSummary.averageScore == null ? "-" : stats.performanceSummary.averageScore.toFixed(1)}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-xs text-zinc-500">
|
||||||
|
{stats.performanceSummary.cycle
|
||||||
|
? `${stats.performanceSummary.cycle.name} · ${stats.performanceSummary.cycle.startDate} 至 ${stats.performanceSummary.cycle.endDate}`
|
||||||
|
: "暂无可展示的绩效周期"}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="card-std p-5">
|
||||||
|
<div className="text-sm text-zinc-500">当前 / 最近周期已评分人数</div>
|
||||||
|
<div className="mt-2 text-3xl font-semibold text-zinc-900">{stats.performanceSummary.reviewedCount}</div>
|
||||||
|
<div className="mt-2 text-xs text-zinc-500">只统计当前 active 或最近 completed 周期</div>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
|
<div className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
|
||||||
@@ -126,6 +142,25 @@ export function PeopleStatsPage() {
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<section className="card-std p-6">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold text-zinc-900">绩效评分分布</h2>
|
||||||
|
<p className="mt-1 text-sm text-zinc-500">按当前 active 周期或最近 completed 周期的总分分布汇总。</p>
|
||||||
|
</div>
|
||||||
|
<div className="mt-6 grid gap-3 md:grid-cols-3 xl:grid-cols-5">
|
||||||
|
{stats.performanceSummary.cycle && stats.performanceSummary.distribution.length ? (
|
||||||
|
stats.performanceSummary.distribution.map((item) => (
|
||||||
|
<div key={item.score} className="rounded-2xl border border-zinc-200 bg-white px-4 py-3">
|
||||||
|
<div className="text-sm text-zinc-500">{item.score.toFixed(1)} 分</div>
|
||||||
|
<div className="mt-2 text-2xl font-semibold text-zinc-900">{item.count}</div>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<div className="text-sm text-zinc-500">暂无绩效周期统计。</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,409 @@
|
|||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { Link } from "react-router-dom";
|
||||||
|
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
createPerformanceCycle,
|
||||||
|
fetchPerformanceCycleOverview,
|
||||||
|
fetchPerformanceCycles,
|
||||||
|
patchPerformanceCycle,
|
||||||
|
type PerformanceReviewCycleType,
|
||||||
|
} from "../api/performance";
|
||||||
|
import { mapApiErrorMessage } from "../api/errorMessages";
|
||||||
|
import { isApiError } from "../api/types";
|
||||||
|
import { PageHeader } from "../components/common/PageHeader";
|
||||||
|
import { StatusBadge } from "../components/common/StatusBadge";
|
||||||
|
import { Button } from "../components/ui/button";
|
||||||
|
import {
|
||||||
|
Dialog,
|
||||||
|
DialogContent,
|
||||||
|
DialogFooter,
|
||||||
|
DialogHeader,
|
||||||
|
DialogTitle,
|
||||||
|
} from "../components/ui/dialog";
|
||||||
|
import { Input } from "../components/ui/input";
|
||||||
|
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
|
type CycleFormState = {
|
||||||
|
name: string;
|
||||||
|
cycleType: PerformanceReviewCycleType;
|
||||||
|
startDate: string;
|
||||||
|
endDate: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const CYCLE_TYPE_OPTIONS: Array<{ value: PerformanceReviewCycleType; label: string }> = [
|
||||||
|
{ value: "monthly", label: "月度" },
|
||||||
|
{ value: "quarterly", label: "季度" },
|
||||||
|
{ value: "semi_annual", label: "半年度" },
|
||||||
|
{ value: "annual", label: "年度" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function buildEmptyCycleForm(): CycleFormState {
|
||||||
|
return {
|
||||||
|
name: "",
|
||||||
|
cycleType: "quarterly",
|
||||||
|
startDate: "",
|
||||||
|
endDate: "",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorMessage(error: unknown, fallback: string) {
|
||||||
|
if (isApiError(error)) {
|
||||||
|
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
|
||||||
|
}
|
||||||
|
return error instanceof Error ? error.message : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cycleTypeLabel(value: PerformanceReviewCycleType) {
|
||||||
|
return CYCLE_TYPE_OPTIONS.find((item) => item.value === value)?.label ?? value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cycleStatusLabel(status: string) {
|
||||||
|
return status === "active" ? "进行中" : status === "completed" ? "已完成" : "草稿";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PerformancePage() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [selectedCycleId, setSelectedCycleId] = useState("");
|
||||||
|
const [cycleDialogOpen, setCycleDialogOpen] = useState(false);
|
||||||
|
const [editingCycleId, setEditingCycleId] = useState<string | null>(null);
|
||||||
|
const [cycleForm, setCycleForm] = useState<CycleFormState>(buildEmptyCycleForm());
|
||||||
|
|
||||||
|
const cyclesQuery = useQuery({
|
||||||
|
queryKey: ["performance-cycles"],
|
||||||
|
queryFn: fetchPerformanceCycles,
|
||||||
|
});
|
||||||
|
|
||||||
|
const cycles = cyclesQuery.data?.items ?? [];
|
||||||
|
const selectedCycle = cycles.find((item) => item.id === selectedCycleId) ?? cycles[0] ?? null;
|
||||||
|
|
||||||
|
const overviewQuery = useQuery({
|
||||||
|
enabled: Boolean(selectedCycle?.id),
|
||||||
|
queryKey: ["performance-cycle-overview", selectedCycle?.id],
|
||||||
|
queryFn: () => fetchPerformanceCycleOverview(selectedCycle!.id),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!cycles.length) {
|
||||||
|
setSelectedCycleId("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!cycles.some((item) => item.id === selectedCycleId)) {
|
||||||
|
const preferred = cycles.find((item) => item.status === "active") ?? cycles[0];
|
||||||
|
setSelectedCycleId(preferred.id);
|
||||||
|
}
|
||||||
|
}, [cycles, selectedCycleId]);
|
||||||
|
|
||||||
|
const cycleMutation = useMutation({
|
||||||
|
mutationFn: async () => {
|
||||||
|
if (editingCycleId) {
|
||||||
|
return patchPerformanceCycle(editingCycleId, cycleForm);
|
||||||
|
}
|
||||||
|
return createPerformanceCycle(cycleForm);
|
||||||
|
},
|
||||||
|
onSuccess: async (cycle) => {
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ["performance-cycles"] });
|
||||||
|
setSelectedCycleId(cycle.id);
|
||||||
|
setCycleDialogOpen(false);
|
||||||
|
setEditingCycleId(null);
|
||||||
|
setCycleForm(buildEmptyCycleForm());
|
||||||
|
toast.success(editingCycleId ? "考核周期已更新" : "考核周期已创建");
|
||||||
|
},
|
||||||
|
onError: (error) => toast.error(errorMessage(error, editingCycleId ? "更新周期失败" : "创建周期失败")),
|
||||||
|
});
|
||||||
|
|
||||||
|
const activateMutation = useMutation({
|
||||||
|
mutationFn: (cycleId: string) => patchPerformanceCycle(cycleId, { status: "active" }),
|
||||||
|
onSuccess: async (cycle) => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["performance-cycles"] }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["employee-stats"] }),
|
||||||
|
]);
|
||||||
|
setSelectedCycleId(cycle.id);
|
||||||
|
toast.success("考核周期已激活");
|
||||||
|
},
|
||||||
|
onError: (error) => toast.error(errorMessage(error, "激活周期失败")),
|
||||||
|
});
|
||||||
|
|
||||||
|
const completeMutation = useMutation({
|
||||||
|
mutationFn: (cycleId: string) => patchPerformanceCycle(cycleId, { status: "completed" }),
|
||||||
|
onSuccess: async (cycle) => {
|
||||||
|
await Promise.all([
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["performance-cycles"] }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["performance-cycle-overview", cycle.id] }),
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["employee-stats"] }),
|
||||||
|
]);
|
||||||
|
setSelectedCycleId(cycle.id);
|
||||||
|
toast.success("考核周期已关闭");
|
||||||
|
},
|
||||||
|
onError: (error) => toast.error(errorMessage(error, "关闭周期失败")),
|
||||||
|
});
|
||||||
|
|
||||||
|
const reviewedItems = overviewQuery.data?.items.filter((item) => item.review) ?? [];
|
||||||
|
const averageScore = reviewedItems.length
|
||||||
|
? reviewedItems.reduce((sum, item) => sum + (item.review?.overallScore ?? 0), 0) / reviewedItems.length
|
||||||
|
: null;
|
||||||
|
|
||||||
|
function openCreateDialog() {
|
||||||
|
setEditingCycleId(null);
|
||||||
|
setCycleForm(buildEmptyCycleForm());
|
||||||
|
setCycleDialogOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditDialog(cycle = selectedCycle) {
|
||||||
|
if (!cycle) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setEditingCycleId(cycle.id);
|
||||||
|
setCycleForm({
|
||||||
|
name: cycle.name,
|
||||||
|
cycleType: cycle.cycleType,
|
||||||
|
startDate: cycle.startDate ?? "",
|
||||||
|
endDate: cycle.endDate ?? "",
|
||||||
|
});
|
||||||
|
setCycleDialogOpen(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<PageHeader
|
||||||
|
title="绩效考核"
|
||||||
|
subtitle="管理考核周期,查看当前或历史周期的全员评分概览。"
|
||||||
|
actions={
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button asChild variant="secondary" type="button">
|
||||||
|
<Link to="/people">返回人员管理</Link>
|
||||||
|
</Button>
|
||||||
|
<Button type="button" onClick={openCreateDialog}>
|
||||||
|
新建周期
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="card-std p-6">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold text-zinc-900">考核周期列表</h2>
|
||||||
|
<p className="mt-1 text-sm text-zinc-500">draft 周期可编辑并激活;active 周期可关闭为 completed。</p>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm text-zinc-500">{cycles.length} 个周期</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>名称</TableHead>
|
||||||
|
<TableHead>类型</TableHead>
|
||||||
|
<TableHead>状态</TableHead>
|
||||||
|
<TableHead>日期</TableHead>
|
||||||
|
<TableHead>操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{cycles.length ? (
|
||||||
|
cycles.map((cycle) => (
|
||||||
|
<TableRow
|
||||||
|
key={cycle.id}
|
||||||
|
className={cycle.id === selectedCycle?.id ? "bg-zinc-50" : undefined}
|
||||||
|
onClick={() => setSelectedCycleId(cycle.id)}
|
||||||
|
>
|
||||||
|
<TableCell>
|
||||||
|
<div className="font-medium text-zinc-900">{cycle.name}</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{cycleTypeLabel(cycle.cycleType)}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<StatusBadge status={cycle.status} label={cycleStatusLabel(cycle.status)} />
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
{cycle.startDate ?? "-"} 至 {cycle.endDate ?? "-"}
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Button type="button" size="sm" variant="secondary" onClick={() => setSelectedCycleId(cycle.id)}>
|
||||||
|
查看概览
|
||||||
|
</Button>
|
||||||
|
{cycle.status === "draft" ? (
|
||||||
|
<>
|
||||||
|
<Button type="button" size="sm" variant="secondary" onClick={() => openEditDialog(cycle)}>
|
||||||
|
编辑
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => activateMutation.mutate(cycle.id)}
|
||||||
|
disabled={activateMutation.isPending}
|
||||||
|
>
|
||||||
|
激活
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
{cycle.status === "active" ? (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => completeMutation.mutate(cycle.id)}
|
||||||
|
disabled={completeMutation.isPending}
|
||||||
|
>
|
||||||
|
关闭
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={5} className="py-4 text-sm text-zinc-500">
|
||||||
|
{cyclesQuery.isLoading ? "加载考核周期中..." : "暂无考核周期"}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedCycle ? (
|
||||||
|
<>
|
||||||
|
<div className="grid gap-4 md:grid-cols-3">
|
||||||
|
<section className="card-std p-5">
|
||||||
|
<div className="text-sm text-zinc-500">当前查看周期</div>
|
||||||
|
<div className="mt-2 text-xl font-semibold text-zinc-900">{selectedCycle.name}</div>
|
||||||
|
<div className="mt-2 text-xs text-zinc-500">
|
||||||
|
{selectedCycle.startDate ?? "-"} 至 {selectedCycle.endDate ?? "-"}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="card-std p-5">
|
||||||
|
<div className="text-sm text-zinc-500">已评分人数</div>
|
||||||
|
<div className="mt-2 text-3xl font-semibold text-zinc-900">{reviewedItems.length}</div>
|
||||||
|
<div className="mt-2 text-xs text-zinc-500">按当前概览中已有评分记录统计</div>
|
||||||
|
</section>
|
||||||
|
<section className="card-std p-5">
|
||||||
|
<div className="text-sm text-zinc-500">平均分</div>
|
||||||
|
<div className="mt-2 text-3xl font-semibold text-zinc-900">{averageScore == null ? "-" : averageScore.toFixed(1)}</div>
|
||||||
|
<div className="mt-2 text-xs text-zinc-500">仅统计已评分记录</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="card-std p-6">
|
||||||
|
<div className="flex items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 className="text-lg font-semibold text-zinc-900">评分概览</h2>
|
||||||
|
<p className="mt-1 text-sm text-zinc-500">查看全员在当前选中周期的评分状态,点击可进入员工档案绩效标签。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4">
|
||||||
|
<Table>
|
||||||
|
<TableHeader>
|
||||||
|
<TableRow>
|
||||||
|
<TableHead>员工</TableHead>
|
||||||
|
<TableHead>部门 / 职位</TableHead>
|
||||||
|
<TableHead>总分</TableHead>
|
||||||
|
<TableHead>评分人</TableHead>
|
||||||
|
<TableHead>状态</TableHead>
|
||||||
|
<TableHead>操作</TableHead>
|
||||||
|
</TableRow>
|
||||||
|
</TableHeader>
|
||||||
|
<TableBody>
|
||||||
|
{overviewQuery.data?.items.length ? (
|
||||||
|
overviewQuery.data.items.map((item) => (
|
||||||
|
<TableRow key={item.employee.id}>
|
||||||
|
<TableCell>
|
||||||
|
<div className="font-medium text-zinc-900">{item.employee.name}</div>
|
||||||
|
<div className="text-xs text-zinc-500">{item.employee.employeeNo}</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<div>{item.employee.department?.name ?? "-"}</div>
|
||||||
|
<div className="text-xs text-zinc-500">{item.employee.title}</div>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>{item.review ? item.review.overallScore.toFixed(1) : "-"}</TableCell>
|
||||||
|
<TableCell>{item.review?.reviewer?.name ?? "-"}</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<StatusBadge
|
||||||
|
status={item.review ? "completed" : "draft"}
|
||||||
|
label={item.review ? "已评分" : selectedCycle.status === "active" ? "待评分" : "暂无评分"}
|
||||||
|
/>
|
||||||
|
</TableCell>
|
||||||
|
<TableCell>
|
||||||
|
<Button asChild type="button" size="sm" variant="secondary">
|
||||||
|
<Link to={`/people/${item.employee.id}?tab=performance`}>查看绩效</Link>
|
||||||
|
</Button>
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
))
|
||||||
|
) : (
|
||||||
|
<TableRow>
|
||||||
|
<TableCell colSpan={6} className="py-4 text-sm text-zinc-500">
|
||||||
|
{overviewQuery.isLoading ? "加载评分概览中..." : "当前周期暂无可展示的评分数据"}
|
||||||
|
</TableCell>
|
||||||
|
</TableRow>
|
||||||
|
)}
|
||||||
|
</TableBody>
|
||||||
|
</Table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<Dialog open={cycleDialogOpen} onOpenChange={setCycleDialogOpen}>
|
||||||
|
<DialogContent>
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{editingCycleId ? "编辑考核周期" : "新建考核周期"}</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="grid gap-4 py-2">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">周期名称</label>
|
||||||
|
<Input value={cycleForm.name} onChange={(event) => setCycleForm((prev) => ({ ...prev, name: event.target.value }))} />
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">周期类型</label>
|
||||||
|
<select
|
||||||
|
className="select-std"
|
||||||
|
value={cycleForm.cycleType}
|
||||||
|
onChange={(event) => setCycleForm((prev) => ({ ...prev, cycleType: event.target.value as PerformanceReviewCycleType }))}
|
||||||
|
>
|
||||||
|
{CYCLE_TYPE_OPTIONS.map((item) => (
|
||||||
|
<option key={item.value} value={item.value}>
|
||||||
|
{item.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-4 md:grid-cols-2">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">开始日期</label>
|
||||||
|
<Input
|
||||||
|
type="date"
|
||||||
|
value={cycleForm.startDate}
|
||||||
|
onChange={(event) => setCycleForm((prev) => ({ ...prev, startDate: event.target.value }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<label className="text-sm text-zinc-500">结束日期</label>
|
||||||
|
<Input
|
||||||
|
type="date"
|
||||||
|
value={cycleForm.endDate}
|
||||||
|
onChange={(event) => setCycleForm((prev) => ({ ...prev, endDate: event.target.value }))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
onClick={() => cycleMutation.mutate()}
|
||||||
|
disabled={cycleMutation.isPending || !cycleForm.name.trim() || !cycleForm.startDate || !cycleForm.endDate}
|
||||||
|
>
|
||||||
|
{cycleMutation.isPending ? "保存中..." : editingCycleId ? "保存修改" : "创建周期"}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default PerformancePage;
|
||||||
@@ -32,6 +32,7 @@ import {
|
|||||||
NotificationChannelsPage,
|
NotificationChannelsPage,
|
||||||
NotificationsPage,
|
NotificationsPage,
|
||||||
OrganizationPage,
|
OrganizationPage,
|
||||||
|
PerformancePage,
|
||||||
PaymentBatchesPage,
|
PaymentBatchesPage,
|
||||||
PeoplePage,
|
PeoplePage,
|
||||||
PeopleStatsPage,
|
PeopleStatsPage,
|
||||||
@@ -304,6 +305,15 @@ export function AppRouter() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Route
|
||||||
|
path="performance"
|
||||||
|
element={
|
||||||
|
<RequirePermission anyOf={["system.users"]}>
|
||||||
|
{withRouteFallback(<PerformancePage />)}
|
||||||
|
</RequirePermission>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
<Route
|
<Route
|
||||||
path="organization"
|
path="organization"
|
||||||
element={
|
element={
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
export { PerformancePage as default } from "../../pages/PerformancePage";
|
||||||
@@ -22,6 +22,7 @@ export const AnnouncementsPage = lazy(() => import("./AnnouncementsPage"));
|
|||||||
export const PaymentBatchesPage = lazy(() => import("./PaymentBatchesPage"));
|
export const PaymentBatchesPage = lazy(() => import("./PaymentBatchesPage"));
|
||||||
export const PeoplePage = lazy(() => import("./PeoplePage"));
|
export const PeoplePage = lazy(() => import("./PeoplePage"));
|
||||||
export const PeopleStatsPage = lazy(() => import("./PeopleStatsPage"));
|
export const PeopleStatsPage = lazy(() => import("./PeopleStatsPage"));
|
||||||
|
export const PerformancePage = lazy(() => import("./PerformancePage"));
|
||||||
export const OrganizationPage = lazy(() => import("./OrganizationPage"));
|
export const OrganizationPage = lazy(() => import("./OrganizationPage"));
|
||||||
export const EmployeeProfilePage = lazy(() => import("./EmployeeProfilePage"));
|
export const EmployeeProfilePage = lazy(() => import("./EmployeeProfilePage"));
|
||||||
export const TeamPresencePage = lazy(() => import("./TeamPresencePage"));
|
export const TeamPresencePage = lazy(() => import("./TeamPresencePage"));
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||||
|
"A1","R46 执行合同与范围冻结","创建 R46 Issue CSV,冻结范围为绩效周期、评分、统计扩展与档案页绩效标签;锁定绩效路由独立于 employees.js,直属上级通过绩效专属 API 访问,不放宽完整档案敏感字段权限。","issues/2026-03-29_r46-performance-review.csv 列完整、依赖清晰、测试方法可复现;范围仅覆盖本轮绩效核心流程。","对照 AGENTS.md 与 issues/README.md 检查列完整、Dependencies 为 JSON 数组字符串、Test_Method 含命令与业务流程步骤;确认范围不包含 OKR/KPI、360 评估、申诉流、模板中心或自动提醒。","manual","DONE","DONE","DONE","issues/2026-03-29_r46-performance-review.csv","[]","none"
|
||||||
|
"A2","R46 Prisma 模型与周期管理后端","新增 PerformanceReviewCycle、PerformanceReview、PerformanceReviewDimension 及相关 enum,注册独立 performance 路由,完成周期创建、草稿编辑、激活、关闭与单一 active 周期约束。","管理员可创建 draft 周期、编辑 draft、激活周期且全局同时仅 1 个 active、关闭 active 为 completed;completed 后不可再回到 active;周期操作写审计日志。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/performance.js && node --check src/app.js && npm test -- tests/unit/routes/performance.cycles.test.js。业务:1) system.users 创建 draft 周期成功;2) draft 周期修改名称/类型/日期成功;3) 激活第一个周期成功,再激活第二个周期返回冲突且原 active 不变;4) active 周期关闭为 completed 后不可再接收评分。","manual","DONE","DONE","DONE","server/prisma/schema.prisma|server/prisma/migrations|server/src/routes/performance.js|server/src/app.js|server/tests/unit/routes/performance.cycles.test.js","[""A1""]","回滚:先清理 performance_review_dimensions / performance_reviews / performance_review_cycles 数据,再回滚 Prisma migration 与 route 注册;本轮不提供周期删除。"
|
||||||
|
"A3","R46 评分接口与三层权限后端","在 performance.js 实现按周期全员概览、按员工绩效时间线与评分 upsert;system.users 可评分任意员工,直属上级仅可评分直属下属 active 周期,本人仅可查看自己已完成结果,report.dashboard.view 不可访问个人明细。","评分接口校验 1-5 且步进 0.5;维度为可选多项且每项带分数;管理员可查看任意员工 active/completed 周期,直属上级可查看直属下属历史并编辑 active,本人仅能查看自己 completed 结果;completed 周期不可再修改。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/routes/performance.js && npm test -- tests/unit/routes/performance.reviews.test.js。业务:1) 直属上级为直属下属在 active 周期提交 4.5 分和多条维度分项成功;2) 非直属上级、普通员工为他人评分返回 403;3) system.users 可修改任意员工 active 周期评分;4) 自己查询仅返回 completed 结果,active 周期对本人不可见;5) completed 周期再次 PUT 评分返回冲突。","manual","DONE","DONE","DONE","server/src/routes/performance.js|server/tests/unit/routes/performance.reviews.test.js","[""A2""]","评分记录按 [cycle_id, employee_id] 唯一;每次更新在事务内全量替换维度明细;不放宽 /api/employees/:id/profile 的现有敏感字段权限。"
|
||||||
|
"A4","R46 绩效统计后端扩展","扩展 employeeStats,在现有员工统计基础上追加 performanceSummary,返回当前 active 或最近 completed 周期的平均分、评分分布与已评分人数,继续保持只返回聚合数据。","GET /api/employees/stats 对 system.users 与 report.dashboard.view 返回聚合绩效统计;有 active 时取 active,无 active 时取最近 completed;无周期时返回空绩效态;不暴露员工级明细。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd server && npx prisma validate && node --check src/services/employeeStats.js && node --check src/routes/employees.js && npm test -- tests/unit/routes/employees.stats.test.js。业务:1) 存在 active 周期时返回该周期平均分与 0.5 档位分布;2) 无 active 但有 completed 周期时返回最近 completed;3) 无任何周期时页面可渲染空态;4) report.dashboard.view 只能看到聚合统计,不能通过绩效详情接口看到个人数据。","manual","DONE","DONE","DONE","server/src/services/employeeStats.js|server/src/routes/employees.js|server/tests/unit/routes/employees.stats.test.js","[""A2"",""A3""]","评分分布按 1.0-5.0、步进 0.5 共 9 档返回;本轮不新增独立绩效统计接口。"
|
||||||
|
"A5","R46 绩效列表页与前端 API","新增 client 侧绩效 API 与独立 /performance 页面,支持管理员创建/激活/关闭周期、按周期查看全员评分概览,并从 PeoplePage 页头进入。","system.users 可访问 /performance 并完成周期管理;选中周期后可看到评分概览、平均分与深链到员工档案绩效 tab;非 system.users 直接访问路由被拦截。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) system.users 从 PeoplePage 进入 /performance 成功;2) 新建 draft 周期、激活、关闭流程与后端一致;3) 切换周期后全员概览刷新;4) 行内“查看绩效”跳转到 /people/:employeeId?tab=performance;5) 非管理员访问 /performance 进入 403。","manual","DONE","DONE","DOING","client/src/api/performance.ts|client/src/pages/PerformancePage.tsx|client/src/router/index.tsx|client/src/router/lazy/index.ts|client/src/router/lazy/PerformancePage.ts|client/src/pages/PeoplePage.tsx","[""A2"",""A3""]","/performance 为独立路由但不进入全局主导航;入口放 PeoplePage 页头,避免继续膨胀导航与 workspace settings。"
|
||||||
|
"A6","R46 档案页绩效标签与直属上级评分","在 EmployeeProfilePage 增加绩效 tab、tab 深链与绩效专属降级视图;本人查看已完成结果,管理员查看并编辑 active,直属上级可从本人档案的直属下级卡片进入下属绩效页并编辑 active。","档案页支持 ?tab=performance 直达;本人仅见 completed 结果;管理员可见 active/completed 并编辑 active;直属上级在完整 profile 403 但绩效接口允许时,页面退化为精简头部 + 绩效 tab;report.dashboard.view 不显示绩效 tab。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 员工本人打开 /people/:me?tab=performance,只看到自己 completed 周期结果;2) system.users 打开任意员工档案可编辑 active 周期评分;3) 直属上级从自己档案“直属下级”卡片进入下属 /people/:id?tab=performance,可提交或修改 active 周期评分;4) 非直属上级即使知道链接也不能查看该员工绩效;5) report.dashboard.view 仍仅能看统计页,不显示绩效 tab。","manual","DONE","DONE","DOING","client/src/pages/EmployeeProfilePage.tsx|client/src/api/performance.ts","[""A3"",""A5""]","不放宽完整档案敏感字段权限;直属上级看到的是绩效专属上下文,不包含生命周期、紧急联系人、资产等扩展信息。"
|
||||||
|
"A7","R46 统计页前端扩展绩效概览","扩展 PeopleStatsPage 与员工统计类型,展示当前/最近周期平均分、已评分人数与评分分布,同时保持 report.dashboard.view 的只读聚合边界。","PeopleStatsPage 新增绩效概览且不暴露个人明细;system.users 与 report.dashboard.view 均可查看;原有员工统计卡片和列表不回归。","命令:export PATH=/home/shunli/.nvm/versions/node/v22.20.0/bin:$PATH && cd client && npm run typecheck && npm run build。业务:1) 进入 /people/stats 可看到当前/最近周期平均分与评分分布;2) 无绩效周期时显示空态文案;3) report.dashboard.view 访问统计页仍只见聚合数据;4) 原有合同到期、证书、雇用状态、部门分布统计继续正常。","manual","DONE","DONE","DOING","client/src/pages/PeopleStatsPage.tsx|client/src/api/employees.ts","[""A4""]","绩效分布按后端 0.5 档位展示为简单列表,不引入图表库。"
|
||||||
|
"A8","Reviewer 与 QA 收口","按 AGENTS 编排启用 reviewer 与 qa,重点审查 Prisma 迁移回滚、三层权限边界、唯一 active 周期约束、completed 冻结与档案页降级视图,并回填 CSV 状态。","A2-A7 的 Review1_Status 与 Regression_Status 都有证据地回填;reviewer 风险项关闭;R43-R45 员工模块能力不回归。","Reviewer:审查 3 个新模型迁移回滚路径、评分权限边界、direct_manager_id 复用逻辑、completed 不可写与 active 唯一约束、是否误放宽完整员工档案权限。QA:运行 backend post-check、frontend post-check,并手工回归 4 条主线:周期创建/激活/关闭、直属上级评分、档案页绩效访问边界、统计页绩效聚合;同时确认 R43 头像/合同/培训证书、R44 高级筛选/批量操作/统计、现有 PeoplePage 与 EmployeeProfilePage 不回归。","manual","DOING","DONE","DOING","issues/2026-03-29_r46-performance-review.csv","[""A2"",""A3"",""A4"",""A5"",""A6"",""A7""]","reviewer 必启用:本轮涉及 3 个新模型、三层权限分级、completed 冻结规则与 profile 降级视图。"
|
||||||
|
@@ -0,0 +1,88 @@
|
|||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PerformanceReviewCycleType" AS ENUM ('monthly', 'quarterly', 'semi_annual', 'annual');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PerformanceReviewCycleStatus" AS ENUM ('draft', 'active', 'completed');
|
||||||
|
|
||||||
|
-- CreateEnum
|
||||||
|
CREATE TYPE "PerformanceReviewDimensionType" AS ENUM ('work_quality', 'work_efficiency', 'teamwork', 'initiative', 'professional_skill');
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "performance_review_cycles" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"name" TEXT NOT NULL,
|
||||||
|
"cycle_type" "PerformanceReviewCycleType" NOT NULL,
|
||||||
|
"start_date" DATE NOT NULL,
|
||||||
|
"end_date" DATE NOT NULL,
|
||||||
|
"status" "PerformanceReviewCycleStatus" NOT NULL DEFAULT 'draft',
|
||||||
|
"activated_at" TIMESTAMP(3),
|
||||||
|
"completed_at" TIMESTAMP(3),
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"created_by" UUID,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_by" UUID,
|
||||||
|
|
||||||
|
CONSTRAINT "performance_review_cycles_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "performance_reviews" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"cycle_id" UUID NOT NULL,
|
||||||
|
"employee_id" UUID NOT NULL,
|
||||||
|
"reviewer_employee_id" UUID NOT NULL,
|
||||||
|
"overall_score" DECIMAL(3,1) NOT NULL,
|
||||||
|
"comment" TEXT,
|
||||||
|
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"created_by" UUID,
|
||||||
|
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updated_by" UUID,
|
||||||
|
|
||||||
|
CONSTRAINT "performance_reviews_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "performance_review_dimensions" (
|
||||||
|
"id" UUID NOT NULL,
|
||||||
|
"review_id" UUID NOT NULL,
|
||||||
|
"dimension_type" "PerformanceReviewDimensionType" NOT NULL,
|
||||||
|
"score" DECIMAL(3,1) NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT "performance_review_dimensions_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "idx_performance_review_cycles_status_start" ON "performance_review_cycles"("status", "start_date");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "idx_performance_review_cycles_status_completed" ON "performance_review_cycles"("status", "completed_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "performance_review_cycles_single_active_ux" ON "performance_review_cycles"("status") WHERE "status" = 'active';
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "performance_reviews_cycle_employee_ux" ON "performance_reviews"("cycle_id", "employee_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "idx_performance_reviews_cycle_reviewer" ON "performance_reviews"("cycle_id", "reviewer_employee_id");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "idx_performance_reviews_employee_created" ON "performance_reviews"("employee_id", "created_at");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE UNIQUE INDEX "performance_review_dimensions_review_dimension_ux" ON "performance_review_dimensions"("review_id", "dimension_type");
|
||||||
|
|
||||||
|
-- CreateIndex
|
||||||
|
CREATE INDEX "idx_performance_review_dimensions_dimension_score" ON "performance_review_dimensions"("dimension_type", "score");
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "performance_reviews" ADD CONSTRAINT "performance_reviews_cycle_id_fkey" FOREIGN KEY ("cycle_id") REFERENCES "performance_review_cycles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "performance_reviews" ADD CONSTRAINT "performance_reviews_employee_id_fkey" FOREIGN KEY ("employee_id") REFERENCES "employees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "performance_reviews" ADD CONSTRAINT "performance_reviews_reviewer_employee_id_fkey" FOREIGN KEY ("reviewer_employee_id") REFERENCES "employees"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "performance_review_dimensions" ADD CONSTRAINT "performance_review_dimensions_review_id_fkey" FOREIGN KEY ("review_id") REFERENCES "performance_reviews"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
+85
-3
@@ -363,6 +363,27 @@ enum EmployeeTrainingStatus {
|
|||||||
cancelled
|
cancelled
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum PerformanceReviewCycleType {
|
||||||
|
monthly
|
||||||
|
quarterly
|
||||||
|
semi_annual
|
||||||
|
annual
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PerformanceReviewCycleStatus {
|
||||||
|
draft
|
||||||
|
active
|
||||||
|
completed
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PerformanceReviewDimensionType {
|
||||||
|
work_quality
|
||||||
|
work_efficiency
|
||||||
|
teamwork
|
||||||
|
initiative
|
||||||
|
professional_skill
|
||||||
|
}
|
||||||
|
|
||||||
enum WeeklyReportStatus {
|
enum WeeklyReportStatus {
|
||||||
draft
|
draft
|
||||||
submitted
|
submitted
|
||||||
@@ -609,6 +630,8 @@ model Employee {
|
|||||||
contracts EmployeeContract[]
|
contracts EmployeeContract[]
|
||||||
trainings EmployeeTraining[]
|
trainings EmployeeTraining[]
|
||||||
certificates EmployeeCertificate[]
|
certificates EmployeeCertificate[]
|
||||||
|
performance_reviews_received PerformanceReview[] @relation("PerformanceReviewEmployee")
|
||||||
|
performance_reviews_authored PerformanceReview[] @relation("PerformanceReviewReviewer")
|
||||||
|
|
||||||
@@index([department_id])
|
@@index([department_id])
|
||||||
@@index([legal_entity_id], map: "idx_employees_legal_entity")
|
@@index([legal_entity_id], map: "idx_employees_legal_entity")
|
||||||
@@ -2045,11 +2068,11 @@ model EmployeeTraining {
|
|||||||
}
|
}
|
||||||
|
|
||||||
model EmployeeCertificate {
|
model EmployeeCertificate {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
employee_id String @db.Uuid
|
employee_id String @db.Uuid
|
||||||
name String
|
name String
|
||||||
issuer String
|
issuer String
|
||||||
obtained_date DateTime @db.Date
|
obtained_date DateTime @db.Date
|
||||||
expiry_date DateTime? @db.Date
|
expiry_date DateTime? @db.Date
|
||||||
certificate_no String?
|
certificate_no String?
|
||||||
attachment_path String?
|
attachment_path String?
|
||||||
@@ -2066,6 +2089,65 @@ model EmployeeCertificate {
|
|||||||
@@map("employee_certificates")
|
@@map("employee_certificates")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model PerformanceReviewCycle {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
name String
|
||||||
|
cycle_type PerformanceReviewCycleType
|
||||||
|
start_date DateTime @db.Date
|
||||||
|
end_date DateTime @db.Date
|
||||||
|
status PerformanceReviewCycleStatus @default(draft)
|
||||||
|
activated_at DateTime?
|
||||||
|
completed_at DateTime?
|
||||||
|
|
||||||
|
created_at DateTime @default(now())
|
||||||
|
created_by String? @db.Uuid
|
||||||
|
updated_at DateTime @default(now()) @updatedAt
|
||||||
|
updated_by String? @db.Uuid
|
||||||
|
|
||||||
|
reviews PerformanceReview[]
|
||||||
|
|
||||||
|
@@index([status, start_date], map: "idx_performance_review_cycles_status_start")
|
||||||
|
@@index([status, completed_at], map: "idx_performance_review_cycles_status_completed")
|
||||||
|
@@map("performance_review_cycles")
|
||||||
|
}
|
||||||
|
|
||||||
|
model PerformanceReview {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
cycle_id String @db.Uuid
|
||||||
|
employee_id String @db.Uuid
|
||||||
|
reviewer_employee_id String @db.Uuid
|
||||||
|
overall_score Decimal @db.Decimal(3, 1)
|
||||||
|
comment String?
|
||||||
|
|
||||||
|
created_at DateTime @default(now())
|
||||||
|
created_by String? @db.Uuid
|
||||||
|
updated_at DateTime @default(now()) @updatedAt
|
||||||
|
updated_by String? @db.Uuid
|
||||||
|
|
||||||
|
cycle PerformanceReviewCycle @relation(fields: [cycle_id], references: [id], onDelete: Cascade)
|
||||||
|
employee Employee @relation("PerformanceReviewEmployee", fields: [employee_id], references: [id], onDelete: Cascade)
|
||||||
|
reviewer_employee Employee @relation("PerformanceReviewReviewer", fields: [reviewer_employee_id], references: [id], onDelete: Restrict)
|
||||||
|
dimensions PerformanceReviewDimension[]
|
||||||
|
|
||||||
|
@@unique([cycle_id, employee_id], map: "performance_reviews_cycle_employee_ux")
|
||||||
|
@@index([cycle_id, reviewer_employee_id], map: "idx_performance_reviews_cycle_reviewer")
|
||||||
|
@@index([employee_id, created_at], map: "idx_performance_reviews_employee_created")
|
||||||
|
@@map("performance_reviews")
|
||||||
|
}
|
||||||
|
|
||||||
|
model PerformanceReviewDimension {
|
||||||
|
id String @id @default(uuid()) @db.Uuid
|
||||||
|
review_id String @db.Uuid
|
||||||
|
dimension_type PerformanceReviewDimensionType
|
||||||
|
score Decimal @db.Decimal(3, 1)
|
||||||
|
|
||||||
|
review PerformanceReview @relation(fields: [review_id], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@unique([review_id, dimension_type], map: "performance_review_dimensions_review_dimension_ux")
|
||||||
|
@@index([dimension_type, score], map: "idx_performance_review_dimensions_dimension_score")
|
||||||
|
@@map("performance_review_dimensions")
|
||||||
|
}
|
||||||
|
|
||||||
model ProjectDeliveryRecord {
|
model ProjectDeliveryRecord {
|
||||||
id String @id @default(uuid()) @db.Uuid
|
id String @id @default(uuid()) @db.Uuid
|
||||||
project_id String @db.Uuid
|
project_id String @db.Uuid
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ const masterDataRoutes = require("./routes/masterData");
|
|||||||
const masterDataHolidayCalendarsRoutes = require("./routes/masterDataHolidayCalendars");
|
const masterDataHolidayCalendarsRoutes = require("./routes/masterDataHolidayCalendars");
|
||||||
const masterDataSuppliersRoutes = require("./routes/masterDataSuppliers");
|
const masterDataSuppliersRoutes = require("./routes/masterDataSuppliers");
|
||||||
const employeesRoutes = require("./routes/employees");
|
const employeesRoutes = require("./routes/employees");
|
||||||
|
const performanceRoutes = require("./routes/performance");
|
||||||
const expenseTypesRoutes = require("./routes/expenseTypes");
|
const expenseTypesRoutes = require("./routes/expenseTypes");
|
||||||
const configReadRoutes = require("./routes/configRead");
|
const configReadRoutes = require("./routes/configRead");
|
||||||
const approvalRulesRoutes = require("./routes/approvalRules");
|
const approvalRulesRoutes = require("./routes/approvalRules");
|
||||||
@@ -313,6 +314,7 @@ async function buildApp() {
|
|||||||
await app.register(auditRoutes, { prefix: "/api" });
|
await app.register(auditRoutes, { prefix: "/api" });
|
||||||
await app.register(usersRoutes, { prefix: "/api" });
|
await app.register(usersRoutes, { prefix: "/api" });
|
||||||
await app.register(employeesRoutes, { prefix: "/api" });
|
await app.register(employeesRoutes, { prefix: "/api" });
|
||||||
|
await app.register(performanceRoutes, { prefix: "/api" });
|
||||||
await app.register(departmentsRoutes, { prefix: "/api" });
|
await app.register(departmentsRoutes, { prefix: "/api" });
|
||||||
await app.register(masterDataRoutes, { prefix: "/api" });
|
await app.register(masterDataRoutes, { prefix: "/api" });
|
||||||
await app.register(masterDataHolidayCalendarsRoutes, { prefix: "/api" });
|
await app.register(masterDataHolidayCalendarsRoutes, { prefix: "/api" });
|
||||||
|
|||||||
@@ -0,0 +1,661 @@
|
|||||||
|
const { z } = require("zod");
|
||||||
|
|
||||||
|
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||||
|
const { currentDateString } = require("../utils/date");
|
||||||
|
const { AppError } = require("../utils/AppError");
|
||||||
|
const { sendData } = require("../utils/reply");
|
||||||
|
const { buildAuditLogData } = require("../utils/audit");
|
||||||
|
|
||||||
|
const UUID_SCHEMA = z.string().uuid();
|
||||||
|
const DATE_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||||
|
const CYCLE_TYPE_SCHEMA = z.enum(["monthly", "quarterly", "semi_annual", "annual"]);
|
||||||
|
const CYCLE_STATUS_SCHEMA = z.enum(["draft", "active", "completed"]);
|
||||||
|
const DIMENSION_TYPE_SCHEMA = z.enum([
|
||||||
|
"work_quality",
|
||||||
|
"work_efficiency",
|
||||||
|
"teamwork",
|
||||||
|
"initiative",
|
||||||
|
"professional_skill",
|
||||||
|
]);
|
||||||
|
|
||||||
|
const SCORE_SCHEMA = z
|
||||||
|
.number()
|
||||||
|
.min(1)
|
||||||
|
.max(5)
|
||||||
|
.refine((value) => Number.isFinite(value) && Math.abs(value * 2 - Math.round(value * 2)) < 1e-9, {
|
||||||
|
message: "invalid_score_step",
|
||||||
|
});
|
||||||
|
|
||||||
|
const CYCLE_CREATE_SCHEMA = z
|
||||||
|
.object({
|
||||||
|
name: z.string().trim().min(1).max(200),
|
||||||
|
cycleType: CYCLE_TYPE_SCHEMA,
|
||||||
|
startDate: DATE_SCHEMA,
|
||||||
|
endDate: DATE_SCHEMA,
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
const CYCLE_PATCH_SCHEMA = z
|
||||||
|
.object({
|
||||||
|
name: z.string().trim().min(1).max(200).optional(),
|
||||||
|
cycleType: CYCLE_TYPE_SCHEMA.optional(),
|
||||||
|
startDate: DATE_SCHEMA.optional(),
|
||||||
|
endDate: DATE_SCHEMA.optional(),
|
||||||
|
status: CYCLE_STATUS_SCHEMA.optional(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
.refine((value) => Object.keys(value).length > 0, { message: "empty_patch" });
|
||||||
|
|
||||||
|
const REVIEW_UPSERT_SCHEMA = z
|
||||||
|
.object({
|
||||||
|
overallScore: SCORE_SCHEMA,
|
||||||
|
comment: z.string().trim().max(3000).nullable().optional(),
|
||||||
|
dimensions: z
|
||||||
|
.array(
|
||||||
|
z
|
||||||
|
.object({
|
||||||
|
dimensionType: DIMENSION_TYPE_SCHEMA,
|
||||||
|
score: SCORE_SCHEMA,
|
||||||
|
})
|
||||||
|
.strict(),
|
||||||
|
)
|
||||||
|
.max(5)
|
||||||
|
.optional()
|
||||||
|
.default([]),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
.superRefine((value, ctx) => {
|
||||||
|
const seen = new Set();
|
||||||
|
value.dimensions.forEach((item, index) => {
|
||||||
|
if (seen.has(item.dimensionType)) {
|
||||||
|
ctx.addIssue({
|
||||||
|
code: z.ZodIssueCode.custom,
|
||||||
|
path: ["dimensions", index, "dimensionType"],
|
||||||
|
message: "duplicate_dimension",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
seen.add(item.dimensionType);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const EMPLOYEE_SUMMARY_SELECT = {
|
||||||
|
id: true,
|
||||||
|
employee_no: true,
|
||||||
|
name: true,
|
||||||
|
title: true,
|
||||||
|
status: true,
|
||||||
|
direct_manager_id: true,
|
||||||
|
avatar_path: true,
|
||||||
|
department: { select: { id: true, name: true } },
|
||||||
|
};
|
||||||
|
|
||||||
|
const REVIEW_DETAIL_INCLUDE = {
|
||||||
|
dimensions: true,
|
||||||
|
reviewer_employee: {
|
||||||
|
select: {
|
||||||
|
id: true,
|
||||||
|
employee_no: true,
|
||||||
|
name: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const DIMENSION_ORDER = ["work_quality", "work_efficiency", "teamwork", "initiative", "professional_skill"];
|
||||||
|
|
||||||
|
function buildValidationError(details, statusCode = 400) {
|
||||||
|
return new AppError({ code: "VALID_001", message: "参数校验失败", statusCode, details });
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseId(value) {
|
||||||
|
const parsed = UUID_SCHEMA.safeParse(value);
|
||||||
|
if (!parsed.success) {
|
||||||
|
throw buildValidationError({ id: "invalid_uuid" });
|
||||||
|
}
|
||||||
|
return parsed.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseBody(schema, body) {
|
||||||
|
const parsed = schema.safeParse(body ?? {});
|
||||||
|
if (!parsed.success) {
|
||||||
|
throw buildValidationError(parsed.error.flatten());
|
||||||
|
}
|
||||||
|
return parsed.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseDateOnly(value) {
|
||||||
|
return value ? new Date(`${value}T00:00:00.000Z`) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildAvatarUrl(employeeId, avatarPath) {
|
||||||
|
return avatarPath ? `/api/avatars/${employeeId}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toNumber(value) {
|
||||||
|
return value == null ? null : Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateCycleDates(startDate, endDate) {
|
||||||
|
if (startDate && endDate && startDate > endDate) {
|
||||||
|
throw buildValidationError({ endDate: "must_be_after_or_equal_startDate" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureFeatureEnabled(fastify, request) {
|
||||||
|
const gate = await evaluateFeatureFlag({
|
||||||
|
prisma: fastify.prisma,
|
||||||
|
config: fastify.config,
|
||||||
|
flagKey: FEATURE_FLAG_KEYS.employeeLifecycle,
|
||||||
|
departmentId: request.employee.department_id ?? null,
|
||||||
|
strictDepartment: false,
|
||||||
|
});
|
||||||
|
if (!gate.enabled) {
|
||||||
|
throw buildValidationError({ featureFlag: "employee_lifecycle_v1_disabled", reason: gate.reason }, 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapEmployeeSummary(employee) {
|
||||||
|
return {
|
||||||
|
id: employee.id,
|
||||||
|
employeeNo: employee.employee_no,
|
||||||
|
name: employee.name,
|
||||||
|
title: employee.title,
|
||||||
|
status: employee.status,
|
||||||
|
avatarUrl: buildAvatarUrl(employee.id, employee.avatar_path),
|
||||||
|
department: employee.department ? { id: employee.department.id, name: employee.department.name } : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapCycle(cycle) {
|
||||||
|
return {
|
||||||
|
id: cycle.id,
|
||||||
|
name: cycle.name,
|
||||||
|
cycleType: cycle.cycle_type,
|
||||||
|
status: cycle.status,
|
||||||
|
startDate: cycle.start_date?.toISOString?.()?.slice(0, 10) ?? null,
|
||||||
|
endDate: cycle.end_date?.toISOString?.()?.slice(0, 10) ?? null,
|
||||||
|
activatedAt: cycle.activated_at?.toISOString?.() ?? null,
|
||||||
|
completedAt: cycle.completed_at?.toISOString?.() ?? null,
|
||||||
|
createdAt: cycle.created_at?.toISOString?.() ?? null,
|
||||||
|
createdBy: cycle.created_by ?? null,
|
||||||
|
updatedAt: cycle.updated_at?.toISOString?.() ?? null,
|
||||||
|
updatedBy: cycle.updated_by ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapReview(review) {
|
||||||
|
return {
|
||||||
|
id: review.id,
|
||||||
|
cycleId: review.cycle_id,
|
||||||
|
employeeId: review.employee_id,
|
||||||
|
reviewerEmployeeId: review.reviewer_employee_id,
|
||||||
|
overallScore: toNumber(review.overall_score),
|
||||||
|
comment: review.comment ?? null,
|
||||||
|
reviewer: review.reviewer_employee
|
||||||
|
? {
|
||||||
|
id: review.reviewer_employee.id,
|
||||||
|
employeeNo: review.reviewer_employee.employee_no,
|
||||||
|
name: review.reviewer_employee.name,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
dimensions: [...(review.dimensions ?? [])]
|
||||||
|
.sort((left, right) => DIMENSION_ORDER.indexOf(left.dimension_type) - DIMENSION_ORDER.indexOf(right.dimension_type))
|
||||||
|
.map((item) => ({
|
||||||
|
dimensionType: item.dimension_type,
|
||||||
|
score: toNumber(item.score),
|
||||||
|
})),
|
||||||
|
createdAt: review.created_at?.toISOString?.() ?? null,
|
||||||
|
createdBy: review.created_by ?? null,
|
||||||
|
updatedAt: review.updated_at?.toISOString?.() ?? null,
|
||||||
|
updatedBy: review.updated_by ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveViewerRole(fastify, request, employee) {
|
||||||
|
if (fastify.hasPermission(request.employee, "system.users")) {
|
||||||
|
return "admin";
|
||||||
|
}
|
||||||
|
if (request.employee.id === employee.id) {
|
||||||
|
return "self";
|
||||||
|
}
|
||||||
|
if (employee.direct_manager_id && employee.direct_manager_id === request.employee.id) {
|
||||||
|
return "manager";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureCycleExists(prisma, cycleId) {
|
||||||
|
const cycle = await prisma.performanceReviewCycle.findUnique({ where: { id: cycleId } });
|
||||||
|
if (!cycle) {
|
||||||
|
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||||
|
}
|
||||||
|
return cycle;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureEmployeeExists(prisma, employeeId) {
|
||||||
|
const employee = await prisma.employee.findUnique({
|
||||||
|
where: { id: employeeId },
|
||||||
|
select: EMPLOYEE_SUMMARY_SELECT,
|
||||||
|
});
|
||||||
|
if (!employee) {
|
||||||
|
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||||
|
}
|
||||||
|
return employee;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function ensureNoOtherActiveCycle(prisma, excludedCycleId = null) {
|
||||||
|
const existing = await prisma.performanceReviewCycle.findFirst({
|
||||||
|
where: {
|
||||||
|
status: "active",
|
||||||
|
...(excludedCycleId ? { id: { not: excludedCycleId } } : {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
throw buildValidationError({ cycle: "active_cycle_exists", activeCycleId: existing.id }, 409);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function lockCycleForUpdate(prisma, cycleId) {
|
||||||
|
if (typeof prisma.$queryRaw === "function") {
|
||||||
|
const rows = await prisma.$queryRaw`
|
||||||
|
SELECT "id", "status"
|
||||||
|
FROM "performance_review_cycles"
|
||||||
|
WHERE "id" = ${cycleId}::uuid
|
||||||
|
FOR UPDATE
|
||||||
|
`;
|
||||||
|
if (!rows.length) {
|
||||||
|
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||||
|
}
|
||||||
|
return rows[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
return ensureCycleExists(prisma, cycleId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isPrismaUniqueConstraintError(error) {
|
||||||
|
return Boolean(error && typeof error === "object" && "code" in error && error.code === "P2002");
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortCycles(items) {
|
||||||
|
const rank = { active: 0, draft: 1, completed: 2 };
|
||||||
|
return [...items].sort((left, right) => {
|
||||||
|
const rankDiff = (rank[left.status] ?? 9) - (rank[right.status] ?? 9);
|
||||||
|
if (rankDiff !== 0) return rankDiff;
|
||||||
|
const leftDate = left.endDate ?? left.startDate ?? "";
|
||||||
|
const rightDate = right.endDate ?? right.startDate ?? "";
|
||||||
|
return rightDate.localeCompare(leftDate) || String(right.name ?? "").localeCompare(String(left.name ?? ""));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortEmployeeItems(items) {
|
||||||
|
return [...items].sort((left, right) => {
|
||||||
|
const leftDepartment = left.employee.department?.name ?? "";
|
||||||
|
const rightDepartment = right.employee.department?.name ?? "";
|
||||||
|
return (
|
||||||
|
leftDepartment.localeCompare(rightDepartment) ||
|
||||||
|
left.employee.employeeNo.localeCompare(right.employee.employeeNo) ||
|
||||||
|
left.employee.name.localeCompare(right.employee.name)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildCycleOverview(prisma, cycle) {
|
||||||
|
const reviews = await prisma.performanceReview.findMany({
|
||||||
|
where: { cycle_id: cycle.id },
|
||||||
|
include: {
|
||||||
|
...REVIEW_DETAIL_INCLUDE,
|
||||||
|
employee: {
|
||||||
|
select: EMPLOYEE_SUMMARY_SELECT,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const reviewByEmployeeId = new Map(reviews.map((item) => [item.employee_id, item]));
|
||||||
|
|
||||||
|
if (cycle.status === "completed") {
|
||||||
|
return sortEmployeeItems(
|
||||||
|
reviews.map((item) => ({
|
||||||
|
employee: mapEmployeeSummary(item.employee),
|
||||||
|
review: mapReview(item),
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const activeEmployees = await prisma.employee.findMany({
|
||||||
|
where: { status: "active" },
|
||||||
|
select: EMPLOYEE_SUMMARY_SELECT,
|
||||||
|
});
|
||||||
|
|
||||||
|
const items = activeEmployees.map((employee) => ({
|
||||||
|
employee: mapEmployeeSummary(employee),
|
||||||
|
review: reviewByEmployeeId.has(employee.id) ? mapReview(reviewByEmployeeId.get(employee.id)) : null,
|
||||||
|
}));
|
||||||
|
|
||||||
|
for (const review of reviews) {
|
||||||
|
if (!items.some((item) => item.employee.id === review.employee_id)) {
|
||||||
|
items.push({
|
||||||
|
employee: mapEmployeeSummary(review.employee),
|
||||||
|
review: mapReview(review),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return sortEmployeeItems(items);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildEmployeeTimeline(prisma, employeeId, viewerRole) {
|
||||||
|
const cycles = await prisma.performanceReviewCycle.findMany({
|
||||||
|
where:
|
||||||
|
viewerRole === "self"
|
||||||
|
? {
|
||||||
|
status: "completed",
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
status: {
|
||||||
|
in: ["active", "completed"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!cycles.length) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const reviews = await prisma.performanceReview.findMany({
|
||||||
|
where: {
|
||||||
|
employee_id: employeeId,
|
||||||
|
cycle_id: { in: cycles.map((item) => item.id) },
|
||||||
|
},
|
||||||
|
include: REVIEW_DETAIL_INCLUDE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const reviewByCycleId = new Map(reviews.map((item) => [item.cycle_id, item]));
|
||||||
|
const items = cycles
|
||||||
|
.map((cycle) => ({
|
||||||
|
cycle: mapCycle(cycle),
|
||||||
|
review: reviewByCycleId.has(cycle.id) ? mapReview(reviewByCycleId.get(cycle.id)) : null,
|
||||||
|
canEdit: viewerRole !== "self" && cycle.status === "active",
|
||||||
|
}))
|
||||||
|
.filter((item) => (viewerRole === "self" ? Boolean(item.review) : true));
|
||||||
|
|
||||||
|
return sortCycles(items.map((item) => ({ ...item, status: item.cycle.status, endDate: item.cycle.endDate, startDate: item.cycle.startDate }))).map(
|
||||||
|
({ status, endDate, startDate, ...item }) => item,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function performanceRoutes(fastify) {
|
||||||
|
fastify.get("/performance/cycles", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
if (!fastify.hasPermission(request.employee, "system.users")) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "system.users" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cycles = await fastify.prisma.performanceReviewCycle.findMany();
|
||||||
|
return sendData(reply, request, {
|
||||||
|
items: sortCycles(cycles.map(mapCycle)),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.post("/performance/cycles", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
if (!fastify.hasPermission(request.employee, "system.users")) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "system.users" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = parseBody(CYCLE_CREATE_SCHEMA, request.body);
|
||||||
|
validateCycleDates(body.startDate, body.endDate);
|
||||||
|
|
||||||
|
const cycle = await fastify.prisma.performanceReviewCycle.create({
|
||||||
|
data: {
|
||||||
|
name: body.name,
|
||||||
|
cycle_type: body.cycleType,
|
||||||
|
start_date: parseDateOnly(body.startDate),
|
||||||
|
end_date: parseDateOnly(body.endDate),
|
||||||
|
created_by: request.employee.id,
|
||||||
|
updated_by: request.employee.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await fastify.prisma.auditLog.create({
|
||||||
|
data: buildAuditLogData(request, {
|
||||||
|
actorId: request.employee.id,
|
||||||
|
action: "PERFORMANCE_REVIEW_CYCLE_CREATED",
|
||||||
|
targetType: "performance_review_cycle",
|
||||||
|
targetId: cycle.id,
|
||||||
|
extra: { status: cycle.status },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return sendData(reply, request, mapCycle(cycle));
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.patch("/performance/cycles/:cycleId", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
if (!fastify.hasPermission(request.employee, "system.users")) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "system.users" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cycleId = parseId(request.params?.cycleId);
|
||||||
|
const body = parseBody(CYCLE_PATCH_SCHEMA, request.body);
|
||||||
|
const current = await ensureCycleExists(fastify.prisma, cycleId);
|
||||||
|
const nextStartDate = body.startDate ?? current.start_date?.toISOString?.()?.slice(0, 10) ?? null;
|
||||||
|
const nextEndDate = body.endDate ?? current.end_date?.toISOString?.()?.slice(0, 10) ?? null;
|
||||||
|
validateCycleDates(nextStartDate, nextEndDate);
|
||||||
|
|
||||||
|
if (current.status === "completed") {
|
||||||
|
throw buildValidationError({ cycle: "completed_cycle_locked" }, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
let action = "PERFORMANCE_REVIEW_CYCLE_UPDATED";
|
||||||
|
let data;
|
||||||
|
|
||||||
|
if (current.status === "active") {
|
||||||
|
const invalidKeys = Object.keys(body).filter((key) => key !== "status");
|
||||||
|
if (invalidKeys.length > 0 || body.status !== "completed") {
|
||||||
|
throw buildValidationError({ cycle: "active_cycle_only_supports_complete" }, 409);
|
||||||
|
}
|
||||||
|
action = "PERFORMANCE_REVIEW_CYCLE_COMPLETED";
|
||||||
|
data = {
|
||||||
|
status: "completed",
|
||||||
|
completed_at: new Date(),
|
||||||
|
updated_by: request.employee.id,
|
||||||
|
};
|
||||||
|
} else {
|
||||||
|
if (body.status === "completed") {
|
||||||
|
throw buildValidationError({ cycle: "draft_cycle_cannot_complete_directly" }, 409);
|
||||||
|
}
|
||||||
|
if (body.status === "active") {
|
||||||
|
await ensureNoOtherActiveCycle(fastify.prisma, cycleId);
|
||||||
|
action = "PERFORMANCE_REVIEW_CYCLE_ACTIVATED";
|
||||||
|
}
|
||||||
|
|
||||||
|
data = {
|
||||||
|
...(body.name !== undefined ? { name: body.name } : {}),
|
||||||
|
...(body.cycleType !== undefined ? { cycle_type: body.cycleType } : {}),
|
||||||
|
...(body.startDate !== undefined ? { start_date: parseDateOnly(body.startDate) } : {}),
|
||||||
|
...(body.endDate !== undefined ? { end_date: parseDateOnly(body.endDate) } : {}),
|
||||||
|
...(body.status !== undefined ? { status: body.status } : {}),
|
||||||
|
...(body.status === "active" ? { activated_at: new Date() } : {}),
|
||||||
|
updated_by: request.employee.id,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let cycle;
|
||||||
|
try {
|
||||||
|
cycle = await fastify.prisma.performanceReviewCycle.update({
|
||||||
|
where: { id: cycleId },
|
||||||
|
data,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (body.status === "active" && isPrismaUniqueConstraintError(error)) {
|
||||||
|
throw buildValidationError({ cycle: "active_cycle_exists" }, 409);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
await fastify.prisma.auditLog.create({
|
||||||
|
data: buildAuditLogData(request, {
|
||||||
|
actorId: request.employee.id,
|
||||||
|
action,
|
||||||
|
targetType: "performance_review_cycle",
|
||||||
|
targetId: cycle.id,
|
||||||
|
extra: { status: cycle.status },
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return sendData(reply, request, mapCycle(cycle));
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get("/performance/cycles/:cycleId/reviews", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
if (!fastify.hasPermission(request.employee, "system.users")) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403, details: { permission: "system.users" } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const cycleId = parseId(request.params?.cycleId);
|
||||||
|
const cycle = await ensureCycleExists(fastify.prisma, cycleId);
|
||||||
|
const items = await buildCycleOverview(fastify.prisma, cycle);
|
||||||
|
|
||||||
|
return sendData(reply, request, {
|
||||||
|
cycle: mapCycle(cycle),
|
||||||
|
items,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.get("/performance/employees/:employeeId/reviews", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
const employeeId = parseId(request.params?.employeeId);
|
||||||
|
const employee = await ensureEmployeeExists(fastify.prisma, employeeId);
|
||||||
|
const viewerRole = resolveViewerRole(fastify, request, employee);
|
||||||
|
|
||||||
|
if (!viewerRole) {
|
||||||
|
throw new AppError({
|
||||||
|
code: "PERM_001",
|
||||||
|
message: "无权限",
|
||||||
|
statusCode: 403,
|
||||||
|
details: { permission: "performance.review.view" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = await buildEmployeeTimeline(fastify.prisma, employeeId, viewerRole);
|
||||||
|
|
||||||
|
return sendData(reply, request, {
|
||||||
|
employee: mapEmployeeSummary(employee),
|
||||||
|
viewerRole,
|
||||||
|
items,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.put("/performance/cycles/:cycleId/reviews/:employeeId", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||||
|
await ensureFeatureEnabled(fastify, request);
|
||||||
|
const cycleId = parseId(request.params?.cycleId);
|
||||||
|
const employeeId = parseId(request.params?.employeeId);
|
||||||
|
const body = parseBody(REVIEW_UPSERT_SCHEMA, request.body);
|
||||||
|
const employee = await ensureEmployeeExists(fastify.prisma, employeeId);
|
||||||
|
const viewerRole = resolveViewerRole(fastify, request, employee);
|
||||||
|
|
||||||
|
if (viewerRole !== "admin" && viewerRole !== "manager") {
|
||||||
|
throw new AppError({
|
||||||
|
code: "PERM_001",
|
||||||
|
message: "无权限",
|
||||||
|
statusCode: 403,
|
||||||
|
details: { permission: "performance.review.write" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (employee.status !== "active") {
|
||||||
|
throw buildValidationError({ employee: "inactive_employee_not_reviewable" }, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
await ensureCycleExists(fastify.prisma, cycleId);
|
||||||
|
|
||||||
|
const savedReview = await fastify.prisma.$transaction(async (tx) => {
|
||||||
|
const lockedCycle = await lockCycleForUpdate(tx, cycleId);
|
||||||
|
if (lockedCycle.status !== "active") {
|
||||||
|
throw buildValidationError({ cycle: "active_cycle_required" }, 409);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await tx.performanceReview.findFirst({
|
||||||
|
where: {
|
||||||
|
cycle_id: cycleId,
|
||||||
|
employee_id: employeeId,
|
||||||
|
},
|
||||||
|
include: REVIEW_DETAIL_INCLUDE,
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
reviewer_employee_id: request.employee.id,
|
||||||
|
overall_score: body.overallScore,
|
||||||
|
comment: body.comment?.trim() ? body.comment.trim() : null,
|
||||||
|
updated_by: request.employee.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
let reviewId = existing?.id ?? null;
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
await tx.performanceReview.update({
|
||||||
|
where: { id: existing.id },
|
||||||
|
data: payload,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const created = await tx.performanceReview.create({
|
||||||
|
data: {
|
||||||
|
cycle_id: cycleId,
|
||||||
|
employee_id: employeeId,
|
||||||
|
...payload,
|
||||||
|
created_by: request.employee.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
reviewId = created.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.performanceReviewDimension.deleteMany({
|
||||||
|
where: { review_id: reviewId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (body.dimensions.length > 0) {
|
||||||
|
await tx.performanceReviewDimension.createMany({
|
||||||
|
data: body.dimensions.map((item) => ({
|
||||||
|
review_id: reviewId,
|
||||||
|
dimension_type: item.dimensionType,
|
||||||
|
score: item.score,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.performanceReview.findUnique({
|
||||||
|
where: { id: reviewId },
|
||||||
|
include: REVIEW_DETAIL_INCLUDE,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await fastify.prisma.auditLog.create({
|
||||||
|
data: buildAuditLogData(request, {
|
||||||
|
actorId: request.employee.id,
|
||||||
|
action: "PERFORMANCE_REVIEW_UPSERTED",
|
||||||
|
targetType: "performance_review",
|
||||||
|
targetId: savedReview.id,
|
||||||
|
extra: {
|
||||||
|
cycleId,
|
||||||
|
employeeId,
|
||||||
|
reviewerRole: viewerRole,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return sendData(reply, request, mapReview(savedReview));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = performanceRoutes;
|
||||||
|
|
||||||
|
module.exports.__testables = {
|
||||||
|
buildCycleOverview,
|
||||||
|
buildEmployeeTimeline,
|
||||||
|
buildValidationError,
|
||||||
|
mapCycle,
|
||||||
|
mapEmployeeSummary,
|
||||||
|
mapReview,
|
||||||
|
resolveViewerRole,
|
||||||
|
sortCycles,
|
||||||
|
};
|
||||||
@@ -6,6 +6,22 @@ function addDays(date, days) {
|
|||||||
return next;
|
return next;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toNumber(value) {
|
||||||
|
return value == null ? null : Number(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPerformanceDistribution(rows) {
|
||||||
|
const countByScore = new Map(rows.map((item) => [toNumber(item.overall_score), item._count._all]));
|
||||||
|
const items = [];
|
||||||
|
for (let score = 1; score <= 5; score += 0.5) {
|
||||||
|
items.push({
|
||||||
|
score: Number(score.toFixed(1)),
|
||||||
|
count: countByScore.get(Number(score.toFixed(1))) ?? 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
async function buildEmployeeStats(prisma, options = {}) {
|
async function buildEmployeeStats(prisma, options = {}) {
|
||||||
const timeZone = options.timeZone ?? "Asia/Shanghai";
|
const timeZone = options.timeZone ?? "Asia/Shanghai";
|
||||||
const todayString = currentDateString(timeZone);
|
const todayString = currentDateString(timeZone);
|
||||||
@@ -14,7 +30,7 @@ async function buildEmployeeStats(prisma, options = {}) {
|
|||||||
const next30DateTo = addDays(today, 30);
|
const next30DateTo = addDays(today, 30);
|
||||||
const activeEmployeeWhere = { status: "active" };
|
const activeEmployeeWhere = { status: "active" };
|
||||||
|
|
||||||
const [employmentStatusRows, departmentRows, departments, recentHires, recentDepartures, expiringContracts, validCertificateHolders, expiringCertificates] = await Promise.all([
|
const [employmentStatusRows, departmentRows, departments, recentHires, recentDepartures, expiringContracts, validCertificateHolders, expiringCertificates, activeCycle, completedCycle] = await Promise.all([
|
||||||
prisma.employee.groupBy({
|
prisma.employee.groupBy({
|
||||||
by: ["employment_status"],
|
by: ["employment_status"],
|
||||||
where: activeEmployeeWhere,
|
where: activeEmployeeWhere,
|
||||||
@@ -78,9 +94,53 @@ async function buildEmployeeStats(prisma, options = {}) {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
|
prisma.performanceReviewCycle.findFirst({
|
||||||
|
where: { status: "active" },
|
||||||
|
orderBy: [{ activated_at: "desc" }, { start_date: "desc" }],
|
||||||
|
}),
|
||||||
|
prisma.performanceReviewCycle.findFirst({
|
||||||
|
where: { status: "completed" },
|
||||||
|
orderBy: [{ completed_at: "desc" }, { end_date: "desc" }],
|
||||||
|
}),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const departmentMap = new Map(departments.map((item) => [item.id, item.name]));
|
const departmentMap = new Map(departments.map((item) => [item.id, item.name]));
|
||||||
|
const performanceCycle = activeCycle ?? completedCycle ?? null;
|
||||||
|
let performanceSummary = {
|
||||||
|
cycle: null,
|
||||||
|
averageScore: null,
|
||||||
|
reviewedCount: 0,
|
||||||
|
distribution: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
if (performanceCycle) {
|
||||||
|
const [reviewAggregate, reviewDistribution] = await Promise.all([
|
||||||
|
prisma.performanceReview.aggregate({
|
||||||
|
where: { cycle_id: performanceCycle.id },
|
||||||
|
_avg: { overall_score: true },
|
||||||
|
_count: { _all: true },
|
||||||
|
}),
|
||||||
|
prisma.performanceReview.groupBy({
|
||||||
|
by: ["overall_score"],
|
||||||
|
where: { cycle_id: performanceCycle.id },
|
||||||
|
_count: { _all: true },
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
performanceSummary = {
|
||||||
|
cycle: {
|
||||||
|
id: performanceCycle.id,
|
||||||
|
name: performanceCycle.name,
|
||||||
|
cycleType: performanceCycle.cycle_type,
|
||||||
|
status: performanceCycle.status,
|
||||||
|
startDate: performanceCycle.start_date?.toISOString?.()?.slice(0, 10) ?? null,
|
||||||
|
endDate: performanceCycle.end_date?.toISOString?.()?.slice(0, 10) ?? null,
|
||||||
|
},
|
||||||
|
averageScore: toNumber(reviewAggregate._avg.overall_score),
|
||||||
|
reviewedCount: reviewAggregate._count._all,
|
||||||
|
distribution: buildPerformanceDistribution(reviewDistribution),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
asOfDate: todayString,
|
asOfDate: todayString,
|
||||||
@@ -117,6 +177,7 @@ async function buildEmployeeStats(prisma, options = {}) {
|
|||||||
validHolderCount: validCertificateHolders.length,
|
validHolderCount: validCertificateHolders.length,
|
||||||
expiringSoonCount: expiringCertificates,
|
expiringSoonCount: expiringCertificates,
|
||||||
},
|
},
|
||||||
|
performanceSummary,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,32 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
|||||||
{ employee_id: "emp-3" },
|
{ employee_id: "emp-3" },
|
||||||
]);
|
]);
|
||||||
const certificateCount = vi.fn().mockResolvedValue(4);
|
const certificateCount = vi.fn().mockResolvedValue(4);
|
||||||
|
const performanceCycleFindFirst = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
id: "cycle-active",
|
||||||
|
name: "2026 Q2",
|
||||||
|
cycle_type: "quarterly",
|
||||||
|
status: "active",
|
||||||
|
start_date: new Date("2026-04-01T00:00:00.000Z"),
|
||||||
|
end_date: new Date("2026-06-30T00:00:00.000Z"),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
id: "cycle-completed",
|
||||||
|
name: "2026 Q1",
|
||||||
|
cycle_type: "quarterly",
|
||||||
|
status: "completed",
|
||||||
|
start_date: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
end_date: new Date("2026-03-31T00:00:00.000Z"),
|
||||||
|
});
|
||||||
|
const performanceReviewAggregate = vi.fn().mockResolvedValue({
|
||||||
|
_avg: { overall_score: 4.2 },
|
||||||
|
_count: { _all: 5 },
|
||||||
|
});
|
||||||
|
const performanceReviewGroupBy = vi.fn().mockResolvedValue([
|
||||||
|
{ overall_score: 4, _count: { _all: 3 } },
|
||||||
|
{ overall_score: 4.5, _count: { _all: 2 } },
|
||||||
|
]);
|
||||||
|
|
||||||
app.decorate("prisma", {
|
app.decorate("prisma", {
|
||||||
employee: {
|
employee: {
|
||||||
@@ -47,6 +73,13 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
|||||||
count: stats?.employeeCertificateCount ?? certificateCount,
|
count: stats?.employeeCertificateCount ?? certificateCount,
|
||||||
findMany: vi.fn().mockResolvedValue([]),
|
findMany: vi.fn().mockResolvedValue([]),
|
||||||
},
|
},
|
||||||
|
performanceReviewCycle: {
|
||||||
|
findFirst: stats?.performanceReviewCycleFindFirst ?? performanceCycleFindFirst,
|
||||||
|
},
|
||||||
|
performanceReview: {
|
||||||
|
aggregate: stats?.performanceReviewAggregate ?? performanceReviewAggregate,
|
||||||
|
groupBy: stats?.performanceReviewGroupBy ?? performanceReviewGroupBy,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
app.decorate("authenticate", async (request) => {
|
app.decorate("authenticate", async (request) => {
|
||||||
request.employee = {
|
request.employee = {
|
||||||
@@ -79,12 +112,34 @@ async function buildApp({ permissionCodes = ["system.users"], stats } = {}) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
await app.register(employeesRoutes, { prefix: "/api" });
|
await app.register(employeesRoutes, { prefix: "/api" });
|
||||||
return { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount, certificateGroupBy, certificateCount };
|
return {
|
||||||
|
app,
|
||||||
|
employeeGroupBy,
|
||||||
|
employeeCount,
|
||||||
|
departmentFindMany,
|
||||||
|
contractCount,
|
||||||
|
certificateGroupBy,
|
||||||
|
certificateCount,
|
||||||
|
performanceCycleFindFirst,
|
||||||
|
performanceReviewAggregate,
|
||||||
|
performanceReviewGroupBy,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
describe("employees stats route", () => {
|
describe("employees stats route", () => {
|
||||||
it("returns aggregated employee stats for read-only viewers", async () => {
|
it("returns aggregated employee stats for read-only viewers", async () => {
|
||||||
const { app, employeeGroupBy, employeeCount, departmentFindMany, contractCount, certificateGroupBy, certificateCount } = await buildApp({
|
const {
|
||||||
|
app,
|
||||||
|
employeeGroupBy,
|
||||||
|
employeeCount,
|
||||||
|
departmentFindMany,
|
||||||
|
contractCount,
|
||||||
|
certificateGroupBy,
|
||||||
|
certificateCount,
|
||||||
|
performanceCycleFindFirst,
|
||||||
|
performanceReviewAggregate,
|
||||||
|
performanceReviewGroupBy,
|
||||||
|
} = await buildApp({
|
||||||
permissionCodes: ["report.dashboard.view"],
|
permissionCodes: ["report.dashboard.view"],
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -109,12 +164,38 @@ describe("employees stats route", () => {
|
|||||||
validHolderCount: 3,
|
validHolderCount: 3,
|
||||||
expiringSoonCount: 4,
|
expiringSoonCount: 4,
|
||||||
});
|
});
|
||||||
|
expect(payload.data.performanceSummary).toEqual({
|
||||||
|
cycle: {
|
||||||
|
id: "cycle-active",
|
||||||
|
name: "2026 Q2",
|
||||||
|
cycleType: "quarterly",
|
||||||
|
status: "active",
|
||||||
|
startDate: "2026-04-01",
|
||||||
|
endDate: "2026-06-30",
|
||||||
|
},
|
||||||
|
averageScore: 4.2,
|
||||||
|
reviewedCount: 5,
|
||||||
|
distribution: [
|
||||||
|
{ score: 1, count: 0 },
|
||||||
|
{ score: 1.5, count: 0 },
|
||||||
|
{ score: 2, count: 0 },
|
||||||
|
{ score: 2.5, count: 0 },
|
||||||
|
{ score: 3, count: 0 },
|
||||||
|
{ score: 3.5, count: 0 },
|
||||||
|
{ score: 4, count: 3 },
|
||||||
|
{ score: 4.5, count: 2 },
|
||||||
|
{ score: 5, count: 0 },
|
||||||
|
],
|
||||||
|
});
|
||||||
expect(employeeGroupBy).toHaveBeenCalledTimes(2);
|
expect(employeeGroupBy).toHaveBeenCalledTimes(2);
|
||||||
expect(employeeCount).toHaveBeenCalledTimes(2);
|
expect(employeeCount).toHaveBeenCalledTimes(2);
|
||||||
expect(departmentFindMany).toHaveBeenCalledTimes(1);
|
expect(departmentFindMany).toHaveBeenCalledTimes(1);
|
||||||
expect(contractCount).toHaveBeenCalledTimes(1);
|
expect(contractCount).toHaveBeenCalledTimes(1);
|
||||||
expect(certificateGroupBy).toHaveBeenCalledTimes(1);
|
expect(certificateGroupBy).toHaveBeenCalledTimes(1);
|
||||||
expect(certificateCount).toHaveBeenCalledTimes(1);
|
expect(certificateCount).toHaveBeenCalledTimes(1);
|
||||||
|
expect(performanceCycleFindFirst).toHaveBeenCalledTimes(2);
|
||||||
|
expect(performanceReviewAggregate).toHaveBeenCalledTimes(1);
|
||||||
|
expect(performanceReviewGroupBy).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
await app.close();
|
await app.close();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,248 @@
|
|||||||
|
const crypto = require("node:crypto");
|
||||||
|
const Fastify = require("fastify");
|
||||||
|
|
||||||
|
const performanceRoutes = require("../../../src/routes/performance");
|
||||||
|
const { AppError } = require("../../../src/utils/AppError");
|
||||||
|
|
||||||
|
const ADMIN_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||||
|
|
||||||
|
function buildFeatureFlagRecord() {
|
||||||
|
return {
|
||||||
|
id: "flag-1",
|
||||||
|
flag_key: "employee_lifecycle_v1",
|
||||||
|
override_mode: "force_on",
|
||||||
|
rollout_type: "global",
|
||||||
|
department_ids: [],
|
||||||
|
note: "",
|
||||||
|
version: 1,
|
||||||
|
created_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||||
|
created_by: null,
|
||||||
|
updated_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||||
|
updated_by: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCycleRow(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "11111111-1111-4111-8111-111111111111",
|
||||||
|
name: "2026 Q1",
|
||||||
|
cycle_type: "quarterly",
|
||||||
|
start_date: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
end_date: new Date("2026-03-31T00:00:00.000Z"),
|
||||||
|
status: "draft",
|
||||||
|
activated_at: null,
|
||||||
|
completed_at: null,
|
||||||
|
created_at: new Date("2026-03-29T08:00:00.000Z"),
|
||||||
|
created_by: ADMIN_ID,
|
||||||
|
updated_at: new Date("2026-03-29T08:00:00.000Z"),
|
||||||
|
updated_by: ADMIN_ID,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildApp({ actor = { id: ADMIN_ID, department_id: DEPARTMENT_ID, permissionCodes: ["system.users"] } } = {}) {
|
||||||
|
const app = Fastify();
|
||||||
|
const state = {
|
||||||
|
cycles: [],
|
||||||
|
};
|
||||||
|
const idSequence = [
|
||||||
|
"11111111-1111-4111-8111-111111111111",
|
||||||
|
"22222222-2222-4222-8222-222222222222",
|
||||||
|
"33333333-3333-4333-8333-333333333333",
|
||||||
|
];
|
||||||
|
|
||||||
|
const performanceReviewCycle = {
|
||||||
|
findMany: vi.fn(async () => [...state.cycles]),
|
||||||
|
findUnique: vi.fn(async ({ where }) => state.cycles.find((item) => item.id === where.id) ?? null),
|
||||||
|
findFirst: vi.fn(async ({ where }) => {
|
||||||
|
return (
|
||||||
|
state.cycles.find((item) => {
|
||||||
|
if (where.status && item.status !== where.status) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (where.id?.not && item.id === where.id.not) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}) ?? null
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
create: vi.fn(async ({ data }) => {
|
||||||
|
const cycle = buildCycleRow({
|
||||||
|
id: idSequence[state.cycles.length] ?? crypto.randomUUID(),
|
||||||
|
name: data.name,
|
||||||
|
cycle_type: data.cycle_type,
|
||||||
|
start_date: data.start_date,
|
||||||
|
end_date: data.end_date,
|
||||||
|
created_by: data.created_by,
|
||||||
|
updated_by: data.updated_by,
|
||||||
|
});
|
||||||
|
state.cycles.push(cycle);
|
||||||
|
return cycle;
|
||||||
|
}),
|
||||||
|
update: vi.fn(async ({ where, data }) => {
|
||||||
|
const index = state.cycles.findIndex((item) => item.id === where.id);
|
||||||
|
state.cycles[index] = {
|
||||||
|
...state.cycles[index],
|
||||||
|
...data,
|
||||||
|
updated_at: new Date("2026-03-29T09:00:00.000Z"),
|
||||||
|
};
|
||||||
|
return state.cycles[index];
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
app.decorate("config", { appTimezone: "Asia/Shanghai", employeeLifecycleEnabled: true });
|
||||||
|
app.decorate("authenticate", async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
});
|
||||||
|
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
const codes = actor.permissionCodes ?? [];
|
||||||
|
if (!codes.includes("*") && !codes.includes(permissionCode)) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||||
|
const codes = employee.permissionCodes ?? [];
|
||||||
|
return codes.includes("*") || codes.includes(permissionCode);
|
||||||
|
});
|
||||||
|
app.decorate("prisma", {
|
||||||
|
featureFlag: {
|
||||||
|
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||||
|
},
|
||||||
|
performanceReviewCycle,
|
||||||
|
auditLog: {
|
||||||
|
create: vi.fn().mockResolvedValue({}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
app.setErrorHandler((error, request, reply) => {
|
||||||
|
reply.status(error.statusCode || 500).send({
|
||||||
|
requestId: request.id,
|
||||||
|
error: {
|
||||||
|
code: error.code || "SYS_001",
|
||||||
|
message: error.message,
|
||||||
|
details: error.details ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(performanceRoutes, { prefix: "/api" });
|
||||||
|
return { app, state, performanceReviewCycle };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("performance cycle routes", () => {
|
||||||
|
it("allows admins to create, update, activate and complete cycles with a single active cycle guard", async () => {
|
||||||
|
const { app, state, performanceReviewCycle } = await buildApp();
|
||||||
|
|
||||||
|
const createResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/performance/cycles",
|
||||||
|
payload: {
|
||||||
|
name: "2026 Q1",
|
||||||
|
cycleType: "quarterly",
|
||||||
|
startDate: "2026-01-01",
|
||||||
|
endDate: "2026-03-31",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(createResponse.statusCode).toBe(200);
|
||||||
|
expect(createResponse.json().data).toMatchObject({
|
||||||
|
name: "2026 Q1",
|
||||||
|
cycleType: "quarterly",
|
||||||
|
status: "draft",
|
||||||
|
});
|
||||||
|
|
||||||
|
const patchResponse = await app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: `/api/performance/cycles/${state.cycles[0].id}`,
|
||||||
|
payload: {
|
||||||
|
name: "2026 Q1 调整版",
|
||||||
|
endDate: "2026-04-05",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(patchResponse.statusCode).toBe(200);
|
||||||
|
expect(patchResponse.json().data).toMatchObject({
|
||||||
|
name: "2026 Q1 调整版",
|
||||||
|
endDate: "2026-04-05",
|
||||||
|
status: "draft",
|
||||||
|
});
|
||||||
|
|
||||||
|
const activateResponse = await app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: `/api/performance/cycles/${state.cycles[0].id}`,
|
||||||
|
payload: {
|
||||||
|
status: "active",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(activateResponse.statusCode).toBe(200);
|
||||||
|
expect(activateResponse.json().data).toMatchObject({
|
||||||
|
status: "active",
|
||||||
|
});
|
||||||
|
|
||||||
|
const secondCreateResponse = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/api/performance/cycles",
|
||||||
|
payload: {
|
||||||
|
name: "2026 Q2",
|
||||||
|
cycleType: "quarterly",
|
||||||
|
startDate: "2026-04-01",
|
||||||
|
endDate: "2026-06-30",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(secondCreateResponse.statusCode).toBe(200);
|
||||||
|
|
||||||
|
const secondActivateResponse = await app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: `/api/performance/cycles/${state.cycles[1].id}`,
|
||||||
|
payload: {
|
||||||
|
status: "active",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(secondActivateResponse.statusCode).toBe(409);
|
||||||
|
expect(secondActivateResponse.json().error.details).toMatchObject({
|
||||||
|
cycle: "active_cycle_exists",
|
||||||
|
activeCycleId: state.cycles[0].id,
|
||||||
|
});
|
||||||
|
|
||||||
|
const completeResponse = await app.inject({
|
||||||
|
method: "PATCH",
|
||||||
|
url: `/api/performance/cycles/${state.cycles[0].id}`,
|
||||||
|
payload: {
|
||||||
|
status: "completed",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(completeResponse.statusCode).toBe(200);
|
||||||
|
expect(completeResponse.json().data).toMatchObject({
|
||||||
|
status: "completed",
|
||||||
|
});
|
||||||
|
expect(performanceReviewCycle.create).toHaveBeenCalledTimes(2);
|
||||||
|
expect(performanceReviewCycle.update).toHaveBeenCalledTimes(3);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-admin users", async () => {
|
||||||
|
const { app } = await buildApp({
|
||||||
|
actor: {
|
||||||
|
id: "employee-1",
|
||||||
|
department_id: DEPARTMENT_ID,
|
||||||
|
permissionCodes: ["employee"],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: "/api/performance/cycles",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(403);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
const Fastify = require("fastify");
|
||||||
|
|
||||||
|
const performanceRoutes = require("../../../src/routes/performance");
|
||||||
|
const { AppError } = require("../../../src/utils/AppError");
|
||||||
|
|
||||||
|
const ADMIN_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||||
|
const MANAGER_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||||
|
const EMPLOYEE_ID = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
|
||||||
|
const OTHER_EMPLOYEE_ID = "dddddddd-dddd-4ddd-8ddd-dddddddddddd";
|
||||||
|
const DEPARTMENT_ID = "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee";
|
||||||
|
const ACTIVE_CYCLE_ID = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const COMPLETED_CYCLE_ID = "22222222-2222-4222-8222-222222222222";
|
||||||
|
|
||||||
|
function buildFeatureFlagRecord() {
|
||||||
|
return {
|
||||||
|
id: "flag-1",
|
||||||
|
flag_key: "employee_lifecycle_v1",
|
||||||
|
override_mode: "force_on",
|
||||||
|
rollout_type: "global",
|
||||||
|
department_ids: [],
|
||||||
|
note: "",
|
||||||
|
version: 1,
|
||||||
|
created_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||||
|
created_by: null,
|
||||||
|
updated_at: new Date("2026-03-28T00:00:00.000Z"),
|
||||||
|
updated_by: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildCycleRow(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: ACTIVE_CYCLE_ID,
|
||||||
|
name: "2026 Q2",
|
||||||
|
cycle_type: "quarterly",
|
||||||
|
start_date: new Date("2026-04-01T00:00:00.000Z"),
|
||||||
|
end_date: new Date("2026-06-30T00:00:00.000Z"),
|
||||||
|
status: "active",
|
||||||
|
activated_at: new Date("2026-04-01T00:00:00.000Z"),
|
||||||
|
completed_at: null,
|
||||||
|
created_at: new Date("2026-03-29T08:00:00.000Z"),
|
||||||
|
created_by: ADMIN_ID,
|
||||||
|
updated_at: new Date("2026-03-29T08:00:00.000Z"),
|
||||||
|
updated_by: ADMIN_ID,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEmployeeRow(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: EMPLOYEE_ID,
|
||||||
|
employee_no: "E001",
|
||||||
|
name: "Alice",
|
||||||
|
title: "专员",
|
||||||
|
status: "active",
|
||||||
|
direct_manager_id: MANAGER_ID,
|
||||||
|
avatar_path: null,
|
||||||
|
department: { id: DEPARTMENT_ID, name: "行政部" },
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildReviewRow(overrides = {}) {
|
||||||
|
return {
|
||||||
|
id: "33333333-3333-4333-8333-333333333333",
|
||||||
|
cycle_id: COMPLETED_CYCLE_ID,
|
||||||
|
employee_id: EMPLOYEE_ID,
|
||||||
|
reviewer_employee_id: MANAGER_ID,
|
||||||
|
overall_score: 4,
|
||||||
|
comment: "完成良好",
|
||||||
|
created_at: new Date("2026-03-28T08:00:00.000Z"),
|
||||||
|
created_by: MANAGER_ID,
|
||||||
|
updated_at: new Date("2026-03-28T08:00:00.000Z"),
|
||||||
|
updated_by: MANAGER_ID,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function buildApp({
|
||||||
|
actor = { id: MANAGER_ID, department_id: DEPARTMENT_ID, permissionCodes: ["employee"] },
|
||||||
|
} = {}) {
|
||||||
|
const app = Fastify();
|
||||||
|
const state = {
|
||||||
|
cycles: [
|
||||||
|
buildCycleRow(),
|
||||||
|
buildCycleRow({
|
||||||
|
id: COMPLETED_CYCLE_ID,
|
||||||
|
name: "2026 Q1",
|
||||||
|
start_date: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
end_date: new Date("2026-03-31T00:00:00.000Z"),
|
||||||
|
status: "completed",
|
||||||
|
activated_at: new Date("2026-01-01T00:00:00.000Z"),
|
||||||
|
completed_at: new Date("2026-03-31T10:00:00.000Z"),
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
employees: [
|
||||||
|
buildEmployeeRow(),
|
||||||
|
buildEmployeeRow({
|
||||||
|
id: MANAGER_ID,
|
||||||
|
employee_no: "M001",
|
||||||
|
name: "Bob",
|
||||||
|
title: "经理",
|
||||||
|
direct_manager_id: null,
|
||||||
|
}),
|
||||||
|
buildEmployeeRow({
|
||||||
|
id: OTHER_EMPLOYEE_ID,
|
||||||
|
employee_no: "E002",
|
||||||
|
name: "Carol",
|
||||||
|
direct_manager_id: ADMIN_ID,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
reviews: [buildReviewRow()],
|
||||||
|
dimensions: [
|
||||||
|
{
|
||||||
|
id: "dim-1",
|
||||||
|
review_id: "33333333-3333-4333-8333-333333333333",
|
||||||
|
dimension_type: "work_quality",
|
||||||
|
score: 4,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
function hydrateReview(review) {
|
||||||
|
const employee = state.employees.find((item) => item.id === review.employee_id);
|
||||||
|
const reviewer = state.employees.find((item) => item.id === review.reviewer_employee_id);
|
||||||
|
return {
|
||||||
|
...review,
|
||||||
|
employee,
|
||||||
|
reviewer_employee: reviewer
|
||||||
|
? {
|
||||||
|
id: reviewer.id,
|
||||||
|
employee_no: reviewer.employee_no,
|
||||||
|
name: reviewer.name,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
dimensions: state.dimensions.filter((item) => item.review_id === review.id),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const performanceReview = {
|
||||||
|
findMany: vi.fn(async ({ where }) => {
|
||||||
|
let rows = [...state.reviews];
|
||||||
|
if (typeof where?.cycle_id === "string") {
|
||||||
|
rows = rows.filter((item) => item.cycle_id === where.cycle_id);
|
||||||
|
}
|
||||||
|
if (where?.cycle_id?.in) {
|
||||||
|
rows = rows.filter((item) => where.cycle_id.in.includes(item.cycle_id));
|
||||||
|
}
|
||||||
|
if (where?.employee_id) {
|
||||||
|
rows = rows.filter((item) => item.employee_id === where.employee_id);
|
||||||
|
}
|
||||||
|
return rows.map(hydrateReview);
|
||||||
|
}),
|
||||||
|
findFirst: vi.fn(async ({ where }) => {
|
||||||
|
const review = state.reviews.find((item) => item.cycle_id === where.cycle_id && item.employee_id === where.employee_id);
|
||||||
|
return review ? hydrateReview(review) : null;
|
||||||
|
}),
|
||||||
|
findUnique: vi.fn(async ({ where }) => {
|
||||||
|
const review = state.reviews.find((item) => item.id === where.id);
|
||||||
|
return review ? hydrateReview(review) : null;
|
||||||
|
}),
|
||||||
|
create: vi.fn(async ({ data }) => {
|
||||||
|
const review = buildReviewRow({
|
||||||
|
id: "44444444-4444-4444-8444-444444444444",
|
||||||
|
cycle_id: data.cycle_id,
|
||||||
|
employee_id: data.employee_id,
|
||||||
|
reviewer_employee_id: data.reviewer_employee_id,
|
||||||
|
overall_score: data.overall_score,
|
||||||
|
comment: data.comment,
|
||||||
|
created_by: data.created_by,
|
||||||
|
updated_by: data.updated_by,
|
||||||
|
});
|
||||||
|
state.reviews.push(review);
|
||||||
|
return review;
|
||||||
|
}),
|
||||||
|
update: vi.fn(async ({ where, data }) => {
|
||||||
|
const index = state.reviews.findIndex((item) => item.id === where.id);
|
||||||
|
state.reviews[index] = {
|
||||||
|
...state.reviews[index],
|
||||||
|
...data,
|
||||||
|
};
|
||||||
|
return state.reviews[index];
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const performanceReviewDimension = {
|
||||||
|
deleteMany: vi.fn(async ({ where }) => {
|
||||||
|
state.dimensions = state.dimensions.filter((item) => item.review_id !== where.review_id);
|
||||||
|
return { count: 1 };
|
||||||
|
}),
|
||||||
|
createMany: vi.fn(async ({ data }) => {
|
||||||
|
state.dimensions.push(
|
||||||
|
...data.map((item, index) => ({
|
||||||
|
id: `dim-${state.dimensions.length + index + 1}`,
|
||||||
|
review_id: item.review_id,
|
||||||
|
dimension_type: item.dimension_type,
|
||||||
|
score: item.score,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
return { count: data.length };
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
app.decorate("config", { appTimezone: "Asia/Shanghai", employeeLifecycleEnabled: true });
|
||||||
|
app.decorate("authenticate", async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
});
|
||||||
|
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||||
|
request.employee = actor;
|
||||||
|
const codes = actor.permissionCodes ?? [];
|
||||||
|
if (!codes.includes("*") && !codes.includes(permissionCode)) {
|
||||||
|
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||||
|
const codes = employee.permissionCodes ?? [];
|
||||||
|
return codes.includes("*") || codes.includes(permissionCode);
|
||||||
|
});
|
||||||
|
app.decorate("prisma", {
|
||||||
|
featureFlag: {
|
||||||
|
findUnique: vi.fn().mockResolvedValue(buildFeatureFlagRecord()),
|
||||||
|
},
|
||||||
|
employee: {
|
||||||
|
findUnique: vi.fn(async ({ where }) => state.employees.find((item) => item.id === where.id) ?? null),
|
||||||
|
findMany: vi.fn(async ({ where }) => {
|
||||||
|
if (where?.status === "active") {
|
||||||
|
return state.employees.filter((item) => item.status === "active");
|
||||||
|
}
|
||||||
|
return [...state.employees];
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
performanceReviewCycle: {
|
||||||
|
findMany: vi.fn(async ({ where }) =>
|
||||||
|
state.cycles.filter((item) => {
|
||||||
|
if (!where) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (where?.status?.in) {
|
||||||
|
return where.status.in.includes(item.status);
|
||||||
|
}
|
||||||
|
return item.status === where?.status;
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
findUnique: vi.fn(async ({ where }) => state.cycles.find((item) => item.id === where.id) ?? null),
|
||||||
|
findFirst: vi.fn(async ({ where }) =>
|
||||||
|
state.cycles.find((item) => {
|
||||||
|
if (where?.status && item.status !== where.status) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (where?.id?.not && item.id === where.id.not) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}) ?? null,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
performanceReview,
|
||||||
|
performanceReviewDimension,
|
||||||
|
auditLog: {
|
||||||
|
create: vi.fn().mockResolvedValue({}),
|
||||||
|
},
|
||||||
|
$transaction: vi.fn(async (callback) => callback(app.prisma)),
|
||||||
|
});
|
||||||
|
app.setErrorHandler((error, request, reply) => {
|
||||||
|
reply.status(error.statusCode || 500).send({
|
||||||
|
requestId: request.id,
|
||||||
|
error: {
|
||||||
|
code: error.code || "SYS_001",
|
||||||
|
message: error.message,
|
||||||
|
details: error.details ?? null,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.register(performanceRoutes, { prefix: "/api" });
|
||||||
|
return { app, state, performanceReview, performanceReviewDimension };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("performance review routes", () => {
|
||||||
|
it("allows direct managers to score direct reports in active cycles", async () => {
|
||||||
|
const { app, state, performanceReviewDimension } = await buildApp();
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: `/api/performance/cycles/${ACTIVE_CYCLE_ID}/reviews/${EMPLOYEE_ID}`,
|
||||||
|
payload: {
|
||||||
|
overallScore: 4.5,
|
||||||
|
comment: "表现稳定",
|
||||||
|
dimensions: [
|
||||||
|
{ dimensionType: "work_quality", score: 4.5 },
|
||||||
|
{ dimensionType: "teamwork", score: 4 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
expect(response.json().data).toMatchObject({
|
||||||
|
employeeId: EMPLOYEE_ID,
|
||||||
|
overallScore: 4.5,
|
||||||
|
comment: "表现稳定",
|
||||||
|
dimensions: [
|
||||||
|
{ dimensionType: "work_quality", score: 4.5 },
|
||||||
|
{ dimensionType: "teamwork", score: 4 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(state.reviews.find((item) => item.cycle_id === ACTIVE_CYCLE_ID && item.employee_id === EMPLOYEE_ID)).toBeTruthy();
|
||||||
|
expect(performanceReviewDimension.createMany).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns completed results only for self viewers", async () => {
|
||||||
|
const { app } = await buildApp({
|
||||||
|
actor: {
|
||||||
|
id: EMPLOYEE_ID,
|
||||||
|
department_id: DEPARTMENT_ID,
|
||||||
|
permissionCodes: ["employee"],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/api/performance/employees/${EMPLOYEE_ID}/reviews`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
expect(response.json().data.viewerRole).toBe("self");
|
||||||
|
expect(response.json().data.items).toHaveLength(1);
|
||||||
|
expect(response.json().data.items[0].cycle.status).toBe("completed");
|
||||||
|
expect(response.json().data.items[0].review.overallScore).toBe(4);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects non-manager non-admin access to other employees", async () => {
|
||||||
|
const { app } = await buildApp({
|
||||||
|
actor: {
|
||||||
|
id: OTHER_EMPLOYEE_ID,
|
||||||
|
department_id: DEPARTMENT_ID,
|
||||||
|
permissionCodes: ["employee"],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: `/api/performance/cycles/${ACTIVE_CYCLE_ID}/reviews/${EMPLOYEE_ID}`,
|
||||||
|
payload: {
|
||||||
|
overallScore: 4,
|
||||||
|
comment: "无权限",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(403);
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("blocks updates on completed cycles and lets admins inspect cycle overviews", async () => {
|
||||||
|
const { app } = await buildApp({
|
||||||
|
actor: {
|
||||||
|
id: ADMIN_ID,
|
||||||
|
department_id: DEPARTMENT_ID,
|
||||||
|
permissionCodes: ["system.users"],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const overviewResponse = await app.inject({
|
||||||
|
method: "GET",
|
||||||
|
url: `/api/performance/cycles/${ACTIVE_CYCLE_ID}/reviews`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(overviewResponse.statusCode).toBe(200);
|
||||||
|
expect(overviewResponse.json().data.items).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
employee: expect.objectContaining({ id: EMPLOYEE_ID }),
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const completedResponse = await app.inject({
|
||||||
|
method: "PUT",
|
||||||
|
url: `/api/performance/cycles/${COMPLETED_CYCLE_ID}/reviews/${EMPLOYEE_ID}`,
|
||||||
|
payload: {
|
||||||
|
overallScore: 4.5,
|
||||||
|
comment: "不允许修改",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(completedResponse.statusCode).toBe(409);
|
||||||
|
expect(completedResponse.json().error.details).toMatchObject({
|
||||||
|
cycle: "active_cycle_required",
|
||||||
|
});
|
||||||
|
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
在新工单中引用
屏蔽一个用户