1074 行
39 KiB
TypeScript
1074 行
39 KiB
TypeScript
import { useEffect, useState } from "react";
|
||
import { Link } from "react-router-dom";
|
||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||
import { toast } from "sonner";
|
||
import {
|
||
clockInAttendance,
|
||
clockOutAttendance,
|
||
fetchMyTodayAttendance,
|
||
type AttendanceTodayResponse,
|
||
} from "../api/attendance";
|
||
import { mapApiErrorMessage } from "../api/errorMessages";
|
||
import {
|
||
fetchPortalHome,
|
||
type PortalHomePayload,
|
||
type PortalRecentActivity,
|
||
type PortalTeamStatusItem,
|
||
} from "../api/portal";
|
||
import { isApiError } from "../api/types";
|
||
import { useAuth } from "../auth/AuthContext";
|
||
import { hasAnyPermission, isManagerRole } from "../auth/permissions";
|
||
import { EmployeeAvatar } from "../components/common/EmployeeAvatar";
|
||
import { ErrorBoundary } from "../components/common/ErrorBoundary";
|
||
import { EmptyStateCard } from "../components/common/EmptyStateCard";
|
||
import { WelcomeDialog } from "../components/onboarding/WelcomeDialog";
|
||
import { MetricCard } from "../components/patterns/MetricCard";
|
||
import { PageScaffold } from "../components/patterns/PageScaffold";
|
||
import { SectionPanel } from "../components/patterns/SectionPanel";
|
||
import { WorkbenchHero } from "../components/patterns/WorkbenchHero";
|
||
import { Button } from "../components/ui/button";
|
||
import { employeePortalSchema, managerPortalSchema } from "../features/portal/schema";
|
||
import {
|
||
clearWelcomeDialogFlag,
|
||
dismissGettingStartedCard,
|
||
shouldShowGettingStartedCard,
|
||
shouldShowWelcomeDialog,
|
||
} from "../lib/onboardingGuide";
|
||
import { readRecentVisits } from "../lib/recentVisits";
|
||
|
||
type SummaryItem = {
|
||
key: string;
|
||
href: string;
|
||
label: string;
|
||
value: string;
|
||
note?: string;
|
||
tone?: "normal" | "warning";
|
||
};
|
||
|
||
type TodoAggregateItem = {
|
||
title: string;
|
||
sourceLabel: string;
|
||
severity: "normal" | "warning" | "high";
|
||
href: string;
|
||
icon: string;
|
||
};
|
||
|
||
type QuickActionConfig = {
|
||
key: string;
|
||
icon: string;
|
||
label: string;
|
||
description: string;
|
||
to?: string;
|
||
onClick?: () => void;
|
||
disabled?: boolean;
|
||
};
|
||
|
||
type GettingStartedChecklistItem = {
|
||
key: string;
|
||
title: string;
|
||
description: string;
|
||
href: string;
|
||
completed: boolean;
|
||
};
|
||
|
||
const LEAVE_PORTAL_PERMISSIONS = ["leave.view_own", "leave.view_all", "leave.create", "leave.submit"];
|
||
const EXPENSE_PORTAL_PERMISSIONS = ["expense.view_own", "expense.view_all", "expense.create", "expense.proxy_manage"];
|
||
const TODO_SEVERITY_RANK = {
|
||
high: 3,
|
||
warning: 2,
|
||
normal: 1,
|
||
} as const;
|
||
|
||
function isSummaryItem(item: SummaryItem | null): item is SummaryItem {
|
||
return Boolean(item);
|
||
}
|
||
|
||
function severityTone(severity?: "normal" | "warning" | "high") {
|
||
if (severity === "high") return "danger" as const;
|
||
if (severity === "warning") return "warning" as const;
|
||
return "neutral" as const;
|
||
}
|
||
|
||
function pickCards(cards: PortalHomePayload["cards"], keys: string[]) {
|
||
const map = new Map(cards.map((card) => [card.key, card]));
|
||
return keys.map((key) => map.get(key)).filter((card): card is PortalHomePayload["cards"][number] => Boolean(card));
|
||
}
|
||
|
||
function compactCards(cards: PortalHomePayload["cards"], excludedKeys: string[]) {
|
||
return cards.filter((card) => !excludedKeys.includes(card.key));
|
||
}
|
||
|
||
function formatWeeklyStatus(payload: PortalHomePayload["weeklyReport"]) {
|
||
if (!payload) return "未启用";
|
||
return payload.status === "submitted" ? "已提交" : "待填写";
|
||
}
|
||
|
||
function resolveErrorMessage(error: unknown) {
|
||
if (isApiError(error)) {
|
||
return `${error.code}: ${mapApiErrorMessage(error.code, error.details, error.message)}`;
|
||
}
|
||
if (error instanceof Error) {
|
||
return error.message;
|
||
}
|
||
return "请求失败,请稍后重试。";
|
||
}
|
||
|
||
function isAttendanceFeatureDisabled(error: unknown) {
|
||
return isApiError(error) && error.code === "VALID_001" && error.details?.featureFlag === "attendance_v1_disabled";
|
||
}
|
||
|
||
function formatRelativeTime(value: string | null) {
|
||
if (!value) {
|
||
return "-";
|
||
}
|
||
|
||
const timestamp = new Date(value).getTime();
|
||
if (Number.isNaN(timestamp)) {
|
||
return "-";
|
||
}
|
||
|
||
const diffMs = Date.now() - timestamp;
|
||
if (diffMs < 60 * 1000) {
|
||
return "刚刚";
|
||
}
|
||
|
||
const diffMinutes = Math.floor(diffMs / (60 * 1000));
|
||
if (diffMinutes < 60) {
|
||
return `${diffMinutes} 分钟前`;
|
||
}
|
||
|
||
const diffHours = Math.floor(diffMinutes / 60);
|
||
if (diffHours < 24) {
|
||
return `${diffHours} 小时前`;
|
||
}
|
||
|
||
const diffDays = Math.floor(diffHours / 24);
|
||
return `${diffDays} 天前`;
|
||
}
|
||
|
||
function formatShortTime(value: string | null) {
|
||
if (!value) {
|
||
return "--:--";
|
||
}
|
||
try {
|
||
return new Date(value).toLocaleTimeString("zh-CN", {
|
||
hour: "2-digit",
|
||
minute: "2-digit",
|
||
hour12: false,
|
||
});
|
||
} catch {
|
||
return value;
|
||
}
|
||
}
|
||
|
||
function formatWorkMinutes(value: number | null | undefined) {
|
||
if (value == null) {
|
||
return "-";
|
||
}
|
||
const hours = Math.floor(value / 60);
|
||
const minutes = value % 60;
|
||
return `${hours}h ${String(minutes).padStart(2, "0")}m`;
|
||
}
|
||
|
||
function buildTodoAggregateItems(payload: PortalHomePayload) {
|
||
const cards = Array.isArray(payload.cards) ? payload.cards : [];
|
||
const items: TodoAggregateItem[] = [];
|
||
if (payload.pendingTasks.count > 0) {
|
||
items.push({
|
||
title: `审批待办 ${payload.pendingTasks.count} 条`,
|
||
sourceLabel: "审批",
|
||
severity: "warning",
|
||
href: payload.pendingTasks.href,
|
||
icon: "fact_check",
|
||
});
|
||
}
|
||
if ((payload.todoSummary?.openCount ?? 0) > 0) {
|
||
items.push({
|
||
title: `TODO 待办 ${payload.todoSummary?.openCount ?? 0} 条`,
|
||
sourceLabel: "TODO",
|
||
severity: (payload.todoSummary?.highPriorityCount ?? 0) > 0 ? "high" : "normal",
|
||
href: payload.todoSummary?.href ?? "/todos",
|
||
icon: "check_circle",
|
||
});
|
||
}
|
||
for (const card of cards) {
|
||
if (!card.severity || (card.severity !== "warning" && card.severity !== "high")) {
|
||
continue;
|
||
}
|
||
items.push({
|
||
title: `${card.title}:${card.value}`,
|
||
sourceLabel: "工作台",
|
||
severity: card.severity,
|
||
href: card.href,
|
||
icon: card.severity === "high" ? "priority_high" : "warning",
|
||
});
|
||
}
|
||
|
||
const deduped = new Map<string, TodoAggregateItem>();
|
||
for (const item of items) {
|
||
deduped.set(`${item.title}|${item.href}|${item.sourceLabel}`, item);
|
||
}
|
||
|
||
return Array.from(deduped.values())
|
||
.sort((left, right) => {
|
||
const severityCompare = TODO_SEVERITY_RANK[right.severity] - TODO_SEVERITY_RANK[left.severity];
|
||
if (severityCompare !== 0) {
|
||
return severityCompare;
|
||
}
|
||
return left.title.localeCompare(right.title, "zh-CN");
|
||
})
|
||
.slice(0, 10);
|
||
}
|
||
|
||
function resolveTeamStatusBadge(item: PortalTeamStatusItem) {
|
||
if (item.onLeave) {
|
||
return {
|
||
label: item.leaveType ? `请假 · ${item.leaveType}` : "请假",
|
||
className: "badge-warning",
|
||
};
|
||
}
|
||
if (item.presenceStatus === "office") {
|
||
return { label: "在岗", className: "badge-success" };
|
||
}
|
||
if (item.presenceStatus === "out") {
|
||
return {
|
||
label: "外出",
|
||
className: "inline-flex items-center rounded-full bg-sky-50 px-2.5 py-0.5 text-xs font-semibold text-sky-700 ring-1 ring-inset ring-sky-600/10",
|
||
};
|
||
}
|
||
if (item.presenceStatus === "travel") {
|
||
return {
|
||
label: "差旅",
|
||
className: "inline-flex items-center rounded-full bg-sky-50 px-2.5 py-0.5 text-xs font-semibold text-sky-700 ring-1 ring-inset ring-sky-600/10",
|
||
};
|
||
}
|
||
if (item.presenceStatus === "remote") {
|
||
return { label: "居家", className: "badge-neutral" };
|
||
}
|
||
if (!item.attendanceClockIn) {
|
||
return { label: "未打卡", className: "badge-neutral" };
|
||
}
|
||
return {
|
||
label: "已打卡",
|
||
className: "inline-flex items-center rounded-full bg-slate-100 px-2.5 py-0.5 text-xs font-semibold text-slate-700 ring-1 ring-inset ring-slate-600/10",
|
||
};
|
||
}
|
||
|
||
function formatTeamStatusAttendance(item: PortalTeamStatusItem) {
|
||
if (item.onLeave) {
|
||
return item.leaveType ? `${item.leaveType} 已审批` : "今日请假";
|
||
}
|
||
if (item.attendanceClockIn && item.attendanceClockOut) {
|
||
return `${formatShortTime(item.attendanceClockIn)} - ${formatShortTime(item.attendanceClockOut)}`;
|
||
}
|
||
if (item.attendanceClockIn) {
|
||
return `${formatShortTime(item.attendanceClockIn)} 已打卡`;
|
||
}
|
||
if (item.presenceStatus === "travel") {
|
||
return "今日差旅";
|
||
}
|
||
if (item.presenceStatus === "out") {
|
||
return "当前外出";
|
||
}
|
||
if (item.presenceStatus === "remote") {
|
||
return "今日居家办公";
|
||
}
|
||
return "暂无打卡记录";
|
||
}
|
||
|
||
function resolveClockAction(
|
||
attendanceToday: AttendanceTodayResponse | null,
|
||
state: {
|
||
isLoading: boolean;
|
||
isError: boolean;
|
||
featureDisabled: boolean;
|
||
pending: boolean;
|
||
},
|
||
) {
|
||
if (state.pending) {
|
||
return {
|
||
label: "处理中...",
|
||
description: "正在提交考勤动作",
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
if (state.isLoading) {
|
||
return {
|
||
label: "打卡读取中",
|
||
description: "正在读取今日考勤状态",
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
if (state.isError && !state.featureDisabled) {
|
||
return {
|
||
label: "打卡不可用",
|
||
description: "当前无法读取今日考勤状态",
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
if (!attendanceToday) {
|
||
return {
|
||
label: "今日考勤",
|
||
description: "暂无可用考勤数据",
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
if (!attendanceToday.needClockIn) {
|
||
return {
|
||
label: "今日无需打卡",
|
||
description: "系统已自动排除缺卡统计",
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
if (!attendanceToday.item?.clockInAt) {
|
||
return {
|
||
label: "上班打卡",
|
||
description: "记录今日到岗时间",
|
||
disabled: false,
|
||
action: "clock-in",
|
||
} as const;
|
||
}
|
||
if (!attendanceToday.item.clockOutAt) {
|
||
return {
|
||
label: "下班打卡",
|
||
description: `已上班 ${formatShortTime(attendanceToday.item.clockInAt)}`,
|
||
disabled: false,
|
||
action: "clock-out",
|
||
} as const;
|
||
}
|
||
return {
|
||
label: "今日已完成",
|
||
description: `工时 ${formatWorkMinutes(attendanceToday.item.workMinutes)}`,
|
||
disabled: true,
|
||
action: null,
|
||
} as const;
|
||
}
|
||
|
||
function SummaryPanel({ title, items }: { title: string; items: SummaryItem[] }) {
|
||
if (!items.length) {
|
||
return <EmptyStateCard title={title} description="暂无需要优先处理的摘要信息。" />;
|
||
}
|
||
|
||
return (
|
||
<SectionPanel title={title} description="优先看结论与下一步,再进入对应模块处理。">
|
||
<div className="space-y-3">
|
||
{items.map((item) => (
|
||
<Link
|
||
key={item.key}
|
||
to={item.href}
|
||
className={item.tone === "warning"
|
||
? "block rounded-2xl border border-amber-200 bg-amber-50 px-4 py-4 hover:bg-amber-100"
|
||
: "block rounded-2xl border border-zinc-200 bg-white px-4 py-4 hover:bg-zinc-50"}
|
||
>
|
||
<div className="flex items-center justify-between gap-3">
|
||
<div className="font-medium text-zinc-900">{item.label}</div>
|
||
<div className="text-sm font-semibold text-zinc-900">{item.value}</div>
|
||
</div>
|
||
{item.note ? <div className="mt-2 text-sm leading-6 text-zinc-500">{item.note}</div> : null}
|
||
</Link>
|
||
))}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function AnnouncementsPanel({ announcements }: { announcements: PortalHomePayload["announcements"] }) {
|
||
const safeAnnouncements = Array.isArray(announcements) ? announcements : [];
|
||
|
||
return (
|
||
<SectionPanel
|
||
title="公告"
|
||
description="公告保留在第二阅读层,不与今日任务卡竞争。"
|
||
actions={<Link to="/announcements" className="text-sm font-medium text-primary hover:underline">查看全部</Link>}
|
||
>
|
||
<div className="space-y-3">
|
||
{safeAnnouncements.length ? safeAnnouncements.slice(0, 4).map((item) => (
|
||
<div key={item.id} className="rounded-2xl border border-zinc-200 bg-white px-4 py-4">
|
||
<div className="font-medium text-zinc-900">{item.title}</div>
|
||
<div className="mt-2 text-sm leading-6 text-zinc-600">{item.summary}</div>
|
||
{item.href ? (
|
||
<a className="mt-3 inline-flex text-sm font-medium text-primary hover:underline" href={item.href} rel="noreferrer" target="_blank">
|
||
查看详情
|
||
</a>
|
||
) : null}
|
||
</div>
|
||
)) : <EmptyStateCard title="暂无公告" description="当前没有需要广播的公告。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function RecentVisitsPanel() {
|
||
const recentVisits = readRecentVisits();
|
||
|
||
return (
|
||
<SectionPanel title="继续工作" description="保留最近访问路径,帮助快速回到上一次处理中断的位置。">
|
||
<div className="space-y-3">
|
||
{recentVisits.length ? recentVisits.map((item) => (
|
||
<Link key={item.path} to={item.path} className="block rounded-2xl border border-zinc-200 bg-white px-4 py-4 hover:bg-zinc-50">
|
||
<div className="font-medium text-zinc-900">{item.title}</div>
|
||
<div className="mt-1 text-xs text-zinc-500">{item.path}</div>
|
||
</Link>
|
||
)) : <EmptyStateCard title="暂无最近访问" description="开始使用后,最近处理过的页面会显示在这里。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function QuickLinksPanel({ items }: { items: PortalHomePayload["quickLinks"] }) {
|
||
const safeItems = Array.isArray(items) ? items : [];
|
||
|
||
return (
|
||
<SectionPanel title="常用入口" description="只保留高频入口,避免把所有模块堆成超市。">
|
||
<div className="grid gap-3 sm:grid-cols-2">
|
||
{safeItems.length ? safeItems.map((item) => (
|
||
<Link key={item.key} to={item.href} className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-sm font-medium text-zinc-700 hover:bg-zinc-50">
|
||
{item.title}
|
||
</Link>
|
||
)) : <EmptyStateCard title="暂无常用入口" description="工作区尚未配置推荐入口。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function SecondaryCardsPanel({ title, description, cards }: { title: string; description: string; cards: PortalHomePayload["cards"] }) {
|
||
if (!cards.length) {
|
||
return <EmptyStateCard title={title} description="暂无需要额外关注的统计项。" />;
|
||
}
|
||
|
||
return (
|
||
<SectionPanel title={title} description={description}>
|
||
<div className="grid gap-3 sm:grid-cols-2">
|
||
{cards.map((card) => (
|
||
<MetricCard
|
||
key={card.key}
|
||
title={card.title}
|
||
value={card.value}
|
||
href={card.href}
|
||
note="进入详情页处理"
|
||
tone={severityTone(card.severity)}
|
||
/>
|
||
))}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function AdoptionSummaryPanel({ adoptionSummary }: { adoptionSummary: NonNullable<PortalHomePayload["adoptionSummary"]> | null }) {
|
||
if (!adoptionSummary) {
|
||
return null;
|
||
}
|
||
|
||
return (
|
||
<details className="card-std p-6" open>
|
||
<summary className="flex cursor-pointer list-none items-center justify-between gap-3 text-left">
|
||
<div>
|
||
<div className="text-base font-semibold text-zinc-900">试点观测摘要</div>
|
||
<div className="mt-1 text-sm text-zinc-500">只给管理员默认展开,用于观察习惯是否已形成。</div>
|
||
</div>
|
||
<span className="text-xs uppercase tracking-[0.18em] text-zinc-400">展开 / 收起</span>
|
||
</summary>
|
||
<div className="mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||
<div className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-sm">
|
||
<div className="text-zinc-500">近 7 天登录覆盖率</div>
|
||
<div className="mt-2 text-2xl font-semibold tracking-tight text-zinc-900">{adoptionSummary.login7dRate}%</div>
|
||
</div>
|
||
<div className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-sm">
|
||
<div className="text-zinc-500">周报提交率</div>
|
||
<div className="mt-2 text-2xl font-semibold tracking-tight text-zinc-900">{adoptionSummary.weeklySubmissionRate}%</div>
|
||
</div>
|
||
<div className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-sm">
|
||
<div className="text-zinc-500">团队状态覆盖率</div>
|
||
<div className="mt-2 text-2xl font-semibold tracking-tight text-zinc-900">{adoptionSummary.presenceCoverageRate}%</div>
|
||
</div>
|
||
<div className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-sm">
|
||
<div className="text-zinc-500">当前公告数</div>
|
||
<div className="mt-2 text-2xl font-semibold tracking-tight text-zinc-900">{adoptionSummary.announcementCount}</div>
|
||
</div>
|
||
</div>
|
||
<div className="mt-4 rounded-2xl border border-zinc-200 bg-zinc-50 px-4 py-4 text-sm text-zinc-600">
|
||
<div className="font-medium text-zinc-900">本周观测提示</div>
|
||
<ul className="mt-2 list-disc space-y-1 pl-5">
|
||
{adoptionSummary.hints.map((hint) => (
|
||
<li key={hint}>{hint}</li>
|
||
))}
|
||
</ul>
|
||
</div>
|
||
</details>
|
||
);
|
||
}
|
||
|
||
function PortalSectionFallback({
|
||
title,
|
||
description,
|
||
}: {
|
||
title: string;
|
||
description: string;
|
||
}) {
|
||
return (
|
||
<SectionPanel title={title} description={description}>
|
||
<EmptyStateCard title={`${title}暂时不可用`} description="该区域渲染失败,请刷新页面后重试。" />
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function GettingStartedCard({
|
||
items,
|
||
completedCount,
|
||
onDismiss,
|
||
}: {
|
||
items: GettingStartedChecklistItem[];
|
||
completedCount: number;
|
||
onDismiss: () => void;
|
||
}) {
|
||
const progressPercent = items.length ? Math.round((completedCount / items.length) * 100) : 0;
|
||
|
||
return (
|
||
<SectionPanel
|
||
title="快速上手"
|
||
description="先完成基础资料和入口熟悉,再进入请假、通知等日常动作。"
|
||
actions={(
|
||
<button
|
||
type="button"
|
||
className="text-sm font-medium text-zinc-500 transition-colors hover:text-zinc-700"
|
||
data-testid="onboarding-getting-started-dismiss"
|
||
onClick={onDismiss}
|
||
>
|
||
关闭清单
|
||
</button>
|
||
)}
|
||
className="shadow-sm"
|
||
>
|
||
<div className="space-y-3" data-testid="onboarding-getting-started-card">
|
||
{items.map((item) => (
|
||
<Link
|
||
key={item.key}
|
||
to={item.href}
|
||
className="flex items-center gap-3 rounded-2xl border border-zinc-200 bg-white px-4 py-4 transition-colors hover:bg-zinc-50"
|
||
>
|
||
<span className={item.completed ? "text-emerald-600" : "text-zinc-400"}>
|
||
<span className="material-symbols-outlined text-[20px]">
|
||
{item.completed ? "check_circle" : "radio_button_unchecked"}
|
||
</span>
|
||
</span>
|
||
<div className="min-w-0 flex-1">
|
||
<div className="font-medium text-zinc-900">{item.title}</div>
|
||
<div className="mt-1 text-sm leading-6 text-zinc-500">{item.description}</div>
|
||
</div>
|
||
<span className="material-symbols-outlined text-zinc-400">arrow_forward</span>
|
||
</Link>
|
||
))}
|
||
|
||
<div className="rounded-2xl border border-zinc-200 bg-zinc-50 px-4 py-4">
|
||
<div className="flex items-center justify-between gap-3 text-sm">
|
||
<span className="font-medium text-zinc-900">完成进度</span>
|
||
<span className="text-zinc-500">{completedCount}/{items.length}</span>
|
||
</div>
|
||
<div className="mt-3 h-2 overflow-hidden rounded-full bg-zinc-200">
|
||
<div
|
||
className="h-full rounded-full bg-primary transition-all"
|
||
style={{ width: `${progressPercent}%` }}
|
||
/>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function QuickActionTile({
|
||
icon,
|
||
label,
|
||
description,
|
||
to,
|
||
onClick,
|
||
disabled = false,
|
||
}: QuickActionConfig) {
|
||
const baseClassName = disabled
|
||
? "rounded-2xl border border-zinc-200 bg-zinc-50 px-4 py-4 text-left text-zinc-400"
|
||
: "rounded-2xl border border-zinc-200 bg-white px-4 py-4 text-left shadow-sm transition-colors hover:bg-zinc-50";
|
||
|
||
const content = (
|
||
<>
|
||
<div className="flex items-center gap-3">
|
||
<div className={disabled
|
||
? "flex size-10 items-center justify-center rounded-2xl bg-zinc-100 text-zinc-400"
|
||
: "flex size-10 items-center justify-center rounded-2xl bg-primary/10 text-primary"}
|
||
>
|
||
<span className="material-symbols-outlined text-[20px]">{icon}</span>
|
||
</div>
|
||
<div className="min-w-0">
|
||
<div className={disabled ? "font-medium text-zinc-500" : "font-medium text-zinc-900"}>{label}</div>
|
||
<div className="mt-1 text-xs text-zinc-500">{description}</div>
|
||
</div>
|
||
</div>
|
||
</>
|
||
);
|
||
|
||
if (to && !disabled) {
|
||
return <Link to={to} className={baseClassName}>{content}</Link>;
|
||
}
|
||
if (onClick) {
|
||
return (
|
||
<button type="button" className={baseClassName} disabled={disabled} onClick={onClick}>
|
||
{content}
|
||
</button>
|
||
);
|
||
}
|
||
return <div className={baseClassName}>{content}</div>;
|
||
}
|
||
|
||
function QuickActionsPanel({
|
||
items,
|
||
}: {
|
||
items: QuickActionConfig[];
|
||
}) {
|
||
return (
|
||
<SectionPanel title="快捷操作栏" description="把每天高频动作直接前置到首页,不再绕路。">
|
||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||
{items.length ? items.map((item) => (
|
||
<QuickActionTile
|
||
key={item.key}
|
||
icon={item.icon}
|
||
label={item.label}
|
||
description={item.description}
|
||
to={item.to}
|
||
onClick={item.onClick}
|
||
disabled={item.disabled}
|
||
/>
|
||
)) : <EmptyStateCard title="暂无快捷动作" description="当前账号没有可直接执行的首页动作。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function TodoAggregatePanel({ items }: { items: TodoAggregateItem[] }) {
|
||
return (
|
||
<SectionPanel title="今日待办聚合" description="合并审批、TODO 和高风险指标,只保留今天最该处理的事。">
|
||
<div className="space-y-3">
|
||
{items.length ? items.map((item) => (
|
||
<Link key={`${item.title}-${item.href}-${item.sourceLabel}`} to={item.href} className="block rounded-2xl border border-zinc-200 bg-white px-4 py-4 hover:bg-zinc-50">
|
||
<div className="flex items-start gap-3">
|
||
<div className={item.severity === "high"
|
||
? "mt-0.5 flex size-9 items-center justify-center rounded-2xl bg-red-50 text-red-600"
|
||
: item.severity === "warning"
|
||
? "mt-0.5 flex size-9 items-center justify-center rounded-2xl bg-amber-50 text-amber-600"
|
||
: "mt-0.5 flex size-9 items-center justify-center rounded-2xl bg-zinc-100 text-zinc-600"}
|
||
>
|
||
<span className="material-symbols-outlined text-[18px]">{item.icon}</span>
|
||
</div>
|
||
<div className="min-w-0 flex-1">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<div className="font-medium text-zinc-900">{item.title}</div>
|
||
<span className="badge-neutral">{item.sourceLabel}</span>
|
||
{item.severity === "high" ? <span className="badge-error">高优先</span> : null}
|
||
{item.severity === "warning" ? <span className="badge-warning">关注</span> : null}
|
||
</div>
|
||
<div className="mt-2 text-sm text-primary">进入处理</div>
|
||
</div>
|
||
</div>
|
||
</Link>
|
||
)) : <EmptyStateCard title="暂无待办事项,休息一下吧" description="当前没有需要立刻处理的审批、TODO 或风险提醒。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function TeamStatusBoardPanel({ items }: { items: PortalTeamStatusItem[] }) {
|
||
const safeItems = Array.isArray(items) ? items : [];
|
||
|
||
return (
|
||
<SectionPanel title="团队全员状态" description="同时看人在不在岗、有没有请假,以及今天是否已打卡。">
|
||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
|
||
{safeItems.length ? safeItems.map((item) => {
|
||
const badge = resolveTeamStatusBadge(item);
|
||
return (
|
||
<div key={item.employeeId} className="rounded-2xl border border-zinc-200 bg-white px-4 py-4">
|
||
<div className="flex items-center gap-3">
|
||
<EmployeeAvatar name={item.name} src={item.avatarUrl} size="sm" />
|
||
<div className="min-w-0 flex-1">
|
||
<div className="truncate font-medium text-zinc-900">{item.name}</div>
|
||
<div className="mt-1 text-xs text-zinc-500">{formatTeamStatusAttendance(item)}</div>
|
||
</div>
|
||
<span className={badge.className}>{badge.label}</span>
|
||
</div>
|
||
</div>
|
||
);
|
||
}) : <EmptyStateCard title="暂无团队状态" description="当前没有可展示的团队成员状态。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
function RecentActivitiesPanel({ items }: { items: PortalRecentActivity[] }) {
|
||
const safeItems = Array.isArray(items) ? items : [];
|
||
|
||
return (
|
||
<SectionPanel title="近期动态流" description="把最近发生的报销、请假、考勤和资产动作放在同一条时间线上。">
|
||
<div className="space-y-3">
|
||
{safeItems.length ? safeItems.map((item) => (
|
||
<Link key={item.id} to={item.href} className="block rounded-2xl border border-zinc-200 bg-white px-4 py-4 hover:bg-zinc-50">
|
||
<div className="flex items-start gap-3">
|
||
<EmployeeAvatar name={item.actorName} size="sm" />
|
||
<div className="min-w-0 flex-1">
|
||
<div className="text-sm font-medium leading-6 text-zinc-900">{item.summary}</div>
|
||
<div className="mt-1 text-xs text-zinc-500">{formatRelativeTime(item.createdAt)}</div>
|
||
</div>
|
||
</div>
|
||
</Link>
|
||
)) : <EmptyStateCard title="暂无近期动态" description="当前没有可展示的最近业务动作。" />}
|
||
</div>
|
||
</SectionPanel>
|
||
);
|
||
}
|
||
|
||
export function PortalHomePage() {
|
||
const queryClient = useQueryClient();
|
||
const { me, permissions } = useAuth();
|
||
const [showWelcome, setShowWelcome] = useState(false);
|
||
const [showGettingStarted, setShowGettingStarted] = useState(false);
|
||
const portalQuery = useQuery({ queryKey: ["portal-home"], queryFn: () => fetchPortalHome() });
|
||
const attendanceTodayQuery = useQuery({
|
||
queryKey: ["portal-home", "attendance", "today"],
|
||
queryFn: () => fetchMyTodayAttendance(),
|
||
retry: (failureCount, error) => !isAttendanceFeatureDisabled(error) && failureCount < 2,
|
||
});
|
||
const canSetupWorkspace = hasAnyPermission(permissions, ["system.settings"]);
|
||
const isManagerView = isManagerRole(permissions);
|
||
|
||
useEffect(() => {
|
||
setShowWelcome(shouldShowWelcomeDialog());
|
||
setShowGettingStarted(shouldShowGettingStartedCard());
|
||
}, []);
|
||
|
||
const gettingStartedItems: GettingStartedChecklistItem[] = [
|
||
{
|
||
key: "profile",
|
||
title: "完善个人资料",
|
||
description: "补充紧急联系人和银行账户",
|
||
href: "/settings/profile",
|
||
completed: (me?.profileCompleteness?.score ?? 0) >= 50,
|
||
},
|
||
{
|
||
key: "notification-preferences",
|
||
title: "设置通知偏好",
|
||
description: "选择是否接收外部渠道推送",
|
||
href: "/settings/profile",
|
||
completed: true,
|
||
},
|
||
{
|
||
key: "leave-flow",
|
||
title: "了解请假流程",
|
||
description: "查看假期类型和余额",
|
||
href: "/leave-requests",
|
||
completed: false,
|
||
},
|
||
{
|
||
key: "notifications",
|
||
title: "查看通知中心",
|
||
description: "了解审批和业务消息",
|
||
href: "/notifications",
|
||
completed: false,
|
||
},
|
||
];
|
||
const gettingStartedCompletedCount = gettingStartedItems.filter((item) => item.completed).length;
|
||
|
||
const attendanceClockInMutation = useMutation({
|
||
mutationFn: () => clockInAttendance(),
|
||
onSuccess: async (response) => {
|
||
await Promise.all([
|
||
queryClient.invalidateQueries({ queryKey: ["portal-home"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["portal-home", "attendance", "today"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["attendance", "me", "today"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["attendance", "me", "month"] }),
|
||
]);
|
||
toast.success(
|
||
response.item.isLate
|
||
? `上班打卡成功,已迟到 ${response.item.lateMinutes} 分钟`
|
||
: "上班打卡成功",
|
||
);
|
||
},
|
||
onError: (error) => {
|
||
toast.error(resolveErrorMessage(error));
|
||
},
|
||
});
|
||
|
||
const attendanceClockOutMutation = useMutation({
|
||
mutationFn: () => clockOutAttendance(),
|
||
onSuccess: async () => {
|
||
await Promise.all([
|
||
queryClient.invalidateQueries({ queryKey: ["portal-home"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["portal-home", "attendance", "today"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["attendance", "me", "today"] }),
|
||
queryClient.invalidateQueries({ queryKey: ["attendance", "me", "month"] }),
|
||
]);
|
||
toast.success("下班打卡成功");
|
||
},
|
||
onError: (error) => {
|
||
toast.error(resolveErrorMessage(error));
|
||
},
|
||
});
|
||
|
||
if (portalQuery.isLoading) {
|
||
return <div className="card-std p-6 text-sm text-zinc-500">加载 Portal 中...</div>;
|
||
}
|
||
|
||
if (portalQuery.isError || !portalQuery.data) {
|
||
const message = isApiError(portalQuery.error)
|
||
? `${portalQuery.error.code}: ${mapApiErrorMessage(portalQuery.error.code, portalQuery.error.details, portalQuery.error.message)}`
|
||
: "Portal 加载失败";
|
||
return <div className="card-std p-6 text-sm text-red-600">{message}</div>;
|
||
}
|
||
|
||
const payload = portalQuery.data;
|
||
const cards = Array.isArray(payload.cards) ? payload.cards : [];
|
||
const applicationItems = Array.isArray(payload.myApplications) ? payload.myApplications : [];
|
||
const announcementItems = Array.isArray(payload.announcements) ? payload.announcements : [];
|
||
const quickLinkItems = Array.isArray(payload.quickLinks) ? payload.quickLinks : [];
|
||
const recentActivities = Array.isArray(payload.recentActivities) ? payload.recentActivities : [];
|
||
const teamStatusBoard = Array.isArray(payload.teamStatusBoard) ? payload.teamStatusBoard : [];
|
||
const portalSchema = isManagerView ? managerPortalSchema : employeePortalSchema;
|
||
const primaryCards = pickCards(cards, portalSchema.heroCards);
|
||
const primaryCardKeySet = primaryCards.map((card) => card.key);
|
||
const secondaryCards = compactCards(cards, primaryCardKeySet);
|
||
const attendanceFeatureDisabled = isAttendanceFeatureDisabled(attendanceTodayQuery.error);
|
||
const attendanceToday = attendanceTodayQuery.data ?? null;
|
||
const clockAction = resolveClockAction(attendanceToday, {
|
||
isLoading: attendanceTodayQuery.isLoading,
|
||
isError: attendanceTodayQuery.isError,
|
||
featureDisabled: attendanceFeatureDisabled,
|
||
pending: attendanceClockInMutation.isPending || attendanceClockOutMutation.isPending,
|
||
});
|
||
const todoAggregateItems = buildTodoAggregateItems({ ...payload, cards });
|
||
|
||
function handleCloseWelcome() {
|
||
clearWelcomeDialogFlag();
|
||
setShowWelcome(false);
|
||
}
|
||
|
||
function handleDismissGettingStarted() {
|
||
dismissGettingStartedCard();
|
||
setShowGettingStarted(false);
|
||
}
|
||
|
||
const employeeSummaryItems = ([
|
||
{
|
||
key: "expense",
|
||
href: "/reimbursements",
|
||
label: "我的报销",
|
||
value: `${applicationItems.find((item) => item.domain === "reimbursement")?.count ?? 0} 条`,
|
||
},
|
||
{
|
||
key: "leave",
|
||
href: "/leave-requests",
|
||
label: "我的请假",
|
||
value: `${applicationItems.find((item) => item.domain === "leave")?.count ?? 0} 条`,
|
||
},
|
||
{
|
||
key: "assets",
|
||
href: "/assets",
|
||
label: "我的资产",
|
||
value: String(secondaryCards.find((card) => card.key === "my_assets")?.value ?? 0),
|
||
},
|
||
payload.todayPresence
|
||
? {
|
||
key: "today-status-note",
|
||
href: payload.todayPresence.href,
|
||
label: "今日状态",
|
||
value: payload.todayPresence.label,
|
||
note: payload.todayPresence.note ?? "可在团队页手动更新在岗、居家、外出或出差状态。",
|
||
tone: payload.todayPresence.status === "leave" ? "warning" as const : "normal" as const,
|
||
}
|
||
: null,
|
||
] as Array<SummaryItem | null>).filter(isSummaryItem);
|
||
|
||
const managerSummaryItems = ([
|
||
{
|
||
key: "team-summary",
|
||
href: payload.teamPresence?.href ?? "/team",
|
||
label: "今日团队状态",
|
||
value: payload.teamPresence ? `在岗 ${payload.teamPresence.office}/${payload.teamPresence.total}` : "待启用",
|
||
note: payload.teamPresence ? `请假 ${payload.teamPresence.leave},未更新 ${payload.teamPresence.unspecified}` : "团队状态板可展示在岗、居家、外出、出差与请假。",
|
||
tone: payload.teamPresence && (payload.teamPresence.leave > 0 || payload.teamPresence.unspecified > 0) ? "warning" as const : "normal" as const,
|
||
},
|
||
payload.weeklySummary
|
||
? {
|
||
key: "weekly-summary",
|
||
href: payload.weeklySummary.href,
|
||
label: "未提交周报",
|
||
value: `${payload.weeklySummary.missingCount} 人`,
|
||
note: `需协助 ${payload.weeklySummary.needsHelpCount} 人`,
|
||
tone: payload.weeklySummary.missingCount > 0 ? "warning" as const : "normal" as const,
|
||
}
|
||
: null,
|
||
] as Array<SummaryItem | null>).filter(isSummaryItem);
|
||
|
||
const quickActions: QuickActionConfig[] = [];
|
||
if (hasAnyPermission(permissions, LEAVE_PORTAL_PERMISSIONS)) {
|
||
quickActions.push({
|
||
key: "leave",
|
||
icon: "event_available",
|
||
label: "提交请假",
|
||
description: "直接进入请假申请页",
|
||
to: "/leave-requests?action=create",
|
||
});
|
||
}
|
||
if (hasAnyPermission(permissions, EXPENSE_PORTAL_PERMISSIONS)) {
|
||
quickActions.push({
|
||
key: "expense",
|
||
icon: "request_quote",
|
||
label: "提交报销",
|
||
description: "进入报销工作台创建单据",
|
||
to: "/reimbursements",
|
||
});
|
||
}
|
||
if (!attendanceFeatureDisabled) {
|
||
quickActions.push({
|
||
key: "attendance",
|
||
icon: clockAction.action === "clock-out" ? "logout" : "schedule",
|
||
label: clockAction.label,
|
||
description: clockAction.description,
|
||
disabled: clockAction.disabled,
|
||
onClick: clockAction.action === "clock-in"
|
||
? () => attendanceClockInMutation.mutate()
|
||
: clockAction.action === "clock-out"
|
||
? () => attendanceClockOutMutation.mutate()
|
||
: undefined,
|
||
});
|
||
}
|
||
if (payload.weeklyReport || payload.weeklySummary) {
|
||
quickActions.push({
|
||
key: "weekly",
|
||
icon: "article",
|
||
label: "提交周报",
|
||
description: "进入周报页继续填写或查看团队缺口",
|
||
to: "/weekly-reports",
|
||
});
|
||
}
|
||
|
||
return (
|
||
<PageScaffold>
|
||
<ErrorBoundary fallback={null}>
|
||
<WelcomeDialog open={showWelcome} onClose={handleCloseWelcome} />
|
||
</ErrorBoundary>
|
||
|
||
<WorkbenchHero
|
||
eyebrow={isManagerView ? "管理工作台" : "个人工作台"}
|
||
title={`你好,${payload.greeting.name}`}
|
||
subtitle={isManagerView
|
||
? "先处理审批、团队状态和周报缺口,再进入项目与组织协同。"
|
||
: "先处理今天必须完成的事,再继续查看项目、周报和公告。"}
|
||
actions={
|
||
!payload.workspace.persisted && canSetupWorkspace ? (
|
||
<Button asChild variant="secondary" type="button">
|
||
<Link to="/system/workspace">完成工作区设置</Link>
|
||
</Button>
|
||
) : null
|
||
}
|
||
/>
|
||
|
||
<div className="grid gap-4 xl:grid-cols-4">
|
||
{primaryCards.map((card) => (
|
||
<MetricCard
|
||
key={card.key}
|
||
ariaLabel={`portal-card-${card.key}`}
|
||
href={card.href}
|
||
note={card.key === "my_weekly_report"
|
||
? formatWeeklyStatus(payload.weeklyReport)
|
||
: card.key === "today_presence"
|
||
? payload.todayPresence?.note ?? "更新今日状态"
|
||
: card.key === "team_presence"
|
||
? payload.teamPresence ? `请假 ${payload.teamPresence.leave},未更新 ${payload.teamPresence.unspecified}` : "团队状态板待启用"
|
||
: undefined}
|
||
title={card.title}
|
||
tone={severityTone(card.severity)}
|
||
value={card.value}
|
||
/>
|
||
))}
|
||
</div>
|
||
|
||
{showGettingStarted ? (
|
||
<ErrorBoundary
|
||
fallback={(
|
||
<PortalSectionFallback
|
||
title="快速上手"
|
||
description="先完成基础资料和入口熟悉,再进入请假、通知等日常动作。"
|
||
/>
|
||
)}
|
||
>
|
||
<GettingStartedCard
|
||
items={gettingStartedItems}
|
||
completedCount={gettingStartedCompletedCount}
|
||
onDismiss={handleDismissGettingStarted}
|
||
/>
|
||
</ErrorBoundary>
|
||
) : null}
|
||
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr),minmax(0,1fr)]">
|
||
<QuickActionsPanel items={quickActions} />
|
||
<TodoAggregatePanel items={todoAggregateItems} />
|
||
</div>
|
||
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1.15fr),minmax(0,0.85fr)]">
|
||
<ErrorBoundary
|
||
fallback={(
|
||
<PortalSectionFallback
|
||
title="团队全员状态"
|
||
description="同时看人在不在岗、有没有请假,以及今天是否已打卡。"
|
||
/>
|
||
)}
|
||
>
|
||
<TeamStatusBoardPanel items={teamStatusBoard} />
|
||
</ErrorBoundary>
|
||
<ErrorBoundary
|
||
fallback={(
|
||
<PortalSectionFallback
|
||
title="近期动态流"
|
||
description="把最近发生的报销、请假、考勤和资产动作放在同一条时间线上。"
|
||
/>
|
||
)}
|
||
>
|
||
<RecentActivitiesPanel items={recentActivities} />
|
||
</ErrorBoundary>
|
||
</div>
|
||
|
||
{isManagerView ? (
|
||
<>
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1.05fr),minmax(0,0.95fr)]">
|
||
<SummaryPanel title="今日管理重点" items={managerSummaryItems} />
|
||
<QuickLinksPanel items={quickLinkItems} />
|
||
</div>
|
||
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,0.95fr),minmax(0,1.05fr)]">
|
||
<AnnouncementsPanel announcements={announcementItems} />
|
||
<SecondaryCardsPanel
|
||
title="项目跟进与组织协同"
|
||
description="把项目、组织和风险类信息下移到第二阅读层。"
|
||
cards={secondaryCards}
|
||
/>
|
||
</div>
|
||
|
||
<AdoptionSummaryPanel adoptionSummary={payload.adoptionSummary} />
|
||
</>
|
||
) : (
|
||
<>
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1.1fr),minmax(0,0.9fr)]">
|
||
<SummaryPanel title="我的申请与资产" items={employeeSummaryItems} />
|
||
<AnnouncementsPanel announcements={announcementItems} />
|
||
</div>
|
||
|
||
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr),minmax(0,1fr)]">
|
||
<RecentVisitsPanel />
|
||
<QuickLinksPanel items={quickLinkItems} />
|
||
</div>
|
||
</>
|
||
)}
|
||
</PageScaffold>
|
||
);
|
||
}
|