统一全系统资源加载、轻量趋势与缓存恢复
This commit is contained in:
+238
-154
@@ -65,6 +65,9 @@ import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, Source
|
||||
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 '当前数据或配置已变化,请刷新后重新操作。';
|
||||
@@ -248,9 +251,12 @@ function PageHeader({ actions }: { title: string; description?: string; actions?
|
||||
}
|
||||
|
||||
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
|
||||
const { active } = usePageCache();
|
||||
const [sources, setSources] = useState<SourceItem[]>([]);
|
||||
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
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');
|
||||
@@ -268,64 +274,85 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
||||
? { ...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 = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [sourceResult, releaseResult] = await Promise.all([api.sources(), api.releases()]);
|
||||
setSources(collectionItems(sourceResult)); setCurrentReleaseId(releaseResult.currentReleaseId ?? null); setError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const load = useCallback(() => sourceRead.run(async () => {
|
||||
const failures: string[] = [];
|
||||
const [sourceResult, releaseResult] = await Promise.allSettled([api.sources(), api.releases()]);
|
||||
if (sourceResult.status === 'fulfilled') { setSources(collectionItems(sourceResult.value)); setSourcesLoaded(true); }
|
||||
else if (!onUnauthorized(sourceResult.reason)) failures.push(`来源清单:${apiMessage(sourceResult.reason)}`);
|
||||
if (releaseResult.status === 'fulfilled') { setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null); setReleaseLoaded(true); }
|
||||
else if (!onUnauthorized(releaseResult.reason)) failures.push(`当前发布版本:${apiMessage(releaseResult.reason)}`);
|
||||
setError(failures.join(';'));
|
||||
}), [onUnauthorized, sourceRead.run]);
|
||||
useEffect(() => { if (active && (!sourcesLoaded || !releaseLoaded)) void load(); }, [active, sourcesLoaded, releaseLoaded, load]);
|
||||
useMaintenanceRefresh(load);
|
||||
return <div className="management-page">
|
||||
{error && <Alert showIcon type="error" message="来源清单读取失败" description={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
{error && <Alert showIcon type="error" message="来源信息读取失败" description={sourcesLoaded || releaseLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
|
||||
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
||||
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} sourcesLoaded={sourcesLoaded} loading={sourceRead.busy} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} onUnauthorized={onUnauthorized} /> },
|
||||
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
||||
]} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
|
||||
function ImportHistoryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const read = useDelayedBusy();
|
||||
const loading = read.busy;
|
||||
const [error, setError] = useState('');
|
||||
const load = useCallback(async () => {
|
||||
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setError(''); }
|
||||
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)); }
|
||||
finally { setLoading(false); }
|
||||
}, [onUnauthorized]);
|
||||
useEffect(() => { void load(); }, [load, currentReleaseId]);
|
||||
useEffect(() => { if (active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load, active]);
|
||||
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span></div>
|
||||
{error && <Alert showIcon type="error" message="导入记录读取失败" description={error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
||||
{loading ? <Spin /> : <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
}), [onUnauthorized, read.run]);
|
||||
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||
useVisiblePolling(load, 2000, active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase())));
|
||||
useMaintenanceRefresh(load);
|
||||
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button></div>
|
||||
{error && <Alert showIcon type="error" message="导入记录读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
||||
{loading && !loaded ? <Spin /> : loaded && <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [result, setResult] = useState<Collection | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [loadedRunId, setLoadedRunId] = useState('');
|
||||
const [loadedPage, setLoadedPage] = useState(0);
|
||||
const read = useDelayedBusy();
|
||||
const loading = read.busy;
|
||||
const [error, setError] = useState('');
|
||||
const [page, setPage] = useState(1);
|
||||
const activeRef = useRef(active); activeRef.current = active;
|
||||
const requestGeneration = useRef(0);
|
||||
const requestRef = useRef<{ key: string; promise: Promise<void> } | null>(null);
|
||||
const load = useCallback(() => {
|
||||
if (!active || !runId) return Promise.resolve();
|
||||
const key = importIssuePageKey(runId, page);
|
||||
if (requestRef.current?.key === key) return requestRef.current.promise;
|
||||
const generation = ++requestGeneration.current;
|
||||
const promise = read.run(async () => {
|
||||
try {
|
||||
const value = await api.importIssues(runId, page, TABLE_PAGE_SIZE);
|
||||
if (generation !== requestGeneration.current || !activeRef.current) return;
|
||||
setResult(value); setLoadedRunId(runId); setLoadedPage(page); setError('');
|
||||
} catch (value) { if (generation === requestGeneration.current && activeRef.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
}).finally(() => { if (requestRef.current?.promise === promise) requestRef.current = null; });
|
||||
requestRef.current = { key, promise };
|
||||
return promise;
|
||||
}, [active, onUnauthorized, page, read.run, runId]);
|
||||
useEffect(() => {
|
||||
if (!runId) return;
|
||||
let alive = true;
|
||||
setLoading(true);
|
||||
api.importIssues(runId, page, TABLE_PAGE_SIZE).then(value => { if (alive) { setResult(value); setError(''); } })
|
||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); })
|
||||
.finally(() => { if (alive) setLoading(false); });
|
||||
return () => { alive = false; };
|
||||
}, [runId, page, onUnauthorized]);
|
||||
const items = unwrapItems(result).items;
|
||||
if (active && runId && (loadedRunId !== runId || loadedPage !== page)) void load();
|
||||
}, [active, loadedPage, loadedRunId, load, page, runId]);
|
||||
const items = loadedRunId === runId ? unwrapItems(result).items : [];
|
||||
const hasSameRunResult = loadedRunId === runId && loadedPage > 0;
|
||||
const pageMatches = hasSameRunResult && matchesImportIssuePage(loadedRunId, loadedPage, runId, page);
|
||||
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
|
||||
{error && <Alert showIcon type="error" message="问题清单读取失败" description={error} />}
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取问题行…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
||||
{result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
|
||||
{error && <Alert showIcon type="error" message="问题清单读取失败" description={pageMatches ? `${error};第 ${page} 页的上次成功结果仍保留。` : hasSameRunResult ? `${error};以下仍显示第 ${loadedPage} 页上次成功结果。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
{loading && !hasSameRunResult ? <div className="loading-panel"><Spin />正在读取问题行…</div> : hasSameRunResult ? <><DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />{!pageMatches && loading && <div className="completion-note"><Spin size="small" /> 正在读取第 {page} 页,暂时保留第 {loadedPage} 页结果。</div>}</> : null}
|
||||
{hasSameRunResult && result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={pageMatches ? page : loadedPage} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
|
||||
</Drawer>;
|
||||
}
|
||||
|
||||
@@ -333,27 +360,30 @@ function ReadOnlyResourcePage({ endpoint, title, subtitle, user, onUnauthorized
|
||||
endpoint: 'imports' | 'tasks'; title: string; subtitle: string; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void;
|
||||
}) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
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 = async () => {
|
||||
setLoading(true);
|
||||
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('');
|
||||
setError(''); setLoaded(true);
|
||||
} catch (value) {
|
||||
if (!onUnauthorized(value)) setError(apiMessage(value));
|
||||
} finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, [endpoint]);
|
||||
}
|
||||
}), [endpoint, onUnauthorized, read.run]);
|
||||
useEffect(() => { if (active && !loaded) void load(); }, [active, endpoint, loaded, load]);
|
||||
useVisiblePolling(load, endpoint === 'imports' ? 2000 : 15000, active && loaded && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status || '').toUpperCase())));
|
||||
return <div className="management-page">
|
||||
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
||||
{error && <Alert type="error" showIcon message="列表读取失败" description={error} />}
|
||||
<PageHeader title={title} description={subtitle} actions={<Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>} />
|
||||
{error && <Alert type="error" showIcon message="列表读取失败" description={loaded ? `${error};以下为上次成功读取的结果。` : error} action={!loaded ? <Button onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}</strong><span>{metadata.total !== undefined ? `共 ${metadata.total} 条` : `服务端返回 ${items.length} 条`}</span></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
{loading && !loaded ? <div className="loading-panel"><Spin />正在读取…</div> : loaded && <TaskTable items={items} importOnly={endpoint === 'imports'} user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
@@ -373,10 +403,14 @@ type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'pr
|
||||
|
||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||
const { message } = App.useApp();
|
||||
const { active: pageActive } = usePageCache();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [itemsLoaded, setItemsLoaded] = useState(false);
|
||||
const itemRead = useDelayedBusy();
|
||||
const loading = itemRead.busy;
|
||||
const [error, setError] = useState('');
|
||||
const [busyId, setBusyId] = useState('');
|
||||
const actionLock = useRef(false);
|
||||
const [drafting, setDrafting] = useState<Record<string, unknown> | null>(null);
|
||||
const [validation, setValidation] = useState<{ id: string; value: unknown; purpose?: 'definition' } | null>(null);
|
||||
const [impactOpen, setImpactOpen] = useState(false);
|
||||
@@ -399,6 +433,9 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [workflowStatusError, setWorkflowStatusError] = useState('');
|
||||
const statusRead = useDelayedBusy();
|
||||
const supportRequested = useRef(false);
|
||||
const isRules = kind === 'rules';
|
||||
const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系';
|
||||
const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||
@@ -410,31 +447,37 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
? { ...items.find(item => String(item.id || '') === String(workflowStatus.activeMapping?.id || '')), ...workflowStatus.activeMapping }
|
||||
: items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
|
||||
|
||||
const load = async (silent = false) => {
|
||||
if(!silent)setLoading(true);
|
||||
try {
|
||||
const result = isRules ? await api.rules() : await api.mappings();
|
||||
setItems(collectionItems(result)); setError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
const loadEditorSupport = async () => {
|
||||
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.all([api.referenceNames(),api.classificationMetadata()]);setPublishedNames(names);setMatchMetadata(metadata);}
|
||||
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)}`); } }
|
||||
};
|
||||
const refreshWorkflowStatus = async () => {
|
||||
try { setWorkflowStatus(await api.dataWorkflowStatus()); }
|
||||
catch { setWorkflowStatus(null); }
|
||||
finally { setWorkflowStatusLoaded(true); }
|
||||
};
|
||||
}, [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(() => { void load(); }, [kind]);
|
||||
useEffect(() => { void loadEditorSupport(); }, [isRules]);
|
||||
useEffect(() => { void refreshWorkflowStatus(); }, [kind]);
|
||||
useEffect(() => { if (pageActive && !itemsLoaded) void load(); }, [pageActive, itemsLoaded, load]);
|
||||
useEffect(() => { if (pageActive && !supportRequested.current) { supportRequested.current = true; void loadEditorSupport(); } }, [pageActive, loadEditorSupport]);
|
||||
useEffect(() => { if (pageActive && !workflowStatusLoaded && !workflowStatusError) void refreshWorkflowStatus(); }, [pageActive, workflowStatusLoaded, workflowStatusError, refreshWorkflowStatus]);
|
||||
useEffect(() => {
|
||||
if (!workflowStatus) return;
|
||||
const active = (isRules ? workflowStatus.activeRule : workflowStatus.activeMapping) as { id?: string; name?: string; description?: string; definition?: Record<string, unknown> } | null | undefined;
|
||||
@@ -445,8 +488,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
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;
|
||||
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]);
|
||||
if (!drafting) form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
||||
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema, drafting, form]);
|
||||
|
||||
const openRegression = async (item: Record<string, unknown>, preferredRunId?: string) => {
|
||||
if (!isRules) return;
|
||||
@@ -486,6 +529,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
};
|
||||
|
||||
const saveDraft = async () => {
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
const body: Record<string, unknown> = { name: values.name.trim(), definition: isRules ? draftDefinition : { ...draftDefinition, maintenanceNote: values.description?.trim() || '' } };
|
||||
@@ -504,11 +548,11 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
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 { setBusyId(''); }
|
||||
} finally { actionLock.current = false; setBusyId(''); }
|
||||
};
|
||||
|
||||
const runAction = async (item: Record<string, unknown>, action: 'validate' | 'activate', confirmDifferences = false) => {
|
||||
const id = String(item.id || ''); if (!id) return;
|
||||
const id = String(item.id || ''); if (!id || actionLock.current) return; actionLock.current = true;
|
||||
setBusyId(id);
|
||||
try {
|
||||
const result = isRules
|
||||
@@ -522,7 +566,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
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 { setBusyId(''); }
|
||||
finally { actionLock.current = false; setBusyId(''); }
|
||||
};
|
||||
|
||||
const showImpact = async (item: Record<string, unknown>) => {
|
||||
@@ -566,6 +610,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
};
|
||||
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();
|
||||
const values = form.getFieldsValue(true);
|
||||
@@ -574,17 +619,18 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
if (!onUnauthorized(value)) message.error(apiMessage(value));
|
||||
}
|
||||
finally { actionLock.current = false; }
|
||||
};
|
||||
|
||||
useMaintenanceRefresh(() => { void load(true); void refreshWorkflowStatus(); void loadEditorSupport(); });
|
||||
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
|
||||
if (!workflowStatusLoaded) return <div className="management-page">{statusRead.busy ? <div className="loading-panel"><Spin />正在读取当前维护模式…</div> : workflowStatusError ? <Alert showIcon type="error" message="维护模式读取失败" description={workflowStatusError} action={<Button size="small" onClick={() => void refreshWorkflowStatus()}>重试</Button>} /> : null}</div>;
|
||||
if (testMode) {
|
||||
const notices = <>
|
||||
{kind==='mappings'&&classificationUpdates.jobs.some(job=>job.status!=='completed')&&<div className="classification-queue-status" role="status">
|
||||
{classificationBusy&&<span><Spin size="small"/> 后台更新中 · {classificationUpdates.jobs.filter(job=>!['failed','completed'].includes(job.status)).length} 条</span>}
|
||||
{classificationUpdates.jobs.filter(job=>['failed','paused'].includes(job.status)).map(job=><Alert key={job.id} type="error" showIcon message={`${job.target}:${job.error}`} action={<><Button size="small" onClick={()=>classificationUpdates.queue.retry(job.id)}>重试</Button>{job.status==='failed'&&<Button size="small" onClick={()=>classificationUpdates.queue.dismiss(job.id)}>关闭</Button>}</>}/>)}
|
||||
</div>}
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
|
||||
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />}
|
||||
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
@@ -621,10 +667,10 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
|
||||
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadEditorSupport(); }}>刷新</Button>
|
||||
</>} />
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={itemsLoaded ? `${error};下方仍显示上次成功结果。` : error} action={!itemsLoaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>{title}记录</strong><span>{items.length} 个服务端记录</span></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" />}
|
||||
{loading && !itemsLoaded ? <div className="loading-panel"><Spin />正在读取…</div> : itemsLoaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1160 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有配置记录;可新建草稿。" /> : null}
|
||||
</section>
|
||||
<Alert showIcon type="info" message="变更先保存为草稿" description="保存后在清单中校验并启用;启用后重新计算、核对并发布,查询结果才采用新配置。" action={!isRules ? <Button onClick={() => onNavigate('sources')}>前往重新计算</Button> : undefined} />
|
||||
<Modal className="management-modal structured-config-modal" open={Boolean(drafting)} title={drafting?.id ? `编辑${title}草稿` : `新建${title}草稿`} width={1120} okText="保存草稿" confirmLoading={Boolean(busyId)} onCancel={() => setDrafting(null)} onOk={() => void saveDraft()}>
|
||||
@@ -691,7 +737,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSec
|
||||
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
|
||||
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
|
||||
</div>;
|
||||
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
|
||||
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{if(actionLock.current)return;actionLock.current=true;setBusyId('editor-new');void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));}).finally(()=>{actionLock.current=false;setBusyId('');});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
|
||||
}
|
||||
|
||||
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
|
||||
@@ -767,24 +813,23 @@ function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorize
|
||||
|
||||
function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const read = useDelayedBusy(); const loading = read.busy;
|
||||
const [dictionaryError, setDictionaryError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const savingRef = useRef(false);
|
||||
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
|
||||
const [inspecting, setInspecting] = useState<Record<string, unknown> | null>(null);
|
||||
const [form] = Form.useForm<{ name: string; aliases: string; description: string; reason: string }>();
|
||||
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role));
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const result = await api.metricDictionary();
|
||||
setItems(collectionItems(result)); setDictionaryError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
||||
setLoading(false);
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const load = useCallback(() => read.run(async () => {
|
||||
try { const result = await api.metricDictionary(); setItems(collectionItems(result)); setLoaded(true); setDictionaryError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setDictionaryError(apiMessage(value)); }
|
||||
}), [onUnauthorized, read.run]);
|
||||
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||
|
||||
const openEditor = (item: Record<string, unknown>) => {
|
||||
setEditing(item);
|
||||
@@ -795,7 +840,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
});
|
||||
};
|
||||
const save = async () => {
|
||||
if (!editing) return;
|
||||
if (!editing || savingRef.current) return; savingRef.current = true;
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
const code = String(editing.code || '');
|
||||
@@ -813,7 +858,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
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 { setSaving(false); }
|
||||
} finally { savingRef.current = false; setSaving(false); }
|
||||
};
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
@@ -828,8 +873,8 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
useMaintenanceRefresh(load);
|
||||
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>
|
||||
{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: 1100 }} /></div> : !dictionaryError && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" />}
|
||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={loaded ? `${dictionaryError};以下为上次成功读取的结果。` : dictionaryError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}
|
||||
{loading && !loaded ? <div className="loading-panel"><Spin />读取术语定义…</div> : loaded ? items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.code)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1100 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无指标术语" /> : null}
|
||||
<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">
|
||||
@@ -851,6 +896,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
const [selected, setSelected] = useState<Record<string, unknown> | null>(null);
|
||||
const [issuesRunId, setIssuesRunId] = useState('');
|
||||
const [busyId, setBusyId] = useState('');
|
||||
const actionLock = useRef(false);
|
||||
const canRetry = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role));
|
||||
const canCancel = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'SYSTEM_OPERATOR'].includes(role));
|
||||
const runIdOf = (row: Record<string, unknown>) => {
|
||||
@@ -859,6 +905,7 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
};
|
||||
const retry = async (row: Record<string, unknown>) => {
|
||||
const id = String(row.id || ''); if (!id) return;
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
setBusyId(id);
|
||||
try {
|
||||
const releases = await api.releases();
|
||||
@@ -869,16 +916,17 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
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 { setBusyId(''); }
|
||||
finally { actionLock.current = false; setBusyId(''); }
|
||||
};
|
||||
const cancel = async (row: Record<string, unknown>) => {
|
||||
const id = String(row.id || ''); if (!id) return;
|
||||
if (actionLock.current) return; actionLock.current = true;
|
||||
setBusyId(id);
|
||||
try {
|
||||
await api.cancelTask(id, { expectedStatus: String(row.status || '') });
|
||||
message.success('已取消排队任务'); onRefresh();
|
||||
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
||||
finally { setBusyId(''); }
|
||||
finally { actionLock.current = false; setBusyId(''); }
|
||||
};
|
||||
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
@@ -894,8 +942,8 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
{ title: '操作', key: 'detail', fixed: 'right', width: importOnly ? 240 : 150, align: 'center', render: (_, row) => <span className="task-actions">
|
||||
<Button type="link" onClick={() => setSelected(row)}>详情</Button>
|
||||
{importOnly && runIdOf(row) && <Button type="link" onClick={() => setIssuesRunId(runIdOf(row))}>校验问题</Button>}
|
||||
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
|
||||
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
|
||||
{canRetry && String(row.status).toUpperCase() === 'FAILED' && runIdOf(row) && <Button type="link" disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void retry(row)}>重试</Button>}
|
||||
{canCancel && String(row.status).toUpperCase() === 'QUEUED' && <Button type="link" danger disabled={Boolean(busyId)} loading={busyId === String(row.id)} onClick={() => void cancel(row)}>取消</Button>}
|
||||
</span> },
|
||||
];
|
||||
return <>
|
||||
@@ -913,6 +961,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const [renameTarget, setRenameTarget] = useState<Record<string, unknown> | null>(null);
|
||||
const [renameTitle, setRenameTitle] = useState('');
|
||||
const [renaming, setRenaming] = useState(false);
|
||||
const sessionMutationLock = useRef(false);
|
||||
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
|
||||
const activePage = useRef(active); activePage.current = active;
|
||||
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
|
||||
@@ -924,9 +973,16 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const [sessionReadOnly, setSessionReadOnly] = useState(false);
|
||||
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
|
||||
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
||||
const [sessionsLoaded, setSessionsLoaded] = useState(false);
|
||||
const sessionReadRequest = useRef<Promise<void> | null>(null);
|
||||
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [historyLoading, setHistoryLoading] = useState(true);
|
||||
const showHistoryLoading = useDelayedIndicator(historyLoading && active, 150);
|
||||
const optionsRead = useDelayedBusy();
|
||||
const [optionsError, setOptionsError] = useState('');
|
||||
const optionsRequestStarted = useRef(false);
|
||||
const restoreStarted = useRef(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [queuedFollowup, setQueuedFollowup] = useState('');
|
||||
const [stopping, setStopping] = useState(false);
|
||||
@@ -1052,22 +1108,33 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
}, [lastTurn, busy, turns, sessionId, active]);
|
||||
|
||||
const loadSessions = async () => {
|
||||
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); }
|
||||
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
if (!mounted.current || !active || document.visibilityState !== 'visible') return;
|
||||
if (sessionReadRequest.current) return sessionReadRequest.current;
|
||||
const request = (async () => {
|
||||
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setError(''); } }
|
||||
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
})();
|
||||
sessionReadRequest.current = request;
|
||||
try { await request; }
|
||||
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
|
||||
};
|
||||
const retrySessions = async () => { setHistoryLoading(true); await loadSessions(); if (mounted.current) setHistoryLoading(false); };
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api.options().then(value => { if (alive) setOptions(value); })
|
||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!active || 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(loadSessions, 5000, active && hasBackgroundTurns);
|
||||
const wasActive = useRef(active);
|
||||
useEffect(() => {
|
||||
if (!hasBackgroundTurns) return;
|
||||
const timer = window.setInterval(() => void loadSessions(), 5000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [hasBackgroundTurns]);
|
||||
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
|
||||
wasActive.current = active;
|
||||
}, [active, hasBackgroundTurns]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
|
||||
@@ -1229,6 +1296,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
|
||||
const deleteSession = async (id: string) => {
|
||||
if (sessionMutationLock.current) return; sessionMutationLock.current = true;
|
||||
const generation = navigationGeneration.current;
|
||||
try {
|
||||
await api.deleteAnalysisSession(id);
|
||||
@@ -1237,17 +1305,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
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() || renaming) return;
|
||||
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 { setRenaming(false); }
|
||||
finally { sessionMutationLock.current = false; setRenaming(false); }
|
||||
};
|
||||
|
||||
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
|
||||
@@ -1367,31 +1435,36 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!active || restoreStarted.current) return;
|
||||
restoreStarted.current = true;
|
||||
mounted.current = true;
|
||||
let cancelled = false;
|
||||
const restore = async () => {
|
||||
const requestedAt = navigationGeneration.current;
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const items = collectionItems(await api.analysisSessions());
|
||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
||||
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
|
||||
setSessions(items);
|
||||
setSessionsLoaded(true);
|
||||
let linkedSession = initialSessionId;
|
||||
if (initialTurnId) {
|
||||
const linkedTurn = await api.analysisTurn(initialTurnId);
|
||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
||||
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) linkedSession = defaultAnalysisSession(user.id, items);
|
||||
if (!cancelled && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
|
||||
} catch (value) { if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { if (!cancelled && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
|
||||
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 () => {
|
||||
cancelled = true; mounted.current = false;
|
||||
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;
|
||||
@@ -1589,17 +1662,19 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
|
||||
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>} />}
|
||||
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
|
||||
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
|
||||
{!options && optionsRead.busy && <div className="loading-panel compact"><Spin />读取分析选项…</div>}
|
||||
<div className="analysis-workspace">
|
||||
<aside className="panel analysis-session-panel">
|
||||
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
|
||||
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
|
||||
{showHistoryLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
|
||||
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
|
||||
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
|
||||
], onClick: ({ key }) => {
|
||||
if (key === 'rename') { setRenameTarget(item); setRenameTitle(String(item.title || '')); }
|
||||
else if (key === 'delete') modal.confirm({ title: '删除此会话及其分析记录?', content: '删除后无法恢复', okText: '删除', cancelText: '取消', okButtonProps: { danger: true }, onOk: () => deleteSession(String(item.id)) });
|
||||
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
|
||||
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
|
||||
</aside>
|
||||
<section className="panel analysis-chat-panel">
|
||||
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
|
||||
@@ -1758,23 +1833,24 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
|
||||
}
|
||||
|
||||
function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [result, setResult] = useState<Collection | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [loadedPage, setLoadedPage] = useState(0);
|
||||
const read = useDelayedBusy(); const loading = read.busy;
|
||||
const [error, setError] = useState('');
|
||||
const load = async (nextPage = page) => {
|
||||
setLoading(true);
|
||||
try { setResult(await api.audit(nextPage, TABLE_PAGE_SIZE)); setError(''); }
|
||||
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)); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(page); }, [page]);
|
||||
}), [onUnauthorized, page, read.run]);
|
||||
useEffect(() => { if (active && loadedPage !== page) void load(page); }, [active, loadedPage, page, load]);
|
||||
useMaintenanceRefresh(() => { void load(page); });
|
||||
const items = unwrapItems(result).items;
|
||||
const total = result?.total ?? items.length;
|
||||
return <div className="resource-tab">
|
||||
{error && <Alert type="error" showIcon message="审计记录读取失败" description={error} />}
|
||||
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} onClick={() => void load(page)}>刷新</Button></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
||||
{error && <Alert type="error" showIcon message="审计记录读取失败" description={loadedPage ? `${error};当前仍显示第 ${loadedPage} 页上次成功结果。` : error} action={!loadedPage ? <Button size="small" onClick={() => void load(page)}>重试</Button> : undefined} />}
|
||||
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load(page)}>刷新</Button></div>
|
||||
{loading && loadedPage !== page ? <div className="loading-panel"><Spin />正在读取…</div> : result && <DynamicTable items={items} paginate={false} indexOffset={(loadedPage - 1) * TABLE_PAGE_SIZE} />}
|
||||
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
|
||||
</div>;
|
||||
}
|
||||
@@ -1783,29 +1859,35 @@ const ROLE_OPTIONS = ['SYSTEM_ADMIN', 'QUALITY_VIEWER', 'BUSINESS_ANALYST', 'DAT
|
||||
|
||||
function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
const { active } = usePageCache();
|
||||
const [users, setUsers] = useState<Record<string, unknown>[]>([]);
|
||||
const [departments, setDepartments] = useState<string[]>([]);
|
||||
const [groups, setGroups] = useState<string[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [usersLoaded, setUsersLoaded] = useState(false);
|
||||
const [optionsLoaded, setOptionsLoaded] = useState(false);
|
||||
const read = useDelayedBusy(); const loading = read.busy;
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const saveLock = useRef(false);
|
||||
const [editing, setEditing] = useState<Record<string, unknown> | null>(null);
|
||||
const [form] = Form.useForm<{ username: string; displayName: string; password: string; active: boolean; forcePasswordChange: boolean; roles: string[]; departments: string[]; groups: string[] }>();
|
||||
const canManage = user.roles.includes('SYSTEM_ADMIN');
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const [userResult, optionsResult] = await Promise.all([api.users(), api.options()]);
|
||||
const rows = collectionItems(userResult);
|
||||
setUsers(rows);
|
||||
setDepartments(Array.from(new Set([...(optionsResult.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
|
||||
setGroups(Array.from(new Set([...(optionsResult.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
|
||||
setError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
const load = useCallback(() => read.run(async () => {
|
||||
const [userResult, optionsResult] = await Promise.allSettled([api.users(), api.options()]);
|
||||
const failures: string[] = [];
|
||||
let rows = users;
|
||||
if (userResult.status === 'fulfilled') { rows = collectionItems(userResult.value); setUsers(rows); setUsersLoaded(true); }
|
||||
else if (!onUnauthorized(userResult.reason)) failures.push(`用户清单:${apiMessage(userResult.reason)}`);
|
||||
if (optionsResult.status === 'fulfilled') {
|
||||
setDepartments(Array.from(new Set([...(optionsResult.value.departments || []), ...rows.flatMap(row => Array.isArray(row.departments) ? row.departments.map(String) : [])])));
|
||||
setGroups(Array.from(new Set([...(optionsResult.value.groups || []), ...rows.flatMap(row => Array.isArray(row.groups) ? row.groups.map(String) : [])])));
|
||||
setOptionsLoaded(true);
|
||||
} else if (!onUnauthorized(optionsResult.reason)) failures.push(`授权选项:${apiMessage(optionsResult.reason)}`);
|
||||
setError(failures.join(';'));
|
||||
}), [onUnauthorized, read.run, users]);
|
||||
useEffect(() => { if (active && !usersLoaded) void load(); }, [active, usersLoaded, load]);
|
||||
useMaintenanceRefresh(load);
|
||||
|
||||
const openEditor = (record?: Record<string, unknown>) => {
|
||||
setEditing(record || {});
|
||||
@@ -1819,6 +1901,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
if (saveLock.current) return; saveLock.current = true;
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
setBusy(true);
|
||||
@@ -1834,7 +1917,7 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
||||
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 { setBusy(false); }
|
||||
} finally { saveLock.current = false; setBusy(false); }
|
||||
};
|
||||
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
@@ -1847,9 +1930,9 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 110, align: 'center', render: (_, row) => canManage ? <Button type="link" onClick={() => openEditor(row)}>编辑授权</Button> : <span className="muted-dash">权限不足</span> },
|
||||
];
|
||||
return <div className="resource-tab">
|
||||
{error && <Alert type="error" showIcon message="用户清单读取失败" description={error} />}
|
||||
{error && <Alert type="error" showIcon message="用户清单读取失败" description={usersLoaded || optionsLoaded ? `${error};已成功读取的内容仍保留。` : error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
<div className="resource-toolbar"><strong>用户清单</strong><span>{users.length} 个账号</span>{canManage && <Button type="primary" onClick={() => openEditor()}>新建用户</Button>}<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" />}
|
||||
{loading && !usersLoaded ? <div className="loading-panel"><Spin />正在读取用户与授权范围…</div> : usersLoaded ? users.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={users} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1210 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有用户" /> : null}
|
||||
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑用户授权' : '新建用户'} width={700} confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
|
||||
<Alert className="user-management-note" showIcon type="info" message="需至少保留一个启用的系统管理员;未配置产业部的非管理员账号可能没有业务数据访问范围。" />
|
||||
<Form form={form} layout="vertical">
|
||||
@@ -1865,21 +1948,22 @@ function UsersResourceTab({ user, onUnauthorized }: { user: AuthUser; onUnauthor
|
||||
}
|
||||
|
||||
function BasisPage({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [rules, setRules] = useState<Record<string, unknown>[]>([]);
|
||||
const [ruleError, setRuleError] = useState('');
|
||||
const [loading, setLoading] = useState(true);
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try { setRules(unwrapItems(await api.rules()).items); setRuleError(''); }
|
||||
const [loaded, setLoaded] = useState(false);
|
||||
const read = useDelayedBusy(); const loading = read.busy;
|
||||
const load = useCallback(() => read.run(async () => {
|
||||
try { setRules(unwrapItems(await api.rules()).items); setLoaded(true); setRuleError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setRuleError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
}), [onUnauthorized, read.run]);
|
||||
useEffect(() => { if (active && !loaded) void load(); }, [active, loaded, load]);
|
||||
useMaintenanceRefresh(load);
|
||||
return <div className="management-page">
|
||||
<PageHeader title="数据与计算依据" description="综合合格率沿用正式指标服务结果;计算规则由服务端统一维护。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
||||
<Alert showIcon type="info" message="综合合格率 = 同一筛选条件下黑片合格率 × 亮片合格率" description="此处说明业务口径。前端只展示服务端正式返回的指标,不用浏览器数据重算或替代正式结果。" />
|
||||
<div className="basis-grid">
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" message={ruleError} />}{loading ? <div className="loading-panel"><Spin /></div> : <DynamicTable items={rules} />}</section>
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>指标规则</strong><span>{rules.length} 条</span></div>{ruleError && <Alert type="error" showIcon message="指标规则读取失败" description={loaded ? `${ruleError};下方保留上次成功结果。` : ruleError} action={!loaded ? <Button size="small" onClick={() => void load()}>重试</Button> : undefined} />}{loading && !loaded ? <div className="loading-panel"><Spin /></div> : loaded && <DynamicTable items={rules} />}</section>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user