320 lines
14 KiB
TypeScript
320 lines
14 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
import {
|
|
Alert,
|
|
App,
|
|
Button,
|
|
Dropdown,
|
|
Form,
|
|
Input,
|
|
Select,
|
|
Spin,
|
|
Tooltip,
|
|
} from 'antd';
|
|
import {
|
|
AppstoreOutlined,
|
|
ApartmentOutlined,
|
|
BgColorsOutlined,
|
|
CheckOutlined,
|
|
DatabaseOutlined,
|
|
DownOutlined,
|
|
DeploymentUnitOutlined,
|
|
KeyOutlined,
|
|
LineChartOutlined,
|
|
LoadingOutlined,
|
|
LogoutOutlined,
|
|
RobotOutlined,
|
|
SettingOutlined,
|
|
TeamOutlined,
|
|
ToolOutlined,
|
|
UserOutlined,
|
|
} 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';
|
|
import PersonalAccount, { type AccountTab } from './PersonalAccount';
|
|
|
|
import { CachedWorkspacePages, type WorkspaceNavigation } from './CachedWorkspacePages';
|
|
|
|
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' || key === 'imports') return 'sources';
|
|
if (key === 'scrap') return 'product';
|
|
if (key === 'basis') return 'overall';
|
|
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],
|
|
] as const,
|
|
},
|
|
{
|
|
label: '规则与管理',
|
|
items: [
|
|
['rules', '计算规则', SettingOutlined],
|
|
['mappings', '对应关系', ToolOutlined],
|
|
['masterData', '基础数据', DatabaseOutlined],
|
|
['tasks', '任务与监控', LineChartOutlined],
|
|
['access', '权限与审计', KeyOutlined],
|
|
] as const,
|
|
},
|
|
];
|
|
|
|
function shownDepartment(value: string): string {
|
|
return value === '质量管理部' ? '质量中心' : value;
|
|
}
|
|
|
|
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 [accountTab, setAccountTab] = useState<AccountTab | null>(null);
|
|
const workspaceNavigation = useRef<WorkspaceNavigation>(null);
|
|
|
|
useEffect(() => {
|
|
const syncFromLocation = () => {
|
|
const url = new URL(window.location.href);
|
|
const currentPage = url.searchParams.get('page') || '';
|
|
if (['headers', 'releases', 'scrap', 'basis', 'imports'].includes(currentPage)) {
|
|
if (currentPage === 'imports') url.searchParams.set('showImportHistory', '1');
|
|
url.searchParams.set('page', currentPage === 'basis' ? 'overall' : currentPage === 'scrap' ? 'product' : 'sources');
|
|
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
|
|
}
|
|
if (workspaceNavigation.current) workspaceNavigation.current.syncLocation(); else 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) => {
|
|
if (workspaceNavigation.current) { workspaceNavigation.current.navigate(next, query, resultRef); return; }
|
|
const url = new URL(window.location.href);
|
|
if (next === 'imports') { next = 'sources'; url.searchParams.set('showImportHistory', '1'); }
|
|
else url.searchParams.delete('showImportHistory');
|
|
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);
|
|
};
|
|
|
|
const handleUnauthorized = useCallback((error: unknown) => {
|
|
if (error instanceof ApiError && error.status === 401) {
|
|
setUser(null);
|
|
void api.refreshCsrf().catch(() => undefined);
|
|
return true;
|
|
}
|
|
return false;
|
|
}, []);
|
|
|
|
const logout = async () => {
|
|
try { await api.logout(); setAccountTab(null); setUser(null); }
|
|
catch (error) { if (!handleUnauthorized(error)) message.error(error instanceof Error ? error.message : '退出失败'); }
|
|
};
|
|
|
|
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>
|
|
))}
|
|
</nav>
|
|
<div className="user-block">
|
|
<button type="button" className="user-profile-trigger" aria-label="打开个人账户" onClick={() => setAccountTab('profile')}>
|
|
<span className="avatar">{(user.displayName || user.username).slice(0, 1)}</span>
|
|
<span className="user-copy"><strong>{user.displayName || user.username}</strong><small>{user.departments.map(shownDepartment).join('、') || '个人账户'}</small></span>
|
|
</button>
|
|
<Tooltip title="退出登录"><Button type="text" icon={<LogoutOutlined />} aria-label="退出登录" onClick={() => void logout()} /></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">
|
|
<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>
|
|
{user.departments.length > 0 && <span className="top-organization"><TeamOutlined />{user.departments.map(shownDepartment).join('、')}</span>}
|
|
<Dropdown trigger={['click']} menu={{ items: [
|
|
{ key: 'profile', icon: <UserOutlined />, label: '个人资料' },
|
|
{ key: 'password', icon: <KeyOutlined />, label: '修改密码' },
|
|
{ type: 'divider' },
|
|
{ key: 'logout', icon: <LogoutOutlined />, label: '退出登录' },
|
|
], onClick: ({ key }) => { if (key === 'logout') void logout(); else setAccountTab(key as AccountTab); } }}>
|
|
<Button type="text" aria-label="个人账户菜单"><UserOutlined />{user.displayName || user.username}<DownOutlined /></Button>
|
|
</Dropdown>
|
|
</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 })) })),
|
|
]} />
|
|
<Button type="text" icon={<UserOutlined />} aria-label="打开个人账户" onClick={() => setAccountTab('profile')} />
|
|
</div>
|
|
<div className="page-content">
|
|
<CachedWorkspacePages ref={workspaceNavigation} page={page} user={user} onPageChange={setPage} onUserChange={setUser} onUnauthorized={handleUnauthorized} />
|
|
</div>
|
|
</main>
|
|
<PersonalAccount user={user} tab={accountTab} onClose={() => setAccountTab(null)} onUserChange={setUser}
|
|
onUnauthorized={handleUnauthorized} onLogout={logout} />
|
|
</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>
|
|
);
|
|
}
|