R42: 完成考勤增强首轮交付
这个提交包含在:
+92
-2
@@ -1,8 +1,9 @@
|
||||
import { apiRequestData } from "./http";
|
||||
import { apiRequestBlob, apiRequestData, type ApiBlobResponse } from "./http";
|
||||
|
||||
export type PresenceStatus = "office" | "remote" | "out" | "travel" | "leave";
|
||||
export type PresenceTimeRange = "full_day" | "morning" | "afternoon";
|
||||
export type PresenceSource = "manual" | "leave_sync";
|
||||
export type PresenceSource = "manual" | "leave_sync" | "admin_override";
|
||||
export type PresenceHistoryStatusFilter = PresenceStatus | "unspecified";
|
||||
|
||||
export type PresenceItem = {
|
||||
id: string;
|
||||
@@ -29,6 +30,17 @@ export type TeamPresenceItem = {
|
||||
presence: PresenceItem | null;
|
||||
};
|
||||
|
||||
export type MyPresenceHistoryItem = {
|
||||
date: string;
|
||||
presence: PresenceItem | null;
|
||||
};
|
||||
|
||||
export type TeamPresenceHistoryItem = {
|
||||
date: string;
|
||||
employee: PresenceEmployee;
|
||||
presence: PresenceItem | null;
|
||||
};
|
||||
|
||||
export type PresenceSummary = {
|
||||
office: number;
|
||||
remote: number;
|
||||
@@ -39,6 +51,20 @@ export type PresenceSummary = {
|
||||
total: number;
|
||||
};
|
||||
|
||||
export type MyPresenceHistoryResponse = {
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
summary: PresenceSummary;
|
||||
items: MyPresenceHistoryItem[];
|
||||
};
|
||||
|
||||
export type TeamPresenceHistoryResponse = {
|
||||
dateFrom: string;
|
||||
dateTo: string;
|
||||
summary: PresenceSummary;
|
||||
items: TeamPresenceHistoryItem[];
|
||||
};
|
||||
|
||||
export async function fetchMyPresence(date?: string) {
|
||||
const suffix = date ? `?date=${encodeURIComponent(date)}` : "";
|
||||
return apiRequestData<{ item: PresenceItem | null; date: string }>(`/api/presence/me${suffix}`);
|
||||
@@ -61,7 +87,71 @@ export async function fetchTeamPresence(date?: string) {
|
||||
return apiRequestData<{ date: string; summary: PresenceSummary; items: TeamPresenceItem[] }>(`/api/presence/team${suffix}`);
|
||||
}
|
||||
|
||||
export async function fetchMyPresenceHistory(params: {
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
}) {
|
||||
const search = new URLSearchParams();
|
||||
if (params.dateFrom) search.set("dateFrom", params.dateFrom);
|
||||
if (params.dateTo) search.set("dateTo", params.dateTo);
|
||||
|
||||
const query = search.toString();
|
||||
return apiRequestData<MyPresenceHistoryResponse>(`/api/presence/me/history${query ? `?${query}` : ""}`);
|
||||
}
|
||||
|
||||
export async function fetchTeamPresenceHistory(params: {
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
departmentId?: string;
|
||||
employeeId?: string;
|
||||
status?: PresenceHistoryStatusFilter;
|
||||
}) {
|
||||
const search = new URLSearchParams();
|
||||
if (params.dateFrom) search.set("dateFrom", params.dateFrom);
|
||||
if (params.dateTo) search.set("dateTo", params.dateTo);
|
||||
if (params.departmentId) search.set("departmentId", params.departmentId);
|
||||
if (params.employeeId) search.set("employeeId", params.employeeId);
|
||||
if (params.status) search.set("status", params.status);
|
||||
|
||||
const query = search.toString();
|
||||
return apiRequestData<TeamPresenceHistoryResponse>(`/api/presence/team/history${query ? `?${query}` : ""}`);
|
||||
}
|
||||
|
||||
export async function fetchPresenceSummary(date?: string) {
|
||||
const suffix = date ? `?date=${encodeURIComponent(date)}` : "";
|
||||
return apiRequestData<{ date: string; summary: PresenceSummary }>(`/api/presence/summary${suffix}`);
|
||||
}
|
||||
|
||||
export async function exportPresenceHistory(params: {
|
||||
format: "csv" | "xlsx";
|
||||
dateFrom?: string;
|
||||
dateTo?: string;
|
||||
departmentId?: string;
|
||||
employeeId?: string;
|
||||
status?: PresenceHistoryStatusFilter;
|
||||
}): Promise<ApiBlobResponse> {
|
||||
const search = new URLSearchParams();
|
||||
search.set("format", params.format);
|
||||
if (params.dateFrom) search.set("dateFrom", params.dateFrom);
|
||||
if (params.dateTo) search.set("dateTo", params.dateTo);
|
||||
if (params.departmentId) search.set("departmentId", params.departmentId);
|
||||
if (params.employeeId) search.set("employeeId", params.employeeId);
|
||||
if (params.status) search.set("status", params.status);
|
||||
|
||||
return apiRequestBlob(`/api/exports/presence-history?${search.toString()}`);
|
||||
}
|
||||
|
||||
export async function patchTeamPresence(
|
||||
employeeId: string,
|
||||
payload: {
|
||||
date: string;
|
||||
status: Extract<PresenceStatus, "office" | "remote" | "out" | "travel">;
|
||||
timeRange?: PresenceTimeRange;
|
||||
note?: string | null;
|
||||
},
|
||||
) {
|
||||
return apiRequestData<{ item: PresenceItem }>(`/api/presence/team/${employeeId}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,13 +1,48 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { fetchMyPresence, fetchTeamPresence, upsertMyPresence } from "../api/presence";
|
||||
import { fetchDepartments } from "../api/departments";
|
||||
import {
|
||||
exportPresenceHistory,
|
||||
fetchMyPresence,
|
||||
fetchMyPresenceHistory,
|
||||
fetchTeamPresence,
|
||||
fetchTeamPresenceHistory,
|
||||
patchTeamPresence,
|
||||
type PresenceHistoryStatusFilter,
|
||||
type PresenceEmployee,
|
||||
type PresenceStatus,
|
||||
type PresenceTimeRange,
|
||||
type TeamPresenceHistoryItem,
|
||||
upsertMyPresence,
|
||||
} from "../api/presence";
|
||||
import { mapApiErrorMessage } from "../api/errorMessages";
|
||||
import { isApiError } from "../api/types";
|
||||
import { useAuth } from "../auth/AuthContext";
|
||||
import { hasPermission } from "../auth/permissions";
|
||||
import { PageHeader } from "../components/common/PageHeader";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "../components/ui/dialog";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "../components/ui/dropdown-menu";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../components/ui/table";
|
||||
import { Textarea } from "../components/ui/textarea";
|
||||
import { downloadBlob } from "../lib/download";
|
||||
import { toast } from "sonner";
|
||||
import { isApiError } from "../api/types";
|
||||
import { mapApiErrorMessage } from "../api/errorMessages";
|
||||
|
||||
type ViewMode = "today" | "history";
|
||||
type EditablePresenceStatus = Extract<PresenceStatus, "office" | "remote" | "out" | "travel">;
|
||||
|
||||
function statusLabel(status: string | null) {
|
||||
if (status === "office") return "在岗";
|
||||
@@ -18,15 +53,108 @@ function statusLabel(status: string | null) {
|
||||
return "未更新";
|
||||
}
|
||||
|
||||
function timeRangeLabel(value: string | null | undefined) {
|
||||
if (value === "morning") return "上午";
|
||||
if (value === "afternoon") return "下午";
|
||||
if (value === "full_day") return "全天";
|
||||
return "-";
|
||||
}
|
||||
|
||||
function sourceLabel(value: string | null | undefined) {
|
||||
if (value === "manual") return "手工";
|
||||
if (value === "leave_sync") return "审批同步";
|
||||
if (value === "admin_override") return "管理员修正";
|
||||
return "-";
|
||||
}
|
||||
|
||||
function currentDateString() {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function offsetDateString(offsetDays: number) {
|
||||
const next = new Date();
|
||||
next.setUTCDate(next.getUTCDate() + offsetDays);
|
||||
return next.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function resolveErrorMessage(error: unknown, fallback = "加载失败") {
|
||||
if (isApiError(error)) {
|
||||
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
|
||||
}
|
||||
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function resolveEditableStatus(item: TeamPresenceHistoryItem | null): EditablePresenceStatus {
|
||||
if (!item?.presence) {
|
||||
return "office";
|
||||
}
|
||||
if (item.presence.status === "office" || item.presence.status === "remote" || item.presence.status === "out" || item.presence.status === "travel") {
|
||||
return item.presence.status;
|
||||
}
|
||||
return "office";
|
||||
}
|
||||
|
||||
export function TeamPresencePage() {
|
||||
const { permissions } = useAuth();
|
||||
const canManagePresence = hasPermission(permissions, "system.users");
|
||||
const queryClient = useQueryClient();
|
||||
const [viewMode, setViewMode] = useState<ViewMode>("today");
|
||||
const [date, setDate] = useState("");
|
||||
const [note, setNote] = useState("");
|
||||
const [status, setStatus] = useState<"office" | "remote" | "out" | "travel">("office");
|
||||
const [status, setStatus] = useState<EditablePresenceStatus>("office");
|
||||
const [filter, setFilter] = useState<"all" | "onsite" | "away">("all");
|
||||
const [historyDateFrom, setHistoryDateFrom] = useState(offsetDateString(-6));
|
||||
const [historyDateTo, setHistoryDateTo] = useState(currentDateString());
|
||||
const [historyDepartmentId, setHistoryDepartmentId] = useState("");
|
||||
const [historyEmployeeId, setHistoryEmployeeId] = useState("");
|
||||
const [historyStatus, setHistoryStatus] = useState<"" | PresenceHistoryStatusFilter>("");
|
||||
const [correctionTarget, setCorrectionTarget] = useState<TeamPresenceHistoryItem | null>(null);
|
||||
const [correctionStatus, setCorrectionStatus] = useState<EditablePresenceStatus>("office");
|
||||
const [correctionTimeRange, setCorrectionTimeRange] = useState<PresenceTimeRange>("full_day");
|
||||
const [correctionNote, setCorrectionNote] = useState("");
|
||||
|
||||
const myPresenceQuery = useQuery({ queryKey: ["presence", "me", date], queryFn: () => fetchMyPresence(date || undefined) });
|
||||
const teamPresenceQuery = useQuery({ queryKey: ["presence", "team", date], queryFn: () => fetchTeamPresence(date || undefined) });
|
||||
const departmentsQuery = useQuery({
|
||||
enabled: viewMode === "history",
|
||||
queryKey: ["departments", "team-presence-history", "active"],
|
||||
queryFn: () => fetchDepartments({ includeArchived: false }),
|
||||
});
|
||||
const myHistoryQuery = useQuery({
|
||||
enabled: viewMode === "history",
|
||||
queryKey: ["presence", "me", "history", historyDateFrom, historyDateTo],
|
||||
queryFn: () =>
|
||||
fetchMyPresenceHistory({
|
||||
dateFrom: historyDateFrom || undefined,
|
||||
dateTo: historyDateTo || undefined,
|
||||
}),
|
||||
});
|
||||
const teamHistoryQuery = useQuery({
|
||||
enabled: viewMode === "history",
|
||||
queryKey: [
|
||||
"presence",
|
||||
"team",
|
||||
"history",
|
||||
historyDateFrom,
|
||||
historyDateTo,
|
||||
historyDepartmentId,
|
||||
historyEmployeeId,
|
||||
historyStatus,
|
||||
],
|
||||
queryFn: () =>
|
||||
fetchTeamPresenceHistory({
|
||||
dateFrom: historyDateFrom || undefined,
|
||||
dateTo: historyDateTo || undefined,
|
||||
departmentId: historyDepartmentId || undefined,
|
||||
employeeId: historyEmployeeId || undefined,
|
||||
status: historyStatus || undefined,
|
||||
}),
|
||||
});
|
||||
|
||||
const mutation = useMutation({
|
||||
mutationFn: () => upsertMyPresence({ date: date || undefined, status, note: note || undefined }),
|
||||
@@ -39,12 +167,51 @@ export function TeamPresencePage() {
|
||||
toast.success("今日状态已更新");
|
||||
},
|
||||
onError: (error) => {
|
||||
const message = isApiError(error)
|
||||
? `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`
|
||||
: error instanceof Error
|
||||
? error.message
|
||||
: "更新失败";
|
||||
toast.error(message);
|
||||
toast.error(resolveErrorMessage(error, "更新失败"));
|
||||
},
|
||||
});
|
||||
|
||||
const exportMutation = useMutation({
|
||||
mutationFn: (format: "csv" | "xlsx") =>
|
||||
exportPresenceHistory({
|
||||
format,
|
||||
dateFrom: historyDateFrom || undefined,
|
||||
dateTo: historyDateTo || undefined,
|
||||
departmentId: historyDepartmentId || undefined,
|
||||
employeeId: historyEmployeeId || undefined,
|
||||
status: historyStatus || undefined,
|
||||
}),
|
||||
onSuccess: (response, format) => {
|
||||
downloadBlob(response.blob, response.filename ?? `presence-history.${format}`);
|
||||
toast.success("导出完成");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(resolveErrorMessage(error, "导出失败"));
|
||||
},
|
||||
});
|
||||
|
||||
const correctionMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!correctionTarget) {
|
||||
throw new Error("请先选择要修正的历史记录");
|
||||
}
|
||||
return patchTeamPresence(correctionTarget.employee.id, {
|
||||
date: correctionTarget.date,
|
||||
status: correctionStatus,
|
||||
timeRange: correctionTimeRange,
|
||||
note: correctionNote.trim() ? correctionNote.trim() : null,
|
||||
});
|
||||
},
|
||||
onSuccess: async () => {
|
||||
await Promise.all([
|
||||
queryClient.invalidateQueries({ queryKey: ["presence"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["portal-home"] }),
|
||||
]);
|
||||
handleCorrectionDialogChange(false);
|
||||
toast.success("管理员修正已保存");
|
||||
},
|
||||
onError: (error) => {
|
||||
toast.error(resolveErrorMessage(error, "修正失败"));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -55,74 +222,404 @@ export function TeamPresencePage() {
|
||||
return items.filter((item) => item.presence?.status !== "office");
|
||||
}, [filter, teamPresenceQuery.data?.items]);
|
||||
|
||||
const historyEmployeeOptions = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const items: PresenceEmployee[] = [];
|
||||
for (const item of teamPresenceQuery.data?.items ?? []) {
|
||||
if (seen.has(item.employee.id)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(item.employee.id);
|
||||
items.push(item.employee);
|
||||
}
|
||||
return items;
|
||||
}, [teamPresenceQuery.data?.items]);
|
||||
|
||||
const historyDepartments = departmentsQuery.data?.items ?? [];
|
||||
const historyMyItems = myHistoryQuery.data?.items ?? [];
|
||||
const historyTeamItems = teamHistoryQuery.data?.items ?? [];
|
||||
|
||||
function handleCorrectionDialogChange(open: boolean) {
|
||||
if (!open) {
|
||||
setCorrectionTarget(null);
|
||||
setCorrectionStatus("office");
|
||||
setCorrectionTimeRange("full_day");
|
||||
setCorrectionNote("");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function openCorrectionDialog(item: TeamPresenceHistoryItem) {
|
||||
setCorrectionTarget(item);
|
||||
setCorrectionStatus(resolveEditableStatus(item));
|
||||
setCorrectionTimeRange(item.presence?.timeRange ?? "full_day");
|
||||
setCorrectionNote(item.presence?.note ?? "");
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<PageHeader title="团队状态" subtitle="不做打卡,只管理今天谁在岗 / 居家 / 外出 / 出差 / 请假。" />
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-3">
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<h3 className="text-base font-semibold text-zinc-900">更新我的今日状态</h3>
|
||||
<Input type="date" value={date} onChange={(event) => setDate(event.target.value)} />
|
||||
<select className="select-std" value={status} onChange={(event) => setStatus(event.target.value as typeof status)}>
|
||||
<option value="office">在岗</option>
|
||||
<option value="remote">居家</option>
|
||||
<option value="out">外出</option>
|
||||
<option value="travel">出差</option>
|
||||
</select>
|
||||
<Input value={note} onChange={(event) => setNote(event.target.value)} placeholder="可选备注,如下午外出办事" />
|
||||
<Button type="button" onClick={() => mutation.mutate()} disabled={mutation.isPending}>保存状态</Button>
|
||||
<div className="rounded-lg border border-zinc-200 p-3 text-sm text-zinc-600">
|
||||
当前:{statusLabel(myPresenceQuery.data?.item?.status ?? null)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 xl:col-span-2">
|
||||
<h3 className="text-base font-semibold text-zinc-900">今日汇总</h3>
|
||||
<div className="mt-4 grid gap-3 md:grid-cols-3 xl:grid-cols-6">
|
||||
{teamPresenceQuery.data?.summary ? Object.entries(teamPresenceQuery.data.summary).map(([key, value]) => (
|
||||
<div key={key} className="rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<div className="text-zinc-500">{key}</div>
|
||||
<div className="mt-2 text-lg font-semibold text-zinc-900">{value}</div>
|
||||
</div>
|
||||
)) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 className="text-base font-semibold text-zinc-900">团队列表</h3>
|
||||
<PageHeader
|
||||
title="团队状态"
|
||||
subtitle="不做打卡,只管理今天谁在岗 / 居家 / 外出 / 出差 / 请假。"
|
||||
actions={
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant={filter === "all" ? "default" : "secondary"} type="button" onClick={() => setFilter("all")}>全部</Button>
|
||||
<Button size="sm" variant={filter === "onsite" ? "default" : "secondary"} type="button" onClick={() => setFilter("onsite")}>在岗</Button>
|
||||
<Button size="sm" variant={filter === "away" ? "default" : "secondary"} type="button" onClick={() => setFilter("away")}>不在岗</Button>
|
||||
{viewMode === "history" && canManagePresence ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" type="button" disabled={exportMutation.isPending}>
|
||||
{exportMutation.isPending ? "导出中..." : "导出"}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onSelect={() => exportMutation.mutate("csv")}>
|
||||
导出 CSV
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onSelect={() => exportMutation.mutate("xlsx")}>
|
||||
导出 Excel
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : null}
|
||||
<Button type="button" variant={viewMode === "today" ? "default" : "secondary"} onClick={() => setViewMode("today")}>
|
||||
今日
|
||||
</Button>
|
||||
<Button type="button" variant={viewMode === "history" ? "default" : "secondary"} onClick={() => setViewMode("history")}>
|
||||
历史
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>成员</TableHead>
|
||||
<TableHead>部门</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{teamItems.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.title}</div>
|
||||
</TableCell>
|
||||
<TableCell>{item.employee.department?.name ?? "-"}</TableCell>
|
||||
<TableCell>{statusLabel(item.presence?.status ?? null)}</TableCell>
|
||||
<TableCell>{item.presence?.note ?? "-"}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{viewMode === "today" ? (
|
||||
<>
|
||||
<div className="grid gap-6 xl:grid-cols-3">
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<h3 className="text-base font-semibold text-zinc-900">更新我的今日状态</h3>
|
||||
<Input type="date" value={date} onChange={(event) => setDate(event.target.value)} />
|
||||
<select className="select-std" value={status} onChange={(event) => setStatus(event.target.value as EditablePresenceStatus)}>
|
||||
<option value="office">在岗</option>
|
||||
<option value="remote">居家</option>
|
||||
<option value="out">外出</option>
|
||||
<option value="travel">出差</option>
|
||||
</select>
|
||||
<Input value={note} onChange={(event) => setNote(event.target.value)} placeholder="可选备注,如下午外出办事" />
|
||||
<Button type="button" onClick={() => mutation.mutate()} disabled={mutation.isPending}>保存状态</Button>
|
||||
<div className="rounded-lg border border-zinc-200 p-3 text-sm text-zinc-600">
|
||||
当前:{statusLabel(myPresenceQuery.data?.item?.status ?? null)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 xl:col-span-2">
|
||||
<h3 className="text-base font-semibold text-zinc-900">今日汇总</h3>
|
||||
<div className="mt-4 grid gap-3 md:grid-cols-3 xl:grid-cols-6">
|
||||
{teamPresenceQuery.data?.summary ? Object.entries(teamPresenceQuery.data.summary).map(([key, value]) => (
|
||||
<div key={key} className="rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<div className="text-zinc-500">{key}</div>
|
||||
<div className="mt-2 text-lg font-semibold text-zinc-900">{value}</div>
|
||||
</div>
|
||||
)) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 className="text-base font-semibold text-zinc-900">团队列表</h3>
|
||||
<div className="flex gap-2">
|
||||
<Button size="sm" variant={filter === "all" ? "default" : "secondary"} type="button" onClick={() => setFilter("all")}>全部</Button>
|
||||
<Button size="sm" variant={filter === "onsite" ? "default" : "secondary"} type="button" onClick={() => setFilter("onsite")}>在岗</Button>
|
||||
<Button size="sm" variant={filter === "away" ? "default" : "secondary"} type="button" onClick={() => setFilter("away")}>不在岗</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{teamPresenceQuery.isError ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{resolveErrorMessage(teamPresenceQuery.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>成员</TableHead>
|
||||
<TableHead>部门</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{teamItems.length ? (
|
||||
teamItems.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.title}</div>
|
||||
</TableCell>
|
||||
<TableCell>{item.employee.department?.name ?? "-"}</TableCell>
|
||||
<TableCell>{statusLabel(item.presence?.status ?? null)}</TableCell>
|
||||
<TableCell>{item.presence?.note ?? "-"}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell className="py-3 text-zinc-500" colSpan={4}>
|
||||
暂无团队状态数据
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="card-std p-4">
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5">
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">开始日期</div>
|
||||
<Input type="date" value={historyDateFrom} onChange={(event) => setHistoryDateFrom(event.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">结束日期</div>
|
||||
<Input type="date" value={historyDateTo} onChange={(event) => setHistoryDateTo(event.target.value)} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">部门</div>
|
||||
<select className="select-std" value={historyDepartmentId} onChange={(event) => setHistoryDepartmentId(event.target.value)}>
|
||||
<option value="">全部部门</option>
|
||||
{historyDepartments.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">成员</div>
|
||||
<select className="select-std" value={historyEmployeeId} onChange={(event) => setHistoryEmployeeId(event.target.value)}>
|
||||
<option value="">全部成员</option>
|
||||
{historyEmployeeOptions.map((item) => (
|
||||
<option key={item.id} value={item.id}>
|
||||
{item.name} · {item.employeeNo}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">状态</div>
|
||||
<select className="select-std" value={historyStatus} onChange={(event) => setHistoryStatus(event.target.value as "" | PresenceHistoryStatusFilter)}>
|
||||
<option value="">全部状态</option>
|
||||
<option value="office">在岗</option>
|
||||
<option value="remote">居家</option>
|
||||
<option value="out">外出</option>
|
||||
<option value="travel">出差</option>
|
||||
<option value="leave">请假</option>
|
||||
<option value="unspecified">未更新</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{myHistoryQuery.isError || teamHistoryQuery.isError ? (
|
||||
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-600">
|
||||
{resolveErrorMessage(myHistoryQuery.error ?? teamHistoryQuery.error)}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-6 xl:grid-cols-3">
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-zinc-900">我的历史概览</h3>
|
||||
<div className="mt-1 text-sm text-zinc-500">
|
||||
{myHistoryQuery.data ? `${myHistoryQuery.data.dateFrom} ~ ${myHistoryQuery.data.dateTo}` : "按所选区间查看我的历史状态"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-1">
|
||||
{myHistoryQuery.data?.summary ? Object.entries(myHistoryQuery.data.summary).map(([key, value]) => (
|
||||
<div key={key} className="rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<div className="text-zinc-500">{key}</div>
|
||||
<div className="mt-2 text-lg font-semibold text-zinc-900">{value}</div>
|
||||
</div>
|
||||
)) : null}
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border border-zinc-200">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>日期</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{historyMyItems.length ? (
|
||||
historyMyItems.map((item) => (
|
||||
<TableRow key={item.date}>
|
||||
<TableCell>{item.date}</TableCell>
|
||||
<TableCell>{statusLabel(item.presence?.status ?? null)}</TableCell>
|
||||
<TableCell>{item.presence?.note ?? "-"}</TableCell>
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell className="py-3 text-zinc-500" colSpan={3}>
|
||||
{myHistoryQuery.isLoading ? "加载中..." : "暂无历史记录"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 xl:col-span-2">
|
||||
<div>
|
||||
<h3 className="text-base font-semibold text-zinc-900">团队历史汇总</h3>
|
||||
<div className="mt-1 text-sm text-zinc-500">
|
||||
{teamHistoryQuery.data ? `${teamHistoryQuery.data.dateFrom} ~ ${teamHistoryQuery.data.dateTo}` : "按所选区间查看团队历史汇总"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-3 md:grid-cols-3 xl:grid-cols-6">
|
||||
{teamHistoryQuery.data?.summary ? Object.entries(teamHistoryQuery.data.summary).map(([key, value]) => (
|
||||
<div key={key} className="rounded-lg border border-zinc-200 p-3 text-sm">
|
||||
<div className="text-zinc-500">{key}</div>
|
||||
<div className="mt-2 text-lg font-semibold text-zinc-900">{value}</div>
|
||||
</div>
|
||||
)) : (
|
||||
<div className="rounded-lg border border-dashed border-zinc-300 px-4 py-6 text-sm text-zinc-500 xl:col-span-6">
|
||||
{teamHistoryQuery.isLoading ? "加载历史汇总中..." : "暂无历史汇总数据"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-std p-6 space-y-4">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<h3 className="text-base font-semibold text-zinc-900">团队历史明细</h3>
|
||||
<div className="text-sm text-zinc-500">
|
||||
{teamHistoryQuery.data ? `${teamHistoryQuery.data.summary.total} 条记录` : "按筛选条件查看明细"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>日期</TableHead>
|
||||
<TableHead>成员</TableHead>
|
||||
<TableHead>部门</TableHead>
|
||||
<TableHead>状态</TableHead>
|
||||
<TableHead>时间段</TableHead>
|
||||
<TableHead>来源</TableHead>
|
||||
<TableHead>备注</TableHead>
|
||||
{canManagePresence ? <TableHead>操作</TableHead> : null}
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{historyTeamItems.length ? (
|
||||
historyTeamItems.map((item) => (
|
||||
<TableRow key={`${item.date}-${item.employee.id}`}>
|
||||
<TableCell>{item.date}</TableCell>
|
||||
<TableCell>
|
||||
<div className="font-medium text-zinc-900">{item.employee.name}</div>
|
||||
<div className="text-xs text-zinc-500">{item.employee.employeeNo} · {item.employee.title}</div>
|
||||
</TableCell>
|
||||
<TableCell>{item.employee.department?.name ?? "-"}</TableCell>
|
||||
<TableCell>{statusLabel(item.presence?.status ?? null)}</TableCell>
|
||||
<TableCell>{timeRangeLabel(item.presence?.timeRange)}</TableCell>
|
||||
<TableCell>{sourceLabel(item.presence?.source)}</TableCell>
|
||||
<TableCell>{item.presence?.note ?? "-"}</TableCell>
|
||||
{canManagePresence ? (
|
||||
<TableCell>
|
||||
<Button type="button" size="sm" variant="secondary" onClick={() => openCorrectionDialog(item)}>
|
||||
修正
|
||||
</Button>
|
||||
</TableCell>
|
||||
) : null}
|
||||
</TableRow>
|
||||
))
|
||||
) : (
|
||||
<TableRow>
|
||||
<TableCell className="py-3 text-zinc-500" colSpan={canManagePresence ? 8 : 7}>
|
||||
{teamHistoryQuery.isLoading ? "加载历史明细中..." : "暂无匹配的历史记录"}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Dialog open={Boolean(correctionTarget)} onOpenChange={handleCorrectionDialogChange}>
|
||||
<DialogContent className="max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>管理员修正团队状态</DialogTitle>
|
||||
<DialogDescription>
|
||||
修正会写入管理员覆盖记录,并同步刷新历史明细、团队今日状态与首页团队状态卡片。
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">员工</div>
|
||||
<div className="rounded-lg border border-zinc-200 px-3 py-2 text-sm text-zinc-700">
|
||||
{correctionTarget ? `${correctionTarget.employee.name} · ${correctionTarget.employee.employeeNo}` : "-"}
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">日期</div>
|
||||
<div className="rounded-lg border border-zinc-200 px-3 py-2 text-sm text-zinc-700">
|
||||
{correctionTarget?.date ?? "-"}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">状态</div>
|
||||
<select className="select-std" value={correctionStatus} onChange={(event) => setCorrectionStatus(event.target.value as EditablePresenceStatus)}>
|
||||
<option value="office">在岗</option>
|
||||
<option value="remote">居家</option>
|
||||
<option value="out">外出</option>
|
||||
<option value="travel">出差</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">时间段</div>
|
||||
<select className="select-std" value={correctionTimeRange} onChange={(event) => setCorrectionTimeRange(event.target.value as PresenceTimeRange)}>
|
||||
<option value="full_day">全天</option>
|
||||
<option value="morning">上午</option>
|
||||
<option value="afternoon">下午</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="text-xs font-medium text-zinc-500">备注</div>
|
||||
<Textarea
|
||||
value={correctionNote}
|
||||
onChange={(event) => setCorrectionNote(event.target.value)}
|
||||
placeholder="可选备注,最多 300 字"
|
||||
maxLength={300}
|
||||
className="min-h-[100px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button type="button" variant="secondary" onClick={() => handleCorrectionDialogChange(false)}>
|
||||
取消
|
||||
</Button>
|
||||
<Button type="button" onClick={() => correctionMutation.mutate()} disabled={!correctionTarget || correctionMutation.isPending}>
|
||||
{correctionMutation.isPending ? "保存中..." : "保存修正"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,4 +2,4 @@ ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regr
|
||||
R37-0,R37治理合同补建与范围冻结,为 AGENTS 多 agent 规则更新补建治理合同并锁定本轮仅做治理文档与提交准备,新 CSV 校验通过 且范围明确为 AGENTS agent modes 固化与提交留痕 不承接业务代码改动,python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,none,DONE,DONE,DONE,issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,[],"本轮仅治理协作规则与提交流程;不修改 server/src 或 client/src 业务代码。"
|
||||
R37-1,Agent modes 治理规则固化与 review 修订落地,将 3 常驻加 2 按需模式固化到 AGENTS 并落实 qa 写权限 Test_Method 语义和 backend post-check 三处修订,AGENTS.md 包含 Agent modes 段落 且三处修订与现有 issues/README 和 docs/mcp-tools 边界一致,1) git diff --check 2) 核对 AGENTS.md 中 mode:qa 允许写 issues/*.csv 与 scripts/ 3) 核对回滚说明已移入 Notes 约束 4) 核对 backend post-check 已改为按变更类型执行,manual,DONE,DONE,DONE,AGENTS.md,"[""R37-0""]","若后续证明规则过严或过松,回滚方式为还原本次 Agent modes 段落并保留 CSV 审计记录。"
|
||||
R37-2,治理变更提交与审计留痕,提交 AGENTS 与治理 CSV 变更并使用中文 commit message 引用本 Issue ID,生成 1 个仅包含治理变更的 commit 且 git log 最新提交可见 Issue ID,"1) git diff --stat 确认仅含 AGENTS.md 与 issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv 2) git commit -m ""R37: 固化 Agent modes 治理规则"" 3) git log -1 --oneline",manual,DONE,DONE,DONE,AGENTS.md|issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv,"[""R37-1""]","commit 仅承载治理变更;若提交前发现额外文件改动则先停止并重新确认范围。"
|
||||
R37-3,下个真实迭代按新模式试跑并复盘,在后续一个同时涉及 backend frontend qa 的真实迭代中按新 Agent modes 跑一次并记录阻塞点,至少完成 1 次真实试跑 并能说明 handoff QA 回填 reviewer 触发条件是否顺畅,"1) 选择一个同时涉及 server/ 与 client/ 的真实 issue 组 2) 按 Agent modes 执行 3) 在 Notes 或后续治理 issue 中记录问题与修订建议",manual,DONE,DONE,DONE,TBD,"[""R37-2""]","已用 R38 员工管理试跑完成一次真实迭代。结论: Files 派工整体清晰 backend 侧唯一摩擦点是 /employees 复用 usersRoutes 需要显式 allowDepartmentFilter;QA 回填顺畅 命令式验证和合同状态映射明确;reviewer 触发条件当前无需细化 本轮未触及权限模型 状态机 workflow 或迁移。R39 后续观测: 围绕单一 profile 响应做 backend/frontend handoff 比 R38 更清晰 扩现有接口比新建专用端点更顺;qa-runner 的新增经验是即使 shell 初始 PATH 缺少 Node,也可通过显式注入 NVM 路径完成验证,R39 最终已完成 node --check、后端单测、client typecheck 和 build。R40 后续观测: 同页中的可看 可改 可导出边界不能只靠前端,最终需要前后端同时收口;hireDate 这类“看起来已有字段”的需求仍要先核对 PATCH schema 与 update data,再决定是否是纯前端改动;员工导出验证了 exports.js 路由模式可以继续平移复用。R41 后续观测: 日常运营类导入继续放在 system.users 域内比挂到 cutover console 更顺,Files 派工也更清晰;qa-runner 在这轮除了命令验证,还额外覆盖了 multipart 上传与一次性密码清单下载这类结果物校验;reviewer 仍无需默认启用,但同批上级引用会引入两阶段创建与 direct_manager_id 回填,这类跨行依赖以后仍应优先判定为后端主导问题。"
|
||||
R37-3,下个真实迭代按新模式试跑并复盘,在后续一个同时涉及 backend frontend qa 的真实迭代中按新 Agent modes 跑一次并记录阻塞点,至少完成 1 次真实试跑 并能说明 handoff QA 回填 reviewer 触发条件是否顺畅,"1) 选择一个同时涉及 server/ 与 client/ 的真实 issue 组 2) 按 Agent modes 执行 3) 在 Notes 或后续治理 issue 中记录问题与修订建议",manual,DONE,DONE,DONE,TBD,"[""R37-2""]","已用 R38 员工管理试跑完成一次真实迭代。结论: Files 派工整体清晰 backend 侧唯一摩擦点是 /employees 复用 usersRoutes 需要显式 allowDepartmentFilter;QA 回填顺畅 命令式验证和合同状态映射明确;reviewer 触发条件当前无需细化 本轮未触及权限模型 状态机 workflow 或迁移。R39 后续观测: 围绕单一 profile 响应做 backend/frontend handoff 比 R38 更清晰 扩现有接口比新建专用端点更顺;qa-runner 的新增经验是即使 shell 初始 PATH 缺少 Node,也可通过显式注入 NVM 路径完成验证,R39 最终已完成 node --check、后端单测、client typecheck 和 build。R40 后续观测: 同页中的可看 可改 可导出边界不能只靠前端,最终需要前后端同时收口;hireDate 这类“看起来已有字段”的需求仍要先核对 PATCH schema 与 update data,再决定是否是纯前端改动;员工导出验证了 exports.js 路由模式可以继续平移复用。R41 后续观测: 日常运营类导入继续放在 system.users 域内比挂到 cutover console 更顺,Files 派工也更清晰;qa-runner 在这轮除了命令验证,还额外覆盖了 multipart 上传与一次性密码清单下载这类结果物校验;reviewer 仍无需默认启用,但同批上级引用会引入两阶段创建与 direct_manager_id 回填,这类跨行依赖以后仍应优先判定为后端主导问题。R42 后续观测: 这轮把 presence 历史读模型抽到共享服务后,backend 到 frontend 到 qa 的 handoff 更清晰,portal 与团队页不再各自维护一套考勤口径;exports.js 继续复用业务域服务依然顺手,说明导出模式还能沿用;reviewer 触发条件应从笼统的“权限/状态机/workflow”细化到“新增 source 或调整覆盖优先级”这类读模型语义变更。"
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
ID,Title,Description,Acceptance,Test_Method,Tools,Dev_Status,Review1_Status,Regression_Status,Files,Dependencies,Notes
|
||||
R42-0,R42执行合同建档与范围冻结,为考勤增强建立独立合同并冻结范围为历史查询 导出 管理员修正 不承接打卡 排班 迟到早退与复杂统计报表,CSV 校验通过 且本轮权限口径固定为沿用现有团队状态页访问边界 system.users 仅用于管理员修正与导出,"python3 /home/shunli/.codex/skills/plan/scripts/validate_issues_csv.py issues/2026-03-28_18-57-20-r42-presence-enhancements.csv",none,DONE,DONE,DONE,issues/2026-03-28_18-57-20-r42-presence-enhancements.csv,[],"默认不启用 reviewer;仅当管理员修正规则触及 leave_sync travel 覆盖优先级或引入新权限码时再升级。"
|
||||
R42-1,考勤历史查询与区间读模型,扩展 presence API 与 TeamPresencePage 支持按日期范围查询个人与团队状态历史 并补齐部门 成员 状态筛选,团队状态页可查看指定日期范围内的历史记录与汇总且筛选结果稳定 不新增独立考勤页面,"业务流程: 进入团队状态页 选择日期范围 查看汇总与明细 再切换部门 成员 状态筛选 确认结果与汇总同步变化。验证命令: cd server && node --check src/routes/presence.js && cd ../client && npm run typecheck && npm run build",manual,TODO,TODO,TODO,server/src/routes/presence.js|client/src/api/presence.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0""]","沿用 presence_board_v1 开关与现有 /team 入口,不新开组织考勤页。"
|
||||
R42-2,考勤导出,在 exports 路由新增团队状态导出并在 TeamPresencePage 提供导出按钮 复用当前日期范围与筛选条件导出 csv xlsx,system.users 用户可导出当前筛选后的团队状态全量结果 文件包含员工 部门 日期 状态 时间段 来源 备注 且与页面口径一致,"业务流程: 在团队状态页选择日期范围与筛选条件 点击导出 csv xlsx 确认导出内容与当前筛选一致。验证命令: cd server && node --check src/routes/exports.js && cd ../client && npm run typecheck && npm run build",manual,TODO,TODO,TODO,server/src/routes/exports.js|client/src/api/exports.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0"",""R42-1""]","继续复用 exports.js 模式与审计日志;导出权限固定为 system.users,避免扩散到新的权限模型。"
|
||||
R42-3,管理员修正团队状态,为 system.users 增加对他人团队状态的手工修正能力 并记录审计与覆盖来源边界,管理员可对指定员工指定日期执行修正并在页面看到结果刷新 非管理员无入口且审批同步状态的优先级规则保持明确,"业务流程: system.users 用户进入团队状态页 选择员工和日期 修正状态后刷新列表确认生效;非 system.users 用户确认没有修正入口;若目标日期受请假或出差覆盖 结果符合既定冲突规则。验证命令: cd server && node --check src/routes/presence.js && cd ../client && npm run typecheck && npm run build",manual,TODO,TODO,TODO,server/src/routes/presence.js|client/src/api/presence.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0"",""R42-1""]","默认沿用现有权限码收口在 system.users;若实现中需要新增专用 attendance 权限码或改动 leave_sync travel 覆盖语义,需升级 reviewer。"
|
||||
R42-4,QA回归与R37-3后续观测,完成考勤增强单项验证 最小回归与治理复盘 并记录历史查询 导出 管理员修正三类 handoff 是否顺畅,R42 状态正确回填 且 Notes 记录 presence.js 是否已需要拆分 exports 复用是否顺畅 reviewer 触发条件是否要细化,"业务流程: 验证日期范围历史查询 导出 管理员修正 非管理员无导出与修正入口 以及 Portal 团队状态页现有今日更新链路不回归。验证命令: cd server && node --check src/routes/presence.js && node --check src/routes/exports.js && cd ../client && npm run typecheck && npm run build",manual,TODO,TODO,TODO,issues/2026-03-28_18-57-20-r42-presence-enhancements.csv|issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv|server/src/routes/presence.js|server/src/routes/exports.js|client/src/pages/TeamPresencePage.tsx,"[""R42-1"",""R42-2"",""R42-3""]","复盘至少回答 3 点: presence.js 单文件继续扩展是否仍可接受;exports.js 在业务域扩展时是否继续顺手;管理员修正是否需要独立 reviewer 触发条件。"
|
||||
R42-1,考勤历史查询与区间读模型,扩展 presence API 与 TeamPresencePage 支持按日期范围查询个人与团队状态历史 并补齐部门 成员 状态筛选,团队状态页可查看指定日期范围内的历史记录与汇总且筛选结果稳定 不新增独立考勤页面,"业务流程: 进入团队状态页 选择日期范围 查看汇总与明细 再切换部门 成员 状态筛选 确认结果与汇总同步变化。验证命令: cd server && node --check src/routes/presence.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,server/src/routes/presence.js|client/src/api/presence.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0""]","已新增 /api/presence/me/history 与 /api/presence/team/history,区间默认最近 7 天 上限 31 天,team/history 支持 departmentId employeeId status 组合筛选并显式物化 unspecified。已验证: cd server && node --check src/routes/presence.js 通过;cd server && npm test -- tests/unit/routes/presence.history.test.js 4/4 通过;cd client && npm run typecheck 通过;cd client && npm run build 通过。"
|
||||
R42-2,考勤导出,在 exports 路由新增团队状态导出并在 TeamPresencePage 提供导出按钮 复用当前日期范围与筛选条件导出 csv xlsx,system.users 用户可导出当前筛选后的团队状态全量结果 文件包含员工 部门 日期 状态 时间段 来源 备注 且与页面口径一致,"业务流程: 在团队状态页选择日期范围与筛选条件 点击导出 csv xlsx 确认导出内容与当前筛选一致。验证命令: cd server && node --check src/routes/exports.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,server/src/services/presenceHistory.js|server/src/routes/exports.js|server/tests/unit/routes/exports.presence.test.js|client/src/api/presence.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0"",""R42-1""]","已新增 /api/exports/presence-history,导出只复用历史模式筛选口径,超过 5000 条返回 VALID_001 + export=too_large,不做截断。导出实现改为直接复用 presenceHistory 共享服务,避免页面与导出口径漂移。已通过 node --check、相关单测、client typecheck 与 build;另修复了 exports.presence.test.js 缺少 setErrorHandler 导致 AppError details 序列化不一致的问题。"
|
||||
R42-3,管理员修正团队状态,为 system.users 增加对他人团队状态的手工修正能力 并记录审计与覆盖来源边界,管理员可对指定员工指定日期执行修正并在页面看到结果刷新 非管理员无入口且审批同步状态的优先级规则保持明确,"业务流程: system.users 用户进入团队状态页 选择员工和日期 修正状态后刷新列表确认生效;非 system.users 用户确认没有修正入口;若目标日期受请假或出差覆盖 结果符合既定冲突规则。验证命令: cd server && node --check src/routes/presence.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,server/prisma/schema.prisma|server/prisma/migrations/20260328194500_r42_presence_admin_override|server/src/services/presenceHistory.js|server/src/routes/presence.js|server/src/routes/portal.js|server/tests/unit/routes/presence.admin.test.js|client/src/api/presence.ts|client/src/pages/TeamPresencePage.tsx,"[""R42-0"",""R42-1""]","因已确认允许强制覆盖,本轮正式新增 EmployeePresenceSource.admin_override,不再用 manual 冒充覆盖;读模型统一为 manual -> travel/leave_sync -> admin_override,Portal 今日卡片也改走同一共享服务。回滚路径: 先将 employee_presence.source='admin_override' 批量降级为 manual,再回滚代码与 Prisma 枚举。本轮不做“清空回未更新”,因为唯一键下删除/清空会引入额外审计与冲突语义,留待后续独立设计。已通过 prisma validate、node --check、相关单测、client typecheck 与 build。"
|
||||
R42-4,QA回归与R37-3后续观测,完成考勤增强单项验证 最小回归与治理复盘 并记录历史查询 导出 管理员修正三类 handoff 是否顺畅,R42 状态正确回填 且 Notes 记录 presence.js 是否已需要拆分 exports 复用是否顺畅 reviewer 触发条件是否要细化,"业务流程: 验证日期范围历史查询 导出 管理员修正 非管理员无导出与修正入口 以及 Portal 团队状态页现有今日更新链路不回归。验证命令: cd server && node --check src/routes/presence.js && node --check src/routes/exports.js && cd ../client && npm run typecheck && npm run build",manual,DONE,DONE,DONE,issues/2026-03-28_18-57-20-r42-presence-enhancements.csv|issues/2026-03-28_12-36-28-r37-agent-modes-governance.csv|server/src/services/presenceHistory.js|server/src/routes/presence.js|server/src/routes/exports.js|server/src/routes/portal.js|client/src/pages/TeamPresencePage.tsx,"[""R42-1"",""R42-2"",""R42-3""]","本轮把 presence 历史区间解析和读模型抽到共享服务,presence.js 单文件继续扩展已开始逼近拆分阈值,但服务层抽离后仍在可控范围。exports.js 继续复用业务域服务是顺手的,说明导出模式还能沿用;reviewer 触发条件应明确细化为“新增 source 或改覆盖优先级”。QA 已完成历史查询、导出、管理员修正、非管理员无入口、Portal 今日状态不回归的验证;R37-3 复盘已同步更新。"
|
||||
|
||||
|
@@ -0,0 +1 @@
|
||||
ALTER TYPE "EmployeePresenceSource" ADD VALUE IF NOT EXISTS 'admin_override';
|
||||
@@ -340,6 +340,7 @@ enum EmployeePresenceTimeRange {
|
||||
enum EmployeePresenceSource {
|
||||
manual
|
||||
leave_sync
|
||||
admin_override
|
||||
}
|
||||
|
||||
enum WeeklyReportStatus {
|
||||
|
||||
+149
-2
@@ -3,10 +3,17 @@ const { Readable } = require("node:stream");
|
||||
const ExcelJS = require("exceljs");
|
||||
const { z } = require("zod");
|
||||
|
||||
const {
|
||||
HISTORY_STATUS_VALUES,
|
||||
buildPresenceValidationError,
|
||||
buildTeamPresenceHistory,
|
||||
resolvePresenceHistoryRange,
|
||||
} = require("../services/presenceHistory");
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
|
||||
const EXPORT_FORMAT_SCHEMA = z.enum(["csv", "xlsx"]);
|
||||
const DATE_ONLY_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
|
||||
const REIMBURSEMENT_STATUS_SCHEMA = z.enum([
|
||||
"draft",
|
||||
@@ -43,8 +50,8 @@ const AUDIT_EXPORT_QUERY_SCHEMA = z.object({
|
||||
|
||||
const DASHBOARD_EXPORT_QUERY_SCHEMA = z.object({
|
||||
format: EXPORT_FORMAT_SCHEMA.optional(),
|
||||
dateFrom: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
dateTo: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
|
||||
dateFrom: DATE_ONLY_SCHEMA.optional(),
|
||||
dateTo: DATE_ONLY_SCHEMA.optional(),
|
||||
departmentId: z.string().uuid().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(20000).optional(),
|
||||
});
|
||||
@@ -57,6 +64,16 @@ const EMPLOYEE_EXPORT_QUERY_SCHEMA = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(20000).optional(),
|
||||
});
|
||||
|
||||
const PRESENCE_HISTORY_EXPORT_QUERY_SCHEMA = z.object({
|
||||
format: EXPORT_FORMAT_SCHEMA.optional(),
|
||||
dateFrom: DATE_ONLY_SCHEMA.optional(),
|
||||
dateTo: DATE_ONLY_SCHEMA.optional(),
|
||||
departmentId: z.string().uuid().optional(),
|
||||
employeeId: z.string().uuid().optional(),
|
||||
status: z.enum(HISTORY_STATUS_VALUES).optional(),
|
||||
});
|
||||
const PRESENCE_HISTORY_EXPORT_LIMIT = 5000;
|
||||
|
||||
function csvCell(value) {
|
||||
if (value == null) return "";
|
||||
|
||||
@@ -801,6 +818,87 @@ async function buildEmployeesXlsx(prisma, where, limit) {
|
||||
return workbook.xlsx.writeBuffer();
|
||||
}
|
||||
|
||||
function presenceStatusLabel(status) {
|
||||
if (status === "office") return "在岗";
|
||||
if (status === "remote") return "居家";
|
||||
if (status === "out") return "外出";
|
||||
if (status === "travel") return "出差";
|
||||
if (status === "leave") return "请假";
|
||||
return "未更新";
|
||||
}
|
||||
|
||||
function presenceTimeRangeLabel(timeRange) {
|
||||
if (timeRange === "morning") return "上午";
|
||||
if (timeRange === "afternoon") return "下午";
|
||||
if (timeRange === "full_day") return "全天";
|
||||
return "-";
|
||||
}
|
||||
|
||||
function presenceSourceLabel(source) {
|
||||
if (source === "manual") return "手工";
|
||||
if (source === "leave_sync") return "审批同步";
|
||||
if (source === "admin_override") return "管理员修正";
|
||||
return "-";
|
||||
}
|
||||
|
||||
function mapPresenceHistoryExportRow(item) {
|
||||
return [
|
||||
item.date,
|
||||
item.employee.employeeNo,
|
||||
item.employee.name,
|
||||
item.employee.department?.name ?? "",
|
||||
item.employee.title ?? "",
|
||||
presenceStatusLabel(item.presence?.status ?? null),
|
||||
presenceTimeRangeLabel(item.presence?.timeRange),
|
||||
presenceSourceLabel(item.presence?.source),
|
||||
item.presence?.note ?? "-",
|
||||
];
|
||||
}
|
||||
|
||||
function buildPresenceHistoryCsv(items) {
|
||||
const rows = [
|
||||
"\ufeff",
|
||||
csvRow(["日期", "工号", "姓名", "部门", "岗位", "状态", "时间段", "来源", "备注"]),
|
||||
];
|
||||
for (const item of items) {
|
||||
rows.push(csvRow(mapPresenceHistoryExportRow(item)));
|
||||
}
|
||||
return rows.join("");
|
||||
}
|
||||
|
||||
async function buildPresenceHistoryXlsx(items) {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet("presence_history");
|
||||
|
||||
sheet.columns = [
|
||||
{ header: "日期", key: "date", width: 14 },
|
||||
{ header: "工号", key: "employeeNo", width: 14 },
|
||||
{ header: "姓名", key: "name", width: 14 },
|
||||
{ header: "部门", key: "departmentName", width: 18 },
|
||||
{ header: "岗位", key: "title", width: 18 },
|
||||
{ header: "状态", key: "status", width: 12 },
|
||||
{ header: "时间段", key: "timeRange", width: 12 },
|
||||
{ header: "来源", key: "source", width: 14 },
|
||||
{ header: "备注", key: "note", width: 32 },
|
||||
];
|
||||
|
||||
for (const item of items) {
|
||||
sheet.addRow({
|
||||
date: item.date,
|
||||
employeeNo: item.employee.employeeNo,
|
||||
name: item.employee.name,
|
||||
departmentName: item.employee.department?.name ?? "",
|
||||
title: item.employee.title ?? "",
|
||||
status: presenceStatusLabel(item.presence?.status ?? null),
|
||||
timeRange: presenceTimeRangeLabel(item.presence?.timeRange),
|
||||
source: presenceSourceLabel(item.presence?.source),
|
||||
note: item.presence?.note ?? "-",
|
||||
});
|
||||
}
|
||||
|
||||
return workbook.xlsx.writeBuffer();
|
||||
}
|
||||
|
||||
async function exportsRoutes(fastify) {
|
||||
fastify.get(
|
||||
"/exports/employees",
|
||||
@@ -843,6 +941,55 @@ async function exportsRoutes(fastify) {
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/exports/presence-history",
|
||||
{
|
||||
preHandler: fastify.requirePermission("system.users"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
const query = parseQuery(PRESENCE_HISTORY_EXPORT_QUERY_SCHEMA, request.query);
|
||||
const format = resolveExportFormat(query);
|
||||
const range = resolvePresenceHistoryRange(query, fastify.config.appTimezone);
|
||||
const history = await buildTeamPresenceHistory(fastify.prisma, {
|
||||
dateStrings: range.dateStrings,
|
||||
departmentId: query.departmentId,
|
||||
employeeId: query.employeeId,
|
||||
status: query.status,
|
||||
});
|
||||
|
||||
if (history.items.length > PRESENCE_HISTORY_EXPORT_LIMIT) {
|
||||
throw buildPresenceValidationError({ export: "too_large" }, 409);
|
||||
}
|
||||
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "EXPORT_PRESENCE_HISTORY",
|
||||
targetType: "export",
|
||||
extra: {
|
||||
format,
|
||||
dateFrom: range.dateFrom,
|
||||
dateTo: range.dateTo,
|
||||
departmentId: query.departmentId ?? null,
|
||||
employeeId: query.employeeId ?? null,
|
||||
status: query.status ?? null,
|
||||
matchedTotal: history.items.length,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const filename = exportFilename("presence-history", format);
|
||||
setExportHeaders(reply, format, filename);
|
||||
|
||||
if (format === "xlsx") {
|
||||
const buffer = await buildPresenceHistoryXlsx(history.items);
|
||||
return reply.send(Buffer.from(buffer));
|
||||
}
|
||||
|
||||
return reply.send(buildPresenceHistoryCsv(history.items));
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get(
|
||||
"/exports/reimbursements",
|
||||
{
|
||||
|
||||
+4
-62
@@ -1,4 +1,8 @@
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const {
|
||||
buildTeamPresenceSummary,
|
||||
resolvePresenceForEmployee,
|
||||
} = require("../services/presenceHistory");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||
const { getWorkspaceSetting } = require("../services/workspaceSettings");
|
||||
@@ -78,68 +82,6 @@ function formatPresenceStatus(item) {
|
||||
return item.status;
|
||||
}
|
||||
|
||||
async function resolvePresenceForEmployee(prisma, employeeId, dateString) {
|
||||
const date = parseDateOnlyString(dateString);
|
||||
const leave = await prisma.leaveRequest.findFirst({
|
||||
where: {
|
||||
owner_id: employeeId,
|
||||
status: "approved",
|
||||
start_date: { lte: date },
|
||||
end_date: { gte: date },
|
||||
},
|
||||
select: { id: true, reason: true },
|
||||
});
|
||||
if (leave) {
|
||||
return { status: "leave", note: leave.reason ?? null, source: "leave_sync" };
|
||||
}
|
||||
|
||||
const travel = await prisma.travelRequest.findFirst({
|
||||
where: {
|
||||
applicant_employee_id: employeeId,
|
||||
status: "approved",
|
||||
start_date: { lte: date },
|
||||
end_date: { gte: date },
|
||||
},
|
||||
select: { id: true, purpose: true },
|
||||
});
|
||||
if (travel) {
|
||||
return { status: "travel", note: travel.purpose ?? null, source: "leave_sync" };
|
||||
}
|
||||
|
||||
const manual = await prisma.employeePresence.findUnique({
|
||||
where: {
|
||||
employee_id_date: {
|
||||
employee_id: employeeId,
|
||||
date,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!manual) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
status: manual.status,
|
||||
note: manual.note ?? null,
|
||||
source: manual.source,
|
||||
timeRange: manual.time_range,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildTeamPresenceSummary(prisma, dateString) {
|
||||
const employees = await prisma.employee.findMany({ where: { status: "active" }, select: { id: true } });
|
||||
const summary = { office: 0, remote: 0, out: 0, travel: 0, leave: 0, unspecified: 0, total: employees.length };
|
||||
for (const employee of employees) {
|
||||
const item = await resolvePresenceForEmployee(prisma, employee.id, dateString);
|
||||
const status = item?.status;
|
||||
if (!status || !(status in summary)) {
|
||||
summary.unspecified += 1;
|
||||
continue;
|
||||
}
|
||||
summary[status] += 1;
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
function buildQuickLinks({ request, featureEnabled }) {
|
||||
const items = [];
|
||||
items.push({ key: "team", title: "团队状态", href: "/team" });
|
||||
|
||||
+176
-221
@@ -1,40 +1,66 @@
|
||||
const { z } = require("zod");
|
||||
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const {
|
||||
HISTORY_STATUS_VALUES,
|
||||
PRESENCE_TIME_RANGE_VALUES,
|
||||
PRESENCE_WRITE_STATUS_VALUES,
|
||||
buildMyPresenceHistory,
|
||||
buildPresenceHistoryState,
|
||||
buildPresenceState,
|
||||
buildPresenceSummary,
|
||||
buildPresenceValidationError,
|
||||
buildTeamPresenceHistory,
|
||||
filterHistoryItemsByStatus,
|
||||
mapPresenceRow,
|
||||
listActivePresenceEmployees,
|
||||
resolvePresenceForEmployee,
|
||||
resolvePresenceHistoryRange,
|
||||
} = require("../services/presenceHistory");
|
||||
const { FEATURE_FLAG_KEYS, evaluateFeatureFlag } = require("../services/featureFlags");
|
||||
const { parseDateOnlyString, currentDateString } = require("../utils/date");
|
||||
const { sendData } = require("../utils/reply");
|
||||
const { buildAuditLogData } = require("../utils/audit");
|
||||
|
||||
const DATE_SCHEMA = z.string().regex(/^\d{4}-\d{2}-\d{2}$/);
|
||||
const QUERY_SCHEMA = z.object({ date: DATE_SCHEMA.optional() });
|
||||
const WRITE_SCHEMA = z
|
||||
.object({
|
||||
date: DATE_SCHEMA.optional(),
|
||||
status: z.enum(["office", "remote", "out", "travel"]),
|
||||
timeRange: z.enum(["full_day", "morning", "afternoon"]).optional(),
|
||||
status: z.enum(PRESENCE_WRITE_STATUS_VALUES),
|
||||
timeRange: z.enum(PRESENCE_TIME_RANGE_VALUES).optional(),
|
||||
note: z.string().trim().max(300).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
const HISTORY_QUERY_SCHEMA = z.object({
|
||||
dateFrom: DATE_SCHEMA.optional(),
|
||||
dateTo: DATE_SCHEMA.optional(),
|
||||
});
|
||||
const TEAM_HISTORY_QUERY_SCHEMA = HISTORY_QUERY_SCHEMA.extend({
|
||||
departmentId: z.string().uuid().optional(),
|
||||
employeeId: z.string().uuid().optional(),
|
||||
status: z.enum(HISTORY_STATUS_VALUES).optional(),
|
||||
});
|
||||
const TEAM_OVERRIDE_PARAMS_SCHEMA = z.object({
|
||||
employeeId: z.string().uuid(),
|
||||
});
|
||||
const TEAM_OVERRIDE_BODY_SCHEMA = z
|
||||
.object({
|
||||
date: DATE_SCHEMA,
|
||||
status: z.enum(PRESENCE_WRITE_STATUS_VALUES),
|
||||
timeRange: z.enum(PRESENCE_TIME_RANGE_VALUES).optional(),
|
||||
note: z.string().trim().max(300).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
function buildValidationError(details, statusCode = 400) {
|
||||
return new AppError({ code: "VALID_001", message: "参数校验失败", statusCode, details });
|
||||
}
|
||||
|
||||
function parseBody(schema, body) {
|
||||
const parsed = schema.safeParse(body ?? {});
|
||||
function parseInput(schema, value) {
|
||||
const parsed = schema.safeParse(value ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
throw buildPresenceValidationError(parsed.error.flatten());
|
||||
}
|
||||
return parsed.data;
|
||||
}
|
||||
|
||||
function formatDateOnly(value) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
return new Date(`${value.toISOString().slice(0, 10)}T00:00:00.000Z`).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function resolveDateInput(rawDate, timeZone) {
|
||||
return rawDate ? rawDate : currentDateString(timeZone ?? "Asia/Shanghai");
|
||||
}
|
||||
@@ -48,188 +74,28 @@ async function ensureFeatureEnabled(fastify, request) {
|
||||
strictDepartment: false,
|
||||
});
|
||||
if (!gate.enabled) {
|
||||
throw buildValidationError({ featureFlag: "presence_board_v1_disabled", reason: gate.reason }, 409);
|
||||
throw buildPresenceValidationError({ featureFlag: "presence_board_v1_disabled", reason: gate.reason }, 409);
|
||||
}
|
||||
}
|
||||
|
||||
function computeLeaveTimeRange(leave, dateString) {
|
||||
const startDate = formatDateOnly(leave.start_date);
|
||||
const endDate = formatDateOnly(leave.end_date);
|
||||
if (startDate === dateString && endDate === dateString) {
|
||||
if (leave.start_session === "pm" && leave.end_session === "pm") return "afternoon";
|
||||
if (leave.start_session === "am" && leave.end_session === "am") return "morning";
|
||||
return "full_day";
|
||||
}
|
||||
if (startDate === dateString && leave.start_session === "pm") {
|
||||
return "afternoon";
|
||||
}
|
||||
if (endDate === dateString && leave.end_session === "am") {
|
||||
return "morning";
|
||||
}
|
||||
return "full_day";
|
||||
}
|
||||
|
||||
function mapPresenceRow(row) {
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
employeeId: row.employee_id,
|
||||
date: formatDateOnly(row.date),
|
||||
status: row.status,
|
||||
timeRange: row.time_range,
|
||||
note: row.note ?? null,
|
||||
source: row.source,
|
||||
updatedAt: row.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
async function findLeaveOverlay(prisma, employeeIds, dateString) {
|
||||
if (!employeeIds.length) {
|
||||
return new Map();
|
||||
}
|
||||
const date = parseDateOnlyString(dateString);
|
||||
const rows = await prisma.leaveRequest.findMany({
|
||||
where: {
|
||||
owner_id: { in: employeeIds },
|
||||
status: "approved",
|
||||
start_date: { lte: date },
|
||||
end_date: { gte: date },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
owner_id: true,
|
||||
start_date: true,
|
||||
end_date: true,
|
||||
start_session: true,
|
||||
end_session: true,
|
||||
reason: true,
|
||||
},
|
||||
});
|
||||
const map = new Map();
|
||||
for (const row of rows) {
|
||||
if (!map.has(row.owner_id)) {
|
||||
map.set(row.owner_id, {
|
||||
id: `leave-${row.id}`,
|
||||
employeeId: row.owner_id,
|
||||
date: dateString,
|
||||
status: "leave",
|
||||
timeRange: computeLeaveTimeRange(row, dateString),
|
||||
note: row.reason ?? null,
|
||||
source: "leave_sync",
|
||||
updatedAt: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async function findTravelOverlay(prisma, employeeIds, dateString) {
|
||||
if (!employeeIds.length) {
|
||||
return new Map();
|
||||
}
|
||||
const date = parseDateOnlyString(dateString);
|
||||
const rows = await prisma.travelRequest.findMany({
|
||||
where: {
|
||||
applicant_employee_id: { in: employeeIds },
|
||||
status: "approved",
|
||||
start_date: { lte: date },
|
||||
end_date: { gte: date },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
applicant_employee_id: true,
|
||||
purpose: true,
|
||||
},
|
||||
});
|
||||
const map = new Map();
|
||||
for (const row of rows) {
|
||||
if (!map.has(row.applicant_employee_id)) {
|
||||
map.set(row.applicant_employee_id, {
|
||||
id: `travel-${row.id}`,
|
||||
employeeId: row.applicant_employee_id,
|
||||
date: dateString,
|
||||
status: "travel",
|
||||
timeRange: "full_day",
|
||||
note: row.purpose ?? null,
|
||||
source: "leave_sync",
|
||||
updatedAt: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
async function buildPresenceState(prisma, employeeIds, dateString) {
|
||||
const [manualRows, leaveOverlay, travelOverlay] = await Promise.all([
|
||||
prisma.employeePresence.findMany({
|
||||
where: { employee_id: { in: employeeIds }, date: parseDateOnlyString(dateString) },
|
||||
}),
|
||||
findLeaveOverlay(prisma, employeeIds, dateString),
|
||||
findTravelOverlay(prisma, employeeIds, dateString),
|
||||
]);
|
||||
|
||||
const manualMap = new Map(manualRows.map((row) => [row.employee_id, mapPresenceRow(row)]));
|
||||
const result = new Map();
|
||||
for (const employeeId of employeeIds) {
|
||||
if (leaveOverlay.has(employeeId)) {
|
||||
result.set(employeeId, leaveOverlay.get(employeeId));
|
||||
continue;
|
||||
}
|
||||
if (travelOverlay.has(employeeId)) {
|
||||
result.set(employeeId, travelOverlay.get(employeeId));
|
||||
continue;
|
||||
}
|
||||
if (manualMap.has(employeeId)) {
|
||||
result.set(employeeId, manualMap.get(employeeId));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildSummary(items) {
|
||||
const summary = {
|
||||
office: 0,
|
||||
remote: 0,
|
||||
out: 0,
|
||||
travel: 0,
|
||||
leave: 0,
|
||||
unspecified: 0,
|
||||
total: items.length,
|
||||
};
|
||||
|
||||
for (const item of items) {
|
||||
const status = item.presence?.status;
|
||||
if (!status || !(status in summary)) {
|
||||
summary.unspecified += 1;
|
||||
continue;
|
||||
}
|
||||
summary[status] += 1;
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
async function presenceRoutes(fastify) {
|
||||
fastify.get("/presence/me", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const parsed = QUERY_SCHEMA.safeParse(request.query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
const dateString = resolveDateInput(parsed.data.date, fastify.config.appTimezone);
|
||||
const query = parseInput(QUERY_SCHEMA, request.query);
|
||||
const dateString = resolveDateInput(query.date, fastify.config.appTimezone);
|
||||
const map = await buildPresenceState(fastify.prisma, [request.employee.id], dateString);
|
||||
return sendData(reply, request, { item: map.get(request.employee.id) ?? null, date: dateString });
|
||||
});
|
||||
|
||||
fastify.put("/presence/me", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const body = parseBody(WRITE_SCHEMA, request.body);
|
||||
const body = parseInput(WRITE_SCHEMA, request.body);
|
||||
const dateString = resolveDateInput(body.date, fastify.config.appTimezone);
|
||||
const leaveOverlay = await findLeaveOverlay(fastify.prisma, [request.employee.id], dateString);
|
||||
if (leaveOverlay.has(request.employee.id)) {
|
||||
throw buildValidationError({ date: "covered_by_approved_leave" }, 409);
|
||||
const before = await resolvePresenceForEmployee(fastify.prisma, request.employee.id, dateString);
|
||||
if (before?.source === "leave_sync" && before.status === "leave") {
|
||||
throw buildPresenceValidationError({ date: "covered_by_approved_leave" }, 409);
|
||||
}
|
||||
|
||||
const record = await fastify.prisma.employeePresence.upsert({
|
||||
where: {
|
||||
employee_id_date: {
|
||||
@@ -254,57 +120,146 @@ async function presenceRoutes(fastify) {
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
return sendData(reply, request, { item: mapPresenceRow(record) });
|
||||
});
|
||||
|
||||
fastify.get("/presence/team", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const parsed = QUERY_SCHEMA.safeParse(request.query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
const dateString = resolveDateInput(parsed.data.date, fastify.config.appTimezone);
|
||||
const employees = await fastify.prisma.employee.findMany({
|
||||
where: { status: "active" },
|
||||
orderBy: [{ department_id: "asc" }, { employee_no: "asc" }],
|
||||
select: {
|
||||
id: true,
|
||||
employee_no: true,
|
||||
name: true,
|
||||
title: true,
|
||||
employment_status: true,
|
||||
department: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
const map = await buildPresenceState(fastify.prisma, employees.map((item) => item.id), dateString);
|
||||
const query = parseInput(QUERY_SCHEMA, request.query);
|
||||
const dateString = resolveDateInput(query.date, fastify.config.appTimezone);
|
||||
const employees = await listActivePresenceEmployees(fastify.prisma);
|
||||
const map = await buildPresenceState(
|
||||
fastify.prisma,
|
||||
employees.map((item) => item.id),
|
||||
dateString,
|
||||
);
|
||||
const items = employees.map((item) => ({
|
||||
employee: {
|
||||
id: item.id,
|
||||
employeeNo: item.employee_no,
|
||||
name: item.name,
|
||||
title: item.title,
|
||||
employmentStatus: item.employment_status,
|
||||
department: item.department ? { id: item.department.id, name: item.department.name } : null,
|
||||
},
|
||||
employee: item,
|
||||
presence: map.get(item.id) ?? null,
|
||||
}));
|
||||
return sendData(reply, request, { date: dateString, summary: buildSummary(items), items });
|
||||
return sendData(reply, request, {
|
||||
date: dateString,
|
||||
summary: buildPresenceSummary(items),
|
||||
items,
|
||||
});
|
||||
});
|
||||
|
||||
fastify.get("/presence/me/history", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const query = parseInput(HISTORY_QUERY_SCHEMA, request.query);
|
||||
const range = resolvePresenceHistoryRange(query, fastify.config.appTimezone);
|
||||
const history = await buildMyPresenceHistory(fastify.prisma, request.employee.id, range.dateStrings);
|
||||
return sendData(reply, request, {
|
||||
dateFrom: range.dateFrom,
|
||||
dateTo: range.dateTo,
|
||||
summary: history.summary,
|
||||
items: history.items,
|
||||
});
|
||||
});
|
||||
|
||||
fastify.get("/presence/team/history", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const query = parseInput(TEAM_HISTORY_QUERY_SCHEMA, request.query);
|
||||
const range = resolvePresenceHistoryRange(query, fastify.config.appTimezone);
|
||||
const history = await buildTeamPresenceHistory(fastify.prisma, {
|
||||
dateStrings: range.dateStrings,
|
||||
departmentId: query.departmentId,
|
||||
employeeId: query.employeeId,
|
||||
status: query.status,
|
||||
});
|
||||
|
||||
return sendData(reply, request, {
|
||||
dateFrom: range.dateFrom,
|
||||
dateTo: range.dateTo,
|
||||
summary: history.summary,
|
||||
items: history.items,
|
||||
});
|
||||
});
|
||||
|
||||
fastify.put(
|
||||
"/presence/team/:employeeId",
|
||||
{
|
||||
preHandler: fastify.requirePermission("system.users"),
|
||||
},
|
||||
async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const params = parseInput(TEAM_OVERRIDE_PARAMS_SCHEMA, request.params);
|
||||
const body = parseInput(TEAM_OVERRIDE_BODY_SCHEMA, request.body);
|
||||
|
||||
const employee = await fastify.prisma.employee.findUnique({
|
||||
where: { id: params.employeeId },
|
||||
select: { id: true, status: true },
|
||||
});
|
||||
if (!employee || employee.status !== "active") {
|
||||
throw new AppError({ code: "SYS_404", message: "Not Found", statusCode: 404 });
|
||||
}
|
||||
|
||||
const before = await resolvePresenceForEmployee(fastify.prisma, params.employeeId, body.date);
|
||||
const record = await fastify.prisma.employeePresence.upsert({
|
||||
where: {
|
||||
employee_id_date: {
|
||||
employee_id: params.employeeId,
|
||||
date: parseDateOnlyString(body.date),
|
||||
},
|
||||
},
|
||||
update: {
|
||||
status: body.status,
|
||||
time_range: body.timeRange ?? "full_day",
|
||||
note: body.note ?? null,
|
||||
source: "admin_override",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
create: {
|
||||
employee_id: params.employeeId,
|
||||
date: parseDateOnlyString(body.date),
|
||||
status: body.status,
|
||||
time_range: body.timeRange ?? "full_day",
|
||||
note: body.note ?? null,
|
||||
source: "admin_override",
|
||||
updated_by: request.employee.id,
|
||||
},
|
||||
});
|
||||
|
||||
const after = mapPresenceRow(record);
|
||||
await fastify.prisma.auditLog.create({
|
||||
data: buildAuditLogData(request, {
|
||||
actorId: request.employee.id,
|
||||
action: "PRESENCE_ADMIN_CORRECTED",
|
||||
targetType: "employee_presence",
|
||||
targetId: params.employeeId,
|
||||
extra: {
|
||||
employeeId: params.employeeId,
|
||||
date: body.date,
|
||||
before,
|
||||
after,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return sendData(reply, request, { item: after });
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get("/presence/summary", { preHandler: fastify.authenticate }, async (request, reply) => {
|
||||
await ensureFeatureEnabled(fastify, request);
|
||||
const parsed = QUERY_SCHEMA.safeParse(request.query ?? {});
|
||||
if (!parsed.success) {
|
||||
throw buildValidationError(parsed.error.flatten());
|
||||
}
|
||||
const dateString = resolveDateInput(parsed.data.date, fastify.config.appTimezone);
|
||||
const employeeIds = (
|
||||
await fastify.prisma.employee.findMany({ where: { status: "active" }, select: { id: true } })
|
||||
).map((item) => item.id);
|
||||
const query = parseInput(QUERY_SCHEMA, request.query);
|
||||
const dateString = resolveDateInput(query.date, fastify.config.appTimezone);
|
||||
const employeeIds = (await listActivePresenceEmployees(fastify.prisma)).map((item) => item.id);
|
||||
const map = await buildPresenceState(fastify.prisma, employeeIds, dateString);
|
||||
const items = employeeIds.map((employeeId) => ({ employeeId, presence: map.get(employeeId) ?? null }));
|
||||
return sendData(reply, request, { date: dateString, summary: buildSummary(items) });
|
||||
return sendData(reply, request, {
|
||||
date: dateString,
|
||||
summary: buildPresenceSummary(items),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
presenceRoutes.__testables = {
|
||||
buildPresenceHistoryState,
|
||||
filterHistoryItemsByStatus,
|
||||
listActivePresenceEmployees,
|
||||
resolveHistoryRange: resolvePresenceHistoryRange,
|
||||
};
|
||||
|
||||
module.exports = presenceRoutes;
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
const { AppError } = require("../utils/AppError");
|
||||
const { currentDateString, parseDateOnlyString } = require("../utils/date");
|
||||
|
||||
const HISTORY_STATUS_VALUES = ["office", "remote", "out", "travel", "leave", "unspecified"];
|
||||
const PRESENCE_WRITE_STATUS_VALUES = ["office", "remote", "out", "travel"];
|
||||
const PRESENCE_TIME_RANGE_VALUES = ["full_day", "morning", "afternoon"];
|
||||
const HISTORY_DEFAULT_DAYS = 7;
|
||||
const HISTORY_MAX_DAYS = 31;
|
||||
|
||||
function buildPresenceValidationError(details, statusCode = 400) {
|
||||
return new AppError({
|
||||
code: "VALID_001",
|
||||
message: "参数校验失败",
|
||||
statusCode,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
function formatDateOnly(value) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
return new Date(`${value.toISOString().slice(0, 10)}T00:00:00.000Z`).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function addUtcDays(date, days) {
|
||||
const next = new Date(date.getTime());
|
||||
next.setUTCDate(next.getUTCDate() + days);
|
||||
return next;
|
||||
}
|
||||
|
||||
function buildDateStrings(dateFrom, dateTo) {
|
||||
const items = [];
|
||||
for (let current = new Date(dateFrom.getTime()); current <= dateTo; current = addUtcDays(current, 1)) {
|
||||
items.push(formatDateOnly(current));
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
function resolvePresenceHistoryRange(query, timeZone) {
|
||||
const todayString = currentDateString(timeZone ?? "Asia/Shanghai");
|
||||
let dateFrom = query.dateFrom ?? null;
|
||||
let dateTo = query.dateTo ?? null;
|
||||
|
||||
if (!dateFrom && !dateTo) {
|
||||
dateTo = todayString;
|
||||
dateFrom = formatDateOnly(addUtcDays(parseDateOnlyString(dateTo), -(HISTORY_DEFAULT_DAYS - 1)));
|
||||
} else if (!dateFrom && dateTo) {
|
||||
dateFrom = formatDateOnly(addUtcDays(parseDateOnlyString(dateTo), -(HISTORY_DEFAULT_DAYS - 1)));
|
||||
} else if (dateFrom && !dateTo) {
|
||||
dateTo = todayString;
|
||||
}
|
||||
|
||||
const start = parseDateOnlyString(dateFrom);
|
||||
const end = parseDateOnlyString(dateTo);
|
||||
if (start > end) {
|
||||
throw buildPresenceValidationError({ dateTo: "must_be_after_or_equal_dateFrom" });
|
||||
}
|
||||
|
||||
const totalDays = Math.floor((end.getTime() - start.getTime()) / 86400000) + 1;
|
||||
if (totalDays > HISTORY_MAX_DAYS) {
|
||||
throw buildPresenceValidationError({ dateRange: "too_large" });
|
||||
}
|
||||
|
||||
return {
|
||||
dateFrom,
|
||||
dateTo,
|
||||
dateStrings: buildDateStrings(start, end),
|
||||
};
|
||||
}
|
||||
|
||||
function computeLeaveTimeRange(leave, dateString) {
|
||||
const startDate = formatDateOnly(leave.start_date);
|
||||
const endDate = formatDateOnly(leave.end_date);
|
||||
if (startDate === dateString && endDate === dateString) {
|
||||
if (leave.start_session === "pm" && leave.end_session === "pm") return "afternoon";
|
||||
if (leave.start_session === "am" && leave.end_session === "am") return "morning";
|
||||
return "full_day";
|
||||
}
|
||||
if (startDate === dateString && leave.start_session === "pm") {
|
||||
return "afternoon";
|
||||
}
|
||||
if (endDate === dateString && leave.end_session === "am") {
|
||||
return "morning";
|
||||
}
|
||||
return "full_day";
|
||||
}
|
||||
|
||||
function mapPresenceRow(row) {
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: row.id,
|
||||
employeeId: row.employee_id,
|
||||
date: formatDateOnly(row.date),
|
||||
status: row.status,
|
||||
timeRange: row.time_range,
|
||||
note: row.note ?? null,
|
||||
source: row.source,
|
||||
updatedAt: row.updated_at?.toISOString?.() ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function mapPresenceEmployee(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
employeeNo: row.employee_no,
|
||||
name: row.name,
|
||||
title: row.title,
|
||||
employmentStatus: row.employment_status,
|
||||
department: row.department ? { id: row.department.id, name: row.department.name } : null,
|
||||
};
|
||||
}
|
||||
|
||||
function comparePresenceEmployees(left, right) {
|
||||
const departmentCompare = (left.department?.name ?? "").localeCompare(right.department?.name ?? "", "zh-CN");
|
||||
if (departmentCompare !== 0) {
|
||||
return departmentCompare;
|
||||
}
|
||||
return left.employeeNo.localeCompare(right.employeeNo, "en");
|
||||
}
|
||||
|
||||
function buildHistoryKey(employeeId, dateString) {
|
||||
return `${employeeId}:${dateString}`;
|
||||
}
|
||||
|
||||
function buildTravelPresence(row, dateString) {
|
||||
return {
|
||||
id: `travel-${row.id}`,
|
||||
employeeId: row.applicant_employee_id,
|
||||
date: dateString,
|
||||
status: "travel",
|
||||
timeRange: "full_day",
|
||||
note: row.purpose ?? null,
|
||||
source: "leave_sync",
|
||||
updatedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
function buildLeavePresence(row, dateString) {
|
||||
return {
|
||||
id: `leave-${row.id}`,
|
||||
employeeId: row.owner_id,
|
||||
date: dateString,
|
||||
status: "leave",
|
||||
timeRange: computeLeaveTimeRange(row, dateString),
|
||||
note: row.reason ?? null,
|
||||
source: "leave_sync",
|
||||
updatedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildPresenceHistoryState(prisma, employeeIds, dateStrings) {
|
||||
if (!employeeIds.length || !dateStrings.length) {
|
||||
return new Map();
|
||||
}
|
||||
|
||||
const dateFrom = dateStrings[0];
|
||||
const dateTo = dateStrings[dateStrings.length - 1];
|
||||
const [presenceRows, leaveRows, travelRows] = await Promise.all([
|
||||
prisma.employeePresence.findMany({
|
||||
where: {
|
||||
employee_id: { in: employeeIds },
|
||||
date: {
|
||||
gte: parseDateOnlyString(dateFrom),
|
||||
lte: parseDateOnlyString(dateTo),
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.leaveRequest.findMany({
|
||||
where: {
|
||||
owner_id: { in: employeeIds },
|
||||
status: "approved",
|
||||
start_date: { lte: parseDateOnlyString(dateTo) },
|
||||
end_date: { gte: parseDateOnlyString(dateFrom) },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
owner_id: true,
|
||||
start_date: true,
|
||||
end_date: true,
|
||||
start_session: true,
|
||||
end_session: true,
|
||||
reason: true,
|
||||
},
|
||||
}),
|
||||
prisma.travelRequest.findMany({
|
||||
where: {
|
||||
applicant_employee_id: { in: employeeIds },
|
||||
status: "approved",
|
||||
start_date: { lte: parseDateOnlyString(dateTo) },
|
||||
end_date: { gte: parseDateOnlyString(dateFrom) },
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
applicant_employee_id: true,
|
||||
start_date: true,
|
||||
end_date: true,
|
||||
purpose: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const result = new Map();
|
||||
const adminOverrideMap = new Map();
|
||||
for (const row of presenceRows) {
|
||||
const key = buildHistoryKey(row.employee_id, formatDateOnly(row.date));
|
||||
const mapped = mapPresenceRow(row);
|
||||
if (row.source === "admin_override") {
|
||||
adminOverrideMap.set(key, mapped);
|
||||
} else {
|
||||
result.set(key, mapped);
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of travelRows) {
|
||||
const startDate = formatDateOnly(row.start_date);
|
||||
const endDate = formatDateOnly(row.end_date);
|
||||
for (const dateString of dateStrings) {
|
||||
if (dateString < startDate || dateString > endDate) {
|
||||
continue;
|
||||
}
|
||||
const key = buildHistoryKey(row.applicant_employee_id, dateString);
|
||||
if (!result.has(key) || result.get(key)?.source !== "leave_sync") {
|
||||
result.set(key, buildTravelPresence(row, dateString));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const row of leaveRows) {
|
||||
const startDate = formatDateOnly(row.start_date);
|
||||
const endDate = formatDateOnly(row.end_date);
|
||||
for (const dateString of dateStrings) {
|
||||
if (dateString < startDate || dateString > endDate) {
|
||||
continue;
|
||||
}
|
||||
const key = buildHistoryKey(row.owner_id, dateString);
|
||||
result.set(key, buildLeavePresence(row, dateString));
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, value] of adminOverrideMap.entries()) {
|
||||
result.set(key, value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
async function buildPresenceState(prisma, employeeIds, dateString) {
|
||||
const historyMap = await buildPresenceHistoryState(prisma, employeeIds, [dateString]);
|
||||
const result = new Map();
|
||||
for (const employeeId of employeeIds) {
|
||||
const key = buildHistoryKey(employeeId, dateString);
|
||||
if (historyMap.has(key)) {
|
||||
result.set(employeeId, historyMap.get(key));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function resolvePresenceForEmployee(prisma, employeeId, dateString) {
|
||||
const map = await buildPresenceState(prisma, [employeeId], dateString);
|
||||
return map.get(employeeId) ?? null;
|
||||
}
|
||||
|
||||
function buildPresenceSummary(items) {
|
||||
const summary = {
|
||||
office: 0,
|
||||
remote: 0,
|
||||
out: 0,
|
||||
travel: 0,
|
||||
leave: 0,
|
||||
unspecified: 0,
|
||||
total: items.length,
|
||||
};
|
||||
|
||||
for (const item of items) {
|
||||
const status = item.presence?.status;
|
||||
if (!status || !(status in summary)) {
|
||||
summary.unspecified += 1;
|
||||
continue;
|
||||
}
|
||||
summary[status] += 1;
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
function filterHistoryItemsByStatus(items, status) {
|
||||
if (!status) {
|
||||
return items;
|
||||
}
|
||||
if (status === "unspecified") {
|
||||
return items.filter((item) => !item.presence);
|
||||
}
|
||||
return items.filter((item) => item.presence?.status === status);
|
||||
}
|
||||
|
||||
async function listActivePresenceEmployees(prisma, filters = {}) {
|
||||
const employees = await prisma.employee.findMany({
|
||||
where: {
|
||||
status: "active",
|
||||
...(filters.departmentId ? { department_id: filters.departmentId } : {}),
|
||||
...(filters.employeeId ? { id: filters.employeeId } : {}),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
employee_no: true,
|
||||
name: true,
|
||||
title: true,
|
||||
employment_status: true,
|
||||
department: { select: { id: true, name: true } },
|
||||
},
|
||||
});
|
||||
|
||||
return employees.map(mapPresenceEmployee).sort(comparePresenceEmployees);
|
||||
}
|
||||
|
||||
function buildTeamHistoryItems(employees, dateStrings, historyMap) {
|
||||
return [...dateStrings]
|
||||
.reverse()
|
||||
.flatMap((date) =>
|
||||
employees.map((employee) => ({
|
||||
date,
|
||||
employee,
|
||||
presence: historyMap.get(buildHistoryKey(employee.id, date)) ?? null,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
async function buildMyPresenceHistory(prisma, employeeId, dateStrings) {
|
||||
const historyMap = await buildPresenceHistoryState(prisma, [employeeId], dateStrings);
|
||||
const items = [...dateStrings].reverse().map((date) => ({
|
||||
date,
|
||||
presence: historyMap.get(buildHistoryKey(employeeId, date)) ?? null,
|
||||
}));
|
||||
return {
|
||||
items,
|
||||
summary: buildPresenceSummary(items),
|
||||
};
|
||||
}
|
||||
|
||||
async function buildTeamPresenceHistory(prisma, options) {
|
||||
const employees = await listActivePresenceEmployees(prisma, {
|
||||
departmentId: options.departmentId,
|
||||
employeeId: options.employeeId,
|
||||
});
|
||||
const historyMap = await buildPresenceHistoryState(
|
||||
prisma,
|
||||
employees.map((item) => item.id),
|
||||
options.dateStrings,
|
||||
);
|
||||
const items = filterHistoryItemsByStatus(
|
||||
buildTeamHistoryItems(employees, options.dateStrings, historyMap),
|
||||
options.status,
|
||||
);
|
||||
|
||||
return {
|
||||
employees,
|
||||
items,
|
||||
summary: buildPresenceSummary(items),
|
||||
};
|
||||
}
|
||||
|
||||
async function buildTeamPresenceSummary(prisma, dateString) {
|
||||
const employees = await listActivePresenceEmployees(prisma);
|
||||
const map = await buildPresenceState(
|
||||
prisma,
|
||||
employees.map((item) => item.id),
|
||||
dateString,
|
||||
);
|
||||
const items = employees.map((employee) => ({
|
||||
employee,
|
||||
presence: map.get(employee.id) ?? null,
|
||||
}));
|
||||
return buildPresenceSummary(items);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
HISTORY_DEFAULT_DAYS,
|
||||
HISTORY_MAX_DAYS,
|
||||
HISTORY_STATUS_VALUES,
|
||||
PRESENCE_TIME_RANGE_VALUES,
|
||||
PRESENCE_WRITE_STATUS_VALUES,
|
||||
addUtcDays,
|
||||
buildHistoryKey,
|
||||
buildMyPresenceHistory,
|
||||
buildPresenceHistoryState,
|
||||
buildPresenceState,
|
||||
buildPresenceSummary,
|
||||
buildPresenceValidationError,
|
||||
buildTeamPresenceHistory,
|
||||
buildTeamPresenceSummary,
|
||||
filterHistoryItemsByStatus,
|
||||
formatDateOnly,
|
||||
listActivePresenceEmployees,
|
||||
mapPresenceEmployee,
|
||||
mapPresenceRow,
|
||||
resolvePresenceForEmployee,
|
||||
resolvePresenceHistoryRange,
|
||||
};
|
||||
@@ -0,0 +1,267 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const exportsRoutes = require("../../../src/routes/exports");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OTHER_EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
const OTHER_DEPARTMENT_ID = "cccccccc-cccc-4ccc-8ccc-cccccccccccc";
|
||||
|
||||
function buildEmployeeRow(overrides = {}) {
|
||||
return {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "Alice",
|
||||
title: "员工",
|
||||
employment_status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
status: "active",
|
||||
department: {
|
||||
id: DEPARTMENT_ID,
|
||||
name: "行政部",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPresenceRow(overrides = {}) {
|
||||
return {
|
||||
id: "presence-1",
|
||||
employee_id: EMPLOYEE_ID,
|
||||
date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
status: "office",
|
||||
time_range: "full_day",
|
||||
note: "补录",
|
||||
source: "admin_override",
|
||||
updated_at: new Date("2026-03-27T08:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: ACTOR_ID,
|
||||
roleCodes: ["hr"],
|
||||
permissionCodes: ["system.users"],
|
||||
};
|
||||
const employees = options.employees ?? [buildEmployeeRow()];
|
||||
const presenceRows = options.presenceRows ?? [];
|
||||
const leaveRows = options.leaveRows ?? [];
|
||||
const travelRows = options.travelRows ?? [];
|
||||
|
||||
const employeeFindMany = vi.fn(async ({ where, select }) => {
|
||||
if (select?.id === true && Object.keys(select).length === 1) {
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.map((item) => ({ id: item.id }));
|
||||
}
|
||||
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.filter((item) => !where?.department_id || item.department_id === where.department_id)
|
||||
.filter((item) => !where?.id || item.id === where.id)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
employee_no: item.employee_no,
|
||||
name: item.name,
|
||||
title: item.title,
|
||||
employment_status: item.employment_status,
|
||||
department: item.department,
|
||||
}));
|
||||
});
|
||||
|
||||
const employeePresenceFindMany = vi.fn(async ({ where }) =>
|
||||
presenceRows.filter((row) => {
|
||||
if (!where?.employee_id?.in?.includes(row.employee_id)) return false;
|
||||
if (where?.date?.gte && row.date < where.date.gte) return false;
|
||||
if (where?.date?.lte && row.date > where.date.lte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const leaveFindMany = vi.fn(async ({ where }) =>
|
||||
leaveRows.filter((row) => {
|
||||
if (!where?.owner_id?.in?.includes(row.owner_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const travelFindMany = vi.fn(async ({ where }) =>
|
||||
travelRows.filter((row) => {
|
||||
if (!where?.applicant_employee_id?.in?.includes(row.applicant_employee_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const auditCreate = vi.fn().mockResolvedValue({});
|
||||
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes("*") && !permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("hasPermission", (employee, permissionCode) => {
|
||||
const permissionCodes = employee.permissionCodes ?? [];
|
||||
return permissionCodes.includes("*") || permissionCodes.includes(permissionCode);
|
||||
});
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
employee: {
|
||||
findMany: employeeFindMany,
|
||||
},
|
||||
employeePresence: {
|
||||
findMany: employeePresenceFindMany,
|
||||
},
|
||||
leaveRequest: {
|
||||
findMany: leaveFindMany,
|
||||
},
|
||||
travelRequest: {
|
||||
findMany: travelFindMany,
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
});
|
||||
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof AppError) {
|
||||
return reply.status(error.statusCode).send({
|
||||
requestId: request.id,
|
||||
error: {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
details: error.details ?? {},
|
||||
},
|
||||
});
|
||||
}
|
||||
return reply.status(500).send({ error: { message: error.message } });
|
||||
});
|
||||
|
||||
await app.register(exportsRoutes, { prefix: "/api" });
|
||||
return { app, employeeFindMany, auditCreate };
|
||||
}
|
||||
|
||||
describe("presence history exports route", () => {
|
||||
it("exports filtered presence history for system.users", async () => {
|
||||
const { app, employeeFindMany, auditCreate } = await buildApp({
|
||||
employees: [
|
||||
buildEmployeeRow(),
|
||||
buildEmployeeRow({
|
||||
id: OTHER_EMPLOYEE_ID,
|
||||
employee_no: "E002",
|
||||
name: "Bob",
|
||||
department_id: OTHER_DEPARTMENT_ID,
|
||||
department: {
|
||||
id: OTHER_DEPARTMENT_ID,
|
||||
name: "市场部",
|
||||
},
|
||||
}),
|
||||
],
|
||||
presenceRows: [
|
||||
buildPresenceRow(),
|
||||
buildPresenceRow({
|
||||
id: "presence-2",
|
||||
employee_id: OTHER_EMPLOYEE_ID,
|
||||
status: "remote",
|
||||
source: "manual",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/exports/presence-history?format=csv&dateFrom=2026-03-27&dateTo=2026-03-27&departmentId=${DEPARTMENT_ID}&employeeId=${EMPLOYEE_ID}&status=office`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.headers["content-type"]).toContain("text/csv");
|
||||
expect(response.headers["content-disposition"]).toContain("presence-history-");
|
||||
expect(response.body).toContain("日期,工号,姓名,部门,岗位,状态,时间段,来源,备注");
|
||||
expect(response.body).toContain("E001");
|
||||
expect(response.body).toContain("管理员修正");
|
||||
expect(employeeFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
id: EMPLOYEE_ID,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(auditCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "EXPORT_PRESENCE_HISTORY",
|
||||
extra: expect.objectContaining({
|
||||
matchedTotal: 1,
|
||||
departmentId: DEPARTMENT_ID,
|
||||
employeeId: EMPLOYEE_ID,
|
||||
status: "office",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects exports larger than the hard limit", async () => {
|
||||
const employees = Array.from({ length: 162 }, (_, index) =>
|
||||
buildEmployeeRow({
|
||||
id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,
|
||||
employee_no: `E${String(index + 1).padStart(4, "0")}`,
|
||||
name: `员工${index + 1}`,
|
||||
}),
|
||||
);
|
||||
|
||||
const { app, auditCreate } = await buildApp({
|
||||
employees,
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/exports/presence-history?format=csv&dateFrom=2026-02-26&dateTo=2026-03-28",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(409);
|
||||
expect(response.json().error.details).toEqual({ export: "too_large" });
|
||||
expect(auditCreate).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects non system.users access", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: {
|
||||
id: ACTOR_ID,
|
||||
roleCodes: ["manager"],
|
||||
permissionCodes: ["report.dashboard.view"],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/exports/presence-history?format=csv",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,396 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const presenceRoutes = require("../../../src/routes/presence");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const ACTOR_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const OTHER_EMPLOYEE_ID = "22222222-2222-4222-8222-222222222222";
|
||||
const DEPARTMENT_ID = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb";
|
||||
|
||||
function buildEmployeeRow(overrides = {}) {
|
||||
return {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "Alice",
|
||||
title: "员工",
|
||||
employment_status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
status: "active",
|
||||
department: {
|
||||
id: DEPARTMENT_ID,
|
||||
name: "行政部",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPresenceRow(overrides = {}) {
|
||||
return {
|
||||
id: "presence-1",
|
||||
employee_id: EMPLOYEE_ID,
|
||||
date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
status: "office",
|
||||
time_range: "full_day",
|
||||
note: null,
|
||||
source: "manual",
|
||||
updated_at: new Date("2026-03-27T08:00:00.000Z"),
|
||||
updated_by: ACTOR_ID,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildLeaveRow(overrides = {}) {
|
||||
return {
|
||||
id: "leave-1",
|
||||
owner_id: EMPLOYEE_ID,
|
||||
start_date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
end_date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
start_session: "am",
|
||||
end_session: "pm",
|
||||
reason: "年假",
|
||||
status: "approved",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function sameDate(left, right) {
|
||||
return left.toISOString().slice(0, 10) === right.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const actor = options.actor ?? {
|
||||
id: ACTOR_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: ["system.users"],
|
||||
};
|
||||
const employees = options.employees ?? [buildEmployeeRow()];
|
||||
const presenceRows = [...(options.presenceRows ?? [])];
|
||||
const leaveRows = options.leaveRows ?? [];
|
||||
const travelRows = options.travelRows ?? [];
|
||||
|
||||
const employeeFindMany = vi.fn(async ({ where, select }) => {
|
||||
if (select?.id === true && Object.keys(select).length === 1) {
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.map((item) => ({ id: item.id }));
|
||||
}
|
||||
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.filter((item) => !where?.department_id || item.department_id === where.department_id)
|
||||
.filter((item) => !where?.id || item.id === where.id)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
employee_no: item.employee_no,
|
||||
name: item.name,
|
||||
title: item.title,
|
||||
employment_status: item.employment_status,
|
||||
department: item.department,
|
||||
}));
|
||||
});
|
||||
|
||||
const employeeFindUnique = vi.fn(async ({ where }) => {
|
||||
const employee = employees.find((item) => item.id === where.id);
|
||||
if (!employee) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: employee.id,
|
||||
status: employee.status,
|
||||
};
|
||||
});
|
||||
|
||||
const employeePresenceFindMany = vi.fn(async ({ where }) =>
|
||||
presenceRows.filter((row) => {
|
||||
if (!where?.employee_id?.in?.includes(row.employee_id)) return false;
|
||||
if (where?.date instanceof Date) {
|
||||
return row.date.getTime() === where.date.getTime();
|
||||
}
|
||||
if (where?.date?.gte && row.date < where.date.gte) return false;
|
||||
if (where?.date?.lte && row.date > where.date.lte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const employeePresenceUpsert = vi.fn(async ({ where, update, create }) => {
|
||||
const rowIndex = presenceRows.findIndex(
|
||||
(row) =>
|
||||
row.employee_id === where.employee_id_date.employee_id &&
|
||||
sameDate(row.date, where.employee_id_date.date),
|
||||
);
|
||||
const nextUpdatedAt = new Date("2026-03-28T10:30:00.000Z");
|
||||
if (rowIndex >= 0) {
|
||||
presenceRows[rowIndex] = {
|
||||
...presenceRows[rowIndex],
|
||||
status: update.status,
|
||||
time_range: update.time_range,
|
||||
note: update.note,
|
||||
source: update.source,
|
||||
updated_by: update.updated_by,
|
||||
updated_at: nextUpdatedAt,
|
||||
};
|
||||
return presenceRows[rowIndex];
|
||||
}
|
||||
|
||||
const created = {
|
||||
id: `presence-${presenceRows.length + 1}`,
|
||||
employee_id: create.employee_id,
|
||||
date: create.date,
|
||||
status: create.status,
|
||||
time_range: create.time_range,
|
||||
note: create.note,
|
||||
source: create.source,
|
||||
updated_by: create.updated_by,
|
||||
updated_at: nextUpdatedAt,
|
||||
};
|
||||
presenceRows.push(created);
|
||||
return created;
|
||||
});
|
||||
|
||||
const leaveFindMany = vi.fn(async ({ where }) =>
|
||||
leaveRows.filter((row) => {
|
||||
if (!where?.owner_id?.in?.includes(row.owner_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const travelFindMany = vi.fn(async ({ where }) =>
|
||||
travelRows.filter((row) => {
|
||||
if (!where?.applicant_employee_id?.in?.includes(row.applicant_employee_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const auditCreate = vi.fn().mockResolvedValue({});
|
||||
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = actor;
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = actor;
|
||||
const permissionCodes = actor.permissionCodes ?? [];
|
||||
if (!permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
presenceBoardEnabled: true,
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
employee: {
|
||||
findMany: employeeFindMany,
|
||||
findUnique: employeeFindUnique,
|
||||
},
|
||||
employeePresence: {
|
||||
findMany: employeePresenceFindMany,
|
||||
upsert: employeePresenceUpsert,
|
||||
},
|
||||
leaveRequest: {
|
||||
findMany: leaveFindMany,
|
||||
},
|
||||
travelRequest: {
|
||||
findMany: travelFindMany,
|
||||
},
|
||||
auditLog: {
|
||||
create: auditCreate,
|
||||
},
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue({
|
||||
id: "flag-presence",
|
||||
flag_key: "presence_board_v1",
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "",
|
||||
version: 1,
|
||||
created_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
created_by: "system",
|
||||
updated_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
updated_by: "system",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await app.register(presenceRoutes, { prefix: "/api" });
|
||||
|
||||
return {
|
||||
app,
|
||||
auditCreate,
|
||||
employeePresenceUpsert,
|
||||
presenceRows,
|
||||
};
|
||||
}
|
||||
|
||||
describe("presence admin override routes", () => {
|
||||
it("allows system.users to override leave-covered dates and keeps admin_override as final state", async () => {
|
||||
const { app, auditCreate, employeePresenceUpsert } = await buildApp({
|
||||
leaveRows: [buildLeaveRow()],
|
||||
});
|
||||
|
||||
const updateResponse = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/presence/team/${EMPLOYEE_ID}`,
|
||||
payload: {
|
||||
date: "2026-03-27",
|
||||
status: "office",
|
||||
timeRange: "morning",
|
||||
note: "上午补录在岗",
|
||||
},
|
||||
});
|
||||
|
||||
expect(updateResponse.statusCode).toBe(200);
|
||||
expect(employeePresenceUpsert).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
update: expect.objectContaining({
|
||||
source: "admin_override",
|
||||
status: "office",
|
||||
time_range: "morning",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(auditCreate).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({
|
||||
action: "PRESENCE_ADMIN_CORRECTED",
|
||||
extra: expect.objectContaining({
|
||||
employeeId: EMPLOYEE_ID,
|
||||
date: "2026-03-27",
|
||||
before: expect.objectContaining({
|
||||
status: "leave",
|
||||
source: "leave_sync",
|
||||
}),
|
||||
after: expect.objectContaining({
|
||||
status: "office",
|
||||
source: "admin_override",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
const teamResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/presence/team?date=2026-03-27",
|
||||
});
|
||||
expect(teamResponse.statusCode).toBe(200);
|
||||
expect(teamResponse.json().data.items).toEqual([
|
||||
{
|
||||
employee: expect.objectContaining({
|
||||
id: EMPLOYEE_ID,
|
||||
employeeNo: "E001",
|
||||
}),
|
||||
presence: expect.objectContaining({
|
||||
status: "office",
|
||||
source: "admin_override",
|
||||
timeRange: "morning",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
const historyResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/presence/team/history?dateFrom=2026-03-27&dateTo=2026-03-27&employeeId=${EMPLOYEE_ID}`,
|
||||
});
|
||||
expect(historyResponse.statusCode).toBe(200);
|
||||
expect(historyResponse.json().data.items).toEqual([
|
||||
{
|
||||
date: "2026-03-27",
|
||||
employee: expect.objectContaining({
|
||||
id: EMPLOYEE_ID,
|
||||
employeeNo: "E001",
|
||||
}),
|
||||
presence: expect.objectContaining({
|
||||
status: "office",
|
||||
source: "admin_override",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
const summaryResponse = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/presence/summary?date=2026-03-27",
|
||||
});
|
||||
expect(summaryResponse.statusCode).toBe(200);
|
||||
expect(summaryResponse.json().data.summary).toEqual({
|
||||
office: 1,
|
||||
remote: 0,
|
||||
out: 0,
|
||||
travel: 0,
|
||||
leave: 0,
|
||||
unspecified: 0,
|
||||
total: 1,
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("updates existing manual rows to admin_override", async () => {
|
||||
const { app } = await buildApp({
|
||||
presenceRows: [
|
||||
buildPresenceRow({
|
||||
status: "remote",
|
||||
note: "原始记录",
|
||||
source: "manual",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/presence/team/${EMPLOYEE_ID}`,
|
||||
payload: {
|
||||
date: "2026-03-27",
|
||||
status: "out",
|
||||
note: "管理员修正",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.json().data.item).toMatchObject({
|
||||
status: "out",
|
||||
source: "admin_override",
|
||||
note: "管理员修正",
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects non system.users access", async () => {
|
||||
const { app } = await buildApp({
|
||||
actor: {
|
||||
id: ACTOR_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: ["report.dashboard.view"],
|
||||
},
|
||||
employees: [
|
||||
buildEmployeeRow(),
|
||||
buildEmployeeRow({
|
||||
id: OTHER_EMPLOYEE_ID,
|
||||
employee_no: "E002",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "PUT",
|
||||
url: `/api/presence/team/${OTHER_EMPLOYEE_ID}`,
|
||||
payload: {
|
||||
date: "2026-03-27",
|
||||
status: "office",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,323 @@
|
||||
const Fastify = require("fastify");
|
||||
|
||||
const presenceRoutes = require("../../../src/routes/presence");
|
||||
const { AppError } = require("../../../src/utils/AppError");
|
||||
|
||||
const EMPLOYEE_ID = "11111111-1111-4111-8111-111111111111";
|
||||
const DEPARTMENT_ID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa";
|
||||
|
||||
function buildEmployeeRow(overrides = {}) {
|
||||
return {
|
||||
id: EMPLOYEE_ID,
|
||||
employee_no: "E001",
|
||||
name: "Alice",
|
||||
title: "员工",
|
||||
employment_status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
status: "active",
|
||||
department: {
|
||||
id: DEPARTMENT_ID,
|
||||
name: "行政部",
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildPresenceRow(overrides = {}) {
|
||||
return {
|
||||
id: "presence-1",
|
||||
employee_id: EMPLOYEE_ID,
|
||||
date: new Date("2026-03-28T00:00:00.000Z"),
|
||||
status: "office",
|
||||
time_range: "full_day",
|
||||
note: null,
|
||||
source: "manual",
|
||||
updated_at: new Date("2026-03-28T08:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildLeaveRow(overrides = {}) {
|
||||
return {
|
||||
id: "leave-1",
|
||||
owner_id: EMPLOYEE_ID,
|
||||
start_date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
end_date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
start_session: "am",
|
||||
end_session: "pm",
|
||||
reason: "请假",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function buildApp(options = {}) {
|
||||
const app = Fastify();
|
||||
const employees = options.employees ?? [buildEmployeeRow()];
|
||||
const presenceRows = options.presenceRows ?? [];
|
||||
const leaveRows = options.leaveRows ?? [];
|
||||
const travelRows = options.travelRows ?? [];
|
||||
|
||||
const employeeFindMany = vi.fn(async ({ where, select }) => {
|
||||
if (select?.id === true && Object.keys(select).length === 1) {
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.map((item) => ({ id: item.id }));
|
||||
}
|
||||
|
||||
return employees
|
||||
.filter((item) => item.status === (where?.status ?? item.status))
|
||||
.filter((item) => !where?.department_id || item.department_id === where.department_id)
|
||||
.filter((item) => !where?.id || item.id === where.id)
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
employee_no: item.employee_no,
|
||||
name: item.name,
|
||||
title: item.title,
|
||||
employment_status: item.employment_status,
|
||||
department: item.department,
|
||||
}));
|
||||
});
|
||||
|
||||
const employeePresenceFindMany = vi.fn(async ({ where }) =>
|
||||
presenceRows.filter((row) => {
|
||||
if (!where?.employee_id?.in?.includes(row.employee_id)) return false;
|
||||
if (where?.date instanceof Date) {
|
||||
return row.date.getTime() === where.date.getTime();
|
||||
}
|
||||
if (where?.date?.gte && row.date < where.date.gte) return false;
|
||||
if (where?.date?.lte && row.date > where.date.lte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const leaveFindMany = vi.fn(async ({ where }) =>
|
||||
leaveRows.filter((row) => {
|
||||
if (!where?.owner_id?.in?.includes(row.owner_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
const travelFindMany = vi.fn(async ({ where }) =>
|
||||
travelRows.filter((row) => {
|
||||
if (!where?.applicant_employee_id?.in?.includes(row.applicant_employee_id)) return false;
|
||||
if (row.status && where?.status && row.status !== where.status) return false;
|
||||
if (where?.start_date?.lte && row.start_date > where.start_date.lte) return false;
|
||||
if (where?.end_date?.gte && row.end_date < where.end_date.gte) return false;
|
||||
return true;
|
||||
}),
|
||||
);
|
||||
|
||||
app.decorate("authenticate", async (request) => {
|
||||
request.employee = {
|
||||
id: EMPLOYEE_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: [],
|
||||
};
|
||||
});
|
||||
app.decorate("requirePermission", (permissionCode) => async (request) => {
|
||||
request.employee = {
|
||||
id: EMPLOYEE_ID,
|
||||
department_id: DEPARTMENT_ID,
|
||||
permissionCodes: [],
|
||||
};
|
||||
if (!request.employee.permissionCodes.includes(permissionCode)) {
|
||||
throw new AppError({ code: "PERM_001", message: "无权限", statusCode: 403 });
|
||||
}
|
||||
});
|
||||
app.decorate("config", {
|
||||
appTimezone: "Asia/Shanghai",
|
||||
presenceBoardEnabled: true,
|
||||
});
|
||||
app.decorate("prisma", {
|
||||
employee: {
|
||||
findMany: employeeFindMany,
|
||||
},
|
||||
employeePresence: {
|
||||
findMany: employeePresenceFindMany,
|
||||
},
|
||||
leaveRequest: {
|
||||
findMany: leaveFindMany,
|
||||
},
|
||||
travelRequest: {
|
||||
findMany: travelFindMany,
|
||||
},
|
||||
featureFlag: {
|
||||
findUnique: vi.fn().mockResolvedValue({
|
||||
id: "flag-presence",
|
||||
flag_key: "presence_board_v1",
|
||||
override_mode: "force_on",
|
||||
rollout_type: "global",
|
||||
department_ids: [],
|
||||
note: "",
|
||||
version: 1,
|
||||
created_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
created_by: "system",
|
||||
updated_at: new Date("2026-03-01T00:00:00.000Z"),
|
||||
updated_by: "system",
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
await app.register(presenceRoutes, { prefix: "/api" });
|
||||
|
||||
return { app, employeeFindMany };
|
||||
}
|
||||
|
||||
describe("presence history routes", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-03-28T10:00:00.000Z"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("defaults me history to the last 7 days", async () => {
|
||||
const { app } = await buildApp({
|
||||
presenceRows: [
|
||||
buildPresenceRow({
|
||||
date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
status: "remote",
|
||||
note: "历史记录",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/presence/me/history",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const payload = response.json().data;
|
||||
expect(payload.dateFrom).toBe("2026-03-22");
|
||||
expect(payload.dateTo).toBe("2026-03-28");
|
||||
expect(payload.items).toHaveLength(7);
|
||||
expect(payload.items[1]).toMatchObject({
|
||||
date: "2026-03-27",
|
||||
presence: expect.objectContaining({
|
||||
status: "remote",
|
||||
}),
|
||||
});
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("rejects history ranges longer than 31 days", async () => {
|
||||
const { app, employeeFindMany } = await buildApp();
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/presence/team/history?dateFrom=2026-02-01&dateTo=2026-03-28",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(employeeFindMany).not.toHaveBeenCalled();
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("filters team history by employee department and unspecified status", async () => {
|
||||
const employeeId = "22222222-2222-4222-8222-222222222222";
|
||||
const otherEmployee = buildEmployeeRow({
|
||||
id: employeeId,
|
||||
employee_no: "E002",
|
||||
name: "Bob",
|
||||
});
|
||||
const archivedEmployee = buildEmployeeRow({
|
||||
id: "33333333-3333-4333-8333-333333333333",
|
||||
employee_no: "E003",
|
||||
name: "Carol",
|
||||
status: "archived",
|
||||
});
|
||||
|
||||
const { app, employeeFindMany } = await buildApp({
|
||||
employees: [otherEmployee, archivedEmployee],
|
||||
presenceRows: [
|
||||
buildPresenceRow({
|
||||
employee_id: employeeId,
|
||||
date: new Date("2026-03-28T00:00:00.000Z"),
|
||||
status: "office",
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/api/presence/team/history?dateFrom=2026-03-27&dateTo=2026-03-28&departmentId=${DEPARTMENT_ID}&employeeId=${employeeId}&status=unspecified`,
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const payload = response.json().data;
|
||||
expect(payload.items).toEqual([
|
||||
{
|
||||
date: "2026-03-27",
|
||||
employee: expect.objectContaining({
|
||||
id: employeeId,
|
||||
employeeNo: "E002",
|
||||
}),
|
||||
presence: null,
|
||||
},
|
||||
]);
|
||||
expect(payload.summary).toEqual({
|
||||
office: 0,
|
||||
remote: 0,
|
||||
out: 0,
|
||||
travel: 0,
|
||||
leave: 0,
|
||||
unspecified: 1,
|
||||
total: 1,
|
||||
});
|
||||
expect(employeeFindMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
where: expect.objectContaining({
|
||||
status: "active",
|
||||
department_id: DEPARTMENT_ID,
|
||||
id: employeeId,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it("prefers leave overlays over manual records in team history", async () => {
|
||||
const { app } = await buildApp({
|
||||
presenceRows: [
|
||||
buildPresenceRow({
|
||||
date: new Date("2026-03-27T00:00:00.000Z"),
|
||||
status: "office",
|
||||
note: "原始手工状态",
|
||||
}),
|
||||
],
|
||||
leaveRows: [buildLeaveRow()],
|
||||
});
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: "/api/presence/team/history?dateFrom=2026-03-27&dateTo=2026-03-27",
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
const payload = response.json().data;
|
||||
expect(payload.items).toEqual([
|
||||
{
|
||||
date: "2026-03-27",
|
||||
employee: expect.objectContaining({
|
||||
id: EMPLOYEE_ID,
|
||||
employeeNo: "E001",
|
||||
}),
|
||||
presence: expect.objectContaining({
|
||||
status: "leave",
|
||||
source: "leave_sync",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
在新工单中引用
屏蔽一个用户