diff --git a/src/App.tsx b/src/App.tsx index 56c82e3..42ac955 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -6,6 +6,7 @@ import { RequireAuth } from './components/RequireAuth'; import { LoginPage } from './pages/LoginPage'; import { PageRenderPage } from './pages/PageRenderPage'; import { TodoPage } from './pages/TodoPage'; +import { WorkbenchPage } from './pages/WorkbenchPage'; // 把 401 跳登录的 handler 注入 http 层(在路由上下文内,可用 navigate) function UnauthorizedBridge() { @@ -32,10 +33,12 @@ export default function App() { } > + {/* 工作台首页(F1-3)*/} + } /> } /> } /> - {/* 根路径默认跳待办 */} - } /> + {/* 根路径默认跳工作台 */} + } /> {/* 兜底 */} diff --git a/src/api/done.ts b/src/api/done.ts new file mode 100644 index 0000000..4fe337e --- /dev/null +++ b/src/api/done.ts @@ -0,0 +1,44 @@ +// 已办聚合 API —— GET /api/done +// 与待办接口同网关,引擎不可达时同样返回 503;前端据此降级。 +import { http } from './http'; + +export interface DoneItem { + taskId?: string; + taskName?: string; + assignee?: string; + businessKey?: string; + businessTable?: string | null; + businessSummary?: Record; + /** 办理结果:agree / reject / transfer 等后端枚举,显示时做映射 */ + result?: string; + /** 办理时间 */ + endTime?: string; + processInstanceId?: string; + [key: string]: unknown; +} + +export interface DoneResult { + items: DoneItem[]; + unavailable: boolean; + message?: string; +} + +export async function fetchDone(firstResult = 0, maxResults = 20): Promise { + try { + const { data } = await http.get('/api/done', { + params: { firstResult, maxResults }, + }); + const items = Array.isArray(data) ? data : (data?.items ?? []); + return { items, unavailable: false }; + } catch (err) { + const e = err as { response?: { status?: number; data?: { message?: string } } }; + if (e.response?.status === 503) { + return { + items: [], + unavailable: true, + message: e.response.data?.message || '工作流引擎服务暂不可达,请稍后重试', + }; + } + throw err; + } +} diff --git a/src/pages/TodoPage.tsx b/src/pages/TodoPage.tsx index 77e29a9..f167f31 100644 --- a/src/pages/TodoPage.tsx +++ b/src/pages/TodoPage.tsx @@ -1,114 +1,420 @@ -// 待办列表页 /todo —— 调 /api/todo,列表 + 点击进对应业务页占位 -// flowable-service 不起时网关 503,本页降级展示提示(不崩)。 +// 待办中心 /todo +// 参照 screens-home.jsx TodoCenter + DoneList 升级: +// - Tab 切换:「待办」/ 「已办」 +// - 待办:本地关键字筛选(taskName / businessTable)+ 点击跳业务页(pageUrl 优先) +// - 已办:GET /api/done,同样支持关键字筛选 +// - 批量操作:后端暂无批量端点,不做(不发明假按钮) +// - pageUrl 字段:P4-6 已实现映射,优先使用;缺失时按 businessTable 推算 import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { fetchTodo, type TodoItem } from '../api/todo'; +import { fetchDone, type DoneItem } from '../api/done'; +import { Pagination } from '../components/ui/Pagination'; +import { Icon } from '../components/ui/Icon'; -export function TodoPage() { - const navigate = useNavigate(); - const [items, setItems] = useState([]); - const [unavailable, setUnavailable] = useState(false); - const [message, setMessage] = useState(''); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(''); +const PAGE_SIZE = 20; - useEffect(() => { - let alive = true; - fetchTodo() - .then((r) => { - if (!alive) return; - setItems(r.items); - setUnavailable(r.unavailable); - setMessage(r.message || ''); - }) - .catch((e: Error) => alive && setError(e.message)) - .finally(() => alive && setLoading(false)); - return () => { - alive = false; - }; - }, []); - - const openBusiness = (item: TodoItem) => { - // 占位:按业务表跳对应业务页(本期无 表→templateId 映射表,跳通用占位并带参) - const tpl = item.businessTable ? String(item.businessTable).toLowerCase() : 'usergroup-manage'; - navigate(`/page/${tpl}`, { state: { businessKey: item.businessKey } }); - }; - - return ( -
-

我的待办

- - {loading &&
加载中…
} - - {!loading && unavailable && ( -
- ⚠ 工作流引擎暂不可达(网关 503 熔断降级):{message || '请稍后重试'} -
- 单体侧待办聚合依赖 flowable-service;引擎宕机时本页降级,不影响其他页面。 -
-
- )} - - {!loading && error &&
请求失败:{error}
} - - {!loading && !unavailable && !error && items.length === 0 && ( -
暂无待办。
- )} - - {!loading && items.length > 0 && ( - - - - - - - - - - - {items.map((it, idx) => ( - - - - - - - ))} - -
任务名业务摘要业务表操作
{it.taskName || '-'}{summarize(it)}{it.businessTable || (无映射)} - -
- )} -
- ); -} - -function summarize(it: TodoItem): string { +// --------------------------------------------------------------------------- +// 工具 +// --------------------------------------------------------------------------- +function summarize(it: TodoItem | DoneItem): string { const s = it.businessSummary; if (s && typeof s === 'object') { const vals = Object.values(s).filter((v) => v != null && v !== ''); if (vals.length) return vals.slice(0, 2).map(String).join(' / '); } - return it.businessKey ? `businessKey:${it.businessKey}` : '-'; + return it.businessKey ? `${String(it.businessKey)}` : '-'; } -const thStyle: React.CSSProperties = { padding: '10px 12px', fontSize: 13, color: '#555' }; -const tdStyle: React.CSSProperties = { padding: '10px 12px', fontSize: 13, color: '#333' }; -const linkBtnStyle: React.CSSProperties = { - background: 'transparent', - border: 'none', - color: '#2468f2', - cursor: 'pointer', - fontSize: 13, -}; +// --------------------------------------------------------------------------- +// 待办列表 +// --------------------------------------------------------------------------- +function TodoList() { + const navigate = useNavigate(); + const [allItems, setAllItems] = useState([]); + const [unavailable, setUnavailable] = useState(false); + const [unavailMsg, setUnavailMsg] = useState(''); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [keyword, setKeyword] = useState(''); + const [page, setPage] = useState(1); + + useEffect(() => { + let alive = true; + setLoading(true); + setError(''); + fetchTodo(0, 200) + .then((r) => { + if (!alive) return; + setAllItems(r.items); + setUnavailable(r.unavailable); + setUnavailMsg(r.message || ''); + }) + .catch((e: Error) => alive && setError(e.message)) + .finally(() => alive && setLoading(false)); + return () => { alive = false; }; + }, []); + + // 关键字本地过滤(taskName / businessTable 均参与) + const filtered = keyword + ? allItems.filter( + (it) => + (it.taskName && String(it.taskName).includes(keyword)) || + (it.businessTable && String(it.businessTable).includes(keyword)) || + (it.businessKey && String(it.businessKey).includes(keyword)), + ) + : allItems; + + const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); + const safePage = Math.min(page, totalPages); + const pageItems = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE); + + const openBusiness = (item: TodoItem) => { + const pageUrl = item.pageUrl as string | undefined; + if (pageUrl) { + navigate(pageUrl); + return; + } + // pageUrl 缺失时按 businessTable 推算(等待 P4-6 映射全量上线) + const tpl = item.businessTable ? String(item.businessTable).toLowerCase() : 'usergroup-manage'; + navigate(`/page/${tpl}`, { state: { businessKey: item.businessKey } }); + }; + + return ( +
+ {/* 筛选栏 */} +
+ + { setKeyword(e.target.value); setPage(1); }} + /> + {keyword && ( + + )} + + 共 {filtered.length} 条 + +
+ + {/* 降级提示 */} + {!loading && unavailable && ( +
+ ⚠ 工作流引擎暂不可达(503 熔断降级):{unavailMsg || '请稍后重试'} +
+ )} + + {loading &&
加载中…
} + {!loading && error &&
请求失败:{error}
} + + {/* 表格 */} + {!loading && !unavailable && !error && ( +
+ + + + + + + + + + + + {pageItems.length === 0 ? ( + + + + ) : ( + pageItems.map((it, idx) => ( + openBusiness(it)} + > + + + + + + + )) + )} + +
单据类型流程 / 任务名称业务摘要到达时间操作
+ {keyword ? '无匹配结果' : '暂无待办'} +
+ + {it.businessTable ? String(it.businessTable).slice(0, 8) : '待办'} + + + + {it.taskName || '(无标题)'} + + + {summarize(it)} + + {it.createTime ? String(it.createTime).slice(0, 16) : '-'} + + +
+
+ )} + + {!loading && !unavailable && !error && filtered.length > PAGE_SIZE && ( + + )} +
+ ); +} + +// --------------------------------------------------------------------------- +// 已办列表 +// --------------------------------------------------------------------------- + +/** 办理结果枚举映射 */ +function resultLabel(result?: string): { text: string; cls: string } { + if (!result) return { text: '-', cls: 'tag-gray' }; + const map: Record = { + agree: { text: '同意', cls: 'tag-ok' }, + reject: { text: '驳回', cls: 'tag-err' }, + transfer: { text: '转办', cls: 'tag-warn' }, + complete: { text: '完成', cls: 'tag-ok' }, + approved: { text: '同意', cls: 'tag-ok' }, + rejected: { text: '驳回', cls: 'tag-err' }, + }; + return map[result.toLowerCase()] ?? { text: result, cls: 'tag-gray' }; +} + +function DoneList() { + const [allItems, setAllItems] = useState([]); + const [unavailable, setUnavailable] = useState(false); + const [unavailMsg, setUnavailMsg] = useState(''); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(''); + const [keyword, setKeyword] = useState(''); + const [page, setPage] = useState(1); + + useEffect(() => { + let alive = true; + setLoading(true); + setError(''); + fetchDone(0, 200) + .then((r) => { + if (!alive) return; + setAllItems(r.items); + setUnavailable(r.unavailable); + setUnavailMsg(r.message || ''); + }) + .catch((e: Error) => alive && setError(e.message)) + .finally(() => alive && setLoading(false)); + return () => { alive = false; }; + }, []); + + const filtered = keyword + ? allItems.filter( + (it) => + (it.taskName && String(it.taskName).includes(keyword)) || + (it.businessTable && String(it.businessTable).includes(keyword)) || + (it.businessKey && String(it.businessKey).includes(keyword)), + ) + : allItems; + + const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE)); + const safePage = Math.min(page, totalPages); + const pageItems = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE); + + return ( +
+ {/* 筛选栏 */} +
+ + { setKeyword(e.target.value); setPage(1); }} + /> + {keyword && ( + + )} + + 共 {filtered.length} 条 + +
+ + {!loading && unavailable && ( +
+ ⚠ 已办数据暂时不可用:{unavailMsg || '请稍后重试'} +
+ )} + + {loading &&
加载中…
} + {!loading && error &&
请求失败:{error}
} + + {!loading && !unavailable && !error && ( +
+ + + + + + + + + + + + {pageItems.length === 0 ? ( + + + + ) : ( + pageItems.map((it, idx) => { + const r = resultLabel(it.result); + return ( + + + + + + + + ); + }) + )} + +
单据类型流程 / 任务名称业务摘要办理结果办理时间
+ {keyword ? '无匹配结果' : '暂无已办记录'} +
+ + {it.businessTable ? String(it.businessTable).slice(0, 8) : '已办'} + + + + {it.taskName || '(无标题)'} + + + {summarize(it)} + + {r.text} + + {it.endTime ? String(it.endTime).slice(0, 16) : '-'} +
+
+ )} + + {!loading && !unavailable && !error && filtered.length > PAGE_SIZE && ( + + )} +
+ ); +} + +// --------------------------------------------------------------------------- +// 待办中心(Tab 容器) +// --------------------------------------------------------------------------- +type TabKey = 'todo' | 'done'; + +export function TodoPage() { + const [tab, setTab] = useState('todo'); + + const tabStyle = (key: TabKey): React.CSSProperties => ({ + padding: '6px 18px', + cursor: 'pointer', + fontSize: 'var(--fs)', + fontWeight: tab === key ? 600 : 400, + color: tab === key ? 'var(--brand)' : 'var(--text-2)', + borderTop: 'none', + borderLeft: 'none', + borderRight: 'none', + borderBottom: tab === key ? '2px solid var(--brand)' : '2px solid transparent', + background: 'transparent', + fontFamily: 'inherit', + }); + + return ( +
+ {/* 页头 */} +
+

待办中心

+ +
+ + {/* Tab 切换 */} +
+ + +
+ + {/* Tab 内容 */} + {tab === 'todo' && } + {tab === 'done' && } +
+ ); +} diff --git a/src/pages/WorkbenchPage.tsx b/src/pages/WorkbenchPage.tsx new file mode 100644 index 0000000..f11d684 --- /dev/null +++ b/src/pages/WorkbenchPage.tsx @@ -0,0 +1,471 @@ +// WorkbenchPage — 工作台首页 /workbench +// 布局参考 screens-home.jsx Workbench;数据全部走真实 API,无假数据。 +// 降级说明: +// - urgentCount(加急待办数):等待后端 GET /api/todo 支持 urgent 字段或独立端点,目前隐藏 +// - KPI「流程实例数」「通知数」:等待 GET /api/stats 端点,目前隐藏,留扩展位 +// - 通知公告区:等待 GET /api/notice 端点,目前隐藏 +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { fetchTodo, type TodoItem } from '../api/todo'; +import { fetchMenu, collectLeaves, type MenuLeaf } from '../api/menu'; +import { loadRecentPages, type RecentPage } from '../utils/recentPages'; +import { Icon } from '../components/ui/Icon'; +import { getProfile } from '../auth/token'; + +// 快速功能网格中每项的图标映射(按菜单名关键词匹配) +const ICON_MAP: Array<[string, string]> = [ + ['合同', 'doc'], + ['付款', 'doc'], + ['采购', 'list'], + ['质量', 'check'], + ['安全', 'zap'], + ['劳务', 'team'], + ['设备', 'crane'], + ['考勤', 'cal'], + ['报表', 'chart'], + ['组织', 'org'], + ['流程', 'flow'], + ['通知', 'bell'], +]; + +function guessIcon(name: string): string { + for (const [kw, icon] of ICON_MAP) { + if (name.includes(kw)) return icon; + } + return 'list'; +} + +/** 时间问候语 */ +function greeting(): string { + const h = new Date().getHours(); + if (h < 6) return '夜深了'; + if (h < 12) return '早上好'; + if (h < 14) return '中午好'; + if (h < 18) return '下午好'; + return '晚上好'; +} + +// --------------------------------------------------------------------------- +// KPI 卡片 +// --------------------------------------------------------------------------- +interface KpiCardProps { + label: string; + value: number | string; + unit?: string; + /** 'norm' | 'warn' */ + tone?: 'norm' | 'warn'; + onClick?: () => void; +} + +function KpiCard({ label, value, unit, tone, onClick }: KpiCardProps) { + return ( +
+ {label} + + {value} + {unit ? ( + + {unit} + + ) : null} + +
+ ); +} + +// --------------------------------------------------------------------------- +// 快捷功能项 +// --------------------------------------------------------------------------- +interface QuickItem { + templateId: string; + name: string; + path: string; +} + +function QuickIcon({ item, onClick }: { item: QuickItem; onClick: () => void }) { + return ( +
((e.currentTarget as HTMLDivElement).style.background = 'var(--surface-2)')} + onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.background = '')} + title={item.path} + > + + + + + {item.name} + +
+ ); +} + +// --------------------------------------------------------------------------- +// 主组件 +// --------------------------------------------------------------------------- +export function WorkbenchPage() { + const navigate = useNavigate(); + const profile = getProfile(); + + // 待办快照(最近 5 条) + const [todoItems, setTodoItems] = useState([]); + const [todoUnavailable, setTodoUnavailable] = useState(false); + const [todoLoading, setTodoLoading] = useState(true); + + // 常用功能:优先用 localStorage 最近访问,回退到菜单叶子前 8 条 + const [quickItems, setQuickItems] = useState([]); + const [quickLoaded, setQuickLoaded] = useState(false); + + // 加载待办快照 + useEffect(() => { + let alive = true; + fetchTodo(0, 5) + .then((r) => { + if (!alive) return; + setTodoItems(r.items.slice(0, 5)); + setTodoUnavailable(r.unavailable); + }) + .catch(() => alive && setTodoUnavailable(true)) + .finally(() => alive && setTodoLoading(false)); + return () => { + alive = false; + }; + }, []); + + // 加载常用功能 + useEffect(() => { + // 先从 localStorage 读最近访问 + const recent: RecentPage[] = loadRecentPages(); + if (recent.length > 0) { + setQuickItems( + recent.slice(0, 8).map((r) => ({ + templateId: r.templateId, + name: r.name, + path: r.path, + })), + ); + setQuickLoaded(true); + return; + } + // 无最近访问时回退到菜单叶子 + fetchMenu() + .then((data) => { + const leaves: MenuLeaf[] = []; + for (const root of data.roots ?? []) { + leaves.push(...collectLeaves(root.children ?? [], [root.name])); + } + setQuickItems( + leaves.slice(0, 8).map((l) => ({ + templateId: l.templateId, + name: l.name, + path: l.path, + })), + ); + }) + .catch(() => { + // 菜单不可达时保持空态,显示引导文案 + }) + .finally(() => setQuickLoaded(true)); + }, []); + + const openPage = (templateId: string) => { + navigate(`/page/${templateId}`); + }; + + const openTodo = () => { + navigate('/todo'); + }; + + // 业务摘要简短文本 + const summarize = (item: TodoItem): string => { + const s = item.businessSummary; + if (s && typeof s === 'object') { + const vals = Object.values(s).filter((v) => v != null && v !== ''); + if (vals.length) return vals.slice(0, 2).map(String).join(' / '); + } + return item.businessKey ? `单号 ${item.businessKey}` : ''; + }; + + return ( +
+ {/* 问候语 */} +
+

+ {greeting()},{profile?.name ?? '同学'} +

+ {/* 加急待办数:等待 GET /api/todo 支持 urgent 字段,当前隐藏 */} + {!todoUnavailable && todoItems.length > 0 && ( + + 共有{' '} + {todoItems.length}{' '} + 条待处理事项(已显示最新 5 条) + + )} +
+ + {/* KPI 卡片行 */} +
+ 0 ? 'warn' : 'norm'} + onClick={openTodo} + /> + {/* 流程实例数:等待 GET /api/stats 端点,当前隐藏 */} + {/* 通知数:等待 GET /api/stats 端点,当前隐藏 */} +
+ + {/* 主内容区:待办快照 + 快捷功能 */} +
+ {/* 待办快照卡片 */} +
+ {/* 面板头 */} +
+

我的待办

+ +
+ + {/* 内容区 */} + {todoLoading && ( +
+ 加载中… +
+ )} + + {!todoLoading && todoUnavailable && ( +
+ 工作流引擎暂不可达(503 熔断),待办数据暂时无法显示 +
+ )} + + {!todoLoading && !todoUnavailable && todoItems.length === 0 && ( +
+ + 太棒了,暂无待办事项 +
+ )} + + {!todoLoading && !todoUnavailable && todoItems.length > 0 && ( +
+ {todoItems.map((item, idx) => { + // 跳转目标:优先 pageUrl 字段;其次按 businessTable 推算 + const pageUrl = item.pageUrl as string | undefined; + const jumpTo = () => { + if (pageUrl) { + navigate(pageUrl); + } else { + const tpl = item.businessTable + ? String(item.businessTable).toLowerCase() + : 'usergroup-manage'; + navigate(`/page/${tpl}`, { state: { businessKey: item.businessKey } }); + } + }; + + return ( +
+ ((e.currentTarget as HTMLDivElement).style.background = 'var(--brand-softer)') + } + onMouseLeave={(e) => + ((e.currentTarget as HTMLDivElement).style.background = '') + } + > + {/* 类型标签(businessTable 首字母大写) */} + + {item.businessTable + ? String(item.businessTable).slice(0, 6) + : '待办'} + + + {/* 标题 + 摘要 */} +
+
+ {item.taskName || '(无标题)'} +
+ {summarize(item) && ( +
+ {summarize(item)} +
+ )} +
+ + {/* 创建时间 */} + {item.createTime && ( + + {String(item.createTime).slice(5, 16)} + + )} + + +
+ ); + })} +
+ )} +
+ + {/* 右侧:常用功能 */} +
+
+

常用功能

+ 按访问记录自动更新 +
+ + {quickLoaded && quickItems.length === 0 && ( +
+ 暂无常用功能记录。 +
+ 从左侧菜单打开页面后,常用功能将自动出现在这里。 +
+ )} + + {quickItems.length > 0 && ( +
+ {quickItems.map((item) => ( + openPage(item.templateId)} /> + ))} +
+ )} +
+
+ + {/* 通知公告区:等待 GET /api/notice 端点,当前隐藏 */} +
+ ); +} diff --git a/src/shell/AppShell.tsx b/src/shell/AppShell.tsx index 7093292..ca20493 100644 --- a/src/shell/AppShell.tsx +++ b/src/shell/AppShell.tsx @@ -7,11 +7,12 @@ // 原因:keep-alive 需要将所有 Tab 内容同时挂载在 DOM 中,对 amis 渲染宿主 // 会产生大量隐藏实例,内存/副作用难以控制。当前阶段优先保证正确性, // keep-alive 作为后续优化项。 -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { Outlet, useLocation, useNavigate } from 'react-router-dom'; import { getProfile } from '../auth/token'; import { collectLeaves, fetchMenu } from '../api/menu'; import type { MenuLeaf } from '../api/menu'; +import { fetchTodo } from '../api/todo'; import { ToastHost } from '../components/ui/Toast'; import { Topbar } from './Topbar'; import { SideMenu } from './SideMenu'; @@ -22,8 +23,11 @@ import { SettingsDrawer, initTheme } from './SettingsDrawer'; const TABS_KEY = 'eip4-tabs'; const ACTIVE_KEY = 'eip4-active-tab'; -// 初始 Tab:「待办」作为保底 Tab,不可关闭 -const TODO_TAB: Tab = { key: '/todo', title: '待办' }; +// 待办 badge 轮询间隔(毫秒),每 60 秒刷新一次 +const TODO_POLL_INTERVAL = 60_000; + +// 初始 Tab:「工作台」作为保底 Tab,不可关闭 +const TODO_TAB: Tab = { key: '/workbench', title: '工作台' }; function loadTabs(): Tab[] { try { @@ -60,6 +64,9 @@ export function AppShell() { const [collapsed, setCollapsed] = useState(false); const [showSettings, setShowSettings] = useState(false); const [leaves, setLeaves] = useState([]); + // 顶栏铃铛真实待办数(F1-3:接真实 API) + const [todoBadge, setTodoBadge] = useState(undefined); + const pollTimer = useRef | null>(null); const profile = getProfile(); @@ -105,6 +112,30 @@ export function AppShell() { }); }, []); + // 顶栏铃铛:每 TODO_POLL_INTERVAL 轮询一次待办数(503 时 badge 清零不报错) + useEffect(() => { + const loadBadge = () => { + fetchTodo(0, 1) + .then((r) => { + if (r.unavailable) { + setTodoBadge(undefined); + return; + } + // 当前 API 无 totalCount,用 items 数量作近似(maxResults=1 不准确) + // 实际拉取少量条目仅做"有无"判断;完整 count 等待后端 GET /api/todo/count 端点 + fetchTodo(0, 200).then((full) => { + if (!full.unavailable) setTodoBadge(full.items.length || undefined); + }).catch(() => setTodoBadge(undefined)); + }) + .catch(() => setTodoBadge(undefined)); + }; + loadBadge(); + pollTimer.current = setInterval(loadBadge, TODO_POLL_INTERVAL); + return () => { + if (pollTimer.current) clearInterval(pollTimer.current); + }; + }, []); + // 打开/激活一个 Tab const openTab = useCallback( (key: string, title: string) => { @@ -125,6 +156,10 @@ export function AppShell() { openTab('/todo', '待办'); return; } + if (templateId === '__workbench__') { + openTab('/workbench', '工作台'); + return; + } openTab(`/page/${templateId}`, templateId); }, [openTab], @@ -174,6 +209,7 @@ export function AppShell() { handleActive('/todo')} onOpenTemplate={handleSearchOpen} onOpenSettings={() => setShowSettings(true)} diff --git a/src/utils/recentPages.test.ts b/src/utils/recentPages.test.ts new file mode 100644 index 0000000..06d184a --- /dev/null +++ b/src/utils/recentPages.test.ts @@ -0,0 +1,52 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { clearRecentPages, loadRecentPages, recordRecentPage } from './recentPages'; + +// jsdom 已提供 localStorage 实现,测试前清空 +beforeEach(() => { + clearRecentPages(); +}); + +describe('recordRecentPage', () => { + it('首次写入后可读取', () => { + recordRecentPage({ templateId: 'tpl-1', name: '付款申请', path: '合同管理 / 付款申请' }); + const list = loadRecentPages(); + expect(list).toHaveLength(1); + expect(list[0].templateId).toBe('tpl-1'); + expect(list[0].name).toBe('付款申请'); + }); + + it('重复访问同一页面提升到最前,不重复', () => { + recordRecentPage({ templateId: 'tpl-1', name: '付款申请', path: 'A' }); + recordRecentPage({ templateId: 'tpl-2', name: '质量整改', path: 'B' }); + recordRecentPage({ templateId: 'tpl-1', name: '付款申请', path: 'A' }); + const list = loadRecentPages(); + expect(list).toHaveLength(2); + expect(list[0].templateId).toBe('tpl-1'); // 最新访问排第一 + expect(list[1].templateId).toBe('tpl-2'); + }); + + it('超过 MAX_RECENT(8) 时截断最旧记录', () => { + for (let i = 1; i <= 10; i++) { + recordRecentPage({ templateId: `tpl-${i}`, name: `页面${i}`, path: `路径${i}` }); + } + const list = loadRecentPages(); + expect(list).toHaveLength(8); + // 最新访问的是 tpl-10,应在最前 + expect(list[0].templateId).toBe('tpl-10'); + // 最早的 tpl-1、tpl-2 应被淘汰 + expect(list.find((p) => p.templateId === 'tpl-1')).toBeUndefined(); + expect(list.find((p) => p.templateId === 'tpl-2')).toBeUndefined(); + }); + + it('clearRecentPages 后列表为空', () => { + recordRecentPage({ templateId: 'tpl-1', name: '付款申请', path: 'A' }); + clearRecentPages(); + expect(loadRecentPages()).toHaveLength(0); + }); +}); + +describe('loadRecentPages', () => { + it('localStorage 为空时返回空数组', () => { + expect(loadRecentPages()).toEqual([]); + }); +}); diff --git a/src/utils/recentPages.ts b/src/utils/recentPages.ts new file mode 100644 index 0000000..e1c253a --- /dev/null +++ b/src/utils/recentPages.ts @@ -0,0 +1,48 @@ +// 常用/最近访问功能工具 —— 基于 localStorage +// 记录用户最近打开的菜单叶子(templateId),用于工作台「常用功能」快捷入口。 +// 最多保留 MAX_RECENT 条,按最近访问顺序排列(最新在前)。 + +const STORAGE_KEY = 'eip4-recent-pages'; +const MAX_RECENT = 8; + +export interface RecentPage { + templateId: string; + name: string; + /** 面包屑路径,如 "合同管理 / 付款申请" */ + path: string; + /** 最近访问时间戳 */ + ts: number; +} + +/** 读取最近访问列表 */ +export function loadRecentPages(): RecentPage[] { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return []; + const parsed = JSON.parse(raw) as RecentPage[]; + if (!Array.isArray(parsed)) return []; + return parsed; + } catch { + return []; + } +} + +/** 记录一次访问(已存在则提升到最前,超出 MAX_RECENT 截断) */ +export function recordRecentPage(page: Omit): void { + const list = loadRecentPages().filter((p) => p.templateId !== page.templateId); + const next: RecentPage[] = [{ ...page, ts: Date.now() }, ...list].slice(0, MAX_RECENT); + try { + localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } catch { + // localStorage 不可用时静默忽略 + } +} + +/** 清空记录(测试/重置用) */ +export function clearRecentPages(): void { + try { + localStorage.removeItem(STORAGE_KEY); + } catch { + // 忽略 + } +}