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, metadata: Collection> | { items: Record[] }): Record[] { 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 }; 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; const rawQuery = source.query && typeof source.query === 'object' ? source.query as Record : 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; 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 : 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 —; if (typeof value === 'object') return
{publicJson(value)}
; 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).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[]; total?: number; page?: number; pageSize?: number; currentReleaseId?: string | null } { if (Array.isArray(value)) return { items: value as Record[] }; if (value && typeof value === 'object') { const candidate = value as Collection; return { ...candidate, items: collectionItems(candidate).filter(item => item && typeof item === 'object') as Record[] }; } return { items: [] }; } function DynamicTable({ items, rowKey = 'id', paginate = true, indexOffset = 0 }: { items: Record[]; rowKey?: string; paginate?: boolean; indexOffset?: number }) { const keys = useMemo(() => { const discovered = new Set(); 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> = keys.map(key => ({ title: key, dataIndex: key, key, width: ['id', 'sha256'].includes(key) ? 220 : 160, ellipsis: true, render: value => readableValue(value), })); return items.length ?
String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} indexOffset={indexOffset} scroll={{ x: 'max-content' }} />

共 {items.length} 条记录

: ; } type ManagementPageProps = { page: PageKey; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void; }; export default function ManagementPages(props: ManagementPageProps) { return ; } function RulesWorkspace({ user, onUnauthorized, onNavigate }: Omit) { 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 }, { key: 'targets', label: '质量目标', children: }, { key: 'settings', label: '计算设置', children: }, ]} />; } function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) { if (page === 'sources' || page === 'imports') return ; if (page === 'tasks') return ; if (page === 'analysis') return ; if (page === 'access') return ; if (page === 'basis') return ; if (page === 'rules') return ; if (page === 'masterData') return },{ key: 'filters', label: '查询字段', children: ['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />; if (page === 'mappings') return ; const resource: Record = { imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' }, tasks: { endpoint: 'tasks', title: '后台任务', subtitle: '任务状态、进度和服务端返回的失败信息。' }, }; const config = resource[page]; return config ? onNavigate('tasks')} /> : ; } function PageHeader({ actions }: { title: string; description?: string; actions?: React.ReactNode }) { return actions ?
{actions}
: null; } function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) { const { active } = usePageCache(); const [sources, setSources] = useState([]); const [currentReleaseId, setCurrentReleaseId] = useState(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(() => { 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
{error && void load()}>重试} />} void load()} /> }, { key: 'files', label: '来源文件', children: setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> }, { key: 'history', label: '导入记录', children: }, { key: 'audit', label: '来源审计', children: }, ]} />
; } function ImportHistoryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { active } = usePageCache(); const [items, setItems] = useState[]>([]); 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
导入记录{items.length} 条 · 可查看处理结果和逐行校验问题
{error && void load()}>重试} />} {loading && !loaded ? : loaded && void load()} />}
; } function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) { const { active } = usePageCache(); const [result, setResult] = useState(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 } | 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 {error && void load()}>重试} />} {loading && !hasSameRunResult ?
正在读取问题行…
: hasSameRunResult ? <>{!pageMatches && loading &&
正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。
} : null} {hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && `共 ${count} 条问题`} onChange={setPage} />}
; } 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[]>([]); 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
} loading={loading} onClick={() => void load()}>刷新} /> {error && void load()}>重试 : undefined} />}
{title}{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}
{loading && !loaded ?
正在读取…
: loaded && void load()} />}
; } function RuleContents({ value }: { value: unknown }) { const definition = value && typeof value === 'object' ? value as Record : {}; if (definition.version === 'pq-dax-v1' && !definition.rowRules && !definition.metricRules) return

此历史记录未保存可展开的公式明细。

; return ; } 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 & { groupDepartments?: Record }; 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[]>([]); 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 | null>(null); const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null); const [impactOpen, setImpactOpen] = useState(false); const [impact, setImpact] = useState | null>(null); const [regressionOpen, setRegressionOpen] = useState(false); const [regression, setRegression] = useState | null>(null); const [regressionRuns, setRegressionRuns] = useState[]>([]); const [regressionError, setRegressionError] = useState(''); const [regressionBusy, setRegressionBusy] = useState(false); const [form] = Form.useForm<{ name: string; description: string }>(); const [draftDefinition, setDraftDefinition] = useState({}); const loadedDefinitionKey=useRef(''); const loadedDefinition=useRef(''); const classificationUpdates=useClassificationQueue(kind==='mappings'?String(user.id):'inactive-'+kind); const [ruleSchema, setRuleSchema] = useState | null>(null); const [ruleSchemaError, setRuleSchemaError] = useState(''); const [ruleBaseline, setRuleBaseline] = useState({}); const [publishedNames, setPublishedNames] = useState(null); const [matchMetadata,setMatchMetadata]=useState|null>(null); const [differenceItem, setDifferenceItem] = useState | null>(null); const [differenceConfirmed, setDifferenceConfirmed] = useState(false); const [workflowStatus, setWorkflowStatus] = useState(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 } | 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, 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[]; setRegressionRuns(runs); const embeddedValidation = item.validation && typeof item.validation === 'object' ? item.validation as Record : {}; 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) => { 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 | 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(); 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 = { 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, 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 | 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) => { 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[] : []; const impactHits = Array.isArray(impact?.hits) ? impact.hits.filter(item => item && typeof item === 'object') as Record[] : []; const regroupingPreview = Array.isArray(impact?.regroupingPreview) ? impact.regroupingPreview.filter(item => item && typeof item === 'object') as Record[] : []; const regroupingColumns: ColumnsType> = [ { 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 | null)?.compositeRate)) }, { title: '变更后综合率', key: 'afterComposite', align: 'right', width: 130, render: (_, row) => ratioText(((row.after as Record | null)?.compositeRate)) }, { title: '变更前黑/亮报废重量', key: 'beforeScrap', align: 'right', width: 180, render: (_, row) => { const before = row.before as Record | null; return `${toText((before?.black as Record | undefined)?.scrapWeight)} / ${toText((before?.bright as Record | undefined)?.scrapWeight)}`; } }, { title: '变更后黑/亮报废重量', key: 'afterScrap', align: 'right', width: 180, render: (_, row) => { const after = row.after as Record | null; return `${toText((after?.black as Record | undefined)?.scrapWeight)} / ${toText((after?.bright as Record | undefined)?.scrapWeight)}`; } }, { title: '差异项', key: 'differences', render: (_, row) => Array.isArray(row.differences) ? row.differences.map(item => { const value = item && typeof item === 'object' ? item as Record : {}; return `${toText(value.path)}:${toText(value.delta ?? value.after)}`; }).join(';') : '—' }, ]; const columns: ColumnsType> = [ { title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => {toText(isRules ? ruleDisplayName(value) : value)} }, { title: '状态', dataIndex: 'status', key: 'status', width: 125, align: 'center', render: value => {({ ACTIVE: '已启用', VALIDATED: '已校验', DRAFT: '草稿', SUPERSEDED: '历史记录', ENGINE_BASELINE: '原始公式', ARCHIVED: '已归档' } as Record)[String(value).toUpperCase()] || toText(value)} }, { 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) => {canManage && ['DRAFT', 'VALIDATED'].includes(String(row.status).toUpperCase()) && } {canManage && } {isRules && } {canManage && String(row.status).toUpperCase() !== 'ACTIVE' && } }, ]; const simpleStageLabel: Record = { 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
{statusRead.busy ?
正在读取当前维护模式…
: workflowStatusError ? void refreshWorkflowStatus()}>重试} /> : null}
; if (testMode) { const notices = <> {kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&
{classificationBusy&& 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条} {classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=>{job.status==='failed'&&}}/>)}
} {error && void load()}>重试 : undefined} />} {isRules && ruleSchemaError && } {!canApplyWorkflow && } {workflowOperation.error && 重试读取进度 : undefined} />} {workflowOperation.operation &&
{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}
{workflowOperation.busy ? : }
} ; const editor = (mode: 'catalog' | 'lookups' | 'matchRules' | 'rules') =>
{notices}
{mode === 'rules' &&
} {mode === 'rules' ? : mode === 'catalog' ? : mode === 'lookups' ? : } {!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && {validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=>
  • {issue}
  • )}} />} {isRules && ruleChangeSummary(ruleBaseline, draftDefinition).length > 0 &&
    本次变更{ruleChangeSummary(ruleBaseline, draftDefinition).join(';')}
    } {canApplyWorkflow &&
    {isRules ? '检查规则 → 重新计算 → 更新报表' : '保存后检查配置并更新报表。'}
    }
    ; if (kind === 'masterData') return <>
    {editor('catalog')}; if (kind === 'mappings') return 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|undefined)?.groups)?((draftDefinition.masterData as Record).groups as Record[]).filter(row=>row.enabled!==false).map(row=>String(row.name)):publishedNames?.groups??[]}}> ({ ...section, children: <>{notices}{section.children} })), ]} />; return editor('rules'); } const standardContent =
    {canManage && !isRules && String(item.status).toUpperCase() === 'ACTIVE')} onUnauthorized={onUnauthorized} onComplete={() => void load()} />} {canManage && } } /> {error && void load()}>重试 : undefined} />} {isRules && ruleSchemaError && }
    {title}记录{items.length} 个服务端记录
    {loading && !itemsLoaded ?
    正在读取…
    : itemsLoaded ? items.length ?
    String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /> : : null} onNavigate('sources')}>前往重新计算 : undefined} /> setDrafting(null)} onOk={() => void saveDraft()}>
    {isRules ? : <> {kind === 'masterData' ? : } {validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && {validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0, 20).map((issue, index) =>
  • {issue}
  • )}} />} } {!isRules && }
    setDifferenceItem(null)} onOk={() => { if (differenceItem) void runAction(differenceItem, 'activate', true); }}> {differenceItem && (() => { const result = differenceItem.validation as Record; return <>

    汇总差异

    [] : []} />

    来源行差异(最多 100 行)

    [] : []} /> setDifferenceConfirmed(event.target.checked)}>我已核对本次试算差异,并确认启用此规则 ; })()}
    {validation && !drafting && setValidation(null)}>{validation.purpose === 'definition' ? isRules ? : : (() => { const response = validation.value && typeof validation.value === 'object' ? validation.value as Record : {}; const result = response.validation && typeof response.validation === 'object' ? response.validation as Record : response; const errors = Array.isArray(result.errors) ? result.errors : []; const warnings = Array.isArray(result.warnings) ? result.warnings : []; return <> {errors.length > 0 && <>

    需要处理

      {errors.map((issue, index) =>
    • {summaryText(issue)}
    • )}
    } {warnings.length > 0 && <>

    提示

      {warnings.map((issue, index) =>
    • {summaryText(issue)}
    • )}
    } {Array.isArray(result.differences) && result.differences.length > 0 && <>

    汇总差异

    []} />} {Array.isArray(result.rowDifferences) && result.rowDifferences.length > 0 && <>

    来源行差异(最多 100 行)

    []} />}
    校验原始记录
    {publicJson(validation.value)}
    ; })()}
    } {isRules && { setRegressionOpen(false); setRegression(null); }}> {regressionError && } {regressionRuns.length > 0 &&
    历史执行 {regressionRuns.length} 次
    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 ? 通过 : row.passed === false ? 失败 : toText(value) }, { title: '期望行数', key: 'expectedRows', align: 'right', width: 120, render: (_, row) => toText((row.details as Record | undefined)?.expectedRows) }, { title: '实际行数', key: 'actualRows', align: 'right', width: 120, render: (_, row) => toText((row.details as Record | undefined)?.actualRows) }, { title: '差异说明', key: 'details', render: (_, row) => summaryText((row.details as Record | undefined)?.differences || (row.details as Record | undefined)?.failedRows || (row.details as Record | undefined)?.actual) }, ]} locale={{ emptyText: '本次回归没有返回案例' }} /> {failures.length > 0 && <>

    失败案例

    String(row.name || index)} dataSource={failures} pagination={false} columns={[{ title: '案例', dataIndex: 'name', key: 'name' }, { title: '说明', key: 'details', render: (_, row) => summaryText(row.details) }]} />}
    回归报告原始记录
    {publicJson(regression)}
    ; })() : } } { setImpactOpen(false); setImpact(null); }}>{impact ? <>
    影响来源{Array.isArray(impact.affectedSources) ? impact.affectedSources.length : toText(impact.affectedSources)}
    冻结状态{impact.frozen === true ? '已冻结' : impact.frozen === false ? '未冻结' : '—'}
    需要更新报表{impact.requiresNewRelease === true ? '是' : '否'}
    {impact.status === 'NO_PUBLISHED_RELEASE' && } {isRules ? <>

    依赖与来源

    [] : []), ...(Array.isArray(impact.affectedSources) ? impact.affectedSources as Record[] : [])]} /> : <>

    映射键前后值

    `${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 && 停用} }, { title: '变更后', dataIndex: 'after', key: 'after', width: 200, render: (value, row) => <>{toText(value)}{row.afterEnabled === false && 停用} }, { title: '命中范围', key: 'ranges', render: (_, row) => `前:${toText(row.beforeRanges)} · 后:${toText(row.afterRanges)}` }]} locale={{ emptyText: '服务端未报告映射键变化' }} />

    命中来源与行数

    `${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: '无来源命中记录' }} />

    对象重分组预览

    `${toText(row.dimension)}:${toText(row.key)}:${index}`} pagination={{ pageSize: 25, showSizeChanger: false }} scroll={{ x: 1050 }} columns={regroupingColumns} locale={{ emptyText: '服务端未返回重分组结果' }} /> }
    影响预览技术字段
    {publicJson(impact)}
    :
    由服务端重新核对配置依赖…
    }; return extraSections ? {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;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('');});}}}> : standardContent; } function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit) { const canEdit=user.roles.some(role=>['SYSTEM_ADMIN', 'DATA_ADMIN'].includes(role)); return {edit=>}}, {key:'projects',label:'项目组未分类',children:{edit=>}}, ]}/>; } 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> = [ { 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) => }, ]; return
    {error && }
    业务分组未分类汇总
    共 {total} 条
    JSON.stringify([row.stage, row.department, row.product, row.sourceKey])} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1280 }} /> {total > TABLE_PAGE_SIZE && } ; } 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(); const [businessGroup,setBusinessGroup]=useState(); const [department,setDepartment]=useState(); 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> = [ { 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 : {}; return Array.isArray(details.periods) ? (details.periods as unknown[]).map(toText).join('、') : '—'; } }, { title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => {value==='OPEN'?'待处理':toText(value)} }, { title: '操作', key: 'action', width: 120, fixed: 'right', render: (_, row) => }, ]; return
    {error && }
    项目组未分类汇总
    共 {total} 条
    ({ label: value, value }))} onChange={value => { setBusinessGroup(value); setPage(1); }} />
    String(row.id)} pagination={false} indexOffset={(currentPage - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1320 }} /> : }{total > TABLE_PAGE_SIZE && `共 ${count} 条问题`} onChange={setPage} />} ; } 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[]>([]); 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 | null>(null); const [inspecting, setInspecting] = useState | 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) => { 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> = [ { title: '指标', dataIndex: 'name', key: 'name', width: 190 }, { title: '当前计算公式', key: 'formula', width: 330, render: (_, row) =>
    {formulaOnly(currentMetricFormula(row))}
    }, { title: '计算口径', dataIndex: 'description', key: 'description', width: 280, render: value => readableValue(readableRuleDescription(value)) }, { title: '操作', key: 'actions', width: 220, render: (_, row) => {canManage && <>{onEditFormula && }} }, ]; useMaintenanceRefresh(load); return
    当前生效指标
    {dictionaryError && void load()}>重试 : undefined} />} {loading && !loaded ?
    读取指标说明…
    : loaded ? items.length ?
    String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /> : : null} { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
    setInspecting(null)}> {inspecting &&
    名称
    {toText(inspecting.name)}
    别名
    {Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}
    说明
    {toText(readableRuleDescription(inspecting.description))}
    单位
    {inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}
    适用维度
    当前生效公式
    {currentMetricFormula(inspecting)}
    状态
    }
    ; } function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { items: Record[]; importOnly: boolean; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onRefresh: () => void }) { const { message } = App.useApp(); const [selected, setSelected] = useState | 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) => { const payload = row.payload && typeof row.payload === 'object' ? row.payload as Record : {}; return String(row.importRunId || payload.importRunId || ''); }; const retry = async (row: Record) => { 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 : {}; const run = body.run && typeof body.run === 'object' ? body.run as Record : {}; 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) => { 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> = [ { 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 => {importOnly ? importState(value) : toText(value)} }, { 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 ? {value==='OPEN'?'待处理':toText(value)} : '—' }, { title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? {toText(value)} : '—' }, { title: '创建时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 }, { title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => {importOnly && runIdOf(row) && } {canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && } {canCancel && String(row.status).toUpperCase() === 'QUEUED' && } }, ]; return <> {items.length ?
    ['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 }} /> : } setSelected(null)}> {selected && <>
    {importOnly ? importState(selected.status) : `${toText(selected.type)} · ${toText(selected.status)}`}{!importOnly && {toText(selected.stage)} · {toText(selected.id)}}{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && }
    {importOnly ?
    处理状态
    {importState(selected.status)}
    处理行数
    {toText(selected.processed)} / {toText(selected.total)}
    创建时间
    {toText(selected.createdAt)}
    :
    {publicJson(selected)}
    }}
    setIssuesRunId('')} onUnauthorized={onUnauthorized} /> ; } function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) { const { message, modal } = App.useApp(); const [renameTarget, setRenameTarget] = useState | 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 | null>(null); const [sessions, setSessions] = useState[]>([]); const [sessionsLoaded, setSessionsLoaded] = useState(false); const [sessionsLoading, setSessionsLoading] = useState(true); const [sessionsError, setSessionsError] = useState(''); const showSessionsLoading = useDelayedIndicator(sessionsLoading && active, 150); const sessionReadRequest = useRef[] | undefined> | null>(null); const [turns, setTurns] = useState[]>([]); const [options, setOptions] = useState(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 | null>(null); const [activeTurnId, setActiveTurnId] = useState(''); const streamController = useRef(null); const eventCursors = useRef>({}); const mounted = useRef(true); const userSelectionMade = useRef(false); const navigationGeneration = useRef(0); const subscriptionGeneration = useRef(0); const submissionAttempt = useRef(null); const [releaseId, setReleaseId] = useState(); const [sourceResultRef, setSourceResultRef] = useState(); const conversation = useRef(null); const followOutput = useRef(true); const explicitlyFollowing = useRef(false); const userScrollIntent = useRef(null); const userScrollIntentTimer = useRef | null>(null); const scrollbarPointerActive = useRef(false); const touchPosition = useRef(null); const followRequest = useRef(null); const seenConclusion = useRef(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) => { clearUserScrollIntent(); userScrollIntent.current = intent; userScrollIntentTimer.current = setTimeout(clearUserScrollIntent, 100); }; const handleUserScrollIntent = (element: HTMLDivElement, intent: Exclude) => { 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('.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 = { 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 => { 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 : {}; 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 : {}; 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 = {}; let terminalEventStatus = ''; setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' })); let timingReadInFlight = false, timingReadAgain = false, startConfirmed = false; const refreshTiming = async (): Promise => { 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 = {}; 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 : {}; 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 => { 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) => { 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
    {error && {retryQuestion && }} />} {optionsError && { 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)); } }); }}>重试} />}
    { 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) => 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 && 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 &&
    正在读取会话…
    } {!turns.length && !lastTurn && !busy && !historyLoading && !error && !sessionsError &&
    想了解哪些质量情况?例如:9月汽车交通的合格率为什么下降?
    }
    {hasNewContent && } {sessionReadOnly ?
    { const fixedRelease=releaseId; newSession(); setReleaseId(fixedRelease); }}>新建会话继续分析} /> {composer.showStop && }
    :
    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 &&
    待发送:{queuedFollowup}
    }
    Enter {busy ? '排队发送' : '发送'} · Shift + Enter 换行
    {user.roles.includes('SYSTEM_ADMIN') && }{composer.showStop && }
    }
    { if (!renaming) setRenameTarget(null); }} onOk={() => void renameSession()}> setRenameTitle(event.target.value)} onPressEnter={() => void renameSession()} />
    ; } function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauthorized, retryDisabled = false }: { turn: Record; onClarify?: (question: string) => void | Promise; 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
    {question &&

    {question}

    }
    ; 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
    {question &&

    {question}

    } } /> {(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) &&
    {status === 'NEEDS_CLARIFICATION' && onClarify ? : answer ? <> {resumable ? : authorizeAnalysisSnapshot(turn)} turn={turn} />} : emptyNotice ?

    {emptyNotice}

    : null} {recovery.error &&

    {recovery.error}

    }
    {(reportMarkdown.trim() || reportHtml?.trim()) && } {!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && } {recovery.available&&} {['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && } {resumable && !retryDisabled && typeof turn.id === 'string' && onResume && }
    } {memberList !== undefined && memberList !== null && } {recordList !== undefined && recordList !== null && }
    ; } function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record; 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 = { SUBMITTING: '提交中', QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' }; return {status !== 'PARTIAL' && {labels[status] || (running ? '运行中' : '分析记录')}} {durationText && {running && } {!compact && start !== undefined && 开始 {stamp(start)}} {!compact && !running && finish !== undefined && {status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}} {!compact && steps.length > 0 && 工具调用 {steps.length} 次} ; } function isObjectRecord(value: unknown): value is Record { 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: }] : []), ...(canManageUsers ? [{ key: 'policy', label: '明细与证据范围', children: }] : []), ...(canViewServiceIdentities ? [{ key: 'services', label: '服务身份', children: }] : []), ...(canReadAudit ? [{ key: 'audit', label: '审计记录', children: }] : []), ]; return
    {tabs.length > 0 ?
    当前账号{user.displayName || user.username}{user.displayName && user.displayName !== user.username && {user.username}}
    角色{shownRole(user.roles[0])}
    授权产业部{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}
    授权分组{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}
    }]} /> : }
    ; } function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { const { active } = usePageCache(); const [result, setResult] = useState(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
    {error && void load(page)}>重试 : undefined} />}
    审计事件{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}
    {loading && loadedPage !== page ?
    正在读取…
    : result && } {total > TABLE_PAGE_SIZE && `共 ${count} 条`} onChange={setPage} />}
    ; } function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const { active } = usePageCache(); const [users, setUsers] = useState[]>([]); const [departments, setDepartments] = useState([]); const [groups, setGroups] = useState([]); 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 | 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 | 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) => { 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> = [ { 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 => {value === true ? '启用' : '停用'} }, { title: '角色', dataIndex: 'roles', key: 'roles', width: 250, render: value => Array.isArray(value) ? value.length ? {value.map((role, index) => {shownRole(role)})} : '—' : '—' }, { 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 ? <> : 权限不足 }, ]; return
    {error && void load()}>重试} />}
    用户清单{users.length} 个账号{canManage && }
    {loading && !usersLoaded ?
    正在读取用户与授权范围…
    : usersLoaded ? users.length ?
    String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1280 }} /> : : null} { if (!busy) setDeleting(null); }} onOk={() => void removeUser()}>

    删除后,该账号将无法登录,并从用户清单移除。已有业务数据和操作记录会保留。

    setEditing(null)} onOk={() => void save()}>
    {!editing?.id && <>} ({ label: shownDepartment(value), value }))} placeholder="选择数据范围;空范围可能无法读取业务数据" />