R64 A1-A6:新员工入门引导

这个提交包含在:
2026-04-14 16:45:10 +08:00
父节点 86644a6766
当前提交 7ac0de660c
共修改 12 个文件,包含 453 行新增和 5 行删除
+9
查看文件
@@ -23,6 +23,14 @@ export type LoginResponse = {
mustChangePassword?: boolean;
};
export type ProfileCompleteness = {
hasEmergencyContact: boolean;
hasBankAccount: boolean;
hasAvatar: boolean;
hasIdNumber: boolean;
score: number;
};
export type MeResponse = {
id: string;
employeeNo: string;
@@ -34,6 +42,7 @@ export type MeResponse = {
status: string;
notificationPushEnabled: boolean;
roleCodes: string[];
profileCompleteness: ProfileCompleteness;
wecomBinding?: {
externalUserId: string;
createdAt: string | null;
+32 -3
查看文件
@@ -9,7 +9,7 @@ import {
useState,
} from "react";
import { configureHttpAuth } from "../api/http";
import type { AuthState, LoginResponse, MeResponse } from "../api/types";
import type { AuthState, LoginResponse, MeResponse, ProfileCompleteness } from "../api/types";
import { changePassword as changePasswordApi } from "../api/auth";
import { clearPwaRuntimeCaches } from "../pwa";
import {
@@ -53,6 +53,13 @@ const OFFLINE_AUTH_SNAPSHOT_VERSION = 1;
const OFFLINE_AUTH_SNAPSHOT_TTL_MS = 24 * 60 * 60 * 1000;
const PROACTIVE_REFRESH_RATIO = 0.8;
const MIN_REFRESH_DELAY_MS = 1000;
const DEFAULT_PROFILE_COMPLETENESS: ProfileCompleteness = {
hasEmergencyContact: false,
hasBankAccount: false,
hasAvatar: false,
hasIdNumber: false,
score: 0,
};
function isWindowAvailable() {
return typeof window !== "undefined";
@@ -69,6 +76,28 @@ function clearSessionHint() {
document.cookie = "has_session=; path=/; max-age=0";
}
function normalizeProfileCompleteness(value: unknown): ProfileCompleteness {
if (!value || typeof value !== "object") {
return DEFAULT_PROFILE_COMPLETENESS;
}
const payload = value as Partial<ProfileCompleteness>;
return {
hasEmergencyContact: Boolean(payload.hasEmergencyContact),
hasBankAccount: Boolean(payload.hasBankAccount),
hasAvatar: Boolean(payload.hasAvatar),
hasIdNumber: Boolean(payload.hasIdNumber),
score: typeof payload.score === "number" && Number.isFinite(payload.score) ? payload.score : 0,
};
}
function normalizeMeResponse(value: MeResponse | Partial<MeResponse>) {
return {
...value,
profileCompleteness: normalizeProfileCompleteness(value.profileCompleteness),
} as MeResponse;
}
function readMustChangePasswordFromStorage() {
return isWindowAvailable() && window.localStorage.getItem(MUST_CHANGE_PASSWORD_STORAGE_KEY) === "1";
}
@@ -110,7 +139,7 @@ function readOfflineAuthSnapshot() {
return {
version: OFFLINE_AUTH_SNAPSHOT_VERSION,
me: parsed.me,
me: normalizeMeResponse(parsed.me as Partial<MeResponse>),
permissions: parsed.permissions.map((item) => String(item)),
savedAt: savedAt.toISOString(),
} satisfies OfflineAuthSnapshot;
@@ -127,7 +156,7 @@ function writeOfflineAuthSnapshot(me: MeResponse, permissions: string[]) {
const snapshot: OfflineAuthSnapshot = {
version: OFFLINE_AUTH_SNAPSHOT_VERSION,
me,
me: normalizeMeResponse(me),
permissions,
savedAt: new Date().toISOString(),
};
@@ -0,0 +1,106 @@
import { Link } from "react-router-dom";
import { Button } from "../ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "../ui/dialog";
type WelcomeLinkItem = {
icon: string;
label: string;
description: string;
to: string;
};
const WELCOME_LINKS: WelcomeLinkItem[] = [
{
icon: "event_available",
label: "请假申请",
description: "提交和查看请假流程",
to: "/leave-requests",
},
{
icon: "request_quote",
label: "报销提交",
description: "进入报销工作台创建单据",
to: "/reimbursements",
},
{
icon: "schedule",
label: "考勤打卡",
description: "查看今日状态并完成打卡",
to: "/attendance",
},
{
icon: "manage_accounts",
label: "个人设置",
description: "补充资料并维护通知偏好",
to: "/settings/profile",
},
{
icon: "notifications",
label: "通知中心",
description: "查看审批和业务消息",
to: "/notifications",
},
];
export function WelcomeDialog({
open,
onClose,
}: {
open: boolean;
onClose: () => void;
}) {
return (
<Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && onClose()}>
<DialogContent className="max-w-2xl" data-testid="onboarding-welcome-dialog">
<DialogHeader>
<DialogTitle>欢迎加入海音达工作台!</DialogTitle>
<DialogDescription>
你的账号已就绪。以下是常用功能入口,点击即可开始使用:
</DialogDescription>
</DialogHeader>
<div className="grid gap-3 sm:grid-cols-2">
{WELCOME_LINKS.map((item) => (
<Link
key={item.label}
to={item.to}
onClick={onClose}
className="rounded-2xl border border-zinc-200 bg-white px-4 py-4 shadow-sm transition-colors hover:bg-zinc-50"
>
<div className="flex items-start gap-3">
<div className="flex size-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
<span className="material-symbols-outlined text-[20px]">{item.icon}</span>
</div>
<div className="min-w-0">
<div className="font-medium text-zinc-900">{item.label}</div>
<div className="mt-1 text-sm leading-6 text-zinc-500">{item.description}</div>
</div>
</div>
</Link>
))}
</div>
<div className="rounded-2xl border border-zinc-200 bg-zinc-50 px-4 py-3 text-sm text-zinc-600">
你可以随时在左侧菜单找到所有功能模块。
</div>
<DialogFooter>
<Button
type="button"
data-testid="onboarding-welcome-close"
onClick={onClose}
>
开始使用
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+48
查看文件
@@ -0,0 +1,48 @@
export const ONBOARDING_WELCOME_STORAGE_KEY = "hyb_oa_show_welcome";
export const ONBOARDING_ACTIVE_STORAGE_KEY = "hyb_oa_onboarding_active";
export const ONBOARDING_DISMISSED_STORAGE_KEY = "hyb_oa_getting_started_dismissed";
function canUseLocalStorage() {
return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
}
export function markOnboardingEntryReady() {
if (!canUseLocalStorage()) {
return;
}
window.localStorage.setItem(ONBOARDING_WELCOME_STORAGE_KEY, "1");
window.localStorage.setItem(ONBOARDING_ACTIVE_STORAGE_KEY, "1");
window.localStorage.removeItem(ONBOARDING_DISMISSED_STORAGE_KEY);
}
export function shouldShowWelcomeDialog() {
return canUseLocalStorage() && window.localStorage.getItem(ONBOARDING_WELCOME_STORAGE_KEY) === "1";
}
export function clearWelcomeDialogFlag() {
if (!canUseLocalStorage()) {
return;
}
window.localStorage.removeItem(ONBOARDING_WELCOME_STORAGE_KEY);
}
export function shouldShowGettingStartedCard() {
if (!canUseLocalStorage()) {
return false;
}
return (
window.localStorage.getItem(ONBOARDING_ACTIVE_STORAGE_KEY) === "1" &&
window.localStorage.getItem(ONBOARDING_DISMISSED_STORAGE_KEY) !== "1"
);
}
export function dismissGettingStartedCard() {
if (!canUseLocalStorage()) {
return;
}
window.localStorage.setItem(ONBOARDING_DISMISSED_STORAGE_KEY, "1");
}
+6
查看文件
@@ -7,6 +7,12 @@ export const TEST_IDS = {
topbar: {
profileTrigger: "topbar-profile-trigger",
},
onboarding: {
welcomeDialog: "onboarding-welcome-dialog",
welcomeClose: "onboarding-welcome-close",
gettingStartedCard: "onboarding-getting-started-card",
gettingStartedDismiss: "onboarding-getting-started-dismiss",
},
workflow: {
tasksTable: "workflow-tasks-table",
taskRow: "workflow-task-row",
+2 -1
查看文件
@@ -6,6 +6,7 @@ import { useAuth } from "../auth/AuthContext";
import { Button } from "../components/ui/button";
import { Input } from "../components/ui/input";
import { Label } from "../components/ui/label";
import { markOnboardingEntryReady } from "../lib/onboardingGuide";
const PASSWORD_REQUIREMENTS = [
"至少 12 位",
@@ -35,6 +36,7 @@ export function ChangePasswordPage() {
setSubmitting(true);
try {
await changePassword(oldPassword, newPassword);
markOnboardingEntryReady();
navigate("/portal", { replace: true });
} catch (err) {
if (isApiError(err)) {
@@ -127,4 +129,3 @@ export function ChangePasswordPage() {
</div>
);
}
+139 -1
查看文件
@@ -1,3 +1,4 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
@@ -19,12 +20,19 @@ import { useAuth } from "../auth/AuthContext";
import { hasAnyPermission, isManagerRole } from "../auth/permissions";
import { EmployeeAvatar } from "../components/common/EmployeeAvatar";
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 = {
@@ -54,6 +62,14 @@ type QuickActionConfig = {
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 = {
@@ -481,6 +497,70 @@ function AdoptionSummaryPanel({ adoptionSummary }: { adoptionSummary: NonNullabl
);
}
function GettingStartedCard({
items,
completedCount,
onDismiss,
}: {
items: GettingStartedChecklistItem[];
completedCount: number;
onDismiss: () => void;
}) {
const progressPercent = Math.round((completedCount / items.length) * 100);
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,
@@ -625,7 +705,9 @@ function RecentActivitiesPanel({ items }: { items: PortalRecentActivity[] }) {
export function PortalHomePage() {
const queryClient = useQueryClient();
const { permissions } = useAuth();
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"],
@@ -635,6 +717,11 @@ export function PortalHomePage() {
const canSetupWorkspace = hasAnyPermission(permissions, ["system.settings"]);
const isManagerView = isManagerRole(permissions);
useEffect(() => {
setShowWelcome(shouldShowWelcomeDialog());
setShowGettingStarted(shouldShowGettingStartedCard());
}, []);
const attendanceClockInMutation = useMutation({
mutationFn: () => clockInAttendance(),
onSuccess: async (response) => {
@@ -696,6 +783,47 @@ export function PortalHomePage() {
pending: attendanceClockInMutation.isPending || attendanceClockOutMutation.isPending,
});
const todoAggregateItems = buildTodoAggregateItems(payload);
const gettingStartedItems = useMemo<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,
},
]), [me?.profileCompleteness.score]);
const gettingStartedCompletedCount = gettingStartedItems.filter((item) => item.completed).length;
function handleCloseWelcome() {
clearWelcomeDialogFlag();
setShowWelcome(false);
}
function handleDismissGettingStarted() {
dismissGettingStartedCard();
setShowGettingStarted(false);
}
const employeeSummaryItems = ([
{
@@ -794,6 +922,8 @@ export function PortalHomePage() {
return (
<PageScaffold>
<WelcomeDialog open={showWelcome} onClose={handleCloseWelcome} />
<WorkbenchHero
eyebrow={isManagerView ? "管理工作台" : "个人工作台"}
title={`你好,${payload.greeting.name}`}
@@ -829,6 +959,14 @@ export function PortalHomePage() {
))}
</div>
{showGettingStarted ? (
<GettingStartedCard
items={gettingStartedItems}
completedCount={gettingStartedCompletedCount}
onDismiss={handleDismissGettingStarted}
/>
) : null}
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr),minmax(0,1fr)]">
<QuickActionsPanel items={quickActions} />
<TodoAggregatePanel items={todoAggregateItems} />
+7
查看文件
@@ -47,6 +47,13 @@ export type MeResponse = {
email: string;
roleCodes: string[];
permissions: string[];
profileCompleteness?: {
hasEmergencyContact: boolean;
hasBankAccount: boolean;
hasAvatar: boolean;
hasIdNumber: boolean;
score: number;
};
};
export type AuthenticatedApiClient = {
+31
查看文件
@@ -1,6 +1,7 @@
import { expect, test } from "@playwright/test";
import { EMPLOYEE, login } from "./helpers/auth";
import { TEST_IDS } from "./helpers/testIds";
const ADMIN = { identifier: "[email protected]", password: "AdminPassword1234", name: "Admin" };
@@ -25,7 +26,15 @@ function mockMe(page: import("@playwright/test").Page, roleCodes: string[], name
departmentId: "dept-1",
directManagerId: null,
status: "active",
notificationPushEnabled: true,
roleCodes,
profileCompleteness: {
hasEmergencyContact: true,
hasBankAccount: true,
hasAvatar: false,
hasIdNumber: false,
score: 50,
},
wecomBinding: null,
})),
});
@@ -258,6 +267,28 @@ test("Portal 管理视角重排正确,备用模块默认折叠", async ({ page
await expect(page.getByRole("link", { name: "采购申请" })).toBeVisible();
});
test("Portal 新员工引导先显示欢迎弹窗,再显示快速上手清单", async ({ page }) => {
await page.addInitScript(() => {
window.localStorage.setItem("hyb_oa_show_welcome", "1");
window.localStorage.setItem("hyb_oa_onboarding_active", "1");
window.localStorage.removeItem("hyb_oa_getting_started_dismissed");
});
await mockNavigation(page, "employee");
await mockPortalHome(page, "employee");
await mockAttendanceToday(page);
await mockMe(page, ["employee"], "Employee");
await login(page, EMPLOYEE);
await expect(page.getByTestId(TEST_IDS.onboarding.welcomeDialog)).toBeVisible();
await page.getByTestId(TEST_IDS.onboarding.welcomeClose).click();
await expect(page.getByTestId(TEST_IDS.onboarding.welcomeDialog)).not.toBeVisible();
await expect(page.getByTestId(TEST_IDS.onboarding.gettingStartedCard)).toBeVisible();
await page.getByTestId(TEST_IDS.onboarding.gettingStartedDismiss).click();
await expect(page.getByTestId(TEST_IDS.onboarding.gettingStartedCard)).not.toBeVisible();
});
test("Portal 域管理角色也进入经理视图", async ({ page }) => {
await mockNavigation(page, "manager");
await mockPortalHome(page, "manager");