F1-3: 工作台首页与待办中心成品化

- 新增 WorkbenchPage (/workbench):KPI 卡片(待办数接真实 API)、待办快照(最近 5 条)、常用功能(localStorage 最近访问优先,回退菜单叶子)
- 升级 TodoPage:待办/已办 Tab、关键字本地筛选、pageUrl 优先跳转、Pagination 组件复用
- 新增 api/done.ts:GET /api/done 已办接口,与待办接口同样的 503 降级逻辑
- 新增 utils/recentPages.ts:localStorage 常用功能工具,MAX_RECENT=8 LRU
- 新增 utils/recentPages.test.ts:5 个单测覆盖写入/提升/截断/清空逻辑
- AppShell:顶栏铃铛接真实待办数(60s 轮询);默认 Tab 改为工作台
- App.tsx:新增 /workbench 路由,根路径重定向目标改为 /workbench

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 20:13:53 +08:00
parent 0e5d42debc
commit effc21d929
7 changed files with 1067 additions and 107 deletions

View File

@@ -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() {
</RequireAuth>
}
>
{/* 工作台首页(F1-3)*/}
<Route path="/workbench" element={<WorkbenchPage />} />
<Route path="/todo" element={<TodoPage />} />
<Route path="/page/:templateId" element={<PageRenderPage />} />
{/* 根路径默认跳待办 */}
<Route index element={<Navigate to="/todo" replace />} />
{/* 根路径默认跳工作台 */}
<Route index element={<Navigate to="/workbench" replace />} />
</Route>
{/* 兜底 */}

44
src/api/done.ts Normal file
View File

@@ -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<string, unknown>;
/** 办理结果: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<DoneResult> {
try {
const { data } = await http.get<DoneItem[] | { items: DoneItem[] }>('/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;
}
}

View File

@@ -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<TodoItem[]>([]);
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 (
<div style={{ padding: 24 }}>
<h2 style={{ marginTop: 0, color: '#1f2d3d' }}>我的待办</h2>
{loading && <div style={{ color: '#888' }}>加载中…</div>}
{!loading && unavailable && (
<div
data-testid="todo-degraded"
style={{
padding: 16,
background: '#fff7e6',
border: '1px solid #ffd591',
borderRadius: 6,
color: '#ad6800',
}}
>
⚠ 工作流引擎暂不可达(网关 503 熔断降级):{message || '请稍后重试'}
<div style={{ fontSize: 12, marginTop: 6, color: '#b08600' }}>
单体侧待办聚合依赖 flowable-service;引擎宕机时本页降级,不影响其他页面。
</div>
</div>
)}
{!loading && error && <div style={{ color: '#d9534f' }}>请求失败:{error}</div>}
{!loading && !unavailable && !error && items.length === 0 && (
<div style={{ color: '#888' }}>暂无待办。</div>
)}
{!loading && items.length > 0 && (
<table style={{ width: '100%', borderCollapse: 'collapse', background: '#fff' }}>
<thead>
<tr style={{ background: '#fafafa', textAlign: 'left' }}>
<th style={thStyle}>任务名</th>
<th style={thStyle}>业务摘要</th>
<th style={thStyle}>业务表</th>
<th style={thStyle}>操作</th>
</tr>
</thead>
<tbody>
{items.map((it, idx) => (
<tr key={it.taskId || idx} style={{ borderTop: '1px solid #f0f0f0' }}>
<td style={tdStyle}>{it.taskName || '-'}</td>
<td style={tdStyle}>{summarize(it)}</td>
<td style={tdStyle}>{it.businessTable || <span style={{ color: '#bbb' }}>(无映射)</span>}</td>
<td style={tdStyle}>
<button onClick={() => openBusiness(it)} style={linkBtnStyle}>
打开
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
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<TodoItem[]>([]);
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* 筛选栏 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
<label style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-2)' }}>关键字</label>
<input
className="input"
style={{ width: 220 }}
placeholder="流程名称 / 单据类型 / 单号"
value={keyword}
onChange={(e) => { setKeyword(e.target.value); setPage(1); }}
/>
{keyword && (
<button className="btn btn-sm" onClick={() => { setKeyword(''); setPage(1); }}>
重置
</button>
)}
<span className="muted" style={{ fontSize: 'var(--fs-sm)', marginLeft: 'auto' }}>
共 {filtered.length} 条
</span>
</div>
{/* 降级提示 */}
{!loading && unavailable && (
<div
data-testid="todo-degraded"
style={{
padding: 12,
background: 'var(--warn-soft)',
border: '1px solid var(--warn)',
borderRadius: 'var(--radius)',
color: 'var(--warn)',
fontSize: 'var(--fs-sm)',
}}
>
⚠ 工作流引擎暂不可达(503 熔断降级):{unavailMsg || '请稍后重试'}
</div>
)}
{loading && <div style={{ color: 'var(--text-3)' }}>加载中…</div>}
{!loading && error && <div style={{ color: 'var(--err)' }}>请求失败:{error}</div>}
{/* 表格 */}
{!loading && !unavailable && !error && (
<div className="tbl-wrap">
<table className="tbl">
<thead>
<tr>
<th style={{ width: 100 }}>单据类型</th>
<th>流程 / 任务名称</th>
<th style={{ width: 200 }}>业务摘要</th>
<th style={{ width: 110 }}>到达时间</th>
<th style={{ width: 80 }}>操作</th>
</tr>
</thead>
<tbody>
{pageItems.length === 0 ? (
<tr>
<td colSpan={5} style={{ textAlign: 'center', color: 'var(--text-3)', padding: 32 }}>
{keyword ? '无匹配结果' : '暂无待办'}
</td>
</tr>
) : (
pageItems.map((it, idx) => (
<tr
key={it.taskId ?? idx}
style={{ cursor: 'pointer' }}
onClick={() => openBusiness(it)}
>
<td>
<span className="tag tag-info">
{it.businessTable ? String(it.businessTable).slice(0, 8) : '待办'}
</span>
</td>
<td style={{ maxWidth: 300 }}>
<span
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'block',
}}
>
{it.taskName || '(无标题)'}
</span>
</td>
<td
style={{
color: 'var(--text-2)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
maxWidth: 200,
}}
>
{summarize(it)}
</td>
<td className="muted">
{it.createTime ? String(it.createTime).slice(0, 16) : '-'}
</td>
<td>
<button
className="btn btn-text"
onClick={(e) => { e.stopPropagation(); openBusiness(it); }}
>
办理
</button>
</td>
</tr>
))
)}
</tbody>
</table>
</div>
)}
{!loading && !unavailable && !error && filtered.length > PAGE_SIZE && (
<Pagination total={filtered.length} page={safePage} pageSize={PAGE_SIZE} onPage={setPage} />
)}
</div>
);
}
// ---------------------------------------------------------------------------
// 已办列表
// ---------------------------------------------------------------------------
/** 办理结果枚举映射 */
function resultLabel(result?: string): { text: string; cls: string } {
if (!result) return { text: '-', cls: 'tag-gray' };
const map: Record<string, { text: string; cls: string }> = {
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<DoneItem[]>([]);
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* 筛选栏 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<label style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-2)' }}>关键字</label>
<input
className="input"
style={{ width: 220 }}
placeholder="流程名称 / 单据类型 / 单号"
value={keyword}
onChange={(e) => { setKeyword(e.target.value); setPage(1); }}
/>
{keyword && (
<button className="btn btn-sm" onClick={() => { setKeyword(''); setPage(1); }}>
重置
</button>
)}
<span className="muted" style={{ fontSize: 'var(--fs-sm)', marginLeft: 'auto' }}>
共 {filtered.length} 条
</span>
</div>
{!loading && unavailable && (
<div
style={{
padding: 12,
background: 'var(--warn-soft)',
border: '1px solid var(--warn)',
borderRadius: 'var(--radius)',
color: 'var(--warn)',
fontSize: 'var(--fs-sm)',
}}
>
⚠ 已办数据暂时不可用:{unavailMsg || '请稍后重试'}
</div>
)}
{loading && <div style={{ color: 'var(--text-3)' }}>加载中…</div>}
{!loading && error && <div style={{ color: 'var(--err)' }}>请求失败:{error}</div>}
{!loading && !unavailable && !error && (
<div className="tbl-wrap">
<table className="tbl">
<thead>
<tr>
<th style={{ width: 100 }}>单据类型</th>
<th>流程 / 任务名称</th>
<th style={{ width: 200 }}>业务摘要</th>
<th style={{ width: 90 }}>办理结果</th>
<th style={{ width: 130 }}>办理时间</th>
</tr>
</thead>
<tbody>
{pageItems.length === 0 ? (
<tr>
<td colSpan={5} style={{ textAlign: 'center', color: 'var(--text-3)', padding: 32 }}>
{keyword ? '无匹配结果' : '暂无已办记录'}
</td>
</tr>
) : (
pageItems.map((it, idx) => {
const r = resultLabel(it.result);
return (
<tr key={it.taskId ?? idx}>
<td>
<span className="tag tag-gray">
{it.businessTable ? String(it.businessTable).slice(0, 8) : '已办'}
</span>
</td>
<td style={{ maxWidth: 300 }}>
<span
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'block',
}}
>
{it.taskName || '(无标题)'}
</span>
</td>
<td className="muted" style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 200 }}>
{summarize(it)}
</td>
<td>
<span className={`tag ${r.cls}`}>{r.text}</span>
</td>
<td className="muted">
{it.endTime ? String(it.endTime).slice(0, 16) : '-'}
</td>
</tr>
);
})
)}
</tbody>
</table>
</div>
)}
{!loading && !unavailable && !error && filtered.length > PAGE_SIZE && (
<Pagination total={filtered.length} page={safePage} pageSize={PAGE_SIZE} onPage={setPage} />
)}
</div>
);
}
// ---------------------------------------------------------------------------
// 待办中心(Tab 容器)
// ---------------------------------------------------------------------------
type TabKey = 'todo' | 'done';
export function TodoPage() {
const [tab, setTab] = useState<TabKey>('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 (
<div style={{ padding: 'var(--pad-lg)', display: 'flex', flexDirection: 'column', gap: 'var(--pad)' }}>
{/* 页头 */}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<h2 style={{ margin: 0, fontSize: 18, fontWeight: 700 }}>待办中心</h2>
<Icon name="todo" size={18} style={{ color: 'var(--text-3)' }} />
</div>
{/* Tab 切换 */}
<div
style={{
display: 'flex',
gap: 0,
borderBottom: '1px solid var(--line)',
marginBottom: 4,
}}
>
<button style={tabStyle('todo')} onClick={() => setTab('todo')}>
待办
</button>
<button style={tabStyle('done')} onClick={() => setTab('done')}>
已办
</button>
</div>
{/* Tab 内容 */}
{tab === 'todo' && <TodoList />}
{tab === 'done' && <DoneList />}
</div>
);
}

471
src/pages/WorkbenchPage.tsx Normal file
View File

@@ -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 (
<div
className="card"
onClick={onClick}
style={{
padding: '18px 20px 16px',
cursor: onClick ? 'pointer' : 'default',
display: 'flex',
flexDirection: 'column',
gap: 6,
}}
>
<span style={{ fontSize: 'var(--fs-sm)', color: 'var(--text-2)' }}>{label}</span>
<span
style={{
fontSize: 28,
fontWeight: 700,
lineHeight: 1.15,
color: tone === 'warn' ? 'var(--err)' : 'var(--text)',
fontFamily: 'var(--font-num)',
}}
>
{value}
{unit ? (
<small style={{ fontSize: 14, fontWeight: 400, color: 'var(--text-3)', marginLeft: 3 }}>
{unit}
</small>
) : null}
</span>
</div>
);
}
// ---------------------------------------------------------------------------
// 快捷功能项
// ---------------------------------------------------------------------------
interface QuickItem {
templateId: string;
name: string;
path: string;
}
function QuickIcon({ item, onClick }: { item: QuickItem; onClick: () => void }) {
return (
<div
onClick={onClick}
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: 6,
padding: '10px 4px',
borderRadius: 'var(--radius)',
cursor: 'pointer',
fontSize: 'var(--fs-sm)',
color: 'var(--text-2)',
transition: 'background .12s',
}}
onMouseEnter={(e) => ((e.currentTarget as HTMLDivElement).style.background = 'var(--surface-2)')}
onMouseLeave={(e) => ((e.currentTarget as HTMLDivElement).style.background = '')}
title={item.path}
>
<span
style={{
width: 36,
height: 36,
borderRadius: 10,
background: 'var(--brand-soft)',
color: 'var(--brand)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Icon name={guessIcon(item.name)} size={17} />
</span>
<span
style={{
maxWidth: 56,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
textAlign: 'center',
}}
>
{item.name}
</span>
</div>
);
}
// ---------------------------------------------------------------------------
// 主组件
// ---------------------------------------------------------------------------
export function WorkbenchPage() {
const navigate = useNavigate();
const profile = getProfile();
// 待办快照(最近 5 条)
const [todoItems, setTodoItems] = useState<TodoItem[]>([]);
const [todoUnavailable, setTodoUnavailable] = useState(false);
const [todoLoading, setTodoLoading] = useState(true);
// 常用功能:优先用 localStorage 最近访问,回退到菜单叶子前 8 条
const [quickItems, setQuickItems] = useState<QuickItem[]>([]);
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 (
<div style={{ padding: 'var(--pad-lg)', display: 'flex', flexDirection: 'column', gap: 'var(--pad)' }}>
{/* 问候语 */}
<div style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
<h2 style={{ fontSize: 20, fontWeight: 700, margin: 0 }}>
{greeting()},{profile?.name ?? '同学'}
</h2>
{/* 加急待办数:等待 GET /api/todo 支持 urgent 字段,当前隐藏 */}
{!todoUnavailable && todoItems.length > 0 && (
<span className="sub-text">
共有{' '}
<b style={{ color: 'var(--brand)' }}>{todoItems.length}</b>{' '}
条待处理事项(已显示最新 5 条)
</span>
)}
</div>
{/* KPI 卡片行 */}
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(160px, 1fr))',
gap: 'var(--pad)',
}}
>
<KpiCard
label="我的待办"
value={todoLoading ? '…' : todoUnavailable ? '-' : todoItems.length}
unit={todoLoading || todoUnavailable ? undefined : '条'}
tone={!todoLoading && !todoUnavailable && todoItems.length > 0 ? 'warn' : 'norm'}
onClick={openTodo}
/>
{/* 流程实例数:等待 GET /api/stats 端点,当前隐藏 */}
{/* 通知数:等待 GET /api/stats 端点,当前隐藏 */}
</div>
{/* 主内容区:待办快照 + 快捷功能 */}
<div
style={{
display: 'grid',
gridTemplateColumns: '1fr 320px',
gap: 'var(--pad)',
alignItems: 'start',
}}
>
{/* 待办快照卡片 */}
<div className="card" style={{ overflow: 'hidden' }}>
{/* 面板头 */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '12px var(--pad)',
borderBottom: '1px solid var(--line)',
}}
>
<h3 style={{ margin: 0, fontSize: 'var(--fs)', fontWeight: 600 }}>我的待办</h3>
<button className="btn btn-text btn" onClick={openTodo}>
进入待办中心 ›
</button>
</div>
{/* 内容区 */}
{todoLoading && (
<div style={{ padding: '24px var(--pad)', color: 'var(--text-3)', fontSize: 'var(--fs-sm)' }}>
加载中…
</div>
)}
{!todoLoading && todoUnavailable && (
<div
style={{
margin: 'var(--pad)',
padding: 12,
background: 'var(--warn-soft)',
border: '1px solid var(--warn)',
borderRadius: 'var(--radius)',
color: 'var(--warn)',
fontSize: 'var(--fs-sm)',
}}
>
工作流引擎暂不可达(503 熔断),待办数据暂时无法显示
</div>
)}
{!todoLoading && !todoUnavailable && todoItems.length === 0 && (
<div className="empty">
<Icon name="check" size={28} style={{ color: 'var(--ok)' }} />
太棒了,暂无待办事项
</div>
)}
{!todoLoading && !todoUnavailable && todoItems.length > 0 && (
<div>
{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 (
<div
key={item.taskId ?? idx}
onClick={jumpTo}
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '10px var(--pad)',
borderBottom: '1px solid var(--line)',
cursor: 'pointer',
}}
onMouseEnter={(e) =>
((e.currentTarget as HTMLDivElement).style.background = 'var(--brand-softer)')
}
onMouseLeave={(e) =>
((e.currentTarget as HTMLDivElement).style.background = '')
}
>
{/* 类型标签(businessTable 首字母大写) */}
<span
className="tag tag-info"
style={{ flex: '0 0 auto', maxWidth: 80, overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{item.businessTable
? String(item.businessTable).slice(0, 6)
: '待办'}
</span>
{/* 标题 + 摘要 */}
<div style={{ flex: 1, minWidth: 0 }}>
<div
style={{
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontSize: 'var(--fs)',
}}
>
{item.taskName || '(无标题)'}
</div>
{summarize(item) && (
<div
className="muted"
style={{ fontSize: 'var(--fs-sm)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}
>
{summarize(item)}
</div>
)}
</div>
{/* 创建时间 */}
{item.createTime && (
<span className="muted" style={{ fontSize: 'var(--fs-sm)', flex: '0 0 auto' }}>
{String(item.createTime).slice(5, 16)}
</span>
)}
<button
className="btn btn-sm btn-pri"
onClick={(e) => {
e.stopPropagation();
jumpTo();
}}
>
办理
</button>
</div>
);
})}
</div>
)}
</div>
{/* 右侧:常用功能 */}
<div className="card" style={{ overflow: 'hidden' }}>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '12px var(--pad)',
borderBottom: '1px solid var(--line)',
}}
>
<h3 style={{ margin: 0, fontSize: 'var(--fs)', fontWeight: 600 }}>常用功能</h3>
<span className="muted" style={{ fontSize: 11 }}>按访问记录自动更新</span>
</div>
{quickLoaded && quickItems.length === 0 && (
<div
style={{
padding: 'var(--pad)',
color: 'var(--text-3)',
fontSize: 'var(--fs-sm)',
lineHeight: 1.8,
}}
>
暂无常用功能记录。
<br />
从左侧菜单打开页面后,常用功能将自动出现在这里。
</div>
)}
{quickItems.length > 0 && (
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(4, 1fr)',
gap: 4,
padding: '8px var(--pad) var(--pad)',
}}
>
{quickItems.map((item) => (
<QuickIcon key={item.templateId} item={item} onClick={() => openPage(item.templateId)} />
))}
</div>
)}
</div>
</div>
{/* 通知公告区:等待 GET /api/notice 端点,当前隐藏 */}
</div>
);
}

View File

@@ -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<MenuLeaf[]>([]);
// 顶栏铃铛真实待办数(F1-3:接真实 API)
const [todoBadge, setTodoBadge] = useState<number | undefined>(undefined);
const pollTimer = useRef<ReturnType<typeof setInterval> | 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() {
<Topbar
leaves={leaves}
profile={profile}
todoBadge={todoBadge}
onOpenTodo={() => handleActive('/todo')}
onOpenTemplate={handleSearchOpen}
onOpenSettings={() => setShowSettings(true)}

View File

@@ -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([]);
});
});

48
src/utils/recentPages.ts Normal file
View File

@@ -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<RecentPage, 'ts'>): 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 {
// 忽略
}
}