同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
+361
-159
@@ -1,7 +1,14 @@
|
||||
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 } from './pageCache';
|
||||
import { FilterFieldSettings } from './FilterFieldSettings';
|
||||
import { isInternalDataField, publicJson } from './publicDataDisplay';
|
||||
import { isInternalDataField, publicJson, readableRuleDescription } from './publicDataDisplay';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
@@ -23,7 +30,7 @@ import {
|
||||
Tag,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { CompactManagementTables, QualityTable as Table } from './QualityTable';
|
||||
import { DeleteOutlined, EditOutlined, MoreOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
|
||||
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
|
||||
@@ -36,8 +43,13 @@ import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExpo
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { authorizeAnalysisSnapshot } from './analysisSnapshot';
|
||||
import { AnalysisApiSettings } from './AnalysisApiSettings';
|
||||
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress } from './analysisConversationState';
|
||||
import { acceptAnalysisEvent, analysisScrollFollows, partialAnalysisNotice, partialAnswerIsOnlyProgress, type AnalysisScrollIntent } from './analysisConversationState';
|
||||
import { AnalysisProcess } from './AnalysisProcess';
|
||||
import { AnalysisMemberListPanel } from './AnalysisMemberList';
|
||||
import { AnalysisRecordListPanel } from './AnalysisRecordList';
|
||||
import { analysisScopeText, 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';
|
||||
|
||||
@@ -45,7 +57,7 @@ const TABLE_PAGE_SIZE = 20;
|
||||
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 { BackupOperationsPanel, CostConfigurationPanel, OperationsMonitorPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
import { CostConfigurationPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
|
||||
function apiMessage(error: unknown): string {
|
||||
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
|
||||
@@ -58,6 +70,10 @@ function toText(value: unknown): string {
|
||||
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;
|
||||
}
|
||||
@@ -67,7 +83,8 @@ function restoredAnalysisTurns(history: Record<string, unknown>, metadata: Colle
|
||||
return collectionItems(metadata).slice().reverse().map(turn => {
|
||||
const found = saved.find(item => item.id === turn.id);
|
||||
const answer = found && isObjectRecord(found.result) ? found.result : {};
|
||||
return { ...found, ...answer, ...turn, sessionId: history.id };
|
||||
const status=answer.visualRecovery&&answer.originalStatus===turn.status?answer.status||turn.status:turn.status;
|
||||
return { ...found, ...answer, ...turn, status, sessionId: history.id };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -91,11 +108,14 @@ function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext
|
||||
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);
|
||||
if ((month !== undefined && (!Number.isInteger(month) || month < 1 || month > 12)) || (quarter !== undefined && (!Number.isInteger(quarter) || quarter < 1 || quarter > 4)) || (month !== undefined && quarter !== undefined)) throw new Error('分析条件链接中的月/季度无效');
|
||||
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 } : {}), view };
|
||||
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;
|
||||
@@ -186,15 +206,22 @@ function DynamicTable({ items, rowKey = 'id', paginate = true, indexOffset = 0 }
|
||||
}));
|
||||
return items.length
|
||||
? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} indexOffset={indexOffset} scroll={{ x: 'max-content' }} />
|
||||
<p className="table-caption">显示服务端返回的 {items.length} 条记录</p></div>
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前返回空列表" />;
|
||||
<p className="table-caption">共 {items.length} 条记录</p></div>
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无记录" />;
|
||||
}
|
||||
|
||||
export default function ManagementPages({ page, user, onUnauthorized, onNavigate }: {
|
||||
type ManagementPageProps = {
|
||||
page: PageKey; user: AuthUser; onUnauthorized: (error: unknown) => boolean;
|
||||
onNavigate: (page: PageKey) => void;
|
||||
}) {
|
||||
};
|
||||
export default function ManagementPages(props: ManagementPageProps) {
|
||||
return <CompactManagementTables.Provider value={['sources','imports','rules','mappings','masterData','tasks','access','basis'].includes(props.page)}>
|
||||
<ManagementPageContents {...props}/>
|
||||
</CompactManagementTables.Provider>;
|
||||
}
|
||||
function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: ManagementPageProps) {
|
||||
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'tasks') return <TasksMonitorPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
||||
@@ -291,7 +318,7 @@ function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string;
|
||||
</Drawer>;
|
||||
}
|
||||
|
||||
function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized, onNavigate }: {
|
||||
function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized }: {
|
||||
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
|
||||
}) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
@@ -317,11 +344,20 @@ function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized,
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
</section>
|
||||
{endpoint === 'tasks' && <><OperationsMonitorPanel user={user} onUnauthorized={onUnauthorized} /><BackupOperationsPanel user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /></>}
|
||||
<Alert showIcon type="info" message="状态以服务端为准" description={endpoint === 'imports' ? '此处显示任务服务返回的导入状态、校验结果和错误;选择问题行可查看后端返回的逐行检查记录。' : '可查看真实任务进度、失败原因,并按权限对失败任务重试或取消排队任务。'} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
function RuleContents({ value }: { value: unknown }) {
|
||||
const definition = value && typeof value === 'object' ? value as Record<string, unknown> : {};
|
||||
if (definition.version === 'pq-dax-v1' && !definition.rowRules && !definition.metricRules) return <p>此历史记录未保存可展开的公式明细。</p>;
|
||||
return <BusinessValue value={value} />;
|
||||
}
|
||||
|
||||
function ruleDisplayName(value: unknown): string {
|
||||
const name = String(value || '');
|
||||
return /power\s*query|power\s*pivot|\bdax\b|\bpq\b/i.test(name) ? '基础计算规则' : name;
|
||||
}
|
||||
|
||||
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
|
||||
|
||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||
@@ -394,7 +430,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const definition = isRules && testMode && String(active?.id ?? fallback?.id) === 'pq-dax-v1' && ruleSchema?.defaultDefinition
|
||||
? ruleSchema.defaultDefinition : storedDefinition;
|
||||
if (definition && typeof definition === 'object') setDraftDefinition(JSON.parse(JSON.stringify(definition)) as ConfigDefinition);
|
||||
form.setFieldsValue({ name: String(active?.name || fallback?.name || (isRules ? '测试计算规则' : '测试基础数据与对应关系')), description: String(active?.description || fallback?.description || '') });
|
||||
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
||||
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]);
|
||||
|
||||
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
|
||||
@@ -430,7 +467,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
setDraftDefinition(definition);
|
||||
form.setFieldsValue({
|
||||
name: String(item?.name || (source?.name ? `${String(source.name).slice(0, 112)}·草稿` : '')),
|
||||
description: String(source?.description || (source?.definition as ConfigDefinition | undefined)?.maintenanceNote || ''),
|
||||
description: isRules ? readableRuleDescription(source?.description) : String(source?.description || (source?.definition as ConfigDefinition | undefined)?.maintenanceNote || ''),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -447,7 +484,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
} else {
|
||||
if (isRules) await api.createRule(body); else await api.createMapping(body);
|
||||
}
|
||||
message.success('草稿已保存到服务端');
|
||||
message.success('草稿已保存');
|
||||
setDrafting(null); form.resetFields(); await load();
|
||||
} catch (value) {
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
@@ -467,7 +504,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
setValidation({ id, value: result });
|
||||
|
||||
}
|
||||
message.success(action === 'validate' ? '服务端校验已完成' : '配置已启用');
|
||||
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(); }
|
||||
@@ -495,9 +532,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
];
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => <strong>{toText(value)}</strong> },
|
||||
{ title: '名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 230, render: value => <strong>{toText(isRules ? ruleDisplayName(value) : value)}</strong> },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 125, align: 'center', render: value => <Tag color={String(value).toUpperCase().includes('ACTIVE') ? 'green' : 'blue'}>{({ ACTIVE: '已启用', VALIDATED: '已校验', DRAFT: '草稿', SUPERSEDED: '历史记录', ENGINE_BASELINE: '原始公式', ARCHIVED: '已归档' } as Record<string, string>)[String(value).toUpperCase()] || toText(value)}</Tag> },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: (value, row) => readableValue(value || (row.definition as ConfigDefinition | undefined)?.maintenanceNote) },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: (value, row) => readableValue(isRules ? readableRuleDescription(value) : value || (row.definition as ConfigDefinition | undefined)?.maintenanceNote) },
|
||||
{ title: '更新时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 330, align: 'center', render: (_, row) => <span className="task-actions">
|
||||
<Button type="link" onClick={() => setValidation({ id: String(row.id || ''), value: row.definition, purpose: 'definition' })}>{isRules ? '查看定义' : '查看内容'}</Button>
|
||||
@@ -512,19 +549,14 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const simpleStageLabel: Record<string, string> = { QUEUED: '等待处理', VALIDATING: '检查配置与来源', VERSION_CREATED: '保存配置', REBUILDING: '重新计算报表', PUBLISHING: '更新当前报表', COMPLETED: '已完成', FAILED: '处理失败' };
|
||||
const applyCurrent = async () => {
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
await workflowOperation.start(() => api.applyDataWorkflow({ kind: isRules ? 'rule' : 'mapping', name: values.name.trim(), definition: draftDefinition, expectedCurrentReleaseId: workflowStatus?.currentReleaseId ?? null, ...(values.description?.trim() ? { description: values.description.trim() } : {}) }));
|
||||
await form.validateFields();
|
||||
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));
|
||||
}
|
||||
};
|
||||
const simpleHistoryColumns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '配置名称', dataIndex: 'name', key: 'name', width: 250, render: name => <strong>{toText(name)}</strong> },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: status => <Tag color={String(status).toUpperCase() === 'ACTIVE' ? 'green' : 'default'}>{String(status).toUpperCase() === 'ACTIVE' ? '当前使用' : '历史记录'}</Tag> },
|
||||
{ title: '更新时间', dataIndex: 'createdAt', key: 'createdAt', width: 205 },
|
||||
{ title: '操作', key: 'actions', width: 120, render: (_, row) => <Button type="link" onClick={() => setValidation({ id: String(row.id || ''), value: row.definition, purpose: 'definition' })}>查看内容</Button> },
|
||||
];
|
||||
|
||||
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
|
||||
if (testMode) return <div className="management-page nc-simplified-config-page">
|
||||
@@ -535,10 +567,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
{workflowOperation.error && <Alert showIcon type="error" message={workflowOperation.operation?.status === 'FAILED' ? '保存或报表更新失败' : '进度读取失败'} description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{workflowOperation.busy ? (simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理') : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? '报表已更新' : '操作结束'}</strong></div><Progress percent={workflowOperation.busy ? undefined : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 'success' : 'active'} /></section>}
|
||||
<section className="panel section-panel nc-simple-current-config">
|
||||
<div className="resource-toolbar"><strong>{isRules ? '当前计算规则' : '当前基础数据、对应关系与匹配规则'}</strong></div>
|
||||
<Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="name" label="配置名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input disabled={!canApplyWorkflow} maxLength={120} /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div></Form>
|
||||
{isRules ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <pre className="json-result">{publicJson(draftDefinition)}</pre> : <>
|
||||
<div className="nc-simple-config-intro"><Alert showIcon type="info" message="Excel 与系统名称对应" description="Excel“事业部”映射为系统“产业部”;Excel“产业部”映射为系统“业务分组”。对应到的新目标会自动加入相应名录。" /></div>
|
||||
{isRules && <div className="resource-toolbar"><strong>当前计算规则</strong></div>}
|
||||
<Form form={form} component={isRules ? 'form' : false} layout="vertical">{isRules && <div className="structured-config-form-grid"><Form.Item name="name" label="配置名称"><Input readOnly placeholder="保存时自动生成" /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div>}</Form>
|
||||
{isRules ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <RuleContents value={draftDefinition} /> : <>
|
||||
<Tabs className="nc-simple-config-tabs" activeKey={simpleTab} onChange={key => setSimpleTab(key as typeof simpleTab)} items={[
|
||||
{ key: 'catalog', label: '名录', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="masterData" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
{ key: 'lookups', label: '基础对应', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="mappings" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
@@ -548,8 +579,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
</>}
|
||||
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存会自动检查配置、保存配置、按当前来源重算并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
||||
</section>
|
||||
<section className="panel section-panel nc-simple-history"><div className="resource-toolbar"><strong>历史配置记录</strong><span>{items.length} 条记录 · 仅供查看</span></div>{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <Table size="small" bordered columns={simpleHistoryColumns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 760 }} locale={{ emptyText: '暂无历史配置记录' }} />}</section>
|
||||
{validation && <Drawer className="management-drawer" open title="历史记录内容" width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{isRules ? <pre className="json-result">{publicJson(validation.value)}</pre> : <ReadableConfigDefinition kind="mappings" value={validation.value} />}</Drawer>}
|
||||
|
||||
</div>;
|
||||
|
||||
return <div className="management-page">
|
||||
@@ -571,7 +601,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
{kind === 'masterData' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} /> : <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
|
||||
{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="草稿存在需要处理的名录引用" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0, 20).map((issue, index) => <li key={`${issue}:${index}`}>{issue}</li>)}</ul>} />}
|
||||
</>}
|
||||
<TechnicalDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />
|
||||
{!isRules && <TechnicalDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} />}
|
||||
</Modal>
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(differenceItem)} title="确认规则试算差异" width={920} okText="确认差异并启用" okButtonProps={{ disabled: !differenceConfirmed }} confirmLoading={Boolean(busyId)} onCancel={() => setDifferenceItem(null)} onOk={() => { if (differenceItem) void runAction(differenceItem, 'activate', true); }}>
|
||||
{differenceItem && (() => { const result = differenceItem.validation as Record<string, unknown>; return <>
|
||||
@@ -581,7 +611,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
<Checkbox checked={differenceConfirmed} onChange={event => setDifferenceConfirmed(event.target.checked)}>我已核对本次试算差异,并确认启用此规则</Checkbox>
|
||||
</>; })()}
|
||||
</Modal>
|
||||
{validation && !drafting && <Drawer className="management-drawer" open title={validation.purpose === 'definition' ? '配置定义' : '服务端校验结果'} width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{validation.purpose === 'definition' ? isRules ? <pre className="json-result">{publicJson(validation.value)}</pre> : <ReadableConfigDefinition kind={kind === 'masterData' ? 'masterData' : 'mappings'} value={validation.value} /> : (() => {
|
||||
{validation && !drafting && <Drawer className="management-drawer" open title={validation.purpose === 'definition' ? '配置定义' : '服务端校验结果'} width={Math.min(980, window.innerWidth)} onClose={() => setValidation(null)}>{validation.purpose === 'definition' ? isRules ? <RuleContents value={validation.value} /> : <ReadableConfigDefinition kind={kind === 'masterData' ? 'masterData' : 'mappings'} value={validation.value} /> : (() => {
|
||||
const response = validation.value && typeof validation.value === 'object' ? validation.value as Record<string, unknown> : {};
|
||||
const result = response.validation && typeof response.validation === 'object' ? response.validation as Record<string, unknown> : response;
|
||||
const errors = Array.isArray(result.errors) ? result.errors : []; const warnings = Array.isArray(result.warnings) ? result.warnings : [];
|
||||
@@ -601,7 +631,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const failures = Array.isArray(result.failedCases) ? result.failedCases.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
|
||||
const precision = result.precisionPolicy && typeof result.precisionPolicy === 'object' ? result.precisionPolicy as Record<string, unknown> : {};
|
||||
return <>
|
||||
<div className="governance-monitor-grid"><div><small>执行状态</small><strong>{toText(result.status)}</strong></div><div><small>隔离环境</small><strong>{result.isolated === true ? '是' : result.isolated === false ? '否' : '—'}</strong></div><div><small>回归案例</small><strong>{cases.length}</strong></div><div><small>失败案例</small><strong className={failures.length ? 'negative' : ''}>{failures.length}</strong></div></div>
|
||||
<div className="governance-monitor-grid"><div><small>执行状态</small><strong>{regressionStatus(result.status)}</strong></div><div><small>隔离环境</small><strong>{result.isolated === true ? '是' : result.isolated === false ? '否' : '—'}</strong></div><div><small>回归案例</small><strong>{cases.length}</strong></div><div><small>失败案例</small><strong className={failures.length ? 'negative' : ''}>{failures.length}</strong></div></div>
|
||||
<p className="completion-note">核验精度:重量 ±{toText(precision.weightAbsolute)},比率 ±{toText(precision.rateAbsolute)}</p>
|
||||
{Array.isArray(result.errors) && result.errors.length > 0 && <Alert showIcon type="error" message="回归错误" description={(result.errors as unknown[]).map(String).join(';')} />}
|
||||
<Table size="small" bordered rowKey={(row, index) => String(row.name || index)} dataSource={cases} pagination={false} scroll={{ x: 820 }} columns={[
|
||||
@@ -769,10 +799,8 @@ function MappingIssueResolutionPanel({ user, onUnauthorized }: { user: AuthUser;
|
||||
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [migration, setMigration] = useState<Record<string, unknown> | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dictionaryError, setDictionaryError] = useState('');
|
||||
const [migrationError, setMigrationError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
|
||||
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
|
||||
@@ -781,12 +809,10 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
const [dictionaryResult, migrationResult] = await Promise.allSettled([api.metricDictionary(), api.metricDictionaryMigration()]);
|
||||
if (dictionaryResult.status === 'fulfilled') {
|
||||
setItems(collectionItems(dictionaryResult.value)); setDictionaryError('');
|
||||
} else if (!onUnauthorized(dictionaryResult.reason)) setDictionaryError(apiMessage(dictionaryResult.reason));
|
||||
if (migrationResult.status === 'fulfilled') { setMigration(migrationResult.value); setMigrationError(''); }
|
||||
else if (!onUnauthorized(migrationResult.reason)) setMigrationError(apiMessage(migrationResult.reason));
|
||||
try {
|
||||
const result = await api.metricDictionary();
|
||||
setItems(collectionItems(result)); setDictionaryError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
||||
setLoading(false);
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
@@ -796,7 +822,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
form.setFieldsValue({
|
||||
name: String(item.name || ''),
|
||||
aliases: Array.isArray(item.aliases) ? item.aliases.map(String).join('\n') : '',
|
||||
description: String(item.description || ''), reason: '',
|
||||
description: readableRuleDescription(item.description), reason: '',
|
||||
});
|
||||
};
|
||||
const save = async () => {
|
||||
@@ -822,47 +848,19 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
};
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '指标编码', dataIndex: 'code', key: 'code', fixed: 'left', width: 220 },
|
||||
{ title: '术语名称', dataIndex: 'name', key: 'name', width: 190 },
|
||||
{ title: '别名', dataIndex: 'aliases', key: 'aliases', width: 240, ellipsis: true, render: value => Array.isArray(value) ? value.map(String).join('、') || '—' : toText(value) },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 260, ellipsis: true, render: readableValue },
|
||||
{ title: '单位', dataIndex: 'unit', key: 'unit', width: 100 },
|
||||
{ title: '维度', dataIndex: 'dimensions', key: 'dimensions', width: 190, ellipsis: true, render: value => Array.isArray(value) ? value.map(String).join('、') : readableValue(value) },
|
||||
{ title: '原始基线公式', dataIndex: 'formula', key: 'formula', width: 280, ellipsis: true, render: readableValue },
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 90, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 150, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
||||
{ title: '术语名称', dataIndex: 'name', key: 'name', width: 160 },
|
||||
{ title: '说明', dataIndex: 'description', key: 'description', width: 200, render: value => readableValue(readableRuleDescription(value)) },
|
||||
{ title: '单位', dataIndex: 'unit', key: 'unit', width: 55, render: value => value === 'RATE' ? '%' : toText(value) },
|
||||
{ title: '适用范围', dataIndex: 'dimensions', key: 'dimensions', width: 130, render: value => <BusinessValue value={value} field="dimensions" /> },
|
||||
{ title: '当前生效公式', key: 'formula', width: 420, render: (_, row) => <div style={{ whiteSpace: 'normal', overflowWrap: 'anywhere', lineHeight: 1.7 }}>{currentMetricFormula(row)}</div> },
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 70, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 100, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
||||
];
|
||||
const dictionary = Array.isArray(migration?.items)
|
||||
? migration.items.filter(item => item && typeof item === 'object') as Record<string, unknown>[]
|
||||
: [];
|
||||
const verification = migration?.verification;
|
||||
const verificationData = verification && typeof verification === 'object' ? verification as Record<string, unknown> : {};
|
||||
const migrationStatusLabel = (value: unknown) => ({
|
||||
MIGRATED_BASELINE: '已迁移基线',
|
||||
OBSERVED_MAPPING_BASELINE: '已观察映射基线',
|
||||
RECORDED_ORIGINAL_BASELINE: '已登记原度量基线',
|
||||
EXTRACTED_SOURCE_DEFINITION: '已提取定义,尚未开放执行',
|
||||
DECLARED_DEPENDENCY: '已登记依赖关系',
|
||||
FORMAL_RATE_BASELINE: '已建立正式比率基线',
|
||||
} as Record<string, string>)[String(value)] || String(value || '未标记');
|
||||
const migrationRows = dictionary.map(item => ({ ...item, sourceStatus: item.status, status: migrationStatusLabel(item.status) }));
|
||||
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典与迁移账本</Button></div>
|
||||
<Tabs items={[
|
||||
{ key: 'dictionary', label: `术语字典(${items.length})`, children: <>
|
||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={dictionaryError} />}
|
||||
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1580 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未登记指标术语" />}
|
||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="此处显示原始基线公式。生效公式以当前生效的计算规则为准。" />
|
||||
</> },
|
||||
{ key: 'migration', label: `迁移与公式账本(${dictionary.length})`, children: <>
|
||||
{migrationError && <Alert showIcon type="error" message="迁移账本读取失败" description={migrationError} />}
|
||||
{loading ? <div className="loading-panel"><Spin />读取迁移与验证记录…</div> : <>
|
||||
{verification !== undefined && <><h3>迁移核验状态</h3><div className="governance-monitor-grid"><div><small>核验场景</small><strong>{toText(verificationData.scenarioCount)}</strong></div><div><small>失败场景</small><strong>{toText(verificationData.failedScenarios)}</strong></div><div><small>字段检查</small><strong>{toText(verificationData.fieldChecks)}</strong></div><div><small>查询 / 度量</small><strong>{toText(migration?.queryCount)} / {toText(migration?.measureCount)}</strong></div><div><small>成本核算</small><strong>{migration?.costCalculationEnabled === false ? '未启用' : toText(migration?.costCalculationEnabled)}</strong></div></div><p className="completion-note">产物:{toText(verificationData.artifact)} · {toText(verificationData.notice) || '状态由服务端迁移账本返回'}</p><details><summary>查看服务端核验明细</summary><pre className="json-result">{publicJson(verification)}</pre></details></>}
|
||||
<h3>迁移公式条目</h3>{migrationRows.length ? <><Alert showIcon type="info" message="迁移状态按服务端标记逐项呈现" description="已提取的源定义不等于已开放执行;正式公式、依赖、映射观察与迁移基线保持各自状态。" /><DynamicTable items={migrationRows} rowKey="id" /></> : !migrationError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未返回迁移条目" />}
|
||||
</>}
|
||||
</> },
|
||||
]} />
|
||||
{loading ? <div className="loading-panel"><Spin />读取术语定义…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" />}
|
||||
<Alert showIcon type="info" message="术语编辑不改变计算规则" description="公式来自当前查询数据所绑定的计算规则;编辑术语不会改变计算结果。" />
|
||||
<Modal className="management-modal" open={Boolean(editing)} title={`编辑术语 · ${String(editing?.code || '')}`} okText="保存术语" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()}>
|
||||
<Form form={form} layout="vertical">
|
||||
<Form.Item name="name" label="展示名称" rules={[{ required: true, whitespace: true, message: '请填写展示名称' }]}><Input maxLength={160} /></Form.Item>
|
||||
@@ -870,10 +868,10 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
<Form.Item name="description" label="术语说明"><Input.TextArea rows={3} maxLength={1000} /></Form.Item>
|
||||
<Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true, message: '请填写修改原因' }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item>
|
||||
</Form>
|
||||
<Alert showIcon type="info" message="原始基线参考" description={`原始公式:${toText(editing?.formula)} · 单位:${toText(editing?.unit)} · 维度:${toText(editing?.dimensions)}`} />
|
||||
<Alert showIcon type="info" message="当前生效公式" description={editing ? currentMetricFormula(editing) : undefined} />
|
||||
</Modal>
|
||||
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标术语 · ${String(inspecting?.code || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
||||
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(inspecting.description)}</dd><dt>单位</dt><dd>{toText(inspecting.unit)}</dd><dt>适用维度</dt><dd>{readableValue(inspecting.dimensions)}</dd><dt>原始基线公式</dt><dd>{readableValue(inspecting.formula)}</dd><dt>状态</dt><dd>{toText(inspecting.enabled)}</dd></dl>}
|
||||
<Drawer className="management-drawer" open={Boolean(inspecting)} title={`指标术语 · ${String(inspecting?.name || '')}`} width={Math.min(760, window.innerWidth)} onClose={() => setInspecting(null)}>
|
||||
{inspecting && <dl className="completion-definition-list"><dt>名称</dt><dd>{toText(inspecting.name)}</dd><dt>别名</dt><dd>{Array.isArray(inspecting.aliases) ? inspecting.aliases.map(String).join('、') : toText(inspecting.aliases)}</dd><dt>说明</dt><dd>{toText(readableRuleDescription(inspecting.description))}</dd><dt>单位</dt><dd>{inspecting.unit === 'RATE' ? '%' : toText(inspecting.unit)}</dd><dt>适用维度</dt><dd><BusinessValue value={inspecting.dimensions} field="dimensions" /></dd><dt>当前生效公式</dt><dd>{currentMetricFormula(inspecting)}</dd><dt>状态</dt><dd><BusinessValue value={inspecting.enabled} /></dd></dl>}
|
||||
</Drawer>
|
||||
</section>;
|
||||
}
|
||||
@@ -918,7 +916,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
{ title: '任务类型', dataIndex: 'type', key: 'type', width: 130 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') || String(value).toUpperCase() === 'ERROR' ? 'red' : String(value).toUpperCase() === 'SUCCEEDED' || String(value).toUpperCase() === 'COMPLETED' ? 'green' : 'blue'}>{importOnly ? importState(value) : toText(value)}</Tag> },
|
||||
{ title: '处理阶段', dataIndex: 'stage', key: 'stage', width: 150 },
|
||||
{ title: importOnly ? '进度' : '进度(服务端)', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: importOnly ? '进度' : '进度', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: '已处理 / 总数', key: 'processed', width: 140, align: 'right', render: (_, row) => `${toText(row.processed)} / ${toText(row.total)}` },
|
||||
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{toText(value)}</Tag> : '—' },
|
||||
{ title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? <span className="task-error">{toText(value)}</span> : '—' },
|
||||
@@ -932,7 +930,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
];
|
||||
return <>
|
||||
{items.length ? <div className="resource-table"><Table size="small" bordered columns={importOnly ? columns.filter(column => ['createdAt', 'status', 'progress', 'processed', 'errorMessage', 'detail'].includes(String(column.key))) : columns} dataSource={items} rowKey={row => String(row.id ?? JSON.stringify(row))} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: importOnly ? 1000 : 1600 }} />
|
||||
{!importOnly && <p className="table-caption">错误信息、进度和结果均按任务服务实际返回展示。</p>}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有后台任务" />}
|
||||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无后台任务" />}
|
||||
<Drawer className="management-drawer" open={Boolean(selected)} title="任务详情" width={Math.min(760, window.innerWidth)} onClose={() => setSelected(null)}>
|
||||
{selected && <><div className="task-detail-summary"><strong>{importOnly ? importState(selected.status) : `${toText(selected.type)} · ${toText(selected.status)}`}</strong>{!importOnly && <span>{toText(selected.stage)} · {toText(selected.id)}</span>}{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && <Alert showIcon type="error" message={toText(selected.errorCode || '任务错误')} description={toText(selected.errorMessage)} />}</div>{importOnly ? <dl className="nc-form-grid"><dt>处理状态</dt><dd>{importState(selected.status)}</dd><dt>处理行数</dt><dd>{toText(selected.processed)} / {toText(selected.total)}</dd><dt>创建时间</dt><dd>{toText(selected.createdAt)}</dd></dl> : <pre className="json-result">{publicJson(selected)}</pre>}</>}
|
||||
</Drawer>
|
||||
@@ -953,35 +951,102 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
|
||||
const [query, setQuery] = useState('');
|
||||
const [sessionId, setSessionId] = useState(initialSessionId);
|
||||
const [sessionReadOnly, setSessionReadOnly] = useState(false);
|
||||
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
|
||||
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
||||
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [historyLoading, setHistoryLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [queuedFollowup, setQueuedFollowup] = useState('');
|
||||
const [stopping, setStopping] = useState(false);
|
||||
const cancellationRequest = useRef<{ generation: number } | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
const [retryQuestion, setRetryQuestion] = useState('');
|
||||
const [lastTurn, setLastTurn] = useState<Record<string, unknown> | null>(null);
|
||||
const [activeTurnId, setActiveTurnId] = useState('');
|
||||
const [streamProgress, setStreamProgress] = useState('');
|
||||
const streamController = useRef<AbortController | null>(null);
|
||||
const eventCursors = useRef<Record<string, string>>({});
|
||||
const mounted = useRef(true);
|
||||
const userSelectionMade = useRef(false);
|
||||
const navigationGeneration = useRef(0);
|
||||
const subscriptionGeneration = useRef(0);
|
||||
const submissionAttempt = useRef<AnalysisSubmission | null>(null);
|
||||
const [releaseId, setReleaseId] = useState<string>();
|
||||
const [sourceResultRef, setSourceResultRef] = useState<AnalysisResultRef>();
|
||||
const conversation = useRef<HTMLDivElement>(null);
|
||||
const followOutput = useRef(true);
|
||||
const explicitlyFollowing = useRef(false);
|
||||
const userScrollIntent = useRef<AnalysisScrollIntent>(null);
|
||||
const userScrollIntentTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const scrollbarPointerActive = useRef(false);
|
||||
const touchPosition = useRef<number | null>(null);
|
||||
const followRequest = useRef<string | null>(null);
|
||||
const seenConclusion = useRef<string | null>(null);
|
||||
const previousScrollTop = useRef(0);
|
||||
const readingPosition = useRef(0);
|
||||
const [hasNewContent, setHasNewContent] = useState(false);
|
||||
const clearUserScrollIntent = () => {
|
||||
userScrollIntent.current = null;
|
||||
if (userScrollIntentTimer.current !== null) {
|
||||
clearTimeout(userScrollIntentTimer.current);
|
||||
userScrollIntentTimer.current = null;
|
||||
}
|
||||
};
|
||||
const markUserScrollIntent = (intent: Exclude<AnalysisScrollIntent, null>) => {
|
||||
clearUserScrollIntent();
|
||||
userScrollIntent.current = intent;
|
||||
userScrollIntentTimer.current = setTimeout(clearUserScrollIntent, 100);
|
||||
};
|
||||
const handleUserScrollIntent = (element: HTMLDivElement, intent: Exclude<AnalysisScrollIntent, null>) => {
|
||||
if (intent === 'up') {
|
||||
if (element.scrollTop <= 0) return;
|
||||
clearUserScrollIntent();
|
||||
explicitlyFollowing.current = false;
|
||||
followOutput.current = analysisScrollFollows(
|
||||
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current, intent);
|
||||
return;
|
||||
}
|
||||
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
|
||||
if (distanceFromBottom <= 24) {
|
||||
clearUserScrollIntent();
|
||||
explicitlyFollowing.current = true;
|
||||
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
|
||||
setHasNewContent(false);
|
||||
} else markUserScrollIntent(intent);
|
||||
};
|
||||
const scrollToLatest = (element: HTMLDivElement) => {
|
||||
const latest = element.querySelector<HTMLElement>('.analysis-turn:last-child');
|
||||
const finished = latest && ANALYSIS_FINAL_STATUSES.has(latest.dataset.analysisStatus || '');
|
||||
const bounds = element.getBoundingClientRect();
|
||||
// DOM rectangles include the workspace zoom; scrollTop uses layout pixels.
|
||||
const renderedScale = element.offsetHeight ? bounds.height / element.offsetHeight : 1;
|
||||
const scale = renderedScale > 0 ? renderedScale : 1;
|
||||
const pauseAtConclusion = Boolean(finished && !explicitlyFollowing.current);
|
||||
element.scrollTop = pauseAtConclusion && latest
|
||||
? element.scrollTop + (latest.getBoundingClientRect().top - bounds.top) / scale - element.clientTop
|
||||
: element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
// Once the conclusion is visible, preserve the reader's place as charts load.
|
||||
if (finished) {
|
||||
seenConclusion.current = latest.dataset.analysisTurnId || null;
|
||||
setHasNewContent(false);
|
||||
if (pauseAtConclusion) followOutput.current = false;
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
if (!busy) { cancellationRequest.current = null; setStopping(false); }
|
||||
}, [busy]);
|
||||
useEffect(() => {
|
||||
const element = conversation.current;
|
||||
if (active && element) element.scrollTop = followOutput.current ? element.scrollHeight : readingPosition.current;
|
||||
if (active && element) { if (followOutput.current) scrollToLatest(element); else element.scrollTop = readingPosition.current; }
|
||||
}, [active]);
|
||||
useEffect(() => { followOutput.current = true; previousScrollTop.current = 0; setHasNewContent(false); }, [sessionId]);
|
||||
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;
|
||||
@@ -991,9 +1056,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
frame = requestAnimationFrame(() => {
|
||||
if (!activePage.current) return;
|
||||
if (followOutput.current) {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
scrollToLatest(element);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1004,12 +1067,18 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
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) {
|
||||
element.scrollTop = element.scrollHeight;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
scrollToLatest(element);
|
||||
setHasNewContent(false);
|
||||
} else if (active && element) setHasNewContent(true);
|
||||
} 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 () => {
|
||||
@@ -1055,6 +1124,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
...(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 } : {}),
|
||||
@@ -1127,6 +1198,9 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
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);
|
||||
@@ -1136,8 +1210,9 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (!current()) return false;
|
||||
const historyTurns = restoredAnalysisTurns(history, turnHistory);
|
||||
const active = activeAnalysisTurn(historyTurns);
|
||||
const selectedTurnId = focusTurnId || (active ? String(active.id || '') : '');
|
||||
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('');
|
||||
@@ -1167,11 +1242,15 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const newSession = () => {
|
||||
userSelectionMade.current = true;
|
||||
beginAnalysisSelection(user.id);
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
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);
|
||||
@@ -1208,7 +1287,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const current = () => mounted.current && generation === subscriptionGeneration.current;
|
||||
const linkedSessionId = sessionOverride || sessionId;
|
||||
if (linkedSessionId) writeAnalysisLocation(linkedSessionId, id);
|
||||
setActiveTurnId(id); setBusy(true); setStreamProgress('分析任务已排队,等待服务端步骤…');
|
||||
setActiveTurnId(id); setBusy(true);
|
||||
const controller = new AbortController(); streamController.current = controller;
|
||||
let streamedResult: Record<string, unknown> = {};
|
||||
let terminalEventStatus = '';
|
||||
@@ -1229,7 +1308,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (event.id) eventCursors.current[id] = event.id;
|
||||
const data = event.data && typeof event.data === 'object' ? event.data as Record<string, unknown> : {};
|
||||
const messageText = typeof data.message === 'string' ? data.message : event.event === 'answer' ? '正在整理分析结论…' : '正在分析…';
|
||||
setStreamProgress(messageText);
|
||||
const eventResult = isObjectRecord(data.result) ? data.result : undefined;
|
||||
if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
|
||||
const eventName = event.event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_');
|
||||
@@ -1253,7 +1331,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
...(Array.isArray(data.steps) ? { steps: data.steps } : {}),
|
||||
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
|
||||
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
|
||||
progressMessage: messageText,
|
||||
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 } } : {}),
|
||||
@@ -1267,7 +1346,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
} catch (streamError) {
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
if (streamError instanceof ApiError && [401, 403, 404].includes(streamError.status)) throw streamError;
|
||||
if (!terminalEventStatus) setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
@@ -1279,7 +1357,6 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
catch (readError) {
|
||||
if (!current()) return;
|
||||
if (readError instanceof ApiError && [401, 403, 404].includes(readError.status)) throw readError;
|
||||
setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
if (!current()) return;
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) break;
|
||||
@@ -1293,7 +1370,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
}
|
||||
if (!current()) return;
|
||||
const settledTurn = settledAnalysisTurn(id, question, detail, streamedResult, terminalEventStatus);
|
||||
setLastTurn(settledTurn);
|
||||
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;
|
||||
@@ -1351,38 +1428,68 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
}, []);
|
||||
|
||||
const cancelTurn = async () => {
|
||||
if (!activeTurnId) return;
|
||||
const generation = navigationGeneration.current;
|
||||
const id = activeTurnId;
|
||||
const cancelAcceptedTurn = async (id: string, generation: number, question?: string): Promise<boolean> => {
|
||||
const attempt = submissionAttempt.current;
|
||||
const subscription = subscriptionGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current
|
||||
&& subscription === subscriptionGeneration.current && submissionAttempt.current === attempt;
|
||||
try {
|
||||
await api.cancelAnalysisTurn(id, '用户请求停止');
|
||||
if (!mounted.current || generation !== navigationGeneration.current) return;
|
||||
setStreamProgress('正在停止分析…');
|
||||
if (!current()) return false;
|
||||
const detail = await api.analysisTurn(id);
|
||||
if (mounted.current && generation === navigationGeneration.current) {
|
||||
setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
|
||||
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;
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
await loadSessions();
|
||||
if (attempt) attempt.inFlight = false;
|
||||
submissionAttempt.current = null;
|
||||
setBusy(false); setActiveTurnId('');
|
||||
void loadSessions();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
} catch (value) {
|
||||
if (current()) { cancellationRequest.current = null; setStopping(false); if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const cancelTurn = async () => {
|
||||
const generation = navigationGeneration.current;
|
||||
if (cancellationRequest.current?.generation === generation) return;
|
||||
cancellationRequest.current = { generation };
|
||||
setStopping(true);
|
||||
if (queuedFollowup) { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }
|
||||
const attempt = submissionAttempt.current;
|
||||
const pending = requestSubmissionCancellation(attempt, generation);
|
||||
if (pending) {
|
||||
// Creating/retrying a turn can still be in transit. Remember the intent
|
||||
// and cancel the accepted turn, rather than cancelling an old retry state.
|
||||
if (!attempt?.acceptedTurnId) return;
|
||||
}
|
||||
const id = pending ? attempt!.acceptedTurnId : activeTurnId;
|
||||
if (id) await cancelAcceptedTurn(id, generation, pending ? attempt?.question : undefined);
|
||||
else if (!pending) { cancellationRequest.current = null; setStopping(false); }
|
||||
};
|
||||
|
||||
const retryTurn = async (turn: Record<string, unknown>) => {
|
||||
if (busy || historyLoading) return;
|
||||
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 current = () => mounted.current && generation === navigationGeneration.current;
|
||||
const question = typeof turn.question === 'string' ? turn.question : '';
|
||||
const targetSessionId = String(turn.sessionId || sessionId || '');
|
||||
setError(''); setBusy(true); setActiveTurnId(id); setStreamProgress('正在按原冻结计划重新排队…');
|
||||
const attempt = beginAnalysisSubmission(null, { sessionId: targetSessionId, question, generation });
|
||||
submissionAttempt.current = attempt;
|
||||
followRequest.current = attempt.idempotencyKey;
|
||||
followOutput.current = true;
|
||||
explicitlyFollowing.current = false;
|
||||
setLastTurn({ ...turn, status: 'QUEUED', _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;
|
||||
@@ -1390,13 +1497,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
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 });
|
||||
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question, _uiFollowKey: attempt.idempotencyKey });
|
||||
writeAnalysisLocation(retrySessionId, retryId);
|
||||
await loadSessions();
|
||||
void loadSessions();
|
||||
if (!current()) return;
|
||||
setBusy(false);
|
||||
if (current()) await followTurn(retryId, question, retrySessionId);
|
||||
@@ -1408,29 +1519,36 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...turn, ...detail, id, question, sessionId: targetSessionId });
|
||||
} catch (refreshError) { if (!onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
setBusy(false); setActiveTurnId('');
|
||||
} finally {
|
||||
attempt.inFlight = false;
|
||||
if (submissionAttempt.current === attempt) submissionAttempt.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async (question = query) => {
|
||||
if (!question.trim()) return;
|
||||
if (busy || historyLoading) 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 current = () => mounted.current && generation === navigationGeneration.current;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setRetryQuestion(question.trim());
|
||||
if (lastTurn) setTurns(previous => previous.some(item => item.id === lastTurn.id) ? previous : [...previous, lastTurn]);
|
||||
setLastTurn({ question: question.trim(), status: 'QUEUED' });
|
||||
setQuery('');
|
||||
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]);
|
||||
setLastTurn({ question: question.trim(), status: 'QUEUED', _uiFollowKey: attempt.idempotencyKey });
|
||||
setQuery('');
|
||||
try {
|
||||
let selectedSessionId = sessionId;
|
||||
if (!selectedSessionId) {
|
||||
@@ -1440,22 +1558,65 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
|
||||
if (current()) setSessionId(selectedSessionId);
|
||||
}
|
||||
const started = await api.startAnalysisTurn(selectedSessionId, { question: question.trim(), ...(context ? { context } : {}), idempotencyKey: crypto.randomUUID() });
|
||||
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;
|
||||
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId });
|
||||
attempt.uncertain = false;
|
||||
attempt.acceptedTurnId = turnId;
|
||||
setActiveTurnId(turnId);
|
||||
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId, _uiFollowKey: attempt.idempotencyKey });
|
||||
writeAnalysisLocation(selectedSessionId, turnId);
|
||||
await loadSessions();
|
||||
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) { if (current()) { if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); } setBusy(false); } }
|
||||
catch (value) {
|
||||
attempt.uncertain = attempt.turnRequestStarted && !attempt.acceptedTurnId && submissionOutcomeUnknown(value);
|
||||
if (current()) {
|
||||
if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); }
|
||||
if (!attempt.acceptedTurnId) setLastTurn({ question: question.trim(), _uiFollowKey: attempt.idempotencyKey, submissionNotice: attempt.uncertain
|
||||
? '提交结果暂未确认,请重试上一问恢复原任务。'
|
||||
: '本次提交未成功,请检查错误提示后重试。' });
|
||||
setBusy(false);
|
||||
}
|
||||
} finally {
|
||||
attempt.inFlight = false;
|
||||
if (submissionAttempt.current === attempt && !attempt.uncertain) submissionAttempt.current = null;
|
||||
}
|
||||
};
|
||||
|
||||
const queueFollowup = () => {
|
||||
if (sessionReadOnly || !busy || historyLoading || queuedFollowup || cancellationRequest.current || !query.trim()) return;
|
||||
setQueuedFollowup(query.trim());
|
||||
setQuery('');
|
||||
message.info('当前分析结束后发送追问');
|
||||
};
|
||||
|
||||
const sendQueuedFollowup = () => {
|
||||
if (!queuedFollowup || busy || historyLoading ||
|
||||
!ANALYSIS_FINAL_STATUSES.has(String(lastTurn?.status || '').toUpperCase())) return;
|
||||
const question = queuedFollowup;
|
||||
setQueuedFollowup('');
|
||||
return submit(question);
|
||||
};
|
||||
useEffect(() => { void sendQueuedFollowup(); }, [busy, historyLoading, lastTurn?.status, queuedFollowup]);
|
||||
|
||||
const composer = analysisComposerState(busy, stopping, historyLoading, query, queuedFollowup);
|
||||
|
||||
return <div className="management-page analysis-simple-page">
|
||||
<PageHeader title="智能分析" />
|
||||
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>} />}
|
||||
@@ -1472,30 +1633,59 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
</aside>
|
||||
<section className="panel analysis-chat-panel">
|
||||
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
||||
if (event.deltaY < 0 && event.currentTarget.scrollTop > 0) followOutput.current = false;
|
||||
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;
|
||||
followOutput.current = analysisScrollFollows(previousScrollTop.current, element.scrollTop,
|
||||
element.scrollHeight - element.clientHeight - element.scrollTop, followOutput.current);
|
||||
const distanceFromBottom = element.scrollHeight - element.clientHeight - element.scrollTop;
|
||||
const pointerIntent = scrollbarPointerActive.current && element.scrollTop !== previousScrollTop.current
|
||||
? element.scrollTop < previousScrollTop.current ? 'up' : 'down' : null;
|
||||
const intent = userScrollIntent.current || pointerIntent;
|
||||
clearUserScrollIntent();
|
||||
followOutput.current = analysisScrollFollows(distanceFromBottom, followOutput.current, intent);
|
||||
if (intent === 'up') explicitlyFollowing.current = false;
|
||||
else if (intent === 'down' && followOutput.current) explicitlyFollowing.current = true;
|
||||
previousScrollTop.current = element.scrollTop;
|
||||
readingPosition.current = element.scrollTop;
|
||||
if (followOutput.current) setHasNewContent(false);
|
||||
}}>
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={(id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} retryDisabled={busy || historyLoading} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} retryDisabled={busy || historyLoading} />}
|
||||
{busy && <div className="analysis-progress"><span>{streamProgress || '正在分析…'}</span><Button size="small" danger onClick={() => void cancelTurn()}>停止分析</Button></div>}
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
|
||||
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
|
||||
</div>
|
||||
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
|
||||
const element = conversation.current;
|
||||
followOutput.current = true; setHasNewContent(false);
|
||||
followOutput.current = true; explicitlyFollowing.current = true; clearUserScrollIntent(); setHasNewContent(false);
|
||||
if (element) { element.scrollTop = element.scrollHeight; previousScrollTop.current = element.scrollTop; readingPosition.current = element.scrollTop; }
|
||||
}}>回到最新内容 ↓</Button>}
|
||||
<div className="analysis-composer">
|
||||
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void submit(); } }} />
|
||||
<div className="ai-actions"><span>Enter 发送 · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}<Button type="primary" aria-label="发送" loading={busy} disabled={!query.trim() || busy || historyLoading} onClick={() => void submit()}>发送</Button></div></div>
|
||||
</div>
|
||||
{sessionReadOnly ? <div className="analysis-composer">
|
||||
<Alert type="info" message="此会话保留用于查看历史结果。" action={<Button type="primary" disabled={busy || historyLoading} onClick={() => { const fixedRelease=releaseId; newSession(); setReleaseId(fixedRelease); }}>新建会话继续分析</Button>} />
|
||||
{composer.showStop && <Button danger loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>停止分析</Button>}
|
||||
</div> : <div className="analysis-composer">
|
||||
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); if (busy) queueFollowup(); else void submit(); } }} />
|
||||
{queuedFollowup && <div className="analysis-queued-followup" role="status"><span title={queuedFollowup}>待发送:{queuedFollowup}</span><Button type="text" size="small" onClick={() => { setQuery(restoredAnalysisDraft(query, queuedFollowup)); setQueuedFollowup(''); }}>取回编辑</Button></div>}
|
||||
<div className="ai-actions"><span>Enter {busy ? '排队发送' : '发送'} · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}{composer.showStop && <Button danger aria-label="停止分析" loading={stopping} disabled={composer.stopDisabled} onClick={() => void cancelTurn()}>{stopping ? '正在停止' : '停止分析'}</Button>}<Button type="primary" aria-label={composer.sendLabel} disabled={composer.sendDisabled} onClick={() => { if (busy) queueFollowup(); else void submit(); }}>{composer.sendLabel}</Button></div></div>
|
||||
</div>}
|
||||
</section>
|
||||
</div>
|
||||
<Modal title="重命名会话" open={Boolean(renameTarget)} confirmLoading={renaming} okText="保存" cancelText="取消" okButtonProps={{ disabled: !renameTitle.trim() }} onCancel={() => { if (!renaming) setRenameTarget(null); }} onOk={() => void renameSession()}>
|
||||
@@ -1504,9 +1694,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
</div>;
|
||||
}
|
||||
|
||||
function AnalysisTurn({ turn, onResume, onRetry, retryDisabled = false }: { turn: Record<string, unknown>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; retryDisabled?: boolean }) {
|
||||
function AnalysisTurn({ turn: sourceTurn, onResume, onRetry, onClarify, onUnauthorized, retryDisabled = false }: { turn: Record<string, unknown>; onClarify?: (question: string) => void | Promise<void>; onResume?: (turnId: string) => void; onRetry?: (turnId: string) => void; onUnauthorized: (error: unknown) => boolean; retryDisabled?: boolean }) {
|
||||
const recovery=useAnalysisVisualRecovery(sourceTurn,onUnauthorized),turn=recovery.turn;
|
||||
const question = typeof turn.question === 'string' ? turn.question : '';
|
||||
if (!turn.id && typeof turn.submissionNotice === 'string') return <article className="analysis-turn">
|
||||
{question && <div className="analysis-question"><p>{question}</p></div>}
|
||||
<p className="analysis-chat-notice" role="status">{turn.submissionNotice}</p>
|
||||
</article>;
|
||||
const result = isObjectRecord(turn.result) ? turn.result : turn;
|
||||
const memberList = result.memberList ?? turn.memberList;
|
||||
const recordList = result.recordList ?? turn.recordList;
|
||||
const answer = partialAnswerIsOnlyProgress(turn) ? '' : typeof result.answer === 'string' ? result.answer : typeof turn.answer === 'string' ? turn.answer : '';
|
||||
const status = String(turn.status || result.status || '').toUpperCase();
|
||||
const visuals = result.visualSchemaVersion === 1 ? result.visuals : undefined;
|
||||
@@ -1519,27 +1716,32 @@ function AnalysisTurn({ turn, onResume, onRetry, retryDisabled = false }: { turn
|
||||
: status === 'PARTIAL' ? '本轮已保存查询过程,尚未形成最终答复。'
|
||||
: status === 'COMPLETED' ? '分析任务已完成,但未返回回答内容。'
|
||||
: failure;
|
||||
return <article className="analysis-turn">
|
||||
const scope = analysisScopeText(turn);
|
||||
return <article className="analysis-turn" data-analysis-turn-id={String(turn.id || '')} data-analysis-status={status}>
|
||||
{question && <div className="analysis-question"><p>{question}</p></div>}
|
||||
<AnalysisTurnMetadata turn={turn} status={status} />
|
||||
<AnalysisProcess turn={turn} />
|
||||
{scope && <p className="analysis-turn-scope" aria-label="本轮分析范围">{scope}</p>}
|
||||
<AnalysisProcess turn={turn} metadata={<AnalysisTurnMetadata turn={turn} status={status} compact />} />
|
||||
{(!resumable || !Array.isArray(turn.timeline || (isObjectRecord(turn.plan) ? turn.plan.timeline : undefined))) && (answer || !resumable || !retryDisabled) && <div className="analysis-answer">
|
||||
{answer ? <>
|
||||
{status === 'NEEDS_CLARIFICATION' && onClarify ? <AnalysisClarification turn={turn} disabled={retryDisabled} onContinue={onClarify} /> : answer ? <>
|
||||
{resumable ? <AiMarkdown content={answer} className="ai-answer" />
|
||||
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} />}
|
||||
: <AnalysisNarrative answer={answer} visuals={visuals} visualState={result.visualState} question={question} turnId={String(turn.id || '')} beforeExport={() => authorizeAnalysisSnapshot(turn)} turn={turn} />}
|
||||
</> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
|
||||
{status === 'PARTIAL' && answer && <p className="analysis-chat-notice">{partialAnalysisNotice(result.stopReason || turn.stopReason || (isObjectRecord(turn.plan) ? turn.plan.stopReason : ''))}</p>}
|
||||
<div className="analysis-message-actions">
|
||||
{(reportMarkdown.trim() || reportHtml?.trim()) && <NativeAnalysisReport turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} />}
|
||||
{!reportMarkdown.trim() && !reportHtml?.trim() && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
|
||||
{recovery.available&&<Button size="small" type="text" loading={recovery.recovering} disabled={retryDisabled} onClick={()=>void recovery.recover()}>重试图表</Button>}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled||recovery.recovering} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
|
||||
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
|
||||
</div>
|
||||
{recovery.error&&<p className="analysis-chat-notice" role="alert">{recovery.error}</p>}
|
||||
</div>}
|
||||
{memberList !== undefined && memberList !== null && <AnalysisMemberListPanel turn={turn} value={memberList} onUnauthorized={onUnauthorized} />}
|
||||
{recordList !== undefined && recordList !== null && <AnalysisRecordListPanel turn={turn} value={recordList} onUnauthorized={onUnauthorized} />}
|
||||
</article>;
|
||||
}
|
||||
|
||||
function AnalysisTurnMetadata({ turn, status }: { turn: Record<string, unknown>; status: string }) {
|
||||
function AnalysisTurnMetadata({ turn, status, compact = false }: { turn: Record<string, unknown>; status: string; compact?: boolean }) {
|
||||
const [now, setNow] = useState(Date.now());
|
||||
const running = analysisIsRunning(status);
|
||||
useEffect(() => { if (!running) return; setNow(Date.now()); const timer = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(timer); }, [running]);
|
||||
@@ -1553,13 +1755,13 @@ function AnalysisTurnMetadata({ turn, status }: { turn: Record<string, unknown>;
|
||||
const stamp = (value: number) => new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }).format(value);
|
||||
const steps = Array.isArray(turn.steps) ? turn.steps : Array.isArray(plan.steps) ? plan.steps : [];
|
||||
const labels: Record<string, string> = { QUEUED: '排队中', RUNNING: '运行中', COMPLETED: '已完成', PARTIAL: '部分完成', FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '待补充信息' };
|
||||
return <div className="analysis-turn-metadata" aria-label="分析运行信息">
|
||||
return <span className="analysis-turn-metadata" aria-label="分析运行信息">
|
||||
<span>{labels[status] || (running ? '运行中' : '分析记录')}</span>
|
||||
{durationText && <span>{running ? '已运行' : '运行时长'} {durationText}</span>}
|
||||
{start !== undefined && <span>开始 {stamp(start)}</span>}
|
||||
{!running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
|
||||
{steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
|
||||
</div>;
|
||||
{!compact && start !== undefined && <span>开始 {stamp(start)}</span>}
|
||||
{!compact && !running && finish !== undefined && <span>{status === 'COMPLETED' ? '完成时间' : '结束时间'} {stamp(finish)}</span>}
|
||||
{!compact && steps.length > 0 && <span>工具调用 {steps.length} 次</span>}
|
||||
</span>;
|
||||
}
|
||||
|
||||
function isObjectRecord(value: unknown): value is Record<string, unknown> {
|
||||
|
||||
Reference in New Issue
Block a user