初始化:质量数据分析平台源码
This commit is contained in:
@@ -0,0 +1,382 @@
|
||||
import { lazy, Suspense, useCallback, useEffect, useState, type ReactNode } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
Button,
|
||||
Dropdown,
|
||||
Form,
|
||||
Input,
|
||||
Modal,
|
||||
Select,
|
||||
Spin,
|
||||
Tooltip,
|
||||
} from 'antd';
|
||||
import {
|
||||
AppstoreOutlined,
|
||||
ApartmentOutlined,
|
||||
BgColorsOutlined,
|
||||
CheckSquareOutlined,
|
||||
CheckOutlined,
|
||||
DatabaseOutlined,
|
||||
DownOutlined,
|
||||
DeploymentUnitOutlined,
|
||||
FileSearchOutlined,
|
||||
KeyOutlined,
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
LogoutOutlined,
|
||||
RobotOutlined,
|
||||
SearchOutlined,
|
||||
QuestionCircleOutlined,
|
||||
SettingOutlined,
|
||||
TeamOutlined,
|
||||
ToolOutlined,
|
||||
} from '@ant-design/icons';
|
||||
import { ApiError, api } from './api';
|
||||
import type { AuthUser, QueryParams } from './types';
|
||||
import { workspaceThemes, type WorkspaceThemeId } from './ui-themes';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
|
||||
export type PageKey = 'overall' | 'department' | 'group' | 'product' | 'basis' | 'analysis' | 'sources' | 'imports' | 'rules' | 'mappings' | 'masterData' | 'tasks' | 'access';
|
||||
|
||||
const pageNames: Record<PageKey, string> = {
|
||||
overall: '总体汇总', department: '产业部汇总', group: '产业部-业务分组', product: '产品汇总',
|
||||
basis: '数据与计算依据', analysis: '智能分析', sources: '数据接入', imports: '导入与校验',
|
||||
rules: '计算规则', mappings: '对应关系', masterData: '基础数据', tasks: '任务与监控', access: '权限与审计',
|
||||
};
|
||||
|
||||
const pageFromLocation = (): PageKey => {
|
||||
const key = new URLSearchParams(window.location.search).get('page');
|
||||
if (key === 'headers' || key === 'releases') return 'sources';
|
||||
if (key === 'scrap') return 'product';
|
||||
return key && key in pageNames ? key as PageKey : 'overall';
|
||||
};
|
||||
|
||||
type TopResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
function encodeContext(value: { query: QueryParams; resultRef?: TopResultRef }): string {
|
||||
const bytes = new TextEncoder().encode(JSON.stringify(value));
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
}
|
||||
|
||||
const navGroups = [
|
||||
{
|
||||
label: '质量查询',
|
||||
items: [
|
||||
['overall', '总体汇总', AppstoreOutlined],
|
||||
['department', '产业部汇总', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '分析工作台',
|
||||
items: [
|
||||
['analysis', '智能分析', RobotOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '数据中心',
|
||||
items: [
|
||||
['sources', '数据接入', DatabaseOutlined],
|
||||
['imports', '导入与校验', CheckSquareOutlined],
|
||||
] as const,
|
||||
},
|
||||
{
|
||||
label: '规则与管理',
|
||||
items: [
|
||||
['rules', '计算规则', SettingOutlined],
|
||||
['mappings', '对应关系', ToolOutlined],
|
||||
['masterData', '基础数据', DatabaseOutlined],
|
||||
['tasks', '任务与监控', LineChartOutlined],
|
||||
['access', '权限与审计', KeyOutlined],
|
||||
] as const,
|
||||
},
|
||||
];
|
||||
|
||||
const searchablePages: { key: PageKey; label: string }[] = [
|
||||
...navGroups.flatMap(group => group.items.map(([key, label]) => ({ key, label }))),
|
||||
{ key: 'basis', label: pageNames.basis },
|
||||
];
|
||||
|
||||
function shownDepartment(value: string): string {
|
||||
return value === '质量管理部' ? '质量中心' : value;
|
||||
}
|
||||
|
||||
function PageReveal({ page, children }: { page: PageKey; children: ReactNode }) {
|
||||
return <div className="page-view" data-page={page}>{children}</div>;
|
||||
}
|
||||
|
||||
type QualityWorkspaceProps = {
|
||||
appearance: (typeof workspaceThemes)[number];
|
||||
onAppearanceChange: (themeId: WorkspaceThemeId) => void;
|
||||
};
|
||||
|
||||
export default function QualityWorkspace({ appearance, onAppearanceChange }: QualityWorkspaceProps) {
|
||||
const { message } = App.useApp();
|
||||
const [page, setPage] = useState<PageKey>(pageFromLocation);
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const [sessionLoading, setSessionLoading] = useState(true);
|
||||
const [sessionError, setSessionError] = useState('');
|
||||
const [searchOpen, setSearchOpen] = useState(false);
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const onShortcut = (event: KeyboardEvent) => {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
|
||||
event.preventDefault();
|
||||
setSearchTerm('');
|
||||
setSearchOpen(true);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onShortcut);
|
||||
return () => window.removeEventListener('keydown', onShortcut);
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
const syncFromLocation = () => {
|
||||
const url = new URL(window.location.href);
|
||||
const currentPage = url.searchParams.get('page') || '';
|
||||
if (['headers', 'releases', 'scrap'].includes(currentPage)) {
|
||||
url.searchParams.set('page', currentPage === 'scrap' ? 'product' : 'sources');
|
||||
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
}
|
||||
setPage(pageFromLocation());
|
||||
};
|
||||
syncFromLocation();
|
||||
window.addEventListener('popstate', syncFromLocation);
|
||||
return () => window.removeEventListener('popstate', syncFromLocation);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
(async () => {
|
||||
try {
|
||||
await api.refreshCsrf();
|
||||
const current = await api.me();
|
||||
if (alive) setUser(current);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
if (alive) setUser(null);
|
||||
} else if (alive) {
|
||||
setSessionError(error instanceof Error ? error.message : '无法连接服务');
|
||||
}
|
||||
} finally {
|
||||
if (alive) setSessionLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: TopResultRef) => {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('page', next);
|
||||
if (next !== 'analysis' || query || resultRef) {
|
||||
url.searchParams.delete('sessionId');
|
||||
url.searchParams.delete('turnId');
|
||||
}
|
||||
if (query) url.searchParams.set('context', encodeContext({ query, ...(resultRef ? { resultRef } : {}) }));
|
||||
else url.searchParams.delete('context');
|
||||
window.history.pushState({}, '', `${url.pathname}${url.search}${url.hash}`);
|
||||
setPage(next);
|
||||
setSearchOpen(false);
|
||||
};
|
||||
|
||||
const matchingPages = searchablePages.filter(({ key, label }) => {
|
||||
const normalized = searchTerm.trim().toLocaleLowerCase();
|
||||
return !normalized || `${label} ${key}`.toLocaleLowerCase().includes(normalized);
|
||||
});
|
||||
|
||||
const handleUnauthorized = useCallback((error: unknown) => {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
setUser(null);
|
||||
void api.refreshCsrf().catch(() => undefined);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}, []);
|
||||
|
||||
if (sessionLoading) return <div className="screen-state"><Spin indicator={<LoadingOutlined spin />} /> <span>正在连接质量中心…</span></div>;
|
||||
if (sessionError) return <div className="screen-state"><div className="state-card"><strong>服务暂不可用</strong><p>{sessionError}</p><Button onClick={() => window.location.reload()}>重新连接</Button></div></div>;
|
||||
if (!user) return <LoginPage onSuccess={setUser} />;
|
||||
|
||||
return (
|
||||
<div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<button className="brand" onClick={() => navigate('overall')} aria-label="回到总体汇总">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span>
|
||||
<span>质量中心</span>
|
||||
</button>
|
||||
<div className="workspace-caption">质量中心 · 分析工作台</div>
|
||||
<nav className="side-navigation" aria-label="主导航">
|
||||
{navGroups.map(group => (
|
||||
<div className="nav-group" key={group.label}>
|
||||
<div className="nav-group-label">{group.label}</div>
|
||||
{group.items.map(([key, label, Icon]) => (
|
||||
<button
|
||||
key={key}
|
||||
className={`nav-item ${page === key ? 'active' : ''}`}
|
||||
aria-current={page === key ? 'page' : undefined}
|
||||
onClick={() => navigate(key)}
|
||||
>
|
||||
<Icon aria-hidden="true" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
<div className="nav-group nav-group-tail">
|
||||
<div className="nav-group-label">数据口径</div>
|
||||
<button className={`nav-item ${page === 'basis' ? 'active' : ''}`} aria-current={page === 'basis' ? 'page' : undefined} onClick={() => navigate('basis')}>
|
||||
<FileSearchOutlined aria-hidden="true" /><span>数据与计算依据</span>
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
<div className="user-block">
|
||||
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
|
||||
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.length ? user.departments.map(shownDepartment).join('、') : '质量中心'}</small></span>
|
||||
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
|
||||
try { await api.logout(); setUser(null); }
|
||||
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
|
||||
}} /></Tooltip>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<main className="main-column">
|
||||
<header className="topbar">
|
||||
<div className="breadcrumb"><span>质量分析</span><span className="breadcrumb-slash">/</span><strong>{pageNames[page]}</strong></div>
|
||||
<div className="topbar-actions">
|
||||
<Button className="topbar-search" type="text" aria-label="搜索功能页面" onClick={() => { setSearchTerm(''); setSearchOpen(true); }}>
|
||||
<SearchOutlined /><span>搜索功能页面…</span><kbd>⌘ K</kbd>
|
||||
</Button>
|
||||
<Dropdown
|
||||
trigger={['click']}
|
||||
classNames={{ root: 'workspace-theme-dropdown' }}
|
||||
menu={{
|
||||
selectedKeys: [appearance.id],
|
||||
items: workspaceThemes.map(theme => ({
|
||||
key: theme.id,
|
||||
label: <span className="theme-choice"><i style={{ backgroundColor: theme.primary }} /><span>{theme.name}</span>{theme.id === appearance.id && <CheckOutlined />}</span>,
|
||||
})),
|
||||
onClick: ({ key }) => onAppearanceChange(key as WorkspaceThemeId),
|
||||
}}
|
||||
>
|
||||
<Button className="topbar-theme" type="text" aria-label={`切换主题,当前${appearance.name}`}>
|
||||
<BgColorsOutlined /><span>{appearance.name}</span><DownOutlined />
|
||||
</Button>
|
||||
</Dropdown>
|
||||
<Tooltip title="查看数据与计算依据">
|
||||
<Button className="topbar-help" type="text" icon={<QuestionCircleOutlined />} aria-label="查看数据与计算依据" onClick={() => navigate('basis')} />
|
||||
</Tooltip>
|
||||
<span className="top-organization"><TeamOutlined />质量中心</span>
|
||||
</div>
|
||||
</header>
|
||||
<div className="mobile-brand">
|
||||
<span className="brand-mark" aria-hidden="true"><i /><i /><i /></span><strong>质量中心</strong>
|
||||
<Select<PageKey> {...readableSelectPopup} aria-label="页面导航" value={page} onChange={value => navigate(value)} options={[
|
||||
...navGroups.map(group => ({ label: group.label, options: group.items.map(([value, label]) => ({ value, label })) })),
|
||||
{ label: '数据口径', options: [{ value: 'basis' as PageKey, label: '数据与计算依据' }] },
|
||||
]} />
|
||||
<Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={async () => {
|
||||
try { await api.logout(); setUser(null); }
|
||||
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
|
||||
}} />
|
||||
</div>
|
||||
<div className="page-content">
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
<PageReveal page={page}>
|
||||
{['overall', 'department', 'group', 'product'].includes(page)
|
||||
? <QueryPage page={page} onUnauthorized={handleUnauthorized} onNavigate={navigate} />
|
||||
: <ManagementPages page={page} user={user} onUnauthorized={handleUnauthorized} onNavigate={navigate} />}
|
||||
</PageReveal>
|
||||
</Suspense>
|
||||
</div>
|
||||
</main>
|
||||
<Modal
|
||||
className="navigation-search-modal"
|
||||
title="搜索功能页面"
|
||||
open={searchOpen}
|
||||
footer={null}
|
||||
centered
|
||||
width={520}
|
||||
onCancel={() => setSearchOpen(false)}
|
||||
>
|
||||
<Input
|
||||
autoFocus
|
||||
allowClear
|
||||
prefix={<SearchOutlined />}
|
||||
placeholder="输入页面名称"
|
||||
value={searchTerm}
|
||||
onChange={event => setSearchTerm(event.target.value)}
|
||||
onPressEnter={() => matchingPages[0] && navigate(matchingPages[0].key)}
|
||||
/>
|
||||
<div className="navigation-search-results" role="listbox" aria-label="功能页面">
|
||||
{matchingPages.length ? matchingPages.map(item => (
|
||||
<button className="navigation-result" type="button" key={item.key} role="option" aria-selected={page === item.key} onClick={() => navigate(item.key)}>
|
||||
<span>{item.label}</span><kbd>Enter</kbd>
|
||||
</button>
|
||||
)) : <div className="navigation-search-empty">没有匹配的功能页面</div>}
|
||||
</div>
|
||||
<div className="navigation-search-footnote">按 Enter 打开首项,Esc 关闭</div>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginPage({ onSuccess }: { onSuccess: (user: AuthUser) => void }) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [loginError, setLoginError] = useState('');
|
||||
const [form] = Form.useForm<{ username: string; password: string }>();
|
||||
const submit = async (values: { username: string; password: string }) => {
|
||||
setBusy(true);
|
||||
setLoginError('');
|
||||
try {
|
||||
const result = await api.login(values.username, values.password);
|
||||
onSuccess(result.user);
|
||||
} catch (error) {
|
||||
setLoginError(error instanceof Error ? error.message : '登录失败,请检查账号后重试');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="login-screen">
|
||||
<section className="login-art" aria-label="质量中心品牌介绍">
|
||||
<div className="login-orbit login-orbit-one" aria-hidden="true" />
|
||||
<div className="login-orbit login-orbit-two" aria-hidden="true" />
|
||||
<div className="login-brand-lockup">
|
||||
<img src="/yunsheng-logo.png" alt="宁波韵升" />
|
||||
<span className="login-brand-divider" />
|
||||
<strong>质量中心</strong>
|
||||
</div>
|
||||
<div className="login-art-copy">
|
||||
<span className="login-eyebrow">QUALITY DATA PLATFORM</span>
|
||||
<h1>质量数据<br />分析平台</h1>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="login-panel" aria-label="账号登录">
|
||||
<div className="login-card">
|
||||
<h2>登录工作台</h2>
|
||||
<Form form={form} layout="vertical" onFinish={submit} onValuesChange={() => setLoginError('')} requiredMark={false} name="quality-center-login">
|
||||
<Form.Item name="username" label="账号" rules={[{ required: true, whitespace: true, message: '请输入账号' }]}>
|
||||
<Input autoComplete="username" autoFocus placeholder="请输入登录账号" disabled={busy} />
|
||||
</Form.Item>
|
||||
<Form.Item name="password" label="密码" rules={[{ required: true, message: '请输入密码' }]}>
|
||||
<Input.Password autoComplete="current-password" placeholder="请输入密码" disabled={busy} />
|
||||
</Form.Item>
|
||||
{loginError && <Alert className="login-error" type="error" showIcon message={loginError} role="alert" />}
|
||||
<Button className="login-submit" type="primary" htmlType="submit" loading={busy} block>{busy ? '正在登录…' : '登录质量中心'}</Button>
|
||||
</Form>
|
||||
</div>
|
||||
<footer className="login-footer">宁波韵升股份有限公司 <span>·</span> © 2026</footer>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user