Files
quality_analyse/web/src/ManagementPages.tsx
T
lyun c3354c1f64 新增:查询页面快照并修复筛选选框闪烁
页面快照支持勾选查询条件、指标卡片、趋势、汇总表、不良构成和细分缺陷图,复制PNG或下载;增加取消、分阶段提示和等待超时恢复。

修复公共Select弹层准备帧被opacity覆盖导致的先闪出再展开,并取消查询字段原生label的重复点击转发。

同步已经验收上线的销售订单类型映射、排除筛选及预聚合,以及其线上权限、删除确认配套源码;保留既有公式编辑和名录编码修改。源码范围按发布清单冻结,不纳入本机数据、凭据及未发布工作。

验证:前后端独立源码构建通过;10项前端检查、4项订单分类单元测试通过;实际系统剪贴板粘贴PNG验证通过;线上配置及筛选结果与发布前一致,后端未重启。
2026-11-04 00:15:32 +08:00

2041 lines
166 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
import { MappingEditorContext } from './MappingEditorContext';
import { ClassificationRuleEditor } from './ClassificationRuleEditor';
import { ManagementSections } from './ManagementSections';
import { ROLE_LABELS, ROLE_DESCRIPTIONS, USER_ROLE_OPTIONS } from './userRoles';
import type { ClassificationSelection } from './classificationMaintenance';
import { TasksMonitorPage } from './TasksMonitorPage';
import { configurationDateTime, currentConfigurationName } from './configurationName';
import { BusinessValue, currentMetricFormula } from './BusinessValue';
import { AnalysisNarrative } from './AnalysisNarrative';
import { AnalysisClarification } from './AnalysisClarification';
import { pendingClarificationTurnId } from './analysisClarificationModel';
import { useAnalysisVisualRecovery } from './analysisVisualRecovery';
import { mergeModelThinking, modelThinkingEntries } from './analysisModelThinking';
import { usePageCache, useMaintenanceRefresh } from './pageCache';
import { FilterFieldSettings } from './FilterFieldSettings';
import { isInternalDataField, publicJson, readableRuleDescription } from './publicDataDisplay';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useClassificationQueue } from './useClassificationQueue';
import { useUnclassifiedInventory } from './useUnclassifiedInventory';
import type { ClassificationCommand } from './classificationQueue';
import {
Alert,
App,
Button,
Checkbox,
Drawer,
Dropdown,
Empty,
Form,
Input,
Modal,
Pagination,
Progress,
Select,
Spin,
Switch,
Tag,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined, LoadingOutlined } from '@ant-design/icons';
import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
import type { DataWorkflowStatus } from './NoCodeDataTypes';
import type { PageKey } from './QualityWorkspace';
import { readableSelectPopup } from './readableSelectPopup';
import './management-alignment.css';
import { QualityTargetsPanel } from './QualityTargetsPanel';
import { METRIC_KEYS, formulaOnly, ruleChangeSummary } from './rulePresentation';
import { ruleLogicIssues } from './ruleEditing';
import './rules-workspace.css';
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
import { AiMarkdown } from './AiMarkdown';
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
import { AnalysisApiSettings } from './AnalysisApiSettings';
import { acceptAnalysisEvent, analysisScrollFollows, analysisStreamStatus, emptyAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
import { AnalysisProcess } from './AnalysisProcess';
import { AnalysisMemberListPanel } from './AnalysisMemberList';
import { AnalysisRecordListPanel } from './AnalysisRecordList';
import { restoredAnalysisDraft, analysisComposerState, analysisFollowRequestReady } from './analysisScope';
import { isValidAnalysisPeriodContext } from './analysisPeriodModel';
import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutcomeUnknown, type AnalysisSubmission } from './analysisSubmission';
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
import './analysis-chat.css';
const TABLE_PAGE_SIZE = 15;
import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, SourceFilesPanel, type PendingSourceDeletion } from './NoCodeDataWorkflow';
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
import { ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
import { useDelayedBusy, useDelayedIndicator } from './useDelayedBusy';
import { useVisiblePolling } from './useVisiblePolling';
import { importIssuePageKey, matchesImportIssuePage } from './importLifecycleGuards';
function apiMessage(error: unknown): string {
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
return error instanceof Error ? error.message : '服务请求失败';
}
function toText(value: unknown): string {
if (value === null || value === undefined || value === '') return '—';
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return String(value);
try { return JSON.stringify(value); } catch { return String(value); }
}
function regressionStatus(value: unknown): string {
return value === 'UNCONFIGURED' ? '未配置原表验收资料' : toText(value);
}
function shownDepartment(value: string): string {
return value === '质量管理部' ? '质量中心' : value;
}
function restoredAnalysisTurns(history: Record<string, unknown>, metadata: Collection<Record<string, unknown>> | { items: Record<string, unknown>[] }): Record<string, unknown>[] {
const saved = Array.isArray(history.turns) ? history.turns.filter(isObjectRecord) : [];
return collectionItems(metadata).slice().reverse().map(turn => {
const found = saved.find(item => item.id === turn.id);
const answer = found && isObjectRecord(found.result) ? found.result : {};
const status=answer.visualRecovery&&answer.originalStatus===turn.status?answer.status||turn.status:turn.status;
return { ...found, ...answer, ...turn, status, sessionId: history.id };
});
}
type AnalysisResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
type AnalysisLinkContext = { present: boolean; query?: QueryParams; resultRef?: AnalysisResultRef; error?: string };
type LinkedSessionRequest = { key: string; promise: ReturnType<typeof api.createAnalysisSession> };
type AnalysisPageWindow = Window & { __qualityAnalysisLinkedSessionRequest?: LinkedSessionRequest };
const ANALYSIS_FINAL_STATUSES = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']);
function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext {
if (!encoded) return { present: false };
try {
const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/').padEnd(Math.ceil(encoded.length / 4) * 4, '='));
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
const payload: unknown = JSON.parse(new TextDecoder().decode(bytes));
if (!payload || typeof payload !== 'object') throw new Error('分析条件链接格式无效');
const source = payload as Record<string, unknown>;
const rawQuery = source.query && typeof source.query === 'object' ? source.query as Record<string, unknown> : null;
if (!rawQuery) throw new Error('分析条件链接缺少查询上下文');
const year = Number(rawQuery.year);
if (!Number.isInteger(year) || year < 2000 || year > 2100) throw new Error('分析条件链接中的年份无效');
const month = rawQuery.month === undefined || rawQuery.month === null ? undefined : Number(rawQuery.month);
const quarter = rawQuery.quarter === undefined || rawQuery.quarter === null ? undefined : Number(rawQuery.quarter);
const monthStart = rawQuery.monthStart === undefined || rawQuery.monthStart === null ? undefined : Number(rawQuery.monthStart);
const monthEnd = rawQuery.monthEnd === undefined || rawQuery.monthEnd === null ? undefined : Number(rawQuery.monthEnd);
if (!isValidAnalysisPeriodContext({ year, month, quarter, monthStart, monthEnd }, 2000, 2100)) throw new Error('分析条件链接中的统计期间无效');
const views: ViewKind[] = ['overall', 'department', 'group', 'product', 'projectGroup'];
if (!views.includes(rawQuery.view as ViewKind)) throw new Error('分析条件链接中的查询维度无效');
const view = rawQuery.view as ViewKind;
const query: QueryParams = { year, ...(month !== undefined ? { month } : {}), ...(quarter !== undefined ? { quarter } : {}),
...(monthStart !== undefined ? { monthStart } : {}), ...(monthEnd !== undefined ? { monthEnd } : {}), view };
for (const key of ['department', 'group', 'product', 'projectGroup'] as const) {
const value = rawQuery[key];
if (value === undefined || value === null || value === '') continue;
if (typeof value !== 'string') throw new Error(`分析条件链接中的${key}筛选无效`);
if (value.startsWith('~qv1~') && decodeQueryValueList(value).length === 0) throw new Error(`分析条件链接中的${key}多选值无效`);
query[key] = value;
}
if (rawQuery.extraFilters && typeof rawQuery.extraFilters === 'object') query.extraFilters = rawQuery.extraFilters as Record<string,string[]>;
if (rawQuery.releaseId && typeof rawQuery.releaseId === 'string') query.releaseId = rawQuery.releaseId;
if (typeof rawQuery.includeUnassigned === 'boolean') query.includeUnassigned = rawQuery.includeUnassigned;
const rawRef = source.resultRef && typeof source.resultRef === 'object' ? source.resultRef as Record<string, unknown> : undefined;
let resultRef: AnalysisResultRef | undefined;
if (rawRef) {
if (rawRef.kind !== 'TOP' || typeof rawRef.resultId !== 'string' || !rawRef.resultId || typeof rawRef.releaseId !== 'string' || !rawRef.releaseId) throw new Error('排名结果引用不完整,请重新打开分析');
if (query.releaseId && query.releaseId !== rawRef.releaseId) throw new Error('查询数据已更新,请重新打开分析');
query.releaseId = rawRef.releaseId;
resultRef = { kind: 'TOP', resultId: rawRef.resultId, releaseId: rawRef.releaseId };
}
return { present: true, query, ...(resultRef ? { resultRef } : {}) };
} catch (error) {
return { present: true, error: error instanceof Error ? error.message : '分析条件链接无法读取' };
}
}
function shownRole(value: unknown): string {
const role = String(value ?? '');
return ROLE_LABELS[role] ?? role;
}
function readableValue(value: unknown) {
if (value === null || value === undefined || value === '') return <span className="muted-dash">—</span>;
if (typeof value === 'object') return <pre className="json-cell">{publicJson(value)}</pre>;
return String(value);
}
function ratioText(value: unknown): string {
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
}
function summaryText(value: unknown): string {
if (Array.isArray(value)) return value.map(item => summaryText(item)).filter(Boolean).join(';') || '—';
if (value && typeof value === 'object') {
return Object.entries(value as Record<string, unknown>).filter(([key]) => !isInternalDataField(key)).map(([key, item]) => `${key}:${summaryText(item)}`).join(';') || '—';
}
return value === null || value === undefined || value === '' ? '—' : String(value);
}
function unwrapItems(value: unknown): { items: Record<string, unknown>[]; total?: number; page?: number; pageSize?: number; currentReleaseId?: string | null } {
if (Array.isArray(value)) return { items: value as Record<string, unknown>[] };
if (value && typeof value === 'object') {
const candidate = value as Collection;
return { ...candidate, items: collectionItems(candidate).filter(item => item && typeof item === 'object') as Record<string, unknown>[] };
}
return { items: [] };
}
function DynamicTable({ items, rowKey = 'id', paginate = true, indexOffset = 0 }: { items: Record<string, unknown>[]; rowKey?: string; paginate?: boolean; indexOffset?: number }) {
const keys = useMemo(() => {
const discovered = new Set<string>();
for (const item of items.slice(0, 30)) Object.keys(item).filter(key => !isInternalDataField(key)).forEach(key => discovered.add(key));
const list = [...discovered];
const priority = ['name', 'sourceFile', 'status', 'stage', 'year', 'month', 'id', 'createdAt', 'updatedAt'];
list.sort((a, b) => {
const ai = priority.indexOf(a); const bi = priority.indexOf(b);
if (ai >= 0 || bi >= 0) return (ai < 0 ? 999 : ai) - (bi < 0 ? 999 : bi);
return a.localeCompare(b);
});
return list.slice(0, 10);
}, [items]);
const columns: ColumnsType<Record<string, unknown>> = keys.map(key => ({
title: key,
dataIndex: key,
key,
width: ['id', 'sha256'].includes(key) ? 220 : 160,
ellipsis: true,
render: value => readableValue(value),
}));
return items.length
? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} indexOffset={indexOffset} scroll={{ x: 'max-content' }} />
<p className="table-caption">共 {items.length} 条记录</p></div>
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无记录" />;
}
type ManagementPageProps = {
page: PageKey; user: AuthUser; onUnauthorized: (error: unknown) => boolean;
onNavigate: (page: PageKey) => void;
};
export default function ManagementPages(props: ManagementPageProps) {
return <CompactManagementTables.Provider value={['sources','imports','rules','mappings','masterData','tasks','access','basis'].includes(props.page)}>
<ManagementPageContents {...props}/>
</CompactManagementTables.Provider>;
}
function RulesWorkspace({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
const [section, setSection] = useState('dictionary');
const [focusMetric, setFocusMetric] = useState<{ code: string; request: number }>();
const editFormula = (code: string) => { setFocusMetric({ code: METRIC_KEYS[code] || code, request: Date.now() }); setSection('settings'); };
return <ManagementSections selectedKey={section} onSelect={setSection} items={[
{ key: 'dictionary', label: '指标说明', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} onEditFormula={editFormula} /> },
{ key: 'targets', label: '质量目标', children: <QualityTargetsPanel onUnauthorized={onUnauthorized} /> },
{ key: 'settings', label: '计算设置', children: <ConfigManagementPage kind="rules" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} focusMetric={focusMetric} /> },
]} />;
}
function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) {
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
if (page === 'tasks') return <TasksMonitorPage user={user} onUnauthorized={onUnauthorized} />;
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
if (page === 'rules') return <RulesWorkspace user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />;
if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' },
tasks: { endpoint: 'tasks', title: '后台任务', subtitle: '任务状态、进度和服务端返回的失败信息。' },
};
const config = resource[page];
return config ? <ReadOnlyResourcePage {...config} user={user} onUnauthorized={onUnauthorized} onNavigate={() => onNavigate('tasks')} /> : <Empty description="未找到页面" />;
}
function PageHeader({ actions }: { title: string; description?: string; actions?: React.ReactNode }) {
return actions ? <div className="management-module-actions"><div className="page-heading-actions">{actions}</div></div> : null;
}
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
const { active } = usePageCache();
const [sources, setSources] = useState<SourceItem[]>([]);
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
const [sourcesLoaded, setSourcesLoaded] = useState(false);
const [releaseLoaded, setReleaseLoaded] = useState(false);
const sourceRead = useDelayedBusy();
const [error, setError] = useState('');
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
const [historyOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
const pendingKey = `quality-pending-source-deletions:${user.id}`;
const [pendingDeletion, setPendingDeletion] = useState<PendingSourceDeletion>(() => {
try {
const saved = JSON.parse(localStorage.getItem(pendingKey) || 'null');
if (saved && Array.isArray(saved.ids) && saved.ids.length <= 50 && saved.ids.every((id: unknown) => typeof id === 'string') && (saved.releaseId === null || typeof saved.releaseId === 'string')) return saved;
} catch { /* Pending changes are optional when storage is unavailable. */ }
return { ids: [], releaseId: null };
});
useEffect(() => { try { if (pendingDeletion.ids.length) localStorage.setItem(pendingKey, JSON.stringify(pendingDeletion)); else localStorage.removeItem(pendingKey); } catch { /* Keep in-memory changes available. */ } }, [pendingKey, pendingDeletion]);
const onDeleted = useCallback((ids: string[]) => setPendingDeletion(previous => ({ ...previous, ids: previous.ids.filter(id => !ids.includes(id)) })), []);
const toggleDelete = (id: string) => setPendingDeletion(previous => previous.ids.includes(id)
? { ...previous, ids: previous.ids.filter(value => value !== id) }
: previous.ids.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId });
const load = useCallback(() => sourceRead.run(async () => {
const failures: string[] = [];
const [sourceResult, releaseResult] = await Promise.allSettled([api.sources(), api.releases()]);
if (sourceResult.status === 'fulfilled') { setSources(collectionItems(sourceResult.value)); setSourcesLoaded(true); }
else if (!onUnauthorized(sourceResult.reason)) failures.push(`来源清单:${apiMessage(sourceResult.reason)}`);
if (releaseResult.status === 'fulfilled') { setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null); setReleaseLoaded(true); }
else if (!onUnauthorized(releaseResult.reason)) failures.push(`当前发布版本:${apiMessage(releaseResult.reason)}`);
setError(failures.join(';'));
}), [onUnauthorized, sourceRead.run]);
useEffect(() => { if (active && (!sourcesLoaded || !releaseLoaded)) void load(); }, [active, sourcesLoaded, releaseLoaded, load]);
useMaintenanceRefresh(load);
return <div className="management-page">
{error && <Alert showIcon type="error" message="来源信息读取失败" description={sourcesLoaded || releaseLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} onUnauthorized={onUnauthorized} /> },
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
]} />
</div>;
}
function ImportHistoryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const load = useCallback(() => read.run(async () => {
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setLoaded(true); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
useVisiblePolling(load, 2000, active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase())));
useMaintenanceRefresh(load);
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button></div>
{error && <Alert showIcon type="error" message="导入记录读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={<Button onClick={() => void load()}>重试</Button>} />}
{loading && !loaded ? <Spin /> : loaded && <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
</section>;
}
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [result, setResult] = useState<Collection | null>(null);
const [loadedRunId, setLoadedRunId] = useState('');
const [loadedPage, setLoadedPage] = useState(0);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const [page, setPage] = useState(1);
const activeRef = useRef(active); activeRef.current = active;
const requestGeneration = useRef(0);
const requestRef = useRef<{ key: string; promise: Promise<void> } | null>(null);
const load = useCallback(() => {
if (!active || !runId) return Promise.resolve();
const key = importIssuePageKey(runId, page);
if (requestRef.current?.key === key) return requestRef.current.promise;
const generation = ++requestGeneration.current;
const promise = read.run(async () => {
try {
const value = await api.importIssues(runId, page, TABLE_PAGE_SIZE);
if (generation !== requestGeneration.current || !activeRef.current) return;
setResult(value); setLoadedRunId(runId); setLoadedPage(page); setError('');
} catch (value) { if (generation === requestGeneration.current && activeRef.current && !onUnauthorized(value)) setError(apiMessage(value)); }
}).finally(() => { if (requestRef.current?.promise === promise) requestRef.current = null; });
requestRef.current = { key, promise };
return promise;
}, [active, onUnauthorized, page, read.run, runId]);
useEffect(() => {
if (active && runId && (loadedRunId !== runId || loadedPage !== page)) void load();
}, [active, loadedPage, loadedRunId, load, page, runId]);
const items = loadedRunId === runId ? unwrapItems(result).items : [];
const hasSameRunResult = loadedRunId === runId && loadedPage > 0;
const pageMatches = hasSameRunResult && matchesImportIssuePage(loadedRunId, loadedPage, runId, page);
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
{error && <Alert showIcon type="error" message="问题清单读取失败" description={pageMatches ? `${error};第 ${page} 页的上次成功结果仍保留。` : hasSameRunResult ? `${error};以下仍显示第 ${loadedPage} 页上次成功结果。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
{loading && !hasSameRunResult ? <div className="loading-panel"><Spin />正在读取问题行…</div> : hasSameRunResult ? <><DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />{!pageMatches && loading && <div className="completion-note"><Spin size="small" /> 正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。</div>}</> : null}
{hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={pageMatches ? page : loadedPage} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
</Drawer>;
}
function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized }: {
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
}) {
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const { active } = usePageCache();
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy();
const loading = read.busy;
const [error, setError] = useState('');
const [metadata, setMetadata] = useState<{ total?: number; page?: number; pageSize?: number }>({});
const load = useCallback(() => read.run(async () => {
try {
const result = await api.tasks();
const normalized = unwrapItems(result);
setItems(endpoint === 'imports' ? normalized.items.filter(item => String(item.type).toUpperCase() === 'IMPORT') : normalized.items);
setMetadata({ total: normalized.total, page: normalized.page, pageSize: normalized.pageSize });
setError(''); setLoaded(true);
} catch (value) {
if (!onUnauthorized(value)) setError(apiMessage(value));
}
}), [endpoint, onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, endpoint, loaded, load]);
useVisiblePolling(load, endpoint === 'imports' ? 2000 : 15000, active && loaded && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status || '').toUpperCase())));
return <div className="management-page">
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>} />
{error && <Alert type="error" showIcon message="列表读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={!loaded ? <Button onClick={() => void load()}>重试</Button> : undefined} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
{loading && !loaded ? <div className="loading-panel"><Spin />正在读取…</div> : loaded && <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
</section>
</div>;
}
function RuleContents({ value }: { value: unknown }) {
const definition = value && typeof value === 'object' ? value as Record<string, unknown> : {};
if (definition.version === 'pq-dax-v1' && !definition.rowRules && !definition.metricRules) return <p>此历史记录未保存可展开的公式明细。</p>;
return <BusinessValue value={value} />;
}
function ruleDisplayName(value: unknown): string {
const name = String(value || '');
return /power\s*query|power\s*pivot|\bdax\b|\bpq\b/i.test(name) ? '基础计算规则' : name;
}
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections, focusMetric }: { focusMetric?: { code: string; request: number }; extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
const { message } = App.useApp();
const { active: pageActive } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [itemsLoaded, setItemsLoaded] = useState(false);
const itemRead = useDelayedBusy();
const loading = itemRead.busy;
const [error, setError] = useState('');
const [busyId, setBusyId] = useState('');
const actionLock = useRef(false);
const [drafting, setDrafting] = useState<Record<string, unknown> | null>(null);
const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null);
const [impactOpen, setImpactOpen] = useState(false);
const [impact, setImpact] = useState<Record<string, unknown> | null>(null);
const [regressionOpen, setRegressionOpen] = useState(false);
const [regression, setRegression] = useState<Record<string, unknown> | null>(null);
const [regressionRuns, setRegressionRuns] = useState<Record<string, unknown>[]>([]);
const [regressionError, setRegressionError] = useState('');
const [regressionBusy, setRegressionBusy] = useState(false);
const [form] = Form.useForm<{ name: string; description: string }>();
const [draftDefinition, setDraftDefinition] = useState<ConfigDefinition>({});
const loadedDefinitionKey=useRef('');
const loadedDefinition=useRef('');
const classificationUpdates=useClassificationQueue(kind==='mappings'?String(user.id):'inactive-'+kind);
const [ruleSchema, setRuleSchema] = useState<Record<string, unknown> | null>(null);
const [ruleSchemaError, setRuleSchemaError] = useState('');
const [ruleBaseline, setRuleBaseline] = useState<ConfigDefinition>({});
const [publishedNames, setPublishedNames] = useState<PublishedConfigNames | null>(null);
const [matchMetadata,setMatchMetadata]=useState<Record<string,unknown>|null>(null);
const [differenceItem, setDifferenceItem] = useState<Record<string, unknown> | null>(null);
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
const [workflowStatusError, setWorkflowStatusError] = useState('');
const statusRead = useDelayedBusy();
const supportRequested = useRef(false);
const isRules = kind === 'rules';
const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系';
const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
const canManage = user.roles.some(role => isRules
? ['SYSTEM_ADMIN'].includes(role)
: ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canApplyWorkflow = (isRules ? workflowStatus?.capabilities?.canApplyRule : workflowStatus?.capabilities?.canApplyMapping) ?? workflowStatus?.capabilities?.canApply ?? canManage;
const workflowMappingBase = workflowStatus?.activeMapping
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
const load = useCallback((silent = false) => {
const read = async () => {
try {
const result = isRules ? await api.rules() : await api.mappings();
setItems(collectionItems(result)); setItemsLoaded(true); setError('');
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
};
return silent ? read() : itemRead.run(read);
}, [isRules, itemRead.run, onUnauthorized]);
const loadEditorSupport = useCallback(async () => {
try {
if (isRules) { setRuleSchema(await api.ruleSchema()); setRuleSchemaError(''); }
else {
const [names, metadata] = await Promise.allSettled([api.referenceNames(), api.classificationMetadata()]);
if (names.status === 'fulfilled') setPublishedNames(names.value);
if (metadata.status === 'fulfilled') setMatchMetadata(metadata.value);
const errors = [names, metadata].flatMap((result, index) => result.status === 'rejected' && !onUnauthorized(result.reason) ? [`${index === 0 ? '发布名录' : '对应关系元数据'}:${apiMessage(result.reason)}`] : []);
if (errors.length) setError(errors.join(';'));
}
} catch (value) { if (!onUnauthorized(value)) { if (isRules) setRuleSchemaError(apiMessage(value)); else setError(`当前发布名录读取失败:${apiMessage(value)}`); } }
}, [isRules, onUnauthorized]);
const refreshWorkflowStatus = useCallback(() => statusRead.run(async () => {
try { setWorkflowStatus(await api.dataWorkflowStatus()); setWorkflowStatusLoaded(true); setWorkflowStatusError(''); }
catch (value) { if (!onUnauthorized(value)) setWorkflowStatusError(apiMessage(value)); }
}), [onUnauthorized, statusRead.run]);
const workflowOperation = useDataWorkflowOperation(isRules ? 'apply-rule' : 'apply-mapping', () => {
void load(); void refreshWorkflowStatus();
});
useEffect(() => { if (pageActive && !itemsLoaded) void load(); }, [pageActive, itemsLoaded, load]);
useEffect(() => { if (pageActive && !supportRequested.current) { supportRequested.current = true; void loadEditorSupport(); } }, [pageActive, loadEditorSupport]);
useEffect(() => { if (pageActive && !workflowStatusLoaded && !workflowStatusError) void refreshWorkflowStatus(); }, [pageActive, workflowStatusLoaded, workflowStatusError, refreshWorkflowStatus]);
useEffect(() => {
if (!workflowStatus) return;
const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record<string, unknown> } | null | undefined;
const fallback = items.find(row => String(row.status).toUpperCase() === 'ACTIVE');
const storedDefinition = active?.definition ?? fallback?.definition;
const definition = isRules && testMode && String(active?.id ?? fallback?.id) === 'pq-dax-v1' && ruleSchema?.defaultDefinition
? ruleSchema.defaultDefinition : storedDefinition;
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;const serialized=JSON.stringify(definition),prior=loadedDefinition.current;setDraftDefinition(previous=>!prior||JSON.stringify(previous)===prior?JSON.parse(serialized) as ConfigDefinition:previous);loadedDefinition.current=serialized;}
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
if (!drafting && isRules) setRuleBaseline(JSON.parse(JSON.stringify(definition || {})) as ConfigDefinition);
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
if (!isRules) return;
const id = String(item.id || ''); if (!id) return;
setRegressionOpen(true); setRegression(null); setRegressionRuns([]); setRegressionError(''); setRegressionBusy(true);
try {
const listResult = await api.ruleRegressions(id);
const runs = collectionItems(listResult).filter(value => value && typeof value === 'object') as Record<string, unknown>[];
setRegressionRuns(runs);
const embeddedValidation = item.validation && typeof item.validation === 'object' ? item.validation as Record<string, unknown> : {};
const runId = preferredRunId || String(embeddedValidation.regressionRunId || runs[0]?.id || '');
if (runId) setRegression(await api.ruleRegression(runId));
else if (embeddedValidation.cases) setRegression({ id: '', ruleVersionId: id, result: embeddedValidation });
} catch (value) { if (!onUnauthorized(value)) setRegressionError(apiMessage(value)); }
finally { setRegressionBusy(false); }
};
const openDraft = (item?: Record<string, unknown>) => {
const source = item ?? items.find(row => String(row.status).toUpperCase() === 'ACTIVE');
setDrafting(item || {});
const definition = JSON.parse(JSON.stringify(!item && isRules && ruleSchema && (source?.definition as Record<string, unknown> | undefined)?.schemaVersion !== ruleSchema.schemaVersion ? ruleSchema.defaultDefinition : source?.definition ?? {})) as ConfigDefinition;
if (kind === 'masterData' && !Object.hasOwn(definition, 'masterData') && publishedNames) {
const mappingField = { departments: 'departmentLookup', groups: 'categoryLookup', products: 'productLookup', projectGroups: 'projectGroupLookup' };
definition.masterData = Object.fromEntries((['departments', 'groups', 'products', 'projectGroups'] as const).map(key => {
const lookup = definition[mappingField[key]]; const mapped = lookup && typeof lookup === 'object' && !Array.isArray(lookup) ? Object.values(lookup).filter((name): name is string => typeof name === 'string' && Boolean(name.trim())) : [];
const codes = new Set<string>();
return [key, Array.from(new Set([...(publishedNames[key] ?? []), ...mapped])).map(name => {
let code = name.slice(0, 100); let suffix = 2; while (codes.has(code)) { const tail = `-${suffix++}`; code = `${name.slice(0, 100 - tail.length)}${tail}`; } codes.add(code); return { code, name, enabled: true };
})];
}));
}
setDraftDefinition(definition);
form.setFieldsValue({
name: String(item?.name || (source?.name ? `${String(source.name).slice(0, 112)}·草稿` : '')),
description: isRules ? readableRuleDescription(source?.description) : String(source?.description || (source?.definition as ConfigDefinition | undefined)?.maintenanceNote || ''),
});
};
const saveDraft = async () => {
if (actionLock.current) return; actionLock.current = true;
try {
const values = await form.validateFields();
const body: Record<string, unknown> = { name: values.name.trim(), definition: isRules ? draftDefinition : { ...draftDefinition, maintenanceNote: values.description?.trim() || '' } };
if (values.description?.trim()) body.description = values.description.trim();
const id = String(drafting?.id || '');
setBusyId(id || 'new');
if (id) {
body.expectedRowVersion = Number(drafting?.rowVersion || 0);
if (isRules) await api.updateRule(id, body); else await api.updateMapping(id, body);
} else {
if (isRules) await api.createRule(body); else await api.createMapping(body);
}
message.success('草稿已保存');
setDrafting(null); form.resetFields(); await load();
} catch (value) {
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { actionLock.current = false; setBusyId(''); }
};
const runAction = async (item: Record<string, unknown>, action: 'validate' | 'activate', confirmDifferences = false) => {
const id = String(item.id || ''); if (!id || actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
const result = isRules
? action === 'validate' ? await api.validateRule(id, { expectedRowVersion: Number(item.rowVersion || 0) }) : await api.activateRule(id, { expectedRowVersion: Number(item.rowVersion || 0), ...(confirmDifferences ? { confirmDifferences: true, regressionRunId: String((item.validation as Record<string, unknown> | undefined)?.regressionRunId || '') } : {}) })
: action === 'validate' ? await api.validateMapping(id, { expectedRowVersion: Number(item.rowVersion || 0) }) : await api.activateMapping(id, { expectedRowVersion: Number(item.rowVersion || 0) });
if (action === 'validate') {
setValidation({ id, value: result });
}
message.success(action === 'validate' ? '校验已完成' : '配置已启用');
if (action === 'activate') setDifferenceItem(null);
await load();
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); if (value instanceof ApiError && value.status === 409) await load(); }
finally { actionLock.current = false; setBusyId(''); }
};
const showImpact = async (item: Record<string, unknown>) => {
const id = String(item.id || ''); if (!id) return;
setImpactOpen(true); setImpact(null);
try { setImpact(await api.governanceDependencyImpact(isRules ? 'rule' : 'mapping', id)); }
catch (value) { setImpactOpen(false); if (!onUnauthorized(value)) message.error(apiMessage(value)); }
};
const changedKeyRows = Array.isArray(impact?.changedKeys) ? impact.changedKeys.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
const impactHits = Array.isArray(impact?.hits) ? impact.hits.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
const regroupingPreview = Array.isArray(impact?.regroupingPreview) ? impact.regroupingPreview.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
const regroupingColumns: ColumnsType<Record<string, unknown>> = [
{ title: '维度', dataIndex: 'dimension', key: 'dimension', width: 120, render: value => toText(value) },
{ title: '对象', dataIndex: 'key', key: 'key', width: 220 },
{ title: '变更前综合率', key: 'beforeComposite', align: 'right', width: 130, render: (_, row) => ratioText(((row.before as Record<string, unknown> | null)?.compositeRate)) },
{ title: '变更后综合率', key: 'afterComposite', align: 'right', width: 130, render: (_, row) => ratioText(((row.after as Record<string, unknown> | null)?.compositeRate)) },
{ title: '变更前黑/亮报废重量', key: 'beforeScrap', align: 'right', width: 180, render: (_, row) => { const before = row.before as Record<string, unknown> | null; return `${toText((before?.black as Record<string, unknown> | undefined)?.scrapWeight)} / ${toText((before?.bright as Record<string, unknown> | undefined)?.scrapWeight)}`; } },
{ title: '变更后黑/亮报废重量', key: 'afterScrap', align: 'right', width: 180, render: (_, row) => { const after = row.after as Record<string, unknown> | null; return `${toText((after?.black as Record<string, unknown> | undefined)?.scrapWeight)} / ${toText((after?.bright as Record<string, unknown> | undefined)?.scrapWeight)}`; } },
{ title: '差异项', key: 'differences', render: (_, row) => Array.isArray(row.differences) ? row.differences.map(item => { const value = item && typeof item === 'object' ? item as Record<string, unknown> : {}; return `${toText(value.path)}:${toText(value.delta ?? value.after)}`; }).join(';') : '—' },
];
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => <strong>{toText(isRules ? ruleDisplayName(value) : value)}</strong> },
{ title: '状态', dataIndex: 'status', key: 'status', width: 125, align: 'center', render: value => <Tag color={String(value).toUpperCase().includes('ACTIVE') ? 'green' : 'blue'}>{({ ACTIVE: '已启用', VALIDATED: '已校验', DRAFT: '草稿', SUPERSEDED: '历史记录', ENGINE_BASELINE: '原始公式', ARCHIVED: '已归档' } as Record<string, string>)[String(value).toUpperCase()] || toText(value)}</Tag> },
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: (value, row) => readableValue(isRules ? readableRuleDescription(value) : value || (row.definition as ConfigDefinition | undefined)?.maintenanceNote) },
{ title: '更新时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
{ title: '操作', key: 'actions', fixed: 'right', width: 330, align: 'center', render: (_, row) => <span className="task-actions">
<Button type="link" onClick={() => setValidation({ id: String(row.id || ''), value: row.definition, purpose: 'definition' })}>{isRules ? '查看定义' : '查看内容'}</Button>
<Button type="link" onClick={() => void showImpact(row)}>影响范围</Button>
{canManage && ['DRAFT', 'VALIDATED'].includes(String(row.status).toUpperCase()) && <Button type="link" onClick={() => openDraft(row)}>编辑草稿</Button>}
{canManage && <Button type="link" loading={busyId === String(row.id)} onClick={() => void runAction(row, 'validate')}>校验</Button>}
{isRules && <Button type="link" loading={regressionBusy && regressionOpen} onClick={() => void openRegression(row)}>回归报告</Button>}
{canManage && String(row.status).toUpperCase() !== 'ACTIVE' && <Button type="link" disabled={String(row.status).toUpperCase() !== 'VALIDATED' || !row.validation || typeof row.validation !== 'object' || (row.validation as Record<string, unknown>).activatable !== true} title="需先通过服务端校验且确认当前引擎可执行" loading={busyId === String(row.id)} onClick={() => { if (isRules && (row.validation as Record<string, unknown>).requiresDifferenceConfirmation === true) { setDifferenceItem(row); setDifferenceConfirmed(false); } else void runAction(row, 'activate'); }}>启用</Button>}
</span> },
];
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', CLASSIFYING_UNASSIGNED:'处理未分类记录', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
const saveClassification = (command: ClassificationCommand) => {
classificationUpdates.queue.enqueue(command,draftDefinition,Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]);
};
const classificationBusy=classificationUpdates.jobs.some(job=>!['failed','completed'].includes(job.status));
const applyCurrent = async () => {
if (actionLock.current) return; actionLock.current = true;
try {
await form.validateFields();
if (isRules && ruleSchema) {
const issues = ruleLogicIssues(draftDefinition, ruleSchema);
if (issues.length) throw new Error(issues[0].message);
}
const values = form.getFieldsValue(true);
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: configurationDateTime(new Date()), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
} catch (value) {
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
}
finally { actionLock.current = false; }
};
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
if (!workflowStatusLoaded) return <div className="management-page">{statusRead.busy ? <div className="loading-panel"><Spin />正在读取当前维护模式…</div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void refreshWorkflowStatus()}>重试</Button>} /> : null}</div>;
if (testMode) {
const notices = <>
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
</div>}
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
{!canApplyWorkflow && <Alert showIcon type="info" message={isRules ? '计算规则由系统管理员维护,当前账号可查看。' : '当前账号可查看配置;维护数据需要数据管理员权限。'} />}
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div>{workflowOperation.busy ? <Spin size="small" /> : <Progress percent={String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : 'success'} />}</section>}
</>;
const editor = (mode: 'catalog' | 'lookups' | 'matchRules' | 'rules') => <div className="management-page nc-simplified-config-page flat-config-page">
{notices}
<section className="panel section-panel flat-config-panel">
<div className="flat-config-toolbar">
<div className="completion-actions"><ConfigurationWorkbookActions value={draftDefinition} onChange={setDraftDefinition} scope={mode==='rules'?'rules':mode==='catalog'?'catalogs':'all'} label={mode==='rules'?'计算规则':mode==='catalog'?'基础名录':'对应关系配置'} defaults={Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]} readOnly={!canApplyWorkflow} disabled={loading||(isRules?!ruleSchema:!matchMetadata)} validate={isRules?undefined:validateStructuredMappingDefinition} whole /></div>
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); }}>刷新</Button>
</div>
{mode === 'rules' && <Form form={form} component={false}><Form.Item name="name" hidden><Input readOnly /></Form.Item><Form.Item name="description" hidden><Input readOnly /></Form.Item></Form>}
{mode === 'rules' ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} showWorkbookActions={false} focusMetric={focusMetric} readOnly={!canApplyWorkflow} />
: mode === 'catalog' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} />
: mode === 'lookups' ? <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} />
: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={matchMetadata??workflowStatus} readOnly={!canApplyWorkflow} />}
{!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=><li key={index}>{issue}</li>)}</ul>} />}
{isRules && ruleChangeSummary(ruleBaseline, draftDefinition).length > 0 && <div className="rule-pending-changes"><strong>本次变更</strong><span>{ruleChangeSummary(ruleBaseline, draftDefinition).join(';')}</span></div>}
{canApplyWorkflow && <div className="nc-simple-save-row"><span>{isRules ? '检查规则 → 重新计算 → 更新报表' : '保存后检查配置并更新报表。'}</span><Button type="primary" size="large" disabled={workflowOperation.busy || classificationBusy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
</section>
</div>;
if (kind === 'masterData') return <><Form form={form} component={false} />{editor('catalog')}</>;
if (kind === 'mappings') return <MappingEditorContext.Provider value={{definition:draftDefinition,update:setDraftDefinition,saveAndApply:saveClassification,classificationJobs:classificationUpdates.jobs,acknowledgeClassifications:ids=>classificationUpdates.queue.acknowledge(ids),ready:canApplyWorkflow && !loading && !workflowOperation.busy && !!workflowMappingBase?.id && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],projectGroups:publishedNames?.projectGroups??[],groups:Array.isArray((draftDefinition.masterData as Record<string,unknown>|undefined)?.groups)?((draftDefinition.masterData as Record<string,unknown>).groups as Record<string,unknown>[]).filter(row=>row.enabled!==false).map(row=>String(row.name)):publishedNames?.groups??[]}}><Form form={form} component={false} /><ManagementSections items={[
{ key: 'lookups', label: '基础对应', children: editor('lookups') },
{ key: 'matchRules', label: '条件匹配', children: editor('matchRules') },
...(extraSections ?? []).map(section => ({ ...section, children: <>{notices}{section.children}</> })),
]} /></MappingEditorContext.Provider>;
return editor('rules');
}
const standardContent = <div className="management-page">
<PageHeader title={title} description={isRules ? '维护来源字段、行计算与指标公式;保留原公式,试算后确认差异再启用。' : kind === 'masterData' ? '独立维护产业部、业务分组、产品和项目组名录;与对应关系共同形成配置。' : '维护源字段到业务分组、项目组、产业部和产品的对应关系。'} actions={<>
{canManage && !isRules && <MasterWorkbookUpload kind={kind === 'masterData' ? 'masterData' : 'mappings'} base={items.find(item => String(item.status).toUpperCase() === 'ACTIVE')} onUnauthorized={onUnauthorized} onComplete={() => void load()} />}
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadEditorSupport(); }}>刷新</Button>
</>} />
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}记录</strong><span>{items.length} 个服务端记录</span></div>
{loading && !itemsLoaded ? <div className="loading-panel"><Spin />正在读取…</div> : itemsLoaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" /> : null}
</section>
<Alert showIcon type="info" message="变更先保存为草稿" description="保存后在清单中校验并启用;启用后重新计算、核对并发布,查询结果才采用新配置。" action={!isRules ? <Button onClick={() => onNavigate('sources')}>前往重新计算</Button> : undefined} />
<Modal className="management-modal structured-config-modal" open={Boolean(drafting)} title={drafting?.id ? `编辑${title}草稿` : `新建${title}草稿`} width={1120} okText="保存草稿" confirmLoading={Boolean(busyId)} onCancel={() => setDrafting(null)} onOk={() => void saveDraft()}>
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="name" label="配置名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input maxLength={120} /></Form.Item>
<Form.Item name="description" label="变更说明"><Input maxLength={1000} /></Form.Item></div></Form>
{isRules ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <>
{kind === 'masterData' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} /> : <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="草稿存在需要处理的名录引用" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0, 20).map((issue, index) => <li key={`${issue}:${index}`}>{issue}</li>)}</ul>} />}
</>}
{!isRules && <TechnicalDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
</Modal>
<Modal className="management-modal structured-config-modal" open={Boolean(differenceItem)} title="确认规则试算差异" width={920} okText="确认差异并启用" okButtonProps={{ disabled: !differenceConfirmed }} confirmLoading={Boolean(busyId)} onCancel={() => setDifferenceItem(null)} onOk={() => { if (differenceItem) void runAction(differenceItem, 'activate', true); }}>
{differenceItem && (() => { const result = differenceItem.validation as Record<string, unknown>; return <>
<Alert showIcon type="warning" message={`试算 ${toText(result.totalRows)} 行,其中 ${toText(result.changedRows)} 行发生变化`} description="启用后用于新构建,现有已发布数据继续保留原结果。请核对差异后确认。" />
<h3>汇总差异</h3><DynamicTable items={Array.isArray(result.differences) ? result.differences as Record<string, unknown>[] : []} />
<h3>来源行差异(最多 100 行)</h3><DynamicTable items={Array.isArray(result.rowDifferences) ? result.rowDifferences as Record<string, unknown>[] : []} />
<Checkbox checked={differenceConfirmed} onChange={event => setDifferenceConfirmed(event.target.checked)}>我已核对本次试算差异,并确认启用此规则</Checkbox>
</>; })()}
</Modal>
{validation && !drafting && <Drawer className="management-drawer" open title={validation.purpose === 'definition' ? '配置定义' : '服务端校验结果'} width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{validation.purpose === 'definition' ? isRules ? <RuleContents value={validation.value} /> : <ReadableConfigDefinition kind={kind === 'masterData' ? 'masterData' : 'mappings'} value={validation.value} /> : (() => {
const response = validation.value && typeof validation.value === 'object' ? validation.value as Record<string, unknown> : {};
const result = response.validation && typeof response.validation === 'object' ? response.validation as Record<string, unknown> : response;
const errors = Array.isArray(result.errors) ? result.errors : []; const warnings = Array.isArray(result.warnings) ? result.warnings : [];
return <><Alert showIcon type={result.activatable === true ? result.requiresDifferenceConfirmation === true ? 'warning' : 'success' : 'error'} message={result.activatable === true ? result.requiresDifferenceConfirmation === true ? '试算存在差异,启用前需要确认' : '校验通过,可以启用' : '校验未通过,请处理以下问题'} description={`校验状态:${toText(result.status)}${result.totalRows !== undefined ? ` · 试算 ${toText(result.totalRows)} 行 · 变化 ${toText(result.changedRows)} 行` : ''}`} />
{errors.length > 0 && <><h3>需要处理</h3><ul className="structured-config-error-list">{errors.map((issue, index) => <li key={index}>{summaryText(issue)}</li>)}</ul></>}
{warnings.length > 0 && <><h3>提示</h3><ul className="structured-config-error-list">{warnings.map((issue, index) => <li key={index}>{summaryText(issue)}</li>)}</ul></>}
{Array.isArray(result.differences) && result.differences.length > 0 && <><h3>汇总差异</h3><DynamicTable items={result.differences as Record<string, unknown>[]} /></>}
{Array.isArray(result.rowDifferences) && result.rowDifferences.length > 0 && <><h3>来源行差异(最多 100 行)</h3><DynamicTable items={result.rowDifferences as Record<string, unknown>[]} /></>}
<details className="completion-technical-detail"><summary>校验原始记录</summary><pre className="json-result">{publicJson(validation.value)}</pre></details></>;
})()}</Drawer>}
{isRules && <Drawer className="management-drawer" open={regressionOpen} title="规则隔离回归报告" width={Math.min(980, window.innerWidth)} onClose={() => { setRegressionOpen(false); setRegression(null); }}>
{regressionError && <Alert showIcon type="error" message="回归报告读取失败" description={regressionError} />}
{regressionRuns.length > 0 && <div className="resource-toolbar"><span>历史执行 {regressionRuns.length} 次</span><Select {...readableSelectPopup} aria-label="选择规则回归执行" value={String(regression?.id || regressionRuns[0]?.id || '') || undefined} options={regressionRuns.map(run => ({ value: String(run.id), label: `${toText(run.status)} · ${toText(run.createdAt)}` }))} onChange={value => { setRegressionBusy(true); api.ruleRegression(value).then(setRegression).catch(value => { if (!onUnauthorized(value)) setRegressionError(apiMessage(value)); }).finally(() => setRegressionBusy(false)); }} /></div>}
{regressionBusy ? <div className="completion-loading"><Spin />读取隔离执行结果…</div> : regression ? (() => {
const result = regression.result && typeof regression.result === 'object' ? regression.result as Record<string, unknown> : regression;
const cases = Array.isArray(result.cases) ? result.cases.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
const failures = Array.isArray(result.failedCases) ? result.failedCases.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
const precision = result.precisionPolicy && typeof result.precisionPolicy === 'object' ? result.precisionPolicy as Record<string, unknown> : {};
return <>
<div className="governance-monitor-grid"><div><small>执行状态</small><strong>{regressionStatus(result.status)}</strong></div><div><small>隔离环境</small><strong>{result.isolated === true ? '是' : result.isolated === false ? '否' : '—'}</strong></div><div><small>回归案例</small><strong>{cases.length}</strong></div><div><small>失败案例</small><strong className={failures.length ? 'negative' : ''}>{failures.length}</strong></div></div>
<p className="completion-note">核验精度:重量 ±{toText(precision.weightAbsolute)},比率 ±{toText(precision.rateAbsolute)}</p>
{Array.isArray(result.errors) && result.errors.length > 0 && <Alert showIcon type="error" message="回归错误" description={(result.errors as unknown[]).map(String).join(';')} />}
<Table size="small" bordered rowKey={(row, index) => String(row.name || index)} dataSource={cases} pagination={false} scroll={{ x: 820 }} columns={[
{ title: '案例', dataIndex: 'name', key: 'name', width: 220 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: (value, row) => row.passed === true ? <Tag color="green">通过</Tag> : row.passed === false ? <Tag color="red">失败</Tag> : toText(value) },
{ title: '期望行数', key: 'expectedRows', align: 'right', width: 120, render: (_, row) => toText((row.details as Record<string, unknown> | undefined)?.expectedRows) },
{ title: '实际行数', key: 'actualRows', align: 'right', width: 120, render: (_, row) => toText((row.details as Record<string, unknown> | undefined)?.actualRows) },
{ title: '差异说明', key: 'details', render: (_, row) => summaryText((row.details as Record<string, unknown> | undefined)?.differences || (row.details as Record<string, unknown> | undefined)?.failedRows || (row.details as Record<string, unknown> | undefined)?.actual) },
]} locale={{ emptyText: '本次回归没有返回案例' }} />
{failures.length > 0 && <><h3>失败案例</h3><Table size="small" bordered rowKey={(row, index) => String(row.name || index)} dataSource={failures} pagination={false} columns={[{ title: '案例', dataIndex: 'name', key: 'name' }, { title: '说明', key: 'details', render: (_, row) => summaryText(row.details) }]} /></>}
<details className="completion-technical-detail"><summary>回归报告原始记录</summary><pre className="json-result">{publicJson(regression)}</pre></details>
</>;
})() : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="该规则尚无隔离回归记录;先执行服务端校验。" />}
</Drawer>}
<Drawer className="management-drawer" open={impactOpen} title={`${title}依赖影响预览`} width={Math.min(980, window.innerWidth)} onClose={() => { setImpactOpen(false); setImpact(null); }}>{impact ? <>
<div className="governance-monitor-grid"><div><small>影响来源</small><strong>{Array.isArray(impact.affectedSources) ? impact.affectedSources.length : toText(impact.affectedSources)}</strong></div><div><small>冻结状态</small><strong>{impact.frozen === true ? '已冻结' : impact.frozen === false ? '未冻结' : '—'}</strong></div><div><small>需要更新报表</small><strong>{impact.requiresNewRelease === true ? '是' : '否'}</strong></div></div>
{impact.status === 'NO_PUBLISHED_RELEASE' && <Alert showIcon type="info" message="暂无可比较的数据" description="服务端没有可用于新旧映射对比的数据;当前没有可计算的映射影响。" />}
<Alert showIcon type="info" message="当前数据保持不变" description={`命中变更键 ${changedKeyRows.length} 项 · 影响来源明细 ${impactHits.length} 项 · 重分组预览 ${regroupingPreview.length} 项`} />
{isRules ? <><h3>依赖与来源</h3><DynamicTable items={[...(Array.isArray(impact.references) ? impact.references as Record<string, unknown>[] : []), ...(Array.isArray(impact.affectedSources) ? impact.affectedSources as Record<string, unknown>[] : [])]} /></> : <>
<h3>映射键前后值</h3><Table size="small" bordered dataSource={changedKeyRows} rowKey={(row, index) => `${toText(row.mappingType)}:${toText(row.sourceKey)}:${index}`} pagination={false} scroll={{ x: 920 }} columns={[{ title: '映射类型', dataIndex: 'mappingType', key: 'mappingType', width: 150 }, { title: '源键', dataIndex: 'sourceKey', key: 'sourceKey', width: 240 }, { title: '变更前', dataIndex: 'before', key: 'before', width: 200, render: (value, row) => <>{toText(value)}{row.beforeEnabled === false && <Tag>停用</Tag>}</> }, { title: '变更后', dataIndex: 'after', key: 'after', width: 200, render: (value, row) => <>{toText(value)}{row.afterEnabled === false && <Tag>停用</Tag>}</> }, { title: '命中范围', key: 'ranges', render: (_, row) => `前:${toText(row.beforeRanges)} · 后:${toText(row.afterRanges)}` }]} locale={{ emptyText: '服务端未报告映射键变化' }} />
<h3>命中来源与行数</h3><Table size="small" bordered dataSource={impactHits} rowKey={(row, index) => `${toText(row.sourceDocumentId)}:${toText(row.sourceKey)}:${index}`} pagination={false} scroll={{ x: 920 }} columns={[{ title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', width: 180 }, { title: '期间', dataIndex: 'month', key: 'month', width: 110 }, { title: '阶段', dataIndex: 'stage', key: 'stage', width: 90, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : toText(value) }, { title: '源键', dataIndex: 'sourceKey', key: 'sourceKey', width: 220 }, { title: '命中行数', dataIndex: 'changedRows', key: 'changedRows', align: 'right', width: 110 }, { title: '源行数', dataIndex: 'rowCount', key: 'rowCount', align: 'right', width: 110 }, { title: '总重量', dataIndex: 'totalWeight', key: 'totalWeight', align: 'right', width: 120 }]} locale={{ emptyText: '无来源命中记录' }} />
<h3>对象重分组预览</h3><Table size="small" bordered dataSource={regroupingPreview} rowKey={(row, index) => `${toText(row.dimension)}:${toText(row.key)}:${index}`} pagination={{ pageSize: 25, showSizeChanger: false }} scroll={{ x: 1050 }} columns={regroupingColumns} locale={{ emptyText: '服务端未返回重分组结果' }} />
</>}
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
</div>;
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{if(actionLock.current)return;actionLock.current=true;setBusyId('editor-new');void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));}).finally(()=>{actionLock.current=false;setBusyId('');});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
}
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
const canEdit=user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
return <ConfigManagementPage kind="mappings" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} extraSections={[
{key:'groups',label:'业务分组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><UnclassifiedSourcesPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
{key:'projects',label:'项目组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><MappingIssueResolutionPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
]}/>;
}
function UnclassifiedSourcesPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
const inventory=useUnclassifiedInventory('group',onUnauthorized);
const [page,setPage]=useState(1);
const total=inventory.items.length;
const currentPage=Math.min(page,Math.max(1,Math.ceil(total/TABLE_PAGE_SIZE)));
const items=inventory.items.slice((currentPage-1)*TABLE_PAGE_SIZE,currentPage*TABLE_PAGE_SIZE);
const {loading,error}=inventory;
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '阶段', dataIndex: 'stage', width: 85, render: value => value === 'black' ? '黑片' : '亮片' },
{ title: '产业部', dataIndex: 'department', width: 140, render: toText },
{ title: '产品', dataIndex: 'product', width: 180, render: toText },
{ title: 'PDT代码', dataIndex: 'pdtCode', width: 90, render: toText },
{ title: '销售区域', dataIndex: 'salesRegion', width: 110, render: toText },
{ title: '原因', key: 'reason', width: 120, render: () => '业务分组未分类' },
{ title: '期间', dataIndex: 'periods', width: 180 },
{ title: '行数', dataIndex: 'rowCount', width: 75, align: 'right' },
{ title: '总重量 / kg', dataIndex: 'totalWeight', width: 140, align: 'right' },
{ title: '操作', key: 'action', width: 125, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'group', row })}>编辑分类</Button> },
];
return <div className="management-page">
{error && <Alert type="error" showIcon message={error} />}
<section className="panel section-panel">
<div className="resource-toolbar"><strong>业务分组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><Button icon={<ReloadOutlined />} onClick={() => void inventory.refresh()}>刷新</Button></div></div>
<div className="resource-table"><Table size="small" bordered loading={loading} columns={columns} dataSource={items} rowKey={row => JSON.stringify([row.stage, row.department, row.product, row.sourceKey])} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1280 }} /></div>
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={currentPage} pageSize={TABLE_PAGE_SIZE} total={total} onChange={setPage} />}
</section>
</div>;
}
function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
const inventory=useUnclassifiedInventory('projectGroup',onUnauthorized);
const [page,setPage]=useState(1);
const [customerCode,setCustomerCode]=useState<string>();
const [businessGroup,setBusinessGroup]=useState<string>();
const [department,setDepartment]=useState<string>();
const {loading,error}=inventory;
const filtered=inventory.items.filter(row=>(!customerCode||row.customerCode===customerCode)&&(!businessGroup||row.businessGroup===businessGroup)&&(!department||(Array.isArray(row.departments)&&row.departments.includes(department))));
const total=filtered.length,currentPage=Math.min(page,Math.max(1,Math.ceil(total/TABLE_PAGE_SIZE)));
const items=filtered.slice((currentPage-1)*TABLE_PAGE_SIZE,currentPage*TABLE_PAGE_SIZE);
const filterOptions={customerCodes:[...new Set(inventory.all.map(row=>String(row.customerCode)))].sort(),businessGroups:[...new Set(inventory.all.map(row=>String(row.businessGroup)))].sort(),departments:[...new Set(inventory.all.flatMap(row=>Array.isArray(row.departments)?row.departments.map(String):[]))].sort()};
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '客户代码', dataIndex: 'customerCode', key: 'customerCode', fixed: 'left', width: 120, render: toText },
{ title: '业务分组', dataIndex: 'businessGroup', key: 'businessGroup', width: 190, render: toText },
{ title: '产业部', dataIndex: 'departments', key: 'departments', width: 190, render: value => Array.isArray(value) && value.length ? value.join('、') : '—' },
{ title: '映射类型', dataIndex: 'mappingType', key: 'mappingType', width: 120, render: value => ({ PROJECT_GROUP: '项目组', CATEGORY: '业务分组', DEPARTMENT: '产业部', PRODUCT: '产品' }[String(value)] ?? toText(value)) },
{ title: '涉及行数', dataIndex: 'rowCount', key: 'rowCount', align: 'right', width: 110 },
{ title: '涉及总重量', dataIndex: 'totalWeight', key: 'totalWeight', align: 'right', width: 130 },
{ title: '问题期间', key: 'periods', width: 170, render: (_, row) => { const details = row.details && typeof row.details === 'object' ? row.details as Record<string, unknown> : {}; return Array.isArray(details.periods) ? (details.periods as unknown[]).map(toText).join('、') : '—'; } },
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => <Tag color={value === 'OPEN' ? 'orange' : value === 'REVALIDATED' ? 'green' : 'blue'}>{value==='OPEN'?'待处理':toText(value)}</Tag> },
{ title: '操作', key: 'action', width: 120, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'projectGroup', row })}>编辑分类</Button> },
];
return <div className="management-page">
{error && <Alert showIcon type="error" message="映射问题操作失败" description={error} />}
<section className="panel section-panel"><div className="resource-toolbar"><strong>项目组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void inventory.refresh()}>刷新</Button></div></div></div>
<div className="resource-toolbar mapping-issue-filters">
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选客户代码" placeholder="客户代码" value={customerCode} options={filterOptions.customerCodes.map(value => ({ label: value, value }))} onChange={value => { setCustomerCode(value); setPage(1); }} />
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选业务分组" placeholder="业务分组" value={businessGroup} options={filterOptions.businessGroups.map(value => ({ label: value, value }))} onChange={value => { setBusinessGroup(value); setPage(1); }} />
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选产业部" placeholder="产业部" value={department} options={filterOptions.departments.map(value => ({ label: value, value }))} onChange={value => { setDepartment(value); setPage(1); }} />
<Button onClick={() => { setCustomerCode(undefined); setBusinessGroup(undefined); setDepartment(undefined); setPage(1); }}>重置</Button>
</div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1320 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="没有项目组未分类记录" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={currentPage} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
</div>;
}
function MetricDictionaryPanel({ user, onUnauthorized, onEditFormula }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onEditFormula?: (code: string) => void }) {
const { message } = App.useApp();
const { active } = usePageCache();
const [items, setItems] = useState<Record<string, unknown>[]>([]);
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const [dictionaryError, setDictionaryError] = useState('');
const [saving, setSaving] = useState(false);
const savingRef = useRef(false);
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ name: string; aliases: string; description: string; reason: string }>();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const load = useCallback(() => read.run(async () => {
try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); }
catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
const openEditor = (item: Record<string, unknown>) => {
setEditing(item);
form.setFieldsValue({
name: String(item.name || ''),
aliases: Array.isArray(item.aliases) ? item.aliases.map(String).join('\n') : '',
description: readableRuleDescription(item.description), reason: '',
});
};
const save = async () => {
if (!editing || savingRef.current) return; savingRef.current = true;
try {
const values = await form.validateFields();
const code = String(editing.code || '');
if (!code) { message.error('术语缺少服务端编码,不能保存'); return; }
setSaving(true);
await api.updateMetricDictionary(code, {
name: values.name.trim(),
aliases: values.aliases.split(/[\n,,;]/).map(value => value.trim()).filter(Boolean),
description: values.description.trim(),
reason: values.reason.trim(),
expectedRowVersion: Number(editing.rowVersion || 0),
});
message.success('指标说明已保存'); setEditing(null); form.resetFields(); await load();
} catch (value) {
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { savingRef.current = false; setSaving(false); }
};
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '指标', dataIndex: 'name', key: 'name', width: 190 },
{ title: '当前计算公式', key: 'formula', width: 330, render: (_, row) => <div style={{ whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.7 }}>{formulaOnly(currentMetricFormula(row))}</div> },
{ title: '计算口径', dataIndex: 'description', key: 'description', width: 280, render: value => readableValue(readableRuleDescription(value)) },
{ title: '操作', key: 'actions', width: 220, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看说明</Button>{canManage && <><Button type="link" onClick={() => openEditor(row)}>编辑说明</Button>{onEditFormula && <Button type="link" onClick={() => onEditFormula(String(row.code))}>修改公式</Button>}</>}</span> },
];
useMaintenanceRefresh(load);
return <CompactManagementTables.Provider value={true}><section className="panel section-panel completion-tools metric-explanation-panel">
<div className="completion-panel-heading"><div><strong>当前生效指标</strong></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
{loading && !loaded ? <div className="loading-panel"><Spin />读取指标说明…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标说明" /> : null}
<Modal className="management-modal" open={Boolean(editing)} title={`编辑说明 · ${String(editing?.name || '')}`} okText="保存说明" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
<Form form={form} layout="vertical">
<Form.Item name="name" label="展示名称" rules={[{ required: true, whitespace: true, message: '请填写展示名称' }]}><Input maxLength={160} /></Form.Item>
<Form.Item name="aliases" label="别名" extra="每行一个,也可用逗号分隔"><Input.TextArea rows={4} maxLength={1000} /></Form.Item>
<Form.Item name="description" label="指标说明"><Input.TextArea rows={3} maxLength={1000} /></Form.Item>
<Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true, message: '请填写修改原因' }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item>
</Form>
<Alert showIcon type="info" message="当前生效公式" description={editing ? currentMetricFormula(editing) : undefined} />
</Modal>
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标说明 · ${String(inspecting?.name || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(readableRuleDescription(inspecting.description))}</dd><dt>单位</dt><dd>{inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}</dd><dt>适用维度</dt><dd><BusinessValue value={inspecting.dimensions} field="dimensions" /></dd><dt>当前生效公式</dt><dd>{currentMetricFormula(inspecting)}</dd><dt>状态</dt><dd><BusinessValue value={inspecting.enabled} /></dd></dl>}
</Drawer>
</section></CompactManagementTables.Provider>;
}
function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { items: Record<string, unknown>[]; importOnly: boolean; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) {
const { message } = App.useApp();
const [selected, setSelected] = useState<Record<string, unknown> | null>(null);
const [issuesRunId, setIssuesRunId] = useState('');
const [busyId, setBusyId] = useState('');
const actionLock = useRef(false);
const canRetry = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const canCancel = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role));
const runIdOf = (row: Record<string, unknown>) => {
const payload = row.payload && typeof row.payload === 'object' ? row.payload as Record<string, unknown> : {};
return String(row.importRunId || payload.importRunId || '');
};
const retry = async (row: Record<string, unknown>) => {
const id = String(row.id || ''); if (!id) return;
if (actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
const releases = await api.releases();
const result = await api.retryTask(id, { idempotencyKey: crypto.randomUUID(), expectedCurrentReleaseId: releases.currentReleaseId ?? null });
const body = result && typeof result === 'object' ? result as Record<string, unknown> : {};
const run = body.run && typeof body.run === 'object' ? body.run as Record<string, unknown> : {};
if (String(run.status).toUpperCase() === 'FAILED') message.error(`重试后仍失败:${toText(run.errorMessage || run.errorCode)}`);
else message.success(`任务重试完成:${toText(run.status || '已更新')}`);
onRefresh();
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
finally { actionLock.current = false; setBusyId(''); }
};
const cancel = async (row: Record<string, unknown>) => {
const id = String(row.id || ''); if (!id) return;
if (actionLock.current) return; actionLock.current = true;
setBusyId(id);
try {
await api.cancelTask(id, { expectedStatus: String(row.status || '') });
message.success('已取消排队任务'); onRefresh();
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
finally { actionLock.current = false; setBusyId(''); }
};
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '任务 ID', dataIndex: 'id', key: 'id', fixed: 'left', width: 220, ellipsis: true },
{ title: '任务类型', dataIndex: 'type', key: 'type', width: 130 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') || String(value).toUpperCase() === 'ERROR' ? 'red' : String(value).toUpperCase() === 'SUCCEEDED' || String(value).toUpperCase() === 'COMPLETED' ? 'green' : 'blue'}>{importOnly ? importState(value) : toText(value)}</Tag> },
{ title: '处理阶段', dataIndex: 'stage', key: 'stage', width: 150 },
{ title: importOnly ? '进度' : '进度', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
{ title: '已处理 / 总数', key: 'processed', width: 140, align: 'right', render: (_, row) => `${toText(row.processed)} / ${toText(row.total)}` },
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{value==='OPEN'?'待处理':toText(value)}</Tag> : '—' },
{ title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? <span className="task-error">{toText(value)}</span> : '—' },
{ title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
<Button type="link" onClick={() => setSelected(row)}>详情</Button>
{importOnly && runIdOf(row) && <Button type="link" onClick={() => setIssuesRunId(runIdOf(row))}>校验问题</Button>}
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
</span> },
];
return <>
{items.length ? <div className="resource-table"><Table size="small" bordered columns={importOnly ? columns.filter(column => ['createdAt', 'status', 'progress', 'processed', 'errorMessage', 'detail'].includes(String(column.key))) : columns} dataSource={items} rowKey={row => String(row.id ?? JSON.stringify(row))} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: importOnly ? 1000 : 1600 }} />
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无后台任务" />}
<Drawer className="management-drawer" open={Boolean(selected)} title="任务详情" width={Math.min(760, window.innerWidth)} onClose={() => setSelected(null)}>
{selected && <><div className="task-detail-summary"><strong>{importOnly ? importState(selected.status) : `${toText(selected.type)} · ${toText(selected.status)}`}</strong>{!importOnly && <span>{toText(selected.stage)} · {toText(selected.id)}</span>}{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && <Alert showIcon type="error" message={toText(selected.errorCode || '任务错误')} description={toText(selected.errorMessage)} />}</div>{importOnly ? <dl className="nc-form-grid"><dt>处理状态</dt><dd>{importState(selected.status)}</dd><dt>处理行数</dt><dd>{toText(selected.processed)} / {toText(selected.total)}</dd><dt>创建时间</dt><dd>{toText(selected.createdAt)}</dd></dl> : <pre className="json-result">{publicJson(selected)}</pre>}</>}
</Drawer>
<ImportIssuesDrawer runId={issuesRunId} onClose={() => setIssuesRunId('')} onUnauthorized={onUnauthorized} />
</>;
}
function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
const { message, modal } = App.useApp();
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
const [renameTitle, setRenameTitle] = useState('');
const [renaming, setRenaming] = useState(false);
const sessionMutationLock = useRef(false);
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
const activePage = useRef(active); activePage.current = active;
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
const initialSessionId = initialParams.get('sessionId') || '';
const initialTurnId = initialParams.get('turnId') || '';
const pendingTurnLink = useRef(initialTurnId);
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
const [query, setQuery] = useState('');
const [sessionId, setSessionId] = useState(initialSessionId);
const [sessionReadOnly, setSessionReadOnly] = useState(false);
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
const [sessionsLoaded, setSessionsLoaded] = useState(false);
const [sessionsLoading, setSessionsLoading] = useState(true);
const [sessionsError, setSessionsError] = useState('');
const showSessionsLoading = useDelayedIndicator(sessionsLoading && active, 150);
const sessionReadRequest = useRef<Promise<Record<string, unknown>[] | undefined> | null>(null);
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
const [options, setOptions] = useState<OptionsResponse | null>(null);
const [historyLoading, setHistoryLoading] = useState(true);
const showHistoryLoading = useDelayedIndicator(historyLoading && active, 150);
const optionsRead = useDelayedBusy();
const [optionsError, setOptionsError] = useState('');
const optionsRequestStarted = useRef(false);
const restoreStarted = useRef(false);
const [busy, setBusy] = useState(false);
const [queuedFollowup, setQueuedFollowup] = useState('');
const [stopping, setStopping] = useState(false);
const cancellationRequest = useRef<{ generation: number } | null>(null);
const [error, setError] = useState('');
const [retryQuestion, setRetryQuestion] = useState('');
const [lastTurn, setLastTurn] = useState<Record<string, unknown> | null>(null);
const [activeTurnId, setActiveTurnId] = useState('');
const streamController = useRef<AbortController | null>(null);
const eventCursors = useRef<Record<string, string>>({});
const mounted = useRef(true);
const userSelectionMade = useRef(false);
const navigationGeneration = useRef(0);
const subscriptionGeneration = useRef(0);
const submissionAttempt = useRef<AnalysisSubmission | null>(null);
const [releaseId, setReleaseId] = useState<string>();
const [sourceResultRef, setSourceResultRef] = useState<AnalysisResultRef>();
const conversation = useRef<HTMLDivElement>(null);
const followOutput = useRef(true);
const explicitlyFollowing = useRef(false);
const userScrollIntent = useRef<AnalysisScrollIntent>(null);
const userScrollIntentTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const scrollbarPointerActive = useRef(false);
const touchPosition = useRef<number | null>(null);
const followRequest = useRef<string | null>(null);
const seenConclusion = useRef<string | null>(null);
const previousScrollTop = useRef(0);
const readingPosition = useRef(0);
const [hasNewContent, setHasNewContent] = useState(false);
const clearUserScrollIntent = () => {
userScrollIntent.current = null;
if (userScrollIntentTimer.current !== null) {
clearTimeout(userScrollIntentTimer.current);
userScrollIntentTimer.current = null;
}
};
const markUserScrollIntent = (intent: Exclude<AnalysisScrollIntent, null>) => {
clearUserScrollIntent();
userScrollIntent.current = intent;
userScrollIntentTimer.current = setTimeout(clearUserScrollIntent, 100);
};
const handleUserScrollIntent = (element: HTMLDivElement, intent: Exclude<AnalysisScrollIntent, null>) => {
if (intent === 'up') {
if (element.scrollTop <= 0) return;
clearUserScrollIntent();
explicitlyFollowing.current = false;
followOutput.current = analysisScrollFollows(
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current, intent);
return;
}
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
if (distanceFromBottom <= 24) {
clearUserScrollIntent();
explicitlyFollowing.current = true;
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
setHasNewContent(false);
} else markUserScrollIntent(intent);
};
const scrollToLatest = (element: HTMLDivElement) => {
const latest = element.querySelector<HTMLElement>('.analysis-turn:last-child');
const finished = latest && ANALYSIS_FINAL_STATUSES.has(latest.dataset.analysisStatus || '');
const bounds = element.getBoundingClientRect();
// DOM rectangles include the workspace zoom; scrollTop uses layout pixels.
const renderedScale = element.offsetHeight ? bounds.height / element.offsetHeight : 1;
const scale = renderedScale > 0 ? renderedScale : 1;
const pauseAtConclusion = Boolean(finished && !explicitlyFollowing.current);
element.scrollTop = pauseAtConclusion && latest
? element.scrollTop + (latest.getBoundingClientRect().top - bounds.top) / scale - element.clientTop
: element.scrollHeight;
previousScrollTop.current = element.scrollTop;
readingPosition.current = element.scrollTop;
// Once the conclusion is visible, preserve the reader's place as charts load.
if (finished) {
seenConclusion.current = latest.dataset.analysisTurnId || null;
setHasNewContent(false);
if (pauseAtConclusion) followOutput.current = false;
}
};
useEffect(() => {
if (!busy) { cancellationRequest.current = null; setStopping(false); }
}, [busy]);
useEffect(() => {
const element = conversation.current;
if (active && element) { if (followOutput.current) scrollToLatest(element); else element.scrollTop = readingPosition.current; }
}, [active]);
useEffect(() => {
followOutput.current = true; explicitlyFollowing.current = false; clearUserScrollIntent();
seenConclusion.current = null; previousScrollTop.current = 0; setHasNewContent(false);
}, [sessionId]);
useEffect(() => () => clearUserScrollIntent(), []);
useEffect(() => {
const element = conversation.current;
if (!element || !active) return;
let frame = 0;
const resize = new ResizeObserver(() => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
if (!activePage.current) return;
if (followOutput.current) {
scrollToLatest(element);
}
});
});
const observe = () => { resize.disconnect(); [...element.children].forEach(child => resize.observe(child)); };
observe();
const mutation = new MutationObserver(observe);
mutation.observe(element, { childList: true });
return () => { cancelAnimationFrame(frame); resize.disconnect(); mutation.disconnect(); };
}, [active, sessionId]);
useEffect(() => {
if (analysisFollowRequestReady(followRequest.current, lastTurn)) {
followOutput.current = true; explicitlyFollowing.current = false; followRequest.current = null;
seenConclusion.current = null; setHasNewContent(false);
}
const element = conversation.current;
if (active && element && followOutput.current) {
scrollToLatest(element);
setHasNewContent(false);
} else if (active && element && seenConclusion.current && seenConclusion.current === String(lastTurn?.id || '')) {
// Final detail/history refreshes are not unread output after we showed it.
setHasNewContent(false);
} else if (active && element && busy) setHasNewContent(true);
}, [lastTurn, busy, turns, sessionId, active]);
const loadSessions = async () => {
// 隐藏时的定时刷新由 useVisiblePolling 暂停;首次恢复不能因后台打开标签页而丢失。
if (!mounted.current || !active) return;
if (sessionReadRequest.current) return sessionReadRequest.current;
setSessionsLoading(true);
const request = (async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setSessionsError(''); } return items; }
catch (value) { if (mounted.current && !onUnauthorized(value)) setSessionsError(apiMessage(value)); }
finally { if (mounted.current) setSessionsLoading(false); }
})();
sessionReadRequest.current = request;
try { return await request; }
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
};
const retrySessions = async () => {
const generation = navigationGeneration.current;
setHistoryLoading(true);
const listRequest = loadSessions();
try {
const focusTurnId = pendingTurnLink.current;
let target = sessionId;
if (!target && focusTurnId) {
const turn = await api.analysisTurn(focusTurnId);
if (!mounted.current || generation !== navigationGeneration.current) return;
target = String(turn.sessionId || '');
if (!target) throw new Error('服务端未返回目标轮次所属会话');
}
if (target) await openSession(target, focusTurnId || undefined);
else {
const items = await listRequest;
const id = items && !initialLink.present ? defaultAnalysisSession(user.id, items) : '';
if (mounted.current && generation === navigationGeneration.current && id) await openSession(id);
}
} catch (value) { if (mounted.current && generation === navigationGeneration.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && generation === navigationGeneration.current) setHistoryLoading(false); }
};
useEffect(() => {
if (!active || !initialLink.present || initialSessionId || initialTurnId || optionsRequestStarted.current) return;
optionsRequestStarted.current = true;
void optionsRead.run(async () => {
try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } }
catch (value) { if (mounted.current && !onUnauthorized(value)) setOptionsError(apiMessage(value)); }
});
}, [active, onUnauthorized, optionsRead.run]);
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
useVisiblePolling(async () => { await loadSessions(); }, 5000, active && hasBackgroundTurns);
const wasActive = useRef(active);
useEffect(() => {
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
wasActive.current = active;
}, [active, hasBackgroundTurns]);
useEffect(() => {
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
const generation = navigationGeneration.current;
const selection = beginAnalysisSelection(user.id);
if (initialLink.error || !initialLink.query) {
setError(initialLink.error || '分析链接缺少有效查询条件');
setHistoryLoading(false);
return;
}
const linkedQuery = initialLink.query;
const linkedRelease = initialLink.resultRef?.releaseId || linkedQuery.releaseId;
const allowedReleaseIds = new Set((options.releases || []).map(item => item.id));
if (linkedRelease && !allowedReleaseIds.has(linkedRelease)) {
setError('链接对应的数据当前不可访问,请从当前查询结果重新打开分析。');
setHistoryLoading(false);
return;
}
setReleaseId(linkedRelease);
setSourceResultRef(initialLink.resultRef);
if (initialLink.resultRef) setQuery('请解释已绑定的阶段 TOP 排名,并说明可核查的来源依据。');
const context: Record<string, unknown> = {
year: linkedQuery.year,
...(linkedQuery.extraFilters ? { extraFilters: linkedQuery.extraFilters } : {}),
...(linkedQuery.month !== undefined ? { month: linkedQuery.month } : {}),
...(linkedQuery.quarter !== undefined ? { quarter: linkedQuery.quarter } : {}),
...(linkedQuery.monthStart !== undefined ? { monthStart: linkedQuery.monthStart } : {}),
...(linkedQuery.monthEnd !== undefined ? { monthEnd: linkedQuery.monthEnd } : {}),
view: linkedQuery.view,
...(linkedQuery.department ? { department: linkedQuery.department } : {}),
...(linkedQuery.group ? { group: linkedQuery.group } : {}),
...(linkedQuery.product ? { product: linkedQuery.product } : {}),
...(linkedQuery.projectGroup ? { projectGroup: linkedQuery.projectGroup } : {}),
...(linkedRelease ? { releaseId: linkedRelease } : {}),
includeUnassigned: linkedQuery.includeUnassigned === true,
...(initialLink.resultRef ? { resultRef: initialLink.resultRef } : {}),
};
setSessionContext(context);
const requestKey = JSON.stringify({ userId: user.id, query: linkedQuery, resultRef: initialLink.resultRef || null });
const pageWindow = window as AnalysisPageWindow;
let linkedSessionRequest = pageWindow.__qualityAnalysisLinkedSessionRequest;
if (!linkedSessionRequest || linkedSessionRequest.key !== requestKey) {
linkedSessionRequest = {
key: requestKey,
promise: api.createAnalysisSession({ ...(linkedRelease ? { releaseId: linkedRelease } : {}), context }),
};
pageWindow.__qualityAnalysisLinkedSessionRequest = linkedSessionRequest;
}
let alive = true;
setHistoryLoading(true);
linkedSessionRequest.promise
.then(created => {
if (!alive || !mounted.current || generation !== navigationGeneration.current) return;
const id = String(created.session.id || '');
if (!id) throw new Error('服务端未返回分析会话编号');
setSessionId(id);
rememberPendingAnalysisSession(user.id, id, selection);
writeAnalysisLocation(id);
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
void loadSessions();
})
.catch(value => {
if (!alive || !mounted.current || generation !== navigationGeneration.current) return;
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
if (!onUnauthorized(value)) setError(apiMessage(value));
})
.finally(() => {
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
if (alive && mounted.current && generation === navigationGeneration.current) setHistoryLoading(false);
});
return () => { alive = false; };
}, [options]);
const writeAnalysisLocation = (selectedSessionId?: string, selectedTurnId?: string) => {
if (!mounted.current) return;
if (selectedSessionId) rememberAnalysisSession(user.id, selectedSessionId);
if (!activePage.current) return;
const url = new URL(window.location.href);
url.searchParams.set('page', 'analysis');
if (selectedSessionId) url.searchParams.set('sessionId', selectedSessionId); else url.searchParams.delete('sessionId');
if (selectedTurnId) url.searchParams.set('turnId', selectedTurnId); else url.searchParams.delete('turnId');
url.searchParams.delete('context');
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
onLocationChange(url.search);
};
useEffect(() => {
if (active && !historyLoading) writeAnalysisLocation(sessionId || undefined, activeTurnId || undefined);
}, [active, historyLoading, sessionId, activeTurnId]);
const refreshSeen = useRef(refreshKey);
useEffect(() => {
if (!active || refreshSeen.current === refreshKey) return;
refreshSeen.current = refreshKey; void loadSessions();
if (sessionId && !busy) void openSession(sessionId);
}, [active, refreshKey]);
const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => {
if (!focusTurnId) pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
const generation = ++navigationGeneration.current;
setQueuedFollowup('');
cancellationRequest.current = null; setStopping(false); followRequest.current = null;
submissionAttempt.current = null;
subscriptionGeneration.current += 1;
streamController.current?.abort(); streamController.current = null;
setBusy(false); setActiveTurnId(''); setHistoryLoading(true);
const current = () => mounted.current && generation === navigationGeneration.current;
try {
const [history, turnHistory] = await Promise.all([api.analysisSession(id), api.analysisSessionTurns(id)]);
if (!current()) return false;
const historyTurns = restoredAnalysisTurns(history, turnHistory);
const active = activeAnalysisTurn(historyTurns);
const selectedTurnId = focusTurnId || (active ? String(active.id || '') : pendingClarificationTurnId(historyTurns));
setSessionId(id);
setSessionReadOnly(history.readOnly === true);
setTurns(historyTurns.filter(turn => !selectedTurnId || String(turn.id || '') !== selectedTurnId));
writeAnalysisLocation(id, selectedTurnId || undefined);
setLastTurn(null); setError(''); setRetryQuestion('');
const context = history.context && typeof history.context === 'object' ? history.context as Record<string, unknown> : {};
const restoredContext = { ...context };
const fixedRelease = typeof history.releaseId === 'string' ? history.releaseId : typeof context.releaseId === 'string' ? context.releaseId : '';
if (fixedRelease) restoredContext.releaseId = fixedRelease;
setSessionContext(Object.keys(restoredContext).length ? restoredContext : null);
setReleaseId(typeof history.releaseId === 'string' ? history.releaseId : typeof context.releaseId === 'string' ? context.releaseId : undefined);
const resultRef = context.resultRef && typeof context.resultRef === 'object' ? context.resultRef as Record<string, unknown> : {};
setSourceResultRef(resultRef.kind === 'TOP' && typeof resultRef.resultId === 'string' && typeof resultRef.releaseId === 'string' && resultRef.releaseId === String(history.releaseId || context.releaseId || '')
? { kind: 'TOP', resultId: resultRef.resultId, releaseId: resultRef.releaseId }
: undefined);
if (selectedTurnId) {
const detail = await api.analysisTurn(selectedTurnId);
if (!current()) return false;
if (String(detail.sessionId || '') !== id) throw new Error('分析轮次与会话链接不匹配');
const restored = { ...historyTurns.find(item => item.id === selectedTurnId), ...detail };
setLastTurn(restored);
if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id);
}
pendingTurnLink.current = '';
return true;
} catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; }
finally { if (current()) setHistoryLoading(false); }
};
const newSession = () => {
pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
setQueuedFollowup('');
setBusy(false); setActiveTurnId('');
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
cancellationRequest.current = null; setStopping(false); followRequest.current = null;
submissionAttempt.current = null;
streamController.current?.abort(); streamController.current = null;
rememberAnalysisSession(user.id, '');
setHistoryLoading(false);
setSessionReadOnly(false);
setSessionId(''); setTurns([]); setLastTurn(null); setQuery(''); setError(''); setRetryQuestion('');
setSessionContext(null);
setReleaseId(undefined);
setSourceResultRef(undefined);
writeAnalysisLocation();
};
const deleteSession = async (id: string) => {
if (sessionMutationLock.current) return; sessionMutationLock.current = true;
const generation = navigationGeneration.current;
try {
await api.deleteAnalysisSession(id);
if (mounted.current && navigationGeneration.current === generation && sessionId === id) newSession();
await loadSessions();
message.success('会话已删除');
} catch (value) {
if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除会话失败');
} finally { sessionMutationLock.current = false; }
};
const renameSession = async () => {
if (!renameTarget || !renameTitle.trim() || sessionMutationLock.current) return; sessionMutationLock.current = true;
setRenaming(true);
try {
await api.renameAnalysisSession(String(renameTarget.id), renameTitle.trim());
setRenameTarget(null); await loadSessions(); message.success('会话已重命名');
} catch (value) { if (!onUnauthorized(value)) message.error(apiMessage(value)); }
finally { sessionMutationLock.current = false; setRenaming(false); }
};
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
if (!mounted.current) return;
streamController.current?.abort();
const generation = ++subscriptionGeneration.current;
const current = () => mounted.current && generation === subscriptionGeneration.current;
const linkedSessionId = sessionOverride || sessionId;
if (linkedSessionId) writeAnalysisLocation(linkedSessionId, id);
setActiveTurnId(id); setBusy(true);
const controller = new AbortController(); streamController.current = controller;
let streamedResult: Record<string, unknown> = {};
let terminalEventStatus = '';
setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' }));
let timingReadInFlight = false, timingReadAgain = false, startConfirmed = false;
const refreshTiming = async (): Promise<void> => {
if (!linkedSessionId || !current() || startConfirmed) return;
if (timingReadInFlight) { timingReadAgain = true; return; }
timingReadInFlight = true;
try {
const history = await api.analysisSessionTurns(linkedSessionId);
if (!current()) return;
const timing = collectionItems(history).find(item => item.id === id);
if (!timing) return;
startConfirmed = typeof timing.startedAt === 'string' && Number.isFinite(Date.parse(timing.startedAt));
setLastTurn(previous => previous?.id !== id ? previous : { ...previous,
...(typeof timing.createdAt === 'string' ? { createdAt: timing.createdAt } : {}),
...(startConfirmed ? { startedAt: timing.startedAt } : {}),
});
} catch (value) { if (current()) onUnauthorized(value); }
finally {
timingReadInFlight = false;
if (timingReadAgain && !startConfirmed && current()) { timingReadAgain = false; void refreshTiming(); }
}
};
void refreshTiming();
try {
let detail: Record<string, unknown> = {};
let reconnectAttempt = 0;
while (!controller.signal.aborted) {
let receivedEvents = 0;
try {
await api.analysisTurnEvents(id, {
signal: controller.signal,
lastEventId: eventCursors.current[id],
onEvent: event => {
if (!current()) return;
receivedEvents += 1;
if (!acceptAnalysisEvent(event.id, eventCursors.current[id])) return;
if (event.id) eventCursors.current[id] = event.id;
const data = event.data && typeof event.data === 'object' ? event.data as Record<string, unknown> : {};
const messageText = typeof data.message === 'string' ? data.message : event.event === 'answer' ? '正在整理分析结论…' : '正在分析…';
const eventResult = isObjectRecord(data.result) ? data.result : undefined;
if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
const eventStatus = String(data.status || '').toUpperCase();
const turnEventStatus = analysisStreamStatus(undefined, event.event, data.status);
if (ANALYSIS_FINAL_STATUSES.has(turnEventStatus)) terminalEventStatus = turnEventStatus;
setLastTurn(previous => {
const prior = previous || {};
if (prior.id === id && ANALYSIS_FINAL_STATUSES.has(String(prior.status || '').toUpperCase()) && !ANALYSIS_FINAL_STATUSES.has(eventStatus)) return prior;
const priorResult = isObjectRecord(prior.result) ? prior.result : {};
const status = analysisStreamStatus(prior.status, event.event, data.status);
return {
...prior,
id,
question,
status,
latestEvent: event.event,
eventStep: data.step,
...(Array.isArray(data.steps) ? { steps: data.steps } : {}),
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
progressMessage: typeof data.message === 'string' ? messageText : prior.progressMessage,
...(data.thinkingDelta ? { modelThinking: mergeModelThinking(modelThinkingEntries(prior), data.thinkingDelta) } : {}),
...(Array.isArray(data.timeline) ? { timeline: data.timeline } : {}),
plan: data.plan || prior.plan,
...(eventResult ? { result: { ...priorResult, ...eventResult } } : {}),
};
});
// The SSE request can otherwise remain open after its terminal event.
// Closing this subscription does not cancel the analysis itself.
if (terminalEventStatus) controller.abort();
else if (eventStatus === 'RUNNING' || eventName.startsWith('TOOL_')) void refreshTiming();
},
});
} catch (streamError) {
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
if (streamError instanceof ApiError && [401, 403, 404].includes(streamError.status)) throw streamError;
}
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
// A normal SSE close is not necessarily turn completion: the server
// rotates its event stream while long-running analyses continue.
for (const delayMs of [0, 250, 500, 750, 1000, 1000, 1200]) {
if (delayMs) await new Promise(resolve => setTimeout(resolve, delayMs));
try { detail = await api.analysisTurn(id); }
catch (readError) {
if (!current()) return;
if (readError instanceof ApiError && [401, 403, 404].includes(readError.status)) throw readError;
}
if (!current()) return;
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) break;
if (controller.signal.aborted && !terminalEventStatus) break;
}
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase()) || terminalEventStatus || controller.signal.aborted) break;
reconnectAttempt = receivedEvents ? 0 : Math.min(reconnectAttempt + 1, 4);
const reconnectDelay = Math.min(500 * (2 ** reconnectAttempt), 8000);
await new Promise(resolve => setTimeout(resolve, reconnectDelay));
}
if (!current()) return;
const settledTurn = settledAnalysisTurn(id, question, detail, streamedResult, terminalEventStatus);
setLastTurn(previous => ({ ...settledTurn, ...(previous?.id === id && previous._uiFollowKey ? { _uiFollowKey: previous._uiFollowKey } : {}) }));
if (ANALYSIS_FINAL_STATUSES.has(String(settledTurn.status || '').toUpperCase())) {
setRetryQuestion('');
const parentSessionId = sessionOverride || sessionId;
if (parentSessionId) {
try {
const [savedHistory, savedMetadata] = await Promise.all([api.analysisSession(parentSessionId), api.analysisSessionTurns(parentSessionId)]);
if (!current()) return;
const historyTurns = restoredAnalysisTurns(savedHistory, savedMetadata);
setTurns(historyTurns.filter(item => String(item.id || '') !== id));
} catch (historyError) { if (current() && !onUnauthorized(historyError)) setError(apiMessage(historyError)); }
await loadSessions();
}
}
} catch (value) {
if (current() && !(value instanceof DOMException && value.name === 'AbortError')) {
if (!onUnauthorized(value)) setError(apiMessage(value));
try { const detail = await api.analysisTurn(id); if (current()) setLastTurn({ ...detail, id, question }); } catch (refreshError) { if (current() && !onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
}
} finally {
if (current() && streamController.current === controller) {
streamController.current = null; setBusy(false); setActiveTurnId('');
}
}
};
useEffect(() => {
if (!active || restoreStarted.current) return;
restoreStarted.current = true;
mounted.current = true;
const restore = async () => {
const requestedAt = navigationGeneration.current;
setHistoryLoading(true);
try {
const listRequest = loadSessions();
let linkedSession = initialSessionId;
if (initialTurnId) {
const linkedTurn = await api.analysisTurn(initialTurnId);
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
const turnSession = String(linkedTurn.sessionId || '');
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
linkedSession ||= turnSession;
}
if (!linkedSession && !initialLink.present) {
const items = await listRequest;
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
if (items) linkedSession = defaultAnalysisSession(user.id, items);
}
if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
} catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
};
void restore();
}, [active]);
useEffect(() => {
mounted.current = true;
return () => {
mounted.current = false;
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
// Unsubscribe from updates only. The accepted server task continues independently.
streamController.current?.abort(); streamController.current = null;
};
}, []);
const cancelAcceptedTurn = async (id: string, generation: number, question?: string): Promise<boolean> => {
const attempt = submissionAttempt.current;
const subscription = subscriptionGeneration.current;
const current = () => mounted.current && generation === navigationGeneration.current
&& subscription === subscriptionGeneration.current && submissionAttempt.current === attempt;
try {
await api.cancelAnalysisTurn(id, '用户请求停止');
if (!current()) return false;
const detail = await api.analysisTurn(id);
if (current()) {
setLastTurn(previous => ({ ...detail, id, question: question ?? previous?.question, ...(previous?._uiFollowKey ? { _uiFollowKey: previous._uiFollowKey } : {}) }));
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) {
subscriptionGeneration.current += 1;
streamController.current?.abort(); streamController.current = null;
if (attempt) attempt.inFlight = false;
submissionAttempt.current = null;
setBusy(false); setActiveTurnId('');
void loadSessions();
return true;
}
}
} catch (value) {
if (current()) { cancellationRequest.current = null; setStopping(false); if (!onUnauthorized(value)) setError(apiMessage(value)); }
}
return false;
};
const cancelTurn = async () => {
const generation = navigationGeneration.current;
if (cancellationRequest.current?.generation === generation) return;
cancellationRequest.current = { generation };
setStopping(true);
if (queuedFollowup) { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }
const attempt = submissionAttempt.current;
const pending = requestSubmissionCancellation(attempt, generation);
if (pending) {
// Creating/retrying a turn can still be in transit. Remember the intent
// and cancel the accepted turn, rather than cancelling an old retry state.
if (!attempt?.acceptedTurnId) return;
}
const id = pending ? attempt!.acceptedTurnId : activeTurnId;
if (id) await cancelAcceptedTurn(id, generation, pending ? attempt?.question : undefined);
else if (!pending) { cancellationRequest.current = null; setStopping(false); }
};
const retryTurn = async (turn: Record<string, unknown>) => {
if (sessionReadOnly || busy || historyLoading || submissionAttempt.current?.inFlight) return;
const id = String(turn.id || '');
const status = String(turn.status || '').toUpperCase();
if (!id || !['FAILED', 'CANCELLED', 'PARTIAL'].includes(status)) return;
const selection = beginAnalysisSelection(user.id);
const generation = navigationGeneration.current;
const question = typeof turn.question === 'string' ? turn.question : '';
const targetSessionId = String(turn.sessionId || sessionId || '');
const attempt = beginAnalysisSubmission(null, { sessionId: targetSessionId, question, generation });
submissionAttempt.current = attempt;
followRequest.current = attempt.idempotencyKey;
followOutput.current = true;
explicitlyFollowing.current = false;
const submittedAt = new Date().toISOString();
setLastTurn({ id, sessionId: targetSessionId, question, status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
setError(''); setBusy(true); setActiveTurnId(id);
try {
const response = await api.retryAnalysisTurn(id);
const retried = response.turn;
if (!current()) { rememberPendingAnalysisSession(user.id, String(retried.sessionId || targetSessionId), selection); return; }
const retryId = String(retried.id || id);
const retrySessionId = String(retried.sessionId || targetSessionId);
if (!retrySessionId) throw new Error('无法确定原分析会话,已停止重试。');
attempt.acceptedTurnId = retryId;
setActiveTurnId(retryId);
setSessionId(retrySessionId);
setTurns(previous => previous.filter(item => String(item.id || '') !== id));
if (attempt.cancelRequested && await cancelAcceptedTurn(retryId, generation, question)) return;
if (!current()) return;
const retriedDetail = await api.analysisTurn(retryId);
if (!current()) return;
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(retrySessionId, retryId);
void loadSessions();
if (!current()) return;
setBusy(false);
if (current()) await followTurn(retryId, question, retrySessionId);
} catch (value) {
if (!current()) return;
if (!onUnauthorized(value)) setError(apiMessage(value));
try {
const detail = await api.analysisTurn(id);
if (!current()) return;
setLastTurn({ ...turn, ...detail, id, question, sessionId: targetSessionId });
} catch (refreshError) { if (!onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
setBusy(false); setActiveTurnId('');
} finally {
attempt.inFlight = false;
if (submissionAttempt.current === attempt) submissionAttempt.current = null;
}
};
const submit = async (question = query) => {
if (!question.trim()) return;
if (sessionReadOnly || busy || historyLoading || submissionAttempt.current?.inFlight) return;
followOutput.current = true;
explicitlyFollowing.current = false;
const selection = beginAnalysisSelection(user.id);
rememberAnalysisSession(user.id, '');
const generation = navigationGeneration.current;
const context = sessionContext
? { ...sessionContext, ...(releaseId ? { releaseId } : {}), ...(sourceResultRef ? { resultRef: sourceResultRef } : {}) }
: releaseId || sourceResultRef
? { ...(releaseId ? { releaseId } : {}), ...(sourceResultRef ? { resultRef: sourceResultRef } : {}) }
: undefined;
const attempt = beginAnalysisSubmission(submissionAttempt.current, { sessionId, question: question.trim(), context, generation });
submissionAttempt.current = attempt;
followRequest.current = attempt.idempotencyKey;
const current = () => mounted.current && generation === navigationGeneration.current && submissionAttempt.current === attempt;
setBusy(true);
setError('');
setRetryQuestion(question.trim());
if (typeof lastTurn?.id === 'string' && lastTurn.id) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
const submittedAt = new Date().toISOString();
setLastTurn({ question: question.trim(), status: 'SUBMITTING', _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
setQuery('');
try {
let selectedSessionId = sessionId;
if (!selectedSessionId) {
const created = await api.createAnalysisSession({ title: question.trim().slice(0, 60), ...(releaseId ? { releaseId } : {}), ...(context ? { context } : {}) });
selectedSessionId = String(created.session.id || '');
if (!selectedSessionId) throw new Error('服务端未返回会话编号');
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
if (current()) setSessionId(selectedSessionId);
}
attempt.sessionId = selectedSessionId;
if (!current()) return;
if (attempt.cancelRequested && !attempt.turnRequestStarted) {
setLastTurn({ question: question.trim(), status: 'CANCELLED', _uiFollowKey: attempt.idempotencyKey });
setRetryQuestion(''); setBusy(false);
void loadSessions();
return;
}
attempt.turnRequestStarted = true;
const started = await api.startAnalysisTurn(selectedSessionId, { question: question.trim(), ...(context ? { context } : {}), idempotencyKey: attempt.idempotencyKey });
const turn = started.turn;
const turnId = String(turn.id || '');
if (!turnId) throw new Error('服务端未返回分析任务编号');
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
if (!current()) return;
attempt.uncertain = false;
attempt.acceptedTurnId = turnId;
setActiveTurnId(turnId);
setLastTurn({ ...turn, status: turn.status || 'QUEUED', id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiSubmittedAt: submittedAt, _uiFollowKey: attempt.idempotencyKey });
writeAnalysisLocation(selectedSessionId, turnId);
if (attempt.cancelRequested && await cancelAcceptedTurn(turnId, generation, question.trim())) return;
void loadSessions();
if (!current()) return;
setBusy(false);
await followTurn(turnId, question.trim(), selectedSessionId);
}
catch (value) {
attempt.uncertain = attempt.turnRequestStarted && !attempt.acceptedTurnId && submissionOutcomeUnknown(value);
if (current()) {
if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); }
if (!attempt.acceptedTurnId) setLastTurn({ question: question.trim(), _uiFollowKey: attempt.idempotencyKey, submissionNotice: attempt.uncertain
? '提交结果暂未确认,请重试上一问恢复原任务。'
: '本次提交未成功,请检查错误提示后重试。' });
setBusy(false);
}
} finally {
attempt.inFlight = false;
if (submissionAttempt.current === attempt && !attempt.uncertain) submissionAttempt.current = null;
}
};
const queueFollowup = () => {
if (sessionReadOnly || !busy || historyLoading || queuedFollowup || cancellationRequest.current || !query.trim()) return;
setQueuedFollowup(query.trim());
setQuery('');
message.info('当前分析结束后发送追问');
};
const sendQueuedFollowup = () => {
if (!queuedFollowup || busy || historyLoading ||
!ANALYSIS_FINAL_STATUSES.has(String(lastTurn?.status || '').toUpperCase())) return;
const question = queuedFollowup;
setQueuedFollowup('');
return submit(question);
};
useEffect(() => { void sendQueuedFollowup(); }, [busy, historyLoading, lastTurn?.status, queuedFollowup]);
const composer = analysisComposerState(busy, stopping, historyLoading, query, queuedFollowup);
return <div className="management-page analysis-simple-page">
<PageHeader title="智能分析" />
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
<div className="analysis-workspace">
<aside className="panel analysis-session-panel">
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
{sessionsError && <Alert type="error" message="会话列表读取失败" description={sessionsError} action={<Button size="small" onClick={() => { if (!userSelectionMade.current && !sessionId) void retrySessions(); else void loadSessions(); }}>重试</Button>} />}
{!sessionsLoaded && showSessionsLoading ? <div className="analysis-region-loading" role="status"><Spin />正在读取会话列表…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => {
if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); }
else if (key === 'delete') modal.confirm({ className:'management-modal deletion-confirmation', title: `删除会话“${String(item.title || '未命名会话')}”?`, content: '此会话及其分析记录将被删除,删除后无法恢复。', okText: '确认删除', cancelText: '取消', autoFocusButton:'cancel', maskClosable:false, okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) });
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
</aside>
<section className="panel analysis-chat-panel">
<div className="analysis-conversation" ref={conversation} aria-live="polite" aria-busy={historyLoading} onWheel={event => {
const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null;
if (direction) handleUserScrollIntent(event.currentTarget, direction);
}} onPointerDown={event => {
const element = event.currentTarget;
const bounds = element.getBoundingClientRect();
const scale = element.offsetWidth ? bounds.width / element.offsetWidth : 1;
const scrollbarZone = Math.max(12, element.offsetWidth - element.clientWidth) * scale;
scrollbarPointerActive.current = event.clientX >= bounds.right - scrollbarZone;
}} onPointerUp={() => { scrollbarPointerActive.current = false; }} onPointerCancel={() => { scrollbarPointerActive.current = false; }} onTouchStart={event => {
touchPosition.current = event.touches[0]?.clientY ?? null;
}} onTouchMove={event => {
const currentY = event.touches[0]?.clientY;
if (currentY === undefined || touchPosition.current === null) return;
const delta = currentY - touchPosition.current;
touchPosition.current = currentY;
if (Math.abs(delta) > 2) handleUserScrollIntent(event.currentTarget, delta > 0 ? 'up' : 'down');
}} onTouchEnd={() => { touchPosition.current = null; }} onTouchCancel={() => { touchPosition.current = null; }} onKeyDown={event => {
if (event.target !== event.currentTarget) return;
const direction = ['ArrowUp', 'PageUp', 'Home'].includes(event.key) ? 'up'
: ['ArrowDown', 'PageDown', 'End'].includes(event.key) ? 'down' : null;
if (direction) handleUserScrollIntent(event.currentTarget, direction);
}} onScroll={event => {
if (!activePage.current) return;
const element = event.currentTarget;
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
const pointerIntent = scrollbarPointerActive.current && element.scrollTop !== previousScrollTop.current
? element.scrollTop < previousScrollTop.current ? 'up' : 'down' : null;
const intent = userScrollIntent.current || pointerIntent;
clearUserScrollIntent();
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
if (intent === 'up') explicitlyFollowing.current = false;
else if (intent === 'down' && followOutput.current) explicitlyFollowing.current = true;
previousScrollTop.current = element.scrollTop;
readingPosition.current = element.scrollTop;
if (followOutput.current) setHasNewContent(false);
}}>
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
{!turns.length && !lastTurn && showHistoryLoading && <div className="analysis-region-loading" role="status"><Spin />正在读取会话…</div>}
{!turns.length && !lastTurn && !busy && !historyLoading && !error && !sessionsError && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
</div>
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
const element = conversation.current;
followOutput.current = true; explicitlyFollowing.current = true; clearUserScrollIntent(); setHasNewContent(false);
if (element) { element.scrollTop = element.scrollHeight; previousScrollTop.current = element.scrollTop; readingPosition.current = element.scrollTop; }
}}>回到最新内容 ↓</Button>}
{sessionReadOnly ? <div className="analysis-composer">
<Alert type="info" message="此会话保留用于查看历史结果。" action={<Button type="primary" disabled={busy || historyLoading} onClick={() => { const fixedRelease=releaseId; newSession(); setReleaseId(fixedRelease); }}>新建会话继续分析</Button>} />
{composer.showStop && <Button danger loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>停止分析</Button>}
</div> : <div className="analysis-composer">
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); if (busy) queueFollowup(); else void submit(); } }} />
{queuedFollowup && <div className="analysis-queued-followup" role="status"><span title={queuedFollowup}>待发送:{queuedFollowup}</span><Button type="text" size="small" onClick={() => { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }}>取回编辑</Button></div>}
<div className="ai-actions"><span>Enter {busy ? '排队发送' : '发送'} · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}{composer.showStop && <Button danger aria-label="停止分析" loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>{stopping ? '正在停止' : '停止分析'}</Button>}<Button type="primary" aria-label={composer.sendLabel} disabled={composer.sendDisabled} onClick={() => { if (busy) queueFollowup(); else void submit(); }}>{composer.sendLabel}</Button></div></div>
</div>}
</section>
</div>
<Modal title="重命名会话" open={Boolean(renameTarget)} confirmLoading={renaming} okText="保存" cancelText="取消" okButtonProps={{ disabled: !renameTitle.trim() }} onCancel={() => { if (!renaming) setRenameTarget(null); }} onOk={() => void renameSession()}>
<Input aria-label="会话名称" value={renameTitle} maxLength={160} disabled={renaming} onChange={event => setRenameTitle(event.target.value)} onPressEnter={() => void renameSession()} />
</Modal>
</div>;
}
function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauthorized, retryDisabled = false }: { turn: Record<string, unknown>; onClarify?: (question: string) => void | Promise<void>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; onUnauthorized: (error: unknown) => boolean; retryDisabled?: boolean }) {
const recovery=useAnalysisVisualRecovery(sourceTurn,onUnauthorized),turn=recovery.turn;
const question = typeof turn.question === 'string' ? turn.question : '';
if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn">
{question && <div className="analysis-question"><p>{question}</p></div>}
</article>;
const result = isObjectRecord(turn.result) ? turn.result : turn;
const memberList = result.memberList ?? turn.memberList;
const recordList = result.recordList ?? turn.recordList;
const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
const status = String(turn.status || result.status || '').toUpperCase();
const emptyNotice = emptyAnalysisNotice(turn, answer);
const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined;
const reportMarkdown = typeof result.reportMarkdown === 'string' ? result.reportMarkdown : typeof turn.reportMarkdown === 'string' ? turn.reportMarkdown : '';
const reportHtml = typeof result.reportHtml === 'string' ? result.reportHtml : typeof turn.reportHtml === 'string' ? turn.reportHtml : undefined;
const resumable = ['SUBMITTING', 'QUEUED', 'RUNNING', 'PROCESSING', 'PLANNING', 'TOOL_RUNNING'].includes(status);
return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}>
{question && <div className="analysis-question"><p>{question}</p></div>}
<AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} />
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
{status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <>
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
</> : emptyNotice ? <p role="status">{emptyNotice}</p> : null}
{recovery.error && <p role="alert">{recovery.error}</p>}
<div className="analysis-message-actions">
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
{recovery.available&&<Button size="small" type="text" loading={recovery.recovering} disabled={retryDisabled} onClick={()=>void recovery.recover()}>重试图表</Button>}
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
</div>
</div>}
{memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />}
{recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />}
</article>;
}
function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) {
const [now, setNow] = useState(Date.now());
const running = analysisIsRunning(status) || status === 'SUBMITTING';
useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]);
const plan = isObjectRecord(turn.plan) ? turn.plan : {};
const date = (value: unknown) => typeof value === 'string' && Number.isFinite(Date.parse(value)) ? Date.parse(value) : undefined;
const start = date(turn.startedAt) ?? date(plan.startedAt);
const waitingSince = date(turn._uiSubmittedAt) ?? date(turn.createdAt);
const clockStart = start ?? (running ? waitingSince : undefined);
const finish = date(turn.finishedAt);
const duration = !running && typeof turn.durationMs === 'number' ? turn.durationMs : clockStart !== undefined && (running || finish !== undefined) ? Math.max(0, (running ? now : finish!) - clockStart) : undefined;
const seconds = duration === undefined ? undefined : Math.floor(duration / 1000);
const durationText = seconds === undefined ? '' : seconds >= 3600 ? `${Math.floor(seconds / 3600)}小时${Math.floor(seconds % 3600 / 60)}分${seconds % 60}秒` : seconds >= 60 ? `${Math.floor(seconds / 60)}分${seconds % 60}秒` : `${seconds}秒`;
const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value);
const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : [];
const labels: Record<string, string> = { SUBMITTING: '提交中', QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
return <span className="analysis-turn-metadata" aria-label="分析运行信息">
{status !== 'PARTIAL' && <span>{labels[status] || (running ? '运行中' : '分析记录')}</span>}
{durationText && <span className="analysis-runtime-clock">{running && <LoadingOutlined spin className="analysis-runtime-spinner" aria-hidden="true" />}{running ? start === undefined ? '已等待' : '已运行' : '运行时长'} {durationText}</span>}
{!compact && start !== undefined && <span>开始 {stamp(start)}</span>}
{!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
{!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
</span>;
}
function isObjectRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const canManageUsers = user.roles.includes('SYSTEM_ADMIN');
const canReadAudit = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const canViewServiceIdentities = user.roles.some(role => ['SYSTEM_ADMIN'].includes(role));
const defaultTab = canManageUsers ? 'users' : canReadAudit ? 'audit' : canViewServiceIdentities ? 'services' : '';
const [activeTab] = useState(defaultTab);
const tabs = [
...(canManageUsers ? [{ key: 'users', label: '用户', children: <UsersResourceTab user={user} onUnauthorized={onUnauthorized} /> }] : []),
...(canManageUsers ? [{ key: 'policy', label: '明细与证据范围', children: <UserAccessPolicyPanel onUnauthorized={onUnauthorized} /> }] : []),
...(canViewServiceIdentities ? [{ key: 'services', label: '服务身份', children: <ServiceIdentityPanel user={user} onUnauthorized={onUnauthorized} /> }] : []),
...(canReadAudit ? [{ key: 'audit', label: '审计记录', children: <ResourceTab onUnauthorized={onUnauthorized} /> }] : []),
];
return <div className="management-page">
<PageHeader title="权限与审计" />
{tabs.length > 0 ? <ManagementSections initialKey={activeTab} items={[...tabs, { key: 'summary', label: '当前授权', children: <section className="panel access-summary"><div><span>当前账号</span><strong>{user.displayName || user.username}</strong>{user.displayName && user.displayName !== user.username && <small>{user.username}</small>}</div><div><span>角色</span><strong>{shownRole(user.roles[0])}</strong></div><div><span>授权产业部</span><strong>{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}</strong></div><div><span>授权分组</span><strong>{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}</strong></div></section> }]} /> : <Alert showIcon type="info" message="当前账号没有用户管理或审计记录读取权限" />}
</div>;
}
function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [result, setResult] = useState<Collection | null>(null);
const [page, setPage] = useState(1);
const [loadedPage, setLoadedPage] = useState(0);
const read = useDelayedBusy(); const loading = read.busy;
const [error, setError] = useState('');
const load = useCallback((nextPage = page) => read.run(async () => {
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setLoadedPage(nextPage); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
}), [onUnauthorized, page, read.run]);
useEffect(() => { if (active && loadedPage !== page) void load(page); }, [active, loadedPage, page, load]);
useMaintenanceRefresh(() => { void load(page); });
const items = unwrapItems(result).items;
const total = result?.total ?? items.length;
return <div className="resource-tab">
{error && <Alert type="error" showIcon message="审计记录读取失败" description={loadedPage ? `${error};当前仍显示第 ${loadedPage} 页上次成功结果。` : error} action={!loadedPage ? <Button size="small" onClick={() => void load(page)}>重试</Button> : undefined} />}
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load(page)}>刷新</Button></div>
{loading && loadedPage !== page ? <div className="loading-panel"><Spin />正在读取…</div> : result && <DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />}
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
</div>;
}
function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const { active } = usePageCache();
const [users, setUsers] = useState<Record<string, unknown>[]>([]);
const [departments, setDepartments] = useState<string[]>([]);
const [groups, setGroups] = useState<string[]>([]);
const [usersLoaded, setUsersLoaded] = useState(false);
const [optionsLoaded, setOptionsLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const saveLock = useRef(false);
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
const [form] = Form.useForm<{ username: string; displayName: string; password: string; active: boolean; forcePasswordChange: boolean; role: string; departments: string[]; groups: string[] }>();
const selectedRole = Form.useWatch('role', form);
const [deleting, setDeleting] = useState<Record<string, unknown> | null>(null);
const canManage = user.roles.includes('SYSTEM_ADMIN');
const load = useCallback(() => read.run(async () => {
const [userResult, optionsResult] = await Promise.allSettled([api.users(), api.options()]);
const failures: string[] = [];
let rows = users;
if (userResult.status === 'fulfilled') { rows = collectionItems(userResult.value); setUsers(rows); setUsersLoaded(true); }
else if (!onUnauthorized(userResult.reason)) failures.push(`用户清单:${apiMessage(userResult.reason)}`);
if (optionsResult.status === 'fulfilled') {
setDepartments(Array.from(new Set([...(optionsResult.value.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
setGroups(Array.from(new Set([...(optionsResult.value.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
setOptionsLoaded(true);
} else if (!onUnauthorized(optionsResult.reason)) failures.push(`授权选项:${apiMessage(optionsResult.reason)}`);
setError(failures.join(';'));
}), [onUnauthorized, read.run, users]);
useEffect(() => { if (active && !usersLoaded) void load(); }, [active, usersLoaded, load]);
useMaintenanceRefresh(load);
const openEditor = (record?: Record<string, unknown>) => {
setEditing(record || {});
form.setFieldsValue({
username: String(record?.username || ''), displayName: String(record?.displayName || ''), password: '',
active: record?.active !== false, forcePasswordChange: record?.forcePasswordChange === true,
role: Array.isArray(record?.roles) ? String(record.roles[0] || 'USER') : 'USER',
departments: Array.isArray(record?.departments) ? record.departments.map(String) : [],
groups: Array.isArray(record?.groups) ? record.groups.map(String) : [],
});
};
const save = async () => {
if (saveLock.current) return; saveLock.current = true;
try {
const values = await form.validateFields();
setBusy(true);
const id = String(editing?.id || '');
if (id) {
await api.updateUser(id, { displayName: values.displayName.trim(), active: values.active, forcePasswordChange: values.forcePasswordChange, roles: [values.role], departments: values.departments, groups: values.groups, expectedRowVersion: Number(editing?.rowVersion || 0) });
} else {
await api.createUser({ username: values.username.trim(), displayName: values.displayName.trim(), password: values.password, roles: [values.role], departments: values.departments, groups: values.groups });
}
message.success(id ? '用户权限已更新' : '用户已创建');
setEditing(null); form.resetFields(); await load();
} catch (value) {
if (value && typeof value === 'object' && 'errorFields' in value) return;
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && value.status === 409) await load();
} finally { saveLock.current = false; setBusy(false); }
};
const removeUser = async () => {
if (!deleting || saveLock.current) return;
saveLock.current = true; setBusy(true);
try {
await api.deleteUser(String(deleting.id), Number(deleting.rowVersion));
setDeleting(null); message.success('账号已删除,历史记录已保留'); await load();
} catch (value) {
if (!onUnauthorized(value)) message.error(apiMessage(value));
if (value instanceof ApiError && [404, 409].includes(value.status)) { setDeleting(null); await load(); }
} finally { saveLock.current = false; setBusy(false); }
};
const columns: ColumnsType<Record<string, unknown>> = [
{ title: '账号', dataIndex: 'username', key: 'username', fixed: 'left', width: 170 },
{ title: '显示名称', dataIndex: 'displayName', key: 'displayName', width: 180 },
{ title: '状态', dataIndex: 'active', key: 'active', width: 90, align: 'center', render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : '停用'}</Tag> },
{ title: '角色', dataIndex: 'roles', key: 'roles', width: 250, render: value => Array.isArray(value) ? value.length ? <span className="role-list">{value.map((role, index) => <span key={`${String(role)}-${index}`}>{shownRole(role)}</span>)}</span> : '—' : '—' },
{ title: '授权产业部', dataIndex: 'departments', key: 'departments', width: 230, render: value => Array.isArray(value) ? value.map(item => shownDepartment(String(item))).join('、') || '未限制' : '—' },
{ title: '授权分组', dataIndex: 'groups', key: 'groups', width: 180, render: value => Array.isArray(value) ? value.join('、') || '未限制' : '—' },
{ title: '操作', key: 'actions', fixed: 'right', width: 180, align: 'center', render: (_, row) => canManage ? <><Button type="link" disabled={busy} onClick={() => openEditor(row)}>编辑授权</Button><Button type="link" danger disabled={busy || row.id === user.id} title={row.id === user.id ? '不能删除当前登录账号' : undefined} onClick={() => setDeleting(row)}>删除</Button></> : <span className="muted-dash">权限不足</span> },
];
return <div className="resource-tab">
{error && <Alert type="error" showIcon message="用户清单读取失败" description={usersLoaded || optionsLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
<div className="resource-toolbar"><strong>用户清单</strong><span>{users.length} 个账号</span>{canManage && <Button type="primary" onClick={() => openEditor()}>新建用户</Button>}<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
{loading && !usersLoaded ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : usersLoaded ? users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1280 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" /> : null}
<Modal className="management-modal" open={Boolean(deleting)} title={`删除账号 ${String(deleting?.username || '')}`} okText="删除账号" cancelText="取消" okButtonProps={{ danger: true }} confirmLoading={busy} cancelButtonProps={{ disabled: busy }} closable={!busy} maskClosable={!busy} onCancel={() => { if (!busy) setDeleting(null); }} onOk={() => void removeUser()}>
<p>删除后,该账号将无法登录,并从用户清单移除。已有业务数据和操作记录会保留。</p>
</Modal>
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑用户授权' : '新建用户'} width={700} confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
<Alert className="user-management-note" showIcon type="info" message="需至少保留一个启用的系统管理员;未配置产业部的非管理员账号可能没有业务数据访问范围。" />
<Form form={form} layout="vertical">
{!editing?.id && <><Form.Item name="username" label="登录账号" rules={[{ required: true, whitespace: true, message: '请填写登录账号' }]}><Input autoComplete="off" /></Form.Item><Form.Item name="password" label="初始密码" rules={[{ required: true, min: 6, message: '初始密码至少6位' }]}><Input.Password autoComplete="new-password" /></Form.Item></>}
<Form.Item name="displayName" label="显示名称" rules={[{ required: true, whitespace: true, message: '请填写显示名称' }]}><Input /></Form.Item>
<Form.Item name="role" label="角色" extra={ROLE_DESCRIPTIONS[selectedRole]} rules={[{ required: true, message: '请选择一个角色' }]}><Select options={USER_ROLE_OPTIONS} /></Form.Item>
<Form.Item name="departments" label="授权产业部"><Select {...readableSelectPopup} mode="multiple" options={departments.map(value => ({ label: shownDepartment(value), value }))} placeholder="选择数据范围;空范围可能无法读取业务数据" /></Form.Item>
<Form.Item name="groups" label="授权业务分组"><Select {...readableSelectPopup} mode="multiple" options={groups.map(value => ({ label: value, value }))} placeholder="选择可访问的业务分组" /></Form.Item>
{Boolean(editing?.id) && <div className="user-access-toggles"><Form.Item name="active" label="账号状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><Form.Item name="forcePasswordChange" label="下次登录修改密码" valuePropName="checked"><Switch /></Form.Item></div>}
</Form>
</Modal>
</div>;
}
function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { active } = usePageCache();
const [rules, setRules] = useState<Record<string, unknown>[]>([]);
const [ruleError, setRuleError] = useState('');
const [loaded, setLoaded] = useState(false);
const read = useDelayedBusy(); const loading = read.busy;
const load = useCallback(() => read.run(async () => {
try { setRules(unwrapItems(await api.rules()).items); setLoaded(true); setRuleError(''); }
catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); }
}), [onUnauthorized, read.run]);
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
useMaintenanceRefresh(load);
return <div className="management-page">
<PageHeader title="数据与计算依据" description="综合合格率沿用正式指标服务结果;计算规则由服务端统一维护。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
<Alert showIcon type="info" message="综合合格率 = 同一筛选条件下黑片合格率 × 亮片合格率" description="此处说明业务口径。前端只展示服务端正式返回的指标,不用浏览器数据重算或替代正式结果。" />
<div className="basis-grid">
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" showIcon message="指标规则读取失败" description={loaded ? `${ruleError};下方保留上次成功结果。` : ruleError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}{loading && !loaded ? <div className="loading-panel"><Spin /></div> : loaded && <DynamicTable items={rules} />}</section>
</div>
</div>;
}